Rename vcore directory to src 75/85775/3 accepted/tizen/3.0/ivi/20161011.053535 accepted/tizen/3.0/mobile/20161015.032743 accepted/tizen/3.0/tv/20161016.004035 accepted/tizen/3.0/wearable/20161015.081932 accepted/tizen/common/20160926.154111 accepted/tizen/ivi/20160927.020901 accepted/tizen/mobile/20160927.020843 accepted/tizen/tv/20160927.020657 accepted/tizen/wearable/20160927.020826 submit/tizen/20160926.005548 submit/tizen_3.0_ivi/20161010.000000 submit/tizen_3.0_ivi/20161010.000010 submit/tizen_3.0_mobile/20161015.000001 submit/tizen_3.0_tv/20161015.000001 submit/tizen_3.0_wearable/20161015.000001
authorsangwan.kwon <sangwan.kwon@samsung.com>
Mon, 29 Aug 2016 05:19:55 +0000 (14:19 +0900)
committersangwan.kwon <sangwan.kwon@samsung.com>
Fri, 23 Sep 2016 01:37:42 +0000 (10:37 +0900)
Change-Id: I48a32ccf36f21e0754de78823c299e516d523272
Signed-off-by: sangwan.kwon <sangwan.kwon@samsung.com>
162 files changed:
CMakeLists.txt
src/CMakeLists.txt [new file with mode: 0644]
src/cert-svc/ccert.h [new file with mode: 0644]
src/cert-svc/cerror.h [new file with mode: 0644]
src/cert-svc/cinstance.h [new file with mode: 0644]
src/cert-svc/cpkcs12.h [new file with mode: 0644]
src/cert-svc/cprimitives.h [new file with mode: 0644]
src/cert-svc/cstring.h [new file with mode: 0644]
src/dpl/core/include/dpl/assert.h [new file with mode: 0644]
src/dpl/core/include/dpl/colors.h [new file with mode: 0644]
src/dpl/core/include/dpl/exception.h [new file with mode: 0644]
src/dpl/core/include/dpl/singleton.h [new file with mode: 0644]
src/dpl/core/include/dpl/singleton_impl.h [new file with mode: 0644]
src/dpl/core/src/assert.cpp [new file with mode: 0644]
src/dpl/core/src/colors.cpp [new file with mode: 0644]
src/dpl/core/src/exception.cpp [new file with mode: 0644]
src/dpl/core/src/singleton.cpp [new file with mode: 0644]
src/dpl/log/include/dpl/log/abstract_log_provider.h [new file with mode: 0644]
src/dpl/log/include/dpl/log/dlog_log_provider.h [new file with mode: 0644]
src/dpl/log/include/dpl/log/journal_log_provider.h [new file with mode: 0644]
src/dpl/log/include/dpl/log/log.h [new file with mode: 0644]
src/dpl/log/include/dpl/log/old_style_log_provider.h [new file with mode: 0644]
src/dpl/log/src/abstract_log_provider.cpp [new file with mode: 0644]
src/dpl/log/src/dlog_log_provider.cpp [new file with mode: 0644]
src/dpl/log/src/journal_log_provider.cpp [new file with mode: 0644]
src/dpl/log/src/log.cpp [new file with mode: 0644]
src/dpl/log/src/old_style_log_provider.cpp [new file with mode: 0644]
src/server/include/cert-server-db.h [new file with mode: 0644]
src/server/include/cert-server-debug.h [new file with mode: 0644]
src/server/include/cert-server-logic.h [new file with mode: 0644]
src/server/src/cert-server-db.c [new file with mode: 0644]
src/server/src/cert-server-logic.c [new file with mode: 0644]
src/server/src/cert-server-main.c [new file with mode: 0644]
src/vcore/Base64.cpp [new file with mode: 0644]
src/vcore/Base64.h [new file with mode: 0644]
src/vcore/CertStoreType.cpp [new file with mode: 0644]
src/vcore/CertStoreType.h [new file with mode: 0644]
src/vcore/Certificate.cpp [new file with mode: 0644]
src/vcore/Certificate.h [new file with mode: 0644]
src/vcore/CertificateCollection.cpp [new file with mode: 0644]
src/vcore/CertificateCollection.h [new file with mode: 0644]
src/vcore/CertificateConfigReader.cpp [new file with mode: 0644]
src/vcore/CertificateConfigReader.h [new file with mode: 0644]
src/vcore/CertificateIdentifier.h [new file with mode: 0644]
src/vcore/CertificateLoader.cpp [new file with mode: 0644]
src/vcore/CertificateLoader.h [new file with mode: 0644]
src/vcore/Client.cpp [new file with mode: 0644]
src/vcore/Client.h [new file with mode: 0644]
src/vcore/CryptoInit.cpp [new file with mode: 0644]
src/vcore/CryptoInit.h [new file with mode: 0644]
src/vcore/Error.h [new file with mode: 0644]
src/vcore/Ocsp.cpp [new file with mode: 0644]
src/vcore/Ocsp.h [new file with mode: 0644]
src/vcore/ParserSchema.h [new file with mode: 0644]
src/vcore/PluginHandler.cpp [new file with mode: 0644]
src/vcore/PluginHandler.h [new file with mode: 0644]
src/vcore/ReferenceValidator.cpp [new file with mode: 0644]
src/vcore/ReferenceValidator.h [new file with mode: 0644]
src/vcore/SaxReader.cpp [new file with mode: 0644]
src/vcore/SaxReader.h [new file with mode: 0644]
src/vcore/SignatureData.cpp [new file with mode: 0644]
src/vcore/SignatureData.h [new file with mode: 0644]
src/vcore/SignatureFinder.cpp [new file with mode: 0644]
src/vcore/SignatureFinder.h [new file with mode: 0644]
src/vcore/SignatureReader.cpp [new file with mode: 0644]
src/vcore/SignatureReader.h [new file with mode: 0644]
src/vcore/SignatureValidator.cpp [new file with mode: 0644]
src/vcore/SignatureValidator.h [new file with mode: 0644]
src/vcore/TimeConversion.cpp [new file with mode: 0644]
src/vcore/TimeConversion.h [new file with mode: 0644]
src/vcore/ValidatorFactories.cpp [new file with mode: 0644]
src/vcore/ValidatorFactories.h [new file with mode: 0644]
src/vcore/ValidatorPluginApi.h [new file with mode: 0644]
src/vcore/XmlsecAdapter.cpp [new file with mode: 0644]
src/vcore/XmlsecAdapter.h [new file with mode: 0644]
src/vcore/api.cpp [new file with mode: 0644]
src/vcore/exception.cpp [new file with mode: 0644]
src/vcore/exception.h [new file with mode: 0644]
src/vcore/init-lib.cpp [new file with mode: 0644]
src/vcore/pkcs12.cpp [new file with mode: 0644]
src/vcore/pkcs12.h [new file with mode: 0644]
tests/CMakeLists.txt
vcore/CMakeLists.txt [deleted file]
vcore/cert-svc/ccert.h [deleted file]
vcore/cert-svc/cerror.h [deleted file]
vcore/cert-svc/cinstance.h [deleted file]
vcore/cert-svc/cpkcs12.h [deleted file]
vcore/cert-svc/cprimitives.h [deleted file]
vcore/cert-svc/cstring.h [deleted file]
vcore/dpl/core/include/dpl/assert.h [deleted file]
vcore/dpl/core/include/dpl/colors.h [deleted file]
vcore/dpl/core/include/dpl/exception.h [deleted file]
vcore/dpl/core/include/dpl/singleton.h [deleted file]
vcore/dpl/core/include/dpl/singleton_impl.h [deleted file]
vcore/dpl/core/src/assert.cpp [deleted file]
vcore/dpl/core/src/colors.cpp [deleted file]
vcore/dpl/core/src/exception.cpp [deleted file]
vcore/dpl/core/src/singleton.cpp [deleted file]
vcore/dpl/log/include/dpl/log/abstract_log_provider.h [deleted file]
vcore/dpl/log/include/dpl/log/dlog_log_provider.h [deleted file]
vcore/dpl/log/include/dpl/log/journal_log_provider.h [deleted file]
vcore/dpl/log/include/dpl/log/log.h [deleted file]
vcore/dpl/log/include/dpl/log/old_style_log_provider.h [deleted file]
vcore/dpl/log/src/abstract_log_provider.cpp [deleted file]
vcore/dpl/log/src/dlog_log_provider.cpp [deleted file]
vcore/dpl/log/src/journal_log_provider.cpp [deleted file]
vcore/dpl/log/src/log.cpp [deleted file]
vcore/dpl/log/src/old_style_log_provider.cpp [deleted file]
vcore/server/include/cert-server-db.h [deleted file]
vcore/server/include/cert-server-debug.h [deleted file]
vcore/server/include/cert-server-logic.h [deleted file]
vcore/server/src/cert-server-db.c [deleted file]
vcore/server/src/cert-server-logic.c [deleted file]
vcore/server/src/cert-server-main.c [deleted file]
vcore/vcore/Base64.cpp [deleted file]
vcore/vcore/Base64.h [deleted file]
vcore/vcore/CertStoreType.cpp [deleted file]
vcore/vcore/CertStoreType.h [deleted file]
vcore/vcore/Certificate.cpp [deleted file]
vcore/vcore/Certificate.h [deleted file]
vcore/vcore/CertificateCollection.cpp [deleted file]
vcore/vcore/CertificateCollection.h [deleted file]
vcore/vcore/CertificateConfigReader.cpp [deleted file]
vcore/vcore/CertificateConfigReader.h [deleted file]
vcore/vcore/CertificateIdentifier.h [deleted file]
vcore/vcore/CertificateLoader.cpp [deleted file]
vcore/vcore/CertificateLoader.h [deleted file]
vcore/vcore/Client.cpp [deleted file]
vcore/vcore/Client.h [deleted file]
vcore/vcore/CryptoInit.cpp [deleted file]
vcore/vcore/CryptoInit.h [deleted file]
vcore/vcore/Error.h [deleted file]
vcore/vcore/Ocsp.cpp [deleted file]
vcore/vcore/Ocsp.h [deleted file]
vcore/vcore/ParserSchema.h [deleted file]
vcore/vcore/PluginHandler.cpp [deleted file]
vcore/vcore/PluginHandler.h [deleted file]
vcore/vcore/ReferenceValidator.cpp [deleted file]
vcore/vcore/ReferenceValidator.h [deleted file]
vcore/vcore/SaxReader.cpp [deleted file]
vcore/vcore/SaxReader.h [deleted file]
vcore/vcore/SignatureData.cpp [deleted file]
vcore/vcore/SignatureData.h [deleted file]
vcore/vcore/SignatureFinder.cpp [deleted file]
vcore/vcore/SignatureFinder.h [deleted file]
vcore/vcore/SignatureReader.cpp [deleted file]
vcore/vcore/SignatureReader.h [deleted file]
vcore/vcore/SignatureValidator.cpp [deleted file]
vcore/vcore/SignatureValidator.h [deleted file]
vcore/vcore/TimeConversion.cpp [deleted file]
vcore/vcore/TimeConversion.h [deleted file]
vcore/vcore/ValidatorFactories.cpp [deleted file]
vcore/vcore/ValidatorFactories.h [deleted file]
vcore/vcore/ValidatorPluginApi.h [deleted file]
vcore/vcore/XmlsecAdapter.cpp [deleted file]
vcore/vcore/XmlsecAdapter.h [deleted file]
vcore/vcore/api.cpp [deleted file]
vcore/vcore/exception.cpp [deleted file]
vcore/vcore/exception.h [deleted file]
vcore/vcore/init-lib.cpp [deleted file]
vcore/vcore/pkcs12.cpp [deleted file]
vcore/vcore/pkcs12.h [deleted file]

index 44f6ba551774274f5b3a50e7996c79134a5351a0..f55fc491cccaec5267f87732edac660a8333ff7c 100644 (file)
@@ -51,7 +51,7 @@ INSTALL(FILES
     DESTINATION ${LIB_INSTALL_DIR}/pkgconfig
 )
 
-ADD_SUBDIRECTORY(vcore)
+ADD_SUBDIRECTORY(src)
 ADD_SUBDIRECTORY(systemd)
 ADD_SUBDIRECTORY(etc)
 
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
new file mode 100644 (file)
index 0000000..227ba74
--- /dev/null
@@ -0,0 +1,172 @@
+# Copyright (c) 2016 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        CMakeLists.txt
+# @author      Kyungwook Tak (k.tak@samsung.com)
+# @author      Sangwan Kwon (sangwan.kwon@samsung.com)
+#
+
+######################### VCORE #########################
+
+IF(TIZEN_PROFILE_MOBILE)
+    ADD_DEFINITIONS("-DTIZEN_PROFILE_MOBILE")
+    SET(LIB_CERT_CHECKER cert-checker)
+ENDIF(TIZEN_PROFILE_MOBILE)
+
+PKG_CHECK_MODULES(VCORE_DEPS
+    REQUIRED
+    libxml-2.0
+    libpcrecpp
+    openssl
+    xmlsec1
+    dlog
+    libsystemd-journal
+    ${LIB_CERT_CHECKER}
+    )
+
+ADD_DEFINITIONS(${VCORE_DEPS_CFLAGS})
+ADD_DEFINITIONS(${VCORE_DEPS_CFLAGS_OTHER})
+
+SET(VCORE_SOURCES
+    dpl/core/src/assert.cpp
+    dpl/core/src/exception.cpp
+    dpl/core/src/singleton.cpp
+    dpl/core/src/colors.cpp
+
+    dpl/log/src/abstract_log_provider.cpp
+    dpl/log/src/old_style_log_provider.cpp
+    dpl/log/src/dlog_log_provider.cpp
+    dpl/log/src/journal_log_provider.cpp
+    dpl/log/src/log.cpp
+
+    vcore/api.cpp
+    vcore/Base64.cpp
+    vcore/Certificate.cpp
+    vcore/CertificateCollection.cpp
+    vcore/CertificateConfigReader.cpp
+    vcore/CertificateLoader.cpp
+    vcore/CertStoreType.cpp
+    vcore/ReferenceValidator.cpp
+    vcore/SaxReader.cpp
+    vcore/SignatureData.cpp
+    vcore/SignatureFinder.cpp
+    vcore/SignatureReader.cpp
+    vcore/TimeConversion.cpp
+    vcore/ValidatorFactories.cpp
+    vcore/SignatureValidator.cpp
+    vcore/XmlsecAdapter.cpp
+    vcore/pkcs12.cpp
+    vcore/exception.cpp
+    vcore/Client.cpp
+    vcore/Ocsp.cpp
+    vcore/CryptoInit.cpp
+    vcore/PluginHandler.cpp
+    vcore/init-lib.cpp
+    )
+
+SET(VCORE_INCLUDES
+    ./
+    dpl/core/include
+    dpl/log/include
+    )
+
+INCLUDE_DIRECTORIES(
+    SYSTEM
+    ${VCORE_DEPS_INCLUDE_DIRS}
+    ${VCORE_INCLUDES}
+    )
+
+ADD_LIBRARY(${TARGET_VCORE_LIB} SHARED ${VCORE_SOURCES})
+
+# TODO: visibility needed to be hidden
+SET_TARGET_PROPERTIES(${TARGET_VCORE_LIB}
+    PROPERTIES
+        COMPILE_FLAGS "-D_GNU_SOURCE -fPIC -fvisibility=default"
+        SOVERSION ${SO_VERSION}
+        VERSION ${VERSION})
+
+TARGET_LINK_LIBRARIES(${TARGET_VCORE_LIB}
+    ${VCORE_DEPS_LIBRARIES}
+    ${TARGET_CERT_SVC_LIB}
+    -ldl
+    )
+
+INSTALL(TARGETS ${TARGET_VCORE_LIB}
+    DESTINATION ${LIB_INSTALL_DIR}
+    )
+
+######################### CERT_SERVER #########################
+
+PKG_CHECK_MODULES(CERT_SERVER_DEP
+    REQUIRED
+    dlog
+    sqlite3
+    db-util
+    libsystemd-daemon
+    key-manager
+    )
+
+SET(CERT_SERVER_DIR ${CMAKE_CURRENT_SOURCE_DIR}/server)
+
+SET(CERT_SERVER_SRC
+    ${CERT_SERVER_DIR}/src/cert-server-main.c
+    ${CERT_SERVER_DIR}/src/cert-server-logic.c
+    ${CERT_SERVER_DIR}/src/cert-server-db.c
+    )
+
+INCLUDE_DIRECTORIES(
+    SYSTEM
+    ./
+    ${CERT_SERVER_DEP_INCLUDE_DIRS}
+    ${CERT_SERVER_DIR}/include
+    )
+
+SET_SOURCE_FILES_PROPERTIES(
+    ${CERT_SERVER_SRC}
+    PROPERTIES
+        COMPILE_FLAGS "-D_GNU_SOURCE -fvisibility=hidden -fPIE"
+    )
+
+ADD_EXECUTABLE(${TARGET_CERT_SERVER} ${CERT_SERVER_SRC})
+
+TARGET_LINK_LIBRARIES(${TARGET_CERT_SERVER}
+    ${CERT_SERVER_DEP_LIBRARIES}
+    -pie
+    )
+
+INSTALL(TARGETS ${TARGET_CERT_SERVER} DESTINATION ${BIN_DIR})
+
+######################### API HEADERS #########################
+
+INSTALL(FILES
+    vcore/SignatureValidator.h
+    vcore/SignatureFinder.h
+    vcore/Certificate.h
+    vcore/SignatureData.h
+    vcore/CertStoreType.h
+    vcore/exception.h
+    vcore/ValidatorPluginApi.h
+    vcore/Error.h
+    DESTINATION ${INCLUDEDIR}/cert-svc/vcore
+    )
+
+INSTALL(FILES
+    cert-svc/ccert.h
+    cert-svc/cinstance.h
+    cert-svc/cerror.h
+    cert-svc/cpkcs12.h
+    cert-svc/cprimitives.h
+    cert-svc/cstring.h
+    DESTINATION ${INCLUDEDIR}/cert-svc/cert-svc
+    )
diff --git a/src/cert-svc/ccert.h b/src/cert-svc/ccert.h
new file mode 100644 (file)
index 0000000..cc2f61b
--- /dev/null
@@ -0,0 +1,447 @@
+/**
+ * Copyright (c) 2016 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        ccert.h
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       This is part of C api for ValidationCore.
+ */
+#ifndef _CERTSVC_CCERT_H_
+#define _CERTSVC_CCERT_H_
+
+#include <time.h>
+
+#include <cert-svc/cinstance.h>
+#include <cert-svc/cstring.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct CertSvcCertificate_t {
+       size_t privateHandler;
+       CertSvcInstance privateInstance;
+} CertSvcCertificate;
+
+typedef struct CertSvcCertificateList_t {
+       size_t privateHandler;
+       CertSvcInstance privateInstance;
+} CertSvcCertificateList;
+
+#define MAX_STORE_ENUMS 5
+typedef enum certImportType_t {
+       NONE_STORE   =  0,
+       VPN_STORE    =  1 << 0,
+       WIFI_STORE   =  1 << 1,
+       EMAIL_STORE  =  1 << 2,
+       SYSTEM_STORE =  1 << 3,
+       ALL_STORE    =  VPN_STORE | WIFI_STORE | EMAIL_STORE | SYSTEM_STORE
+} CertStoreType;
+
+typedef enum certStatus_t {
+       DISABLED     =  0,
+       ENABLED      =  1
+} CertStatus;
+
+typedef struct CertSvcStoreCertList_t {
+       char *gname;            // keyfile group name
+       char *title;            // common Name / Alias provided by the user
+       CertStatus status;
+       CertStoreType storeType;
+       struct CertSvcStoreCertList_t *next;
+} CertSvcStoreCertList;
+
+typedef enum certType_t {
+       PEM_CRT          = 1 << 0,
+       P12_END_USER     = 1 << 1,
+       P12_INTERMEDIATE = 1 << 2,
+       P12_TRUSTED      = 1 << 3,
+       P12_PKEY         = 1 << 4,
+       INVALID_DATA     = 1 << 5
+} CertType;
+
+typedef enum CertSvcCertificateForm_t {
+       /*    CERTSVC_FORM_PEM, */
+       CERTSVC_FORM_DER,
+       CERTSVC_FORM_DER_BASE64
+} CertSvcCertificateForm;
+
+typedef enum CertSvcCertificateField_t {
+       CERTSVC_SUBJECT,
+       CERTSVC_SUBJECT_COMMON_NAME,
+       CERTSVC_SUBJECT_COUNTRY_NAME,
+       CERTSVC_SUBJECT_STATE_NAME,
+       CERTSVC_SUBJECT_LOCALITY_NAME,
+       CERTSVC_SUBJECT_ORGANIZATION_NAME,
+       CERTSVC_SUBJECT_ORGANIZATION_UNIT_NAME,
+       CERTSVC_SUBJECT_EMAIL_ADDRESS,
+       /*    CERTSVC_SUBJECT_UID, */
+       CERTSVC_ISSUER,
+       CERTSVC_ISSUER_COMMON_NAME,
+       CERTSVC_ISSUER_COUNTRY_NAME,
+       CERTSVC_ISSUER_STATE_NAME,
+       CERTSVC_ISSUER_LOCALITY_NAME,
+       CERTSVC_ISSUER_ORGANIZATION_NAME,
+       CERTSVC_ISSUER_ORGANIZATION_UNIT_NAME,
+       CERTSVC_ISSUER_EMAIL_ADDRESS,
+       /*    CERTSVC_ISSUER_UID, */
+       CERTSVC_VERSION,
+       CERTSVC_SERIAL_NUMBER,
+       CERTSVC_KEY_USAGE,
+       CERTSVC_KEY,
+       CERTSVC_KEY_ALGO,
+       CERTSVC_SIGNATURE_ALGORITHM
+} CertSvcCertificateField;
+
+typedef enum CertSvcVisibility_t {
+       CERTSVC_VISIBILITY_DEVELOPER            = 1,
+       CERTSVC_VISIBILITY_PUBLIC               = 1 << 6,
+       CERTSVC_VISIBILITY_PARTNER              = 1 << 7,
+       CERTSVC_VISIBILITY_PLATFORM             = 1 << 10
+} CertSvcVisibility;
+
+/**
+ * Get certificate with gname provided.
+ *
+ * @param[in]  instance     CertSvcInstance object
+ * @param[in]  storeType    cert-svc store type to query
+ * @oaran[in]  gname        Single certificate identifier
+ * @param[out] certificate  Must be freed by certsvc_certificate_free() after use
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ *
+ * @see certsvc_instance_new()
+ * @see certsvc_instance_free()
+ * @see certsvc_certificate_free()
+ * @see #CertStoreType
+ * @see #CertSvcCertificate
+ */
+int certsvc_get_certificate(CertSvcInstance instance,
+                                                       CertStoreType storeType,
+                                                       const char *gname,
+                                                       CertSvcCertificate *certificate);
+
+/**
+ * Load certificate to @a CertSvcCertificate from file.
+ * Certificate must be in PEM/CER/DER format.
+ *
+ * @param[in]  instance     CertSvcInstance object
+ * @param[in]  location     Path of file to load
+ * @param[out] certificate  Certificate id assigned to loaded certificate
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ *
+ * @see certsvc_instance_new()
+ * @see certsvc_instance_free()
+ * @see certsvc_certificate_free()
+ * @see #CertSvcCertificate
+ */
+int certsvc_certificate_new_from_file(CertSvcInstance instance,
+                                                                         const char *location,
+                                                                         CertSvcCertificate *certificate);
+
+/**
+ * Load certificate to @a CertSvcCertificate from memory.
+ *
+ * @param[in]  instance     CertSvcInstance object
+ * @param[in]  memory       Pointer to memory with certificate data
+ * @param[in]  len          Size of certificate in @a memory
+ * @param[in]  form         Certificate format in @a memory
+ * @param[out] certificate  Must be freed by certsvc_certificate_free() after use
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ *
+ * @see certsvc_instance_new()
+ * @see certsvc_instance_free()
+ * @see certsvc_certificate_free()
+ * @see #CertSvcCertificate
+ * @see #CertSvcCertificateForm
+ */
+int certsvc_certificate_new_from_memory(CertSvcInstance instance,
+                                                                               const unsigned char *memory,
+                                                                               size_t len,
+                                                                               CertSvcCertificateForm form,
+                                                                               CertSvcCertificate *certificate);
+
+/**
+ * Free structures connected with certificate.
+ *
+ * @param[in] certificate  Certificate to free
+ */
+void certsvc_certificate_free(CertSvcCertificate certificate);
+
+/**
+ * Save certificate to file in @a location in DER format.
+ *
+ * @param[in] certificate  Certificate
+ * @param[in] location     Location
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ *
+ * @see #CertSvcCertificate
+ */
+int certsvc_certificate_save_file(CertSvcCertificate certificate, const char *location);
+
+/**
+ * Get certificate from list founded by certsvc_certificate_search().
+ * Can be called multiple times to get all results.
+ * Returned certificate can be freed. certsvc_certificate_list_free() doesn't
+ * free certificates in the list.
+ *
+ * @param[in]  hadler      Hander to search results.
+ * @param[in]  position    List index start from 0
+ * @param[out] certificate Certficate i
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ *
+ * @see certsvc_certificate_search()
+ * @see certsvc_certificate_free()
+ * @see #CertSvcCertificate
+ * @see #CertSvcCertificateList
+ */
+int certsvc_certificate_list_get_one(CertSvcCertificateList handler,
+                                                                        size_t position,
+                                                                        CertSvcCertificate *certificate);
+
+/**
+ * Return number of elements on the list.
+ *
+ * @param[in]  handler  Handler to certifiacte list
+ * @param[out] length   Size of list
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ *
+ * @see certsvc_certificate_search()
+ * @see #CertSvcCertificateList
+ */
+int certsvc_certificate_list_get_length(CertSvcCertificateList handler,
+                                                                               size_t *size);
+
+/**
+ * Free @a CertSvcCertificateList. It will not free certificates on the list.
+ * You may free each certificate with certsvc_certificate_free().
+ *
+ * @param[in] handler  Handler to search result
+ *
+ * @see certsvc_certificate_search()
+ * @see certsvc_certificate_list_get_one()
+ * @see certsvc_certificate_free()
+ * @see #CertSvcCertificateList
+ */
+void certsvc_certificate_list_free(CertSvcCertificateList handler);
+
+/**
+ * This function will free list. It will free all certificates on the list.
+ * You should ""NOT"" free each certificate with certsvc_certificate_free.
+ *
+ * @param[in] handler Handler to search result.
+ */
+void certsvc_certificate_list_all_free(CertSvcCertificateList handler);
+
+/**
+ * Compare parent certificate subject with child issuer field.
+ *
+ * @param[in]  child   Child certificate. Issuer field will be used
+ * @param[in]  parent  Parent certificate. Subject field will be used
+ * @param[out] status  #CERTSVC_TRUE if @a child is signed by @a parent,
+ *                     else #CERTSVC_FALSE
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ *
+ * @see #CertSvcCertificate
+ */
+int certsvc_certificate_is_signed_by(CertSvcCertificate child,
+                                                                        CertSvcCertificate parent,
+                                                                        int *status);
+
+/**
+ * Extract data field from certificate. Data in buffer could be free by
+ * certsvc_string_free() function or by certsvc_instance_free or vcore_instance_reset.
+ *
+ * @param[in]  certificate  Certificate
+ * @param[in]  field        Certificate field to get
+ * @param[out] buffer       output string. Must be freed by certsvc_string_free()
+ *                          or certsvc_instance_free() after use
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ *
+ * @see certsvc_instance_free()
+ * @see certsvc_string_free()
+ * @see #CertSvcCertificate
+ * @see #CertSvcCertificateField
+ */
+int certsvc_certificate_get_string_field(CertSvcCertificate certificate,
+               CertSvcCertificateField field,
+               CertSvcString *buffer);
+
+/**
+ * Extract NOT AFTER field from certificate.
+ *
+ * @param[in]  certificate  Certificate
+ * @param[out] result       not after time_t
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ *
+ * @see #CertSvcCertificate
+ */
+int certsvc_certificate_get_not_after(CertSvcCertificate certificate, time_t *result);
+
+/**
+ * Extract NOT BEFORE field from certificate.
+ *
+ * @param[in]   certificate  Certificate
+ * @param[out]  result       not before time_t
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ */
+int certsvc_certificate_get_not_before(CertSvcCertificate certificate, time_t *result);
+
+/**
+ * Check whether the certificate is root ca by checking self-signedness.
+ * TODO: This fuction should also check ROOTCA field in certificate.
+ *
+ * @param[in]   certificate  Certificate
+ * @param[out]  status       #CERTSVC_TRUE or #CERTSVC_FALSE
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ *
+ * @see #CertSvcCertificate
+ */
+int certsvc_certificate_is_root_ca(CertSvcCertificate certificate, int *status);
+
+/**
+ * Sort certificates chain. This fuction modifies certificate_array.
+ *
+ * @param[in/out] unsortedChain  unsorted chain in form of @a CertSvcCertificate array
+ *                               which will be sorted from end entity certificate on
+ *                               the first position and (root) CA certificate on the
+ *                               last position
+ * @param[in]     size           Size of @a unsortedChain
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ *
+ * @see #CertSvcCertificate
+ */
+int certsvc_certificate_chain_sort(CertSvcCertificate *unsortedChain, size_t size);
+
+/**
+ * Base64 string will be connected with same instance as message.
+ *
+ * @param[in]  message  Buffer with input data
+ * @param[out] base64   Buffer with output data which must be freed by
+ *                      certsvc_string_free() or certsvc_instance_free() after use
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ *
+ * @see certsvc_instance_free()
+ * @see certsvc_string_free()
+ */
+int certsvc_base64_encode(CertSvcString message, CertSvcString *base64);
+
+/**
+ * Message string will be connected with same certsvc instance as base64.
+ *
+ * @param[in]  base64   Buffer with input data
+ * @param[out] message  Buffer with output data which must be freed by
+ *                      certsvc_string_free() or certsvc_instance_free() after use
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ *
+ * @see certsvc_instance_free()
+ * @see certsvc_string_free()
+ */
+int certsvc_base64_decode(CertSvcString base64, CertSvcString *message);
+
+/**
+ * Verify signature with given arguments.
+ *
+ * @param[in]  certificate  Certificate
+ * @param[in]  message      Message
+ * @param[in]  signature    Signature to verify
+ * @param[in]  algorithm    May be set to NULL
+ * @param[out] status       #CERTSVC_SUCCESS if success, else #CERTSVC_INVALID_SIGNATURE
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ *
+ */
+int certsvc_message_verify(
+       CertSvcCertificate certificate,
+       CertSvcString message,
+       CertSvcString signature,
+       const char *algorithm,
+       int *status);
+
+/**
+ * Verify certificate. Root CA certificate should be stored in @a trusted.
+ *
+ * @param[in]  certificate    Certificate
+ * @param[in]  trusted        Array with trusted certificates
+ * @param[in]  trustedSize    Array size of @a trusted
+ * @param[in]  untrusted      Array with untrusted certificates
+ * @param[in]  untrustedSize  Array size of @a untrusted
+ * @param[out] status         #CERTSVC_SUCCESS if success, else #CERTSVC_FAIL
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ */
+int certsvc_certificate_verify(
+       CertSvcCertificate certificate,
+       const CertSvcCertificate *trusted,
+       size_t trustedSize,
+       const CertSvcCertificate *untrusted,
+       size_t untrustedSize,
+       int *status);
+
+/**
+ * Verify certificate with strict check of CA flag. Root CA certificate should
+ * be stored in @a trusted.
+ *
+ * @param[in]  certificate    Certificate
+ * @param[in]  trusted        Array with trusted certificates
+ * @param[in]  trustedSize    Array size of @a trusted
+ * @param[in]  untrusted      Array with untrusted certificates
+ * @param[in]  untrustedSize  Array size of @a untrusted
+ * @param[out] status         #CERTSVC_SUCCESS if success, else #CERTSVC_FAIL
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ */
+int certsvc_certificate_verify_with_caflag(
+       CertSvcCertificate certificate,
+       const CertSvcCertificate *trusted,
+       size_t trustedSize,
+       const CertSvcCertificate *untrusted,
+       size_t untrustedSize,
+       int *status);
+
+/**
+ * Get visibility from Tizen app signing root certificate.
+ *
+ * @param[in]  certificate  Tizen app signing root certificate to get visibility
+ * @param[out] visibility   Visibilitay level of @a certificate
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ *
+ * @see #CertSvcVisibility
+ */
+int certsvc_certificate_get_visibility(CertSvcCertificate certificate,
+                                                                          CertSvcVisibility *visibility);
+
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
diff --git a/src/cert-svc/cerror.h b/src/cert-svc/cerror.h
new file mode 100644 (file)
index 0000000..54c74f5
--- /dev/null
@@ -0,0 +1,51 @@
+/**
+ * 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        cerror.h
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       This is part of C api for ValidationCore.
+ */
+
+#ifndef _CERTSVC_CERROR_H_
+#define _CERTSVC_CERROR_H_
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define CERTSVC_TRUE                 (1)
+#define CERTSVC_FALSE                (0)
+
+#define CERTSVC_SUCCESS              (1)
+#define CERTSVC_FAIL                 (0)    /* Openssl internal error. */
+#define CERTSVC_BAD_ALLOC            (-2)   /* Memmory allcation error. */
+#define CERTSVC_WRONG_ARGUMENT       (-4)   /* Function argumnet is wrong. */
+#define CERTSVC_INVALID_ALGORITHM    (-5)   /* Algorithm is not supported. */
+#define CERTSVC_INVALID_SIGNATURE    (-6)   /* Signature and message does not match. */
+#define CERTSVC_IO_ERROR             (-7)   /* Certificate file IO error. */
+#define CERTSVC_INVALID_PASSWORD     (-8)   /* Certificate container password mismatch. */
+#define CERTSVC_DUPLICATED_ALIAS     (-9)   /* User-provided alias is aleady taken. */
+#define CERTSVC_ALIAS_DOES_NOT_EXIST (-10)  /* Alias no exist in store. */
+#define CERTSVC_INVALID_STORE_TYPE   (-11)  /* User-provided invalid import type for storing in system/email/wifi/vpn store. */
+#define CERTSVC_INVALID_STATUS       (-12)  /* User-provided invalid status while stetting the status for the store system/email/wifi/vpn store. */
+#define CERTSVC_INVALID_CERTIFICATE  (-13)  /* Invalid certificate format or content */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // _CERTSVC_CERROR_H_
diff --git a/src/cert-svc/cinstance.h b/src/cert-svc/cinstance.h
new file mode 100644 (file)
index 0000000..3ca455c
--- /dev/null
@@ -0,0 +1,74 @@
+/**
+ * Copyright (c) 2016 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        cinstance.h
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       This is part of C api for ValidationCore.
+ */
+#ifndef _CERTSVC_CINSTANCE_H_
+#define _CERTSVC_CINSTANCE_H_
+
+#include <cert-svc/cerror.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct CertSvcInstance_t {
+       void *privatePtr;
+} CertSvcInstance;
+
+/**
+ * Allocate internal data of CertSvc library and put it in the CertSvcInstance structure.
+ * Initialize Openssl interanal structures.
+ *
+ * @param[out] instance  Pointer to CertSvcInstance
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ */
+int certsvc_instance_new(CertSvcInstance *instance);
+
+/**
+ * Free all allocated data. All certificate identificator will be released and all
+ * strings allocated by certsvc_certificate_get_string_field() will be released also.
+ *
+ * This fucntion does not release CertSvcInstnace itself!
+ *
+ * Plese note: It is safe to use this function after use certsvc_string_free().
+ *
+ * @param[in] instance  CertSvcInstance object
+ */
+void certsvc_instance_reset(CertSvcInstance instance);
+
+/**
+ * Free all allocated data. All certificate identificator will be released and all strings
+ * allocated by certsvc_certificate_get_string_field() will be released also.
+ *
+ * This fucntion also release CertSvcInstnace!
+ *
+ * Please note: It is safe use this function after use certsvc_string_free().
+ *
+ * @param[in] instance CertSvcInstance object
+ */
+void certsvc_instance_free(CertSvcInstance instance);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // _CERTSVC_CINSTANCE_H_
+
diff --git a/src/cert-svc/cpkcs12.h b/src/cert-svc/cpkcs12.h
new file mode 100644 (file)
index 0000000..101d2e3
--- /dev/null
@@ -0,0 +1,375 @@
+/**
+ * Copyright (c) 2016 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        cpkcs12.h
+ * @author      Jacek Migacz (j.migacz@samsung.com)
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @brief       This is part of C api for PKCS#12/PFX storage routines.
+ */
+#ifndef _CERTSVC_CPKCS12_H_
+#define _CERTSVC_CPKCS12_H_
+
+#include <cert-svc/cinstance.h>
+#include <cert-svc/cstring.h>
+#include <cert-svc/ccert.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * Check whenever PKCS#12 container is password protected.
+ *
+ * @param[in]  instance      CertSvcInstance object
+ * @param[in]  filepath      File path to check
+ * @param[out] has_password  #1 if password protectedm, else #0
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ *
+ * @see certsvc_instance_new()
+ * @see certsvc_instance_free()
+ * @see certsvc_string_new()
+ * @see certsvc_string_free()
+ */
+int certsvc_pkcs12_has_password(CertSvcInstance instance,
+                                                               CertSvcString filepath,
+                                                               int *has_password);
+
+/**
+ * Couter-routine for certsvc_pkcs12_private_key_dup.
+ *
+ * @param[in] buffer   Memory claimed by private key
+ */
+void certsvc_pkcs12_private_key_free(char *buffer);
+
+/**
+ * Load to memory of private key in cert-svc store with @a gname.
+ *
+ * @param[in]  instance   CertSvcInstance object
+ * @param[in]  storeType  cert-svc store type to query
+ * @param[in]  gname      Single certificate identifier. It has to be end user's
+ *                        to extract private key
+ * @param[out] buffer     Private key buffer which must be freed after use
+ * @param[out] size       Size of the returned buffer. Zero when no key is found
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ *
+ * @see certsvc_instance_new()
+ * @see certsvc_instance_free()
+ * @see certsvc_string_new()
+ * @see certsvc_string_free()
+ * @see #CertStoreType
+ */
+int certsvc_pkcs12_private_key_dup_from_store(CertSvcInstance instance,
+               CertStoreType storeType,
+               CertSvcString gname,
+               char **buffer,
+               size_t *size);
+
+/**
+ * Set the status for the specified certificate in cert-svc store.
+ *
+ * @param[in] instance     CertSvcInstance object
+ * @param[in] storeType    cert-svc store type to query
+ * @param[in] is_root_app  Should be #ENABLED if master application is changing the status,
+ *                         else #DISABLED for other applications
+ * @param[in] gname        Single certificate identifier
+ * @param[in] status       Status of the certificate to set. [#ENABLED | #DISABLED]
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ *
+ * @see certsvc_instance_new()
+ * @see certsvc_instance_free()
+ * @see certsvc_string_new()
+ * @see certsvc_string_free()
+ * @see #CertStoreType
+ * @see #CertStatus
+ */
+int certsvc_pkcs12_set_certificate_status_to_store(CertSvcInstance instance,
+               CertStoreType storeType,
+               int is_root_app,
+               CertSvcString gname,
+               CertStatus status);
+
+/**
+ * Get the status for the specified certificate in cert-svc store.
+ *
+ * @param[in]  instance   CertSvcInstance object
+ * @param[in]  storeType  cert-svc store type to query
+ * @param[in[  gname      Single certificate identifier
+ * @param[out] status     Status of the certificate. Enabled:1, Disabled:0, Fail:-1
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ *
+ * @see certsvc_instance_new()
+ * @see certsvc_instance_free()
+ * @see certsvc_string_new()
+ * @see certsvc_string_free()
+ * @see #CertStroeType
+ */
+int certsvc_pkcs12_get_certificate_status_from_store(CertSvcInstance instance,
+               CertStoreType storeType,
+               CertSvcString gname,
+               CertStatus *status);
+
+/**
+ * Get the certificates in cert-svc store.
+ *
+ * @param[in]  instance     CertSvcInstance object
+ * @param[in]  storeType    cert-svc store type to query
+ * @param[in]  is_root_app  Should be #ENABLED if master application is changing the
+ *                          status, else #DISABLED for other applications
+ * @param[out] certList     cert list in store returned in linked list. Free by
+ *                          certsvc_pkcs12_free_certificate_list_loaded_from_store()
+ *                          after use
+ * @param[out] length       length of output @a certList
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ *
+ * @see certsvc_instance_new()
+ * @see certsvc_instance_free()
+ * @see #CertStoreType
+ * @see #CertSvcStoreCertList
+ */
+int certsvc_pkcs12_get_certificate_list_from_store(CertSvcInstance instance,
+               CertStoreType storeType,
+               int is_root_app,
+               CertSvcStoreCertList **certList,
+               size_t *length);
+
+/**
+ * Get the end user certificates in cert-svc store.
+ *
+ * @param[in]  instance   CertSvcInstance object
+ * @param[in]  storeType  cert-svc store type to query
+ * @param[out] certList   cert list in store returned in linked list. Free by
+ *                        certsvc_pkcs12_free_certificate_list_loaded_from_store() after use
+ * @param[out] length     length of output @a certList
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ *
+ * @see certsvc_instance_new()
+ * @see certsvc_instance_free()
+ * @see #CertStoreType
+ * @see #CertSvcStoreCertList
+ */
+int certsvc_pkcs12_get_end_user_certificate_list_from_store(CertSvcInstance instance,
+               CertStoreType storeType,
+               CertSvcStoreCertList **certList,
+               size_t *length);
+
+/**
+ * Get the root/trusted certificates in cert-svc store.
+ *
+ * @param[in]  instance   CertSvcInstance object
+ * @param[in]  storeType  cert-svc store type to query
+ * @param[out] certList   cert list in store returned in linked list. Free by
+ *                        certsvc_pkcs12_free_certificate_list_loaded_from_store() after use
+ * @param[out] length     length of output @a certList
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ *
+ * @see certsvc_instance_new()
+ * @see certsvc_instance_free()
+ * @see certsvc_pkcs12_free_certificate_list_loaded_from_store()
+ * @see #CertStoreType
+ * @see #CertSvcStoreCertList
+ */
+int certsvc_pkcs12_get_root_certificate_list_from_store(CertSvcInstance instance,
+               CertStoreType storeType,
+               CertSvcStoreCertList **certList,
+               size_t *length);
+
+/**
+ * Free all @a CertSvcStoreCertList in linked list of data structure.
+ *
+ * @param[in] instance  CertSvcInstance object
+ * @param[in] certList  The structure which need to be freed
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ *
+ * @see certsvc_instance_new()
+ * @see certsvc_instance_free()
+ * @see certsvc_pkcs12_get_certificate_list_from_store()
+ * @see certsvc_pkcs12_get_end_user_certificate_list_from_store()
+ * @see certsvc_pkcs12_get_root_certificate_list_from_store()
+ * @see #CertSvcStoreCertList
+ */
+int certsvc_pkcs12_free_certificate_list_loaded_from_store(CertSvcInstance instance,
+               CertSvcStoreCertList **certList);
+
+/**
+ * Get the certificate with the gname provided from cert-svc store.
+ *
+ * @param[in]  instance     CertSvcInstance object
+ * @param[in]  storeType    cert-svc store type to query
+ * @param[in]  gname        Single certificate identifier
+ * @param[out] certificate  output in @a CertSvcCertificate format
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ *
+ * @see certsvc_instance_new()
+ * @see certsvc_instance_free()
+ * @see certsvc_certificate_free()
+ * @see #CertStoreType
+ */
+int certsvc_pkcs12_get_certificate_from_store(CertSvcInstance instance,
+               CertStoreType storeType,
+               const char *gname,
+               CertSvcCertificate *certificate);
+
+/**
+ * Get the encoded certificate buffer with the gname provided from cert-svc store.
+ *
+ * @param[in]  instance   CertSvcInstance object
+ * @param[in]  storeType  cert-svc store type to query
+ * @param[in]  gname      Single certificate identifier
+ * @param[out] buffer     The base64 encoded certificate which must be freed after
+ *                        use
+ * @param[out] size       Size of the buffer
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ *
+ * @see certsvc_instance_new()
+ * @see certsvc_instance_free()
+ * @see certsvc_string_new()
+ * @see certsvc_string_free()
+ * @see #CertStoreType
+ */
+int certsvc_pkcs12_get_certificate_info_from_store(CertSvcInstance instance,
+               CertStoreType storeType,
+               CertSvcString gname,
+               char **buffer,
+               size_t *size);
+
+/**
+ * Import PKCS#12 bundle(with .pfx or .p12) or certificate(base64 form with .crt
+ * or .pem suffix) from file to specified store. If password isn't needed, create
+ * CertSvcString @a password with null input on certsvc_string_new(). Refer
+ * certsvc_string_new() API description
+ *
+ * @param[in] instance   CertSvcInstance object
+ * @param[in] storeType  cert-svc store type to query
+ * @param[in] path       Path of the certificate which needs to be imported
+ * @param[in] password   Password if the file to import is password-protected which can be
+ *                       empty CertSvcString in case of not-password-protected
+ * @param[in] alias      Primary key for certificate bundle identification (can't be empty)
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ *
+ * @see certsvc_instance_new()
+ * @see certsvc_instance_free()
+ * @see certsvc_string_new()
+ * @see certsvc_string_free()
+ * @see #CertStoreType
+ */
+int certsvc_pkcs12_import_from_file_to_store(CertSvcInstance instance,
+               CertStoreType storeType,
+               CertSvcString path,
+               CertSvcString password,
+               CertSvcString alias);
+
+/**
+ * Delete the certificate with gname provided from cert-svc store.
+ *
+ * @param[in] instance   CertSvcInstance object
+ * @param[in] storeType  cert-svc store type to query
+ * @param[in] gname      Single certificate identifier
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ *
+ * @see certsvc_instance_new()
+ * @see certsvc_instance_free()
+ * @see certsvc_string_new()
+ * @see certsvc_string_free()
+ * @see #CertStoreType
+ */
+int certsvc_pkcs12_delete_certificate_from_store(CertSvcInstance instance,
+               CertStoreType storeType,
+               CertSvcString gname);
+
+/**
+ * Check the uniqueness of the alias in cert-svc store.
+ *
+ * @param[in]  instance   CertSvcInstance object
+ * @param[in]  storeType  cert-svc store type to query
+ * @param[in]  alias      Certificates bundle identifier used when importing
+ * @param[out] is_unique  #CERTSVC_TRUE if the alias is unique, else #CERTSVC_FALSE
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ *
+ * @see certsvc_instance_new()
+ * @see certsvc_instance_free()
+ * @see certsvc_string_new()
+ * @see certsvc_string_free()
+ * @see #CertStoreType
+ */
+int certsvc_pkcs12_check_alias_exists_in_store(CertSvcInstance instance,
+               CertStoreType storeType,
+               CertSvcString alias,
+               int *is_unique);
+
+/**
+ * Get list of certificates from PKCS#12 bundle or single certificate which
+ * is saved in cert-svc store with the alias.
+ *
+ * @param[in]  instance         CertSvcInstance object
+ * @param[in]  alias            Certificates bundle identifier used when importing
+ * @param[out] certificateList  List of certificates. Free by
+ *                              certsvc_certificate_list_free() after use
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ *
+ * @see certsvc_instance_new()
+ * @see certsvc_instance_free()
+ * @see certsvc_string_new()
+ * @see certsvc_string_free()
+ * @see certsvc_certificate_free()
+ * @see certsvc_certificate_list_free()
+ * @see #CertStoreType
+ * @see #CertSvcStoreCertList
+ */
+int certsvc_pkcs12_load_certificate_list_from_store(CertSvcInstance instance,
+               CertStoreType storeType,
+               CertSvcString alias,
+               CertSvcCertificateList *certificateList);
+
+/**
+ * Get the alias name with the gname provided.
+ *
+ * @param[in]  instance  CertSvcInstance object
+ * @param[in]  gname     Single certificate identifier which is associated with alias
+ * @param[out] alias     Certificates bundle identifier used when importing which must
+ *                       be freed after use
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ *
+ * @see certsvc_instance_new()
+ * @see certsvc_instance_free()
+ * @see certsvc_string_new()
+ * @see certsvc_string_free()
+ * @see #CertStoreType
+ */
+int certsvc_pkcs12_get_alias_name_for_certificate_in_store(CertSvcInstance instance,
+               CertStoreType storeType,
+               CertSvcString gname,
+               char **alias);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/src/cert-svc/cprimitives.h b/src/cert-svc/cprimitives.h
new file mode 100644 (file)
index 0000000..8feb9e9
--- /dev/null
@@ -0,0 +1,107 @@
+/**
+ * Copyright (c) 2016 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        cprimitives.h
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       cert-svc capi primitives
+ */
+#ifndef _CERTSVC_C_API_EXTENDED_H_
+#define _CERTSVC_C_API_EXTENDED_H_
+
+#include <openssl/evp.h>
+#include <openssl/x509.h>
+
+#include <cert-svc/ccert.h>
+#include <cert-svc/cstring.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * Duplicate @a CertSvcCertificate structure to openssl X509 structure.
+ * openssl X509 structure should be freed by certsvc_certificate_free_x509().
+ * @a CertSvcInstance isn't free duplicated openssl X509 structure.
+ *
+ * @param[in]  certificate  Certificate
+ * @param[out] x509         Duplicated @a certificate
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ *
+ * @see certsvc_certificate_free_x509()
+ */
+int certsvc_certificate_dup_x509(CertSvcCertificate certificate, X509 **x509);
+
+/**
+ * Free openssl x509 structure duplicated by certsvc_certificate_dup_x509().
+ *
+ * @param[in] x509  openssl X509 structure to free
+ *
+ * @see certsvc_certificate_dup_x509()
+ */
+void certsvc_certificate_free_x509(X509 *x509);
+
+/**
+ * Duplicate pubkey in DER form from CertSvcCertificate.
+ * Remarks: Free returned pubkey after use by free()
+ *
+ * @param[in]  certificate  Pointer to certificate.
+ * @param[out] pubkey       Duplicated certificate in DER form which must be
+ *                          freed after use
+ * @param[out] len          Duplicated certificate length
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ */
+int certsvc_certificate_dup_pubkey_der(CertSvcCertificate certificate, unsigned char **pubkey,
+                                                                          size_t *len);
+
+/**
+ * Get private key from cert-svc store in openssl EVP_PKEY structure.
+ * openssl EVP_PKEY structure should be freed by certsvc_pkcs12_free_evp_pkey().
+ * @a CertSvcInstance isn't free duplicated openssl EVP_PKEY structure.
+ *
+ * @param[in]  instance   CertSvcInstance object
+ * @param[in]  storeType  cert-svc store type to query
+ * @param[in]  gname      Single certificate identifier which is associated with
+ *                        private key
+ * @param[out] pkey       private key from storage which must be freed after use
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ *
+ * @see certsvc_pkcs12_free_evp_pkey()
+ */
+int certsvc_pkcs12_dup_evp_pkey_from_store(CertSvcInstance instance,
+               CertStoreType storeType,
+               CertSvcString gname,
+               EVP_PKEY **pkey);
+
+/**
+ * Free openssl EVP_PKEY structure duplicated by certsvc_pkcs12_dup_ev_pkey()
+ * or certsvc_pkcs12_dup_evp_pkey_from_store().
+ *
+ * @param[in] x509  openssl EVP_PKEY structure to free
+ *
+ * @see certsvc_pkcs12_dup_evp_pkey()
+ * @see certsvc_pkcs12_dup_evp_pkey_from_store()
+ */
+void certsvc_pkcs12_free_evp_pkey(EVP_PKEY *pkey);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/src/cert-svc/cstring.h b/src/cert-svc/cstring.h
new file mode 100644 (file)
index 0000000..4f3c37f
--- /dev/null
@@ -0,0 +1,151 @@
+/**
+ * Copyright (c) 2016 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        cstring.h
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       This is part of C api for ValidationCore.
+ */
+#ifndef _CERTSVC_CSTRING_H_
+#define _CERTSVC_CSTRING_H_
+
+#include <cert-svc/cinstance.h>
+#include <cert-svc/cstring.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+typedef struct CertSvcStringList_t {
+       size_t privateHandler;
+       CertSvcInstance privateInstance;
+} CertSvcStringList;
+
+typedef struct CertSvcString_t {
+       /*
+        * You are not allowed to use private fields of this structure. It is internal
+        * implementation of strings and it may change at any time without notice!
+        * To extract data use certsvc_string_to_cstring function!
+        */
+       char *privateHandler;
+       size_t privateLength;
+       CertSvcInstance privateInstance;
+} CertSvcString;
+
+/**
+ * Create CertSvcString with input cstring and size. Newly allocated memory
+ * is in same lifecycle with @a instance param unless freed by certsvc_string_free().
+ * If empty string is needed, put NULL on @a input param and 0 on @a size param.
+ *
+ * @param[in]  instance  CertSvcInstance object
+ * @param[in]  input     null-terminated string. Put #NULL if empty string needed
+ * @param[in]  size      size of @a input to make. put #0 if empty string needed.
+ *                       Can be smaller than length of @a input
+ * @param[out] output    Output CertSvcString with newly allocated memory
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ *
+ * @see certsvc_instance_new()
+ * @see certsvc_instance_free()
+ * @see certsvc_string_free()
+ */
+int certsvc_string_new(
+       CertSvcInstance instance,
+       const char *input,
+       size_t size,
+       CertSvcString *output);
+
+/**
+ * Create CertSvcString with @a input null-terminated string. @a output CertSvcString will
+ * contain pointer to @a input so input could not be freed as long as ouput param is used.
+ *
+ * @param[in]  instance  CertSvcInstance object
+ * @param[in]  input     null-terminated string. Put #NULL if empty string needed
+ * @param[in]  size      size of @a input to make. put #0 if empty string needed.
+ *                       Can be smaller than length of @a input
+ * @param[out] output    Output CertSvcString based on @a input
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ *
+ * @see certsvc_string_new()
+ * @see certsvc_string_free()
+ */
+int certsvc_string_not_managed(
+       CertSvcInstance instance,
+       const char *input,
+       size_t size,
+       CertSvcString *output);
+
+/**
+ * Get CertSvcString from CertSvcStringList with newly allocated memory.
+ * Output CertSvcString can be freed by certsvc_string_free() or reset/free instance
+ * of CertSvcInstance which is used to get the CertSvcStringList.
+ *
+ * @param[in]  handler   Handler to string list
+ * @param[in]  position  Index of CertSvcString to get in CertSvcStringList
+ * @param[out] buffer    Output CertSvcString must be freed by
+ *                       certsvc_string_free() after use
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ *
+ * @see certsvc_instance_free()
+ * @see certsvc_string_free()
+ */
+int certsvc_string_list_get_one(CertSvcStringList hander,
+                                                               size_t position,
+                                                               CertSvcString *buffer);
+
+/**
+ * Get list size of CertSvcStringList.
+ *
+ * @param[in]  handler  Handler to string list
+ * @param[out] size     Number of elements on the list
+ *
+ * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
+ */
+int certsvc_string_list_get_length(CertSvcStringList hander, size_t *size);
+
+/**
+ * Free CertSvcString.
+ *
+ * @param[in]  string   CertSvcString to free
+ */
+void certsvc_string_free(CertSvcString string);
+
+/**
+ * Free CertSvcStringList.
+ *
+ * @param[in]  handler   Handler to string list
+ */
+void certsvc_string_list_free(CertSvcStringList handler);
+
+/**
+ * Convert CertSvcString into null-terminated C string. Please note that this pointer
+ * is valid as long as CertSvcString is valid.
+ *
+ * @param[in]  string  CertSvcString
+ * @param[out] buffer  null-terminated c string
+ * @param[out] len     Length of string
+ */
+void certsvc_string_to_cstring(CertSvcString string, const char **buffer, size_t *len);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
+
diff --git a/src/dpl/core/include/dpl/assert.h b/src/dpl/core/include/dpl/assert.h
new file mode 100644 (file)
index 0000000..14ef0b7
--- /dev/null
@@ -0,0 +1,51 @@
+/*
+ * Copyright (c) 2011 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        assert.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of assert
+ */
+#ifndef DPL_ASSERT_H
+#define DPL_ASSERT_H
+
+namespace VcoreDPL {
+// Assertion handler procedure
+// Do not call directly
+// Always use Assert macro
+void AssertProc(const char *condition,
+                               const char *file,
+                               int line,
+                               const char *function) __attribute__((__noreturn__));
+} // namespace VcoreDPL
+
+#define Assert(Condition)                                               \
+       do {                                                                    \
+               if (!(Condition)) {                                                 \
+                       VcoreDPL::AssertProc(#Condition, __FILE__, __LINE__, __FUNCTION__);  \
+               }                                                                   \
+       } while (0)
+
+#define AssertMsg(Condition, Msg)                                         \
+       do {                                                                  \
+               if (!(Condition)) {                                               \
+                       VcoreDPL::AssertProc(                                              \
+                                       (std::string(std::string(#Condition)+" ") + Msg).c_str(), \
+                                       __FILE__, __LINE__, __FUNCTION__);                        \
+               }                                                                 \
+       } while (0)
+
+#endif // DPL_ASSERT_H
diff --git a/src/dpl/core/include/dpl/colors.h b/src/dpl/core/include/dpl/colors.h
new file mode 100644 (file)
index 0000000..5d8e91c
--- /dev/null
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2011 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        colors.h
+ * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
+ * @version     1.0
+ * @brief       Some constants with definition of colors for Console
+ *              and html output
+ */
+
+#ifndef DPL_COLORS_H
+#define DPL_COLORS_H
+
+namespace VcoreDPL {
+namespace Colors {
+namespace Text {
+extern const char *BOLD_GREEN_BEGIN;
+extern const char *BOLD_GREEN_END;
+extern const char *PURPLE_BEGIN;
+extern const char *PURPLE_END;
+extern const char *RED_BEGIN;
+extern const char *RED_END;
+extern const char *GREEN_BEGIN;
+extern const char *GREEN_END;
+extern const char *CYAN_BEGIN;
+extern const char *CYAN_END;
+extern const char *BOLD_RED_BEGIN;
+extern const char *BOLD_RED_END;
+extern const char *BOLD_YELLOW_BEGIN;
+extern const char *BOLD_YELLOW_END;
+extern const char *BOLD_GOLD_BEGIN;
+extern const char *BOLD_GOLD_END;
+extern const char *BOLD_WHITE_BEGIN;
+extern const char *BOLD_WHITE_END;
+} //namespace Text
+
+namespace Html {
+extern const char *BOLD_GREEN_BEGIN;
+extern const char *BOLD_GREEN_END;
+extern const char *PURPLE_BEGIN;
+extern const char *PURPLE_END;
+extern const char *RED_BEGIN;
+extern const char *RED_END;
+extern const char *GREEN_BEGIN;
+extern const char *GREEN_END;
+extern const char *CYAN_BEGIN;
+extern const char *CYAN_END;
+extern const char *BOLD_RED_BEGIN;
+extern const char *BOLD_RED_END;
+extern const char *BOLD_YELLOW_BEGIN;
+extern const char *BOLD_YELLOW_END;
+extern const char *BOLD_GOLD_BEGIN;
+extern const char *BOLD_GOLD_END;
+extern const char *BOLD_WHITE_BEGIN;
+extern const char *BOLD_WHITE_END;
+} //namespace Html
+} //namespace Colors
+} //namespace VcoreDPL
+
+#endif /* DPL_COLORS_H */
diff --git a/src/dpl/core/include/dpl/exception.h b/src/dpl/core/include/dpl/exception.h
new file mode 100644 (file)
index 0000000..fba822a
--- /dev/null
@@ -0,0 +1,382 @@
+/*
+ * Copyright (c) 2011 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  Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version 1.0
+ * @brief   Header file for base exception
+ */
+#ifndef VcoreDPL_EXCEPTION_H
+#define VcoreDPL_EXCEPTION_H
+
+#include <string>
+#include <cstring>
+#include <cstdio>
+#include <exception>
+#include <cstdlib>
+#include <sstream>
+
+namespace VcoreDPL {
+void LogUnhandledException(const std::string &str);
+void LogUnhandledException(const std::string &str,
+                                                  const char *filename,
+                                                  int line,
+                                                  const char *function);
+}
+
+namespace VcoreDPL {
+class Exception {
+private:
+       static unsigned int m_exceptionCount;
+       static Exception *m_lastException;
+       static void (*m_terminateHandler)();
+
+       static void AddRef(Exception *exception)
+       {
+               if (!m_exceptionCount) {
+                       m_terminateHandler = std::set_terminate(&TerminateHandler);
+               }
+
+               ++m_exceptionCount;
+               m_lastException = exception;
+       }
+
+       static void UnRef(Exception *e)
+       {
+               if (m_lastException == e) {
+                       m_lastException = NULL;
+               }
+
+               --m_exceptionCount;
+
+               if (!m_exceptionCount) {
+                       std::set_terminate(m_terminateHandler);
+                       m_terminateHandler = NULL;
+               }
+       }
+
+       static void TerminateHandler()
+       {
+               if (m_lastException != NULL) {
+                       DisplayKnownException(*m_lastException);
+                       abort();
+               } else {
+                       DisplayUnknownException();
+                       abort();
+               }
+       }
+
+       Exception *m_reason;
+       std::string m_path;
+       std::string m_function;
+       int m_line;
+
+protected:
+       std::string m_message;
+       std::string m_className;
+
+public:
+       static std::string KnownExceptionToString(const Exception &e)
+       {
+               std::ostringstream message;
+               message <<
+                               "\033[1;5;31m\n=== Unhandled DPL exception occurred ===\033[m\n\n";
+               message << "\033[1;33mException trace:\033[m\n\n";
+               message << e.DumpToString();
+               message << "\033[1;31m\n=== Will now abort ===\033[m\n";
+               return message.str();
+       }
+
+       static std::string UnknownExceptionToString()
+       {
+               std::ostringstream message;
+               message <<
+                               "\033[1;5;31m\n=== Unhandled non-DPL exception occurred ===\033[m\n\n";
+               message << "\033[1;31m\n=== Will now abort ===\033[m\n";
+               return message.str();
+       }
+
+       static void DisplayKnownException(const Exception &e)
+       {
+               LogUnhandledException(KnownExceptionToString(e).c_str());
+       }
+
+       static void DisplayUnknownException()
+       {
+               LogUnhandledException(UnknownExceptionToString().c_str());
+       }
+
+       Exception(const Exception &other)
+       {
+               // Deep copy
+               if (other.m_reason != NULL) {
+                       m_reason = new Exception(*other.m_reason);
+               } else {
+                       m_reason = NULL;
+               }
+
+               m_message = other.m_message;
+               m_path = other.m_path;
+               m_function = other.m_function;
+               m_line = other.m_line;
+               m_className = other.m_className;
+               AddRef(this);
+       }
+
+       const Exception &operator =(const Exception &other)
+       {
+               if (this == &other) {
+                       return *this;
+               }
+
+               // Deep copy
+               if (other.m_reason != NULL) {
+                       m_reason = new Exception(*other.m_reason);
+               } else {
+                       m_reason = NULL;
+               }
+
+               m_message = other.m_message;
+               m_path = other.m_path;
+               m_function = other.m_function;
+               m_line = other.m_line;
+               m_className = other.m_className;
+               AddRef(this);
+               return *this;
+       }
+
+       Exception(const char *path,
+                         const char *function,
+                         int line,
+                         const std::string &message) :
+               m_reason(NULL),
+               m_path(path),
+               m_function(function),
+               m_line(line),
+               m_message(message)
+       {
+               AddRef(this);
+       }
+
+       Exception(const char *path,
+                         const char *function,
+                         int line,
+                         const Exception &reason,
+                         const std::string &message) :
+               m_reason(new Exception(reason)),
+               m_path(path),
+               m_function(function),
+               m_line(line),
+               m_message(message)
+       {
+               AddRef(this);
+       }
+
+       virtual ~Exception() throw()
+       {
+               if (m_reason != NULL) {
+                       delete m_reason;
+                       m_reason = NULL;
+               }
+
+               UnRef(this);
+       }
+
+       void Dump() const
+       {
+               // Show reason first
+               if (m_reason != NULL) {
+                       m_reason->Dump();
+               }
+
+               // Afterward, dump exception
+               const char *file = strchr(m_path.c_str(), '/');
+
+               if (file == NULL) {
+                       file = m_path.c_str();
+               } else {
+                       ++file;
+               }
+
+               printf("\033[0;36m[%s:%i]\033[m %s() \033[4;35m%s\033[m: %s\033[m\n",
+                          file, m_line,
+                          m_function.c_str(),
+                          m_className.c_str(),
+                          m_message.empty() ? "<EMPTY>" : m_message.c_str());
+       }
+
+       std::string DumpToString() const
+       {
+               std::string ret;
+
+               if (m_reason != NULL) {
+                       ret = m_reason->DumpToString();
+               }
+
+               const char *file = strchr(m_path.c_str(), '/');
+
+               if (file == NULL) {
+                       file = m_path.c_str();
+               } else {
+                       ++file;
+               }
+
+               char buf[1024];
+               snprintf(buf,
+                                sizeof(buf),
+                                "\033[0;36m[%s:%i]\033[m %s() \033[4;35m%s\033[m: %s\033[m\n",
+                                file,
+                                m_line,
+                                m_function.c_str(),
+                                m_className.c_str(),
+                                m_message.empty() ? "<EMPTY>" : m_message.c_str());
+               buf[sizeof(buf) - 1] = '\n';
+               ret += buf;
+               return ret;
+       }
+
+       Exception *GetReason() const
+       {
+               return m_reason;
+       }
+
+       std::string GetPath() const
+       {
+               return m_path;
+       }
+
+       std::string GetFunction() const
+       {
+               return m_function;
+       }
+
+       int GetLine() const
+       {
+               return m_line;
+       }
+
+       std::string GetMessage() const
+       {
+               return m_message;
+       }
+
+       std::string GetClassName() const
+       {
+               return m_className;
+       }
+};
+} // namespace VcoreDPL
+
+#define Try try
+
+#define Throw(ClassName) \
+       throw ClassName(__FILE__, __FUNCTION__, __LINE__)
+
+#define ThrowMsg(ClassName, Message)                                                 \
+       do                                                                               \
+       {                                                                                \
+               std::ostringstream dplLoggingStream;                                         \
+               dplLoggingStream << Message;                                                 \
+               throw ClassName(__FILE__, __FUNCTION__, __LINE__, dplLoggingStream.str());   \
+       } while (0)
+
+#define ReThrow(ClassName) \
+       throw ClassName(__FILE__, __FUNCTION__, __LINE__, _rethrown_exception)
+
+#define ReThrowMsg(ClassName, Message)                                               \
+       throw ClassName(__FILE__,                                                        \
+                                       __FUNCTION__,                                                    \
+                                       __LINE__,                                                        \
+                                       _rethrown_exception,                                             \
+                                       Message)
+
+#define Catch(ClassName)                                                             \
+       catch (const ClassName &_rethrown_exception)
+
+#define DECLARE_EXCEPTION_TYPE(BaseClass, Class)                                     \
+       class Class : public BaseClass {                                                 \
+       public:                                                                          \
+               Class(const char *path,                                                      \
+                         const char *function,                                                  \
+                         int line,                                                              \
+                         const std::string & message = std::string())                           \
+                       : BaseClass(path, function, line, message) {                               \
+                       \
+                       BaseClass::m_className = #Class;                                         \
+               }                                                                            \
+               \
+               Class(const char *path,                                                      \
+                         const char *function,                                                  \
+                         int line,                                                              \
+                         const VcoreDPL::Exception & reason,                                    \
+                         const std::string & message = std::string())                           \
+                       : BaseClass(path, function, line, reason, message) {                       \
+                       BaseClass::m_className = #Class;                                         \
+               }                                                                            \
+       };
+
+#define UNHANDLED_EXCEPTION_HANDLER_BEGIN try
+
+#define UNHANDLED_EXCEPTION_HANDLER_END                                              \
+       catch (const VcoreDPL::Exception &exception)                                     \
+       {                                                                                \
+               std::ostringstream msg;                                                      \
+               msg << VcoreDPL::Exception::KnownExceptionToString(exception);               \
+               VcoreDPL::LogUnhandledException(msg.str(),                                   \
+                                                                               __FILE__,                                    \
+                                                                               __LINE__,                                    \
+                                                                               __FUNCTION__);                                \
+               abort();                                                                     \
+       }                                                                                \
+       catch (std::exception& e)                                                        \
+       {                                                                                \
+               std::ostringstream msg;                                                      \
+               msg << e.what();                                                             \
+               msg << "\n";                                                                 \
+               msg << VcoreDPL::Exception::UnknownExceptionToString();                      \
+               VcoreDPL::LogUnhandledException(msg.str(),                                   \
+                                                                               __FILE__,                                    \
+                                                                               __LINE__,                                    \
+                                                                               __FUNCTION__);                               \
+               abort();                                                                     \
+       }                                                                                \
+       catch (...)                                                                      \
+       {                                                                                \
+               std::ostringstream msg;                                                      \
+               msg << VcoreDPL::Exception::UnknownExceptionToString();                      \
+               VcoreDPL::LogUnhandledException(msg.str(),                                   \
+                                                                               __FILE__,                                    \
+                                                                               __LINE__,                                    \
+                                                                               __FUNCTION__);                               \
+               abort();                                                                     \
+       }
+
+namespace VcoreDPL {
+namespace CommonException {
+/**
+ * Internal exception definitions
+ *
+ * These should normally not happen.
+ * Usually, exception trace with internal error includes
+ * important messages.
+ */
+DECLARE_EXCEPTION_TYPE(Exception, InternalError) ///< Unexpected error from
+// underlying libraries or
+// kernel
+}
+}
+
+#endif // VcoreDPL_EXCEPTION_H
diff --git a/src/dpl/core/include/dpl/singleton.h b/src/dpl/core/include/dpl/singleton.h
new file mode 100644 (file)
index 0000000..bec534a
--- /dev/null
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2011 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        singleton.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of singleton
+ */
+#ifndef DPL_SINGLETON_H
+#define DPL_SINGLETON_H
+
+namespace VcoreDPL {
+template<typename Class>
+class Singleton :
+       private Class {
+       //
+       // Note:
+       //
+       // To remove posibility of instantiating directly Class,
+       // make Class' default constructor protected
+       //
+
+private:
+       Singleton()
+       {}
+
+       static Singleton &InternalInstance();
+
+public:
+       virtual ~Singleton()
+       {}
+
+       static Class &Instance();
+};
+} // namespace VcoreDPL
+
+#endif // DPL_SINGLETON_H
diff --git a/src/dpl/core/include/dpl/singleton_impl.h b/src/dpl/core/include/dpl/singleton_impl.h
new file mode 100644 (file)
index 0000000..502d926
--- /dev/null
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2011 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        singleton_impl.h
+ * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of singleton
+ */
+#ifndef DPL_SINGLETON_IMPL_H
+#define DPL_SINGLETON_IMPL_H
+
+#include <dpl/singleton.h>
+
+/*
+ * WARNING!
+ *
+ * If some singleton's implementation uses another singletons implementation,
+ * those templates make the second singleton a dubleton. Be warned. Try to use
+ * singleton_safe_impl.h if possible.
+ */
+
+namespace VcoreDPL {
+template<typename Class>
+Singleton<Class> &Singleton<Class>::InternalInstance()
+{
+       static Singleton<Class> instance;
+       return instance;
+}
+
+template<typename Class>
+Class &Singleton<Class>::Instance()
+{
+       Singleton<Class> &instance = Singleton<Class>::InternalInstance();
+       return instance;
+}
+} // namespace VcoreDPL
+
+#define IMPLEMENT_SINGLETON(Type)                                                     \
+       template VcoreDPL::Singleton<Type>&VcoreDPL::Singleton<Type>::InternalInstance(); \
+       template Type & VcoreDPL::Singleton<Type>::Instance();                            \
+
+#endif // DPL_SINGLETON_IMPL_H
diff --git a/src/dpl/core/src/assert.cpp b/src/dpl/core/src/assert.cpp
new file mode 100644 (file)
index 0000000..6e02192
--- /dev/null
@@ -0,0 +1,52 @@
+/*
+ * Copyright (c) 2011 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        assert.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of assert
+ */
+#include <cstdlib>
+#include <sstream>
+#include <stddef.h>
+#include <dpl/assert.h>
+#include <dpl/exception.h>
+#include <dpl/log/log.h>
+
+namespace VcoreDPL {
+void AssertProc(const char *condition,
+                               const char *file,
+                               int line,
+                               const char *function)
+{
+       // Try to log failed assertion to log system
+       Try {
+               LogError("########################################################################");
+               LogError("###                      DPL assertion failed!                       ###");
+               LogError("########################################################################");
+               LogError("### Condition: " << condition);
+               LogError("### File: " << file);
+               LogError("### Line: " << line);
+               LogError("### Function: " << function);
+               LogError("########################################################################");
+       } catch (Exception) {
+               // Just ignore possible double errors
+       }
+
+       // Fail with c-library abort
+       abort();
+}
+} // namespace VcoreDPL
diff --git a/src/dpl/core/src/colors.cpp b/src/dpl/core/src/colors.cpp
new file mode 100644 (file)
index 0000000..2ec2749
--- /dev/null
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2011 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        colors.cpp
+ * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
+ * @version     1.0
+ * @brief       Some constants with definition of colors for Console
+ *              and html output
+ */
+#include <stddef.h>
+#include <dpl/colors.h>
+
+namespace VcoreDPL {
+namespace Colors {
+namespace Text {
+const char *BOLD_GREEN_BEGIN = "\033[1;32m";
+const char *BOLD_GREEN_END = "\033[m";
+const char *RED_BEGIN = "\033[0;31m";
+const char *RED_END = "\033[m";
+const char *PURPLE_BEGIN = "\033[0;35m";
+const char *PURPLE_END = "\033[m";
+const char *GREEN_BEGIN = "\033[0;32m";
+const char *GREEN_END = "\033[m";
+const char *CYAN_BEGIN = "\033[0;36m";
+const char *CYAN_END = "\033[m";
+const char *BOLD_RED_BEGIN = "\033[1;31m";
+const char *BOLD_RED_END = "\033[m";
+const char *BOLD_YELLOW_BEGIN = "\033[1;33m";
+const char *BOLD_YELLOW_END = "\033[m";
+const char *BOLD_GOLD_BEGIN = "\033[0;33m";
+const char *BOLD_GOLD_END = "\033[m";
+const char *BOLD_WHITE_BEGIN = "\033[1;37m";
+const char *BOLD_WHITE_END = "\033[m";
+} //namespace Text
+
+namespace Html {
+const char *BOLD_GREEN_BEGIN = "<font color=\"green\"><b>";
+const char *BOLD_GREEN_END = "</b></font>";
+const char *PURPLE_BEGIN = "<font color=\"purple\"><b>";
+const char *PURPLE_END = "</b></font>";
+const char *RED_BEGIN = "<font color=\"red\"><b>";
+const char *RED_END = "</b></font>";
+const char *GREEN_BEGIN = "<font color=\"green\">";
+const char *GREEN_END = "</font>";
+const char *CYAN_BEGIN = "<font color=\"cyan\">";
+const char *CYAN_END = "</font>";
+const char *BOLD_RED_BEGIN = "<font color=\"red\"><b>";
+const char *BOLD_RED_END = "</b></font>";
+const char *BOLD_YELLOW_BEGIN = "<font color=\"yellow\"><b>";
+const char *BOLD_YELLOW_END = "</b></font>";
+const char *BOLD_GOLD_BEGIN = "<font color=\"gold\"><b>";
+const char *BOLD_GOLD_END = "</b></font>";
+const char *BOLD_WHITE_BEGIN = "<font color=\"white\"><b>";
+const char *BOLD_WHITE_END = "</b></font>";
+} //namespace Html
+} //namespace Colors
+} //namespace VcoreDPL
diff --git a/src/dpl/core/src/exception.cpp b/src/dpl/core/src/exception.cpp
new file mode 100644 (file)
index 0000000..7e9faa2
--- /dev/null
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2011 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      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation of exception system
+ */
+#include <stddef.h>
+#include <dpl/exception.h>
+#include <dpl/log/log.h>
+#include <cstdio>
+
+namespace VcoreDPL {
+Exception *Exception::m_lastException = NULL;
+unsigned int Exception::m_exceptionCount = 0;
+void (*Exception::m_terminateHandler)() = NULL;
+
+void LogUnhandledException(const std::string &str)
+{
+       LogDebug("" << str);
+}
+
+void LogUnhandledException(const std::string &str,
+                                                  const char *filename,
+                                                  int line,
+                                                  const char *function)
+{
+       LogError("Exception occured on file[" << filename
+                        << "] line[" << line
+                        << "] function[" << function
+                        << "] msg[" << str << "]");
+}
+} // namespace VcoreDPL
diff --git a/src/dpl/core/src/singleton.cpp b/src/dpl/core/src/singleton.cpp
new file mode 100644 (file)
index 0000000..54abd52
--- /dev/null
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2011 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        singleton.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of singleton
+ */
+#include <stddef.h>
+#include <dpl/singleton.h>
+
+//
+// Note:
+//
+// The file here is left blank to enable precompilation
+// of templates in corresponding header file.
+// Do not remove this file.
+//
diff --git a/src/dpl/log/include/dpl/log/abstract_log_provider.h b/src/dpl/log/include/dpl/log/abstract_log_provider.h
new file mode 100644 (file)
index 0000000..b2bf970
--- /dev/null
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2011 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        abstract_log_provider.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of abstract log provider
+ */
+#ifndef DPL_ABSTRACT_LOG_PROVIDER_H
+#define DPL_ABSTRACT_LOG_PROVIDER_H
+
+namespace VcoreDPL {
+namespace Log {
+class AbstractLogProvider {
+public:
+       enum class LogLevel {
+               None,
+               Error,
+               Warning,
+               Info,
+               Debug,
+               Pedantic
+       };
+
+       virtual ~AbstractLogProvider() {}
+
+       virtual void SetTag(const char *tag);
+
+       virtual void Log(LogLevel level,
+                                        const char *message,
+                                        const char *fileName,
+                                        int line,
+                                        const char *function) const = 0;
+
+protected:
+       static const char *LocateSourceFileName(const char *filename);
+};
+}
+} // namespace VcoreDPL
+
+#endif // DPL_ABSTRACT_LOG_PROVIDER_H
diff --git a/src/dpl/log/include/dpl/log/dlog_log_provider.h b/src/dpl/log/include/dpl/log/dlog_log_provider.h
new file mode 100644 (file)
index 0000000..e1e5be2
--- /dev/null
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2011 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        dlog_log_provider.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of DLOG log provider
+ */
+#ifndef DPL_DLOG_LOG_PROVIDER_H
+#define DPL_DLOG_LOG_PROVIDER_H
+
+#include <dpl/log/abstract_log_provider.h>
+#include <memory>
+
+namespace VcoreDPL {
+namespace Log {
+class DLOGLogProvider : public AbstractLogProvider {
+public:
+       DLOGLogProvider();
+       virtual ~DLOGLogProvider();
+
+       virtual void Log(AbstractLogProvider::LogLevel level,
+                                        const char *message,
+                                        const char *fileName,
+                                        int line,
+                                        const char *function) const;
+
+       // Set global Tag according to DLOG
+       virtual void SetTag(const char *tag);
+
+private:
+       std::unique_ptr<char[]> m_tag;
+};
+}
+} // namespace VcoreDPL
+
+#endif // DPL_DLOG_LOG_PROVIDER_H
diff --git a/src/dpl/log/include/dpl/log/journal_log_provider.h b/src/dpl/log/include/dpl/log/journal_log_provider.h
new file mode 100644 (file)
index 0000000..3c2cc5a
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ *  Copyright (c) 2000 - 2014 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       journal_log_provider.h
+ * @author     Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
+ * @version    1.0
+ */
+
+#pragma once
+
+#include <dpl/log/abstract_log_provider.h>
+
+namespace VcoreDPL {
+namespace Log {
+
+class JournalLogProvider: public AbstractLogProvider {
+public:
+       JournalLogProvider();
+       virtual ~JournalLogProvider();
+
+       virtual void Log(AbstractLogProvider::LogLevel level,
+                                        const char *message,
+                                        const char *fileName,
+                                        int line,
+                                        const char *function) const;
+};
+
+} /* namespace Log */
+} /* namespace VcoreDPL */
diff --git a/src/dpl/log/include/dpl/log/log.h b/src/dpl/log/include/dpl/log/log.h
new file mode 100644 (file)
index 0000000..07cac3d
--- /dev/null
@@ -0,0 +1,166 @@
+/*
+ * Copyright (c) 2011 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        log.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of log system
+ */
+#ifndef DPL_LOG_H
+#define DPL_LOG_H
+
+#include <sstream>
+#include <list>
+#include <unordered_map>
+#include <string>
+
+#include <dpl/singleton.h>
+
+#include <dpl/log/abstract_log_provider.h>
+
+namespace VcoreDPL {
+namespace Log {
+/**
+ * DPL log system
+ *
+ * To switch logs into old style, export
+ * DPL_USE_OLD_STYLE_LOGS before application start
+ */
+class LogSystem {
+public:
+       LogSystem();
+       virtual ~LogSystem();
+
+       LogSystem(const LogSystem &) = delete;
+       LogSystem &operator=(const LogSystem &) = delete;
+       LogSystem(LogSystem &&) = delete;
+       LogSystem &operator=(LogSystem &&) = delete;
+
+       AbstractLogProvider::LogLevel GetLogLevel() const
+       {
+               return m_level;
+       }
+
+       void Log(AbstractLogProvider::LogLevel level,
+                        const char *message,
+                        const char *filename,
+                        int line,
+                        const char *function) const;
+
+
+       /**
+        * Set default's DLOG provider Tag
+        */
+       void SetTag(const char *tag);
+
+       /**
+        * Add abstract provider to providers list
+        *
+        * @notice Ownership is transfered to LogSystem and deleted upon exit
+        */
+       void AddProvider(AbstractLogProvider *provider);
+
+       /**
+        * Remove abstract provider from providers list
+        */
+       void RemoveProvider(AbstractLogProvider *provider);
+
+       /**
+        * Selects given provider by name (overwrites environment setting)
+        *
+        * Throws std::out_of_range exception if not found.
+        */
+       void SelectProvider(const std::string &name);
+
+       /**
+        * Sets log level (overwrites environment settings)
+        */
+       void SetLogLevel(const char *level);
+
+private:
+       void RemoveProviders();
+
+       typedef std::list<AbstractLogProvider *> AbstractLogProviderPtrList;
+       AbstractLogProviderPtrList m_providers;
+       AbstractLogProvider::LogLevel m_level;
+
+       typedef AbstractLogProvider *(*ProviderFn)();
+       /*
+        * It cannot be global as it is used in library constructor and we can't be sure which
+        * constructor is called first: library's or new_provider's.
+        */
+       std::unordered_map<std::string, ProviderFn> m_providerCtor;
+};
+
+/*
+ * Replacement low overhead null logging class
+ */
+class NullStream {
+public:
+       NullStream() {}
+
+       template <typename T>
+       NullStream &operator<<(const T &)
+       {
+               return *this;
+       }
+};
+
+/**
+ * Log system singleton
+ */
+typedef Singleton<LogSystem> LogSystemSingleton;
+}
+} // namespace VcoreDPL
+
+
+/* avoid warnings about unused variables */
+#define DPL_MACRO_DUMMY_LOGGING(message, level)                                 \
+       do {                                                                        \
+               VcoreDPL::Log::NullStream ns;                                           \
+               ns << message;                                                          \
+       } while (0)
+
+#define DPL_MACRO_FOR_LOGGING(message, level)                                   \
+       do                                                                              \
+       {                                                                               \
+               if (level > VcoreDPL::Log::AbstractLogProvider::LogLevel::None &&           \
+                               VcoreDPL::Log::LogSystemSingleton::Instance().GetLogLevel() >= level)   \
+               {                                                                           \
+                       std::ostringstream platformLog;                                         \
+                       platformLog << message;                                                 \
+                       VcoreDPL::Log::LogSystemSingleton::Instance().Log(level,                \
+                                       platformLog.str().c_str(), \
+                                       __FILE__,                  \
+                                       __LINE__,                  \
+                                       __FUNCTION__);             \
+               }                                                                           \
+       } while (0)
+
+
+#ifdef TIZEN_ENGINEER_MODE
+#define LogDebug(message)    DPL_MACRO_FOR_LOGGING(message, VcoreDPL::Log::AbstractLogProvider::LogLevel::Debug)
+#define LogPedantic(message) DPL_MACRO_FOR_LOGGING(message, VcoreDPL::Log::AbstractLogProvider::LogLevel::Pedantic)
+#else
+#define LogDebug(message)    DPL_MACRO_DUMMY_LOGGING(message, VcoreDPL::Log::AbstractLogProvider::LogLevel::Debug)
+#define LogPedantic(message) DPL_MACRO_DUMMY_LOGGING(message, VcoreDPL::Log::AbstractLogProvider::LogLevel::Pedantic)
+#endif // TIZEN_ENGINEER_MODE
+
+#define LogInfo(message)    DPL_MACRO_FOR_LOGGING(message, VcoreDPL::Log::AbstractLogProvider::LogLevel::Info)
+#define LogWarning(message) DPL_MACRO_FOR_LOGGING(message, VcoreDPL::Log::AbstractLogProvider::LogLevel::Warning)
+#define LogError(message)   DPL_MACRO_FOR_LOGGING(message, VcoreDPL::Log::AbstractLogProvider::LogLevel::Error)
+
+#endif // DPL_LOG_H
diff --git a/src/dpl/log/include/dpl/log/old_style_log_provider.h b/src/dpl/log/include/dpl/log/old_style_log_provider.h
new file mode 100644 (file)
index 0000000..e26da28
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2011 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        old_style_log_provider.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of old style log provider
+ */
+#ifndef DPL_OLD_STYLE_LOG_PROVIDER_H
+#define DPL_OLD_STYLE_LOG_PROVIDER_H
+
+#include <dpl/log/abstract_log_provider.h>
+
+namespace VcoreDPL {
+namespace Log {
+class OldStyleLogProvider : public AbstractLogProvider {
+public:
+       OldStyleLogProvider();
+       virtual ~OldStyleLogProvider() {}
+
+       virtual void Log(AbstractLogProvider::LogLevel level,
+                                        const char *message,
+                                        const char *fileName,
+                                        int line,
+                                        const char *function) const;
+};
+}
+} // namespace VcoreDPL
+
+#endif // DPL_OLD_STYLE_LOG_PROVIDER_H
diff --git a/src/dpl/log/src/abstract_log_provider.cpp b/src/dpl/log/src/abstract_log_provider.cpp
new file mode 100644 (file)
index 0000000..21fd2f1
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2011 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        abstract_log_provider.cpp
+ * @author      Pawel Sikorski (p.sikorski@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of abstract log provider
+ */
+#include <stddef.h>
+#include <dpl/log/abstract_log_provider.h>
+#include <cstring>
+
+namespace VcoreDPL {
+namespace Log {
+
+void AbstractLogProvider::SetTag(const char *) {}
+
+const char *AbstractLogProvider::LocateSourceFileName(const char *filename)
+{
+       const char *ptr = strrchr(filename, '/');
+       return ptr != NULL ? ptr + 1 : filename;
+}
+}
+}
diff --git a/src/dpl/log/src/dlog_log_provider.cpp b/src/dpl/log/src/dlog_log_provider.cpp
new file mode 100644 (file)
index 0000000..4f514b2
--- /dev/null
@@ -0,0 +1,108 @@
+/*
+ * Copyright (c) 2011 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        dlog_log_provider.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of DLOG log provider
+ */
+#include <stddef.h>
+#include <cstring>
+#include <sstream>
+#include <map>
+#include <stdexcept>
+
+#include <dlog.h>
+
+#include <dpl/log/dlog_log_provider.h>
+
+namespace VcoreDPL {
+namespace Log {
+
+namespace {
+typedef void (*dlogMacro)(const char *, const char *);
+
+void error(const char *tag, const char *msg)
+{
+       SLOG(LOG_ERROR, tag, "%s", msg);
+}
+
+void warning(const char *tag, const char *msg)
+{
+       SLOG(LOG_WARN, tag, "%s", msg);
+}
+
+void info(const char *tag, const char *msg)
+{
+       SLOG(LOG_INFO, tag, "%s", msg);
+}
+
+void debug(const char *tag, const char *msg)
+{
+       SLOG(LOG_DEBUG, tag, "%s", msg);
+}
+
+void pedantic(const char *tag, const char *msg)
+{
+       SLOG(LOG_VERBOSE, tag, "%s", msg);
+}
+
+std::map<AbstractLogProvider::LogLevel, dlogMacro> dlogMacros = {
+       // [](const char* tag, const char* msg) { SLOG(LOG_ERROR, tag, "%s", msg); } won't compile
+       { AbstractLogProvider::LogLevel::Error,     error },
+       { AbstractLogProvider::LogLevel::Warning,   warning },
+       { AbstractLogProvider::LogLevel::Info,      info },
+       { AbstractLogProvider::LogLevel::Debug,     debug},
+       { AbstractLogProvider::LogLevel::Pedantic,  pedantic}
+};
+
+} // namespace anonymous
+
+DLOGLogProvider::DLOGLogProvider()
+{}
+
+DLOGLogProvider::~DLOGLogProvider()
+{}
+
+void DLOGLogProvider::SetTag(const char *tag)
+{
+       size_t size = strlen(tag) + 1;
+       char *buff = new(std::nothrow) char[size];
+
+       if (buff)
+               memcpy(buff, tag, size);
+
+       m_tag.reset(buff);
+}
+
+void DLOGLogProvider::Log(AbstractLogProvider::LogLevel level,
+                                                 const char *message,
+                                                 const char *filename,
+                                                 int line,
+                                                 const char *function) const
+{
+       std::ostringstream val;
+       val << std::string("[") << LocateSourceFileName(filename) << std::string(":") << line <<
+               std::string("] ") << function << std::string("(): ") << message;
+
+       try {
+               dlogMacros.at(level)(m_tag.get(), val.str().c_str());
+       } catch (const std::out_of_range &) {
+               SLOG(LOG_ERROR, m_tag.get(), "Unsupported log level: %d", level);
+       }
+}
+}
+} // namespace VcoreDPL
diff --git a/src/dpl/log/src/journal_log_provider.cpp b/src/dpl/log/src/journal_log_provider.cpp
new file mode 100644 (file)
index 0000000..0abf8d8
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ *  Copyright (c) 2000 - 2014 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       journal_log_provider.cpp
+ * @author     Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
+ * @version    1.0
+ */
+
+#include <dpl/log/journal_log_provider.h>
+#include <systemd/sd-journal.h>
+#include <map>
+#include <stdexcept>
+
+namespace VcoreDPL {
+namespace Log {
+
+namespace {
+std::map<AbstractLogProvider::LogLevel, int> journalLevel = {
+       { AbstractLogProvider::LogLevel::Error,     LOG_ERR     },
+       { AbstractLogProvider::LogLevel::Warning,   LOG_WARNING },
+       { AbstractLogProvider::LogLevel::Info,      LOG_INFO    },
+       { AbstractLogProvider::LogLevel::Debug,     LOG_DEBUG   },
+       { AbstractLogProvider::LogLevel::Pedantic,  LOG_DEBUG   }
+};
+
+} // namespace anonymous
+
+JournalLogProvider::JournalLogProvider()
+{}
+
+JournalLogProvider::~JournalLogProvider()
+{}
+
+void JournalLogProvider::Log(AbstractLogProvider::LogLevel level,
+                                                        const char *message,
+                                                        const char *fileName,
+                                                        int line,
+                                                        const char *function) const
+{
+       try {
+               sd_journal_send("PRIORITY=%d", journalLevel.at(level),
+                                               "CODE_FILE=%s", fileName,
+                                               "CODE_FUNC=%s", function,
+                                               "CODE_LINE=%d", line,
+                                               // add file, line & function info to log message
+                                               "MESSAGE=[%s:%d] %s(): %s", fileName, line, function, message,
+                                               NULL);
+       } catch (const std::out_of_range &) {
+               sd_journal_send(
+                       "PRIORITY=%d", LOG_ERR,
+                       "CODE_FILE=%s", fileName,
+                       "CODE_FUNC=%s", function,
+                       "CODE_LINE=%d", line,
+                       // add file, line & function info to log message
+                       "MESSAGE=[%s:%d] %s(): Unsupported log level %d", fileName, line, function, level,
+                       NULL);
+       }
+}
+
+} /* namespace Log */
+} /* namespace VcoreDPL */
diff --git a/src/dpl/log/src/log.cpp b/src/dpl/log/src/log.cpp
new file mode 100644 (file)
index 0000000..5bd61ed
--- /dev/null
@@ -0,0 +1,140 @@
+/*
+ * Copyright (c) 2011 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        log.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of log system
+ */
+#include <stddef.h>
+#include <string.h>
+#include <stdexcept>
+#include <cassert>
+
+#include <dpl/singleton_impl.h>
+#include <dpl/log/old_style_log_provider.h>
+#include <dpl/log/dlog_log_provider.h>
+#include <dpl/log/journal_log_provider.h>
+
+#include <dpl/log/log.h>
+
+IMPLEMENT_SINGLETON(VcoreDPL::Log::LogSystem)
+
+namespace VcoreDPL {
+namespace Log {
+namespace { // anonymous
+const char *const CERTSVC_LOG_LEVEL    = "CERTSVC_LOG_LEVEL";
+const char *const CERTSVC_LOG_PROVIDER = "CERTSVC_LOG_PROVIDER";
+
+const char *const CONSOLE  = "CONSOLE";
+const char *const DLOG     = "DLOG";
+const char *const JOURNALD = "JOURNALD";
+} // namespace anonymous
+
+LogSystem::LogSystem()
+       : m_providerCtor(
+{
+#ifdef TIZEN_ENGINEER_MODE
+       { CONSOLE,  []{ return static_cast<AbstractLogProvider *>(new OldStyleLogProvider()); }},
+#endif
+       { DLOG,     []{ return static_cast<AbstractLogProvider *>(new DLOGLogProvider());     }},
+       { JOURNALD, []{ return static_cast<AbstractLogProvider *>(new JournalLogProvider());  }}
+})
+{
+       SetLogLevel(getenv(CERTSVC_LOG_LEVEL));
+       AbstractLogProvider *prv = NULL;
+
+       try {
+               prv = m_providerCtor.at(getenv(CERTSVC_LOG_PROVIDER))();
+       } catch (const std::exception &) {
+               prv = m_providerCtor[DLOG]();
+       }
+
+       AddProvider(prv);
+}
+
+LogSystem::~LogSystem()
+{
+       RemoveProviders();
+}
+
+void LogSystem::SetTag(const char *tag)
+{
+       for (auto &it : m_providers)
+               it->SetTag(tag);
+}
+
+void LogSystem::AddProvider(AbstractLogProvider *provider)
+{
+       m_providers.push_back(provider);
+}
+
+void LogSystem::RemoveProvider(AbstractLogProvider *provider)
+{
+       m_providers.remove(provider);
+}
+
+void LogSystem::SelectProvider(const std::string &name)
+{
+       ProviderFn &prv = m_providerCtor.at(name);
+       RemoveProviders();
+       AddProvider(prv());
+}
+
+void LogSystem::SetLogLevel(const char *level)
+{
+       if (!level) {
+               m_level = AbstractLogProvider::LogLevel::Debug;
+       } else {
+               try {
+                       m_level = static_cast<AbstractLogProvider::LogLevel>(std::stoi(level));
+               } catch (const std::exception &) {
+                       m_level = AbstractLogProvider::LogLevel::Debug;
+               }
+       }
+
+       if (m_level < AbstractLogProvider::LogLevel::None)
+               m_level = AbstractLogProvider::LogLevel::None;
+       else if (m_level > AbstractLogProvider::LogLevel::Pedantic)
+               m_level = AbstractLogProvider::LogLevel::Pedantic;
+
+#ifndef TIZEN_ENGINEER_MODE
+
+       if (m_level > AbstractLogProvider::LogLevel::Error)
+               m_level = AbstractLogProvider::LogLevel::Error;
+
+#endif
+}
+
+void LogSystem::Log(AbstractLogProvider::LogLevel level,
+                                       const char *message,
+                                       const char *filename,
+                                       int line,
+                                       const char *function) const
+{
+       for (const auto &it : m_providers)
+               it->Log(level, message, filename, line, function);
+}
+
+void LogSystem::RemoveProviders()
+{
+       for (auto &it : m_providers)
+               delete it;
+
+       m_providers.clear();
+}
+}
+} // namespace VcoreDPL
diff --git a/src/dpl/log/src/old_style_log_provider.cpp b/src/dpl/log/src/old_style_log_provider.cpp
new file mode 100644 (file)
index 0000000..f1dd0d0
--- /dev/null
@@ -0,0 +1,103 @@
+/*
+ * Copyright (c) 2011 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        old_style_log_provider.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of old style log provider
+ */
+#include <stddef.h>
+#include <unistd.h>
+#include <sys/time.h>
+#include <cstdio>
+#include <cstring>
+#include <sstream>
+#include <stdexcept>
+#include <map>
+
+#include <dpl/log/old_style_log_provider.h>
+#include <dpl/colors.h>
+
+namespace VcoreDPL {
+namespace Log {
+namespace { // anonymous
+using namespace VcoreDPL::Colors::Text;
+const char *DEBUG_BEGIN = GREEN_BEGIN;
+const char *DEBUG_END = GREEN_END;
+const char *INFO_BEGIN = CYAN_BEGIN;
+const char *INFO_END = CYAN_END;
+const char *ERROR_BEGIN = RED_BEGIN;
+const char *ERROR_END = RED_END;
+const char *WARNING_BEGIN = BOLD_GOLD_BEGIN;
+const char *WARNING_END = BOLD_GOLD_END;
+const char *PEDANTIC_BEGIN = PURPLE_BEGIN;
+const char *PEDANTIC_END = PURPLE_END;
+
+std::string GetFormattedTime()
+{
+       timeval tv;
+       tm localNowTime;
+       gettimeofday(&tv, NULL);
+       localtime_r(&tv.tv_sec, &localNowTime);
+       char format[64];
+       snprintf(format,
+                        sizeof(format),
+                        "%02i:%02i:%02i.%03i",
+                        localNowTime.tm_hour,
+                        localNowTime.tm_min,
+                        localNowTime.tm_sec,
+                        static_cast<int>(tv.tv_usec / 1000));
+       return format;
+}
+
+struct ColorMark {
+       const char *const begin;
+       const char *const end;
+};
+
+std::map<AbstractLogProvider::LogLevel, ColorMark> consoleLevel = {
+       { AbstractLogProvider::LogLevel::Error,     {ERROR_BEGIN,       ERROR_END} },
+       { AbstractLogProvider::LogLevel::Warning,   {WARNING_BEGIN,     WARNING_END} },
+       { AbstractLogProvider::LogLevel::Info,      {INFO_BEGIN,        INFO_END} },
+       { AbstractLogProvider::LogLevel::Debug,     {DEBUG_BEGIN,       DEBUG_END} },
+       { AbstractLogProvider::LogLevel::Pedantic,  {PEDANTIC_BEGIN,    PEDANTIC_END} }
+};
+
+} // namespace anonymous
+
+OldStyleLogProvider::OldStyleLogProvider() {}
+
+void OldStyleLogProvider::Log(AbstractLogProvider::LogLevel level,
+                                                         const char *message,
+                                                         const char *filename,
+                                                         int line,
+                                                         const char *function) const
+{
+       try {
+               const struct ColorMark &mark = consoleLevel.at(level);
+               std::ostringstream val;
+               val << mark.begin << std::string("[") << GetFormattedTime() << std::string("] [") <<
+                       static_cast<unsigned long>(pthread_self()) << "/" << static_cast<int>(getpid()) <<
+                       std::string("] [") << LocateSourceFileName(filename) << std::string(":") << line <<
+                       std::string("] ") << function << std::string("(): ") << message << mark.end;
+               fprintf(stdout, "%s\n", val.str().c_str());
+       } catch (const std::out_of_range &) {
+               fprintf(stdout, "Unsupported log level: %d\n", level);
+       }
+}
+
+}
+} // namespace VcoreDPL
diff --git a/src/server/include/cert-server-db.h b/src/server/include/cert-server-db.h
new file mode 100644 (file)
index 0000000..5aea447
--- /dev/null
@@ -0,0 +1,43 @@
+/**
+ * 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     cert-server-db.h
+ * @author   Kyungwook Tak (k.tak@samsung.com)
+ * @version  1.0
+ * @brief    cert-server db utils.
+ */
+
+#ifndef CERT_SERVER_DB_H_
+#define CERT_SERVER_DB_H_
+
+#include <sqlite3.h>
+#include <cert-svc/cerror.h>
+
+extern sqlite3 *cert_store_db;
+
+typedef enum schema_version_t {
+       TIZEN_2_4 =  1,
+       TIZEN_3_0 =  2
+} schema_version;
+
+int initialize_db(void);
+void deinitialize_db(void);
+int execute_insert_update_query(const char *query);
+int execute_select_query(const char *query, sqlite3_stmt **stmt);
+int get_schema_version(schema_version *version);
+int set_schema_version(schema_version version);
+
+#endif // CERT_SERVER_DB_H_
diff --git a/src/server/include/cert-server-debug.h b/src/server/include/cert-server-debug.h
new file mode 100644 (file)
index 0000000..1d91b41
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ *
+ * Copyright (c) 2000 - 2015 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ * Contact: Kidong Kim <kd0228.kim@samsung.com>
+ *
+ * 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 CERT_SERVER_DEBUG_H
+#define CERT_SERVER_DEBUG_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#ifdef LOG_TAG
+#undef LOG_TAG
+#endif
+#define LOG_TAG "CERT_SVC_SERVER"
+
+#include <dlog.h>
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // CERT_SERVER_DEBUG_H
diff --git a/src/server/include/cert-server-logic.h b/src/server/include/cert-server-logic.h
new file mode 100644 (file)
index 0000000..e0a01a5
--- /dev/null
@@ -0,0 +1,54 @@
+/**
+ * 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     cert-server-logic.h
+ * @author   Madhan A K (madhan.ak@samsung.com)
+ * @version  1.0
+ * @brief    cert-server routines.
+ */
+
+#ifndef CERT_SERVER_LOGIC_H_
+#define CERT_SERVER_LOGIC_H_
+
+int getCertificateDetailFromStore(CertStoreType storeType, CertType certType, const char *gname,
+                                                                 char *cert);
+
+int getCertificateDetailFromSystemStore(const char *gname, char *cert);
+
+int deleteCertificateFromStore(CertStoreType storeType, const char *gname);
+
+int getCertificateStatusFromStore(CertStoreType storeType, const char *gname, CertStatus *status);
+
+int setCertificateStatusToStore(CertStoreType storeType, int is_root_app, const char *gname,
+                                                               CertStatus status);
+
+int checkAliasExistsInStore(CertStoreType storeType, const char *alias, int *punique);
+
+int installCertificateToStore(CertStoreType storeType, const char *gname, const char *common_name,
+                                                         const char *private_key_gname, const char *associated_gname, const char *pCertBuffer,
+                                                         CertType certType);
+
+int getCertificateListFromStore(int reqType, CertStoreType storeType, int is_root_app,
+                                                               char **ppCertListBuffer, size_t *bufferLen, size_t *certCount);
+
+int getCertificateAliasFromStore(CertStoreType storeType, const char *gname, char *alias);
+
+int loadCertificatesFromStore(CertStoreType storeType, const char *gname, char **ppCertBlockBuffer,
+                                                         size_t *bufferLen, size_t *certBlockCount);
+
+int update_ca_certificate_file(char *cert);
+
+#endif
diff --git a/src/server/src/cert-server-db.c b/src/server/src/cert-server-db.c
new file mode 100644 (file)
index 0000000..77a3246
--- /dev/null
@@ -0,0 +1,169 @@
+/**
+ * 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     cert-server-db.c
+ * @author   Kyungwook Tak (k.tak@samsung.com)
+ * @version  1.0
+ * @brief    cert server db utils.
+ */
+
+#include <db-util.h>
+#include <cert-server-debug.h>
+#include <cert-server-db.h>
+
+sqlite3 *cert_store_db = NULL;
+
+int initialize_db(void)
+{
+       if (cert_store_db != NULL)
+               return CERTSVC_SUCCESS;
+
+       int result = db_util_open(CERTSVC_SYSTEM_STORE_DB, &cert_store_db, 0);
+       if (result != SQLITE_OK) {
+               SLOGE("opening %s failed!", CERTSVC_SYSTEM_STORE_DB);
+               cert_store_db = NULL;
+               return CERTSVC_FAIL;
+       }
+
+       return CERTSVC_SUCCESS;
+}
+
+void deinitialize_db(void)
+{
+       if (cert_store_db == NULL)
+               return;
+
+       db_util_close(cert_store_db);
+       cert_store_db = NULL;
+}
+
+int execute_insert_update_query(const char *query)
+{
+       if (!cert_store_db) {
+               SLOGE("Database not initialised.");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       if (!query) {
+               SLOGE("Query is NULL.");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       /* Begin transaction */
+       int result = sqlite3_exec(cert_store_db, "BEGIN EXCLUSIVE", NULL, NULL, NULL);
+       if (result != SQLITE_OK) {
+               SLOGE("Failed to begin transaction.");
+               return CERTSVC_FAIL;
+       }
+
+       /* Executing command */
+       result = sqlite3_exec(cert_store_db, query, NULL, NULL, NULL);
+       if (result != SQLITE_OK) {
+               SLOGE("Failed to execute query (%s).", query);
+               return CERTSVC_FAIL;
+       }
+
+       /* Committing the transaction */
+       result = sqlite3_exec(cert_store_db, "COMMIT", NULL, NULL, NULL);
+       if (result) {
+               SLOGE("Failed to commit transaction. Roll back now.");
+               result = sqlite3_exec(cert_store_db, "ROLLBACK", NULL, NULL, NULL);
+               if (result != SQLITE_OK)
+                       SLOGE("Failed to commit transaction. Roll back now.");
+
+               return CERTSVC_FAIL;
+       }
+
+       SLOGD("Transaction Commit and End.");
+
+       return CERTSVC_SUCCESS;
+}
+
+int execute_select_query(const char *query, sqlite3_stmt **stmt)
+{
+       if (!cert_store_db || !query)
+               return CERTSVC_WRONG_ARGUMENT;
+
+       sqlite3_stmt *stmts = NULL;
+       if (sqlite3_prepare_v2(cert_store_db, query, strlen(query), &stmts, NULL) != SQLITE_OK) {
+               SLOGE("sqlite3_prepare_v2 failed [%s].", query);
+               return CERTSVC_FAIL;
+       }
+
+       *stmt = stmts;
+       return CERTSVC_SUCCESS;
+}
+
+int get_schema_version(schema_version *version)
+{
+       sqlite3_stmt *stmt = NULL;
+       char *query = NULL;
+
+       query = sqlite3_mprintf("SELECT version FROM schema_info WHERE version=%d",
+                                                       TIZEN_3_0);
+
+       if (!query) {
+               SLOGE("Failed to generate query");
+               return CERTSVC_BAD_ALLOC;
+       }
+
+       int result = execute_select_query(query, &stmt);
+       if (result != CERTSVC_SUCCESS) {
+               SLOGE("Failed to get schema version.");
+               goto exit;
+       }
+
+       if (sqlite3_step(stmt) == SQLITE_ROW) {
+               SLOGI("Database version is 2(Tizen 3.0)");
+               *version = TIZEN_3_0;
+       } else {
+               SLOGW("Database should be upgrade.");
+               *version = TIZEN_2_4;
+       }
+
+exit:
+
+       if (query)
+               sqlite3_free(query);
+       if (stmt)
+               sqlite3_finalize(stmt);
+
+       return result;
+}
+
+int set_schema_version(schema_version version)
+{
+       if (version != TIZEN_3_0) {
+               SLOGE("Schema version should be set as TIZEN_3_0");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       char *query = sqlite3_mprintf("INSERT INTO schema_info (version, description)"
+                                                               "VALUES (%d, 'Tizen 3.0')", (int)version);
+       if (!query) {
+               SLOGE("Failed to generate query");
+               return CERTSVC_BAD_ALLOC;
+       }
+
+       int result = execute_insert_update_query(query);
+       if (result != CERTSVC_SUCCESS)
+               SLOGE("Insert schema version to database failed.");
+
+       if (query)
+               sqlite3_free(query);
+
+       return result;
+}
diff --git a/src/server/src/cert-server-logic.c b/src/server/src/cert-server-logic.c
new file mode 100644 (file)
index 0000000..adb07f8
--- /dev/null
@@ -0,0 +1,1587 @@
+/**
+ * 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     cert-server-logic.c
+ * @author   Madhan A K (madhan.ak@samsung.com)
+ *           Kyungwook Tak (k.tak@samsung.com)
+ * @version  1.0
+ * @brief    cert-server logic.
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <stdbool.h>
+#include <string.h>
+#include <dirent.h>
+#include <sys/smack.h>
+#include <sys/socket.h>
+
+#include <ckmc/ckmc-manager.h>
+#include <ckmc/ckmc-error.h>
+
+#include <cert-svc/cerror.h>
+#include <cert-svc/ccert.h>
+#include <vcore/Client.h>
+
+#include <cert-server-debug.h>
+#include <cert-server-logic.h>
+#include <cert-server-db.h>
+
+static CertStatus int_to_CertStatus(int intval)
+{
+       switch (intval) {
+       case 1:
+               return ENABLED;
+       case 0:
+       default:
+               return DISABLED;
+       }
+}
+
+static int CertStatus_to_int(CertStatus status)
+{
+       switch (status) {
+       case ENABLED:
+               return 1;
+       case DISABLED:
+       default:
+               return 0;
+       }
+}
+
+static const char *storetype_to_string(CertStoreType type)
+{
+       switch (type) {
+       case VPN_STORE:    return "vpn";
+       case EMAIL_STORE:  return "email";
+       case WIFI_STORE:   return "wifi";
+       case SYSTEM_STORE: return "ssl";
+       default:           return NULL;
+       }
+}
+
+static CertStoreType nextStore(CertStoreType type)
+{
+       switch (type) {
+       case NONE_STORE:   return VPN_STORE;
+       case VPN_STORE:    return WIFI_STORE;
+       case WIFI_STORE:   return EMAIL_STORE;
+       case EMAIL_STORE:  return SYSTEM_STORE;
+       case SYSTEM_STORE: return NONE_STORE;
+       default:           return NONE_STORE;
+       }
+}
+
+static bool hasStore(CertStoreType types, CertStoreType type)
+{
+       return (types & type) != 0 ? true : false;
+}
+
+char *add_shared_owner_prefix(const char *name)
+{
+       char *ckm_alias = NULL;
+       int result = asprintf(&ckm_alias, "%s%s%s", ckmc_owner_id_system, ckmc_owner_id_separator, name);
+       if (result < 0 || ckm_alias == NULL) {
+               SLOGE("Failed to allocate memory");
+               return NULL;
+       }
+
+       return ckm_alias;
+}
+
+int ckmc_remove_alias_with_shared_owner_prefix(const char *name)
+{
+       char *ckm_alias = add_shared_owner_prefix(name);
+       if (!ckm_alias) {
+               SLOGE("Failed to allocate memory");
+               return CKMC_ERROR_OUT_OF_MEMORY;
+       }
+
+       int result = ckmc_remove_alias(ckm_alias);
+
+       free(ckm_alias);
+
+       return result;
+}
+
+char *get_complete_path(const char *str1, const char *str2)
+{
+       char *result = NULL;
+       int as_result;
+
+       if (!str1 || !str2)
+               return NULL;
+
+       if (str1[strlen(str1) - 1] != '/')
+               as_result = asprintf(&result, "%s/%s", str1, str2);
+       else
+               as_result = asprintf(&result, "%s%s", str1, str2);
+
+       if (as_result < 0)
+               return NULL;
+
+       return result;
+}
+
+int add_file_to_system_cert_dir(const char *gname)
+{
+       int ret = CERTSVC_SUCCESS;
+
+       /* find certificate which filehash name is gname in root ca certs path. */
+       char *target = get_complete_path(TZ_SYS_CA_CERTS_ORIG, gname);
+       char *link = get_complete_path(TZ_SYS_CA_CERTS, gname);
+
+       if (target == NULL || link == NULL) {
+               SLOGE("Failed to get complete path.");
+               ret = CERTSVC_BAD_ALLOC;
+               goto out;
+       }
+
+       if (symlink(target, link) != 0) {
+               SLOGE("Failed to make symlink from[%s] to[%s]", target, link);
+               ret = CERTSVC_FAIL;
+               goto out;
+       }
+
+out:
+
+       free(target);
+       free(link);
+
+       return ret;
+}
+
+int del_file_from_system_cert_dir(const char *gname)
+{
+       int ret = CERTSVC_SUCCESS;
+       char *link = NULL;
+
+       link = get_complete_path(TZ_SYS_CA_CERTS, gname);
+       if (!link)   {
+               SLOGE("Failed to construct source file path.");
+               return CERTSVC_FAIL;
+       }
+
+       if (unlink(link) != 0) {
+               SLOGE("unlink %s failed. errno : %d", link, errno);
+               ret = CERTSVC_FAIL;
+               goto out;
+       }
+
+out:
+
+       free(link);
+
+       return ret;
+}
+
+int write_to_ca_cert_crt_file(const char *mode, const char *cert)
+{
+       int result = CERTSVC_SUCCESS;
+       FILE *fp = NULL;
+
+       if (cert == NULL || strlen(cert) == 0) {
+               SLOGE("Input buffer is NULL.");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       if (!(fp = fopen(TZ_SYS_CA_BUNDLE, mode))) {
+               SLOGE("Failed to open the file for writing, [%s].", TZ_SYS_CA_BUNDLE);
+               return CERTSVC_FAIL;
+       }
+
+       /* if mode of writing is to append, then goto end of file */
+       if (strcmp(mode,"ab") == 0)
+               fseek(fp, 0L, SEEK_END);
+
+       size_t cert_len = strlen(cert);
+       if (fwrite(cert, sizeof(char), cert_len, fp) != cert_len) {
+               SLOGE("Fail to write into file.");
+               result = CERTSVC_FAIL;
+               goto error;
+       }
+
+       /* adding empty line at the end */
+       fwrite("\n", sizeof(char), 1, fp);
+
+error:
+       if (fp)
+               fclose(fp);
+
+       return result;
+}
+
+int saveCertificateToStore(const char *gname, const char *cert)
+{
+       if (!gname || !cert) {
+               SLOGE("Invalid input parameter passed.");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       ckmc_policy_s cert_policy;
+       cert_policy.password = NULL;
+       cert_policy.extractable = true;
+
+       ckmc_raw_buffer_s cert_data;
+       cert_data.data = (unsigned char *)cert;
+       cert_data.size = strlen(cert);
+
+       char *ckm_alias = add_shared_owner_prefix(gname);
+       if (!ckm_alias) {
+               SLOGE("Failed to make alias. memory allocation error.");
+               return CERTSVC_BAD_ALLOC;
+       }
+
+       int result = ckmc_save_data(ckm_alias, cert_data, cert_policy);
+       free(ckm_alias);
+
+       if (result == CKMC_ERROR_DB_ALIAS_EXISTS) {
+               SLOGI("same alias with gname[%s] alrady exist in ckm. Maybe other store type have it. skip.", gname);
+               return CERTSVC_SUCCESS;
+       }
+
+       if (result != CKMC_ERROR_NONE) {
+               SLOGE("Failed to save trusted data. ckm errcode[%d]", result);
+               return CERTSVC_FAIL;
+       }
+
+       return CERTSVC_SUCCESS;
+}
+
+int saveCertificateToSystemStore(const char *gname)
+{
+       if (!gname) {
+               SLOGE("Invalid input parameter passed.");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       int result = add_file_to_system_cert_dir(gname);
+       if (result != CERTSVC_SUCCESS)
+               SLOGE("Failed to store the certificate in store.");
+
+       return result;
+}
+
+int get_certificate_buffer_from_store(CertStoreType storeType, const char *gname, char **pcert)
+{
+       int result = CERTSVC_SUCCESS;
+       int records = 0;
+       char *tempBuffer = NULL;
+       char *query = NULL;
+       sqlite3_stmt *stmt = NULL;
+
+       if (!gname) {
+               SLOGE("Invalid input parameter passed.");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       if (storeType != SYSTEM_STORE)
+               query = sqlite3_mprintf("select * from %Q where gname=%Q and enabled=%d and is_root_app_enabled=%d",
+                               storetype_to_string(storeType), gname, ENABLED, ENABLED);
+       else
+               query = sqlite3_mprintf("select certificate from ssl where gname=%Q and enabled=%d and is_root_app_enabled=%d",
+                               gname, ENABLED, ENABLED);
+
+       result = execute_select_query(query, &stmt);
+       if (result != CERTSVC_SUCCESS) {
+               SLOGE("Querying database failed.");
+               result = CERTSVC_FAIL;
+               goto error;
+       }
+
+       records = sqlite3_step(stmt);
+       if (records != SQLITE_ROW || records == SQLITE_DONE) {
+               SLOGE("No valid records found for given gname [%s].",gname);
+               result = CERTSVC_FAIL;
+               goto error;
+       }
+
+       tempBuffer = (char *)malloc(sizeof(char) * VCORE_MAX_RECV_DATA_SIZE);
+       if (!tempBuffer) {
+               SLOGE("Fail to allocate memory");
+               result = CERTSVC_FAIL;
+               goto error;
+       }
+
+       memset(tempBuffer, 0x00, VCORE_MAX_RECV_DATA_SIZE);
+
+       if (storeType == SYSTEM_STORE)
+               result = getCertificateDetailFromSystemStore(gname, tempBuffer);
+       else
+               result = getCertificateDetailFromStore(storeType, PEM_CRT, gname, tempBuffer);
+
+       if (result != CERTSVC_SUCCESS) {
+               SLOGE("Failed to set request data.");
+               result = CERTSVC_WRONG_ARGUMENT;
+               goto error;
+       }
+
+       *pcert = tempBuffer;
+
+error:
+       if (result != CERTSVC_SUCCESS)
+               free(tempBuffer);
+
+       if (query)
+               sqlite3_free(query);
+
+       if (stmt)
+               sqlite3_finalize(stmt);
+
+       return result;
+}
+
+int update_ca_certificate_file(char *cert)
+{
+       int result = CERTSVC_SUCCESS;
+       int records = 0;
+       int counter = 0;
+       char *gname = NULL;
+       char *query = NULL;
+       const char *text;
+       sqlite3_stmt *stmt = NULL;
+       CertStoreType storeType;
+
+       /*
+        * During install of a root certificate, the root certificate gets appended at
+        * the end to optimise the write operation onto ca-certificate.crt file.
+        */
+       if (cert != NULL && strlen(cert) > 0) {
+               result = write_to_ca_cert_crt_file("ab", cert);
+               if (result != CERTSVC_SUCCESS) {
+                       SLOGE("Failed to write to file. result[%d]", result);
+                       return result;
+               }
+
+               return CERTSVC_SUCCESS;
+       }
+
+       for (storeType = VPN_STORE; storeType != NONE_STORE; storeType = nextStore(storeType)) {
+               if (storeType == SYSTEM_STORE)
+                       query = sqlite3_mprintf("select certificate from ssl where enabled=%d and is_root_app_enabled=%d", ENABLED, ENABLED);
+               else
+                       query = sqlite3_mprintf("select gname from %Q where is_root_cert=%d and enabled=%d and is_root_app_enabled=%d",
+                                       storetype_to_string(storeType), ENABLED, ENABLED, ENABLED);
+
+               result = execute_select_query(query, &stmt);
+               if (query) {
+                       sqlite3_free(query);
+                       query = NULL;
+               }
+
+               if (result != CERTSVC_SUCCESS) {
+                       SLOGE("Querying database failed.");
+                       goto error_and_exit;
+               }
+
+               /* update the ca-certificate.crt file */
+               while (1) {
+                       records = sqlite3_step(stmt);
+                       if (records == SQLITE_DONE) {
+                               result = CERTSVC_SUCCESS;
+                               break;
+                       }
+
+                       if (records != SQLITE_ROW) {
+                               SLOGE("DB query error when select. result[%d].", records);
+                               result = CERTSVC_FAIL;
+                               goto error_and_exit;
+                       }
+
+                       cert = NULL;
+                       gname = NULL;
+
+                       if (storeType == SYSTEM_STORE) {
+                               text = (const char *)sqlite3_column_text(stmt, 0);
+                               if (text)
+                                       cert = strndup(text, strlen(text));
+                       } else {
+                               text = (const char *)sqlite3_column_text(stmt, 0);
+                               if (text)
+                                       gname = strndup(text, strlen(text));
+
+                               result = get_certificate_buffer_from_store(storeType, gname, &cert);
+                               if (result != CERTSVC_SUCCESS) {
+                                       SLOGE("Failed to get certificate buffer from key-manager. gname[%s]", gname);
+                                       goto error_and_exit;
+                               }
+                       }
+
+                       if (cert == NULL) {
+                               SLOGE("Failed to extract cert buffer to update ca-certificate.");
+                               result = CERTSVC_FAIL;
+                               goto error_and_exit;
+                       }
+
+                       if (counter++ == 0)
+                               result = write_to_ca_cert_crt_file("wb", cert);
+                       else
+                               result = write_to_ca_cert_crt_file("ab", cert);
+
+                       if (result != CERTSVC_SUCCESS) {
+                               SLOGE("Failed to write to file.");
+                               result = CERTSVC_FAIL;
+                               goto error_and_exit;
+                       }
+               }
+       }
+
+       SLOGD("Successfully updated ca-certificate.crt file. added cert num[%d]", counter);
+
+error_and_exit:
+       if (stmt)
+               sqlite3_finalize(stmt);
+
+       return result;
+}
+
+int enable_disable_cert_status(
+       CertStoreType storeType,
+       int is_root_app,
+       const char *gname,
+       CertStatus status)
+{
+       int result = CERTSVC_SUCCESS;
+       int records = 0;
+       char *cert = NULL;
+       char *query = NULL;
+       const char *text = NULL;
+       sqlite3_stmt *stmt = NULL;
+
+       if (status != DISABLED && status != ENABLED) {
+               SLOGE("Invalid cert status");
+               return CERTSVC_INVALID_STATUS;
+       }
+
+       query = sqlite3_mprintf("select * from %Q where gname=%Q", storetype_to_string(storeType), gname);
+       if (!query) {
+               SLOGE("Failed to generate query");
+               return CERTSVC_BAD_ALLOC;
+       }
+
+       result = execute_select_query(query, &stmt);
+       sqlite3_free(query);
+
+       if (result != CERTSVC_SUCCESS || !stmt) {
+               SLOGE("Querying database failed.");
+               return CERTSVC_FAIL;
+       }
+
+       records = sqlite3_step(stmt);
+       sqlite3_finalize(stmt);
+       stmt = NULL;
+
+       if (records != SQLITE_ROW) {
+               SLOGE("No valid records found.");
+               return CERTSVC_FAIL;
+       }
+
+       if (status == DISABLED) {
+               /* check certificate presence in disabled_certs table before inserting */
+               query = sqlite3_mprintf("select * from disabled_certs where gname=%Q", gname);
+               if (!query) {
+                       SLOGE("Failed to generate query");
+                       return CERTSVC_BAD_ALLOC;
+               }
+
+               result = execute_select_query(query, &stmt);
+               sqlite3_free(query);
+               query = NULL;
+
+               if (result != CERTSVC_SUCCESS) {
+                       SLOGE("Querying database failed.");
+                       return CERTSVC_FAIL;
+               }
+
+               records = sqlite3_step(stmt);
+               sqlite3_finalize(stmt);
+               stmt = NULL;
+
+               if (records == SQLITE_ROW) {
+                       SLOGE("Selected certificate identifier is already disabled. [%s]", gname);
+                       return CERTSVC_FAIL;
+               }
+
+               /* get certificate from keymanager*/
+               result = get_certificate_buffer_from_store(storeType, gname, &cert);
+               if (result != CERTSVC_SUCCESS) {
+                       SLOGE("Failed to get certificate buffer. result[%d]", result);
+                       return result;
+               }
+
+               /* inserting the disabled certificate to disabled_certs table */
+               query = sqlite3_mprintf("insert into disabled_certs (gname, certificate) values (%Q, %Q)", gname, cert);
+               free(cert);
+
+               if (!query) {
+                       SLOGE("Failed to generate query");
+                       return CERTSVC_BAD_ALLOC;
+               }
+
+               result = execute_insert_update_query(query);
+               sqlite3_free(query);
+
+               if (result != CERTSVC_SUCCESS) {
+                       SLOGE("Insert to database failed.");
+                       return result;
+               }
+
+               if (storeType != SYSTEM_STORE) {
+                       result = ckmc_remove_alias_with_shared_owner_prefix(gname);
+
+                       if (result != CKMC_ERROR_NONE) {
+                               SLOGE("Failed to delete certificate from key-manager. ckmc_result[%d]", result);
+                               return CERTSVC_FAIL;
+                       }
+
+               } else {
+                       result = del_file_from_system_cert_dir(gname);
+                       if (result != CERTSVC_SUCCESS) {
+                               SLOGE("Error in del_file_from_system_cert_dir. ret[%d]", result);
+                               return result;
+                       }
+               }
+       } else { /* moving the certificate to enabled state */
+               query = sqlite3_mprintf("select certificate from disabled_certs where gname=%Q", gname);
+               if (!query) {
+                       SLOGE("Failed to generate query");
+                       return CERTSVC_BAD_ALLOC;
+               }
+
+               result = execute_select_query(query, &stmt);
+               sqlite3_free(query);
+
+               if (result != CERTSVC_SUCCESS) {
+                       SLOGE("Querying database failed.");
+                       return CERTSVC_FAIL;
+               }
+
+               records = sqlite3_step(stmt);
+               if (records == SQLITE_ROW) {
+                       text = (const char *)sqlite3_column_text(stmt, 0);
+
+                       if (!text) {
+                               SLOGE("Invalid column text");
+                               sqlite3_finalize(stmt);
+                               return CERTSVC_FAIL;
+                       }
+
+                       cert = strndup(text, strlen(text));
+
+                       sqlite3_finalize(stmt);
+
+                       if (!cert) {
+                               SLOGE("Failed to allocate memory");
+                               return CERTSVC_BAD_ALLOC;
+                       }
+
+                       if (storeType == SYSTEM_STORE)
+                               result = saveCertificateToSystemStore(gname);
+                       else
+                               result = saveCertificateToStore(gname, cert);
+
+                       free(cert);
+
+                       if (result != CERTSVC_SUCCESS) {
+                               SLOGE("Failed to save certificate to key-manager. ret[%d]", result);
+                               return result;
+                       }
+
+                       query = sqlite3_mprintf("delete from disabled_certs where gname=%Q", gname);
+                       if (!query) {
+                               SLOGE("Failed to generate query");
+                               return CERTSVC_BAD_ALLOC;
+                       }
+
+                       result = execute_insert_update_query(query);
+                       sqlite3_free(query);
+
+                       if (result != CERTSVC_SUCCESS) {
+                               SLOGE("Unable to delete certificate entry from database. ret[%d]", result);
+                               return result;
+                       }
+               }
+       }
+
+       if (is_root_app == ENABLED)
+               query = sqlite3_mprintf("update %Q set is_root_app_enabled=%d , enabled=%d where gname=%Q",
+                               storetype_to_string(storeType), CertStatus_to_int(status), status, gname);
+       else
+               query = sqlite3_mprintf("update %Q set enabled=%d where gname=%Q",
+                               storetype_to_string(storeType), CertStatus_to_int(status), gname);
+
+       if (!query) {
+               SLOGE("Failed to generate query");
+               return CERTSVC_BAD_ALLOC;
+       }
+
+       result = execute_insert_update_query(query);
+       sqlite3_free(query);
+
+       if (result != CERTSVC_SUCCESS) {
+               SLOGE("Update failed. ret[%d]", result);
+               return result;
+       }
+
+       return result;
+}
+
+int setCertificateStatusToStore(
+       CertStoreType storeType,
+       int is_root_app,
+       const char *gname,
+       CertStatus status)
+{
+       if (!gname) {
+               SLOGE("Invalid input parameter passed.");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       int result = enable_disable_cert_status(storeType, is_root_app, gname, status);
+       if (result != CERTSVC_SUCCESS) {
+               SLOGE("Failed to disable certificate.");
+               return result;
+       }
+
+       SLOGD("Successfully updated the certificate status from %s to %s.",
+               (status == DISABLED) ? "ENABLED" : "DISABLED", (status == DISABLED) ? "DISABLED" : "ENABLED");
+       return CERTSVC_SUCCESS;
+}
+
+int getCertificateStatusFromStore(
+       CertStoreType storeType,
+       const char* gname,
+       CertStatus *status)
+{
+       if (!gname) {
+               SLOGE("Invalid input parameter passed.");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       char *query = sqlite3_mprintf("select gname, common_name, enabled from %Q where gname=%Q",
+                       storetype_to_string(storeType), gname);
+       if (!query) {
+               SLOGE("Failed to generate query");
+               return CERTSVC_BAD_ALLOC;
+       }
+
+       sqlite3_stmt *stmt = NULL;
+       int result = execute_select_query(query, &stmt);
+       sqlite3_free(query);
+
+       if (result != CERTSVC_SUCCESS || !stmt) {
+               SLOGE("Querying database failed.");
+               *status = DISABLED;
+               return CERTSVC_FAIL;
+       }
+
+       result = sqlite3_step(stmt);
+       if (result != SQLITE_ROW || result == SQLITE_DONE) {
+               SLOGE("No valid records found.");
+               *status = DISABLED;
+               sqlite3_finalize(stmt);
+               return CERTSVC_FAIL;
+       }
+
+       *status = int_to_CertStatus(sqlite3_column_int(stmt, 2));
+
+       sqlite3_finalize(stmt);
+
+       return CERTSVC_SUCCESS;
+}
+
+int check_alias_exist_in_database(
+       CertStoreType storeTypes,
+       const char *alias,
+       int *punique)
+{
+       char *query = NULL;
+       sqlite3_stmt *stmt = NULL;
+       int result = CERTSVC_SUCCESS;
+       CertStoreType storeType;
+       bool unique = false;
+
+       if (!alias || !punique) {
+               SLOGE("Invalid input parameter passed.");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       for (storeType = VPN_STORE; storeType < SYSTEM_STORE; storeType = nextStore(storeType)) {
+               if (!hasStore(storeTypes, storeType))
+                       continue;
+
+               query = sqlite3_mprintf("select * from %Q where common_name=%Q",
+                               storetype_to_string(storeType), alias);
+
+               if (!query) {
+                       SLOGE("Failed to generate query");
+                       return CERTSVC_BAD_ALLOC;
+               }
+
+               result = execute_select_query(query, &stmt);
+
+               sqlite3_free(query);
+               query = NULL;
+
+               if (result != CERTSVC_SUCCESS || !stmt) {
+                       SLOGE("Querying database failed. result[%d]", result);
+                       return CERTSVC_FAIL;
+               }
+
+               result = sqlite3_step(stmt);
+
+               sqlite3_finalize(stmt);
+               stmt = NULL;
+
+               if (result == SQLITE_DONE) {
+                       unique = true;
+                       break;
+               }
+       }
+
+       *punique = unique ? CERTSVC_TRUE : CERTSVC_FALSE;
+
+       return CERTSVC_SUCCESS;
+}
+
+int installCertificateToStore(
+       CertStoreType storeType,
+       const char *gname,
+       const char *common_name,
+       const char *private_key_gname,
+       const char *associated_gname,
+       const char *dataBlock,
+       CertType certType)
+{
+       if ((!gname)
+               || (certType == P12_END_USER && !common_name && !private_key_gname)
+               || (certType != P12_END_USER && !common_name && !associated_gname)) {
+               SLOGE("Invalid input parameter passed.");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       int result = CERTSVC_SUCCESS;
+
+       if (storeType != SYSTEM_STORE) {
+               result = saveCertificateToStore(gname, dataBlock);
+               if (result != CERTSVC_SUCCESS) {
+                       SLOGE("FAIL to save certificate to key-manager. result[%d]", result);
+                       return CERTSVC_FAIL;
+               }
+       }
+
+       if (certType == P12_PKEY) {
+               SLOGD("Don't save private key in store");
+               return CERTSVC_SUCCESS;
+       }
+
+       char *query = NULL;
+       if (certType == P12_END_USER && private_key_gname) {
+               query = sqlite3_mprintf("insert into %Q (gname, common_name, private_key_gname, associated_gname, enabled, is_root_app_enabled) "\
+                               "values (%Q, %Q, %Q, %Q, %d, %d)", storetype_to_string(storeType), gname, common_name, private_key_gname,
+                               gname, ENABLED, ENABLED);
+       } else if (certType == PEM_CRT || certType == P12_TRUSTED) {
+               query = sqlite3_mprintf("insert into %Q (gname, common_name, is_root_cert, associated_gname, enabled, is_root_app_enabled) values "\
+                               "(%Q, %Q, %d, %Q, %d, %d)", storetype_to_string(storeType), gname, common_name, ENABLED,
+                               associated_gname, ENABLED, ENABLED);
+       } else if (certType == P12_INTERMEDIATE) {
+               query = sqlite3_mprintf("insert into %Q (gname, common_name, associated_gname, enabled, is_root_app_enabled) values (%Q, %Q, %Q, %d, %d)",
+                               storetype_to_string(storeType), gname, common_name, associated_gname, ENABLED, ENABLED);
+       }
+
+       if (!query) {
+               SLOGE("Failed to generate query");
+               return CERTSVC_BAD_ALLOC;
+       }
+
+       result = execute_insert_update_query(query);
+       sqlite3_free(query);
+
+       if (result != CERTSVC_SUCCESS) {
+               SLOGE("Insert to database failed.");
+               return CERTSVC_FAIL;
+       }
+
+       return CERTSVC_SUCCESS;
+}
+
+int checkAliasExistsInStore(CertStoreType storeType, const char *alias, int *punique)
+{
+       if (!alias) {
+               SLOGE("Invalid input parameter passed.");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       *punique = CERTSVC_FAIL;
+       int result = check_alias_exist_in_database(storeType, alias, punique);
+       if (result != CERTSVC_SUCCESS) {
+               SLOGE("Failed to check_alias_exist_in_database. err[%d]", result);
+               return CERTSVC_FAIL;
+       }
+
+       if (*punique == CERTSVC_TRUE)
+               SLOGD("Alias (%s) does not exist in store(%d).", alias, storeType);
+       else
+               SLOGD("Alias (%s) exist in store(%d).", alias, storeType);
+
+       return CERTSVC_SUCCESS;
+}
+
+int getCertificateDetailFromStore(
+       CertStoreType storeType,
+       CertType certType,
+       const char *gname,
+       char *pOutData)
+{
+       int result = CERTSVC_SUCCESS;
+       int records = 0;
+       char *query = NULL;
+       const char *text = NULL;
+       sqlite3_stmt *stmt = NULL;
+       ckmc_raw_buffer_s *cert_data = NULL;
+
+       if (!gname || !pOutData) {
+               SLOGE("Invalid input parameter passed.");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       /* start constructing query */
+       if (certType == P12_PKEY) {
+               /* From the given certificate identifier, get the associated_gname for the certificate.
+                * Then query the database for records matching the associated_gname to get the private key */
+               query = sqlite3_mprintf("select associated_gname from %Q where gname=%Q",
+                               storetype_to_string(storeType), gname);
+               if (!query) {
+                       SLOGE("Failed to generate query");
+                       return CERTSVC_BAD_ALLOC;
+               }
+
+               result = execute_select_query(query, &stmt);
+               sqlite3_free(query);
+
+               if (result != CERTSVC_SUCCESS) {
+                       SLOGE("Querying database failed.");
+                       return result;
+               }
+
+               records = sqlite3_step(stmt);
+               if (records != SQLITE_ROW) {
+                       SLOGE("No valid records found.");
+                       sqlite3_finalize(stmt);
+                       return CERTSVC_FAIL;
+               }
+
+               text = (const char *)sqlite3_column_text(stmt, 0);
+
+               if (!text) {
+                       SLOGE("No valid column text");
+                       sqlite3_finalize(stmt);
+                       return CERTSVC_FAIL;
+               }
+
+               query = sqlite3_mprintf("select private_key_gname from %Q where gname=%Q and enabled=%d and is_root_app_enabled=%d",
+                               storetype_to_string(storeType), text, ENABLED, ENABLED);
+
+               sqlite3_finalize(stmt);
+       } else if (storeType != SYSTEM_STORE) {
+               query = sqlite3_mprintf("select * from %Q where gname=%Q and enabled=%d and is_root_app_enabled=%d",
+                               storetype_to_string(storeType), gname, ENABLED, ENABLED);
+       }
+
+       if (!query) {
+               SLOGE("Failed to generate query");
+               return CERTSVC_BAD_ALLOC;
+       }
+
+       result = execute_select_query(query, &stmt);
+       sqlite3_free(query);
+
+       if (result != CERTSVC_SUCCESS) {
+               SLOGE("Querying database failed.");
+               return result;
+       }
+
+       records = sqlite3_step(stmt);
+       if (records != SQLITE_ROW) {
+               SLOGE("No valid records found.");
+               sqlite3_finalize(stmt);
+               return CERTSVC_FAIL;
+       }
+
+       if (certType == P12_PKEY) {
+               if (!(text = (const char *)sqlite3_column_text(stmt, 0))) {
+                       SLOGE("No valid column text");
+                       sqlite3_finalize(stmt);
+                       return CERTSVC_FAIL;
+               }
+
+               gname = text;
+       }
+
+       char *ckm_alias = add_shared_owner_prefix(gname);
+       if (!ckm_alias) {
+               SLOGE("Failed to make alias. memory allocation error.");
+               return CERTSVC_BAD_ALLOC;
+       }
+
+       result = ckmc_get_data(ckm_alias, NULL, &cert_data);
+       free(ckm_alias);
+
+       sqlite3_finalize(stmt);
+
+       if (result != CKMC_ERROR_NONE) {
+               SLOGE("Failed to get certificate from key-manager. ckm ret[%d]", result);
+               return CERTSVC_FAIL;
+       }
+
+       memcpy(pOutData, cert_data->data, cert_data->size);
+       pOutData[cert_data->size] = 0;
+
+       ckmc_buffer_free(cert_data);
+
+       return CERTSVC_SUCCESS;
+}
+
+int getCertificateDetailFromSystemStore(const char *gname, char *pOutData)
+{
+       int result = CERTSVC_SUCCESS;
+       int records = 0;
+       char *query = NULL;
+       const char *text = NULL;
+       sqlite3_stmt *stmt = NULL;
+
+       if (!gname) {
+               SLOGE("Invalid input parameter passed.");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       query = sqlite3_mprintf("select certificate from ssl where gname=%Q and is_root_app_enabled=%d",
+                       gname, ENABLED, ENABLED);
+       if (!query) {
+               SLOGE("Query is NULL.");
+               return CERTSVC_FAIL;
+       }
+
+       result = execute_select_query(query, &stmt);
+       sqlite3_free(query);
+
+       if (result != CERTSVC_SUCCESS) {
+               SLOGE("Querying database failed.");
+               return result;
+       }
+
+       records = sqlite3_step(stmt);
+       if (records != SQLITE_ROW) {
+               SLOGE("No valid records found for passed gname [%s].", gname);
+               sqlite3_finalize(stmt);
+               return CERTSVC_FAIL;
+       }
+
+       text = (const char *)sqlite3_column_text(stmt, 0);
+
+       if (!text) {
+               SLOGE("Fail to sqlite3_column_text");
+               sqlite3_finalize(stmt);
+               return CERTSVC_FAIL;
+       }
+
+       size_t cert_len = strlen(text);
+       if (cert_len >= 4096) {
+               sqlite3_finalize(stmt);
+               SLOGE("certificate is too long");
+               return CERTSVC_FAIL;
+       }
+
+       memcpy(pOutData, text, cert_len);
+       pOutData[cert_len] = '\0';
+
+       sqlite3_finalize(stmt);
+
+       return CERTSVC_SUCCESS;
+}
+
+int deleteCertificateFromStore(CertStoreType storeType, const char *gname)
+{
+       int result = CERTSVC_SUCCESS;
+       int records = 0;
+       char *query = NULL;
+       char *private_key_name = NULL;
+       sqlite3_stmt *stmt = NULL;
+
+       SLOGD("Remove certificate of gname[%s] in store[%d]", gname, storeType);
+
+       if (!gname) {
+               SLOGE("Invalid input parameter passed.");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       if (storeType == SYSTEM_STORE) {
+               SLOGE("Invalid store type passed.");
+               return CERTSVC_INVALID_STORE_TYPE;
+       }
+
+       /* start constructing query */
+       query = sqlite3_mprintf("select private_key_gname from %Q where gname=%Q",
+                       storetype_to_string(storeType), gname);
+
+       result = execute_select_query(query, &stmt);
+       if (result != CERTSVC_SUCCESS) {
+               SLOGE("Querying database failed.");
+               result = CERTSVC_FAIL;
+               goto error;
+       }
+
+       records = sqlite3_step(stmt);
+       if (records != SQLITE_ROW) {
+               SLOGE("No valid records found for passed gname [%s]. result[%d].", gname, records);
+               result = CERTSVC_FAIL;
+               goto error;
+       }
+
+       /* if a cert is having private-key in it, the private key should
+        * be deleted first from key-manager, then the actual cert */
+       if (sqlite3_column_text(stmt, 0) != NULL)
+               private_key_name = strdup((const char *)sqlite3_column_text(stmt, 0));
+
+       query = sqlite3_mprintf("delete from disabled_certs where gname=%Q", gname);
+       result = execute_insert_update_query(query);
+       if (result != CERTSVC_SUCCESS) {
+               SLOGE("Unable to delete certificate entry from database. result[%d]", result);
+               goto error;
+       }
+
+       if (query) {
+               sqlite3_free(query);
+               query = NULL;
+       }
+
+       if (stmt) {
+               sqlite3_finalize(stmt);
+               stmt = NULL;
+       }
+
+       query = sqlite3_mprintf("delete from %Q where gname=%Q",
+                       storetype_to_string(storeType), gname);
+
+       result = execute_insert_update_query(query);
+       if (result != CERTSVC_SUCCESS) {
+               SLOGE("Unable to delete certificate entry from database. result[%d]", result);
+               goto error;
+       }
+
+       if (query) {
+               sqlite3_free(query);
+               query = NULL;
+       }
+
+       if (stmt) {
+               sqlite3_finalize(stmt);
+               stmt = NULL;
+       }
+
+       CertStoreType other = ALL_STORE & ~SYSTEM_STORE & ~storeType;
+       CertStoreType current;
+       int gname_exist = 0;
+       for (current = VPN_STORE; current < SYSTEM_STORE; current = nextStore(current)) {
+               if (!hasStore(other, current))
+                       continue;
+
+               query = sqlite3_mprintf("select * from %Q where gname=%Q",
+                               storetype_to_string(current), gname);
+               result = execute_select_query(query, &stmt);
+               if (result != CERTSVC_SUCCESS) {
+                       SLOGE("Querying database failed.");
+                       result = CERTSVC_FAIL;
+                       goto error;
+               }
+               records = sqlite3_step(stmt);
+               if (records == SQLITE_ROW) {
+                       SLOGI("Same gname[%s] exist on store[%d].", gname, current);
+                       gname_exist = 1;
+                       break;
+               }
+
+               sqlite3_free(query);
+               sqlite3_finalize(stmt);
+               query = NULL;
+               stmt = NULL;
+       }
+
+       if (!gname_exist) {
+               SLOGD("The gname[%s] which is in store[%d] is the last one. so remove it from ckm either.", gname, current);
+
+               if (private_key_name != NULL) {
+                       result = ckmc_remove_alias_with_shared_owner_prefix(private_key_name);
+                       if (result != CKMC_ERROR_NONE) {
+                               SLOGE("Failed to delete certificate from key-manager. ckmc_result[%d]", result);
+                               result = CERTSVC_FAIL;
+                               goto error;
+                       }
+               }
+
+               /* removing the actual cert */
+               result = ckmc_remove_alias_with_shared_owner_prefix(gname);
+               if (result != CKMC_ERROR_NONE) {
+                       SLOGE("Failed to remove data in ckm with gname[%s]. ckm_result[%d]", gname, result);
+                       result = CERTSVC_FAIL;
+                       goto error;
+               }
+       }
+
+       SLOGD("Success in deleting the certificate from store.");
+       result = CERTSVC_SUCCESS;
+
+error:
+       if (query)
+               sqlite3_free(query);
+
+       if (stmt)
+               sqlite3_finalize(stmt);
+
+       free(private_key_name);
+
+       return result;
+}
+
+static int makeCertListNode(
+       CertStoreType storeType,
+       const char *gname,
+       const char *title,
+       int statusInt,
+       CertSvcStoreCertList **out)
+{
+       CertSvcStoreCertList *node = NULL;
+       int result = CERTSVC_SUCCESS;
+       size_t gname_len = 0;
+       size_t title_len = 0;
+
+       if (out == NULL || gname == NULL || title == NULL) {
+               SLOGE("Failed to read texts from records");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       node = (CertSvcStoreCertList *)malloc(sizeof(CertSvcStoreCertList));
+       if (node == NULL) {
+               SLOGE("Failed to allocate memory.");
+               return CERTSVC_BAD_ALLOC;
+       }
+
+       gname_len = strlen(gname);
+       title_len = strlen(title);
+
+       node->gname = (char *)malloc(sizeof(char) * (gname_len + 1));
+       node->title = (char *)malloc(sizeof(char) * (title_len + 1));
+       if (node->title == NULL || node->gname == NULL) {
+               SLOGE("Failed to allocate memory");
+               result = CERTSVC_BAD_ALLOC;
+               goto error;
+       }
+
+       memcpy(node->gname, gname, gname_len);
+       memcpy(node->title, title, title_len);
+       node->gname[gname_len] = '\0';
+       node->title[title_len] = '\0';
+
+       node->storeType = storeType;
+       node->status = int_to_CertStatus(statusInt);
+       node->next = NULL;
+
+       *out = node;
+
+       return CERTSVC_SUCCESS;
+
+error:
+       if (node != NULL) {
+               free(node->gname);
+               free(node->title);
+       }
+       free(node);
+
+       return result;
+}
+
+int getCertificateListFromStore(
+       int reqType,
+       CertStoreType storeTypes,
+       int is_root_app,
+       char **certListBuffer,
+       size_t *bufferLen,
+       size_t *certCount)
+{
+       int result = CERTSVC_SUCCESS;
+       CertSvcStoreCertList *rootCertHead = NULL;
+       CertSvcStoreCertList *tmpNode = NULL;
+       CertSvcStoreCertList *currentNode = NULL;
+       sqlite3_stmt *stmt = NULL;
+       char *query = NULL;
+       int records = 0;
+       size_t count = 0;
+       size_t i = 0;
+
+       CertStoreType storeType;
+       for (storeType = VPN_STORE; storeType != NONE_STORE; storeType = nextStore(storeType)) {
+               if (!hasStore(storeTypes, storeType))
+                       continue;
+
+               SLOGD("Processing storetype [%s]", storetype_to_string(storeType));
+
+               if (reqType == CERTSVC_GET_ROOT_CERTIFICATE_LIST) {
+                       if (storeType == SYSTEM_STORE) {
+                               query = sqlite3_mprintf("select gname, common_name, enabled from %Q where enabled=%d "\
+                                               "and is_root_app_enabled=%d and order by common_name asc", "ssl", ENABLED, ENABLED);
+                       } else {
+                               query = sqlite3_mprintf("select gname, common_name, enabled from %Q where "\
+                                               "is_root_cert IS NOT NULL and is_root_app_enabled=%d and enabled=%d",
+                                               storetype_to_string(storeType), ENABLED, ENABLED);
+                       }
+               } else if (reqType == CERTSVC_GET_USER_CERTIFICATE_LIST) {
+                       if (storeType == SYSTEM_STORE) {
+                               SLOGE("Invalid store type passed.");
+                               return CERTSVC_WRONG_ARGUMENT;
+                       } else {
+                               query = sqlite3_mprintf("select gname, common_name, enabled from %Q where "\
+                                               "private_key_gname IS NOT NULL and is_root_app_enabled=%d and enabled=%d",
+                                               storetype_to_string(storeType), ENABLED, ENABLED);
+                       }
+               } else {
+                       if (is_root_app != ENABLED) {
+                       /* Gets only the list of certificates where is_root_app = 1 (which are enabled by the master application) */
+                               if (storeType == SYSTEM_STORE) {
+                                       query = sqlite3_mprintf("select gname, common_name, enabled from %Q where "\
+                                                       "is_root_app_enabled=%d order by common_name asc",
+                                                       storetype_to_string(storeType), ENABLED, ENABLED);
+                               } else {
+                                       query = sqlite3_mprintf("select gname, common_name, enabled from %Q where is_root_app_enabled=%d",
+                                                       storetype_to_string(storeType), ENABLED, ENABLED);
+                               }
+                       } else {
+                       /* Gets all the certificates from store without any restrictions */
+                               if (storeType == SYSTEM_STORE) {
+                                       query = sqlite3_mprintf("select gname, common_name, enabled from %Q order by common_name asc",
+                                                       storetype_to_string(storeType), ENABLED);
+                               } else {
+                                       query = sqlite3_mprintf("select gname, common_name, enabled from %Q",
+                                                       storetype_to_string(storeType), ENABLED);
+                               }
+                       }
+               }
+
+               result = execute_select_query(query, &stmt);
+               if (result != CERTSVC_SUCCESS) {
+                       SLOGE("Querying database failed.");
+                       result = CERTSVC_FAIL;
+                       goto error;
+               }
+
+               while ((records = sqlite3_step(stmt)) == SQLITE_ROW) {
+                       result = makeCertListNode(
+                                       storeType,
+                                       (const char *)sqlite3_column_text(stmt, 0),
+                                       (const char *)sqlite3_column_text(stmt, 1),
+                                       (int)sqlite3_column_int(stmt, 2),
+                                       &tmpNode);
+
+                       if (result != CERTSVC_SUCCESS) {
+                               SLOGE("Failed to make new cert list node. result[%d]", result);
+                               goto error;
+                       }
+
+                       if (count == 0)
+                               rootCertHead = tmpNode;
+                       else
+                               currentNode->next = tmpNode;
+
+                       currentNode = tmpNode;
+                       tmpNode = NULL;
+                       count++;
+               }
+
+               if (records != SQLITE_DONE) {
+                       SLOGE("Error in getting data from sqlite3 statement. result[%d]", records);
+                       result = CERTSVC_FAIL;
+                       goto error;
+               }
+
+               if (query) {
+                       sqlite3_free(query);
+                       query = NULL;
+               }
+
+               if (stmt) {
+                       sqlite3_finalize(stmt);
+                       stmt = NULL;
+               }
+       }
+
+       *certCount = count;
+       VcoreCertResponseData *respCertData = (VcoreCertResponseData *)malloc(count * sizeof(VcoreCertResponseData));
+       if (!respCertData) {
+               SLOGE("Failed to allocate memory");
+               result = CERTSVC_BAD_ALLOC;
+               goto error;
+       }
+       if (count > 0)
+               memset(respCertData, 0x00, count * sizeof(VcoreCertResponseData));
+       VcoreCertResponseData* currRespCertData = NULL;
+
+       currentNode = rootCertHead;
+       for (i = 0; i < count; i++) {
+          tmpNode = currentNode->next;
+
+          currRespCertData = respCertData + i;
+          if (strlen(currentNode->gname) > sizeof(currRespCertData->gname)
+                  || strlen(currentNode->title) > sizeof(currRespCertData->title)) {
+                  SLOGE("String is too long. [%s], [%s]", currentNode->gname, currentNode->title);
+                  result = CERTSVC_FAIL;
+                  *certListBuffer = NULL;
+                  free(respCertData);
+                  goto error;
+          }
+          strncpy(currRespCertData->gname, currentNode->gname, strlen(currentNode->gname));
+          strncpy(currRespCertData->title, currentNode->title, strlen(currentNode->title));
+          currRespCertData->status = currentNode->status;
+          currRespCertData->storeType = currentNode->storeType;
+
+          currentNode = tmpNode;
+       }
+
+       *certListBuffer = (char *) respCertData;
+       *bufferLen = count * sizeof(VcoreCertResponseData);
+
+       SLOGD("Success to create certificate list. cert_count=%d", count);
+       result = CERTSVC_SUCCESS;
+
+error:
+       if (query)
+               sqlite3_free(query);
+
+       if (stmt)
+               sqlite3_finalize(stmt);
+
+       if (rootCertHead) {
+               currentNode = rootCertHead;
+               while (currentNode) {
+                       tmpNode = currentNode->next;
+                       free(currentNode->title);
+                       free(currentNode->gname);
+                       free(currentNode);
+                       currentNode = tmpNode;
+               }
+       }
+
+       return result;
+}
+
+int getCertificateAliasFromStore(CertStoreType storeType, const char *gname, char *alias)
+{
+       int result = CERTSVC_SUCCESS;
+       int records = 0;
+       sqlite3_stmt *stmt = NULL;
+       char *query = NULL;
+       const char *text = NULL;
+
+       query = sqlite3_mprintf("select common_name from %Q where gname=%Q",
+                       storetype_to_string(storeType), gname);
+
+       result = execute_select_query(query, &stmt);
+       if (result != CERTSVC_SUCCESS) {
+               SLOGE("Querying database failed.");
+               result = CERTSVC_FAIL;
+               goto error;
+       }
+
+       records = sqlite3_step(stmt);
+       if (records != SQLITE_ROW || records == SQLITE_DONE) {
+               SLOGE("No valid records found for gname passed [%s].",gname);
+               result = CERTSVC_FAIL;
+               goto error;
+       }
+
+       if (!(text = (const char *)sqlite3_column_text(stmt, 0))) {
+               SLOGE("No column text in returned records");
+               result = CERTSVC_FAIL;
+               goto error;
+       }
+
+       strncpy(alias, text, strlen(text));
+
+       if (strlen(alias) == 0) {
+               SLOGE("Unable to get the alias name for the gname passed.");
+               result = CERTSVC_FAIL;
+               goto error;
+       }
+
+       result = CERTSVC_SUCCESS;
+
+       SLOGD("success : getCertificateAliasFromStore");
+error:
+       if (query)
+               sqlite3_free(query);
+
+       if (stmt)
+               sqlite3_finalize(stmt);
+
+       return result;
+}
+
+int loadCertificatesFromStore(
+       CertStoreType storeType,
+       const char* gname,
+       char **ppCertBlockBuffer,
+       size_t *bufferLen,
+       size_t *certBlockCount)
+{
+       int result = CERTSVC_SUCCESS;
+       size_t count = 0;
+       int records = 0;
+       sqlite3_stmt *stmt = NULL;
+       char *query = NULL;
+       char **certs = NULL;
+       const char *tmpText = NULL;
+       size_t i = 0;
+
+       query = sqlite3_mprintf("select associated_gname from %Q where gname=%Q",
+                       storetype_to_string(storeType), gname);
+
+       result = execute_select_query(query, &stmt);
+       if (result != CERTSVC_SUCCESS) {
+               SLOGE("Querying database failed.");
+               result = CERTSVC_FAIL;
+               goto error;
+       }
+
+       records = sqlite3_step(stmt);
+       if (records != SQLITE_ROW || records == SQLITE_DONE) {
+               SLOGE("No valid records found for gname passed [%s].",gname);
+               result = CERTSVC_FAIL;
+               goto error;
+       }
+
+
+       if (records == SQLITE_ROW) {
+               if (query)
+                       sqlite3_free(query);
+
+               const char *columnText = (const char *)sqlite3_column_text(stmt, 0);
+               if (!columnText) {
+                       SLOGE("Failed to sqlite3_column_text");
+                       result = CERTSVC_FAIL;
+                       goto error;
+               }
+
+               query = sqlite3_mprintf("select gname from %Q where associated_gname=%Q and enabled=%d and is_root_app_enabled=%d",
+                               storetype_to_string(storeType), columnText, ENABLED, ENABLED);
+
+               if (stmt)
+                       sqlite3_finalize(stmt);
+
+               result = execute_select_query(query, &stmt);
+               if (result != CERTSVC_SUCCESS) {
+                       SLOGE("Querying database failed.");
+                       result = CERTSVC_FAIL;
+                       goto error;
+               }
+
+               while (1) {
+                       records = sqlite3_step(stmt);
+                       if (records != SQLITE_ROW || records == SQLITE_DONE)
+                               break;
+
+                       if (count == 0) {
+                               certs = (char**) malloc(4 * sizeof(char *));
+                               if (!certs) {
+                                       SLOGE("Failed to allocate memory");
+                                       result = CERTSVC_BAD_ALLOC;
+                                       goto error;
+                               }
+                               memset(certs, 0x00, 4 * sizeof(char *));
+                       }
+
+                       if (records == SQLITE_ROW) {
+                               tmpText = (const char *)sqlite3_column_text(stmt, 0);
+                               if (!tmpText) {
+                                       SLOGE("Failed to sqlite3_column_text.");
+                                       result = CERTSVC_FAIL;
+                                       goto error;
+                               }
+
+                               if (!((certs)[count] = strdup(tmpText))) {
+                                       SLOGE("Failed to allocate memory");
+                                       result = CERTSVC_BAD_ALLOC;
+                                       goto error;
+                               }
+                       }
+
+                       count++;
+               }
+
+               if (count == 0) {
+                       SLOGE("No valid records found for the gname passed [%s].",gname);
+                       return CERTSVC_FAIL;
+               }
+       }
+
+       *certBlockCount = count;
+       *bufferLen = count * sizeof(ResponseCertBlock);
+       ResponseCertBlock *certBlockList = (ResponseCertBlock *) malloc(*bufferLen);
+       if (!certBlockList) {
+               SLOGE("Failed to allocate memory for ResponseCertBlock");
+               result = CERTSVC_BAD_ALLOC;
+               goto error;
+       }
+
+       if (count > 0)
+               memset(certBlockList, 0x00, *bufferLen);
+
+       ResponseCertBlock *currentBlock = NULL;
+       for (i = 0; i < count; i++) {
+               currentBlock = certBlockList + i;
+               if (sizeof(currentBlock->dataBlock) < strlen(certs[i])) {
+                       SLOGE("src is longer than dst. src[%s] dst size[%d]", certs[i], sizeof(currentBlock->dataBlock));
+                       free(certBlockList);
+                       result = CERTSVC_FAIL;
+                       goto error;
+               }
+               strncpy(currentBlock->dataBlock, certs[i], strlen(certs[i]));
+               currentBlock->dataBlockLen = strlen(certs[i]);
+       }
+       *ppCertBlockBuffer = (char *)certBlockList;
+
+       result = CERTSVC_SUCCESS;
+
+       SLOGD("success: loadCertificatesFromStore. CERT_COUNT=%d", count);
+
+error:
+       if (query)
+               sqlite3_free(query);
+
+       if (stmt)
+               sqlite3_finalize(stmt);
+
+       if (certs) {
+               for(i = 0; i < count; i++)
+                       free(certs[i]);
+
+               free(certs);
+       }
+
+       return result;
+}
diff --git a/src/server/src/cert-server-main.c b/src/server/src/cert-server-main.c
new file mode 100644 (file)
index 0000000..80dc700
--- /dev/null
@@ -0,0 +1,348 @@
+/**
+ * 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     cert-server-main.c
+ * @author   Madhan A K (madhan.ak@samsung.com)
+ *           Kyungwook Tak (k.tak@samsung.com)
+ * @version  1.0
+ * @brief    cert-svc server.
+ */
+
+#include <stdlib.h>
+#include <signal.h>
+#include <unistd.h>
+#include <errno.h>
+#include <sys/un.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <sys/socket.h>
+#include <sys/time.h>
+#include <sys/select.h>
+#include <systemd/sd-daemon.h>
+
+#include <cert-svc/cerror.h>
+#include <cert-svc/ccert.h>
+#include <vcore/Client.h>
+
+#include <cert-server-debug.h>
+#include <cert-server-logic.h>
+#include <cert-server-db.h>
+
+void CertSigHandler(int signo)
+{
+       SLOGD("Got Signal %d, exiting now.", signo);
+
+       deinitialize_db();
+
+       exit(1);
+}
+
+int CertSvcGetSocketFromSystemd(int *pSockfd)
+{
+       int n = sd_listen_fds(0);
+       int fd;
+
+       for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START+n; ++fd) {
+               if (0 < sd_is_socket_unix(fd, SOCK_STREAM, 1, VCORE_SOCK_PATH, 0)) {
+                       LOGD("Get socket from systemd. fd[%d]", fd);
+                       *pSockfd = fd;
+                       return CERTSVC_SUCCESS;
+               }
+       }
+
+       return CERTSVC_FAIL;
+}
+
+void CertSvcServerComm(void)
+{
+       int server_sockfd = 0;
+       int client_sockfd = 0;
+       int read_len = 0;
+       int client_len = 0;
+       struct sockaddr_un clientaddr;
+       int result = CERTSVC_SUCCESS;
+       char *certListBuffer = NULL;
+       char *certBlockBuffer = NULL;
+       size_t bufferLen = 0;
+       size_t blockBufferLen = 0;
+
+       struct timeval timeout;
+       timeout.tv_sec = 10;
+       timeout.tv_usec = 0;
+
+       SLOGI("cert-server is starting...");
+
+       VcoreRequestData recv_data;
+       VcoreResponseData send_data;
+
+       if (CertSvcGetSocketFromSystemd(&server_sockfd) != CERTSVC_SUCCESS) {
+               SLOGE("Failed to get sockfd from systemd.");
+               return;
+       }
+
+       client_len = sizeof(clientaddr);
+       signal(SIGINT, (void*)CertSigHandler);
+
+       result = initialize_db();
+       if (result != CERTSVC_SUCCESS) {
+               SLOGE("Failed to initialize database.");
+               result = CERTSVC_IO_ERROR;
+               goto Error_close_exit;
+       }
+
+       // check schema version for consistent on platform upgrade
+       SLOGI("Start to check schema version.");
+       schema_version version;
+       result = get_schema_version(&version);
+       if (result != CERTSVC_SUCCESS) {
+               SLOGE("Failed to check schema version.");
+               result = CERTSVC_IO_ERROR;
+               goto Error_close_exit;
+       }
+
+       if (version != TIZEN_3_0) {
+               SLOGI("Start to update schema version and bundle.");
+               // remake bundle according to new DB
+               result = update_ca_certificate_file(NULL);
+               if (result != CERTSVC_SUCCESS) {
+                       SLOGE("Failed to migrate bundle.");
+                       result = CERTSVC_IO_ERROR;
+                       goto Error_close_exit;
+               }
+
+               // set DB schema version to TIZEN_3_O
+               set_schema_version(TIZEN_3_0);
+       }
+       SLOGI("Finish checking DB schema version.");
+
+       fd_set fd;
+       struct timeval tv;
+       while (1) {
+               errno = 0;
+
+               FD_ZERO(&fd);
+               FD_SET(server_sockfd, &fd);
+
+               tv.tv_sec = 10;
+               tv.tv_usec = 0;
+
+               memset(&recv_data, 0x00, sizeof(VcoreRequestData));
+               memset(&send_data, 0x00, sizeof(VcoreResponseData));
+
+               int ret = select(server_sockfd + 1, &fd, NULL, NULL, &tv);
+               if (ret == 0) { // timeout
+                       SLOGD("cert-server timeout. exit.");
+                       break;
+               }
+
+               if (ret == -1) {
+                       SLOGE("select() error.");
+                       break;
+               }
+
+               if ((client_sockfd = accept(server_sockfd, (struct sockaddr*)&clientaddr, (socklen_t*)&client_len)) < 0) {
+                       SLOGE("Error in function accept().[socket desc :%d, error no :%d].", client_sockfd, errno);
+                       continue;
+               }
+
+               SLOGD("cert-server Accept! client sock[%d]", client_sockfd);
+
+               if (setsockopt(client_sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)) < 0) {
+                       SLOGE("Error in Set SO_RCVTIMEO Socket Option");
+                       send_data.result = CERTSVC_FAIL;
+                       goto Error_close_exit;
+               }
+
+               if (setsockopt(client_sockfd, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(timeout)) < 0) {
+                       SLOGE("Error in Set SO_SNDTIMEO Socket Option");
+                       send_data.result = CERTSVC_FAIL;
+                       goto Error_close_exit;
+               }
+
+               SLOGD("Connected to a client...");
+
+               read_len = recv(client_sockfd, (char*)&recv_data, sizeof(recv_data), 0);
+               if (read_len < 0) {
+                       SLOGE("Error in function recv().");
+                       send_data.result = CERTSVC_FAIL;
+                       goto Error_close_exit;
+               }
+
+               SLOGD("revc request: reqType=%d", recv_data.reqType);
+
+               switch (recv_data.reqType) {
+               case CERTSVC_EXTRACT_CERT:
+               {
+                       send_data.result = getCertificateDetailFromStore(
+                                       recv_data.storeType,
+                                       recv_data.certType,
+                                       recv_data.gname,
+                                       send_data.dataBlock);
+                       send_data.dataBlockLen = strlen(send_data.dataBlock);
+                       result = send(client_sockfd, (char*)&send_data, sizeof(send_data), 0);
+                       break;
+               }
+
+               case CERTSVC_EXTRACT_SYSTEM_CERT:
+               {
+                       send_data.result = getCertificateDetailFromSystemStore(
+                                       recv_data.gname,
+                                       send_data.dataBlock);
+                       send_data.dataBlockLen = strlen(send_data.dataBlock);
+                       result = send(client_sockfd, (char*)&send_data, sizeof(send_data), 0);
+                       break;
+               }
+
+               case CERTSVC_DELETE_CERT:
+               {
+                       send_data.result = deleteCertificateFromStore(
+                                       recv_data.storeType,
+                                       recv_data.gname);
+                       if (send_data.result == CERTSVC_SUCCESS)
+                               send_data.result = update_ca_certificate_file(NULL);
+                       result = send(client_sockfd, (char*)&send_data, sizeof(send_data), 0);
+                       break;
+               }
+
+               case CERTSVC_GET_CERTIFICATE_STATUS:
+               {
+                       send_data.result = getCertificateStatusFromStore(
+                                       recv_data.storeType,
+                                       recv_data.gname,
+                                       &send_data.certStatus);
+                       result = send(client_sockfd, (char*)&send_data, sizeof(send_data), 0);
+                       break;
+               }
+
+               case CERTSVC_SET_CERTIFICATE_STATUS:
+               {
+                       send_data.result = setCertificateStatusToStore(
+                                       recv_data.storeType,
+                                       recv_data.is_root_app,
+                                       recv_data.gname,
+                                       recv_data.certStatus);
+                       if (send_data.result == CERTSVC_SUCCESS)
+                               send_data.result = update_ca_certificate_file(NULL);
+                       result = send(client_sockfd, (char*)&send_data, sizeof(send_data), 0);
+                       break;
+               }
+
+               case CERTSVC_CHECK_ALIAS_EXISTS:
+               {
+                       send_data.result = checkAliasExistsInStore(
+                                       recv_data.storeType,
+                                       recv_data.gname,
+                                       &send_data.isAliasUnique);
+                       result = send(client_sockfd, (char*)&send_data, sizeof(send_data), 0);
+                       break;
+               }
+
+               case CERTSVC_INSTALL_CERTIFICATE:
+               {
+                       send_data.result = installCertificateToStore(
+                                       recv_data.storeType,
+                                       recv_data.gname,
+                                       recv_data.common_name,
+                                       recv_data.private_key_gname,
+                                       recv_data.associated_gname,
+                                       recv_data.dataBlock,
+                                       recv_data.certType);
+
+                       if (send_data.result == CERTSVC_SUCCESS && (recv_data.certType == PEM_CRT || recv_data.certType == P12_TRUSTED))
+                               send_data.result = update_ca_certificate_file(recv_data.dataBlock);
+                       result = send(client_sockfd, (char*)&send_data, sizeof(send_data), 0);
+                       break;
+               }
+
+               case CERTSVC_GET_CERTIFICATE_LIST:
+               case CERTSVC_GET_USER_CERTIFICATE_LIST:
+               case CERTSVC_GET_ROOT_CERTIFICATE_LIST:
+               {
+                       send_data.result = getCertificateListFromStore(
+                                       recv_data.reqType,
+                                       recv_data.storeType,
+                                       recv_data.is_root_app,
+                                       &certListBuffer,
+                                       &bufferLen,
+                                       &send_data.certCount);
+                       result = send(client_sockfd, (char*)&send_data, sizeof(send_data), 0);
+                       if (bufferLen > 0)
+                               result = send(client_sockfd, certListBuffer, bufferLen, 0);
+                       break;
+               }
+
+               case CERTSVC_GET_CERTIFICATE_ALIAS:
+               {
+                       send_data.result = getCertificateAliasFromStore(
+                                       recv_data.storeType,
+                                       recv_data.gname,
+                                       send_data.common_name);
+                       result = send(client_sockfd, (char*)&send_data, sizeof(send_data), 0);
+                       break;
+               }
+
+               case CERTSVC_LOAD_CERTIFICATES:
+               {
+                       send_data.result = loadCertificatesFromStore(
+                                       recv_data.storeType,
+                                       recv_data.gname,
+                                       &certBlockBuffer,
+                                       &blockBufferLen,
+                                       &send_data.certBlockCount);
+                       result = send(client_sockfd, (char*)&send_data, sizeof(send_data), 0);
+                       if (blockBufferLen > 0)
+                               result = send(client_sockfd, certBlockBuffer, blockBufferLen, 0);
+                       break;
+               }
+
+               default:
+                       SLOGE("Input error. Please check request type");
+                       break;
+               }
+
+               if (result <= 0)
+                       SLOGE("send failed :%d, errno %d try once", result, errno);
+       }
+
+Error_close_exit:
+       close(server_sockfd);
+
+       deinitialize_db();
+
+       free(certListBuffer);
+       free(certBlockBuffer);
+
+       if (client_sockfd >= 0) {
+               result = send(client_sockfd, (char*)&send_data, sizeof(send_data), 0);
+               if (result <= 0)
+                       SLOGE("send failed :%d, errno %d try once", result, errno);
+
+               close(client_sockfd);
+       } else {
+               SLOGE("cannot connect to client socket.");
+       }
+
+       SLOGI("CertSvcServerComm done.");
+}
+
+int main(void)
+{
+       SLOGI("cert-server start");
+       CertSvcServerComm();
+       SLOGI("cert-server end");
+
+       return 0;
+}
diff --git a/src/vcore/Base64.cpp b/src/vcore/Base64.cpp
new file mode 100644 (file)
index 0000000..e3b85ef
--- /dev/null
@@ -0,0 +1,229 @@
+/*
+ * Copyright (c) 2011 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.
+ */
+#include <algorithm>
+#include <string>
+#include <memory>
+#include <string.h>
+#include <openssl/bio.h>
+#include <openssl/evp.h>
+#include <openssl/buffer.h>
+
+#include <dpl/log/log.h>
+
+#include <vcore/Base64.h>
+
+namespace ValidationCore {
+Base64Encoder::Base64Encoder() :
+       m_b64(0),
+       m_bmem(0),
+       m_finalized(false)
+{
+}
+
+void Base64Encoder::append(const std::string &data)
+{
+       if (m_finalized) {
+               LogWarning("Already finalized.");
+               VcoreThrowMsg(Exception::AlreadyFinalized, "Already finalized");
+       }
+
+       if (!m_b64) {
+               reset();
+       }
+
+       BIO_write(m_b64, data.c_str(), data.size());
+}
+
+void Base64Encoder::finalize()
+{
+       if (m_finalized) {
+               LogWarning("Already finalized.");
+               VcoreThrowMsg(Exception::AlreadyFinalized, "Already finalized.");
+       }
+
+       m_finalized = true;
+
+       if (BIO_flush(m_b64) != 1)
+               VcoreThrowMsg(Exception::InternalError, "Bio internal error");
+}
+
+std::string Base64Encoder::get()
+{
+       if (!m_finalized) {
+               LogWarning("Not finalized");
+               VcoreThrowMsg(Exception::NotFinalized, "Not finalized");
+       }
+
+       BUF_MEM *bptr = 0;
+       BIO_get_mem_ptr(m_b64, &bptr);
+
+       if (bptr == 0) {
+               LogError("Bio internal error");
+               VcoreThrowMsg(Exception::InternalError, "Bio internal error");
+       }
+
+       if (bptr->length > 0) {
+               return std::string(bptr->data, bptr->length);
+       }
+
+       return std::string();
+}
+
+void Base64Encoder::reset()
+{
+       m_finalized = false;
+       BIO_free_all(m_b64);
+       m_b64 = BIO_new(BIO_f_base64());
+       m_bmem = BIO_new(BIO_s_mem());
+
+       if (!m_b64 || !m_bmem) {
+               LogError("Error during allocation memory in BIO");
+               VcoreThrowMsg(Exception::InternalError,
+                                         "Error during allocation memory in BIO");
+       }
+
+       BIO_set_flags(m_b64, BIO_FLAGS_BASE64_NO_NL);
+       m_b64 = BIO_push(m_b64, m_bmem);
+}
+
+Base64Encoder::~Base64Encoder()
+{
+       BIO_free_all(m_b64);
+}
+
+Base64Decoder::Base64Decoder() :
+       m_finalized(false)
+{
+}
+
+void Base64Decoder::append(const std::string &data)
+{
+       if (m_finalized) {
+               LogWarning("Already finalized.");
+               VcoreThrowMsg(Exception::AlreadyFinalized, "Already finalized.");
+       }
+
+       m_input.append(data);
+}
+
+static bool whiteCharacter(char a)
+{
+       if (a == '\n')
+               return true;
+
+       return false;
+}
+
+bool Base64Decoder::finalize()
+{
+       if (m_finalized) {
+               LogWarning("Already finalized.");
+               VcoreThrowMsg(Exception::AlreadyFinalized, "Already finalized.");
+       }
+
+       m_finalized = true;
+       m_input.erase(std::remove_if(m_input.begin(),
+                                                                m_input.end(),
+                                                                whiteCharacter),
+                                 m_input.end());
+
+       for (size_t i = 0; i < m_input.size(); ++i) {
+               if (isalnum(m_input[i])
+                               || m_input[i] == '+'
+                               || m_input[i] == '/'
+                               || m_input[i] == '=')
+                       continue;
+
+               LogError("Base64 input contains illegal chars: " << m_input[i]);
+               return false;
+       }
+
+       BIO *b64, *bmem;
+       size_t len = m_input.size();
+       std::shared_ptr<char> buffer(new char[len], [](char *p) {
+               delete []p;
+       });
+
+       if (!buffer.get()) {
+               LogError("Error in new");
+               VcoreThrowMsg(Exception::InternalError, "Error in new");
+       }
+
+       memset(buffer.get(), 0, len);
+       b64 = BIO_new(BIO_f_base64());
+
+       if (!b64) {
+               LogError("Couldn't create BIO object.");
+               VcoreThrowMsg(Exception::InternalError, "Couldn't create BIO object.");
+       }
+
+       BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
+       std::shared_ptr<char> tmp(strdup(m_input.c_str()), [](char *p) {
+               free(p);
+       });
+
+       if (!tmp.get()) {
+               LogError("Error in strdup");
+               VcoreThrowMsg(Exception::InternalError, "Error in strdup");
+       }
+
+       m_input.clear();
+       bmem = BIO_new_mem_buf(tmp.get(), len);
+
+       if (!bmem) {
+               BIO_free(b64);
+               LogError("Internal error in BIO");
+               VcoreThrowMsg(Exception::InternalError, "Internal error in BIO");
+       }
+
+       bmem = BIO_push(b64, bmem);
+
+       if (!bmem) {
+               BIO_free(b64);
+               LogError("Internal error in BIO");
+               VcoreThrowMsg(Exception::InternalError, "Internal error in BIO");
+       }
+
+       int readlen = BIO_read(bmem, buffer.get(), len);
+       m_output.clear();
+       bool status = true;
+
+       if (readlen > 0)
+               m_output.append(buffer.get(), readlen);
+       else
+               status = false;
+
+       BIO_free_all(bmem);
+       return status;
+}
+
+std::string Base64Decoder::get() const
+{
+       if (!m_finalized) {
+               LogWarning("Not finalized.");
+               VcoreThrowMsg(Exception::NotFinalized, "Not finalized");
+       }
+
+       return m_output;
+}
+
+void Base64Decoder::reset()
+{
+       m_finalized = false;
+       m_input.clear();
+       m_output.clear();
+}
+} // namespace ValidationCore
diff --git a/src/vcore/Base64.h b/src/vcore/Base64.h
new file mode 100644 (file)
index 0000000..d8f3817
--- /dev/null
@@ -0,0 +1,82 @@
+/*
+ * Copyright (c) 2011 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.
+ */
+#ifndef _BASE64_H_
+#define _BASE64_H_
+
+#include <string>
+#include <vcore/exception.h>
+
+struct bio_st;
+typedef bio_st BIO;
+
+namespace ValidationCore {
+class Base64Encoder {
+public:
+       class Exception {
+       public:
+               VCORE_DECLARE_EXCEPTION_TYPE(ValidationCore::Exception, Base)
+               VCORE_DECLARE_EXCEPTION_TYPE(Base, InternalError)
+               VCORE_DECLARE_EXCEPTION_TYPE(Base, NotFinalized)
+               VCORE_DECLARE_EXCEPTION_TYPE(Base, AlreadyFinalized)
+       };
+       Base64Encoder();
+       void append(const std::string &data);
+       void finalize();
+       std::string get();
+       void reset();
+       ~Base64Encoder();
+
+private:
+       Base64Encoder(const Base64Encoder &);
+       const Base64Encoder &operator=(const Base64Encoder &);
+
+       BIO *m_b64;
+       BIO *m_bmem;
+       bool m_finalized;
+};
+
+class Base64Decoder {
+public:
+       class Exception {
+       public:
+               VCORE_DECLARE_EXCEPTION_TYPE(ValidationCore::Exception, Base)
+               VCORE_DECLARE_EXCEPTION_TYPE(Base, InternalError)
+               VCORE_DECLARE_EXCEPTION_TYPE(Base, NotFinalized)
+               VCORE_DECLARE_EXCEPTION_TYPE(Base, AlreadyFinalized)
+       };
+       Base64Decoder();
+       void append(const std::string &data);
+
+       /*
+        *  Function will return false when BIO_read fails
+        *  (for example: when string was not in base64 format).
+        */
+       bool finalize();
+       std::string get() const;
+       void reset();
+       ~Base64Decoder() {}
+
+private:
+       Base64Decoder(const Base64Decoder &);
+       const Base64Decoder &operator=(const Base64Decoder &);
+
+       std::string m_input;
+       std::string m_output;
+       bool m_finalized;
+};
+} // namespace ValidationCore
+
+#endif
diff --git a/src/vcore/CertStoreType.cpp b/src/vcore/CertStoreType.cpp
new file mode 100644 (file)
index 0000000..dbabf21
--- /dev/null
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) 2011 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.
+ */
+/*
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @file        CertStoreType.cpp
+ * @version     1.0
+ * @brief       Identification of certificate domain. Certificate domains
+ *              were defined in WAC 1.0 documentation. This is a part
+ *              should be implemented in wrt-installer.
+ */
+#include <vcore/CertStoreType.h>
+
+namespace ValidationCore {
+namespace CertStoreId {
+
+Set::Set()
+       : m_certificateStorage(0)
+{}
+
+Set::~Set()
+{
+}
+
+void Set::add(Type second)
+{
+       m_certificateStorage |= second;
+}
+
+bool Set::contains(Type second) const
+{
+       return static_cast<bool>(m_certificateStorage & second);
+}
+
+bool Set::isContainsVis() const
+{
+       Type visType = VIS_PUBLIC;
+       visType |= VIS_PARTNER;
+       visType |= VIS_PLATFORM;
+       visType &= m_certificateStorage;
+
+       if (visType == 0)
+               return false;
+
+       return true;
+}
+
+bool Set::isEmpty() const
+{
+       return m_certificateStorage == 0;
+}
+
+std::string Set::typeToString() const
+{
+       std::string ret;
+
+       if (m_certificateStorage & TIZEN_DEVELOPER)
+               ret += "TIZEN_DEVELOPER ";
+
+       if (m_certificateStorage & TIZEN_TEST)
+               ret += "TIZEN_TEST ";
+
+       if (m_certificateStorage & TIZEN_VERIFY)
+               ret += "TIZEN_VERIFY ";
+
+       if (m_certificateStorage & TIZEN_STORE)
+               ret += "TIZEN_STORE ";
+
+       if (m_certificateStorage & TIZEN_REVOKED)
+               ret += "TIZEN_REVOKED ";
+
+       if (m_certificateStorage & VIS_PUBLIC)
+               ret += "VIS_PUBLIC ";
+
+       if (m_certificateStorage & VIS_PARTNER)
+               ret += "VIS_PARTNER ";
+
+       if (m_certificateStorage & VIS_PLATFORM)
+               ret += "VIS_PLATFORM ";
+
+       return ret;
+}
+
+} // namespace CertStoreId
+} // namespace ValidationCore
diff --git a/src/vcore/CertStoreType.h b/src/vcore/CertStoreType.h
new file mode 100644 (file)
index 0000000..ea01f7b
--- /dev/null
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 2011 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.
+ */
+/*
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @file        CertStoreType.h
+ * @version     1.0
+ * @brief       Identification of certificate domain. Certificate domains
+ *              were defined in WAC 1.0 documentation. This is a part
+ *              should be implemented in wrt-installer.
+ */
+#ifndef _VALIDATION_CORE_CERTSTORETYPE_H_
+#define _VALIDATION_CORE_CERTSTORETYPE_H_
+
+#include <string>
+
+namespace ValidationCore {
+namespace CertStoreId {
+typedef unsigned int Type;
+
+// RootCA certificates for developer mode.
+const Type TIZEN_DEVELOPER = 1;
+// RootCA certificates for author signatures.
+const Type TIZEN_TEST = 1 << 1;
+const Type TIZEN_VERIFY = 1 << 2;
+const Type TIZEN_STORE = 1 << 3;
+const Type TIZEN_REVOKED = 1 << 4;
+// RootCA's visibility level : public
+const Type VIS_PUBLIC = 1 << 6;
+// RootCA's visibility level : partner
+const Type VIS_PARTNER = 1 << 7;
+// RootCA's visibility level : platform
+const Type VIS_PLATFORM = 1 << 10;
+
+class Set {
+public:
+       Set();
+       virtual ~Set();
+
+       void add(Type second);
+       bool contains(Type second) const;
+       bool isContainsVis() const;
+       bool isEmpty() const;
+
+       std::string typeToString() const;
+
+private:
+       Type m_certificateStorage;
+};
+
+} // namespace CertStoreId
+} // namespace ValidationCore
+
+#endif //  _VALIDATION_CORE_CERTSTORETYPE_H_
diff --git a/src/vcore/Certificate.cpp b/src/vcore/Certificate.cpp
new file mode 100644 (file)
index 0000000..d2c5c01
--- /dev/null
@@ -0,0 +1,680 @@
+/*
+ * 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        Certificate.cpp
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       Certificate class implementation
+ */
+
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#include <cstdio>
+#include <memory>
+#include <iomanip>
+
+#include <openssl/pem.h>
+#include <openssl/x509.h>
+#include <openssl/x509v3.h>
+#include <openssl/objects.h>
+
+#include <dpl/log/log.h>
+
+#include "vcore/Base64.h"
+#include "vcore/TimeConversion.h"
+
+#include "vcore/Certificate.h"
+
+namespace {
+
+typedef std::unique_ptr<X509, std::function<void(X509 *)>> ScopedX509;
+typedef std::unique_ptr<FILE, std::function<int(FILE *)>> ScopedFile;
+
+} // namespace anonymous
+
+namespace ValidationCore {
+
+Certificate::Certificate(X509 *cert)
+{
+       if (cert == NULL)
+               VcoreThrowMsg(Certificate::Exception::WrongParamError,
+                                         "Input X509 shouldn't be NULL.");
+
+       m_x509 = X509_dup(cert);
+
+       if (m_x509 == NULL)
+               VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
+                                         "Internal Openssl error in d2i_X509 function.");
+}
+
+Certificate::Certificate(const std::string &data,
+                                                Certificate::FormType form)
+{
+       if (data.size() == 0)
+               VcoreThrowMsg(Certificate::Exception::WrongParamError,
+                                         "Input data shouldn't be empty");
+
+       int size;
+       const unsigned char *ptr;
+       std::string tmp = data;
+
+       // transform to DER format
+       if (FORM_BASE64 == form) {
+               try {
+                       Base64Decoder base64;
+                       base64.reset();
+                       base64.append(data);
+
+                       if (!base64.finalize()) {
+                               LogWarning("Error during decoding");
+                       }
+
+                       tmp = base64.get();
+               } catch (const Base64Decoder::Exception::Base &e) {
+                       LogError("Exception in Certificate constructor : " << e.DumpToString());
+                       VcoreThrowMsg(Certificate::Exception::Base64Error, "Failed to Base64Decoder");
+               }
+       }
+
+       ptr = reinterpret_cast<const unsigned char *>(tmp.c_str());
+       size = static_cast<int>(tmp.size());
+       m_x509 = d2i_X509(NULL, &ptr, size);
+
+       if (!m_x509)
+               VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
+                                         "Internal Openssl error in d2i_X509 function.");
+}
+
+static off_t getFileSize(const std::string &location)
+{
+       struct stat status;
+       stat(location.c_str(), &status);
+       return status.st_size;
+}
+
+CertificatePtr Certificate::createFromFile(const std::string &location)
+{
+       FILE *fp = NULL;
+       X509 *x509 = NULL;
+       fp = fopen(location.c_str(), "rb");
+
+       if (fp == NULL)
+               VcoreThrowMsg(Certificate::Exception::WrongParamError,
+                                         "File cannot be opened : " << location);
+
+       ScopedFile filePtr(fp, fclose);
+       x509 = PEM_read_X509(fp, NULL, NULL, NULL);
+
+       if (x509 == NULL) {
+               rewind(fp);
+               x509 = PEM_read_X509_AUX(fp, NULL, NULL, NULL);
+       }
+
+       if (x509 != NULL) {
+               ScopedX509 x509Ptr(x509, X509_free);
+               return CertificatePtr(new Certificate(x509));
+       }
+
+       off_t filesize = getFileSize(location);
+
+       if (filesize == 0)
+               VcoreThrowMsg(Certificate::Exception::WrongParamError,
+                                         "File content is empty : " << location);
+
+       unsigned char *content = new unsigned char[filesize + 1];
+       if (content == NULL)
+               VcoreThrowMsg(Certificate::Exception::InternalError,
+                                         "Fail to allocate memory.");
+
+       memset(content, 0x00, filesize + 1);
+       rewind(fp);
+
+       if (fread(content, sizeof(unsigned char), filesize, fp) != static_cast<size_t>(filesize))
+               VcoreThrowMsg(Certificate::Exception::InternalError,
+                                         "file read failed. wrong size : " << location);
+
+       content[filesize] = '\0';
+       const unsigned char *ptr = reinterpret_cast<const unsigned char *>(content);
+       x509 = d2i_X509(NULL, &ptr, filesize);
+
+       if (x509 == NULL)
+               VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
+                                         "Internal Openssl error in d2i_X509 function.");
+
+       return CertificatePtr(new Certificate(x509));
+}
+
+Certificate::~Certificate()
+{
+       X509_free(m_x509);
+}
+
+X509 *Certificate::getX509(void) const
+{
+       return m_x509;
+}
+
+std::string Certificate::getDER(void) const
+{
+       unsigned char *rawDer = NULL;
+       int size = i2d_X509(m_x509, &rawDer);
+
+       if (!rawDer || size <= 0)
+               VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
+                                         "i2d_X509 failed");
+
+       std::string output(reinterpret_cast<char *>(rawDer), size);
+       OPENSSL_free(rawDer);
+       return output;
+}
+
+std::string Certificate::getBase64(void) const
+{
+       Base64Encoder base64;
+
+       try {
+               base64.reset();
+               base64.append(getDER());
+               base64.finalize();
+       } catch (const Base64Encoder::Exception::Base &e) {
+               LogError("Exception in Certificate getBase64 : " << e.DumpToString());
+               VcoreThrowMsg(Certificate::Exception::Base64Error, "Failed to Base64Encoder");
+       }
+
+       return base64.get();
+}
+
+bool Certificate::isSignedBy(const CertificatePtr &parent) const
+{
+       if (!parent) {
+               LogDebug("Invalid certificate parameter.");
+               return false;
+       }
+
+       return 0 == X509_NAME_cmp(X509_get_subject_name(parent->m_x509),
+                                                         X509_get_issuer_name(m_x509));
+}
+
+Certificate::Fingerprint Certificate::getFingerprint(
+       Certificate::FingerprintType type) const
+{
+       unsigned int fingerprintlength = EVP_MAX_MD_SIZE;
+       unsigned char fingerprint[EVP_MAX_MD_SIZE];
+       Fingerprint raw;
+
+       if (type == FINGERPRINT_MD5) {
+               if (!X509_digest(m_x509, EVP_md5(), fingerprint, &fingerprintlength))
+                       VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
+                                                 "MD5 digest counting failed!");
+       }
+
+       if (type == FINGERPRINT_SHA1) {
+               if (!X509_digest(m_x509, EVP_sha1(), fingerprint, &fingerprintlength))
+                       VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
+                                                 "SHA1 digest counting failed");
+       }
+
+       raw.resize(fingerprintlength); // improve performance
+       std::copy(fingerprint, fingerprint + fingerprintlength, raw.begin());
+       return raw;
+}
+
+X509_NAME *Certificate::getX509Name(FieldType type) const
+{
+       X509_NAME *name = NULL;
+
+       switch (type) {
+       case FIELD_ISSUER:
+               name = X509_get_issuer_name(m_x509);
+               break;
+
+       case FIELD_SUBJECT:
+               name = X509_get_subject_name(m_x509);
+               break;
+
+       default:
+               VcoreThrowMsg(Certificate::Exception::WrongParamError,
+                                         "Invalid field type param. type : " << type);
+       }
+
+       if (!name)
+               VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
+                                         "Error during x509 name extraction.");
+
+       return name;
+}
+
+std::string Certificate::getOneLine(FieldType type) const
+{
+       X509_NAME *name = getX509Name(type);
+       static const int MAXB = 1024;
+       char buffer[MAXB] = {0, };
+       X509_NAME_oneline(name, buffer, MAXB);
+       return std::string(buffer);
+}
+
+std::string Certificate::getField(FieldType type, int fieldNid) const
+{
+       X509_NAME *subjectName = getX509Name(type);
+       X509_NAME_ENTRY *subjectEntry = NULL;
+       std::string output;
+       int entryCount = X509_NAME_entry_count(subjectName);
+
+       for (int i = 0; i < entryCount; ++i) {
+               subjectEntry = X509_NAME_get_entry(subjectName,
+                                                                                  i);
+
+               if (!subjectEntry) {
+                       continue;
+               }
+
+               int nid = OBJ_obj2nid(
+                                         static_cast<ASN1_OBJECT *>(
+                                                 X509_NAME_ENTRY_get_object(subjectEntry)));
+
+               if (nid != fieldNid) {
+                       continue;
+               }
+
+               ASN1_STRING *pASN1Str = subjectEntry->value;
+               unsigned char *pData = NULL;
+               int nLength = ASN1_STRING_to_UTF8(&pData,
+                                                                                 pASN1Str);
+
+               if (nLength < 0)
+                       VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
+                                                 "Reading field error.");
+
+               if (!pData) {
+                       output = std::string();
+               } else {
+                       output = std::string(reinterpret_cast<char *>(pData), nLength);
+                       OPENSSL_free(pData);
+               }
+       }
+
+       return output;
+}
+
+std::string Certificate::getCommonName(FieldType type) const
+{
+       return getField(type, NID_commonName);
+}
+
+std::string Certificate::getCountryName(FieldType type) const
+{
+       return getField(type, NID_countryName);
+}
+
+std::string Certificate::getStateOrProvinceName(FieldType type) const
+{
+       return getField(type, NID_stateOrProvinceName);
+}
+
+std::string Certificate::getLocalityName(FieldType type) const
+{
+       return getField(type, NID_localityName);
+}
+
+std::string Certificate::getOrganizationName(FieldType type) const
+{
+       return getField(type, NID_organizationName);
+}
+
+std::string Certificate::getOrganizationalUnitName(FieldType type) const
+{
+       return getField(type, NID_organizationalUnitName);
+}
+
+std::string Certificate::getEmailAddres(FieldType type) const
+{
+       return getField(type, NID_pkcs9_emailAddress);
+}
+
+std::string Certificate::getNameHash(FieldType type) const
+{
+       unsigned long ulNameHash;
+       char buf[9] = {0};
+
+       if (type == FIELD_SUBJECT)
+               ulNameHash = X509_subject_name_hash(m_x509);
+       else
+               ulNameHash = X509_issuer_name_hash(m_x509);
+
+       snprintf(buf, 9, "%08lx", ulNameHash);
+       return std::string(buf);
+}
+
+std::string Certificate::getUID(FieldType type) const
+{
+       ASN1_BIT_STRING *uid = NULL;
+
+       if (type == FIELD_SUBJECT)
+               uid = m_x509->cert_info->subjectUID;
+       else
+               uid = m_x509->cert_info->issuerUID;
+
+       if (uid->data == NULL)
+               return std::string();
+
+       char *temp = new char[uid->length + 1];
+
+       if(temp == NULL) {
+               LogError("Fail to allocate memory.");
+               return std::string();
+       }
+
+       memcpy(temp, uid->data, uid->length);
+       temp[uid->length] = 0;
+       std::string uidStr(temp);
+       delete []temp;
+       return uidStr;
+}
+
+std::string Certificate::getOCSPURL() const
+{
+       // TODO verify this code
+       std::string retValue;
+       AUTHORITY_INFO_ACCESS *aia = static_cast<AUTHORITY_INFO_ACCESS *>(
+                                                                        X509_get_ext_d2i(m_x509,
+                                                                                        NID_info_access,
+                                                                                        NULL,
+                                                                                        NULL));
+
+       // no AIA extension in the cert
+       if (NULL == aia) {
+               return retValue;
+       }
+
+       int count = sk_ACCESS_DESCRIPTION_num(aia);
+
+       for (int i = 0; i < count; ++i) {
+               ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(aia, i);
+
+               if (OBJ_obj2nid(ad->method) == NID_ad_OCSP &&
+                               ad->location->type == GEN_URI) {
+                       void *data = ASN1_STRING_data(ad->location->d.ia5);
+
+                       if (!data)
+                               retValue = std::string();
+                       else
+                               retValue = std::string(static_cast<char *>(data));
+
+                       break;
+               }
+       }
+
+       sk_ACCESS_DESCRIPTION_free(aia);
+       return retValue;
+}
+
+Certificate::AltNameSet Certificate::getAlternativeNameDNS() const
+{
+       AltNameSet set;
+       GENERAL_NAME *namePart = NULL;
+       STACK_OF(GENERAL_NAME)* san =
+               static_cast<STACK_OF(GENERAL_NAME) *>(
+                       X509_get_ext_d2i(m_x509, NID_subject_alt_name, NULL, NULL));
+
+       while (sk_GENERAL_NAME_num(san) > 0) {
+               if ((namePart = sk_GENERAL_NAME_pop(san)) == NULL)
+                       VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
+                                                 "openssl sk_GENERAL_NAME_pop err.");
+
+               if (GEN_DNS == namePart->type) {
+                       char *temp = reinterpret_cast<char *>(ASN1_STRING_data(namePart->d.dNSName));
+
+                       if (!temp) {
+                               set.insert(std::string());
+                       } else {
+                               set.insert(std::string(temp));
+                               LogDebug("FOUND GEN_DNS: " << temp);
+                       }
+               } else {
+                       LogDebug("FOUND GEN TYPE ID: " << namePart->type);
+               }
+       }
+
+       return set;
+}
+
+ASN1_TIME *Certificate::getNotAfterTime() const
+{
+       auto timeafter = X509_get_notAfter(m_x509);
+
+       if (!timeafter)
+               VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
+                                         "Reading Not After error.");
+
+       LogDebug("Get notAfter ASN1_TIME : " <<
+                        reinterpret_cast<char *>(timeafter->data));
+       return timeafter;
+}
+
+ASN1_TIME *Certificate::getNotBeforeTime() const
+{
+       auto timebefore = X509_get_notBefore(m_x509);
+
+       if (!timebefore)
+               VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
+                                         "Reading Not Before error.");
+
+       LogDebug("Get notBefore ASN1_TIME : " <<
+                        reinterpret_cast<char *>(timebefore->data));
+       return timebefore;
+}
+
+time_t Certificate::getNotAfter() const
+{
+       auto time = getNotAfterTime();
+       time_t output;
+
+       if (asn1TimeToTimeT(time, &output) == 0)
+               VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
+                                         "Converting ASN1_time to time_t error.");
+
+       return output;
+}
+
+time_t Certificate::getNotBefore() const
+{
+       auto time = getNotBeforeTime();
+       time_t output;
+
+       if (asn1TimeToTimeT(time, &output) == 0)
+               VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
+                                         "Converting ASN1_time to time_t error.");
+
+       return output;
+}
+
+bool Certificate::isRootCert()
+{
+       // based on that root certificate has the same subject as issuer name
+       return isSignedBy(this->shared_from_this());
+}
+
+long Certificate::getVersion() const
+{
+       return X509_get_version(m_x509);
+}
+
+std::string Certificate::getSerialNumberString() const
+{
+       ASN1_INTEGER *ai = X509_get_serialNumber(m_x509);
+
+       if (!ai)
+               VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
+                                         "Error in X509_get_serialNumber");
+
+       std::stringstream stream;
+       stream << std::hex << std::setfill('0');
+
+       if (ai->type == V_ASN1_NEG_INTEGER) {
+               stream << "(Negetive) ";
+       }
+
+       for (int i = 0; i < ai->length; ++i) {
+               stream << std::setw(2) << (int)ai->data[i] << ":";
+       }
+
+       std::string data = stream.str();
+
+       if (!data.empty()) {
+               data.erase(--data.end());
+       }
+
+       return data;
+}
+
+std::string Certificate::getKeyUsageString() const
+{
+       // Extensions were defined in RFC 3280
+       const char *usage[] = {
+               "digitalSignature",
+               "nonRepudiation",
+               "keyEncipherment",
+               "dataEncipherment",
+               "keyAgreement",
+               "keyCertSign",
+               "cRLSign",
+               "encipherOnly",
+               "decipherOnly"
+       };
+       int crit = -1;
+       int idx = -1;
+       ASN1_BIT_STRING *keyUsage = (ASN1_BIT_STRING *)
+                                                               X509_get_ext_d2i(m_x509, NID_key_usage, &crit, &idx);
+       std::stringstream stream;
+
+       for (int i = 0; i < 9; ++i) {
+               if (ASN1_BIT_STRING_get_bit(keyUsage, i)) {
+                       stream << usage[i] << ",";
+               }
+       }
+
+       std::string result = stream.str();
+
+       if (!result.empty()) {
+               result.erase(--result.end());
+       }
+
+       return result;
+}
+
+std::string Certificate::getSignatureAlgorithmString() const
+{
+       std::unique_ptr<BIO, std::function<int(BIO *)>>
+                       b(BIO_new(BIO_s_mem()), BIO_free);
+
+       if (!b.get())
+               VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
+                                         "Error in BIO_new");
+
+       if (i2a_ASN1_OBJECT(b.get(), m_x509->cert_info->signature->algorithm) < 0)
+               VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
+                                         "Error in i2a_ASN1_OBJECT");
+
+       BUF_MEM *bptr = 0;
+       BIO_get_mem_ptr(b.get(), &bptr);
+
+       if (bptr == 0)
+               VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
+                                         "Error in BIO_get_mem_ptr");
+
+       std::string result(bptr->data, bptr->length);
+       return result;
+}
+
+std::string Certificate::getPublicKeyString() const
+{
+       std::unique_ptr<BIO, std::function<int(BIO *)>>
+                       b(BIO_new(BIO_s_mem()), BIO_free);
+
+       if (!b.get())
+               VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
+                                         "Error in BIO_new");
+
+       EVP_PKEY *pkey = X509_get_pubkey(m_x509);
+
+       if (!pkey)
+               VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
+                                         "Error in X509_get_pubkey");
+
+       EVP_PKEY_print_public(b.get(), pkey, 16, NULL);
+       EVP_PKEY_free(pkey);
+       BUF_MEM *bptr = 0;
+       BIO_get_mem_ptr(b.get(), &bptr);
+
+       if (bptr == 0)
+               VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
+                                         "Error in BIO_get_mem_ptr");
+
+       std::string result(bptr->data, bptr->length);
+       return result;
+}
+
+void Certificate::getPublicKeyDER(unsigned char **pubkey, size_t *len) const
+{
+       if (pubkey == NULL || len == NULL)
+               VcoreThrowMsg(Certificate::Exception::WrongParamError, "Wrong parameter");
+
+       EVP_PKEY *pkey = X509_get_pubkey(m_x509);
+       unsigned char *_pubkey = NULL;
+       int _len = i2d_PUBKEY(pkey, &_pubkey);
+       EVP_PKEY_free(pkey);
+
+       if (_pubkey == NULL || _len == 0)
+               VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
+                                         "Error in i2d_PUBKEY");
+
+       *pubkey = _pubkey;
+       *len = static_cast<size_t>(_len);
+}
+
+std::string Certificate::getPublicKeyAlgoString() const
+{
+       return std::string(static_cast<const char *>(
+                                                  OBJ_nid2ln(OBJ_obj2nid(m_x509->cert_info->key->algor->algorithm))));
+}
+
+int Certificate::isCA() const
+{
+       return X509_check_ca(m_x509);
+}
+
+std::string Certificate::FingerprintToColonHex(
+       const Certificate::Fingerprint &fingerprint)
+{
+       std::string outString;
+       char buff[8];
+
+       for (size_t i = 0; i < fingerprint.size(); ++i) {
+               snprintf(buff,
+                                sizeof(buff),
+                                "%02X:",
+                                static_cast<unsigned int>(fingerprint[i]));
+               outString += buff;
+       }
+
+       // remove trailing ":"
+       outString.erase(outString.end() - 1);
+       return outString;
+}
+
+} //  namespace ValidationCore
diff --git a/src/vcore/Certificate.h b/src/vcore/Certificate.h
new file mode 100644 (file)
index 0000000..64673ab
--- /dev/null
@@ -0,0 +1,180 @@
+/*
+ * 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        Certificate.h
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.1
+ * @brief       Certificate class
+ */
+#pragma once
+
+#include <list>
+#include <set>
+#include <string>
+#include <vector>
+#include <ctime>
+#include <memory>
+
+#include <openssl/x509.h>
+
+#include "vcore/exception.h"
+
+extern "C" {
+       struct x509_st;
+       typedef struct x509_st X509;
+       struct X509_name_st;
+       typedef struct X509_name_st X509_NAME;
+}
+
+namespace ValidationCore {
+
+class Certificate;
+
+typedef std::shared_ptr<Certificate> CertificatePtr;
+typedef std::list<CertificatePtr> CertificateList;
+
+class Certificate : public std::enable_shared_from_this<Certificate> {
+public:
+       class Exception {
+       public:
+               VCORE_DECLARE_EXCEPTION_TYPE(ValidationCore::Exception, Base);
+               VCORE_DECLARE_EXCEPTION_TYPE(Base, OpensslInternalError);
+               VCORE_DECLARE_EXCEPTION_TYPE(Base, Base64Error);
+               VCORE_DECLARE_EXCEPTION_TYPE(Base, WrongParamError);
+               VCORE_DECLARE_EXCEPTION_TYPE(Base, InternalError);
+       };
+
+       typedef std::vector<unsigned char> Fingerprint;
+
+       // ascii string
+       typedef std::string AltName;
+       typedef std::set<AltName> AltNameSet;
+
+       enum FingerprintType {
+               FINGERPRINT_MD5,
+               FINGERPRINT_SHA1
+       };
+       enum FieldType {
+               FIELD_ISSUER,
+               FIELD_SUBJECT
+       };
+
+       enum FormType {
+               FORM_DER,
+               FORM_BASE64
+       };
+
+       static CertificatePtr createFromFile(const std::string &location);
+
+       explicit Certificate(X509 *cert);
+
+       explicit Certificate(const std::string &data,
+                                                FormType form = FORM_DER);
+
+       ~Certificate();
+
+       // It returns pointer to internal structure!
+       // Do not free this pointer!
+       X509 *getX509(void) const;
+
+       std::string getDER(void) const;
+
+       std::string getBase64(void) const;
+
+       // This const is cheating here because you have no
+       // guarantee that X509_get_subject_name will not
+       // change X509 object.
+       bool isSignedBy(const CertificatePtr &parent) const;
+
+       Fingerprint getFingerprint(FingerprintType type) const;
+
+       // getName uses deprecated functions. Usage is strongly discouraged.
+       // utf8 string
+       std::string getOneLine(FieldType type = FIELD_SUBJECT) const;
+       std::string getCommonName(FieldType type = FIELD_SUBJECT) const;
+       std::string getCountryName(FieldType type = FIELD_SUBJECT) const;
+       std::string getStateOrProvinceName(FieldType type = FIELD_SUBJECT) const;
+       std::string getLocalityName(FieldType type = FIELD_SUBJECT) const;
+       std::string getOrganizationName(FieldType type = FIELD_SUBJECT) const;
+       std::string getOrganizationalUnitName(FieldType type = FIELD_SUBJECT) const;
+       std::string getEmailAddres(FieldType type = FIELD_SUBJECT) const;
+
+       std::string getNameHash(FieldType type = FIELD_SUBJECT) const;
+
+       // TODO: UID type is unsigned char. std::string should be changed to unsigned char container
+       std::string getUID(FieldType type = FIELD_SUBJECT) const;
+       std::string getOCSPURL() const;
+
+
+
+       // Openssl supports 9 types of alternative name filed.
+       // 4 of them are "string similar" types so it is possible
+       // to create more generic function.
+       AltNameSet getAlternativeNameDNS() const;
+
+       time_t getNotAfter() const;
+
+       time_t getNotBefore() const;
+
+       ASN1_TIME *getNotAfterTime() const;
+
+       ASN1_TIME *getNotBeforeTime() const;
+
+       /**
+        * @brief This is convenient function.
+        *
+        * @details It can't be const function (however it doesn't change internal
+        * object). For details see #isSignedBy() function description.
+        */
+       bool isRootCert();
+
+       /**
+        * @brief Gets list of CRL distribution's points URIs
+        */
+       std::list<std::string> getCrlUris() const;
+
+       long getVersion() const;
+
+       // utf8 string
+       std::string getSerialNumberString() const;
+       std::string getKeyUsageString() const;
+       std::string getSignatureAlgorithmString() const;
+       std::string getPublicKeyAlgoString() const;
+       std::string getPublicKeyString() const;
+       void getPublicKeyDER(unsigned char **pubkey, size_t *len) const;
+
+       /*
+        * 0 - not CA
+        * 1 - CA
+        * 2 - deprecated and not used
+        * 3 - older version of CA
+        * 4 - older version of CA
+        * 5 - netscape CA
+        */
+       int isCA() const;
+
+       static std::string FingerprintToColonHex(
+               const Fingerprint &fingerprint);
+
+protected:
+       X509_NAME *getX509Name(FieldType type) const;
+
+       // utf8 string
+       std::string getField(FieldType type, int fieldNid) const;
+
+       X509 *m_x509;
+};
+} // namespace ValidationCore
diff --git a/src/vcore/CertificateCollection.cpp b/src/vcore/CertificateCollection.cpp
new file mode 100644 (file)
index 0000000..f7734a3
--- /dev/null
@@ -0,0 +1,334 @@
+/*
+ * 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        CertificateCollection.cpp
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @author      Kyungwook Tak (k.tak@samsung.com)
+ * @version     1.0
+ * @brief       Handles certificate chain, make it complete and sort
+ */
+
+#include <stdlib.h>
+#include <string.h>
+#include <stddef.h>
+#include <unistd.h>
+#include <dirent.h>
+
+#include <memory>
+#include <functional>
+
+#include <openssl/pem.h>
+#include <openssl/x509.h>
+
+#include <cert-svc/cinstance.h>
+#include <cert-svc/ccert.h>
+#include <cert-svc/cprimitives.h>
+
+#include <dpl/log/log.h>
+
+#include "vcore/Base64.h"
+
+#include "vcore/CertificateCollection.h"
+
+namespace {
+
+using namespace ValidationCore;
+
+inline std::string toBinaryString(int data)
+{
+       char buffer[sizeof(int)];
+       memcpy(buffer, &data, sizeof(int));
+       return std::string(buffer, sizeof(int));
+}
+
+bool isHashMatchedName(const std::string &name, const std::string &hash)
+{
+       if (name.compare(0, 8, hash) != 0)
+               return false;
+
+       return true;
+}
+
+bool isHashMatchedFile(const std::string &path, const std::string &hash)
+{
+       CertificatePtr certPtr = Certificate::createFromFile(path);
+       std::string name = certPtr->getNameHash(Certificate::FIELD_SUBJECT);
+       return isHashMatchedName(name, hash);
+}
+
+CertificatePtr searchCert(const std::string &dir, const CertificatePtr &certPtr, bool withHash)
+{
+       try {
+               std::string hash = certPtr->getNameHash(Certificate::FIELD_ISSUER);
+               std::unique_ptr<DIR, std::function<int(DIR *)>> dp(::opendir(dir.c_str()), ::closedir);
+
+               if (dp.get() == NULL) {
+                       LogError("Failed open dir[" << dir << "]");
+                       return CertificatePtr();
+               }
+
+               size_t len = offsetof(struct dirent, d_name) + pathconf(dir.c_str(), _PC_NAME_MAX) + 1;
+               std::unique_ptr<struct dirent, std::function<void(void *)>>
+                               pEntry(static_cast<struct dirent *>(::malloc(len)), ::free);
+               struct dirent *dirp = NULL;
+               int ret = 0;
+
+               while ((ret = readdir_r(dp.get(), pEntry.get(), &dirp)) == 0 && dirp) {
+                       if (dirp->d_type == DT_DIR)
+                               continue;
+
+                       std::string candidatePath(dir);
+                       candidatePath += "/";
+                       candidatePath += dirp->d_name;
+
+                       if (withHash) {
+                               if (!isHashMatchedName(dirp->d_name, hash))
+                                       continue;
+                       } else {
+                               if (!isHashMatchedFile(candidatePath, hash))
+                                       continue;
+                       }
+
+                       LogDebug("Found hash matched file! : " << candidatePath);
+                       CertificatePtr candidate = Certificate::createFromFile(candidatePath);
+
+                       if (candidate->getOneLine().compare(certPtr->getOneLine(Certificate::FIELD_ISSUER)) != 0)
+                               continue;
+
+                       return candidate;
+               }
+
+               if (ret != 0) {
+                       LogError("readdir_r error. ret[" << ret << "]");
+                       return CertificatePtr();
+               }
+
+               LogWarning("cert not found by hash[" << hash << "]");
+               return CertificatePtr();
+       } catch (const Certificate::Exception::Base &e) {
+               VcoreThrowMsg(
+                       CertificateCollection::Exception::CertificateError,
+                       "Error in handling certificate : " << e.DumpToString());
+       } catch (const std::exception &e) {
+               VcoreThrowMsg(
+                       CertificateCollection::Exception::InternalError,
+                       "std::exception occured : " << e.what());
+       } catch (...) {
+               VcoreThrowMsg(
+                       CertificateCollection::Exception::InternalError,
+                       "Unknown exception in CertificateCollection.");
+       }
+}
+
+CertificatePtr getIssuerCertFromStore(const CertificatePtr &certPtr)
+{
+       LogDebug("Start to get issuer from store.");
+       CertificatePtr found = searchCert(TZ_SYS_CA_CERTS_TIZEN, certPtr, false);
+
+       if (found.get() != NULL) {
+               LogDebug("Found issuer cert in tizen root CA dir");
+               return found;
+       }
+
+       return searchCert(TZ_SYS_CA_CERTS, certPtr, true);
+}
+
+} // namespace
+
+namespace ValidationCore {
+
+CertificateCollection::CertificateCollection()
+       : m_collectionStatus(COLLECTION_UNSORTED)
+{}
+
+void CertificateCollection::clear(void)
+{
+       m_collectionStatus = COLLECTION_UNSORTED;
+       m_certList.clear();
+}
+
+void CertificateCollection::load(const CertificateList &certList)
+{
+       m_collectionStatus = COLLECTION_UNSORTED;
+       std::copy(certList.begin(),
+                         certList.end(),
+                         std::back_inserter(m_certList));
+}
+
+std::string CertificateCollection::toBase64String() const
+{
+       std::ostringstream output;
+       int certNum = m_certList.size();
+       output << toBinaryString(certNum);
+
+       for (auto i = m_certList.begin(); i != m_certList.end(); ++i) {
+               std::string derCert = (*i)->getDER();
+               output << toBinaryString(derCert.size());
+               output << derCert;
+       }
+
+       Base64Encoder base64;
+       base64.reset();
+       base64.append(output.str());
+       base64.finalize();
+       return base64.get();
+}
+
+CertificateList CertificateCollection::getCertificateList() const
+{
+       return m_certList;
+}
+
+bool CertificateCollection::isChain() const
+{
+       if (COLLECTION_SORTED != m_collectionStatus)
+               VcoreThrowMsg(CertificateCollection::Exception::WrongUsage,
+                                         "You must sort certificate first");
+
+       return (COLLECTION_SORTED == m_collectionStatus) ? true : false;
+}
+
+bool CertificateCollection::sort()
+{
+       if (COLLECTION_UNSORTED == m_collectionStatus) {
+               sortCollection();
+       }
+
+       return (COLLECTION_SORTED == m_collectionStatus) ? true : false;
+}
+
+CertificateList CertificateCollection::getChain() const
+{
+       if (COLLECTION_SORTED != m_collectionStatus)
+               VcoreThrowMsg(CertificateCollection::Exception::WrongUsage,
+                                         "You must sort certificates first");
+
+       return m_certList;
+}
+
+void CertificateCollection::sortCollection()
+{
+       // sorting is not necessary
+       if (m_certList.empty()) {
+               m_collectionStatus = COLLECTION_SORTED;
+               return;
+       }
+
+       CertificateList sorted;
+       std::map<std::string, CertificatePtr> subTransl;
+       std::map<std::string, CertificatePtr> issTransl;
+
+       // Sort all certificate by subject
+       for (auto it = m_certList.begin(); it != m_certList.end(); ++it) {
+               subTransl.insert(std::make_pair((*it)->getOneLine(), (*it)));
+       }
+
+       // We need one start certificate
+       sorted.push_back(subTransl.begin()->second);
+       subTransl.erase(subTransl.begin());
+
+       // Get the issuer from front certificate and find certificate with this subject in subTransl.
+       // Add this certificate to the front.
+       while (!subTransl.empty()) {
+               std::string issuer = sorted.back()->getOneLine(Certificate::FIELD_ISSUER);
+               auto it = subTransl.find(issuer);
+
+               if (it == subTransl.end()) {
+                       break;
+               }
+
+               sorted.push_back(it->second);
+               subTransl.erase(it);
+       }
+
+       // Sort all certificates by issuer
+       for (auto it = subTransl.begin(); it != subTransl.end(); ++it) {
+               issTransl.insert(std::make_pair(it->second->getOneLine(Certificate::FIELD_ISSUER), it->second));
+       }
+
+       // Get the subject from last certificate and find certificate with such issuer in issTransl.
+       // Add this certificate at end.
+       while (!issTransl.empty()) {
+               std::string sub = sorted.front()->getOneLine();
+               auto it = issTransl.find(sub);
+
+               if (it == issTransl.end()) {
+                       break;
+               }
+
+               sorted.push_front(it->second);
+               issTransl.erase(it);
+       }
+
+       if (!issTransl.empty()) {
+               LogWarning("Certificates don't form a valid chain.");
+               m_collectionStatus = COLLECTION_CHAIN_BROKEN;
+               return;
+       }
+
+       m_collectionStatus = COLLECTION_SORTED;
+       m_certList = sorted;
+}
+
+/*
+ *  Precondition : cert list sorted and has more than one cert
+ */
+bool CertificateCollection::completeCertificateChain()
+{
+       CertificatePtr last = m_certList.back();
+
+       if (last->isRootCert())
+               return true;
+
+       CertificatePtr rootCert = getIssuerCertFromStore(last);
+
+       if (!rootCert.get())
+               return false;
+
+       if (!rootCert->isRootCert())
+               return false;
+
+       m_certList.push_back(rootCert);
+       return true;
+}
+
+size_t CertificateCollection::size() const
+{
+       return m_certList.size();
+}
+
+bool CertificateCollection::empty() const
+{
+       return m_certList.empty();
+}
+
+CertificateCollection::const_iterator CertificateCollection::begin() const
+{
+       return m_certList.begin();
+}
+
+CertificateCollection::const_iterator CertificateCollection::end() const
+{
+       return m_certList.end();
+}
+
+CertificatePtr CertificateCollection::back() const
+{
+       return m_certList.back();
+}
+
+} // namespace ValidationCore
+
diff --git a/src/vcore/CertificateCollection.h b/src/vcore/CertificateCollection.h
new file mode 100644 (file)
index 0000000..7ec3186
--- /dev/null
@@ -0,0 +1,172 @@
+/*
+ * Copyright (c) 2011 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        CertificateCollection.h
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     0.1
+ * @brief
+ */
+#ifndef _VALIDATION_CORE_CERTIFICATECOLLECTION_H_
+#define _VALIDATION_CORE_CERTIFICATECOLLECTION_H_
+
+#include <list>
+#include <string>
+#include <map>
+
+#include <vcore/exception.h>
+
+#include <vcore/Certificate.h>
+
+namespace ValidationCore {
+/*
+ * This class is used to store Certificate Chain.
+ * It could serialize chain to std::string in base64 form.
+ * It could read chain written in base64 form.
+ * It could check if collection creates certificate chain.
+ */
+
+class CertificateCollection {
+public:
+       class Exception {
+       public:
+               VCORE_DECLARE_EXCEPTION_TYPE(ValidationCore::Exception, Base);
+               VCORE_DECLARE_EXCEPTION_TYPE(Base, InternalError);
+               VCORE_DECLARE_EXCEPTION_TYPE(Base, CertificateError);
+               VCORE_DECLARE_EXCEPTION_TYPE(Base, WrongUsage);
+       };
+
+       CertificateCollection();
+
+       typedef CertificateList::const_iterator const_iterator;
+
+       /*
+        * Remove all certificates from collection.
+        */
+       void clear();
+
+       /*
+        * In current implemenation this function MUST success.
+        *
+        * This function will add new certificate to collection.
+        * This function DOES NOT clean collection.
+        */
+       void load(const CertificateList &certList);
+
+       /*
+        * This function will return all certificates from
+        * collection encoded in base64 format.
+        */
+       std::string toBase64String() const;
+
+       /*
+        * This will return all certificate from collection.
+        */
+       CertificateList getCertificateList() const;
+
+       /*
+        * This function will return true if certificates
+        * in in this structure were sorted and create
+        * certificate chain.
+
+        * Note: You MUST sort certificates first.
+        */
+       bool isChain() const;
+
+       /*
+        * This function will return true if all certificate are
+        * able to create certificate chain.
+        *
+        * This function will sort certificates if collection
+        * is not sorted.
+        *
+        * Note: This function will make all iterators invalid.
+        */
+       bool sort();
+
+       /*
+        * Precondition : cert list sorted and has more than on cert.
+        * This function add root cert in cert list to complete cert chain
+        */
+       bool completeCertificateChain();
+
+       /*
+        * This function will return Certificate chain.
+        *
+        * First certificate on the list is EndEntity certificate.
+        *
+        * Last certificate on the list is RootCA certificate or
+        * CA certificate if RootCA is not present.
+        *
+        * Note: You MUST sort certificates first and
+        * check if certificates creates proper chain.
+        */
+       CertificateList getChain() const;
+
+       /*
+        * It returns size of certificate collection.
+        */
+       size_t size() const;
+
+       /*
+        * Return true if collection is empty.
+        */
+       bool empty() const;
+
+       /*
+        * This will return end iterator to internal collection.
+        *
+        * Note: this iterator will lose validity if you call non const
+        * method on CertificateCollection class.
+        */
+       const_iterator begin() const;
+
+       /*
+        * This will return end iterator to internal collection.
+        *
+        * Note: this iterator will lose validity if you call non const
+        * method on CertificateCollection class.
+        */
+       const_iterator end() const;
+
+       /*
+        * This function will return the last certificate from collection.
+        *
+        * Note: There is no point to call this function if certificate
+        * collection is not sorted!
+        */
+       CertificatePtr back() const;
+
+protected:
+       void sortCollection(void);
+
+       enum CollectionStatus {
+               // Certificate collection are not sorted in any way
+               COLLECTION_UNSORTED,
+               // Certificate collection creates certificate chain
+               COLLECTION_SORTED,
+               // Cerfificate collection is not able to create certificate chain
+               COLLECTION_CHAIN_BROKEN,
+       };
+
+       CollectionStatus m_collectionStatus;
+       CertificateList m_certList;
+};
+
+typedef std::list<CertificateCollection> CertificateCollectionList;
+
+} // namespace ValidationCore
+
+#endif // _VALIDATION_CORE_CERTIFICATECHAIN_H_
diff --git a/src/vcore/CertificateConfigReader.cpp b/src/vcore/CertificateConfigReader.cpp
new file mode 100644 (file)
index 0000000..856641f
--- /dev/null
@@ -0,0 +1,168 @@
+/*
+ * Copyright (c) 2011 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
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief
+ */
+
+#include <vcore/CertificateConfigReader.h>
+
+#include <dpl/assert.h>
+
+#include <cstdlib>
+
+namespace {
+const std::string XML_EMPTY_NAMESPACE = "";
+
+const std::string TOKEN_CERTIFICATE_SET = "CertificateSet";
+const std::string TOKEN_CERTIFICATE_DOMAIN = "CertificateDomain";
+const std::string TOKEN_FINGERPRINT_SHA1 = "FingerprintSHA1";
+
+const std::string TOKEN_ATTR_NAME = "name";
+const std::string TOKEN_VALUE_TIZEN_DEVELOPER = "tizen-developer";
+const std::string TOKEN_VALUE_TIZEN_TEST = "tizen-test";
+const std::string TOKEN_VALUE_TIZEN_VERIFY = "tizen-verify";
+const std::string TOKEN_VALUE_TIZEN_STORE = "tizen-store";
+const std::string TOKEN_VALUE_TIZEN_REVOKED = "tizen-revoked";
+const std::string TOKEN_VALUE_VISIBILITY_PUBLIC = "tizen-public";
+const std::string TOKEN_VALUE_VISIBILITY_PARTNER = "tizen-partner";
+const std::string TOKEN_VALUE_VISIBILITY_PLATFORM = "tizen-platform";
+
+int hexCharToInt(char c)
+{
+       if (c >= 'a' && c <= 'f') {
+               return 10 + static_cast<int>(c) - 'a';
+       }
+
+       if (c >= 'A' && c <= 'F') {
+               return 10 + static_cast<int>(c) - 'A';
+       }
+
+       if (c >= '0' && c <= '9') {
+               return static_cast<int>(c) - '0';
+       }
+
+       return c;
+}
+} // anonymous namespace
+
+namespace ValidationCore {
+CertificateConfigReader::CertificateConfigReader()
+       : m_certificateDomain(0)
+       , m_parserSchema(this)
+{
+       m_parserSchema.addBeginTagCallback(
+               TOKEN_CERTIFICATE_SET,
+               XML_EMPTY_NAMESPACE,
+               &CertificateConfigReader::blankFunction);
+       m_parserSchema.addBeginTagCallback(
+               TOKEN_CERTIFICATE_DOMAIN,
+               XML_EMPTY_NAMESPACE,
+               &CertificateConfigReader::tokenCertificateDomain);
+       m_parserSchema.addBeginTagCallback(
+               TOKEN_FINGERPRINT_SHA1,
+               XML_EMPTY_NAMESPACE,
+               &CertificateConfigReader::blankFunction);
+       m_parserSchema.addEndTagCallback(
+               TOKEN_CERTIFICATE_SET,
+               XML_EMPTY_NAMESPACE,
+               &CertificateConfigReader::blankFunction);
+       m_parserSchema.addEndTagCallback(
+               TOKEN_CERTIFICATE_DOMAIN,
+               XML_EMPTY_NAMESPACE,
+               &CertificateConfigReader::blankFunction);
+       m_parserSchema.addEndTagCallback(
+               TOKEN_FINGERPRINT_SHA1,
+               XML_EMPTY_NAMESPACE,
+               &CertificateConfigReader::tokenEndFingerprintSHA1);
+}
+
+void CertificateConfigReader::initialize(
+       const std::string &file,
+       const std::string &scheme)
+{
+       m_parserSchema.initialize(file, true, SaxReader::VALIDATION_XMLSCHEME, scheme);
+}
+
+void CertificateConfigReader::read(CertificateIdentifier &identificator)
+{
+       m_parserSchema.read(identificator);
+}
+
+void CertificateConfigReader::blankFunction(CertificateIdentifier &)
+{
+}
+
+void CertificateConfigReader::tokenCertificateDomain(CertificateIdentifier &)
+{
+       std::string name = m_parserSchema.getReader().attribute(TOKEN_ATTR_NAME);
+
+       if (name.empty()) {
+               VcoreThrowMsg(CertificateConfigReader::Exception::InvalidFile,
+                                         "Invalid fingerprint file. Domain name is mandatory");
+       } else if (name == TOKEN_VALUE_TIZEN_DEVELOPER) {
+               m_certificateDomain = CertStoreId::TIZEN_DEVELOPER;
+       } else if (name == TOKEN_VALUE_TIZEN_TEST) {
+               m_certificateDomain = CertStoreId::TIZEN_TEST;
+       } else if (name == TOKEN_VALUE_TIZEN_VERIFY) {
+               m_certificateDomain = CertStoreId::TIZEN_VERIFY;
+       } else if (name == TOKEN_VALUE_TIZEN_STORE) {
+               m_certificateDomain = CertStoreId::TIZEN_STORE;
+       } else if (name == TOKEN_VALUE_TIZEN_REVOKED) {
+               m_certificateDomain = CertStoreId::TIZEN_REVOKED;
+       } else if (name == TOKEN_VALUE_VISIBILITY_PUBLIC) {
+               m_certificateDomain = CertStoreId::VIS_PUBLIC;
+       } else if (name == TOKEN_VALUE_VISIBILITY_PARTNER) {
+               m_certificateDomain = CertStoreId::VIS_PARTNER;
+       } else if (name == TOKEN_VALUE_VISIBILITY_PLATFORM) {
+               m_certificateDomain = CertStoreId::VIS_PLATFORM;
+       } else {
+               m_certificateDomain = 0;
+       }
+}
+
+void CertificateConfigReader::tokenEndFingerprintSHA1(
+       CertificateIdentifier &identificator)
+{
+       std::string text = m_parserSchema.getText();
+       text += ":"; // add guard at the end of fingerprint
+       Certificate::Fingerprint fingerprint;
+       int s = 0;
+       int byteDescLen = 0;
+
+       for (size_t i = 0; i < text.size(); ++i) {
+               if (isxdigit(text[i])) {
+                       s <<= 4;
+                       s += hexCharToInt(text[i]);
+                       byteDescLen++;
+
+                       if (byteDescLen > 2) {
+                               Assert(0 && "Unsupported fingerprint format in xml file.");
+                       }
+               } else if (text[i] == ':') {
+                       fingerprint.push_back(static_cast<unsigned char>(s));
+                       s = 0;
+                       byteDescLen = 0;
+               } else {
+                       Assert(0 && "Unussported fingerprint format in xml file.");
+               }
+       }
+
+       identificator.add(fingerprint, m_certificateDomain);
+}
+} // namespace ValidationCore
diff --git a/src/vcore/CertificateConfigReader.h b/src/vcore/CertificateConfigReader.h
new file mode 100644 (file)
index 0000000..0d31934
--- /dev/null
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2011 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        CertificateConfigReader.h
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief
+ */
+#ifndef _VALIDATION_CORE_CERTIFICATE_CONFIG_READER_H_
+#define _VALIDATION_CORE_CERTIFICATE_CONFIG_READER_H_
+
+#include <string>
+
+#include <vcore/CertificateIdentifier.h>
+#include <vcore/CertStoreType.h>
+#include <vcore/ParserSchema.h>
+#include <vcore/exception.h>
+
+namespace ValidationCore {
+class CertificateConfigReader {
+public:
+       class Exception {
+       public:
+               VCORE_DECLARE_EXCEPTION_TYPE(ValidationCore::Exception, Base);
+               VCORE_DECLARE_EXCEPTION_TYPE(Base, InvalidFile);
+       };
+
+       CertificateConfigReader();
+
+       void initialize(const std::string &file, const std::string &scheme);
+       void read(CertificateIdentifier &identificator);
+
+private:
+       void blankFunction(CertificateIdentifier &);
+       void tokenCertificateDomain(CertificateIdentifier &identificator);
+       void tokenEndFingerprintSHA1(CertificateIdentifier &identificator);
+
+       CertStoreId::Type m_certificateDomain;
+       ParserSchema<CertificateConfigReader, CertificateIdentifier> m_parserSchema;
+};
+} // namespace ValidationCore
+
+#endif // _VALIDATION_CORE_CERTIFICATE_CONFIG_READER_H_
diff --git a/src/vcore/CertificateIdentifier.h b/src/vcore/CertificateIdentifier.h
new file mode 100644 (file)
index 0000000..adf05c7
--- /dev/null
@@ -0,0 +1,72 @@
+/*
+ * Copyright (c) 2011 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
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief
+ */
+#ifndef \
+    _WRT_ENGINE_SRC_INSTALLER_CORE_VALIDATION_CORE_CERTIFICATEIDENTIFICATOR_H_
+#define \
+       _WRT_ENGINE_SRC_INSTALLER_CORE_VALIDATION_CORE_CERTIFICATEIDENTIFICATOR_H_
+
+#include <map>
+
+#include <vcore/Certificate.h>
+#include <vcore/CertStoreType.h>
+
+namespace ValidationCore {
+class CertificateIdentifier {
+public:
+       typedef std::map<Certificate::Fingerprint, CertStoreId::Set> FingerPrintMap;
+
+       CertificateIdentifier() = default;
+       ~CertificateIdentifier() = default;
+
+       CertificateIdentifier(const CertificateIdentifier &) = delete;
+       CertificateIdentifier &operator=(const CertificateIdentifier &) = delete;
+       CertificateIdentifier(CertificateIdentifier &&) = delete;
+       CertificateIdentifier &operator=(CertificateIdentifier &&) = delete;
+
+       void add(const Certificate::Fingerprint &fingerprint,
+                        CertStoreId::Type domain)
+       {
+               fingerPrintMap[fingerprint].add(domain);
+       }
+
+       CertStoreId::Set find(const Certificate::Fingerprint &fingerprint) const
+       {
+               FingerPrintMap::const_iterator iter = fingerPrintMap.find(fingerprint);
+
+               if (iter == fingerPrintMap.end()) {
+                       return CertStoreId::Set();
+               }
+
+               return iter->second;
+       }
+
+       CertStoreId::Set find(const CertificatePtr &certificate) const
+       {
+               return find(certificate->getFingerprint(Certificate::FINGERPRINT_SHA1));
+       }
+
+private:
+       FingerPrintMap fingerPrintMap;
+};
+} // namespace ValidationCore
+
+#endif // _WRT_ENGINE_SRC_INSTALLER_CORE_VALIDATION_CORE_CERTIFICATEIDENTIFICATOR_H_
diff --git a/src/vcore/CertificateLoader.cpp b/src/vcore/CertificateLoader.cpp
new file mode 100644 (file)
index 0000000..40c82b1
--- /dev/null
@@ -0,0 +1,131 @@
+/*
+ * Copyright (c) 2011 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.
+ */
+#include <dpl/assert.h>
+#include <openssl/x509v3.h>
+#include <dpl/log/log.h>
+#include <openssl/ecdsa.h>
+#include <openssl/evp.h>
+
+#include <vcore/Base64.h>
+#include <vcore/CertificateLoader.h>
+
+namespace {
+const int MIN_RSA_KEY_LENGTH = 1024;
+} // namespace anonymous
+
+namespace ValidationCore {
+CertificateLoader::CertificateLoaderResult CertificateLoader::
+loadCertificateBasedOnExponentAndModulus(const std::string &m_modulus,
+               const std::string &m_exponent)
+{
+       (void) m_modulus;
+       (void) m_exponent;
+       LogError("Not implemented.");
+       return UNKNOWN_ERROR;
+}
+
+CertificateLoader::CertificateLoaderResult CertificateLoader::loadCertificate(
+       const std::string &storageName,
+       CertificateLoader::CertificateLoaderComparator *cmp)
+{
+       (void) storageName;
+       (void) cmp;
+       LogError("Not Implemented");
+       return UNKNOWN_ERROR;
+}
+
+CertificateLoader::CertificateLoaderResult CertificateLoader::
+loadCertificateBasedOnSubjectName(const std::string &subjectName)
+{
+       (void) subjectName;
+       LogError("Not implemented.");
+       return UNKNOWN_ERROR;
+}
+
+CertificateLoader::CertificateLoaderResult CertificateLoader::
+loadCertificateWithECKEY(const std::string &curveName,
+                                                const std::string &publicKey)
+{
+       (void) curveName;
+       (void) publicKey;
+       LogError("Not implemented.");
+       return UNKNOWN_ERROR;
+}
+
+CertificateLoader::CertificateLoaderResult CertificateLoader::loadCertificateFromRawData(
+       const std::string &rawData)
+{
+       VcoreTry {
+               m_certificatePtr = CertificatePtr(new Certificate(rawData, Certificate::FORM_BASE64));
+       } VcoreCatch(Certificate::Exception::Base) {
+               LogWarning("Error reading certificate by openssl.");
+               return UNKNOWN_ERROR;
+       }
+       // Check the key length if sig algorithm is RSA
+       EVP_PKEY *pKey = X509_get_pubkey(m_certificatePtr->getX509());
+
+       if (pKey != NULL) {
+               if (pKey->type == EVP_PKEY_RSA) {
+                       RSA *pRSA = pKey->pkey.rsa;
+
+                       if (pRSA) {
+                               int keyLength = RSA_size(pRSA);
+                               // key Length (modulus) is in bytes
+                               keyLength <<= 3;
+                               LogDebug("RSA key length: " << keyLength << " bits");
+
+                               if (keyLength < MIN_RSA_KEY_LENGTH) {
+                                       LogError("RSA key too short! Has only " << keyLength << " bits");
+                                       return CERTIFICATE_SECURITY_ERROR;
+                               }
+                       }
+               }
+       }
+
+       return NO_ERROR;
+}
+
+CertificateLoader::CertificateLoaderResult CertificateLoader::
+loadCertificateBasedOnDSAComponents(const std::string &strP,
+                                                                       const std::string &strQ,
+                                                                       const std::string &strG,
+                                                                       const std::string &strY,
+                                                                       const std::string &strJ,
+                                                                       const std::string &strSeed,
+                                                                       const std::string &strPGenCounter)
+{
+       (void) strP;
+       (void) strQ;
+       (void) strG;
+       (void) strY;
+       (void) strJ;
+       (void) strSeed;
+       (void) strPGenCounter;
+       LogError("Not implemented.");
+       return UNKNOWN_ERROR;
+}
+
+bool CertificateLoader::convertBase64NodeToBigNum(const std::string &strNode,
+               BIGNUM **ppBigNum)
+{
+       (void) strNode;
+       (void) ppBigNum;
+       LogError("Not implemented.");
+       return false;
+}
+
+} // namespace ValidationCore
+
diff --git a/src/vcore/CertificateLoader.h b/src/vcore/CertificateLoader.h
new file mode 100644 (file)
index 0000000..d87ed7b
--- /dev/null
@@ -0,0 +1,102 @@
+/*
+ * Copyright (c) 2011 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.
+ */
+#ifndef _CERTIFICATELOADER_H_
+#define _CERTIFICATELOADER_H_
+
+#include <string>
+#include <string.h>
+
+#include <openssl/ssl.h>
+
+#include <vcore/Certificate.h>
+
+namespace ValidationCore {
+class CertificateLoader {
+public:
+       CertificateLoader() = default;
+       virtual ~CertificateLoader() = default;
+
+       CertificateLoader(const CertificateLoader &) = delete;
+       CertificateLoader &operator=(const CertificateLoader &) = delete;
+       CertificateLoader(CertificateLoader &&) = delete;
+       CertificateLoader &operator=(CertificateLoader &&) = delete;
+
+       class CertificateLoaderComparator {
+       public:
+               virtual bool compare(X509 *x509cert) = 0;
+               virtual ~CertificateLoaderComparator() = default;
+       };
+
+       enum CertificateLoaderResult {
+               NO_ERROR,
+               CERTIFICATE_NOT_FOUND,
+               UNSUPPORTED_CERTIFICATE_FIELD,
+               WRONG_ARGUMENTS,
+               CERTIFICATE_SECURITY_ERROR,                  //!< there are some issues with certificate security (i.e. key too short)
+               UNKNOWN_ERROR
+       };
+
+       CertificateLoaderResult loadCertificate(const std::string &storage,
+                                                                                       CertificateLoaderComparator *cmp);
+
+       CertificateLoaderResult loadCertificateBasedOnSubjectName(
+               const std::string &subjectName);
+       CertificateLoaderResult loadCertificateBasedOnExponentAndModulus(
+               const std::string &m_modulus,
+               const std::string  &m_exponent);
+       // KW     CertificateLoaderResult loadCertificateBasedOnIssuerName(const std::string &isserName,
+       // KW       const std::string &serialNumber);
+
+       CertificateLoaderResult loadCertificateFromRawData(
+               const std::string &rawData);
+
+       CertificateLoaderResult loadCertificateBasedOnDSAComponents(
+               const std::string &strP,
+               const std::string &strQ,
+               const std::string &strG,
+               const std::string &strY,
+               const std::string &strJ,
+               const std::string &strSeed,
+               const std::string &strPGenCounter);
+
+       CertificateLoaderResult loadCertificateWithECKEY(
+               const std::string &curveName,
+               const std::string &publicKey);
+
+       /**
+        * converts base64 encoded node to SSL bignum
+        * allocates mem on *ppBigNum, don't forget to free it later with BN_free!
+        * returns conversion status
+        */
+       static bool convertBase64NodeToBigNum(const std::string &strNode,
+                                                                                 BIGNUM **ppBigNum);
+
+       /*
+        * encodes SSL bignum into base64 octstring
+        * returns conversion status
+        */
+       // KW     static bool convertBigNumToBase64Node(const BIGNUM* pBigNum, std::string& strNode);
+
+       CertificatePtr getCertificatePtr() const
+       {
+               return m_certificatePtr;
+       }
+private:
+       CertificatePtr m_certificatePtr;
+};
+} // namespace ValidationCore
+
+#endif // _CERTIFICATELOADER_H_
diff --git a/src/vcore/Client.cpp b/src/vcore/Client.cpp
new file mode 100644 (file)
index 0000000..d0f48ae
--- /dev/null
@@ -0,0 +1,674 @@
+/**
+ * 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     Client.cpp
+ * @author   Madhan A K (madhan.ak@samsung.com)
+ *           Kyungwook Tak (k.tak@samsung.com)
+ * @version  1.0
+ * @brief    cert-svc client interface for cert-server.
+ */
+
+#include <sys/stat.h>
+#include <sys/un.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <errno.h>
+#include <unistd.h>
+#include <string.h>
+#include <stdlib.h>
+#include <memory>
+
+#include <dpl/log/log.h>
+
+#include <vcore/Client.h>
+
+namespace {
+
+void initialize_res_data(VcoreResponseData *pData)
+{
+       memset(pData->dataBlock, 0, VCORE_MAX_RECV_DATA_SIZE);
+       memset(pData->common_name, 0, VCORE_MAX_FILENAME_SIZE * 2 + 1);
+       pData->dataBlockLen = 0;
+       pData->certStatus = DISABLED;
+       pData->result = 0;
+       pData->isAliasUnique = 0;
+       pData->certList = NULL;
+       pData->certCount = 0;
+       pData->certBlockList = NULL;
+       pData->certBlockCount = 0;
+}
+
+void initialize_req_data(VcoreRequestData *pData)
+{
+       memset(pData->gname, 0, VCORE_MAX_FILENAME_SIZE + 1);
+       memset(pData->common_name, 0, VCORE_MAX_FILENAME_SIZE + 1);
+       memset(pData->private_key_gname, 0, VCORE_MAX_FILENAME_SIZE + 1);
+       memset(pData->associated_gname, 0, VCORE_MAX_FILENAME_SIZE + 1);
+       memset(pData->dataBlock, 0, VCORE_MAX_SEND_DATA_SIZE);
+       pData->certStatus = DISABLED;
+       pData->storeType = NONE_STORE;
+       pData->reqType = (VcoreRequestType) - 1;
+       pData->dataBlockLen = 0;
+       pData->is_root_app = -1;
+       pData->certType = INVALID_DATA;
+}
+
+CertSvcStoreCertList *createStoreListNode(VcoreCertResponseData *cert)
+{
+       if (cert == NULL)
+               return NULL;
+
+       CertSvcStoreCertList *node = (CertSvcStoreCertList *)malloc(sizeof(CertSvcStoreCertList));
+
+       if (node == NULL)
+               return NULL;
+
+       node->gname = strdup(cert->gname);
+       node->title = strdup(cert->title);
+       node->status = cert->status;
+       node->storeType = cert->storeType;
+       node->next = NULL;
+
+       if (node->gname == NULL || node->title == NULL) {
+               free(node->gname);
+               free(node->title);
+               free(node);
+               return NULL;
+       }
+
+       return node;
+}
+
+void destroyStoreList(CertSvcStoreCertList *list)
+{
+       while (list) {
+               CertSvcStoreCertList *next = list->next;
+               free(list);
+               list = next;
+       }
+}
+
+
+int _recv_fixed_lenghth(int sockfd, char *buff, int length)
+{
+       int offset = 0;
+       int remaining = length;
+       int read_len = 0;
+
+       while (remaining > 0) {
+               read_len = recv(sockfd, buff + offset, remaining, 0);
+
+               if (read_len <= 0)
+                       return offset;
+
+               remaining -= read_len;
+               offset += read_len;
+       }
+
+       return offset;
+}
+
+VcoreRequestData *set_request_data(
+       VcoreRequestType reqType,
+       CertStoreType storeType,
+       int is_root_app,
+       const char *pGroupName,
+       const char *common_name,
+       const char *private_key_gname,
+       const char *associated_gname,
+       const char *pData,
+       size_t dataLen,
+       CertType certType,
+       CertStatus certStatus)
+{
+       VcoreRequestData *pReqData = (VcoreRequestData *)malloc(sizeof(VcoreRequestData));
+
+       if (!pReqData) {
+               LogError("Failed to malloc VcoreRequestData");
+               return NULL;
+       }
+
+       initialize_req_data(pReqData);
+       pReqData->reqType = reqType;
+       pReqData->storeType = (CertStoreType) storeType;
+       pReqData->dataBlockLen = dataLen;
+       pReqData->certType = certType;
+       pReqData->certStatus = certStatus;
+       pReqData->is_root_app = is_root_app;
+
+       if (pGroupName) {
+               if (strlen(pGroupName) > VCORE_MAX_FILENAME_SIZE) {
+                       LogError("The data name is too long");
+                       free(pReqData);
+                       return NULL;
+               }
+
+               strncpy(pReqData->gname, pGroupName, VCORE_MAX_FILENAME_SIZE);
+               pReqData->gname[strlen(pGroupName)] = '\0';
+       }
+
+       if (common_name) {
+               if (strlen(common_name) > VCORE_MAX_FILENAME_SIZE) {
+                       LogError("The length of the path specified is too long");
+                       free(pReqData);
+                       return NULL;
+               }
+
+               strncpy(pReqData->common_name, common_name, VCORE_MAX_FILENAME_SIZE);
+               pReqData->common_name[strlen(common_name)] = '\0';
+       }
+
+       if (private_key_gname) {
+               if (strlen(private_key_gname) > VCORE_MAX_FILENAME_SIZE) {
+                       LogError("The private key gname is too long");
+                       free(pReqData);
+                       return NULL;
+               }
+
+               strncpy(pReqData->private_key_gname, private_key_gname, VCORE_MAX_FILENAME_SIZE);
+               pReqData->private_key_gname[strlen(private_key_gname)] = '\0';
+       }
+
+       if (associated_gname) {
+               if (strlen(associated_gname) > VCORE_MAX_FILENAME_SIZE) {
+                       LogError("The associated gname is too long");
+                       free(pReqData);
+                       return NULL;
+               }
+
+               strncpy(pReqData->associated_gname, associated_gname, VCORE_MAX_FILENAME_SIZE);
+               pReqData->associated_gname[strlen(associated_gname)] = '\0';
+       }
+
+       if (dataLen != 0 && pData != NULL) {
+               if (dataLen > VCORE_MAX_SEND_DATA_SIZE) {
+                       LogError("The data length is too long : " << dataLen);
+                       free(pReqData);
+                       return NULL;
+               }
+
+               memcpy(pReqData->dataBlock, pData, dataLen);
+       }
+
+       return pReqData;
+}
+
+VcoreResponseData cert_svc_client_comm(VcoreRequestData *pClientData)
+{
+       int sockfd = 0;
+       int clientLen = 0;
+       int tempSockLen = 0;
+       int read_len = 0;
+       size_t i = 0;
+       struct sockaddr_un clientaddr;
+       VcoreResponseData recvData;
+       initialize_res_data(&recvData);
+
+       if ((sockfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
+               LogError("Error in function socket()..");
+               recvData.result = VCORE_SOCKET_ERROR;
+               goto Error_exit;
+       }
+
+       tempSockLen = strlen(VCORE_SOCK_PATH);
+       bzero(&clientaddr, sizeof(clientaddr));
+       clientaddr.sun_family = AF_UNIX;
+       strncpy(clientaddr.sun_path, VCORE_SOCK_PATH, tempSockLen);
+       clientaddr.sun_path[tempSockLen] = '\0';
+       clientLen = sizeof(clientaddr);
+       struct timeval timeout;
+       timeout.tv_sec = 10;
+       timeout.tv_usec = 0;
+
+       if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)) < 0) {
+               LogError("Error in Set SO_RCVTIMEO Socket Option");
+               recvData.result = VCORE_SOCKET_ERROR;
+               goto Error_close_exit;
+       }
+
+       if (setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(timeout)) < 0) {
+               LogError("Error in Set SO_SNDTIMEO Socket Option");
+               recvData.result = VCORE_SOCKET_ERROR;
+               goto Error_close_exit;
+       }
+
+       if (connect(sockfd, (struct sockaddr *)&clientaddr, clientLen) < 0) {
+               LogError("Error in function connect()..");
+               recvData.result = VCORE_SOCKET_ERROR;
+               goto Error_close_exit;
+       }
+
+       if (write(sockfd, (char *)pClientData, sizeof(VcoreRequestData)) < 0) {
+               LogError("Error in function write()..");
+               recvData.result = VCORE_SOCKET_ERROR;
+               goto Error_close_exit;
+       }
+
+       read_len = _recv_fixed_lenghth(sockfd, (char *)&recvData, sizeof(recvData));
+
+       if (read_len < 0) {
+               LogError("Error in function read()..");
+               recvData.result = VCORE_SOCKET_ERROR;
+               goto Error_close_exit;
+       }
+
+       if (recvData.certCount > 0) {
+               recvData.certList = (VcoreCertResponseData *) malloc(recvData.certCount * sizeof(
+                                                               VcoreCertResponseData));
+
+               if (!recvData.certList) {
+                       LogError("Failed to allocate memory");
+                       recvData.result = VCORE_SOCKET_ERROR;
+                       goto Error_close_exit;
+               }
+
+               memset(recvData.certList, 0x00, recvData.certCount * sizeof(VcoreCertResponseData));
+
+               for (i = 0; i < recvData.certCount; i++) {
+                       read_len = _recv_fixed_lenghth(sockfd, (char *)(recvData.certList + i),
+                                                                                  sizeof(VcoreCertResponseData));
+
+                       if (read_len < 0) {
+                               LogError("Error in function read()..");
+                               recvData.result = VCORE_SOCKET_ERROR;
+                               goto Error_close_exit;
+                       }
+               }
+       }
+
+       if (recvData.certBlockCount > 0) {
+               recvData.certBlockList = (ResponseCertBlock *) malloc(recvData.certBlockCount * sizeof(
+                                                                        ResponseCertBlock));
+
+               if (!recvData.certBlockList) {
+                       LogError("Failed to allocate memory");
+                       recvData.result = VCORE_SOCKET_ERROR;
+                       goto Error_close_exit;
+               }
+
+               memset(recvData.certBlockList, 0x00, recvData.certBlockCount * sizeof(ResponseCertBlock));
+
+               for (i = 0; i < recvData.certBlockCount; i++) {
+                       read_len = _recv_fixed_lenghth(sockfd, (char *)(recvData.certBlockList + i),
+                                                                                  sizeof(ResponseCertBlock));
+
+                       if (read_len < 0) {
+                               LogError("Error in function read()..");
+                               recvData.result = VCORE_SOCKET_ERROR;
+                               goto Error_close_exit;
+                       }
+               }
+       }
+
+Error_close_exit:
+       close(sockfd);
+
+       if (recvData.result == VCORE_SOCKET_ERROR) {
+               free(recvData.certList);
+               recvData.certList = NULL;
+               recvData.certCount = 0;
+               free(recvData.certBlockList);
+               recvData.certBlockList = NULL;
+               recvData.certBlockCount = 0;
+       }
+
+Error_exit:
+       return recvData;
+}
+
+} /* anonymous namespace */
+
+
+int vcore_client_install_certificate_to_store(
+       CertStoreType storeType,
+       const char *gname,
+       const char *common_name,
+       const char *private_key_gname,
+       const char *associated_gname,
+       const char *certData,
+       size_t certSize,
+       CertType certType)
+{
+       VcoreRequestData *pSendData = NULL;
+       VcoreResponseData recvData;
+       initialize_res_data(&recvData);
+
+       if (!gname && !certData) {
+               LogError("Invalid input argument.");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       pSendData = set_request_data(
+                                       CERTSVC_INSTALL_CERTIFICATE,
+                                       storeType,
+                                       DISABLED,
+                                       gname,
+                                       common_name,
+                                       private_key_gname,
+                                       associated_gname,
+                                       certData,
+                                       certSize,
+                                       certType,
+                                       DISABLED);
+
+       if (pSendData == NULL) {
+               LogError("Failed to set request data");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       recvData = cert_svc_client_comm(pSendData);
+       free(pSendData);
+       return recvData.result;
+}
+
+int vcore_client_set_certificate_status_to_store(CertStoreType storeType, int is_root_app,
+               const char *gname, CertStatus status)
+{
+       VcoreRequestData *pSendData = NULL;
+       VcoreResponseData recvData;
+       initialize_res_data(&recvData);
+
+       if (gname == NULL) {
+               LogError("Invalid input parameter.");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       pSendData = set_request_data(CERTSVC_SET_CERTIFICATE_STATUS, storeType, is_root_app, gname, NULL,
+                                                                NULL, NULL, NULL, 0, INVALID_DATA, status);
+
+       if (pSendData == NULL) {
+               LogError("Failed to set request data");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       recvData = cert_svc_client_comm(pSendData);
+       free(pSendData);
+       return recvData.result;
+}
+
+int vcore_client_get_certificate_status_from_store(CertStoreType storeType, const char *gname,
+               CertStatus *status)
+{
+       VcoreRequestData *pSendData = NULL;
+       VcoreResponseData recvData;
+       initialize_res_data(&recvData);
+
+       if (gname == NULL) {
+               LogError("Invalid input parameter.");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       pSendData = set_request_data(CERTSVC_GET_CERTIFICATE_STATUS, storeType, DISABLED, gname, NULL, NULL,
+                                                                NULL, NULL, 0, INVALID_DATA, DISABLED);
+
+       if (pSendData == NULL) {
+               LogError("Failed to set request data");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       recvData = cert_svc_client_comm(pSendData);
+       free(pSendData);
+       *status = recvData.certStatus;
+       return recvData.result;
+}
+
+int vcore_client_check_alias_exist_in_store(CertStoreType storeType, const char *alias,
+               int *isUnique)
+{
+       VcoreRequestData *pSendData = NULL;
+       VcoreResponseData recvData;
+       initialize_res_data(&recvData);
+
+       if (alias == NULL) {
+               LogError("Invalid input parameter.");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       pSendData = set_request_data(CERTSVC_CHECK_ALIAS_EXISTS, storeType, DISABLED, alias, NULL, NULL,
+                                                                NULL, NULL, 0, INVALID_DATA, DISABLED);
+
+       if (pSendData == NULL) {
+               LogError("Failed to set request data");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       recvData = cert_svc_client_comm(pSendData);
+       free(pSendData);
+       *isUnique = recvData.isAliasUnique;
+       return recvData.result;
+}
+
+int vcore_client_get_certificate_from_store(CertStoreType storeType, const char *gname,
+               char **certData, size_t *certSize, CertType certType)
+{
+       char *outData = NULL;
+       VcoreRequestData *pSendData = NULL;
+       VcoreResponseData recvData;
+
+       if (!gname || !certData || !certSize) {
+               LogError("Invalid input argument.");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       initialize_res_data(&recvData);
+
+       if (storeType == SYSTEM_STORE)  /* for extracting certificate from system store */
+               pSendData = set_request_data(CERTSVC_EXTRACT_SYSTEM_CERT, storeType, DISABLED, gname, NULL, NULL,
+                                                                        NULL, NULL, 0, certType, DISABLED);
+       else /* for extracting certificate from other stores */
+               pSendData = set_request_data(CERTSVC_EXTRACT_CERT, storeType, DISABLED, gname, NULL, NULL, NULL,
+                                                                        NULL, 0, certType, DISABLED);
+
+       if (pSendData == NULL) {
+               LogError("Failed to set request data.");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       recvData = cert_svc_client_comm(pSendData);
+
+       if (recvData.result < 0) {
+               LogError("An error occurred from server side err : " << recvData.result);
+               free(pSendData);
+               return recvData.result;
+       }
+
+       free(pSendData);
+
+       if (recvData.dataBlockLen > 0 && recvData.dataBlockLen <= VCORE_MAX_RECV_DATA_SIZE) {
+               outData = (char *)malloc(recvData.dataBlockLen + 1);
+               if (outData == nullptr)
+                       return CERTSVC_BAD_ALLOC;
+
+               memset(outData, 0x00, recvData.dataBlockLen + 1);
+               memcpy(outData, recvData.dataBlock, recvData.dataBlockLen);
+               *certData = outData;
+               *certSize = recvData.dataBlockLen;
+
+               return recvData.result;
+       } else {
+               LogError("revcData length is wrong : " << recvData.dataBlockLen);
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+}
+
+int vcore_client_delete_certificate_from_store(CertStoreType storeType, const char *gname)
+{
+       VcoreRequestData *pSendData = NULL;
+       VcoreResponseData recvData;
+       initialize_res_data(&recvData);
+
+       if (gname == NULL) {
+               LogError("Invalid input parameter.");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       pSendData = set_request_data(CERTSVC_DELETE_CERT, storeType, DISABLED, gname, NULL, NULL, NULL,
+                                                                NULL, 0, INVALID_DATA, DISABLED);
+
+       if (pSendData == NULL) {
+               LogError("Failed to set request data");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       recvData = cert_svc_client_comm(pSendData);
+       free(pSendData);
+       return recvData.result;
+}
+
+int _vcore_client_get_certificate_list_from_store(VcoreRequestType reqType, CertStoreType storeType,
+               int is_root_app,
+               CertSvcStoreCertList **certList, size_t *length)
+{
+       std::unique_ptr<VcoreRequestData, void(*)(void *)> pSendData(set_request_data(
+                               reqType, storeType, is_root_app,
+                               NULL, NULL, NULL, NULL, NULL, 0, INVALID_DATA, DISABLED), free);
+
+       if (!pSendData) {
+               LogError("Failed to set request data");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       VcoreResponseData recvData;
+       initialize_res_data(&recvData);
+       recvData = cert_svc_client_comm(pSendData.get());
+       CertSvcStoreCertList *curr = NULL;
+       CertSvcStoreCertList *prev = NULL;
+       CertSvcStoreCertList *list = NULL;
+
+       for (size_t i = 0; i < recvData.certCount; i++) {
+               curr = createStoreListNode(recvData.certList + i);
+
+               if (curr == NULL) {
+                       destroyStoreList(list);
+                       free(recvData.certList);
+                       return CERTSVC_BAD_ALLOC;
+               }
+
+               if (list == NULL)
+                       list = curr;
+               else
+                       prev->next = curr;
+
+               prev = curr;
+       }
+
+       *length = recvData.certCount;
+       *certList = list;
+       LogDebug("get_certificate_list_from_store: result : " << recvData.result);
+       free(recvData.certList);
+       return recvData.result;
+}
+
+int vcore_client_get_certificate_list_from_store(CertStoreType storeType, int is_root_app,
+               CertSvcStoreCertList **certList, size_t *length)
+{
+       return _vcore_client_get_certificate_list_from_store(CERTSVC_GET_CERTIFICATE_LIST, storeType,
+                       is_root_app,
+                       certList, length);
+}
+
+int vcore_client_get_root_certificate_list_from_store(CertStoreType storeType,
+               CertSvcStoreCertList **certList, size_t *length)
+{
+       return _vcore_client_get_certificate_list_from_store(CERTSVC_GET_ROOT_CERTIFICATE_LIST, storeType,
+                       0,
+                       certList, length);
+}
+
+int vcore_client_get_end_user_certificate_list_from_store(CertStoreType storeType,
+               CertSvcStoreCertList **certList, size_t *length)
+{
+       return _vcore_client_get_certificate_list_from_store(CERTSVC_GET_USER_CERTIFICATE_LIST, storeType,
+                       0,
+                       certList, length);
+}
+
+int vcore_client_get_certificate_alias_from_store(CertStoreType storeType, const char *gname,
+               char **alias)
+{
+       VcoreRequestData *pSendData = NULL;
+       VcoreResponseData recvData;
+       initialize_res_data(&recvData);
+
+       if (gname == NULL) {
+               LogError("Invalid input parameter.");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       pSendData = set_request_data(CERTSVC_GET_CERTIFICATE_ALIAS, storeType, DISABLED, gname, NULL, NULL,
+                                                                NULL, NULL, 0, INVALID_DATA, DISABLED);
+
+       if (pSendData == NULL) {
+               LogError("Failed to set request data");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       recvData = cert_svc_client_comm(pSendData);
+       *alias = strndup(recvData.common_name, sizeof(recvData.common_name));
+       free(pSendData);
+       return recvData.result;
+}
+
+int vcore_client_load_certificates_from_store(CertStoreType storeType, const char *gname,
+               char ***certs, size_t *ncerts)
+{
+       VcoreResponseData recvData;
+       ResponseCertBlock *cert = NULL;
+       size_t i = 0;
+       size_t ncerts_out = 0;
+       char **certs_out = NULL;
+       initialize_res_data(&recvData);
+       std::unique_ptr<VcoreRequestData, void(*)(void *)> pSendData(set_request_data(
+                               CERTSVC_LOAD_CERTIFICATES, storeType, DISABLED, gname,
+                               NULL, NULL, NULL, NULL, 0, INVALID_DATA, DISABLED), free);
+
+       if (!pSendData) {
+               LogError("Failed to set request data");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       recvData = cert_svc_client_comm(pSendData.get());
+
+       if (recvData.result != CERTSVC_SUCCESS) {
+               LogError("Failed to CERTSVC_LOAD_CERTIFICATES. server retcode : " << recvData.result);
+               return recvData.result;
+       }
+
+       ncerts_out = recvData.certBlockCount;
+
+       if (ncerts_out == 0) {
+               LogError("No certificates exist with gname[" << gname << "] in store[" << storeType << "]");
+               return CERTSVC_ALIAS_DOES_NOT_EXIST;
+       }
+
+       certs_out = (char **)malloc((ncerts_out + 1) * sizeof(char *));
+
+       if (certs_out == NULL)
+               return CERTSVC_BAD_ALLOC;
+
+       certs_out[ncerts_out] = NULL;
+
+       for (i = 0; i < recvData.certBlockCount; i++) {
+               cert = recvData.certBlockList + i;
+               certs_out[i] = strndup(cert->dataBlock, cert->dataBlockLen);
+               LogDebug("vcore_client_load_certificates_from_store. cert[" << certs_out[i] << "]");
+       }
+
+       *certs = certs_out;
+       *ncerts = ncerts_out;
+       free(recvData.certBlockList);
+       return recvData.result;
+}
diff --git a/src/vcore/Client.h b/src/vcore/Client.h
new file mode 100644 (file)
index 0000000..0e62cf2
--- /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        Client.h
+ * @author      Madhan A K (madhan.ak@samsung.com)
+ * @version     1.0
+ * @brief       cert-svc client interface for cert-server.
+ */
+
+#ifndef CERT_SVC_CLIENT_H_
+#define CERT_SVC_CLIENT_H_
+
+#include <cert-svc/cerror.h>
+#include <cert-svc/ccert.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define VCORE_MAX_FILENAME_SIZE     128
+#define VCORE_MAX_RECV_DATA_SIZE    8192    //4096, internal buffer = 4KB*2. /*Note:system store cert size is bigger than 4KB*/
+#define VCORE_MAX_SEND_DATA_SIZE    8192    //4096, internal buffer = 4KB*2.
+#define VCORE_MAX_GROUP_ID_SIZE     32
+#define VCORE_MAX_APPID_SIZE        32
+#define VCORE_MAX_PASSWORD_SIZE     32
+#define VCORE_SOCKET_ERROR          (-0x01C10000) // TIZEN_ERROR_CONNECTION  /*Connection error*/
+#define VCORE_SOCK_PATH             SERVER_STREAM
+#define VCORE_PKEY_TEMP_PATH        "/tmp/tmpData"
+
+typedef enum {
+       CERTSVC_EXTRACT_CERT,
+       CERTSVC_EXTRACT_SYSTEM_CERT,
+       CERTSVC_DELETE_CERT,
+       CERTSVC_INSTALL_CERTIFICATE,
+       CERTSVC_GET_CERTIFICATE_STATUS,
+       CERTSVC_SET_CERTIFICATE_STATUS,
+       CERTSVC_CHECK_ALIAS_EXISTS,
+       CERTSVC_GET_CERTIFICATE_LIST,
+       CERTSVC_GET_CERTIFICATE_ALIAS,
+       CERTSVC_GET_USER_CERTIFICATE_LIST,
+       CERTSVC_GET_ROOT_CERTIFICATE_LIST,
+       CERTSVC_LOAD_CERTIFICATES,
+} VcoreRequestType;
+
+typedef struct {
+       VcoreRequestType reqType;
+       CertStoreType    storeType;
+       char             gname[VCORE_MAX_FILENAME_SIZE * 2 + 1]; /* for gname */
+       char             common_name[VCORE_MAX_FILENAME_SIZE * 2 + 1]; /* for common_name */
+       char             private_key_gname[VCORE_MAX_FILENAME_SIZE * 2 + 1]; /* for private_key_gname */
+       char             associated_gname[VCORE_MAX_FILENAME_SIZE * 2 + 1]; /* for associated_gname */
+       char             dataBlock[VCORE_MAX_SEND_DATA_SIZE];    /* for cert & key buffer */
+       size_t           dataBlockLen;
+       CertStatus       certStatus;
+       int              is_root_app;
+       CertType         certType;
+} VcoreRequestData;
+
+typedef struct {
+       char             gname[VCORE_MAX_FILENAME_SIZE * 2 + 1];
+       char             title[VCORE_MAX_FILENAME_SIZE * 2 + 1];
+       CertStatus       status;
+       CertStoreType    storeType;
+} VcoreCertResponseData;
+
+
+typedef struct {
+       char             dataBlock[VCORE_MAX_RECV_DATA_SIZE];
+       size_t           dataBlockLen;
+} ResponseCertBlock;
+
+typedef struct {
+       char                   dataBlock[VCORE_MAX_RECV_DATA_SIZE];
+       size_t                 dataBlockLen;
+       CertStatus             certStatus;
+       char                   common_name[VCORE_MAX_FILENAME_SIZE * 2 + 1]; /*for common_name*/
+       int                    result;
+       int                    isAliasUnique;
+       size_t                 certCount;
+       VcoreCertResponseData *certList;
+       size_t                 certBlockCount;
+       ResponseCertBlock     *certBlockList; // array
+} VcoreResponseData;
+
+
+
+int vcore_client_set_certificate_status_to_store(CertStoreType storeType, int is_root_app,
+               const char *gname, CertStatus status);
+int vcore_client_get_certificate_status_from_store(CertStoreType storeType, const char *gname,
+               CertStatus *status);
+int vcore_client_check_alias_exist_in_store(CertStoreType storeType, const char *alias,
+               int *isUnique);
+int vcore_client_install_certificate_to_store(CertStoreType storeType, const char *gname,
+               const char *common_name, const char *private_key_gname, const char *associated_gname,
+               const char *dataBlock, size_t dataBlockLen, CertType certType);
+int vcore_client_get_certificate_from_store(CertStoreType storeType, const char *gname,
+               char **certData, size_t *certSize, CertType certType);
+int vcore_client_delete_certificate_from_store(CertStoreType storeType, const char *gname);
+int vcore_client_get_certificate_list_from_store(CertStoreType storeType, int is_root_app,
+               CertSvcStoreCertList **certList, size_t *length);
+int vcore_client_get_root_certificate_list_from_store(CertStoreType storeType,
+               CertSvcStoreCertList **certList, size_t *length);
+int vcore_client_get_end_user_certificate_list_from_store(CertStoreType storeType,
+               CertSvcStoreCertList **certList, size_t *length);
+int vcore_client_get_certificate_alias_from_store(CertStoreType storeType, const char *gname,
+               char **alias);
+int vcore_client_load_certificates_from_store(CertStoreType storeType, const char *gname,
+               char ***certs, size_t *ncerts);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif
diff --git a/src/vcore/CryptoInit.cpp b/src/vcore/CryptoInit.cpp
new file mode 100644 (file)
index 0000000..b1ad4cf
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+ * 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        CryptoInit.cpp
+ * @author      Kyungwook Tak (k.tak@samsung.com)
+ * @version     1.0
+ * @brief       Initialize openssl functions by singleton
+ */
+
+#include <openssl/ssl.h>
+
+#include <dpl/singleton_impl.h>
+
+#include <vcore/CryptoInit.h>
+
+IMPLEMENT_SINGLETON(ValidationCore::CryptoInit)
+
+namespace ValidationCore {
+
+CryptoInit::CryptoInit()
+{
+       SSL_load_error_strings();
+       SSL_library_init();
+}
+
+CryptoInit::~CryptoInit()
+{
+}
+
+} // namespace ValidationCore
diff --git a/src/vcore/CryptoInit.h b/src/vcore/CryptoInit.h
new file mode 100644 (file)
index 0000000..05f8c62
--- /dev/null
@@ -0,0 +1,41 @@
+/*
+ * 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        CryptoInit.h
+ * @author      Kyungwook Tak (k.tak@samsung.com)
+ * @version     1.0
+ * @brief       Initialize openssl functions by singleton
+ */
+#pragma once
+
+#include <dpl/singleton.h>
+
+namespace ValidationCore {
+
+class CryptoInit {
+public:
+       CryptoInit();
+       virtual ~CryptoInit();
+
+       CryptoInit(const CryptoInit &) = delete;
+       CryptoInit &operator=(const CryptoInit &) = delete;
+       CryptoInit(CryptoInit &&) = delete;
+       CryptoInit &operator=(CryptoInit &&) = delete;
+};
+
+typedef VcoreDPL::Singleton<CryptoInit> CryptoInitSingleton;
+
+} // namespace ValidationCore
diff --git a/src/vcore/Error.h b/src/vcore/Error.h
new file mode 100644 (file)
index 0000000..358f5c5
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * 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        Error.h
+ * @author      Kyungwook Tak (k.tak@samsung.com)
+ * @version     1.0
+ * @brief       Error codes of signature validator.
+ */
+#pragma once
+
+namespace ValidationCore {
+
+using VCerr = int;
+
+const VCerr E_SIG_NONE           = 0;
+const VCerr E_SIG_INVALID_FORMAT = -1;
+const VCerr E_SIG_INVALID_CERT   = -2;
+const VCerr E_SIG_INVALID_CHAIN  = -3;
+const VCerr E_SIG_INVALID_SIG    = -4;
+const VCerr E_SIG_INVALID_REF    = -5;
+const VCerr E_SIG_CERT_EXPIRED   = -6;
+const VCerr E_SIG_CERT_NOT_YET   = -7;
+const VCerr E_SIG_DISREGARDED    = -8;
+const VCerr E_SIG_REVOKED        = -9;
+const VCerr E_SIG_PLUGIN         = -10;
+const VCerr E_SIG_OUT_OF_MEM     = -11;
+const VCerr E_SIG_UNKNOWN        = -12;
+
+const VCerr E_SCOPE_FIRST        = E_SIG_INVALID_FORMAT;
+const VCerr E_SCOPE_LAST         = E_SIG_UNKNOWN;
+
+}
diff --git a/src/vcore/Ocsp.cpp b/src/vcore/Ocsp.cpp
new file mode 100644 (file)
index 0000000..ae1dc87
--- /dev/null
@@ -0,0 +1,338 @@
+/*
+ *  Copyright (c) 2015 Samsung Electronics Co.
+ *
+ *  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        Ocsp.cpp
+ * @author      Kyungwook Tak (k.tak@samsung.com)
+ * @version     1.0
+ * @brief       OCSP check for signature validator. It should be used only internally.
+ */
+
+#include <memory>
+#include <functional>
+
+#include <openssl/ssl.h>
+#include <openssl/ocsp.h>
+#include <openssl/err.h>
+
+#include <dpl/log/log.h>
+#include <vcore/CryptoInit.h>
+
+#include <vcore/Ocsp.h>
+
+/* Maximum leeway in validity period : 5 minitues as a default */
+#define MAX_VALIDITY_PERIOD (5 * 60)
+
+namespace {
+
+typedef std::unique_ptr<X509_STORE_CTX, std::function<void(X509_STORE_CTX *)>> X509_STORE_CTX_PTR;
+typedef std::unique_ptr<STACK_OF(X509), std::function<void(STACK_OF(X509) *)>> X509_STACK_PTR;
+typedef std::unique_ptr<X509_STORE,     std::function<void(X509_STORE *)>> X509_STORE_PTR;
+typedef std::unique_ptr<SSL_CTX,        std::function<void(SSL_CTX *)>> SSL_CTX_PTR;
+typedef std::unique_ptr<BIO,            std::function<void(BIO *)>> BIO_PTR;
+typedef std::unique_ptr<char,           std::function<void(void *)>> RAIIstr;
+typedef std::unique_ptr<OCSP_REQUEST,   std::function<void(OCSP_REQUEST *)>> OCSP_REQUEST_PTR;
+typedef std::unique_ptr<OCSP_RESPONSE,  std::function<void(OCSP_RESPONSE *)>> OCSP_RESPONSE_PTR;
+typedef std::unique_ptr<OCSP_BASICRESP, std::function<void(OCSP_BASICRESP *)>> OCSP_BASICRESP_PTR;
+
+inline X509_STACK_PTR create_x509_stack()
+{
+       return X509_STACK_PTR(sk_X509_new_null(), [](STACK_OF(X509) * stack) {
+               sk_X509_free(stack);
+       });
+}
+
+inline X509_STORE_CTX_PTR create_x509_store_ctx()
+{
+       return X509_STORE_CTX_PTR(X509_STORE_CTX_new(), X509_STORE_CTX_free);
+}
+
+inline X509_STORE_PTR create_x509_store()
+{
+       return X509_STORE_PTR(X509_STORE_new(), X509_STORE_free);
+}
+
+inline SSL_CTX_PTR create_SSL_CTX()
+{
+       return SSL_CTX_PTR(SSL_CTX_new(SSLv23_client_method()), SSL_CTX_free);
+}
+
+inline RAIIstr create_RAIIstr(char *str)
+{
+       return RAIIstr(str, [](void *ptr) {
+               OPENSSL_free(ptr);
+       });
+}
+
+inline BIO_PTR create_BIO(BIO *bio)
+{
+       return BIO_PTR(bio, BIO_free_all);
+}
+
+inline OCSP_REQUEST_PTR create_OCSP_REQUEST()
+{
+       return OCSP_REQUEST_PTR(OCSP_REQUEST_new(), OCSP_REQUEST_free);
+}
+
+inline OCSP_RESPONSE_PTR create_OCSP_RESPONSE(OCSP_RESPONSE *resp)
+{
+       return OCSP_RESPONSE_PTR(resp, OCSP_RESPONSE_free);
+}
+
+inline OCSP_BASICRESP_PTR create_OCSP_BASICRESP(OCSP_BASICRESP *basicResp)
+{
+       return OCSP_BASICRESP_PTR(basicResp, OCSP_BASICRESP_free);
+}
+
+void BIO_write_and_free(BIO *bio)
+{
+       if (!bio)
+               return;
+
+       std::vector<char> message(1024);
+       int size = BIO_read(bio, message.data(), message.size());
+
+       if (size > 0) {
+               message.resize(size);
+               LogError("OCSP error description ["
+                                << std::string(message.begin(), message.end()) << "]");
+       }
+
+       BIO_free_all(bio);
+}
+
+} // namespace anonymous
+
+namespace ValidationCore {
+
+Ocsp::Ocsp()
+{
+}
+
+Ocsp::~Ocsp()
+{
+}
+
+Ocsp::Result checkInternal(
+       const CertificatePtr &_cert,
+       const CertificatePtr &_issuer,
+       X509_STACK_PTR &trustedCerts)
+{
+       /* initialize openssl library */
+       CryptoInitSingleton::Instance();
+       BIO_PTR bioLogger(BIO_new(BIO_s_mem()), BIO_write_and_free);
+       X509 *cert = _cert->getX509();
+       X509 *issuer = _issuer->getX509();
+       std::string ocspUrl = _cert->getOCSPURL();
+
+       if (ocspUrl.empty())
+               VcoreThrowMsg(Ocsp::Exception::OcspUnsupported,
+                                         "Certificate[" << _cert->getOneLine() << "] doesn't provide OCSP extension");
+
+       char *_ocspUrl = new char[ocspUrl.length() + 1];
+
+       if (_ocspUrl == NULL)
+               VcoreThrowMsg(Ocsp::Exception::UnknownError, "Failed to alloc memory");
+
+       strncpy(_ocspUrl, ocspUrl.c_str(), ocspUrl.length() + 1);
+       char *_host = NULL;
+       char *_port = NULL;
+       char *_path = NULL;
+       int use_ssl = 0;
+       int temp = OCSP_parse_url(_ocspUrl, &_host, &_port, &_path, &use_ssl);
+       LogDebug("ocspUrl[" << _ocspUrl
+                        << "] host[" << _host
+                        << "] port[" << _port
+                        << "] path[" << _path
+                        << "] use_ssl[" << use_ssl << "]");
+       delete []_ocspUrl;
+
+       if (temp == 0) {
+               ERR_print_errors(bioLogger.get());
+               VcoreThrowMsg(Ocsp::Exception::InvalidUrl, "ocsp url parsing failed. url : " << ocspUrl);
+       }
+
+       RAIIstr host = create_RAIIstr(_host);
+       RAIIstr port = create_RAIIstr(_port);
+       RAIIstr path = create_RAIIstr(_path);
+       BIO_PTR cbio = create_BIO(BIO_new_connect(host.get()));
+
+       if (cbio.get() == NULL) {
+               ERR_print_errors(bioLogger.get());
+               VcoreThrowMsg(Ocsp::Exception::UnknownError, "Failed to create bio connect");
+       }
+
+       if (port)
+               BIO_set_conn_port(cbio.get(), port.get());
+
+       if (use_ssl == 1) {
+               SSL_CTX_PTR ssl_ctx = create_SSL_CTX();
+
+               if (ssl_ctx.get() == NULL) {
+                       ERR_print_errors(bioLogger.get());
+                       VcoreThrowMsg(Ocsp::Exception::UnknownError, "Failed to SSL_CTX_new");
+               }
+
+               SSL_CTX_set_mode(ssl_ctx.get(), SSL_MODE_AUTO_RETRY);
+               BIO_PTR sbio = create_BIO(BIO_new_ssl(ssl_ctx.get(), 1));
+
+               if (sbio.get() == NULL) {
+                       ERR_print_errors(bioLogger.get());
+                       VcoreThrowMsg(Ocsp::Exception::UnknownError, "Failed to BIO_new_ssl");
+               }
+
+               cbio.reset(BIO_push(sbio.get(), cbio.get()));
+
+               if (cbio.get() == NULL) {
+                       ERR_print_errors(bioLogger.get());
+                       VcoreThrowMsg(Ocsp::Exception::UnknownError, "Failed to BIO_push");
+               }
+       }
+
+       if (BIO_do_connect(cbio.get()) <= 0) {
+               ERR_print_errors(bioLogger.get());
+               VcoreThrowMsg(Ocsp::Exception::NetworkError, "Failed to BIO_do_connect");
+       }
+
+       OCSP_REQUEST_PTR req = create_OCSP_REQUEST();
+
+       if (req.get() == NULL) {
+               ERR_print_errors(bioLogger.get());
+               VcoreThrowMsg(Ocsp::Exception::UnknownError, "Failed to OCSP_REQUEST_new");
+       }
+
+       OCSP_CERTID *certid = OCSP_cert_to_id(NULL, cert, issuer);
+
+       if (certid == NULL) {
+               ERR_print_errors(bioLogger.get());
+               VcoreThrowMsg(Ocsp::Exception::UnknownError, "Failed to OCSP_cert_to_id");
+       }
+
+       if (OCSP_request_add0_id(req.get(), certid) == NULL) {
+               ERR_print_errors(bioLogger.get());
+               VcoreThrowMsg(Ocsp::Exception::UnknownError, "Failed to OCSP_request_add0_id");
+       }
+
+       OCSP_RESPONSE_PTR resp =
+               create_OCSP_RESPONSE(OCSP_sendreq_bio(cbio.get(), path.get(), req.get()));
+
+       if (resp.get() == NULL) {
+               ERR_print_errors(bioLogger.get());
+               VcoreThrowMsg(Ocsp::Exception::NetworkError, "Failed to OCSP_sendreq_bio");
+       }
+
+       if (OCSP_response_status(resp.get()) != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
+               ERR_print_errors(bioLogger.get());
+               VcoreThrowMsg(Ocsp::Exception::ServerError, "Failed to OCSP_response_status");
+       }
+
+       OCSP_BASICRESP_PTR basicResp =
+               create_OCSP_BASICRESP(OCSP_response_get1_basic(resp.get()));
+
+       if (basicResp.get() == NULL) {
+               ERR_print_errors(bioLogger.get());
+               VcoreThrowMsg(Ocsp::Exception::InvalidResponse, "Failed to OCSP_response_get1_basic");
+       }
+
+       X509_STORE_PTR trustedStore = create_x509_store();
+
+       if (trustedCerts.get()) {
+               for (int idx = 0; idx < sk_X509_num(trustedCerts.get()); idx++)
+                       X509_STORE_add_cert(trustedStore.get(), sk_X509_value(trustedCerts.get(), idx));
+
+               X509_STORE_add_cert(trustedStore.get(), issuer);
+       }
+
+       if (OCSP_basic_verify(basicResp.get(), NULL, trustedStore.get(), 0) <= 0) {
+               ERR_print_errors(bioLogger.get());
+               VcoreThrowMsg(Ocsp::Exception::InvalidResponse, "Failed to OCSP_basic_verify");
+       }
+
+       if (OCSP_check_nonce(req.get(), basicResp.get()) == 0) {
+               ERR_print_errors(bioLogger.get());
+               VcoreThrowMsg(Ocsp::Exception::InvalidResponse, "nonce exists but not equal");
+       }
+
+       int ocspStatus = -1;
+       int reason = 0;
+       ASN1_GENERALIZEDTIME *rev = NULL;
+       ASN1_GENERALIZEDTIME *thisupd = NULL;
+       ASN1_GENERALIZEDTIME *nextupd = NULL;
+
+       if (OCSP_resp_find_status(
+                               basicResp.get(),
+                               certid,
+                               &ocspStatus,
+                               &reason,
+                               &rev,
+                               &thisupd,
+                               &nextupd) == 0) {
+               ERR_print_errors(bioLogger.get());
+               VcoreThrowMsg(Ocsp::Exception::InvalidResponse, "Failed to OCSP_resp_find_status");
+       }
+
+       if (OCSP_check_validity(thisupd, nextupd, MAX_VALIDITY_PERIOD, -1) == 0) {
+               ERR_print_errors(bioLogger.get());
+               VcoreThrowMsg(Ocsp::Exception::InvalidResponse, "Failed to OCSP_check_validity");
+       }
+
+       if (ocspStatus != V_OCSP_CERTSTATUS_GOOD && ocspStatus != V_OCSP_CERTSTATUS_REVOKED)
+               VcoreThrowMsg(Ocsp::Exception::InvalidResponse, "Unknown ocsp status.");
+
+       return ocspStatus == V_OCSP_CERTSTATUS_GOOD ?
+                  Ocsp::Result::GOOD : Ocsp::Result::REVOKED;
+}
+
+Ocsp::Result Ocsp::check(const SignatureData &data)
+{
+       if (!data.isCertListSorted())
+               VcoreThrowMsg(Exception::InvalidParam, "cert list should be sorted");
+
+       const CertificateList &certChain = data.getCertList();
+
+       if (certChain.size() < 3)
+               VcoreThrowMsg(Exception::InvalidParam, "cert chain is too short");
+
+       X509_STACK_PTR trustedCerts = create_x509_stack();
+       auto it = certChain.cbegin();
+       it++;
+       it++;
+
+       /* don't trust the user cert and the first intermediate CA cert */
+       for (; it != certChain.cend(); it++) {
+               const auto &cert = it->get();
+
+               if (cert->getDER().empty())
+                       VcoreThrowMsg(Exception::InvalidParam, "Broken certificate chain.");
+
+               sk_X509_push(trustedCerts.get(), cert->getX509());
+       }
+
+       auto itCert = certChain.cbegin();
+       auto itIssuer = certChain.cbegin();
+       itIssuer++;
+
+       /* check ocsp except except self-signed root CA cert */
+       for (; itIssuer != certChain.end(); itCert++, itIssuer++) {
+               if (checkInternal(*itCert, *itIssuer, trustedCerts) == Result::REVOKED)
+                       return Result::REVOKED;
+
+               LogDebug("ocsp status good for cert : " << (*itCert)->getOneLine());
+       }
+
+       return Result::GOOD;
+}
+
+}
diff --git a/src/vcore/Ocsp.h b/src/vcore/Ocsp.h
new file mode 100644 (file)
index 0000000..d335e67
--- /dev/null
@@ -0,0 +1,59 @@
+/*
+ *  Copyright (c) 2015 Samsung Electronics Co.
+ *
+ *  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        Ocsp.h
+ * @author      Kyungwook Tak (k.tak@samsung.com)
+ * @version     1.0
+ * @brief       OCSP check for signature validator. It should be used only internally.
+ */
+#pragma once
+
+#include <vcore/SignatureData.h>
+#include <vcore/exception.h>
+
+namespace ValidationCore {
+
+class Ocsp {
+public:
+       virtual ~Ocsp();
+
+       class Exception {
+       public:
+               VCORE_DECLARE_EXCEPTION_TYPE(ValidationCore::Exception, Base);
+               VCORE_DECLARE_EXCEPTION_TYPE(Base, InvalidParam);
+               VCORE_DECLARE_EXCEPTION_TYPE(Base, OcspUnsupported);
+               VCORE_DECLARE_EXCEPTION_TYPE(Base, InvalidUrl);
+               VCORE_DECLARE_EXCEPTION_TYPE(Base, InvalidResponse);
+               VCORE_DECLARE_EXCEPTION_TYPE(Base, ServerError);
+               VCORE_DECLARE_EXCEPTION_TYPE(Base, NetworkError);
+               VCORE_DECLARE_EXCEPTION_TYPE(Base, UnknownError);
+       };
+
+       enum Result {
+               GOOD,
+               REVOKED
+       };
+
+       /*
+        *  Remarks: input cert chain should be sorted state.
+        */
+       static Result check(const SignatureData &data);
+
+private:
+       explicit Ocsp();
+};
+
+}
diff --git a/src/vcore/ParserSchema.h b/src/vcore/ParserSchema.h
new file mode 100644 (file)
index 0000000..02ff6ed
--- /dev/null
@@ -0,0 +1,198 @@
+/*
+ * Copyright (c) 2011 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        ParserSchema.h
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief
+ */
+#ifndef _PARSERSCHEMA_H_
+#define _PARSERSCHEMA_H_
+
+#include <map>
+#include <string>
+
+#include <vcore/SaxReader.h>
+#include <vcore/exception.h>
+
+namespace ValidationCore {
+namespace ParserSchemaException {
+VCORE_DECLARE_EXCEPTION_TYPE(ValidationCore::Exception, Base);
+VCORE_DECLARE_EXCEPTION_TYPE(Base, XmlReaderError);
+VCORE_DECLARE_EXCEPTION_TYPE(Base, CertificateLoaderError);
+VCORE_DECLARE_EXCEPTION_TYPE(Base, UnsupportedAlgorithm);
+VCORE_DECLARE_EXCEPTION_TYPE(Base, UnsupportedValue);
+}
+
+template<typename ParserType, typename DataType>
+class ParserSchema {
+public:
+
+       struct TagDescription {
+               TagDescription(const std::string &tag,
+                                          const std::string &xmlNamespace) :
+                       tagName(tag),
+                       namespaceUri(xmlNamespace)
+               {
+               }
+
+               std::string tagName;
+               std::string namespaceUri;
+
+               bool operator<(const TagDescription &second) const
+               {
+                       if (tagName < second.tagName) {
+                               return true;
+                       }
+
+                       if (tagName > second.tagName) {
+                               return false;
+                       }
+
+                       if (namespaceUri < second.namespaceUri) {
+                               return true;
+                       }
+
+                       return false;
+               }
+       };
+
+
+       ParserSchema(ParserType *parser)
+               : m_functions(parser) {}
+
+       virtual ~ParserSchema() {}
+
+       void initialize(
+               const std::string &filename,
+               bool defaultArgs,
+               SaxReader::ValidationType valType,
+               const std::string &xmlschema)
+       {
+               VcoreTry {
+                       m_reader.initialize(filename, defaultArgs, valType, xmlschema);
+               }
+               VcoreCatch(SaxReader::Exception::Base) {
+                       VcoreReThrowMsg(ParserSchemaException::XmlReaderError, "XmlReaderError");
+               }
+       }
+
+       void deinitialize()
+       {
+               m_reader.deinitialize();
+       }
+
+       void read(DataType &dataContainer)
+       {
+               VcoreTry {
+                       while (m_reader.next())
+                       {
+                               switch (m_reader.type()) {
+                               case SaxReader::NODE_BEGIN:
+                                       beginNode(dataContainer);
+                                       break;
+
+                               case SaxReader::NODE_END:
+                                       endNode(dataContainer);
+                                       break;
+
+                               case SaxReader::NODE_TEXT:
+                                       textNode(dataContainer);
+                                       break;
+
+                               default:
+                                       break;
+                               }
+                       }
+               }
+               VcoreCatch(SaxReader::Exception::Base) {
+                       VcoreReThrowMsg(ParserSchemaException::XmlReaderError, "XmlReaderError");
+               }
+       }
+
+       typedef void (ParserType::*FunctionPtr)(DataType &data);
+       typedef std::map<TagDescription, FunctionPtr> FunctionMap;
+
+       void addBeginTagCallback(
+               const std::string &tag,
+               const std::string &namespaceUri,
+               FunctionPtr function)
+       {
+               TagDescription desc(tag, namespaceUri);
+               m_beginFunctionMap[desc] = function;
+       }
+
+       void addEndTagCallback(
+               const std::string &tag,
+               const std::string &namespaceUri,
+               FunctionPtr function)
+       {
+               TagDescription desc(tag, namespaceUri);
+               m_endFunctionMap[desc] = function;
+       }
+
+       SaxReader &getReader()
+       {
+               return m_reader;
+       }
+
+       std::string &getText()
+       {
+               return m_textNode;
+       }
+
+protected:
+       void beginNode(DataType &dataContainer)
+       {
+               TagDescription desc(m_reader.name(), m_reader.namespaceURI());
+               FunctionPtr fun = m_beginFunctionMap[desc];
+
+               if (fun == 0) {
+                       return;
+               }
+
+               (m_functions->*fun)(dataContainer);
+       }
+
+       void endNode(DataType &dataContainer)
+       {
+               TagDescription desc(m_reader.name(), m_reader.namespaceURI());
+               FunctionPtr fun = m_endFunctionMap[desc];
+
+               if (fun == 0) {
+                       return;
+               }
+
+               (m_functions->*fun)(dataContainer);
+       }
+
+       void textNode(DataType &dataContainer)
+       {
+               (void)dataContainer;
+               m_textNode = m_reader.value();
+       }
+
+       ParserType *m_functions;
+       SaxReader m_reader;
+       FunctionMap m_beginFunctionMap;
+       FunctionMap m_endFunctionMap;
+
+       // temporary values require due parsing textNode
+       std::string m_textNode;
+};
+
+} // namespace ValidationCore
+#endif
diff --git a/src/vcore/PluginHandler.cpp b/src/vcore/PluginHandler.cpp
new file mode 100644 (file)
index 0000000..e722bfc
--- /dev/null
@@ -0,0 +1,106 @@
+/*
+ *  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        PluginHandler.cpp
+ * @author      Kyungwook Tak (k.tak@samsung.com)
+ * @version     1.0
+ * @brief       Validator plugin handler.
+ */
+
+#include <dlfcn.h>
+
+#include <dpl/log/log.h>
+
+#include <vcore/PluginHandler.h>
+
+namespace ValidationCore {
+
+PluginHandler::PluginHandler()
+       : m_dlhandle(nullptr)
+       , m_plugin(nullptr)
+       , m_destroy(nullptr)
+       , m_fail(true)
+{
+       m_dlhandle = dlopen(PLUGIN_PATH.c_str(), RTLD_NOW);
+
+       if (!m_dlhandle) {
+               LogInfo("Plugin library has not been found/opened : " << PLUGIN_PATH);
+               return;
+       }
+
+       CreateValidatorPlugin_t createFun =
+               reinterpret_cast<CreateValidatorPlugin_t>(dlsym(m_dlhandle, "create"));
+
+       if (!createFun) {
+               LogError("create symbol cannot found from " << PLUGIN_PATH
+                                << ". dlerror : " << dlerror());
+               return;
+       }
+
+       m_destroy =
+               reinterpret_cast<DestroyValidatorPlugin_t>(dlsym(m_dlhandle, "destroy"));
+
+       if (!m_destroy) {
+               LogError("destroy symbole cannot found from " << PLUGIN_PATH
+                                << ". dlerror : " << dlerror());
+               return;
+       }
+
+       m_plugin = createFun();
+
+       if (!m_plugin) {
+               LogError("cannot create plugin with create func.");
+               return;
+       }
+
+       LogDebug("create plugin with createFun success.");
+       m_fail = false;
+}
+
+PluginHandler::~PluginHandler()
+{
+       if (m_plugin && m_destroy)
+               m_destroy(m_plugin);
+
+       if (m_dlhandle)
+               dlclose(m_dlhandle);
+}
+
+bool PluginHandler::fail() const
+{
+       return m_fail;
+}
+
+VCerr PluginHandler::step(VCerr result, SignatureData &data)
+{
+       if (!m_plugin) {
+               LogError("Plugin is not initialized.");
+               return result;
+       }
+
+       return m_plugin->step(result, data);
+}
+
+std::string PluginHandler::errorToString(VCerr code)
+{
+       if (!m_plugin)
+               return "Plugin is not initialized";
+
+       return m_plugin->errorToString(code);
+}
+
+} // namespace ValidationCore
diff --git a/src/vcore/PluginHandler.h b/src/vcore/PluginHandler.h
new file mode 100644 (file)
index 0000000..1b83b02
--- /dev/null
@@ -0,0 +1,53 @@
+/*
+ *  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        PluginHandler.h
+ * @author      Kyungwook Tak (k.tak@samsung.com)
+ * @version     1.0
+ * @brief       Validator plugin handler.
+ */
+#pragma once
+
+#include <string>
+
+#include <vcore/SignatureData.h>
+#include <vcore/SignatureValidator.h>
+#include <vcore/ValidatorPluginApi.h>
+#include <vcore/Error.h>
+
+namespace ValidationCore {
+
+class PluginHandler {
+public:
+       PluginHandler();
+       PluginHandler(const PluginHandler &) = delete;
+       PluginHandler &operator=(const PluginHandler &) = delete;
+
+       virtual ~PluginHandler();
+
+       bool fail(void) const;
+       VCerr step(VCerr result, SignatureData &data);
+       std::string errorToString(VCerr code);
+
+private:
+       void *m_dlhandle;
+       ValidatorPlugin *m_plugin;
+       DestroyValidatorPlugin_t m_destroy;
+       bool m_fail;
+};
+
+} // namespace ValidationCore
diff --git a/src/vcore/ReferenceValidator.cpp b/src/vcore/ReferenceValidator.cpp
new file mode 100644 (file)
index 0000000..b4f4713
--- /dev/null
@@ -0,0 +1,293 @@
+/*
+ * Copyright (c) 2011 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.
+ */
+/*
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ *              Sangwan Kwon (sangwan.kwon@samsung.com)
+ * @file        ReferenceValidator.cpp
+ * @version     1.0
+ * @brief       Compare signature reference list and list of widget file.
+ */
+#include <vcore/ReferenceValidator.h>
+
+#include <dirent.h>
+#include <errno.h>
+#include <fstream>
+#include <memory>
+#include <unistd.h>
+#include <limits.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+
+#include <pcrecpp.h>
+
+#include <dpl/log/log.h>
+
+#ifndef PATH_MAX
+#define PATH_MAX 4096
+#endif
+
+namespace {
+
+const char *SPECIAL_SYMBOL_CURRENT_DIR = ".";
+const char *SPECIAL_SYMBOL_UPPER_DIR = "..";
+const char *SPECIAL_SYMBOL_AUTHOR_SIGNATURE_FILE = "author-signature.xml";
+const char *REGEXP_DISTRIBUTOR_SIGNATURE = "^signature[1-9][0-9]*\\.xml";
+
+const char MARK_ENCODED_CHAR = '%';
+
+} // namespace anonymous
+
+namespace ValidationCore {
+
+class ReferenceValidator::Impl {
+public:
+       Impl(const std::string &dirpath)
+               : m_dirpath(dirpath)
+               , m_signatureRegexp(REGEXP_DISTRIBUTOR_SIGNATURE)
+       {}
+
+       virtual ~Impl() {}
+
+       Result checkReferences(const SignatureData &signatureData)
+       {
+               const ReferenceSet &refSet = signatureData.getReferenceSet();
+               ReferenceSet refDecoded;
+
+               try {
+                       for (auto it = refSet.begin(); it != refSet.end(); ++it) {
+                               if (std::string::npos != it->find(MARK_ENCODED_CHAR))
+                                       refDecoded.insert(decodeProcent(*it));
+                               else
+                                       refDecoded.insert(*it);
+                       }
+               } catch (Result &) {
+                       return ERROR_DECODING_URL;
+               }
+
+               return dfsCheckDirectories(
+                                  refDecoded,
+                                  std::string(),
+                                  signatureData.isAuthorSignature());
+       }
+
+       Result checkOutbound(const std::string &linkPath, const std::string &appPath)
+       {
+               char resolvedPath[PATH_MAX];
+
+               if (realpath((appPath + "/" + linkPath).c_str(), resolvedPath) == NULL)
+                       return ERROR_READING_LNK;
+
+               std::string linkRealPath(resolvedPath);
+
+               if (linkRealPath.compare(0, appPath.size(), appPath) == 0)
+                       return NO_ERROR;
+               else
+                       return ERROR_OUTBOUND_LNK;
+       }
+
+private:
+       int hexToInt(char hex);
+       std::string decodeProcent(const std::string &path);
+
+       Result dfsCheckDirectories(
+               const ReferenceSet &referenceSet,
+               const std::string &directory,
+               bool isAuthorSignature);
+
+       inline bool isDistributorSignature(const char *cstring) const
+       {
+               return m_signatureRegexp.FullMatch(cstring);
+       }
+
+       std::string m_dirpath;
+       pcrecpp::RE m_signatureRegexp;
+};
+
+int ReferenceValidator::Impl::hexToInt(char a)
+{
+       if (a >= '0' && a <= '9') return a - '0';
+
+       if (a >= 'A' && a <= 'F') return a - 'A' + 10;
+
+       if (a >= 'a' && a <= 'f') return a - 'a' + 10;
+
+       LogError("Symbol '" << a << "' is out of scope.");
+       throw ERROR_DECODING_URL;
+}
+
+std::string ReferenceValidator::Impl::decodeProcent(const std::string &path)
+{
+       std::vector<int> input(path.begin(), path.end());
+       std::vector<char> output;
+
+       try {
+               size_t i = 0;
+
+               while (i < input.size()) {
+                       if (MARK_ENCODED_CHAR == input[i]) {
+                               if (i + 2 >= input.size())
+                                       throw ERROR_DECODING_URL;
+
+                               int result = hexToInt(input[i + 1]) * 16 + hexToInt(input[i + 2]);
+                               output.push_back(static_cast<char>(result));
+                               i += 3;
+                       } else {
+                               output.push_back(static_cast<char>(input[i]));
+                               ++i;
+                       }
+               }
+       } catch (Result &) {
+               LogError("Error while decoding url path : " << path);
+               throw ERROR_DECODING_URL;
+       }
+
+       return std::string(output.begin(), output.end());
+}
+
+ReferenceValidator::Result ReferenceValidator::Impl::dfsCheckDirectories(
+       const ReferenceSet &referenceSet,
+       const std::string &directory,
+       bool isAuthorSignature)
+{
+       int ret;
+       DIR *dirp;
+       struct dirent entry;
+       struct dirent *result;
+       std::string currentDir = m_dirpath;
+
+       if (!directory.empty()) {
+               currentDir += "/";
+               currentDir += directory;
+       }
+
+       if ((dirp = opendir(currentDir.c_str())) == NULL) {
+               LogError("Error opening directory : " << currentDir);
+               return ERROR_OPENING_DIR;
+       }
+
+       for (ret = readdir_r(dirp, &entry, &result);
+                       ret == 0 && result != NULL;
+                       ret = readdir_r(dirp, &entry, &result)) {
+               if (!strcmp(result->d_name, SPECIAL_SYMBOL_CURRENT_DIR)) {
+                       continue;
+               }
+
+               if (!strcmp(result->d_name, SPECIAL_SYMBOL_UPPER_DIR)) {
+                       continue;
+               }
+
+               if (result->d_type == DT_UNKNOWN) {
+                       // try to stat inode when readdir is not returning known type
+                       std::string path = currentDir + "/" + result->d_name;
+                       struct stat s;
+
+                       if (lstat(path.c_str(), &s) != 0) {
+                               closedir(dirp);
+                               return ERROR_LSTAT;
+                       }
+
+                       if (S_ISREG(s.st_mode)) {
+                               result->d_type = DT_REG;
+                       } else if (S_ISDIR(s.st_mode)) {
+                               result->d_type = DT_DIR;
+                       }
+               }
+
+               if (currentDir == m_dirpath && result->d_type == DT_REG &&
+                               !strcmp(result->d_name, SPECIAL_SYMBOL_AUTHOR_SIGNATURE_FILE) &&
+                               isAuthorSignature) {
+                       continue;
+               }
+
+               if (currentDir == m_dirpath && result->d_type == DT_REG &&
+                               isDistributorSignature(result->d_name)) {
+                       continue;
+               }
+
+               if (result->d_type == DT_DIR) {
+                       LogDebug("Open directory : " << (directory + result->d_name));
+                       std::string tmp_directory = directory + result->d_name + "/";
+                       Result result = dfsCheckDirectories(referenceSet,
+                                                                                               tmp_directory,
+                                                                                               isAuthorSignature);
+
+                       if (result != NO_ERROR) {
+                               closedir(dirp);
+                               return result;
+                       }
+               } else if (result->d_type == DT_REG) {
+                       if (referenceSet.end() ==
+                                       referenceSet.find(directory + result->d_name)) {
+                               LogDebug("Found file : " << (directory + result->d_name));
+                               LogError("Unknown ERROR_REFERENCE_NOT_FOUND.");
+                               closedir(dirp);
+                               return ERROR_REFERENCE_NOT_FOUND;
+                       }
+               } else if (result->d_type == DT_LNK) {
+                       std::string linkPath(directory + result->d_name);
+
+                       if (referenceSet.end() ==
+                                       referenceSet.find(linkPath)) {
+                               LogDebug("Found file : " << (directory + result->d_name));
+                               LogError("Unknown ERROR_REFERENCE_NOT_FOUND.");
+                               closedir(dirp);
+                               return ERROR_REFERENCE_NOT_FOUND;
+                       }
+
+                       Result ret = checkOutbound(linkPath, m_dirpath);
+
+                       if (ret != NO_ERROR) {
+                               LogError("Link file point wrong path");
+                               closedir(dirp);
+                               return ret;
+                       }
+               } else {
+                       LogError("Unknown file type.");
+                       closedir(dirp);
+                       return ERROR_UNSUPPORTED_FILE_TYPE;
+               }
+       }
+
+       if (ret != 0) {
+               closedir(dirp);
+               return ERROR_READING_DIR;
+       }
+
+       closedir(dirp);
+       return NO_ERROR;
+}
+
+ReferenceValidator::ReferenceValidator(const std::string &dirpath)
+       : m_impl(new Impl(dirpath))
+{}
+
+ReferenceValidator::~ReferenceValidator()
+{
+       delete m_impl;
+}
+
+ReferenceValidator::Result ReferenceValidator::checkReferences(
+       const SignatureData &signatureData)
+{
+       return m_impl->checkReferences(signatureData);
+}
+
+ReferenceValidator::Result ReferenceValidator::checkOutbound(
+       const std::string &linkPath, const std::string &appPath)
+{
+       return m_impl->checkOutbound(linkPath, appPath);
+}
+} // ValidationCore
diff --git a/src/vcore/ReferenceValidator.h b/src/vcore/ReferenceValidator.h
new file mode 100644 (file)
index 0000000..450e224
--- /dev/null
@@ -0,0 +1,61 @@
+/*
+ * Copyright (c) 2011 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.
+ */
+/*
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ *              Sangwan Kwon (sangwan.kwon@samsung.com)
+ * @file        ReferenceValidator.h
+ * @version     1.0
+ * @brief       Compare signature reference list with widget package.
+ */
+#ifndef _VALIDATION_CORE_REFERENCEVALIDATOR_H_
+#define _VALIDATION_CORE_REFERENCEVALIDATOR_H_
+
+#include <vcore/SignatureData.h>
+
+namespace ValidationCore {
+
+class ReferenceValidator {
+public:
+       enum Result {
+               NO_ERROR = 0,
+               ERROR_OPENING_DIR,
+               ERROR_READING_DIR,
+               ERROR_UNSUPPORTED_FILE_TYPE,
+               ERROR_REFERENCE_NOT_FOUND,
+               ERROR_DECODING_URL,
+               ERROR_OUTBOUND_LNK,
+               ERROR_READING_LNK,
+               ERROR_LSTAT
+       };
+
+       ReferenceValidator(const std::string &dirpath);
+       virtual ~ReferenceValidator();
+
+       ReferenceValidator(const ReferenceValidator &) = delete;
+       ReferenceValidator &operator=(const ReferenceValidator &) = delete;
+       ReferenceValidator(ReferenceValidator &&) = delete;
+       ReferenceValidator &operator=(ReferenceValidator &&) = delete;
+
+       Result checkReferences(const SignatureData &signatureData);
+       Result checkOutbound(const std::string &linkPath, const std::string &appPath);
+
+private:
+       class Impl;
+       Impl *m_impl;
+};
+}
+
+#endif // _VALIDATION_CORE_REFERENCEVALIDATOR_H_
diff --git a/src/vcore/SaxReader.cpp b/src/vcore/SaxReader.cpp
new file mode 100644 (file)
index 0000000..46dd690
--- /dev/null
@@ -0,0 +1,246 @@
+/*
+ * Copyright (c) 2011 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        SaxReader.cpp
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       Simple c++ interface for libxml2.
+ */
+#include <dpl/assert.h>
+#include <dpl/log/log.h>
+
+#include <vcore/SaxReader.h>
+
+namespace ValidationCore {
+
+
+SaxReader::SaxReader() :
+       m_reader(0)
+{
+}
+
+SaxReader::~SaxReader()
+{
+       if (m_reader) {
+               deinitialize();
+       }
+}
+
+void SaxReader::initialize(
+       const std::string &filename,
+       bool defaultArgs,
+       ValidationType validate,
+       const std::string &schema)
+{
+       Assert(m_reader == 0 && "Double initialization of SaxReader");
+       LogDebug("SaxReader opening file: " << filename);
+       m_reader = xmlNewTextReaderFilename(filename.c_str());
+
+       if (!m_reader) {
+               VcoreThrowMsg(SaxReader::Exception::FileOpeningError,
+                                         "opening file " << filename << " error");
+       }
+
+       if (validate == VALIDATION_XMLSCHEME &&
+                       xmlTextReaderSchemaValidate(m_reader, schema.c_str())) {
+               /*
+                * unable to turn on schema validation
+                */
+               VcoreThrowMsg(SaxReader::Exception::ParserInternalError,
+                                         "Turn on Schema validation failed");
+       }
+
+       // Path to DTD schema is taken from xml file.
+       if (validate == VALIDATION_DTD &&
+                       xmlTextReaderSetParserProp(m_reader, XML_PARSER_VALIDATE, 1)) {
+               /*
+                * unable to turn on DTD validation
+                */
+               VcoreThrowMsg(SaxReader::Exception::ParserInternalError,
+                                         "Turn on DTD validation failed!");
+       }
+
+       if (defaultArgs &&
+                       xmlTextReaderSetParserProp(m_reader, XML_PARSER_DEFAULTATTRS, 1)) {
+               /*
+                * unable to turn on default arguments
+                */
+               VcoreThrowMsg(SaxReader::Exception::ParserInternalError,
+                                         "Turn on default arguments failed");
+       }
+}
+
+void SaxReader::deinitialize()
+{
+       xmlFreeTextReader(m_reader);
+       m_reader = 0;
+}
+
+bool SaxReader::next()
+{
+       int res = xmlTextReaderRead(m_reader);
+
+       if (res < 0)
+               VcoreThrowMsg(SaxReader::Exception::ParserInternalError,
+                                         "xmlTextReaderRead error");
+
+       if (!xmlTextReaderIsValid(m_reader))
+               VcoreThrowMsg(SaxReader::Exception::FileNotValid,
+                                         "xmlTextReader is invalid");
+
+       return res ? true : false;
+}
+
+void SaxReader::next(const std::string &token)
+{
+       int res = xmlTextReaderRead(m_reader);
+
+       if (res < 0)
+               VcoreThrowMsg(SaxReader::Exception::ParserInternalError,
+                                         "xmlTextReaderRead error");
+
+       if (!xmlTextReaderIsValid(m_reader))
+               VcoreThrowMsg(SaxReader::Exception::FileNotValid,
+                                         "xmlTextReader is invalid");
+
+       xmlChar *name = xmlTextReaderName(m_reader);
+
+       if (!name)
+               VcoreThrowMsg(SaxReader::Exception::ParserInternalError,
+                                         "xmlTextReaderName returns NULL");
+
+       xmlChar *xmlToken = xmlCharStrdup(token.c_str());
+
+       if (xmlStrcmp(name, xmlToken)) {
+               xmlFree(name);
+               xmlFree(xmlToken);
+               VcoreThrowMsg(SaxReader::Exception::WrongToken, "Wrong Token");
+       }
+
+       xmlFree(name);
+       xmlFree(xmlToken);
+}
+
+bool SaxReader::isEmpty(void)
+{
+       int ret = xmlTextReaderIsEmptyElement(m_reader);
+
+       if (-1 == ret)
+               VcoreThrowMsg(SaxReader::Exception::ParserInternalError,
+                                         "xmlTextReaderIsEmptyElement error");
+
+       return ret ? true : false;
+}
+
+std::string SaxReader::attribute(const std::string &token, ThrowType throwStatus)
+{
+       xmlChar *attr = xmlTextReaderGetAttribute(m_reader, BAD_CAST(token.c_str()));
+
+       if (!attr) {
+               if (throwStatus == THROW_DISABLE) {
+                       return std::string();
+               } else {
+                       VcoreThrowMsg(SaxReader::Exception::ParserInternalError,
+                                                 "xmlTextReaderGetAttribute error");
+               }
+       }
+
+       std::string value = reinterpret_cast<const char *>(attr);
+       xmlFree(attr);
+       return value;
+}
+
+std::string SaxReader::name()
+{
+       xmlChar *name = xmlTextReaderName(m_reader);
+
+       if (!name)
+               VcoreThrowMsg(SaxReader::Exception::ReadingNameError,
+                                         "reading name error");
+
+       std::string value = reinterpret_cast<const char *>(name);
+       xmlFree(name);
+       size_t pos = value.find_last_of(":");
+
+       if (pos != std::string::npos) {
+               value.erase(0, pos + 1);
+       }
+
+       return value;
+}
+
+std::string SaxReader::namespaceURI()
+{
+       xmlChar *name = xmlTextReaderNamespaceUri(m_reader);
+
+       if (!name) {
+               return std::string();
+       }
+
+       std::string value = reinterpret_cast<const char *>(name);
+       xmlFree(name);
+       return value;
+}
+
+std::string SaxReader::value()
+{
+       xmlChar *text = xmlTextReaderValue(m_reader);
+
+       if (!text)
+               VcoreThrowMsg(SaxReader::Exception::ReadingValueError,
+                                         "reading value error");
+
+       std::string value = reinterpret_cast<const char *>(text);
+       xmlFree(text);
+       return value;
+}
+
+SaxReader::NodeType SaxReader::type()
+{
+       xmlReaderTypes type =
+               static_cast<xmlReaderTypes>(xmlTextReaderNodeType(m_reader));
+
+       switch (type) {
+       case XML_READER_TYPE_ELEMENT:
+               return NODE_BEGIN;
+
+       case XML_READER_TYPE_END_ELEMENT:
+               return NODE_END;
+
+       case XML_READER_TYPE_TEXT:
+               return NODE_TEXT;
+
+       case XML_READER_TYPE_NONE:
+       case XML_READER_TYPE_ATTRIBUTE:
+       case XML_READER_TYPE_CDATA:
+       case XML_READER_TYPE_ENTITY_REFERENCE:
+       case XML_READER_TYPE_ENTITY:
+       case XML_READER_TYPE_PROCESSING_INSTRUCTION:
+       case XML_READER_TYPE_COMMENT:
+       case XML_READER_TYPE_DOCUMENT:
+       case XML_READER_TYPE_DOCUMENT_TYPE:
+       case XML_READER_TYPE_DOCUMENT_FRAGMENT:
+       case XML_READER_TYPE_NOTATION:
+       case XML_READER_TYPE_WHITESPACE:
+       case XML_READER_TYPE_SIGNIFICANT_WHITESPACE:
+       case XML_READER_TYPE_END_ENTITY:
+       case XML_READER_TYPE_XML_DECLARATION:
+       default:
+               return NODE_UNSUPPORTED;
+       }
+}
+
+} // namespace ValidationCore
diff --git a/src/vcore/SaxReader.h b/src/vcore/SaxReader.h
new file mode 100644 (file)
index 0000000..8c7e975
--- /dev/null
@@ -0,0 +1,133 @@
+/*
+ * Copyright (c) 2011 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        SaxReader.h
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       Simple c++ interface for libxml2.
+ *              Its used in wrt-installer only and should be removed
+ *              from cert-svc.
+ */
+#ifndef _SAXREADER_H_
+#define _SAXREADER_H_
+
+#include <string>
+#include <libxml/xmlreader.h>
+
+#include <vcore/exception.h>
+
+namespace ValidationCore {
+class SaxReader {
+public:
+       SaxReader();
+       ~SaxReader();
+
+       class Exception {
+       public:
+               VCORE_DECLARE_EXCEPTION_TYPE(ValidationCore::Exception, Base);
+               VCORE_DECLARE_EXCEPTION_TYPE(Base, FileOpeningError);
+               VCORE_DECLARE_EXCEPTION_TYPE(Base, FileNotValid);
+               VCORE_DECLARE_EXCEPTION_TYPE(Base, ParserInternalError);
+               VCORE_DECLARE_EXCEPTION_TYPE(Base, WrongToken);
+               VCORE_DECLARE_EXCEPTION_TYPE(Base, ReadingValueError);
+               VCORE_DECLARE_EXCEPTION_TYPE(Base, ReadingNameError);
+               VCORE_DECLARE_EXCEPTION_TYPE(Base, UnsupportedType);
+       };
+
+       enum NodeType {
+               NODE_UNSUPPORTED,
+               NODE_BEGIN,
+               NODE_END,
+               NODE_TEXT
+       };
+
+       enum ThrowType {
+               THROW_ENABLE = 0,
+               THROW_DISABLE
+       };
+
+       /*
+        * xml validation modes
+        */
+       enum ValidationType {
+               VALIDATION_DISABLE,
+               VALIDATION_XMLSCHEME,
+               VALIDATION_DTD
+       };
+
+       /*
+        * initializes parser
+        */
+       void initialize(
+               const std::string &filename,
+               bool defaultArgs = false,
+               ValidationType validation = VALIDATION_DISABLE,
+               const std::string &schema = std::string());
+       /*
+        * deinitializes parser
+        */
+       void deinitialize();
+
+       /**
+        * Move to next xml node.
+        */
+       bool next();
+
+       /**
+        * Move to next xml node. If next node name is differ from token the exception wiil
+        * be thronw.
+        */
+       void next(const std::string &token);
+
+       /**
+        * Check if xml tag is empty.
+        */
+       bool isEmpty(void);
+
+       /**
+        * Read attribute tag.
+        */
+       std::string attribute(const std::string &token, ThrowType throwStatus = THROW_ENABLE);
+
+       /**
+        * Read xml tag name without namespace.
+        */
+       std::string name();
+
+       /**
+        * Read xml tag namespace URI
+        */
+       std::string namespaceURI();
+
+       /**
+        * Read xml tag value.
+        */
+       std::string value();
+
+       /**
+        * Return information about node type.
+        */
+       NodeType type();
+
+private:
+       /*
+        * internal libxml text reader
+        */
+       xmlTextReaderPtr m_reader;
+};
+}
+
+#endif // _SAXREADER_H_
diff --git a/src/vcore/SignatureData.cpp b/src/vcore/SignatureData.cpp
new file mode 100644 (file)
index 0000000..8663414
--- /dev/null
@@ -0,0 +1,156 @@
+/*
+ * Copyright (c) 2011 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        SignatureData.cpp
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       SignatureData is used to storage data parsed from digsig file.
+ */
+#include <vcore/SignatureData.h>
+
+#include <dpl/log/log.h>
+
+namespace ValidationCore {
+
+SignatureData::SignatureData()
+       : m_signatureNumber(-1)
+       , m_certificateSorted(false)
+{}
+
+SignatureData::SignatureData(const std::string &fileName, int fileNumber)
+       : m_signatureNumber(fileNumber)
+       , m_fileName(fileName)
+       , m_certificateSorted(false)
+{}
+
+SignatureData::~SignatureData()
+{}
+
+const ReferenceSet &SignatureData::getReferenceSet() const
+{
+       return m_referenceSet;
+}
+
+void SignatureData::setReference(const ReferenceSet &referenceSet)
+{
+       m_referenceSet = referenceSet;
+}
+
+CertificateList SignatureData::getCertList() const
+{
+       return m_certList;
+}
+
+void SignatureData::setSortedCertificateList(const CertificateList &list)
+{
+       m_certList = list;
+       m_certificateSorted = true;
+}
+
+bool SignatureData::isAuthorSignature() const
+{
+       return m_signatureNumber == -1;
+}
+
+std::string SignatureData::getSignatureFileName() const
+{
+       return m_fileName;
+}
+
+int SignatureData::getSignatureNumber() const
+{
+       return m_signatureNumber;
+}
+
+std::string SignatureData::getRoleURI() const
+{
+       return m_roleURI;
+}
+
+std::string SignatureData::getProfileURI() const
+{
+       return m_profileURI;
+}
+
+bool SignatureData::containObjectReference(const std::string &ref) const
+{
+       std::string rName = "#";
+       rName += ref;
+       return m_referenceSet.end() != m_referenceSet.find(rName);
+}
+
+ObjectList SignatureData::getObjectList() const
+{
+       return m_objectList;
+}
+
+void SignatureData::setStorageType(const CertStoreId::Set &storeIdSet)
+{
+       m_storeIdSet = storeIdSet;
+}
+
+bool SignatureData::isCertListSorted() const
+{
+       return m_certificateSorted;
+}
+
+const CertStoreId::Set &SignatureData::getStorageType() const
+{
+       return m_storeIdSet;
+}
+
+CertStoreId::Type SignatureData::getVisibilityLevel() const
+{
+       if (!m_storeIdSet.isContainsVis()) {
+               LogWarning("Visibility level was broken.");
+               return 0;
+       }
+
+       if (m_storeIdSet.contains(CertStoreId::VIS_PLATFORM))
+               return CertStoreId::VIS_PLATFORM;
+       else if (m_storeIdSet.contains(CertStoreId::VIS_PARTNER))
+               return CertStoreId::VIS_PARTNER;
+       else
+               return CertStoreId::VIS_PUBLIC;
+}
+
+const SignatureData::IMEIList &SignatureData::getIMEIList() const
+{
+       return m_imeiList;
+}
+
+const SignatureData::MEIDList &SignatureData::getMEIDList() const
+{
+       return m_meidList;
+}
+
+CertificatePtr SignatureData::getEndEntityCertificatePtr() const
+{
+       if (m_certificateSorted)
+               return m_certList.front();
+
+       return CertificatePtr();
+}
+
+CertificatePtr SignatureData::getRootCaCertificatePtr() const
+{
+       if (m_certificateSorted)
+               return m_certList.back();
+
+       return CertificatePtr();
+}
+
+} // ValidationCore
diff --git a/src/vcore/SignatureData.h b/src/vcore/SignatureData.h
new file mode 100644 (file)
index 0000000..52e39fa
--- /dev/null
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) 2011 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        SignatureData.h
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       SignatureData is used to storage data parsed from digsig file.
+ */
+#ifndef _SIGNATUREDATA_H_
+#define _SIGNATUREDATA_H_
+
+#include <list>
+#include <set>
+#include <string>
+
+#include <vcore/Certificate.h>
+#include <vcore/CertStoreType.h>
+
+namespace ValidationCore {
+
+typedef std::set<std::string> ReferenceSet;
+typedef std::list<std::string> ObjectList;
+
+class SignatureData {
+public:
+       SignatureData();
+       SignatureData(const std::string &fileName, int fileNumber);
+
+       virtual ~SignatureData();
+
+       typedef std::list<std::string> IMEIList;
+       typedef std::list<std::string> MEIDList;
+
+       void setReference(const ReferenceSet &referenceSet);
+       void setSortedCertificateList(const CertificateList &list);
+       void setStorageType(const CertStoreId::Set &storeIdSet);
+       bool isCertListSorted() const;
+
+       const ReferenceSet &getReferenceSet() const;
+       CertificateList getCertList() const;
+       ObjectList getObjectList() const;
+       bool containObjectReference(const std::string &ref) const;
+       bool isAuthorSignature() const;
+       int getSignatureNumber() const;
+       std::string getSignatureFileName() const;
+       std::string getRoleURI() const;
+       std::string getProfileURI() const;
+       const CertStoreId::Set &getStorageType() const;
+       CertStoreId::Type getVisibilityLevel() const;
+       const IMEIList &getIMEIList() const;
+       const MEIDList &getMEIDList() const;
+       CertificatePtr getEndEntityCertificatePtr() const;
+       CertificatePtr getRootCaCertificatePtr() const;
+
+       friend class SignatureReader;
+
+private:
+       ReferenceSet m_referenceSet;
+       CertificateList m_certList;
+
+       //TargetRestriction
+       IMEIList m_imeiList;
+       MEIDList m_meidList;
+
+       /*
+        * This number is taken from distributor signature file name.
+        * Author signature do not contain any number on the file name.
+        * Author signature should have signature number equal to -1.
+        */
+       int m_signatureNumber;
+       std::string m_fileName;
+       std::string m_roleURI;
+       std::string m_profileURI;
+       std::string m_identifier;
+       ObjectList m_objectList;
+       CertStoreId::Set m_storeIdSet;
+       bool m_certificateSorted;
+};
+
+typedef std::set<SignatureData> SignatureDataSet;
+
+} // ValidationCore
+
+#endif
diff --git a/src/vcore/SignatureFinder.cpp b/src/vcore/SignatureFinder.cpp
new file mode 100644 (file)
index 0000000..5010563
--- /dev/null
@@ -0,0 +1,137 @@
+/*
+ * Copyright (c) 2011 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        SignatureFinder.cpp
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       Search for author-signature.xml and signatureN.xml files.
+ */
+#include <vcore/SignatureFinder.h>
+#include <dpl/log/log.h>
+
+#include <dirent.h>
+#include <errno.h>
+#include <istream>
+#include <sstream>
+
+#include <pcrecpp.h>
+
+namespace {
+
+}
+
+namespace ValidationCore {
+static const char *SIGNATURE_AUTHOR = "author-signature.xml";
+static const char *REGEXP_DISTRIBUTOR_SIGNATURE =
+       "^(signature)([1-9][0-9]*)(\\.xml)";
+
+class SignatureFinder::Impl {
+public:
+       Impl(const std::string &dir)
+               : m_dir(dir)
+               , m_signatureRegexp(REGEXP_DISTRIBUTOR_SIGNATURE)
+       {}
+
+       virtual ~Impl() {}
+
+       Result find(SignatureFileInfoSet &set);
+
+private:
+       std::string getFullPath(const std::string &file);
+
+       std::string m_dir;
+       pcrecpp::RE m_signatureRegexp;
+};
+
+std::string SignatureFinder::Impl::getFullPath(const std::string &file)
+{
+       std::string fullPath = m_dir;
+
+       if (fullPath.back() != '/')
+               fullPath += "/";
+
+       fullPath += file;
+       return fullPath;
+}
+
+SignatureFinder::Result SignatureFinder::Impl::find(SignatureFileInfoSet &set)
+{
+       int ret;
+       DIR *dirp;
+       struct dirent entry;
+       struct dirent *result;
+
+       if ((dirp = opendir(m_dir.c_str())) == NULL) {
+               LogError("Error opening directory: " << m_dir);
+               return ERROR_OPENING_DIR;
+       }
+
+       for (ret = readdir_r(dirp, &entry, &result);
+                       ret == 0 && result != NULL;
+                       ret = readdir_r(dirp, &entry, &result)) {
+               /* number for author signature is -1 */
+               if (!strcmp(result->d_name, SIGNATURE_AUTHOR)) {
+                       std::string fullPath = getFullPath(std::string(result->d_name));
+                       LogDebug("Found author signature file full path : " << fullPath);
+                       set.insert(SignatureFileInfo(fullPath, -1));
+                       continue;
+               }
+
+               std::string sig;
+               std::string num;
+               std::string xml; /* just for cutting out .xml */
+
+               if (m_signatureRegexp.FullMatch(result->d_name, &sig, &num, &xml)) {
+                       std::istringstream stream(num);
+                       int number;
+                       stream >> number;
+
+                       if (stream.fail()) {
+                               closedir(dirp);
+                               return ERROR_ISTREAM;
+                       }
+
+                       std::string fullPath = getFullPath(std::string(result->d_name));
+                       LogDebug("Found signature file full path : " << fullPath);
+                       set.insert(SignatureFileInfo(fullPath, number));
+               }
+       }
+
+       if (ret != 0) {
+               LogError("Error in readdir");
+               closedir(dirp);
+               return ERROR_READING_DIR;
+       }
+
+       closedir(dirp);
+       return NO_ERROR;
+}
+
+SignatureFinder::SignatureFinder(const std::string &dir)
+       : m_impl(new Impl(dir))
+{}
+
+SignatureFinder::~SignatureFinder()
+{
+       delete m_impl;
+}
+
+SignatureFinder::Result SignatureFinder::find(SignatureFileInfoSet &set)
+{
+       return m_impl->find(set);
+}
+
+} // namespace ValidationCore
diff --git a/src/vcore/SignatureFinder.h b/src/vcore/SignatureFinder.h
new file mode 100644 (file)
index 0000000..40881b9
--- /dev/null
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 2011 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        SignatureFinder.h
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       Search for author-signature.xml and signatureN.xml files.
+ *              This class is WAC 2.0 specific and shuld be moved to
+ *              wrt-installer.
+ */
+#ifndef _VALIDATION_CORE_SIGNATUREFINDER_H_
+#define _VALIDATION_CORE_SIGNATUREFINDER_H_
+
+#include <set>
+#include <string>
+
+namespace ValidationCore {
+
+class SignatureFileInfo {
+public:
+       SignatureFileInfo(const std::string &fileName, int num)
+               : m_fileName(fileName)
+               , m_fileNumber(num)
+       {}
+
+       std::string getFileName() const
+       {
+               return m_fileName;
+       }
+
+       int getFileNumber() const
+       {
+               return m_fileNumber;
+       }
+
+       bool operator<(const SignatureFileInfo &second) const
+       {
+               return m_fileNumber < second.m_fileNumber;
+       }
+
+private:
+       std::string m_fileName;
+       int m_fileNumber;
+};
+
+typedef std::set<SignatureFileInfo> SignatureFileInfoSet;
+
+class SignatureFinder {
+public:
+       enum Result {
+               NO_ERROR,
+               ERROR_OPENING_DIR,
+               ERROR_READING_DIR,
+               ERROR_ISTREAM
+       };
+
+       SignatureFinder() = delete;
+       explicit SignatureFinder(const std::string &dir);
+
+       virtual ~SignatureFinder();
+
+       Result find(SignatureFileInfoSet &set);
+
+private:
+       class Impl;
+       Impl *m_impl;
+
+       SignatureFinder(const SignatureFinder &);
+       const SignatureFinder &operator=(const SignatureFinder &);
+};
+
+} // namespace ValidationCore
+
+#endif // _VALIDATION_CORE_SIGNATUREFINDER_H_
diff --git a/src/vcore/SignatureReader.cpp b/src/vcore/SignatureReader.cpp
new file mode 100644 (file)
index 0000000..3fd1b58
--- /dev/null
@@ -0,0 +1,579 @@
+/*
+ * Copyright (c) 2011 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        SignatureReader.cpp
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       SignatureReader is used to parse widget digital signature.
+ */
+#include <vcore/SignatureReader.h>
+
+#include <vcore/CertificateLoader.h>
+
+namespace ValidationCore {
+static const std::string XML_NAMESPACE =
+       "http://www.w3.org/2000/09/xmldsig#";
+static const std::string XML_NAMESPACE_DIGITALSIG =
+       "http://wacapps.net/ns/digsig";
+static const std::string XML_OBJ_NS =
+       "http://www.w3.org/2009/xmldsig-properties";
+
+// TAG TOKENS
+static const std::string TOKEN_SIGNATURE = "Signature";
+static const std::string TOKEN_SIGNED_INFO = "SignedInfo";
+static const std::string TOKEN_CANONICALIZATION_METHOD =
+       "CanonicalizationMethod";
+static const std::string TOKEN_SIGNATURE_METHOD = "SignatureMethod";
+static const std::string TOKEN_REFERENCE = "Reference";
+static const std::string TOKEN_TRANSFORMS = "Transforms";
+static const std::string TOKEN_TRANSFORM = "Transform";
+static const std::string TOKEN_DIGEST_METHOD = "DigestMethod";
+static const std::string TOKEN_DIGEST_VALUE = "DigestValue";
+static const std::string TOKEN_SIGNATURE_VALUE = "SignatureValue";
+static const std::string TOKEN_KEY_INFO = "KeyInfo";
+static const std::string TOKEN_X509DATA = "X509Data";
+static const std::string TOKEN_X509CERTIFICATE = "X509Certificate";
+static const std::string TOKEN_KEY_VALUE = "KeyValue";
+static const std::string TOKEN_RSA_KEY_VALUE = "RSAKeyValue";
+static const std::string TOKEN_MODULUS_COMPONENT = "Modulus";
+static const std::string TOKEN_EXPONENT_COMPONENT = "Exponent";
+static const std::string TOKEN_ECKEY_VALUE = "ECKeyValue";
+static const std::string TOKEN_NAMED_CURVE = "NamedCurve";
+static const std::string TOKEN_PUBLIC_KEY = "PublicKey";
+static const std::string TOKEN_OBJECT = "Object";
+static const std::string TOKEN_SIGNATURE_PROPERTIES = "SignatureProperties";
+static const std::string TOKEN_SIGNATURE_PROPERTY = "SignatureProperty";
+static const std::string TOKEN_PROFILE = "Profile";
+static const std::string TOKEN_ROLE = "Role";
+static const std::string TOKEN_IDENTIFIER = "Identifier";
+static const std::string TOKEN_DSAKEYVALUE = "DSAKeyValue";
+static const std::string TOKEN_DSA_P_COMPONENT = "P";
+static const std::string TOKEN_DSA_Q_COMPONENT = "Q";
+static const std::string TOKEN_DSA_G_COMPONENT = "G";
+static const std::string TOKEN_DSA_Y_COMPONENT = "Y";
+static const std::string TOKEN_DSA_J_COMPONENT = "J";
+static const std::string TOKEN_DSA_SEED_COMPONENT = "Seed";
+static const std::string TOKEN_DSA_PGENCOUNTER_COMPONENT = "PgenCounter";
+static const std::string TOKEN_TARGET_RESTRICTION = "TargetRestriction";
+
+// ATTRIBUTTE TOKENS
+
+static const std::string TOKEN_ALGORITHM = "Algorithm";
+static const std::string TOKEN_URI = "URI";
+static const std::string TOKEN_ID = "Id";
+static const std::string TOKEN_TARGET = "Target";
+static const std::string TOKEN_IMEI = "IMEI";
+static const std::string TOKEN_MEID = "MEID";
+
+// ATTIRUBTE VALUES
+
+static const std::string TOKEN_ATTR_PROFILE = "profile";
+static const std::string TOKEN_ATTR_ROLE = "role";
+static const std::string TOKEN_ATTR_IDENTIFIER = "identifier";
+
+// ALGORITHMS
+
+//static const std::string TOKEN_ALGORITHM_XML_EXC_CAN   =
+//            "http://www.w3.org/2001/10/xml-exc-c14n#";
+//static const std::string TOKEN_ALGORITHM_RSA_SHA256    =
+//            "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
+//static const std::string TOKEN_ALGORITHM_DSA_SHA1      =
+//            "http://www.w3.org/2000/09/xmldsig#dsa-sha1";
+//static const std::string TOKEN_ALGORITHM_ECDSA_SHA256  =
+//            "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256";
+//static const std::string TOKEN_ALGORITHM_SHA1          =
+//            "http://www.w3.org/2000/09/xmldsig#sha1";
+//static const std::string TOKEN_ALGORITHM_SHA256        =
+//            "http://www.w3.org/2001/04/xmlenc#sha256";
+//static const std::string TOKEN_ALGORITHM_SHA384        =
+//            "http://www.w3.org/2001/04/xmldsig-more#sha384";
+//static const std::string TOKEN_ALGORITHM_SHA512        =
+//            "http://www.w3.org/2001/04/xmlenc#sha512";
+
+SignatureReader::SignatureReader() :
+       m_signaturePropertiesCounter(0),
+       m_targetRestrictionObjectFound(false),
+       m_parserSchema(this)
+{
+       /**
+        * member func pointers map
+        */
+       m_parserSchema.addBeginTagCallback(TOKEN_SIGNATURE,
+                                                                          XML_NAMESPACE,
+                                                                          &SignatureReader::blankFunction);
+       m_parserSchema.addBeginTagCallback(TOKEN_SIGNED_INFO,
+                                                                          XML_NAMESPACE,
+                                                                          &SignatureReader::blankFunction);
+       m_parserSchema.addBeginTagCallback(TOKEN_CANONICALIZATION_METHOD,
+                                                                          XML_NAMESPACE,
+                                                                          &SignatureReader::blankFunction);
+       m_parserSchema.addBeginTagCallback(TOKEN_SIGNATURE_METHOD,
+                                                                          XML_NAMESPACE,
+                                                                          &SignatureReader::blankFunction);
+       m_parserSchema.addBeginTagCallback(TOKEN_REFERENCE,
+                                                                          XML_NAMESPACE,
+                                                                          &SignatureReader::blankFunction);
+       m_parserSchema.addBeginTagCallback(TOKEN_TRANSFORMS,
+                                                                          XML_NAMESPACE,
+                                                                          &SignatureReader::blankFunction);
+       m_parserSchema.addBeginTagCallback(TOKEN_TRANSFORM,
+                                                                          XML_NAMESPACE,
+                                                                          &SignatureReader::blankFunction);
+       m_parserSchema.addBeginTagCallback(TOKEN_DIGEST_METHOD,
+                                                                          XML_NAMESPACE,
+                                                                          &SignatureReader::blankFunction);
+       m_parserSchema.addBeginTagCallback(TOKEN_DIGEST_VALUE,
+                                                                          XML_NAMESPACE,
+                                                                          &SignatureReader::blankFunction);
+       m_parserSchema.addBeginTagCallback(TOKEN_SIGNATURE_VALUE,
+                                                                          XML_NAMESPACE,
+                                                                          &SignatureReader::blankFunction);
+       m_parserSchema.addBeginTagCallback(TOKEN_KEY_INFO,
+                                                                          XML_NAMESPACE,
+                                                                          &SignatureReader::tokenKeyInfo);
+       m_parserSchema.addBeginTagCallback(TOKEN_X509DATA,
+                                                                          XML_NAMESPACE,
+                                                                          &SignatureReader::tokenX509Data);
+       m_parserSchema.addBeginTagCallback(TOKEN_X509CERTIFICATE,
+                                                                          XML_NAMESPACE,
+                                                                          &SignatureReader::tokenX509Certificate);
+       m_parserSchema.addBeginTagCallback(TOKEN_ECKEY_VALUE,
+                                                                          XML_NAMESPACE,
+                                                                          &SignatureReader::blankFunction);
+       m_parserSchema.addBeginTagCallback(TOKEN_NAMED_CURVE,
+                                                                          XML_NAMESPACE,
+                                                                          &SignatureReader::tokenNamedCurve);
+       m_parserSchema.addBeginTagCallback(TOKEN_PUBLIC_KEY,
+                                                                          XML_NAMESPACE,
+                                                                          &SignatureReader::tokenPublicKey);
+       m_parserSchema.addBeginTagCallback(TOKEN_OBJECT,
+                                                                          XML_NAMESPACE,
+                                                                          &SignatureReader::tokenObject);
+       m_parserSchema.addBeginTagCallback(TOKEN_SIGNATURE_PROPERTIES,
+                                                                          XML_NAMESPACE,
+                                                                          &SignatureReader::tokenSignatureProperties);
+       m_parserSchema.addBeginTagCallback(TOKEN_SIGNATURE_PROPERTY,
+                                                                          XML_NAMESPACE,
+                                                                          &SignatureReader::blankFunction);
+       m_parserSchema.addBeginTagCallback(TOKEN_PROFILE,
+                                                                          XML_OBJ_NS,
+                                                                          &SignatureReader::tokenProfile);
+       m_parserSchema.addBeginTagCallback(TOKEN_ROLE,
+                                                                          XML_OBJ_NS,
+                                                                          &SignatureReader::tokenRole);
+       m_parserSchema.addBeginTagCallback(TOKEN_IDENTIFIER,
+                                                                          XML_OBJ_NS,
+                                                                          &SignatureReader::blankFunction);
+       m_parserSchema.addBeginTagCallback(TOKEN_KEY_VALUE,
+                                                                          XML_NAMESPACE,
+                                                                          &SignatureReader::blankFunction);
+       m_parserSchema.addBeginTagCallback(TOKEN_DSAKEYVALUE,
+                                                                          XML_NAMESPACE,
+                                                                          &SignatureReader::blankFunction);
+       m_parserSchema.addBeginTagCallback(TOKEN_DSA_P_COMPONENT,
+                                                                          XML_NAMESPACE,
+                                                                          &SignatureReader::blankFunction);
+       m_parserSchema.addBeginTagCallback(TOKEN_DSA_Q_COMPONENT,
+                                                                          XML_NAMESPACE,
+                                                                          &SignatureReader::blankFunction);
+       m_parserSchema.addBeginTagCallback(TOKEN_DSA_G_COMPONENT,
+                                                                          XML_NAMESPACE,
+                                                                          &SignatureReader::blankFunction);
+       m_parserSchema.addBeginTagCallback(TOKEN_DSA_Y_COMPONENT,
+                                                                          XML_NAMESPACE,
+                                                                          &SignatureReader::blankFunction);
+       m_parserSchema.addBeginTagCallback(TOKEN_DSA_J_COMPONENT,
+                                                                          XML_NAMESPACE,
+                                                                          &SignatureReader::blankFunction);
+       m_parserSchema.addBeginTagCallback(TOKEN_DSA_SEED_COMPONENT,
+                                                                          XML_NAMESPACE,
+                                                                          &SignatureReader::blankFunction);
+       m_parserSchema.addBeginTagCallback(TOKEN_DSA_PGENCOUNTER_COMPONENT,
+                                                                          XML_NAMESPACE,
+                                                                          &SignatureReader::blankFunction);
+       m_parserSchema.addBeginTagCallback(TOKEN_RSA_KEY_VALUE,
+                                                                          XML_NAMESPACE,
+                                                                          &SignatureReader::blankFunction);
+       m_parserSchema.addBeginTagCallback(TOKEN_MODULUS_COMPONENT,
+                                                                          XML_NAMESPACE,
+                                                                          &SignatureReader::blankFunction);
+       m_parserSchema.addBeginTagCallback(TOKEN_EXPONENT_COMPONENT,
+                                                                          XML_NAMESPACE,
+                                                                          &SignatureReader::blankFunction);
+       m_parserSchema.addBeginTagCallback(TOKEN_TARGET_RESTRICTION,
+                                                                          XML_NAMESPACE_DIGITALSIG,
+                                                                          &SignatureReader::tokenTargetRestriction);
+       m_parserSchema.addEndTagCallback(TOKEN_SIGNATURE,
+                                                                        XML_NAMESPACE,
+                                                                        &SignatureReader::blankFunction);
+       m_parserSchema.addEndTagCallback(TOKEN_SIGNED_INFO,
+                                                                        XML_NAMESPACE,
+                                                                        &SignatureReader::blankFunction);
+       m_parserSchema.addEndTagCallback(TOKEN_CANONICALIZATION_METHOD,
+                                                                        XML_NAMESPACE,
+                                                                        &SignatureReader::blankFunction);
+       m_parserSchema.addEndTagCallback(TOKEN_SIGNATURE_METHOD,
+                                                                        XML_NAMESPACE,
+                                                                        &SignatureReader::blankFunction);
+       m_parserSchema.addEndTagCallback(TOKEN_REFERENCE,
+                                                                        XML_NAMESPACE,
+                                                                        &SignatureReader::blankFunction);
+       m_parserSchema.addEndTagCallback(TOKEN_TRANSFORMS,
+                                                                        XML_NAMESPACE,
+                                                                        &SignatureReader::blankFunction);
+       m_parserSchema.addEndTagCallback(TOKEN_TRANSFORM,
+                                                                        XML_NAMESPACE,
+                                                                        &SignatureReader::blankFunction);
+       m_parserSchema.addEndTagCallback(TOKEN_DIGEST_METHOD,
+                                                                        XML_NAMESPACE,
+                                                                        &SignatureReader::blankFunction);
+       m_parserSchema.addEndTagCallback(TOKEN_DIGEST_VALUE,
+                                                                        XML_NAMESPACE,
+                                                                        &SignatureReader::blankFunction);
+       m_parserSchema.addEndTagCallback(TOKEN_SIGNATURE_VALUE,
+                                                                        XML_NAMESPACE,
+                                                                        &SignatureReader::blankFunction);
+       m_parserSchema.addEndTagCallback(TOKEN_KEY_INFO,
+                                                                        XML_NAMESPACE,
+                                                                        &SignatureReader::tokenEndKeyInfo);
+       m_parserSchema.addEndTagCallback(TOKEN_X509DATA,
+                                                                        XML_NAMESPACE,
+                                                                        &SignatureReader::tokenEndX509Data);
+       m_parserSchema.addEndTagCallback(TOKEN_X509CERTIFICATE,
+                                                                        XML_NAMESPACE,
+                                                                        &SignatureReader::tokenEndX509Certificate);
+       m_parserSchema.addEndTagCallback(TOKEN_ECKEY_VALUE,
+                                                                        XML_NAMESPACE,
+                                                                        &SignatureReader::tokenEndECKeyValue);
+       m_parserSchema.addEndTagCallback(TOKEN_PUBLIC_KEY,
+                                                                        XML_NAMESPACE,
+                                                                        &SignatureReader::tokenEndPublicKey);
+       m_parserSchema.addEndTagCallback(TOKEN_OBJECT,
+                                                                        XML_NAMESPACE,
+                                                                        &SignatureReader::tokenEndObject);
+       m_parserSchema.addEndTagCallback(TOKEN_SIGNATURE_PROPERTIES,
+                                                                        XML_NAMESPACE,
+                                                                        &SignatureReader::blankFunction);
+       m_parserSchema.addEndTagCallback(TOKEN_SIGNATURE_PROPERTY,
+                                                                        XML_NAMESPACE,
+                                                                        &SignatureReader::blankFunction);
+       m_parserSchema.addEndTagCallback(TOKEN_PROFILE,
+                                                                        XML_OBJ_NS,
+                                                                        &SignatureReader::blankFunction);
+       m_parserSchema.addEndTagCallback(TOKEN_ROLE,
+                                                                        XML_OBJ_NS,
+                                                                        &SignatureReader::blankFunction);
+       m_parserSchema.addEndTagCallback(TOKEN_IDENTIFIER,
+                                                                        XML_OBJ_NS,
+                                                                        &SignatureReader::tokenEndIdentifier);
+       m_parserSchema.addEndTagCallback(TOKEN_KEY_VALUE,
+                                                                        XML_NAMESPACE,
+                                                                        &SignatureReader::blankFunction);
+       m_parserSchema.addEndTagCallback(TOKEN_DSAKEYVALUE,
+                                                                        XML_NAMESPACE,
+                                                                        &SignatureReader::tokenEndDSAKeyValue);
+       m_parserSchema.addEndTagCallback(TOKEN_DSA_P_COMPONENT,
+                                                                        XML_NAMESPACE,
+                                                                        &SignatureReader::tokenEndDSAPComponent);
+       m_parserSchema.addEndTagCallback(TOKEN_DSA_Q_COMPONENT,
+                                                                        XML_NAMESPACE,
+                                                                        &SignatureReader::tokenEndDSAQComponent);
+       m_parserSchema.addEndTagCallback(TOKEN_DSA_G_COMPONENT,
+                                                                        XML_NAMESPACE,
+                                                                        &SignatureReader::tokenEndDSAGComponent);
+       m_parserSchema.addEndTagCallback(TOKEN_DSA_Y_COMPONENT,
+                                                                        XML_NAMESPACE,
+                                                                        &SignatureReader::tokenEndDSAYComponent);
+       m_parserSchema.addEndTagCallback(TOKEN_DSA_J_COMPONENT,
+                                                                        XML_NAMESPACE,
+                                                                        &SignatureReader::tokenEndDSAJComponent);
+       m_parserSchema.addEndTagCallback(TOKEN_DSA_SEED_COMPONENT,
+                                                                        XML_NAMESPACE,
+                                                                        &SignatureReader::tokenEndDSASeedComponent);
+       m_parserSchema.addEndTagCallback(TOKEN_DSA_PGENCOUNTER_COMPONENT,
+                                                                        XML_NAMESPACE,
+                                                                        &SignatureReader::tokenEndDSAPGenCounterComponent);
+       m_parserSchema.addEndTagCallback(TOKEN_RSA_KEY_VALUE,
+                                                                        XML_NAMESPACE,
+                                                                        &SignatureReader::tokenEndRSAKeyValue);
+       m_parserSchema.addEndTagCallback(TOKEN_MODULUS_COMPONENT,
+                                                                        XML_NAMESPACE,
+                                                                        &SignatureReader::tokenEndKeyModulus);
+       m_parserSchema.addEndTagCallback(TOKEN_EXPONENT_COMPONENT,
+                                                                        XML_NAMESPACE,
+                                                                        &SignatureReader::tokenEndKeyExponent);
+       m_parserSchema.addEndTagCallback(TOKEN_TARGET_RESTRICTION,
+                                                                        XML_NAMESPACE,
+                                                                        &SignatureReader::blankFunction);
+}
+
+
+void SignatureReader::initialize(
+       SignatureData &signatureData,
+       const std::string &xmlscheme)
+{
+       m_parserSchema.initialize(
+               signatureData.getSignatureFileName(),
+               true,
+               SaxReader::VALIDATION_XMLSCHEME,
+               xmlscheme);
+}
+
+void SignatureReader::read(SignatureData &signatureData)
+{
+       m_parserSchema.read(signatureData);
+}
+
+void SignatureReader::blankFunction(SignatureData &)
+{
+}
+
+void SignatureReader::tokenKeyInfo(SignatureData &)
+{
+}
+
+void SignatureReader::tokenX509Data(SignatureData &)
+{
+}
+
+void SignatureReader::tokenX509Certificate(SignatureData &)
+{
+}
+
+void SignatureReader::tokenPublicKey(SignatureData &)
+{
+}
+
+void SignatureReader::tokenNamedCurve(SignatureData &)
+{
+       m_nameCurveURI = m_parserSchema.getReader().attribute(TOKEN_URI);
+}
+
+void SignatureReader::tokenTargetRestriction(SignatureData &signatureData)
+{
+       std::string IMEI = m_parserSchema.getReader().attribute(TOKEN_IMEI);
+       std::string MEID = m_parserSchema.getReader().attribute(TOKEN_MEID);
+
+       //less verbose way to say (IMEI && MEID) || (!IMEI && !MEID)
+       if (IMEI.empty() == MEID.empty()) {
+               //WAC 2.0 WR-4650 point 4
+               VcoreThrowMsg(SignatureReader::Exception::TargetRestriction,
+                                         "TargetRestriction should contain exactly one attribute.");
+       }
+
+       if (!IMEI.empty()) {
+               signatureData.m_imeiList.push_back(IMEI);
+       }
+
+       if (!MEID.empty()) {
+               signatureData.m_meidList.push_back(MEID);
+       }
+}
+
+void SignatureReader::tokenEndKeyInfo(SignatureData &)
+{
+}
+
+void SignatureReader::tokenEndX509Data(SignatureData &)
+{
+}
+
+void SignatureReader::tokenEndX509Certificate(SignatureData &signatureData)
+{
+       CertificateLoader loader;
+
+       if (CertificateLoader::NO_ERROR !=
+                       loader.loadCertificateFromRawData(m_parserSchema.getText())) {
+               fprintf(stderr, "## [validate error]: Certificate could not be loaded\n");
+               VcoreThrowMsg(ParserSchemaException::CertificateLoaderError,
+                                         "Certificate could not be loaded");
+       }
+
+       signatureData.m_certList.push_back(loader.getCertificatePtr());
+}
+
+void SignatureReader::tokenEndRSAKeyValue(SignatureData &signatureData)
+{
+       CertificateLoader loader;
+
+       if (CertificateLoader::NO_ERROR !=
+                       loader.loadCertificateBasedOnExponentAndModulus(m_modulus,
+                                       m_exponent)) {
+               fprintf(stderr, "## [validate error]: Certificate could not be loaded\n");
+               VcoreThrowMsg(ParserSchemaException::CertificateLoaderError,
+                                         "Certificate could not be loaded");
+       }
+
+       signatureData.m_certList.push_back(loader.getCertificatePtr());
+}
+
+void SignatureReader::tokenEndKeyModulus(SignatureData &)
+{
+       m_modulus = m_parserSchema.getText();
+}
+
+void SignatureReader::tokenEndKeyExponent(SignatureData &)
+{
+       m_exponent = m_parserSchema.getText();
+}
+
+void SignatureReader::tokenEndPublicKey(SignatureData &)
+{
+       m_publicKey = m_parserSchema.getText();
+}
+
+void SignatureReader::tokenEndECKeyValue(SignatureData &signatureData)
+{
+       CertificateLoader loader;
+
+       if (CertificateLoader::NO_ERROR !=
+                       loader.loadCertificateWithECKEY(m_nameCurveURI, m_publicKey)) {
+               fprintf(stderr, "## [validate error]: Certificate could not be loaded\n");
+               VcoreThrowMsg(ParserSchemaException::CertificateLoaderError,
+                                         "Certificate could not be loaded");
+       }
+
+       signatureData.m_certList.push_back(loader.getCertificatePtr());
+}
+
+void SignatureReader::tokenEndObject(SignatureData &signatureData)
+{
+       m_signaturePropertiesCounter = 0;
+
+       if (((!signatureData.m_imeiList.empty()) ||
+                       (!signatureData.m_meidList.empty())) &&
+                       m_targetRestrictionObjectFound) {
+               //WAC 2.0 WR-4650 point 1
+               VcoreThrowMsg(SignatureReader::Exception::TargetRestriction,
+                                         "TargetRestriction should contain exactly one ds:Object "
+                                         "containing zero or more wac:TargetRestriction children.");
+       }
+
+       if ((!signatureData.m_imeiList.empty()) ||
+                       (!signatureData.m_meidList.empty())) {
+               m_targetRestrictionObjectFound = true;
+       }
+}
+void SignatureReader::tokenEndDSAPComponent(SignatureData &)
+{
+       m_dsaKeyPComponent = m_parserSchema.getText();
+}
+
+void SignatureReader::tokenEndDSAQComponent(SignatureData &)
+{
+       m_dsaKeyQComponent = m_parserSchema.getText();
+}
+
+void SignatureReader::tokenEndDSAGComponent(SignatureData &)
+{
+       m_dsaKeyGComponent = m_parserSchema.getText();
+}
+
+void SignatureReader::tokenEndDSAYComponent(SignatureData &)
+{
+       m_dsaKeyYComponent = m_parserSchema.getText();
+}
+
+void SignatureReader::tokenEndDSAJComponent(SignatureData &)
+{
+       m_dsaKeyJComponent = m_parserSchema.getText();
+}
+
+void SignatureReader::tokenEndDSASeedComponent(SignatureData &)
+{
+       m_dsaKeySeedComponent = m_parserSchema.getText();
+}
+
+void SignatureReader::tokenEndDSAPGenCounterComponent(SignatureData &)
+{
+       m_dsaKeyPGenCounter = m_parserSchema.getText();
+}
+
+void SignatureReader::tokenEndDSAKeyValue(SignatureData &signatureData)
+{
+       CertificateLoader loader;
+
+       if (CertificateLoader::NO_ERROR !=
+                       loader.loadCertificateBasedOnDSAComponents(m_dsaKeyPComponent,
+                                       m_dsaKeyQComponent,
+                                       m_dsaKeyGComponent,
+                                       m_dsaKeyYComponent,
+                                       m_dsaKeyJComponent,
+                                       m_dsaKeySeedComponent,
+                                       m_dsaKeyPGenCounter)) {
+               fprintf(stderr, "## [validate error]: Certificate could not be loaded\n");
+               VcoreThrowMsg(ParserSchemaException::CertificateLoaderError,
+                                         "Certificate could not be loaded.");
+       }
+
+       signatureData.m_certList.push_back(loader.getCertificatePtr());
+}
+
+void SignatureReader::tokenRole(SignatureData &signatureData)
+{
+       if (!signatureData.m_roleURI.empty()) {
+               fprintf(stderr, "## [validate error]: Multiple definition of Role is not allowed\n");
+               VcoreThrowMsg(ParserSchemaException::UnsupportedValue,
+                                         "Multiple definition of Role is not allowed.");
+       }
+
+       signatureData.m_roleURI = m_parserSchema.getReader().attribute(TOKEN_URI);
+}
+
+void SignatureReader::tokenProfile(SignatureData &signatureData)
+{
+       if (!signatureData.m_profileURI.empty()) {
+               fprintf(stderr, "## [validate error]: Multiple definition of Profile is not allowed\n");
+               VcoreThrowMsg(ParserSchemaException::UnsupportedValue,
+                                         "Multiple definition of Profile is not allowed.");
+       }
+
+       signatureData.m_profileURI = m_parserSchema.getReader().attribute(TOKEN_URI);
+}
+
+void SignatureReader::tokenEndIdentifier(SignatureData &signatureData)
+{
+       if (!signatureData.m_identifier.empty()) {
+               fprintf(stderr, "## [validate error]: Multiple definition of Identifier is not allowed\n");
+               VcoreThrowMsg(ParserSchemaException::UnsupportedValue,
+                                         "Multiple definition of Identifier is not allowed.");
+       }
+
+       signatureData.m_identifier = m_parserSchema.getText();
+}
+
+void SignatureReader::tokenObject(SignatureData &signatureData)
+{
+       std::string id = m_parserSchema.getReader().attribute(TOKEN_ID);
+
+       if (id.empty()) {
+               fprintf(stderr, "## [validate error]: Unsupported value of Attribute Id in Object tag\n");
+               VcoreThrowMsg(ParserSchemaException::UnsupportedValue,
+                                         "Unsupported value of Attribute Id in Object tag.");
+       }
+
+       signatureData.m_objectList.push_back(id);
+}
+
+void SignatureReader::tokenSignatureProperties(SignatureData &)
+{
+       if (++m_signaturePropertiesCounter > 1) {
+               fprintf(stderr, "## [validate error]: Only one SignatureProperties tag is allowed in Object\n");
+               VcoreThrowMsg(ParserSchemaException::UnsupportedValue,
+                                         "Only one SignatureProperties tag is allowed in Object");
+       }
+}
+} // namespace ValidationCore
diff --git a/src/vcore/SignatureReader.h b/src/vcore/SignatureReader.h
new file mode 100644 (file)
index 0000000..846db22
--- /dev/null
@@ -0,0 +1,115 @@
+/*
+ * Copyright (c) 2011 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        SignatureReader.h
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief       SignatureReader is used to parse widget digital signature.
+ */
+#ifndef _VALIDATION_CORE_SIGNATUREREADER_H_
+#define _VALIDATION_CORE_SIGNATUREREADER_H_
+
+#include <vcore/SignatureData.h>
+#include <vcore/ParserSchema.h>
+#include <vcore/exception.h>
+
+#include <map>
+
+namespace ValidationCore {
+
+class SignatureReader {
+public:
+       class Exception {
+       public:
+               VCORE_DECLARE_EXCEPTION_TYPE(ValidationCore::Exception, Base);
+               VCORE_DECLARE_EXCEPTION_TYPE(Base, TargetRestriction);
+       };
+
+       SignatureReader();
+
+       void initialize(SignatureData &signatureData, const std::string &xmlscheme);
+
+       void read(SignatureData &signatureData);
+
+private:
+       void blankFunction(SignatureData &signatureData);
+
+       void tokenKeyInfo(SignatureData &signatureData);
+       void tokenKeyModulus(SignatureData &signatureData);
+       void tokenKeyExponent(SignatureData &signatureData);
+       void tokenX509Data(SignatureData &signatureData);
+       void tokenX509Certificate(SignatureData &signatureData);
+       void tokenPublicKey(SignatureData &signatureData);
+       void tokenNamedCurve(SignatureData &signatureData);
+       void tokenRole(SignatureData &signatureData);
+       void tokenProfile(SignatureData &signatureData);
+       void tokenObject(SignatureData &signatureData);
+       void tokenSignatureProperties(SignatureData &signatureData);
+
+       void tokenTargetRestriction(SignatureData &signatureData);
+
+       void tokenEndKeyInfo(SignatureData &signatureData);
+       // KW     void tokenEndKeyName(SignatureData &signatureData);
+
+       void tokenEndRSAKeyValue(SignatureData &signatureData);
+
+       void tokenEndKeyModulus(SignatureData &signatureData);
+       void tokenEndKeyExponent(SignatureData &signatureData);
+       void tokenEndX509Data(SignatureData &signatureData);
+
+       void tokenEndX509Certificate(SignatureData &signatureData);
+
+       void tokenEndPublicKey(SignatureData &signatureData);
+       void tokenEndECKeyValue(SignatureData &signatureData);
+       void tokenEndIdentifier(SignatureData &signatureData);
+       void tokenEndObject(SignatureData &signatureData);
+
+       // DSA key components
+       void tokenEndDSAPComponent(SignatureData &signatureData);
+       void tokenEndDSAQComponent(SignatureData &signatureData);
+       void tokenEndDSAGComponent(SignatureData &signatureData);
+       void tokenEndDSAYComponent(SignatureData &signatureData);
+       void tokenEndDSAJComponent(SignatureData &signatureData);
+
+       void tokenEndDSAKeyValue(SignatureData &signatureData);
+
+       void tokenEndDSASeedComponent(SignatureData &signatureData);
+       void tokenEndDSAPGenCounterComponent(SignatureData &signatureData);
+
+       // temporary values required due reference parsing process
+       // optional parameters for dsa
+       std::string m_dsaKeyPComponent;
+       std::string m_dsaKeyQComponent;
+       std::string m_dsaKeyGComponent;
+       std::string m_dsaKeyYComponent;
+       std::string m_dsaKeyJComponent;
+       std::string m_dsaKeySeedComponent;
+       std::string m_dsaKeyPGenCounter;
+       // temporary values of ecdsa key
+       std::string m_publicKey;
+       std::string m_nameCurveURI;
+       std::string m_modulus;
+       std::string m_exponent;
+
+       // temporary values required due Object parsing
+       int m_signaturePropertiesCounter;
+       bool m_targetRestrictionObjectFound;
+
+       ParserSchema<SignatureReader, SignatureData> m_parserSchema;
+};
+}
+
+#endif // _VALIDATION_CORE_SIGNATUREREADER_H_
diff --git a/src/vcore/SignatureValidator.cpp b/src/vcore/SignatureValidator.cpp
new file mode 100644 (file)
index 0000000..1007f95
--- /dev/null
@@ -0,0 +1,648 @@
+/*
+ * Copyright (c) 2011 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        SignatureValidator.cpp
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @author      Sangwan Kwon (sangwan.kwon@samsung.com)
+ * @version     1.0
+ * @brief       Implementatin of tizen signature validation protocol.
+ */
+
+#include <memory>
+#include <string>
+#include <utility>
+
+#include <dpl/log/log.h>
+
+#include <vcore/CertificateCollection.h>
+#include <vcore/Certificate.h>
+#include <vcore/ReferenceValidator.h>
+#include <vcore/ValidatorFactories.h>
+#include <vcore/XmlsecAdapter.h>
+#include <vcore/SignatureReader.h>
+#include <vcore/SignatureFinder.h>
+#include <vcore/Ocsp.h>
+#include <vcore/PluginHandler.h>
+
+#include <vcore/SignatureValidator.h>
+
+#ifdef TIZEN_PROFILE_MOBILE
+#include <cchecker/ocsp.h>
+#endif
+
+using namespace ValidationCore::CertStoreId;
+
+namespace {
+
+const std::string TOKEN_PREFIX          = "http://www.w3.org/ns/widgets-digsig#";
+const std::string TOKEN_ROLE_AUTHOR_URI = TOKEN_PREFIX + "role-author";
+const std::string TOKEN_ROLE_DIST_URI   = TOKEN_PREFIX + "role-distributor";
+const std::string TOKEN_PROFILE_URI     = TOKEN_PREFIX + "profile";
+
+enum class CertTimeStatus : int {
+       VALID,
+       NOT_YET,
+       EXPIRED
+};
+
+inline time_t _getMidTime(time_t lower, time_t upper)
+{
+       return (lower >> 1) + (upper >> 1);
+}
+
+inline CertTimeStatus _timeValidation(time_t lower, time_t upper, time_t current)
+{
+       if (current < lower)
+               return CertTimeStatus::NOT_YET;
+       else if (current > upper)
+               return CertTimeStatus::EXPIRED;
+       else
+               return CertTimeStatus::VALID;
+}
+
+inline bool _isTimeStrict(const Set &stores)
+{
+       return (stores.contains(TIZEN_TEST) || stores.contains(TIZEN_VERIFY))
+                  ? true : false;
+}
+
+} // namespace anonymous
+
+
+namespace ValidationCore {
+
+class SignatureValidator::Impl {
+public:
+       Impl(const SignatureFileInfo &info);
+       virtual ~Impl() {};
+
+       VCerr check(
+               const std::string &contentPath,
+               bool checkOcsp,
+               bool checkReferences,
+               SignatureData &outData);
+
+       VCerr checkList(
+               bool checkOcsp,
+               const UriList &uriList,
+               SignatureData &outData);
+
+       VCerr makeChainBySignature(
+               bool completeWithSystemCert,
+               CertificateList &certList);
+
+       std::string errorToString(VCerr code);
+
+private:
+       VCerr baseCheck(
+               const std::string &contentPath,
+               bool checkOcsp,
+               bool checkReferences);
+
+       VCerr baseCheckList(
+               bool checkOcsp,
+               const UriList &uriList);
+
+       VCerr makeDataBySignature(bool completeWithSystemCert);
+       VCerr additionalCheck(VCerr result);
+
+       VCerr parseSignature(void);
+       VCerr preStep(void);
+       bool checkRoleURI(void);
+       bool checkProfileURI(void);
+       bool checkObjectReferences(void);
+
+       PluginHandler m_pluginHandler;
+       SignatureFileInfo m_fileInfo;
+       XmlSec::XmlSecContext m_context;
+       SignatureData m_data;
+       bool m_disregarded;
+};
+
+
+SignatureValidator::Impl::Impl(const SignatureFileInfo &info) :
+       m_fileInfo(info),
+       m_disregarded(false)
+{
+}
+
+bool SignatureValidator::Impl::checkRoleURI(void)
+{
+       std::string roleURI = m_data.getRoleURI();
+
+       if (roleURI.empty()) {
+               LogWarning("URI attribute in Role tag couldn't be empty.");
+               return false;
+       }
+
+       if (roleURI != TOKEN_ROLE_AUTHOR_URI && m_data.isAuthorSignature()) {
+               LogWarning("URI attribute in Role tag does not "
+                                  "match with signature filename.");
+               return false;
+       }
+
+       if (roleURI != TOKEN_ROLE_DIST_URI && !m_data.isAuthorSignature()) {
+               LogWarning("URI attribute in Role tag does not "
+                                  "match with signature filename.");
+               return false;
+       }
+
+       return true;
+}
+
+
+bool SignatureValidator::Impl::checkProfileURI(void)
+{
+       if (TOKEN_PROFILE_URI != m_data.getProfileURI()) {
+               LogWarning("Profile tag contains unsupported value "
+                                  "in URI attribute " << m_data.getProfileURI());
+               return false;
+       }
+
+       return true;
+}
+
+bool SignatureValidator::Impl::checkObjectReferences(void)
+{
+       for (const auto &object : m_data.getObjectList()) {
+               if (!m_data.containObjectReference(object)) {
+                       LogWarning("Signature does not contain reference for object " << object);
+                       return false;
+               }
+       }
+
+       return true;
+}
+
+VCerr SignatureValidator::Impl::additionalCheck(VCerr result)
+{
+       try {
+               if (m_pluginHandler.fail()) {
+                       LogInfo("No validator plugin found. Skip additional check.");
+                       return result;
+               }
+
+               return m_pluginHandler.step(result, m_data);
+       } catch (...) {
+               LogError("Exception in additional check by plugin.");
+               return E_SIG_PLUGIN;
+       }
+}
+
+VCerr SignatureValidator::Impl::parseSignature(void)
+{
+       try {
+               SignatureReader xml;
+               xml.initialize(m_data, SIGNATURE_SCHEMA_PATH);
+               xml.read(m_data);
+       } catch (ParserSchemaException::CertificateLoaderError &e) {
+               LogError("Certificate loader error: " << e.DumpToString());
+               return E_SIG_INVALID_CERT;
+       } catch (...) {
+               LogError("Failed to parse signature file by signature reader.");
+               return E_SIG_INVALID_FORMAT;
+       }
+
+       return E_SIG_NONE;
+}
+
+/*
+ *  Make SignatureData by parsing signature file.
+ *  and get certificate chain with attached certificate in signature
+ */
+VCerr SignatureValidator::Impl::makeDataBySignature(bool completeWithSystemCert)
+{
+       LogDebug("Start to make chain.");
+       m_data = SignatureData(m_fileInfo.getFileName(), m_fileInfo.getFileNumber());
+
+       if (parseSignature()) {
+               LogError("Failed to parse signature.");
+               return E_SIG_INVALID_FORMAT;
+       }
+
+       if (!checkRoleURI() || !checkProfileURI())
+               return E_SIG_INVALID_FORMAT;
+
+       try {
+               CertificateCollection collection;
+               // Load Certificates and make chain.
+               collection.load(m_data.getCertList());
+
+               if (!collection.sort() || collection.empty()) {
+                       LogError("Certificates do not form valid chain.");
+                       return E_SIG_INVALID_CHAIN;
+               }
+
+               // Add root certificate to chain.
+               if (completeWithSystemCert && !collection.completeCertificateChain()) {
+                       if (m_data.isAuthorSignature() || m_data.getSignatureNumber() == 1) {
+                               LogError("Failed to complete cert chain with system cert");
+                               return E_SIG_INVALID_CHAIN;
+                       } else {
+                               LogDebug("Distributor N's certificate has got "
+                                                "unrecognized root CA certificate.");
+                               m_disregarded = true;
+                       }
+               }
+
+               m_data.setSortedCertificateList(collection.getChain());
+               LogDebug("Finish making chain successfully.");
+       } catch (const CertificateCollection::Exception::Base &e) {
+               LogError("CertificateCollection exception : " << e.DumpToString());
+               return E_SIG_INVALID_CHAIN;
+       } catch (const std::exception &e) {
+               LogError("std exception occured : " << e.what());
+               return E_SIG_UNKNOWN;
+       } catch (...) {
+               LogError("Unknown exception in SignatureValidator::makeChainBySignature");
+               return E_SIG_UNKNOWN;
+       }
+
+       return E_SIG_NONE;
+}
+
+VCerr SignatureValidator::Impl::preStep(void)
+{
+       // Make chain process.
+       VCerr result = makeDataBySignature(true);
+
+       if (result != E_SIG_NONE)
+               return result;
+
+       for (const auto &certptr : m_data.getCertList()) {
+               auto storeIdSet = createCertificateIdentifier().find(certptr);
+               if (!storeIdSet.contains(TIZEN_REVOKED))
+                       continue;
+
+               LogInfo("Revoked certificate: " << certptr->getOneLine());
+               return E_SIG_REVOKED;
+       }
+
+       // Get Identifier from fingerprint original, extention file.
+       LogDebug("Start to check certificate domain.");
+       auto certificatePtr = m_data.getCertList().back();
+       auto storeIdSet = createCertificateIdentifier().find(certificatePtr);
+       // Check root CA certificate has proper domain.
+       LogDebug("root certificate from " << storeIdSet.typeToString() << " domain");
+
+       if (m_data.isAuthorSignature()) {
+               if (!storeIdSet.contains(TIZEN_DEVELOPER)) {
+                       LogError("author-signature.xml's root certificate "
+                                        "isn't in tizen developer domain.");
+                       return E_SIG_INVALID_CHAIN;
+               }
+       } else {
+               if (storeIdSet.contains(TIZEN_DEVELOPER)) {
+                       LogError("distributor signautre root certificate "
+                                        "shouldn't be in tizen developer domain.");
+                       return E_SIG_INVALID_CHAIN;
+               }
+
+               if (m_data.getSignatureNumber() == 1 && !storeIdSet.isContainsVis()) {
+                       LogError("signature1.xml has got unrecognized root CA certificate.");
+                       return E_SIG_INVALID_CHAIN;
+               } else if (!storeIdSet.isContainsVis()) {
+                       LogDebug("signatureN.xml has got unrecognized root CA certificate.");
+                       m_disregarded = true;
+               }
+       }
+
+       m_data.setStorageType(storeIdSet);
+       LogDebug("Finish checking certificate domain.");
+       /*
+        * We add only Root CA certificate because the rest
+        * of certificates are present in signature files ;-)
+        */
+       m_context.signatureFile = m_data.getSignatureFileName();
+       m_context.certificatePtr = m_data.getCertList().back();
+       /* certificate time check */
+       time_t lower = m_data.getEndEntityCertificatePtr()->getNotBefore();
+       time_t upper = m_data.getEndEntityCertificatePtr()->getNotAfter();
+       time_t current = time(NULL);
+       CertTimeStatus status = _timeValidation(lower, upper, current);
+
+       if (status != CertTimeStatus::VALID) {
+               LogDebug("Certificate's time is invalid.");
+
+               if (_isTimeStrict(storeIdSet))
+                       return status == CertTimeStatus::EXPIRED
+                                  ? E_SIG_CERT_EXPIRED : E_SIG_CERT_NOT_YET;
+
+               time_t mid = _getMidTime(lower, upper);
+               LogInfo("Use middle notBeforeTime and notAfterTime."
+                               " lower: " << lower
+                               << " upper: " << upper
+                               << " mid: " << mid
+                               << " current: " << current);
+               m_context.validationTime = mid;
+       }
+
+       return E_SIG_NONE;
+}
+
+VCerr SignatureValidator::Impl::baseCheck(
+       const std::string &contentPath,
+       bool checkOcsp,
+       bool checkReferences)
+{
+       try {
+               // Make certificate chain, check certificate info
+               VCerr result = preStep();
+
+               if (result != E_SIG_NONE)
+                       return result;
+
+               // Since disregard case, uncheck root certs in signatureN.xml
+               if (!m_data.isAuthorSignature() && m_data.getSignatureNumber() != 1)
+                       m_context.allowBrokenChain = true;
+
+               // XmlSec validate
+               XmlSecSingleton::Instance().validate(m_context);
+               // Check reference of 'Object' tag - OID
+               m_data.setReference(m_context.referenceSet);
+
+               if (!checkObjectReferences()) {
+                       LogWarning("Failed to check Object References");
+                       return E_SIG_INVALID_REF;
+               }
+
+               // Check reference's existence
+               if (checkReferences) {
+                       ReferenceValidator fileValidator(contentPath);
+
+                       if (ReferenceValidator::NO_ERROR != fileValidator.checkReferences(m_data)) {
+                               LogWarning("Invalid package - file references broken");
+                               return E_SIG_INVALID_REF;
+                       }
+               }
+
+               // Check OCSP
+               if (checkOcsp && Ocsp::check(m_data) == Ocsp::Result::REVOKED) {
+                       LogError("Certificate is Revoked by OCSP server.");
+                       return E_SIG_REVOKED;
+               }
+
+               LogDebug("Signature validation check done successfully ");
+       } catch (const CertificateCollection::Exception::Base &e) {
+               LogError("CertificateCollection exception : " << e.DumpToString());
+               return E_SIG_INVALID_CHAIN;
+       } catch (const XmlSec::Exception::InternalError &e) {
+               LogError("XmlSec internal error : " << e.DumpToString());
+               return E_SIG_INVALID_FORMAT;
+       } catch (const XmlSec::Exception::InvalidFormat &e) {
+               LogError("XmlSec invalid format : " << e.DumpToString());
+               return E_SIG_INVALID_FORMAT;
+       } catch (const XmlSec::Exception::InvalidSig &e) {
+               LogError("XmlSec invalid signature : " << e.DumpToString());
+               return E_SIG_INVALID_SIG;
+       } catch (const XmlSec::Exception::OutOfMemory &e) {
+               LogError("XmlSec out of memory : " << e.DumpToString());
+               return E_SIG_OUT_OF_MEM;
+       } catch (const XmlSec::Exception::Base &e) {
+               LogError("XmlSec unknown exception : " << e.DumpToString());
+               return E_SIG_INVALID_FORMAT;
+       } catch (const Ocsp::Exception::OcspUnsupported &e) {
+               LogInfo("Ocsp unsupported : " << e.DumpToString());
+       } catch (const Ocsp::Exception::Base &e) {
+               LogInfo("Ocsp check throw exeption : " << e.DumpToString());
+#ifdef TIZEN_PROFILE_MOBILE
+               LogInfo("Launch cert-checker.");
+               try {
+                       if (cchecker_ocsp_request() != 0)
+                               LogError("Load cert-checker failed.");
+               } catch (const std::exception &e) {
+                       LogError("std exception occured while cchecker running : " << e.what());
+               } catch (...) {
+                       LogError("Unknown exception occuured while cchecker running. ");
+               }
+#endif
+       } catch (const std::exception &e) {
+               LogError("std exception occured : " << e.what());
+               return E_SIG_UNKNOWN;
+       } catch (...) {
+               LogError("Unknown exception in SignatureValidator::check");
+               return E_SIG_UNKNOWN;
+       }
+
+       return m_disregarded ? E_SIG_DISREGARDED : E_SIG_NONE;
+}
+
+VCerr SignatureValidator::Impl::baseCheckList(
+       bool checkOcsp,
+       const UriList &uriList)
+{
+       try {
+               // Make certificate chain, check certificate info
+               VCerr result = preStep();
+
+               if (result != E_SIG_NONE)
+                       return result;
+
+               // XmlSec validate
+               if (uriList.size() == 0)
+                       XmlSecSingleton::Instance().validateNoHash(m_context);
+               else
+                       XmlSecSingleton::Instance().validatePartialHash(m_context, uriList);
+
+               if (checkOcsp && Ocsp::check(m_data) == Ocsp::Result::REVOKED) {
+                       LogError("Certificate is Revoked by OCSP server.");
+                       return E_SIG_REVOKED;
+               }
+
+               LogDebug("Signature validation of check list done successfully ");
+       } catch (const CertificateCollection::Exception::Base &e) {
+               LogError("CertificateCollection exception : " << e.DumpToString());
+               return E_SIG_INVALID_CHAIN;
+       } catch (const XmlSec::Exception::InternalError &e) {
+               LogError("XmlSec internal error : " << e.DumpToString());
+               return E_SIG_INVALID_FORMAT;
+       } catch (const XmlSec::Exception::InvalidFormat &e) {
+               LogError("XmlSec invalid format : " << e.DumpToString());
+               return E_SIG_INVALID_FORMAT;
+       } catch (const XmlSec::Exception::InvalidSig &e) {
+               LogError("XmlSec invalid signature : " << e.DumpToString());
+               return E_SIG_INVALID_SIG;
+       } catch (const XmlSec::Exception::OutOfMemory &e) {
+               LogError("XmlSec out of memory : " << e.DumpToString());
+               return E_SIG_OUT_OF_MEM;
+       } catch (const XmlSec::Exception::Base &e) {
+               LogError("XmlSec unknown exception : " << e.DumpToString());
+               return E_SIG_INVALID_FORMAT;
+       } catch (const Ocsp::Exception::OcspUnsupported &e) {
+               LogInfo("Ocsp unsupported : " << e.DumpToString());
+       } catch (const Ocsp::Exception::Base &e) {
+               LogInfo("Ocsp check throw exeption : " << e.DumpToString());
+#ifdef TIZEN_PROFILE_MOBILE
+               LogInfo("Launch cert-checker.");
+               try {
+                       if (cchecker_ocsp_request() != 0)
+                               LogError("Load cert-checker failed.");
+               } catch (const std::exception &e) {
+                       LogError("std exception occured while cchecker running : " << e.what());
+               } catch (...) {
+                       LogError("Unknown exception occuured while cchecker running. ");
+               }
+#endif
+       } catch (...) {
+               LogError("Unknown exception in SignatureValidator::checkList");
+               return E_SIG_UNKNOWN;
+       }
+
+       return m_disregarded ? E_SIG_DISREGARDED : E_SIG_NONE;
+}
+
+VCerr SignatureValidator::Impl::check(
+       const std::string &contentPath,
+       bool checkOcsp,
+       bool checkReferences,
+       SignatureData &outData)
+{
+       VCerr result;
+       result = baseCheck(contentPath, checkOcsp, checkReferences);
+       result = additionalCheck(result);
+       outData = m_data;
+       return result;
+}
+
+VCerr SignatureValidator::Impl::checkList(
+       bool checkOcsp,
+       const UriList &uriList,
+       SignatureData &outData)
+{
+       VCerr result;
+       result = baseCheckList(checkOcsp, uriList);
+       result = additionalCheck(result);
+       outData = m_data;
+       return result;
+}
+
+VCerr SignatureValidator::Impl::makeChainBySignature(
+       bool completeWithSystemCert,
+       CertificateList &certList)
+{
+       VCerr result = makeDataBySignature(completeWithSystemCert);
+
+       if (result != E_SIG_NONE)
+               return result;
+
+       certList = m_data.getCertList();
+       return E_SIG_NONE;
+}
+
+std::string SignatureValidator::Impl::errorToString(VCerr code)
+{
+       switch (code) {
+       case E_SIG_NONE:
+               return "Success.";
+
+       case E_SIG_INVALID_FORMAT:
+               return "Invalid format of signature file.";
+
+       case E_SIG_INVALID_CERT:
+               return "Invalid format of certificate in signature.";
+
+       case E_SIG_INVALID_CHAIN:
+               return "Invalid certificate chain with certificate in signature.";
+
+       case E_SIG_INVALID_SIG:
+               return "Invalid signature. Signed with wrong key, changed signature file or changed package file.";
+
+       case E_SIG_INVALID_REF:
+               return "Invalid file reference. An unsinged file was found.";
+
+       case E_SIG_CERT_EXPIRED:
+               return "Certificate in signature was expired.";
+
+       case E_SIG_CERT_NOT_YET:
+               return "Certificate in signature is not valid yet.";
+
+       case E_SIG_DISREGARDED:
+               return "Signature validation can be disregarded in some cases.";
+
+       case E_SIG_REVOKED:
+               return "One of certificate was revoked in certificate chain.";
+
+       case E_SIG_PLUGIN:
+               return "Failed to load plugin for additional validation check.";
+
+       case E_SIG_OUT_OF_MEM:
+               return "Out of memory.";
+
+       case E_SIG_UNKNOWN:
+               return "Unknown error.";
+
+       default:
+               return m_pluginHandler.errorToString(code);
+       }
+}
+
+
+SignatureValidator::SignatureValidator(const SignatureFileInfo &info)
+{
+       std::unique_ptr<SignatureValidator::Impl> impl(new(std::nothrow) SignatureValidator::Impl(info));
+       m_pImpl = std::move(impl);
+}
+SignatureValidator::~SignatureValidator() {}
+
+std::string SignatureValidator::errorToString(VCerr code)
+{
+       if (!m_pImpl)
+               return "out of memory. error.";
+
+       return m_pImpl->errorToString(code);
+}
+
+VCerr SignatureValidator::check(
+       const std::string &contentPath,
+       bool checkOcsp,
+       bool checkReferences,
+       SignatureData &outData)
+{
+       if (!m_pImpl)
+               return E_SIG_OUT_OF_MEM;
+
+       return m_pImpl->check(
+                          contentPath,
+                          checkOcsp,
+                          checkReferences,
+                          outData);
+}
+
+VCerr SignatureValidator::checkList(
+       bool checkOcsp,
+       const UriList &uriList,
+       SignatureData &outData)
+{
+       if (!m_pImpl)
+               return E_SIG_OUT_OF_MEM;
+
+       return m_pImpl->checkList(
+                          checkOcsp,
+                          uriList,
+                          outData);
+}
+
+VCerr SignatureValidator::makeChainBySignature(
+       bool completeWithSystemCert,
+       CertificateList &certList)
+{
+       if (!m_pImpl)
+               return E_SIG_OUT_OF_MEM;
+
+       return m_pImpl->makeChainBySignature(completeWithSystemCert, certList);
+}
+
+} // namespace ValidationCore
diff --git a/src/vcore/SignatureValidator.h b/src/vcore/SignatureValidator.h
new file mode 100644 (file)
index 0000000..8dc4692
--- /dev/null
@@ -0,0 +1,102 @@
+/*
+ * Copyright (c) 2011 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        SignatureValidator.h
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.1
+ * @brief       Implementatin of tizen signature validation protocol.
+ */
+#ifndef _VALIDATION_CORE_SIGNATUREVALIDATOR_H_
+#define _VALIDATION_CORE_SIGNATUREVALIDATOR_H_
+
+#include <string>
+#include <list>
+#include <memory>
+
+#include <vcore/Certificate.h>
+#include <vcore/SignatureData.h>
+#include <vcore/SignatureFinder.h>
+#include <vcore/Error.h>
+
+namespace ValidationCore {
+
+using UriList = std::list<std::string>;
+
+/*
+ *  Types of Reference checking
+ *
+ *  1. XmlSec validate (default)
+ *        - check reference based on Reference tag on signature xml.
+ *        - Get URI from Reference tag, generate digest value and compare it with value written
+ *        - If value with calculated and written isn't same, validate fail returned.
+ *        * What if file doesn't exist which is written on Reference tag?
+ *        * What if Reference tag doesn't exist for existing file? -> cannot checked.
+ *
+ *  2. checkObjectReferences (default on check function, not checkList)
+ *        - check Reference of 'Object' tag.
+ *        - it's mutual-exclusive check with  1. XmlSec validate.
+ *
+ *  3. ReferenceValidator (enabled when flag on)
+ *        - check file based on content path from parameter
+ *        - check is all existing file is on the Reference tag list on signature xml
+ *        - If file path(URI) cannot found on reference set, validate fail returned.
+ *
+ *  Signature validation disregarded case
+ *
+ *  - distributor signature: signature number is 1 and doesn't contain in store id set
+ */
+
+/*
+ *  Error code defined on vcore/Error.h
+ */
+class SignatureValidator {
+public:
+       SignatureValidator(const SignatureFileInfo &info);
+       virtual ~SignatureValidator();
+
+       SignatureValidator() = delete;
+       SignatureValidator(const SignatureValidator &) = delete;
+       const SignatureValidator &operator=(const SignatureValidator &) = delete;
+
+       VCerr check(
+               const std::string &contentPath,
+               bool checkOcsp,
+               bool checkReferences,
+               SignatureData &outData);
+
+       VCerr checkList(
+               bool checkOcsp,
+               const UriList &uriList,
+               SignatureData &outData);
+
+       /*
+        *  @Remarks : cert list isn't completed with self-signed root CA system cert
+        *             if completeWithSystemCert is false.
+        */
+       VCerr makeChainBySignature(
+               bool completeWithSystemCert,
+               CertificateList &certList);
+
+       std::string errorToString(int code);
+
+private:
+       class Impl;
+       std::unique_ptr<Impl> m_pImpl;
+};
+
+} // namespace ValidationCore
+
+#endif // _VALIDATION_CORE_SIGNATUREVALIDATOR_H_
diff --git a/src/vcore/TimeConversion.cpp b/src/vcore/TimeConversion.cpp
new file mode 100644 (file)
index 0000000..45a642b
--- /dev/null
@@ -0,0 +1,360 @@
+/*
+ * 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        TimeConversion.cpp
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @author      Sangwan Kwon (sangwan.kwon@samsung.com)
+ * @version     0.1
+ * @brief
+ */
+#include <vcore/TimeConversion.h>
+#include <dpl/log/log.h>
+
+#include <cstring>
+#include <climits>
+
+#define TIME_MAX LONG_MAX // time_t max value in arch 32bit
+
+namespace {
+
+void _gmtime_adj(struct tm *tm, int offset)
+{
+       time_t t = mktime(tm);
+       t += offset;
+       memset(tm, 0, sizeof(struct tm));
+       gmtime_r(&t, tm);
+}
+
+/*
+ * from openssl/crypto/asn1/a_gentm.c, openssl version 1.0.2d
+ * return 1 on success, 0 on error
+ * 1. local time only                        : yyyymmddHHMMSS[.fff]
+ * 2. UTC time only                          : yyyymmddHHMM[SS[.fff]]Z
+ * 3. Difference between local and UTC times : yyyymmddHHMM[SS[.fff]](+|-)HHMM
+ */
+int asn1_generalizedtime_to_tm(struct tm *tm, const ASN1_GENERALIZEDTIME *d)
+{
+       static const int min[9] = { 0, 0, 1, 1, 0, 0, 0, 0, 0 };
+       static const int max[9] = { 99, 99, 12, 31, 23, 59, 59, 12, 59 };
+       char *a;
+       int n, i, l, o;
+
+       if (d->type != V_ASN1_GENERALIZEDTIME)
+               return (0);
+
+       l = d->length;
+       a = (char *)d->data;
+       o = 0;
+
+       /*
+        * GENERALIZEDTIME is similar to UTCTIME except the year is represented
+        * as YYYY. This stuff treats everything as a two digit field so make
+        * first two fields 00 to 99
+        */
+       if (l < 13)
+               goto err;
+
+       for (i = 0; i < 7; i++) {
+               if ((i == 6) && ((a[o] == 'Z') || (a[o] == '+') || (a[o] == '-'))) {
+                       i++;
+
+                       if (tm)
+                               tm->tm_sec = 0;
+
+                       break;
+               }
+
+               if ((a[o] < '0') || (a[o] > '9'))
+                       goto err;
+
+               n = a[o] - '0';
+
+               if (++o > l)
+                       goto err;
+
+               if ((a[o] < '0') || (a[o] > '9'))
+                       goto err;
+
+               n = (n * 10) + a[o] - '0';
+
+               if (++o > l)
+                       goto err;
+
+               if ((n < min[i]) || (n > max[i]))
+                       goto err;
+
+               if (tm) {
+                       switch (i) {
+                       case 0:
+                               tm->tm_year = n * 100 - 1900;
+                               break;
+
+                       case 1:
+                               tm->tm_year += n;
+                               break;
+
+                       case 2:
+                               tm->tm_mon = n - 1;
+                               break;
+
+                       case 3:
+                               tm->tm_mday = n;
+                               break;
+
+                       case 4:
+                               tm->tm_hour = n;
+                               break;
+
+                       case 5:
+                               tm->tm_min = n;
+                               break;
+
+                       case 6:
+                               tm->tm_sec = n;
+                               break;
+                       }
+               }
+       }
+
+       /*
+        * Optional fractional seconds: decimal point followed by one or more
+        * digits.
+        */
+       if (a[o] == '.') {
+               if (++o > l)
+                       goto err;
+
+               i = o;
+
+               while ((a[o] >= '0') && (a[o] <= '9') && (o <= l))
+                       o++;
+
+               /* Must have at least one digit after decimal point */
+               if (i == o)
+                       goto err;
+       }
+
+       if (a[o] == 'Z') {
+               o++;
+       } else if ((a[o] == '+') || (a[o] == '-')) {
+               int offsign = a[o] == '-' ? -1 : 1, offset = 0;
+               o++;
+
+               if (o + 4 > l)
+                       goto err;
+
+               for (i = 7; i < 9; i++) {
+                       if ((a[o] < '0') || (a[o] > '9'))
+                               goto err;
+
+                       n = a[o] - '0';
+                       o++;
+
+                       if ((a[o] < '0') || (a[o] > '9'))
+                               goto err;
+
+                       n = (n * 10) + a[o] - '0';
+
+                       if ((n < min[i]) || (n > max[i]))
+                               goto err;
+
+                       if (tm) {
+                               if (i == 7)
+                                       offset = n * 3600;
+                               else if (i == 8)
+                                       offset += n * 60;
+                       }
+
+                       o++;
+               }
+
+               if (offset)
+                       _gmtime_adj(tm, offset * offsign);
+       } else if (a[o]) {
+               /* Missing time zone information. */
+               goto err;
+       }
+
+       return (o == l);
+err:
+       return (0);
+}
+
+/*
+ * from openssl/crypto/asn1/a_utctm.c, openssl version 1.0.2d
+ * return 1 on success, 0 on error
+ * 1. yymmddHHMM[SS]Z
+ * 2. yymmddHHMM[SS](+|-)HHMM
+ */
+int asn1_utctime_to_tm(struct tm *tm, const ASN1_UTCTIME *d)
+{
+       static const int min[8] = { 0, 1, 1, 0, 0, 0, 0, 0 };
+       static const int max[8] = { 99, 12, 31, 23, 59, 59, 12, 59 };
+       char *a;
+       int n, i, l, o;
+
+       if (d->type != V_ASN1_UTCTIME)
+               return (0);
+
+       l = d->length;
+       a = (char *)d->data;
+       o = 0;
+
+       if (l < 11)
+               goto err;
+
+       for (i = 0; i < 6; i++) {
+               if ((i == 5) && ((a[o] == 'Z') || (a[o] == '+') || (a[o] == '-'))) {
+                       i++;
+
+                       if (tm)
+                               tm->tm_sec = 0;
+
+                       break;
+               }
+
+               if ((a[o] < '0') || (a[o] > '9'))
+                       goto err;
+
+               n = a[o] - '0';
+
+               if (++o > l)
+                       goto err;
+
+               if ((a[o] < '0') || (a[o] > '9'))
+                       goto err;
+
+               n = (n * 10) + a[o] - '0';
+
+               if (++o > l)
+                       goto err;
+
+               if ((n < min[i]) || (n > max[i]))
+                       goto err;
+
+               if (tm) {
+                       switch (i) {
+                       case 0:
+                               tm->tm_year = n < 50 ? n + 100 : n;
+                               break;
+
+                       case 1:
+                               tm->tm_mon = n - 1;
+                               break;
+
+                       case 2:
+                               tm->tm_mday = n;
+                               break;
+
+                       case 3:
+                               tm->tm_hour = n;
+                               break;
+
+                       case 4:
+                               tm->tm_min = n;
+                               break;
+
+                       case 5:
+                               tm->tm_sec = n;
+                               break;
+                       }
+               }
+       }
+
+       if (a[o] == 'Z') {
+               o++;
+       } else if ((a[o] == '+') || (a[o] == '-')) {
+               int offsign = a[o] == '-' ? -1 : 1, offset = 0;
+               o++;
+
+               if (o + 4 > l)
+                       goto err;
+
+               for (i = 6; i < 8; i++) {
+                       if ((a[o] < '0') || (a[o] > '9'))
+                               goto err;
+
+                       n = a[o] - '0';
+                       o++;
+
+                       if ((a[o] < '0') || (a[o] > '9'))
+                               goto err;
+
+                       n = (n * 10) + a[o] - '0';
+
+                       if ((n < min[i]) || (n > max[i]))
+                               goto err;
+
+                       if (tm) {
+                               if (i == 6)
+                                       offset = n * 3600;
+                               else if (i == 7)
+                                       offset += n * 60;
+                       }
+
+                       o++;
+               }
+
+               if (offset)
+                       _gmtime_adj(tm, offset * offsign);
+       }
+
+       return o == l;
+err:
+       return 0;
+}
+
+} // namespace anonymous
+
+namespace ValidationCore {
+
+int asn1TimeToTimeT(ASN1_TIME *t, time_t *res)
+{
+       if (res == NULL)
+               return 0;
+
+       int ret = 0;
+       struct tm tm;
+       memset(&tm, 0, sizeof(tm));
+
+       if (t->type == V_ASN1_UTCTIME)
+               ret = asn1_utctime_to_tm(&tm, t);
+       else if (t->type == V_ASN1_GENERALIZEDTIME)
+               ret = asn1_generalizedtime_to_tm(&tm, t);
+       else
+               ret = 0;
+
+       if (ret == 0)
+               return 0;
+
+       char buf[27]; // asctime_r return 26 characters
+       LogDebug("Convert asn1 to tm: " << asctime_r(&tm, buf));
+       *res = mktime(&tm);
+
+       // If time_t occured overflow, set TIME_MAX.
+       if (*res == -1) {
+               LogDebug("Occured overflow time_t. it may year 2038 problem.");
+               *res = TIME_MAX;
+       }
+
+       // For Debugging.
+       struct tm localTm;
+       localtime_r(res, &localTm);
+       LogDebug("Result time_t(tm format): " << asctime_r(&localTm, buf));
+       return 1;
+}
+
+} // namespace ValidationCore
diff --git a/src/vcore/TimeConversion.h b/src/vcore/TimeConversion.h
new file mode 100644 (file)
index 0000000..3cf2acd
--- /dev/null
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2011 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        TimeConversion.h
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     0.1
+ * @brief
+ */
+#ifndef _VALIDATION_CORE_TIMECONVERSION_H_
+#define _VALIDATION_CORE_TIMECONVERSION_H_
+
+#include <ctime>
+#include <openssl/asn1.h>
+
+namespace ValidationCore {
+
+/*
+ * openssl/crypto/asn1/a_time.c based version 1.0.2d
+ * return 1 on success, 0 on error
+ */
+int asn1TimeToTimeT(ASN1_TIME *t, time_t *res);
+
+} // namespace ValidationCore
+
+#endif // _VALIDATION_CORE_TIMECONVERSION_H_
diff --git a/src/vcore/ValidatorFactories.cpp b/src/vcore/ValidatorFactories.cpp
new file mode 100644 (file)
index 0000000..79c0e1c
--- /dev/null
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2011 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
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @author      Sangwan kwon (sangwan.kwon@samsung.com)
+ * @version     1.0
+ * @brief
+ */
+#include <vcore/ValidatorFactories.h>
+
+#include <vcore/Certificate.h>
+#include <vcore/CertificateConfigReader.h>
+#include <dpl/log/log.h>
+
+#include <string>
+#include <fstream>
+#include <memory>
+
+namespace ValidationCore {
+
+const CertificateIdentifier &createCertificateIdentifier()
+{
+       static CertificateIdentifier certificateIdentifier;
+       static bool initialized = false;
+
+       if (initialized)
+               return certificateIdentifier;
+
+       std::string file(FINGERPRINT_LIST_PATH);
+       std::string schema(FINGERPRINT_LIST_SCHEMA_PATH);
+       LogDebug("File with fingerprint list is : " << file);
+       LogDebug("File with fingerprint list schema is : " << schema);
+       // Read the fingerprint original list.
+       CertificateConfigReader reader;
+       reader.initialize(file, schema);
+       reader.read(certificateIdentifier);
+
+       if (std::ifstream(FINGERPRINT_LIST_EXT_PATH)) {
+               LogInfo(FINGERPRINT_LIST_EXT_PATH << " exist, add it.");
+               CertificateConfigReader exReader;
+               exReader.initialize(FINGERPRINT_LIST_EXT_PATH, schema);
+               exReader.read(certificateIdentifier);
+       }
+
+       if (std::ifstream(FINGERPRINT_LIST_RW_PATH)) {
+               LogInfo(FINGERPRINT_LIST_RW_PATH << " exist, add it.");
+               CertificateConfigReader rwReader;
+               rwReader.initialize(FINGERPRINT_LIST_RW_PATH, schema);
+               rwReader.read(certificateIdentifier);
+       }
+
+       initialized = true;
+
+       return certificateIdentifier;
+}
+
+} // namespace ValidationCore
diff --git a/src/vcore/ValidatorFactories.h b/src/vcore/ValidatorFactories.h
new file mode 100644 (file)
index 0000000..b5d87b4
--- /dev/null
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2011 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
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     1.0
+ * @brief
+ */
+#ifndef _WRT_ENGINE_SRC_INSTALLER_CORE_VALIDATION_CORE_VALIDATORFACTORY_H_
+#define _WRT_ENGINE_SRC_INSTALLER_CORE_VALIDATION_CORE_VALIDATORFACTORY_H_
+
+#include <vcore/CertificateIdentifier.h>
+
+namespace ValidationCore {
+// First use of CertificateIdentificator should initialized it.
+// We do not want to create cyclic dependencies between
+// CertificateConfigReader and CertificateIdentificator so
+// we are using factory method to create CertificateIdentificator.
+
+const CertificateIdentifier &createCertificateIdentifier();
+} // namespace ValidationCore
+
+#endif // _WRT_ENGINE_SRC_INSTALLER_CORE_VALIDATION_CORE_VALIDATORFACTORY_H_
diff --git a/src/vcore/ValidatorPluginApi.h b/src/vcore/ValidatorPluginApi.h
new file mode 100644 (file)
index 0000000..fb895b4
--- /dev/null
@@ -0,0 +1,54 @@
+/*
+ *  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        ValidatonPluginApi.h
+ * @author      Kyungwook Tak (k.tak@samsung.com)
+ * @version     1.0
+ * @brief       Validator plugin interface.
+ */
+#pragma once
+
+#include <string>
+
+#include <vcore/SignatureData.h>
+#include <vcore/SignatureValidator.h>
+#include <vcore/Error.h>
+
+namespace ValidationCore {
+
+const std::string PLUGIN_PATH = "/usr/lib/libcert-svc-validator-plugin.so";
+
+class ValidatorPlugin {
+public:
+       virtual ~ValidatorPlugin() {}
+       virtual VCerr step(VCerr result, SignatureData &data) = 0;
+       virtual std::string errorToString(VCerr)
+       {
+               return std::string("Plugin developer should implement if error code added");
+       }
+};
+
+/*
+ *  plugin developer should implement create/destroy pair functions
+ *
+ *  1. function extern C named 'create' of CreateValidatorPlugin_t
+ *  2. function extern C named 'destroy' of DestroyValidatorPlugin_t
+ */
+typedef ValidatorPlugin *(*CreateValidatorPlugin_t)(void);
+typedef void (*DestroyValidatorPlugin_t)(ValidatorPlugin *ptr);
+
+} // namespace ValidatonCore
diff --git a/src/vcore/XmlsecAdapter.cpp b/src/vcore/XmlsecAdapter.cpp
new file mode 100644 (file)
index 0000000..1694f2e
--- /dev/null
@@ -0,0 +1,443 @@
+/*
+ * 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        XmlsecAdapter.cpp
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     2.0
+ * @brief
+ */
+#include <cstdlib>
+#include <cstring>
+#include <functional>
+
+#include <libxml/tree.h>
+#include <libxml/xmlmemory.h>
+#include <libxml/parser.h>
+
+#ifndef XMLSEC_NO_XSLT
+#include <libxslt/xslt.h>
+#endif
+
+#include <xmlsec/xmlsec.h>
+#include <xmlsec/xmltree.h>
+#include <xmlsec/xmldsig.h>
+#include <xmlsec/crypto.h>
+#include <xmlsec/io.h>
+#include <xmlsec/keyinfo.h>
+#include <xmlsec/errors.h>
+
+#include <dpl/assert.h>
+#include <dpl/log/log.h>
+#include <dpl/singleton_impl.h>
+
+#include <vcore/XmlsecAdapter.h>
+
+#define VCORE_ERRORS_BUFFER_SIZE 1024
+
+IMPLEMENT_SINGLETON(ValidationCore::XmlSec)
+
+namespace {
+
+template <typename Type>
+struct CustomPtr {
+       Type ptr;
+       std::function<void(Type)> deleter;
+
+       CustomPtr() = delete;
+
+       explicit CustomPtr(Type in, std::function<void(Type)> d)
+               : ptr(in)
+               , deleter(d) {}
+
+       ~CustomPtr()
+       {
+               deleter(ptr);
+       }
+
+       inline Type get(void) const
+       {
+               return ptr;
+       }
+
+       inline Type operator->() const
+       {
+               return ptr;
+       }
+
+       inline bool operator!() const
+       {
+               return (ptr == nullptr) ? true : false;
+       }
+};
+
+struct FileWrapper {
+       FileWrapper(void *argFile, bool argReleased)
+               : file(argFile)
+               , released(argReleased)
+       {}
+       void *file;
+       bool released;
+};
+
+} // anonymous namespace
+
+namespace ValidationCore {
+
+static const std::string DIGEST_MD5 = "md5";
+
+std::string XmlSec::s_prefixPath;
+
+int XmlSec::fileMatchCallback(const char *filename)
+{
+       std::string path = s_prefixPath + filename;
+       return xmlFileMatch(path.c_str());
+}
+
+void *XmlSec::fileOpenCallback(const char *filename)
+{
+       std::string path = s_prefixPath + filename;
+       LogDebug("Xmlsec opening : " << path);
+       return new FileWrapper(xmlFileOpen(path.c_str()), false);
+}
+
+int XmlSec::fileReadCallback(void *context,
+                                                        char *buffer,
+                                                        int len)
+{
+       FileWrapper *fw = static_cast<FileWrapper *>(context);
+
+       if (fw->released)
+               return 0;
+
+       int output = xmlFileRead(fw->file, buffer, len);
+
+       if (output == 0) {
+               fw->released = true;
+               xmlFileClose(fw->file);
+       }
+
+       return output;
+}
+
+int XmlSec::fileCloseCallback(void *context)
+{
+       FileWrapper *fw = static_cast<FileWrapper *>(context);
+       int output = 0;
+
+       if (!fw->released)
+               output = xmlFileClose(fw->file);
+
+       delete fw;
+       return output;
+}
+
+void XmlSec::fileExtractPrefix(XmlSecContext &context)
+{
+       if (!context.workingDirectory.empty()) {
+               s_prefixPath = context.workingDirectory;
+               return;
+       }
+
+       s_prefixPath = context.signatureFile;
+       size_t pos = s_prefixPath.rfind('/');
+
+       if (pos == std::string::npos)
+               s_prefixPath.clear();
+       else
+               s_prefixPath.erase(pos + 1, std::string::npos);
+}
+
+void LogDebugPrint(const char *file,
+                                  int line,
+                                  const char *func,
+                                  const char *errorObject,
+                                  const char *errorSubject,
+                                  int reason,
+                                  const char *msg)
+{
+       // Get error message from xmlsec.
+       const char *errorMsg = NULL;
+       for (xmlSecSize i = 0; (i < XMLSEC_ERRORS_MAX_NUMBER) &&
+                                                       (xmlSecErrorsGetMsg(i) != NULL); ++i) {
+               if (xmlSecErrorsGetCode(i) == reason) {
+                       errorMsg = xmlSecErrorsGetMsg(i);
+                       break;
+               }
+       }
+
+       // Make full error message.
+       char buff[VCORE_ERRORS_BUFFER_SIZE];
+       snprintf(buff,
+                       sizeof(buff),
+                       "[%s:%d] %s(): obj=%s, subj=%s, error=%d:%s:%s\n",
+                       file,
+                       line,
+                       func,
+                       (errorObject != NULL) ? errorObject : "",
+                       (errorSubject != NULL) ? errorSubject : "",
+                       reason,
+                       (errorMsg != NULL) ? errorMsg : "",
+                       (msg != NULL) ? msg : "");
+
+       if (reason == XMLSEC_ERRORS_MAX_NUMBER)
+               LogError(buff);
+       else
+               LogDebug(buff);
+}
+
+XmlSec::XmlSec()
+       : m_initialized(false)
+       , m_pList(nullptr)
+{
+       LIBXML_TEST_VERSION
+       xmlLoadExtDtdDefaultValue = XML_DETECT_IDS | XML_COMPLETE_ATTRS;
+       xmlSubstituteEntitiesDefault(1);
+#ifndef XMLSEC_NO_XSLT
+       xmlIndentTreeOutput = 1;
+#endif
+
+       if (xmlSecInit() < 0)
+               ThrowMsg(Exception::InternalError, "Xmlsec initialization failed.");
+
+       if (xmlSecCheckVersion() != 1) {
+               xmlSecShutdown();
+               ThrowMsg(Exception::InternalError,
+                                "Loaded xmlsec library version is not compatible.");
+       }
+
+#ifdef XMLSEC_CRYPTO_DYNAMIC_LOADING
+
+       if (xmlSecCryptoDLLoadLibrary(BAD_CAST XMLSEC_CRYPTO) < 0) {
+               xmlSecShutdown();
+               LogError(
+                       "Error: unable to load default xmlsec-crypto library. Make sure "
+                       "that you have it installed and check shared libraries path "
+                       "(LD_LIBRARY_PATH) envornment variable.");
+               ThrowMsg(Exception::InternalError,
+                                "Unable to load default xmlsec-crypto library.");
+       }
+
+#endif
+
+       if (xmlSecCryptoAppInit(nullptr) < 0) {
+               xmlSecShutdown();
+               ThrowMsg(Exception::InternalError, "Crypto initialization failed.");
+       }
+
+       if (xmlSecCryptoInit() < 0) {
+               xmlSecCryptoAppShutdown();
+               xmlSecShutdown();
+               ThrowMsg(Exception::InternalError,
+                                "Xmlsec-crypto initialization failed.");
+       }
+
+       m_initialized = true;
+}
+
+XmlSec::~XmlSec()
+{
+       if (m_initialized)
+               return;
+
+       xmlSecCryptoShutdown();
+       xmlSecCryptoAppShutdown();
+       xmlSecShutdown();
+#ifndef XMLSEC_NO_XSLT
+       xsltCleanupGlobals();
+#endif
+       s_prefixPath.clear();
+       m_initialized = false;
+}
+
+void XmlSec::validateFile(XmlSecContext &context, xmlSecKeysMngrPtr mngrPtr)
+{
+       fileExtractPrefix(context);
+       LogDebug("Prefix path : " << s_prefixPath);
+       xmlSecIOCleanupCallbacks();
+       xmlSecIORegisterCallbacks(
+               fileMatchCallback,
+               fileOpenCallback,
+               fileReadCallback,
+               fileCloseCallback);
+       CustomPtr<xmlDocPtr> docPtr(xmlParseFile(context.signatureFile.c_str()), xmlFreeDoc);
+
+       if (!docPtr || xmlDocGetRootElement(docPtr.get()) == nullptr)
+               ThrowMsg(Exception::InvalidFormat,
+                                "Unable to parse sig xml file: " << context.signatureFile);
+
+       xmlNodePtr node = xmlSecFindNode(
+                                                 xmlDocGetRootElement(docPtr.get()),
+                                                 xmlSecNodeSignature,
+                                                 xmlSecDSigNs);
+
+       if (node == nullptr)
+               ThrowMsg(Exception::InvalidFormat,
+                                "Start node not found in " << context.signatureFile);
+
+       CustomPtr<xmlSecDSigCtxPtr> dsigCtx(xmlSecDSigCtxCreate(mngrPtr), xmlSecDSigCtxDestroy);
+
+       if (!dsigCtx)
+               ThrowMsg(Exception::OutOfMemory, "Failed to create signature context.");
+
+       if (context.allowBrokenChain)
+               dsigCtx->keyInfoReadCtx.flags |= XMLSEC_KEYINFO_FLAGS_ALLOW_BROKEN_CHAIN;
+
+       if (context.validationTime) {
+               LogDebug("Setting validation time.");
+               dsigCtx->keyInfoReadCtx.certsVerificationTime = context.validationTime;
+       }
+
+       int res;
+
+       switch (m_mode) {
+       case ValidateMode::NORMAL:
+               res = xmlSecDSigCtxVerify(dsigCtx.get(), node);
+               break;
+
+       case ValidateMode::NO_HASH:
+               res = xmlSecDSigCtxVerifyEx(dsigCtx.get(), node, 1, nullptr);
+               break;
+
+       case ValidateMode::PARTIAL_HASH: {
+               size_t n = m_pList->size();
+               const char *pList[n + 1] = {0};
+               size_t i = 0;
+
+               for (auto uri : *m_pList)
+                       pList[i++] = uri.c_str();
+
+               res = xmlSecDSigCtxVerifyEx(dsigCtx.get(), node, 0, pList);
+               break;
+       }
+
+       default:
+               ThrowMsg(Exception::InternalError, "ValidateMode is invalid");
+       }
+
+       if (res != 0)
+               ThrowMsg(Exception::InvalidSig, "Signature verify error.");
+
+       if (dsigCtx->keyInfoReadCtx.flags2 & XMLSEC_KEYINFO_ERROR_FLAGS_BROKEN_CHAIN) {
+               LogWarning("Signature contains broken chain!");
+               context.errorBrokenChain = true;
+       }
+
+       if (dsigCtx->status != xmlSecDSigStatusSucceeded)
+               ThrowMsg(Exception::InvalidSig, "Signature status is not succedded.");
+
+       xmlSecSize refSize = xmlSecPtrListGetSize(&(dsigCtx->signedInfoReferences));
+
+       for (xmlSecSize i = 0; i < refSize; ++i) {
+               xmlSecDSigReferenceCtxPtr dsigRefCtx = static_cast<xmlSecDSigReferenceCtxPtr>(
+                               xmlSecPtrListGetItem(&(dsigCtx->signedInfoReferences), i));
+
+               if (!dsigRefCtx || !dsigRefCtx->uri)
+                       continue;
+
+               if (dsigRefCtx->digestMethod
+                               && dsigRefCtx->digestMethod->id
+                               && dsigRefCtx->digestMethod->id->name) {
+                       auto digest = reinterpret_cast<const char *const>(
+                                                         dsigRefCtx->digestMethod->id->name);
+
+                       if (DIGEST_MD5.compare(digest) == 0)
+                               ThrowMsg(Exception::InvalidFormat,
+                                                "MD5 digest method used! Please use sha");
+               }
+
+               context.referenceSet.emplace(reinterpret_cast<char *>(dsigRefCtx->uri));
+       }
+}
+
+void XmlSec::loadDERCertificateMemory(XmlSecContext &context, xmlSecKeysMngrPtr mngrPtr)
+{
+       std::string derCert;
+
+       try {
+               derCert = context.certificatePtr->getDER();
+       } catch (Certificate::Exception::Base &e) {
+               ThrowMsg(Exception::InternalError,
+                                "Failed during x509 conversion to der format: " << e.DumpToString());
+       }
+
+       if (xmlSecCryptoAppKeysMngrCertLoadMemory(
+                               mngrPtr,
+                               reinterpret_cast<const xmlSecByte *>(derCert.data()),
+                               static_cast<xmlSecSize>(derCert.length()),
+                               xmlSecKeyDataFormatDer,
+                               xmlSecKeyDataTypeTrusted) < 0)
+               ThrowMsg(Exception::InternalError, "Failed to load der cert from memory.");
+}
+
+void XmlSec::loadPEMCertificateFile(XmlSecContext &context, xmlSecKeysMngrPtr mngrPtr)
+{
+       if (xmlSecCryptoAppKeysMngrCertLoad(
+                               mngrPtr,
+                               context.certificatePath.c_str(),
+                               xmlSecKeyDataFormatPem,
+                               xmlSecKeyDataTypeTrusted) < 0)
+               ThrowMsg(Exception::InternalError, "Failed to load PEM cert from file.");
+}
+
+void XmlSec::validateInternal(XmlSecContext &context)
+{
+       LogDebug("Start to validate.");
+       Assert(!context.signatureFile.empty());
+       Assert(!!context.certificatePtr || !context.certificatePath.empty());
+       xmlSecErrorsSetCallback(LogDebugPrint);
+
+       if (!m_initialized)
+               ThrowMsg(Exception::InternalError, "XmlSec is not initialized");
+
+       CustomPtr<xmlSecKeysMngrPtr> mngrPtr(xmlSecKeysMngrCreate(), xmlSecKeysMngrDestroy);
+
+       if (!mngrPtr)
+               ThrowMsg(Exception::InternalError, "Failed to create keys manager.");
+
+       if (xmlSecCryptoAppDefaultKeysMngrInit(mngrPtr.get()) < 0)
+               ThrowMsg(Exception::InternalError, "Failed to initialize keys manager.");
+
+       context.referenceSet.clear();
+
+       if (!!context.certificatePtr)
+               loadDERCertificateMemory(context, mngrPtr.get());
+
+       if (!context.certificatePath.empty())
+               loadPEMCertificateFile(context, mngrPtr.get());
+
+       validateFile(context, mngrPtr.get());
+}
+
+void XmlSec::validate(XmlSecContext &context)
+{
+       m_mode = ValidateMode::NORMAL;
+       validateInternal(context);
+}
+
+void XmlSec::validateNoHash(XmlSecContext &context)
+{
+       m_mode = ValidateMode::NO_HASH;
+       validateInternal(context);
+}
+
+void XmlSec::validatePartialHash(XmlSecContext &context, const std::list<std::string> &targetUri)
+{
+       m_mode = ValidateMode::PARTIAL_HASH;
+       m_pList = &targetUri;
+       validateInternal(context);
+}
+
+} // namespace ValidationCore
diff --git a/src/vcore/XmlsecAdapter.h b/src/vcore/XmlsecAdapter.h
new file mode 100644 (file)
index 0000000..0a0a522
--- /dev/null
@@ -0,0 +1,135 @@
+/*
+ * 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        XmlSecAdapter.h
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version     2.0
+ * @brief
+ */
+#pragma once
+
+#include <string>
+#include <list>
+
+#include <xmlsec/keysmngr.h>
+
+#include <dpl/exception.h>
+#include <dpl/singleton.h>
+
+#include <vcore/Certificate.h>
+#include <vcore/SignatureData.h>
+
+namespace ValidationCore {
+class XmlSec {
+
+public:
+       XmlSec();
+       virtual ~XmlSec();
+
+       XmlSec(const XmlSec &) = delete;
+       XmlSec &operator=(const XmlSec &) = delete;
+       XmlSec(XmlSec &&) = delete;
+       XmlSec &operator=(XmlSec &&) = delete;
+
+       struct XmlSecContext {
+               /* You _must_ set one of the value: certificatePath or certificate. */
+               XmlSecContext()
+                       : validationTime(0)
+                       , allowBrokenChain(false)
+                       , errorBrokenChain(false) {}
+
+               /*
+                * Absolute path to signature file.
+                */
+               std::string signatureFile;
+               /*
+                * Direcotory with signed data.
+                * If you leave it empty xmlsec will use directory extracted
+                * from signatureFile.
+                */
+               std::string workingDirectory;
+               /*
+                * Path to trusted certificate.
+                */
+               std::string certificatePath;
+               /*
+                * Trusted certificate. In most cases it should be Root CA certificate.
+                */
+               CertificatePtr certificatePtr;
+               /*
+                * Validation date.
+                * 0 - uses current time.
+                */
+               time_t validationTime;
+               /*
+                * Input parameter.
+                * If true, signature validation will not be interrupted by chain error.
+                * If true and chain is broken then the value errorBrokenChain will be
+                * set to true.
+                */
+               bool allowBrokenChain;
+               /*
+                * Output parameter.
+                * This will be set if chain is incomplete or broken.
+                */
+               bool errorBrokenChain;
+               /*
+                * Output parameter.
+                * Reference checked by xmlsec
+                */
+               ReferenceSet referenceSet;
+       };
+
+       struct Exception {
+               DECLARE_EXCEPTION_TYPE(VcoreDPL::Exception, Base)
+               DECLARE_EXCEPTION_TYPE(Base, InternalError)
+               DECLARE_EXCEPTION_TYPE(Base, InvalidFormat)
+               DECLARE_EXCEPTION_TYPE(Base, InvalidSig)
+               DECLARE_EXCEPTION_TYPE(Base, OutOfMemory)
+       };
+
+       /* context - input/output param. */
+       void validate(XmlSecContext &context);
+       void validateNoHash(XmlSecContext &context);
+       void validatePartialHash(XmlSecContext &context, const std::list<std::string> &targetUri);
+
+private:
+       enum class ValidateMode : int {
+               NORMAL,
+               NO_HASH,
+               PARTIAL_HASH
+       };
+
+       ValidateMode m_mode;
+       bool m_initialized;
+       const std::list<std::string> *m_pList;
+
+       void loadDERCertificateMemory(XmlSecContext &context, xmlSecKeysMngrPtr mngr);
+       void loadPEMCertificateFile(XmlSecContext &context, xmlSecKeysMngrPtr mngr);
+       void validateInternal(XmlSecContext &context);
+       void validateFile(XmlSecContext &context, xmlSecKeysMngrPtr mngr);
+
+       static std::string s_prefixPath;
+       static int fileMatchCallback(const char *filename);
+       static void *fileOpenCallback(const char *filename);
+       static int fileReadCallback(void *context, char *buffer, int len);
+       static int fileCloseCallback(void *context);
+       static void fileExtractPrefix(XmlSecContext &context);
+};
+
+typedef VcoreDPL::Singleton<XmlSec> XmlSecSingleton;
+
+} // namespace ValidationCore
diff --git a/src/vcore/api.cpp b/src/vcore/api.cpp
new file mode 100644 (file)
index 0000000..4554e77
--- /dev/null
@@ -0,0 +1,1969 @@
+/**
+ * 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        api.cpp
+ * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @author      Jacek Migacz (j.migacz@samsung.com)
+ * @author      Sangwan Kwon (sangwan.kwon@samsung.com)
+ * @version     1.0
+ * @brief       This is part of C-api proposition for cert-svc.
+ */
+#include <unistd.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <errno.h>
+
+#include <algorithm>
+#include <fstream>
+#include <map>
+#include <memory>
+#include <set>
+#include <string>
+#include <vector>
+
+#include <openssl/pem.h>
+#include <openssl/ssl.h>
+#include <openssl/x509v3.h>
+#include <openssl/pkcs12.h>
+#include <openssl/err.h>
+#include <openssl/sha.h>
+#include <openssl/evp.h>
+#include <openssl/bio.h>
+#include <libxml/parser.h>
+#include <libxml/tree.h>
+
+#include "dpl/log/log.h"
+
+#include "vcore/Base64.h"
+#include "vcore/Certificate.h"
+#include "vcore/CertificateCollection.h"
+#include "vcore/pkcs12.h"
+#include "vcore/Client.h"
+
+#include "cert-svc/cinstance.h"
+#include "cert-svc/ccert.h"
+#include "cert-svc/cpkcs12.h"
+#include "cert-svc/cprimitives.h"
+
+#define START_CERT      "-----BEGIN CERTIFICATE-----"
+#define END_CERT        "-----END CERTIFICATE-----"
+#define START_TRUSTED   "-----BEGIN TRUSTED CERTIFICATE-----"
+#define END_TRUSTED     "-----END TRUSTED CERTIFICATE-----"
+
+using namespace ValidationCore;
+
+namespace {
+
+struct CharDeleter {
+       void operator()(char *str) const
+       {
+               free(str);
+       }
+};
+
+struct CharArrDeleter {
+       void operator()(char **arr) const
+       {
+               size_t i = 0;
+
+               if (arr == NULL)
+                       return;
+
+               while (arr[i])
+                       free(arr[i++]);
+
+               free(arr);
+       }
+};
+
+class CertSvcInstanceImpl {
+public:
+       CertSvcInstanceImpl()
+               : m_certificateCounter(0)
+               , m_idListCounter(0)
+               , m_stringListCounter(0)
+       {}
+
+       ~CertSvcInstanceImpl()
+       {
+               auto it = m_allocatedStringSet.begin();
+
+               for (; it != m_allocatedStringSet.end(); ++it)
+                       delete[] *it;
+       }
+
+       inline void reset()
+       {
+               m_certificateCounter = 0;
+               m_certificateMap.clear();
+               m_idListCounter = 0;
+               m_idListMap.clear();
+               m_stringListCounter = 0;
+               m_stringListMap.clear();
+               auto it = m_allocatedStringSet.begin();
+
+               for (; it != m_allocatedStringSet.end(); ++it)
+                       delete[] *it;
+
+               m_allocatedStringSet.clear();
+       }
+
+       inline size_t addCert(const CertificatePtr &cert)
+       {
+               m_certificateMap[m_certificateCounter] = cert;
+               return m_certificateCounter++;
+       }
+
+       inline void removeCert(const CertSvcCertificate &cert)
+       {
+               auto iter = m_certificateMap.find(cert.privateHandler);
+
+               if (iter != m_certificateMap.end()) {
+                       m_certificateMap.erase(iter);
+               }
+       }
+
+       inline int getCertFromList(
+               const CertSvcCertificateList &handler,
+               size_t position,
+               CertSvcCertificate *certificate)
+       {
+               auto iter = m_idListMap.find(handler.privateHandler);
+
+               if (iter == m_idListMap.end()) {
+                       return CERTSVC_WRONG_ARGUMENT;
+               }
+
+               if (position >= iter->second.size()) {
+                       return CERTSVC_WRONG_ARGUMENT;
+               }
+
+               certificate->privateInstance = handler.privateInstance;
+               certificate->privateHandler = (iter->second)[position];
+               return CERTSVC_SUCCESS;
+       }
+
+       inline int getCertListLen(const CertSvcCertificateList &handler, size_t *len)
+       {
+               auto iter = m_idListMap.find(handler.privateHandler);
+
+               if (iter == m_idListMap.end() || !len) {
+                       return CERTSVC_WRONG_ARGUMENT;
+               }
+
+               *len = (iter->second).size();
+               return CERTSVC_SUCCESS;
+       }
+
+       inline void removeCertList(const CertSvcCertificateList &handler)
+       {
+               auto iter = m_idListMap.find(handler.privateHandler);
+
+               if (iter != m_idListMap.end())
+                       m_idListMap.erase(iter);
+       }
+
+       inline void removeCertListAll(const CertSvcCertificateList &handler)
+       {
+               auto iter = m_idListMap.find(handler.privateHandler);
+
+               if (iter == m_idListMap.end())
+                       return;
+
+               for (size_t pos = 0; pos < iter->second.size(); ++pos) {
+                       auto iterCert = m_certificateMap.find((iter->second)[pos]);
+
+                       if (iterCert == m_certificateMap.end())
+                               return;
+
+                       m_certificateMap.erase(iterCert);
+               }
+
+               m_idListMap.erase(iter);
+       }
+
+       inline int isSignedBy(const CertSvcCertificate &child,
+                                                 const CertSvcCertificate &parent,
+                                                 int *status)
+       {
+               auto citer = m_certificateMap.find(child.privateHandler);
+
+               if (citer == m_certificateMap.end()) {
+                       return CERTSVC_WRONG_ARGUMENT;
+               }
+
+               auto piter = m_certificateMap.find(parent.privateHandler);
+
+               if (piter == m_certificateMap.end()) {
+                       return CERTSVC_WRONG_ARGUMENT;
+               }
+
+               if (citer->second->isSignedBy(piter->second)) {
+                       *status = CERTSVC_TRUE;
+               } else {
+                       *status = CERTSVC_FALSE;
+               }
+
+               return CERTSVC_SUCCESS;
+       }
+
+       inline int getField(const CertSvcCertificate &cert,
+                                               CertSvcCertificateField field,
+                                               CertSvcString *buffer)
+       {
+               auto iter = m_certificateMap.find(cert.privateHandler);
+
+               if (iter == m_certificateMap.end()) {
+                       return CERTSVC_WRONG_ARGUMENT;
+               }
+
+               auto certPtr = iter->second;
+               std::string result;
+
+               switch (field) {
+               case CERTSVC_SUBJECT:
+                       result = certPtr->getOneLine();
+                       break;
+
+               case CERTSVC_ISSUER:
+                       result = certPtr->getOneLine(Certificate::FIELD_ISSUER);
+                       break;
+
+               case CERTSVC_SUBJECT_COMMON_NAME:
+                       result = certPtr->getCommonName();
+                       break;
+
+               case CERTSVC_SUBJECT_COUNTRY_NAME:
+                       result = certPtr->getCountryName();
+                       break;
+
+               case CERTSVC_SUBJECT_STATE_NAME:
+                       result = certPtr->getStateOrProvinceName();
+                       break;
+
+               case CERTSVC_SUBJECT_LOCALITY_NAME:
+                       result = certPtr->getLocalityName();
+                       break;
+
+               case CERTSVC_SUBJECT_ORGANIZATION_NAME:
+                       result = certPtr->getOrganizationName();
+                       break;
+
+               case CERTSVC_SUBJECT_ORGANIZATION_UNIT_NAME:
+                       result = certPtr->getOrganizationalUnitName();
+                       break;
+
+               case CERTSVC_SUBJECT_EMAIL_ADDRESS:
+                       result = certPtr->getEmailAddres();
+                       break;
+
+               /*
+                           case CERTSVC_SUBJECT_UID:
+                               result = certPtr->getUID();
+                               break;
+               */
+               case CERTSVC_ISSUER_COMMON_NAME:
+                       result = certPtr->getCommonName(Certificate::FIELD_ISSUER);
+                       break;
+
+               case CERTSVC_ISSUER_COUNTRY_NAME:
+                       result = certPtr->getCountryName(Certificate::FIELD_ISSUER);
+                       break;
+
+               case CERTSVC_ISSUER_STATE_NAME:
+                       result = certPtr->getStateOrProvinceName(Certificate::FIELD_ISSUER);
+                       break;
+
+               case CERTSVC_ISSUER_LOCALITY_NAME:
+                       result = certPtr->getLocalityName(Certificate::FIELD_ISSUER);
+                       break;
+
+               case CERTSVC_ISSUER_ORGANIZATION_NAME:
+                       result = certPtr->getOrganizationName(Certificate::FIELD_ISSUER);
+                       break;
+
+               case CERTSVC_ISSUER_ORGANIZATION_UNIT_NAME:
+                       result = certPtr->getOrganizationalUnitName(Certificate::FIELD_ISSUER);
+                       break;
+
+               case CERTSVC_ISSUER_EMAIL_ADDRESS:
+                       result = certPtr->getEmailAddres(Certificate::FIELD_ISSUER);
+                       break;
+
+               /*
+                           case CERTSVC_ISSUER_UID:
+                               result = certPtr->getUID(Certificate::FIELD_ISSUER);
+                               break;
+               */
+               case CERTSVC_VERSION: {
+                       std::stringstream stream;
+                       stream << (certPtr->getVersion() + 1);
+                       result = stream.str();
+                       break;
+               }
+
+               case CERTSVC_SERIAL_NUMBER:
+                       result = certPtr->getSerialNumberString();
+                       break;
+
+               case CERTSVC_KEY_USAGE:
+                       result = certPtr->getKeyUsageString();
+                       break;
+
+               case CERTSVC_KEY:
+                       result = certPtr->getPublicKeyString();
+                       break;
+
+               case CERTSVC_KEY_ALGO:
+                       result = certPtr->getPublicKeyAlgoString();
+                       break;
+
+               case CERTSVC_SIGNATURE_ALGORITHM:
+                       result = certPtr->getSignatureAlgorithmString();
+                       break;
+
+               default:
+                       break;
+               }
+
+               if (result.empty()) {
+                       buffer->privateHandler = NULL;
+                       buffer->privateLength = 0;
+                       buffer->privateInstance = cert.privateInstance;
+                       return CERTSVC_SUCCESS;
+               }
+
+               char *cstring = new char[result.size() + 1];
+
+               if (cstring == NULL) {
+                       buffer->privateHandler = NULL;
+                       buffer->privateLength = 0;
+                       buffer->privateInstance = cert.privateInstance;
+                       return CERTSVC_BAD_ALLOC;
+               }
+
+               strncpy(cstring, result.c_str(), result.size() + 1);
+               buffer->privateHandler = cstring;
+               buffer->privateLength = result.size();
+               buffer->privateInstance = cert.privateInstance;
+               m_allocatedStringSet.insert(cstring);
+               return CERTSVC_SUCCESS;
+       }
+
+       inline int getNotAfter(const CertSvcCertificate &cert,
+                                                  time_t *time)
+       {
+               auto iter = m_certificateMap.find(cert.privateHandler);
+
+               if (iter == m_certificateMap.end()) {
+                       return CERTSVC_WRONG_ARGUMENT;
+               }
+
+               *time = iter->second->getNotAfter();
+               return CERTSVC_SUCCESS;
+       }
+
+       inline int getNotBefore(const CertSvcCertificate &cert,
+                                                       time_t *time)
+       {
+               auto iter = m_certificateMap.find(cert.privateHandler);
+
+               if (iter == m_certificateMap.end()) {
+                       return CERTSVC_WRONG_ARGUMENT;
+               }
+
+               *time = iter->second->getNotBefore();
+               return CERTSVC_SUCCESS;
+       }
+
+       inline int isRootCA(const CertSvcCertificate &cert, int *status)
+       {
+               auto iter = m_certificateMap.find(cert.privateHandler);
+
+               if (iter == m_certificateMap.end()) {
+                       return CERTSVC_WRONG_ARGUMENT;
+               }
+
+               if (iter->second->isRootCert()) {
+                       *status = CERTSVC_TRUE;
+               } else {
+                       *status = CERTSVC_FALSE;
+               }
+
+               return CERTSVC_SUCCESS;
+       }
+
+       inline int getStringFromList(
+               const CertSvcStringList &handler,
+               size_t position,
+               CertSvcString *buffer)
+       {
+               buffer->privateHandler = NULL;
+               buffer->privateLength = 0;
+               auto iter = m_stringListMap.find(handler.privateHandler);
+
+               if (iter == m_stringListMap.end()) {
+                       return CERTSVC_WRONG_ARGUMENT;
+               }
+
+               if (position >= iter->second.size()) {
+                       return CERTSVC_WRONG_ARGUMENT;
+               }
+
+               const std::string &data = iter->second.at(position);
+               size_t size = data.size();
+               char *cstring = new char[size + 1];
+
+               if (!cstring) {
+                       return CERTSVC_FAIL;
+               }
+
+               strncpy(cstring, data.c_str(), size + 1);
+               buffer->privateHandler = cstring;
+               buffer->privateLength = size;
+               buffer->privateInstance = handler.privateInstance;
+               m_allocatedStringSet.insert(cstring);
+               return CERTSVC_SUCCESS;
+       }
+
+       inline int getStringListLen(
+               const CertSvcStringList &handler,
+               size_t *size)
+       {
+               auto iter = m_stringListMap.find(handler.privateHandler);
+
+               if (iter == m_stringListMap.end()) {
+                       return CERTSVC_WRONG_ARGUMENT;
+               }
+
+               *size = iter->second.size();
+               return CERTSVC_SUCCESS;
+       }
+
+       inline void removeStringList(const CertSvcStringList &handler)
+       {
+               m_stringListMap.erase(m_stringListMap.find(handler.privateHandler));
+       }
+
+       inline void removeString(const CertSvcString &handler)
+       {
+               auto iter = m_allocatedStringSet.find(handler.privateHandler);
+
+               if (iter != m_allocatedStringSet.end()) {
+                       delete[] *iter;
+                       m_allocatedStringSet.erase(iter);
+               }
+       }
+
+       inline int sortCollection(CertSvcCertificate *certificate_array, size_t size)
+       {
+               if (size < 2) {
+                       return CERTSVC_WRONG_ARGUMENT;
+               }
+
+               for (size_t i = 1; i < size; ++i) {
+                       if (certificate_array[i - 1].privateInstance.privatePtr
+                                       != certificate_array[i].privateInstance.privatePtr) {
+                               return CERTSVC_WRONG_ARGUMENT;
+                       }
+               }
+
+               CertificateList certList;
+               std::map<Certificate *, size_t> translator;
+
+               for (size_t i = 0; i < size; ++i) {
+                       size_t pos = certificate_array[i].privateHandler;
+                       auto cert = m_certificateMap.find(pos);
+
+                       if (cert == m_certificateMap.end()) {
+                               return CERTSVC_WRONG_ARGUMENT;
+                       }
+
+                       translator[cert->second.get()] = pos;
+                       certList.push_back(cert->second);
+               }
+
+               CertificateCollection collection;
+               collection.load(certList);
+
+               if (!collection.sort()) {
+                       return CERTSVC_FAIL;
+               }
+
+               auto chain = collection.getChain();
+               size_t i = 0;
+
+               for (const auto &cert : collection.getChain())
+                       certificate_array[i++].privateHandler = translator[cert.get()];
+
+               return CERTSVC_SUCCESS;
+       }
+
+       inline int getX509Copy(const CertSvcCertificate &certificate, X509 **cert)
+       {
+               auto it = m_certificateMap.find(certificate.privateHandler);
+
+               if (it == m_certificateMap.end()) {
+                       return CERTSVC_WRONG_ARGUMENT;
+               }
+
+               *cert = X509_dup(it->second->getX509());
+               return CERTSVC_SUCCESS;
+       }
+
+       inline int getPubkeyDER(const CertSvcCertificate &certificate,
+                                                       unsigned char **pubkey,
+                                                       size_t *len)
+       {
+               auto it = m_certificateMap.find(certificate.privateHandler);
+
+               if (it == m_certificateMap.end() || pubkey == NULL || len == NULL)
+                       return CERTSVC_WRONG_ARGUMENT;
+
+               it->second->getPublicKeyDER(pubkey, len);
+               return CERTSVC_SUCCESS;
+       }
+
+       inline int saveToFile(const CertSvcCertificate &certificate,
+                                                 const char *location)
+       {
+               auto it = m_certificateMap.find(certificate.privateHandler);
+
+               if (it == m_certificateMap.end()) {
+                       return CERTSVC_WRONG_ARGUMENT;
+               }
+
+               FILE *out = fopen(location, "w");
+
+               if (out == NULL) {
+                       return CERTSVC_FAIL;
+               }
+
+               if (0 == i2d_X509_fp(out, it->second->getX509())) {
+                       fclose(out);
+                       return CERTSVC_FAIL;
+               }
+
+               fclose(out);
+               return CERTSVC_SUCCESS;
+       }
+
+       inline int verify(
+               CertSvcCertificate certificate,
+               CertSvcString &message,
+               CertSvcString &signature,
+               const char *algorithm,
+               int *status)
+       {
+               int result = CERTSVC_FAIL;
+
+               if (!status) {
+                       return CERTSVC_WRONG_ARGUMENT;
+               }
+
+               auto it = m_certificateMap.find(certificate.privateHandler);
+
+               if (it == m_certificateMap.end()) {
+                       return CERTSVC_WRONG_ARGUMENT;
+               }
+
+               OpenSSL_add_all_digests();
+               int temp;
+               EVP_MD_CTX *mdctx = NULL;
+               const EVP_MD *md = NULL;
+               X509 *cert = it->second->getX509();
+               EVP_PKEY *pkey = NULL;
+
+               if (cert == NULL) {
+                       goto err;
+               }
+
+               pkey = X509_get_pubkey(cert);
+
+               if (pkey == NULL) {
+                       goto err;
+               }
+
+               if (algorithm == NULL) {
+                       md = EVP_get_digestbyobj(cert->cert_info->signature->algorithm);
+               } else {
+                       md = EVP_get_digestbyname(algorithm);
+               }
+
+               if (md == NULL) {
+                       result = CERTSVC_INVALID_ALGORITHM;
+                       goto err;
+               }
+
+               mdctx = EVP_MD_CTX_create();
+
+               if (mdctx == NULL) {
+                       goto err;
+               }
+
+               if (EVP_VerifyInit_ex(mdctx, md, NULL) != 1) {
+                       goto err;
+               }
+
+               if (EVP_VerifyUpdate(mdctx, message.privateHandler, message.privateLength) != 1) {
+                       goto err;
+               }
+
+               temp = EVP_VerifyFinal(mdctx,
+                                                          reinterpret_cast<unsigned char *>(signature.privateHandler),
+                                                          signature.privateLength,
+                                                          pkey);
+
+               if (temp == 0) {
+                       *status = CERTSVC_INVALID_SIGNATURE;
+                       result = CERTSVC_SUCCESS;
+               } else if (temp == 1) {
+                       *status = CERTSVC_SUCCESS;
+                       result = CERTSVC_SUCCESS;
+               }
+
+err:
+
+               if (mdctx != NULL)
+                       EVP_MD_CTX_destroy(mdctx);
+
+               if (pkey != NULL)
+                       EVP_PKEY_free(pkey);
+
+               return result;
+       }
+
+       inline int base64Encode(
+               const CertSvcString &message,
+               CertSvcString *base64)
+       {
+               if (!base64) {
+                       return CERTSVC_WRONG_ARGUMENT;
+               }
+
+               std::string info(message.privateHandler, message.privateLength);
+               Base64Encoder base;
+               base.reset();
+               base.append(info);
+               base.finalize();
+               info = base.get();
+               char *ptr = new char[info.size() + 1];
+
+               if (ptr == NULL) {
+                       return CERTSVC_BAD_ALLOC;
+               }
+
+               memcpy(ptr, info.c_str(), info.size() + 1);
+               m_allocatedStringSet.insert(ptr);
+               base64->privateHandler = ptr;
+               base64->privateLength = info.size();
+               base64->privateInstance = message.privateInstance;
+               return CERTSVC_SUCCESS;
+       }
+
+       int base64Decode(
+               const CertSvcString &base64,
+               CertSvcString *message)
+       {
+               if (!message) {
+                       return CERTSVC_WRONG_ARGUMENT;
+               }
+
+               std::string info(base64.privateHandler, base64.privateLength);
+               Base64Decoder base;
+               base.reset();
+               base.append(info);
+
+               if (!base.finalize()) {
+                       return CERTSVC_FAIL;
+               }
+
+               info = base.get();
+               char *ptr = new char[info.size() + 1];
+
+               if (ptr == NULL) {
+                       return CERTSVC_BAD_ALLOC;
+               }
+
+               memcpy(ptr, info.c_str(), info.size() + 1);
+               m_allocatedStringSet.insert(ptr);
+               message->privateHandler = ptr;
+               message->privateLength = info.size();
+               message->privateInstance = base64.privateInstance;
+               return CERTSVC_SUCCESS;
+       }
+
+       inline int stringNew(
+               CertSvcInstance &instance,
+               const char *str,
+               size_t size,
+               CertSvcString *output)
+       {
+               if (!output)
+                       return CERTSVC_WRONG_ARGUMENT;
+
+               /* return struct for empty string */
+               if (size == 0 || str == NULL) {
+                       output->privateHandler = NULL;
+                       output->privateLength = 0;
+                       output->privateInstance = instance;
+                       return CERTSVC_SUCCESS;
+               }
+
+               if (strlen(str) < size)
+                       return CERTSVC_WRONG_ARGUMENT;
+
+               char *ptr = new(std::nothrow) char[size + 1];
+
+               if (ptr == NULL)
+                       return CERTSVC_BAD_ALLOC;
+
+               memcpy(ptr, str, size);
+               ptr[size] = '\0';
+               output->privateHandler = ptr;
+               output->privateLength = size;
+               output->privateInstance = instance;
+               m_allocatedStringSet.insert(ptr);
+               return CERTSVC_SUCCESS;
+       }
+
+       inline int certificateVerify(
+               CertSvcCertificate certificate,
+               const CertSvcCertificate *trusted,
+               size_t trustedSize,
+               const CertSvcCertificate *untrusted,
+               size_t untrustedSize,
+               int checkCaFlag,
+               int *status)
+       {
+               if (!trusted || !status) {
+                       return CERTSVC_WRONG_ARGUMENT;
+               }
+
+               auto iter = m_certificateMap.find(certificate.privateHandler);
+
+               if (iter == m_certificateMap.end()) {
+                       return CERTSVC_WRONG_ARGUMENT;
+               }
+
+               X509 *cert = iter->second->getX509();
+               X509_STORE *store = X509_STORE_new();
+               STACK_OF(X509) *ustore = sk_X509_new_null();
+
+               for (size_t i = 0; i < trustedSize; ++i) {
+                       auto iter = m_certificateMap.find(trusted[i].privateHandler);
+
+                       if (iter == m_certificateMap.end()) {
+                               X509_STORE_free(store);
+                               sk_X509_free(ustore);
+                               return CERTSVC_WRONG_ARGUMENT;
+                       }
+
+                       X509_STORE_add_cert(store, iter->second->getX509());
+               }
+
+               for (size_t i = 0; i < untrustedSize; ++i) {
+                       auto iter = m_certificateMap.find(untrusted[i].privateHandler);
+
+                       if (iter == m_certificateMap.end()) {
+                               X509_STORE_free(store);
+                               sk_X509_free(ustore);
+                               return CERTSVC_WRONG_ARGUMENT;
+                       }
+
+                       if (sk_X509_push(ustore, iter->second->getX509()) == 0)
+                               break;
+               }
+
+               X509_STORE_CTX context;
+               X509_STORE_CTX_init(&context, store, cert, ustore);
+               int result = X509_verify_cert(&context);
+
+               if (result == 1 && checkCaFlag) { // check strictly
+                       STACK_OF(X509) *resultChain = X509_STORE_CTX_get1_chain(&context);
+                       X509 *tmpCert = NULL;
+                       int caFlagValidity;
+
+                       while ((tmpCert = sk_X509_pop(resultChain))) {
+                               caFlagValidity = X509_check_ca(tmpCert);
+
+                               if (caFlagValidity != 1 && (tmpCert = sk_X509_pop(resultChain)) != NULL) {
+                                       // the last one is not a CA.
+                                       result = 0;
+                                       break;
+                               }
+                       }
+               }
+
+               X509_STORE_CTX_cleanup(&context);
+               X509_STORE_free(store);
+               sk_X509_free(ustore);
+
+               if (result == 1) {
+                       *status = CERTSVC_SUCCESS;
+               } else {
+                       *status = CERTSVC_FAIL;
+               }
+
+               return CERTSVC_SUCCESS;
+       }
+
+       // TODO : sangan.kwon, modify method by using CertificateIdentifier
+       int getVisibility(CertSvcCertificate certificate, CertSvcVisibility *visibility,
+                                         const char *fingerprintListPath)
+       {
+               int ret = CERTSVC_FAIL;
+               //xmlChar *xmlPathCertificateSet  = (xmlChar*) "CertificateSet"; /*unused variable*/
+               //xmlChar *xmlPathCertificateDomain = (xmlChar*) "CertificateDomain";// name=\"tizen-platform\""; /*unused variable*/
+               xmlChar *xmlPathDomainPlatform = (xmlChar *) "tizen-platform";
+               xmlChar *xmlPathDomainPublic = (xmlChar *) "tizen-public";
+               xmlChar *xmlPathDomainPartner = (xmlChar *) "tizen-partner";
+               xmlChar *xmlPathDomainDeveloper = (xmlChar *) "tizen-developer";
+               //xmlChar *xmlPathFingerPrintSHA1 = (xmlChar*) "FingerprintSHA1"; /*unused variable*/
+               auto iter = m_certificateMap.find(certificate.privateHandler);
+
+               if (iter == m_certificateMap.end()) {
+                       return CERTSVC_FAIL;
+               }
+
+               CertificatePtr certPtr = iter->second;
+               std::string fingerprint = Certificate::FingerprintToColonHex(certPtr->getFingerprint(
+                                                                         Certificate::FINGERPRINT_SHA1));
+               /*   load file */
+               xmlDocPtr doc = xmlParseFile(fingerprintListPath);
+
+               if ((doc == NULL) || (xmlDocGetRootElement(doc) == NULL)) {
+                       LogError("Failed to prase fingerprint_list.xml");
+                       return CERTSVC_IO_ERROR;
+               }
+
+               xmlNodePtr curPtr = xmlFirstElementChild(xmlDocGetRootElement(doc));
+
+               if (curPtr == NULL) {
+                       LogError("Can not find root");
+                       ret = CERTSVC_IO_ERROR;
+                       goto out;
+               }
+
+               while (curPtr != NULL) {
+                       xmlAttr *attr = curPtr->properties;
+
+                       if (!attr->children || !attr->children->content) {
+                               LogError("Failed to get fingerprints from list");
+                               ret = CERTSVC_FAIL;
+                               goto out;
+                       }
+
+                       xmlChar *strLevel = attr->children->content;
+                       xmlNodePtr FpPtr = xmlFirstElementChild(curPtr);
+
+                       if (FpPtr == NULL) {
+                               LogError("Could not find fingerprint");
+                               ret = CERTSVC_FAIL;
+                               goto out;
+                       }
+
+                       LogDebug("Retrieve level : " << strLevel);
+
+                       while (FpPtr) {
+                               xmlChar *content = xmlNodeGetContent(FpPtr);
+
+                               if (xmlStrcmp(content, (xmlChar *)fingerprint.c_str()) == 0) {
+                                       LogDebug("fingerprint : " << content << " are " << strLevel);
+
+                                       if (!xmlStrcmp(strLevel, xmlPathDomainPlatform)) {
+                                               *visibility = CERTSVC_VISIBILITY_PLATFORM;
+                                               ret = CERTSVC_SUCCESS;
+                                               goto out;
+                                       } else if (!xmlStrcmp(strLevel, xmlPathDomainPublic)) {
+                                               *visibility = CERTSVC_VISIBILITY_PUBLIC;
+                                               ret = CERTSVC_SUCCESS;
+                                               goto out;
+                                       } else if (!xmlStrcmp(strLevel, xmlPathDomainPartner)) {
+                                               *visibility = CERTSVC_VISIBILITY_PARTNER;
+                                               ret = CERTSVC_SUCCESS;
+                                               goto out;
+                                       } else if (!xmlStrcmp(strLevel, xmlPathDomainDeveloper)) {
+                                               *visibility = CERTSVC_VISIBILITY_DEVELOPER;
+                                               ret = CERTSVC_SUCCESS;
+                                               goto out;
+                                       }
+                               }
+
+                               FpPtr = xmlNextElementSibling(FpPtr);
+                       }
+
+                       curPtr = xmlNextElementSibling(curPtr);
+               }
+
+               xmlFreeDoc(doc);
+               return CERTSVC_FAIL;
+out:
+               xmlFreeDoc(doc);
+               return ret;
+       }
+
+       inline int pkcsNameIsUniqueInStore(
+               CertStoreType storeType,
+               CertSvcString pfxIdString,
+               int *is_unique)
+       {
+               return vcore_client_check_alias_exist_in_store(storeType, pfxIdString.privateHandler, is_unique);
+       }
+
+       inline int getCertDetailFromStore(CertStoreType storeType,
+                                                                         CertSvcString gname,
+                                                                         char **certBuffer,
+                                                                         size_t *certSize)
+       {
+               return vcore_client_get_certificate_from_store(storeType, gname.privateHandler, certBuffer,
+                               certSize, PEM_CRT);
+       }
+
+       inline int pkcsDeleteCertFromStore(
+               CertStoreType storeType,
+               CertSvcString gname
+       )
+       {
+               return vcore_client_delete_certificate_from_store(storeType, gname.privateHandler);
+       }
+
+       inline int pkcsHasPassword(
+               CertSvcString filepath,
+               int *has_password)
+       {
+               return pkcs12_has_password(filepath.privateHandler, has_password);
+       }
+
+       inline int pkcsImportToStore(
+               CertStoreType storeType,
+               CertSvcString path,
+               CertSvcString pass,
+               CertSvcString pfxIdString)
+       {
+               return pkcs12_import_from_file_to_store(storeType, path.privateHandler, pass.privateHandler,
+                                                                                               pfxIdString.privateHandler);
+       }
+
+       inline int pkcsGetAliasNameForCertInStore(CertStoreType storeType,
+                       CertSvcString gname,
+                       char **alias)
+       {
+               return vcore_client_get_certificate_alias_from_store(storeType, gname.privateHandler, alias);
+       }
+
+       inline int pkcsSetCertStatusToStore(CertStoreType storeType,
+                                                                               int is_root_app,
+                                                                               CertSvcString gname,
+                                                                               CertStatus status)
+       {
+               return vcore_client_set_certificate_status_to_store(storeType, is_root_app, gname.privateHandler,
+                               status);
+       }
+
+       inline int pkcsGetCertStatusFromStore(
+               CertStoreType storeType,
+               CertSvcString gname,
+               CertStatus *status)
+       {
+               return vcore_client_get_certificate_status_from_store(storeType, gname.privateHandler, status);
+       }
+
+       inline int getCertFromStore(CertSvcInstance instance,
+                                                               CertStoreType storeType,
+                                                               const char *gname,
+                                                               CertSvcCertificate *certificate)
+       {
+               return certsvc_get_certificate(instance, storeType, gname, certificate);
+       }
+
+       inline int freePkcsIdListFromStore(CertSvcStoreCertList **certList)
+       {
+               CertSvcStoreCertList *current;
+               CertSvcStoreCertList *next;
+
+               for (current = *certList; current != NULL; current = next) {
+                       next = current->next;
+                       free(current->title);
+                       free(current->gname);
+                       free(current);
+               }
+
+               *certList = NULL;
+               return CERTSVC_SUCCESS;
+       }
+
+       inline int getPkcsIdListFromStore(
+               CertStoreType storeType,
+               int is_root_app,
+               CertSvcStoreCertList **certList,
+               size_t *length)
+       {
+               return vcore_client_get_certificate_list_from_store(storeType, is_root_app, certList, length);
+       }
+
+       inline int getPkcsIdEndUserListFromStore(
+               CertStoreType storeType,
+               CertSvcStoreCertList **certList,
+               size_t *length)
+       {
+               return vcore_client_get_end_user_certificate_list_from_store(storeType, certList, length);
+       }
+
+       inline int getPkcsIdRootListFromStore(
+               CertStoreType storeType,
+               CertSvcStoreCertList **certList,
+               size_t *length)
+       {
+               return vcore_client_get_root_certificate_list_from_store(storeType, certList, length);
+       }
+
+       inline int getPkcsPrivateKeyFromStore(
+               CertStoreType storeType,
+               CertSvcString gname,
+               char **certBuffer,
+               size_t *certSize)
+       {
+               return vcore_client_get_certificate_from_store(storeType, gname.privateHandler, certBuffer,
+                               certSize, (CertType)P12_PKEY);
+       }
+
+       inline int getPkcsCertificateListFromStore(
+               CertSvcInstance &instance,
+               CertStoreType storeType,
+               CertSvcString &pfxIdString,
+               CertSvcCertificateList *handler)
+       {
+               char **certs = NULL;
+               size_t ncerts = 0;
+               int result = vcore_client_load_certificates_from_store(storeType, pfxIdString.privateHandler,
+                                        &certs, &ncerts);
+
+               if (result != CERTSVC_SUCCESS) {
+                       LogError("Unable to load certificates from store.");
+                       return result;
+               }
+
+               std::shared_ptr<char *> certsPtr(certs, CharArrDeleter());
+               std::vector<CertificatePtr> certPtrVector;
+
+               for (size_t i = 0; i < ncerts; i++) {
+                       CertSvcString Alias;
+                       Alias.privateHandler = certs[i];
+                       Alias.privateLength = strlen(certs[i]);
+                       char *certBuffer = NULL;
+                       size_t certLength = 0;
+                       result = certsvc_pkcs12_get_certificate_info_from_store(instance, storeType, Alias, &certBuffer,
+                                        &certLength);
+
+                       if (result != CERTSVC_SUCCESS || !certBuffer) {
+                               LogError("Failed to get certificate buffer.");
+                               return CERTSVC_FAIL;
+                       }
+
+                       std::shared_ptr<char> certBufferPtr(certBuffer, CharDeleter());
+                       const char *header = strstr(certBuffer, START_CERT);
+                       const char *headEnd = START_CERT;
+
+                       if (!header) {
+                               header = strstr(certBuffer, START_TRUSTED);
+                               headEnd = START_TRUSTED;
+
+                               if (!header) {
+                                       LogError("Invalid format of certificate. alias : " << certs[i]);
+                                       return CERTSVC_FAIL;
+                               }
+                       }
+
+                       const char *trailer = strstr(header, END_CERT);
+                       const char *tailEnd = END_CERT;
+
+                       if (!trailer) {
+                               trailer = strstr(header, END_TRUSTED);
+                               tailEnd = END_TRUSTED;
+
+                               if (!trailer) {
+                                       LogError("Invalid format of certificate. alias : " << certs[i]);
+                                       return CERTSVC_FAIL;
+                               }
+                       }
+
+                       if ((strcmp(headEnd, START_CERT) == 0 && strcmp(tailEnd, END_TRUSTED) == 0)
+                                       || (strcmp(headEnd, START_TRUSTED) == 0 && strcmp(tailEnd, END_CERT) == 0)) {
+                               LogError("Invalid format of certificate. alias : " << certs[i]);
+                               return CERTSVC_FAIL;
+                       }
+
+                       header += strlen(headEnd); /* cut headEnd */
+                       std::string certStr(header, strlen(header) - strlen(trailer));
+                       certPtrVector.push_back(CertificatePtr(new Certificate(certStr, Certificate::FORM_BASE64)));
+               }
+
+               std::vector<size_t> listId;
+
+               for (const auto &cert : certPtrVector)
+                       listId.push_back(addCert(cert));
+
+               size_t position = m_idListCounter++;
+               m_idListMap[position] = listId;
+               handler->privateInstance = instance;
+               handler->privateHandler = position;
+               return result;
+       }
+
+       inline bool checkValidStoreType(CertStoreType storeType)
+       {
+               if (storeType >= VPN_STORE && storeType <= ALL_STORE)
+                       return true;
+               else
+                       return false;
+       }
+
+private:
+       size_t m_certificateCounter;
+       std::map<size_t, CertificatePtr> m_certificateMap;
+
+       size_t m_idListCounter;
+       std::map<size_t, std::vector<size_t>> m_idListMap;
+
+       size_t m_stringListCounter;
+       std::map<size_t, std::vector<std::string>> m_stringListMap;
+
+       std::set<char *> m_allocatedStringSet;
+};
+
+inline CertSvcInstanceImpl *impl(CertSvcInstance instance)
+{
+       return static_cast<CertSvcInstanceImpl *>(instance.privatePtr);
+}
+
+} // namespace anonymous
+
+int certsvc_instance_new(CertSvcInstance *instance)
+{
+       static int init = 1;
+
+       if (init) {
+               OpenSSL_add_ssl_algorithms();
+               OpenSSL_add_all_digests();
+               init = 0;
+       }
+
+       try {
+               instance->privatePtr =
+                       reinterpret_cast<void *>(new CertSvcInstanceImpl);
+
+               if (instance->privatePtr)
+                       return CERTSVC_SUCCESS;
+       } catch (std::bad_alloc &) {
+               return CERTSVC_BAD_ALLOC;
+       } catch (...) {}
+
+       return CERTSVC_FAIL;
+}
+
+void certsvc_instance_reset(CertSvcInstance instance)
+{
+       impl(instance)->reset();
+}
+
+void certsvc_instance_free(CertSvcInstance instance)
+{
+       delete impl(instance);
+}
+
+int certsvc_certificate_new_from_file(
+       CertSvcInstance instance,
+       const char *location,
+       CertSvcCertificate *certificate)
+{
+       try {
+               CertificatePtr cert = Certificate::createFromFile(location);
+               certificate->privateInstance = instance;
+               certificate->privateHandler = impl(instance)->addCert(cert);
+               return CERTSVC_SUCCESS;
+               // TODO support for std exceptions
+       } catch (std::bad_alloc &) {
+               return CERTSVC_BAD_ALLOC;
+       } catch (...) {}
+
+       return CERTSVC_FAIL;
+}
+
+int certsvc_certificate_new_from_memory(
+       CertSvcInstance instance,
+       const unsigned char *memory,
+       size_t len,
+       CertSvcCertificateForm form,
+       CertSvcCertificate *certificate)
+{
+       try {
+               Certificate::FormType formType;
+               std::string binary((char *)memory, len);
+
+               if (CERTSVC_FORM_DER == form) {
+                       formType = Certificate::FORM_DER;
+               } else {
+                       formType = Certificate::FORM_BASE64;
+               }
+
+               CertificatePtr cert(new Certificate(binary, formType));
+               certificate->privateInstance = instance;
+               certificate->privateHandler = impl(instance)->addCert(cert);
+               return CERTSVC_SUCCESS;
+       } catch (std::bad_alloc &) {
+               return CERTSVC_BAD_ALLOC;
+       } catch (...) {}
+
+       return CERTSVC_FAIL;
+}
+
+void certsvc_certificate_free(CertSvcCertificate certificate)
+{
+       if (certificate.privateHandler != 0)
+               impl(certificate.privateInstance)->removeCert(certificate);
+}
+
+int certsvc_certificate_save_file(
+       CertSvcCertificate certificate,
+       const char *location)
+{
+       return impl(certificate.privateInstance)->saveToFile(certificate, location);
+}
+
+int certsvc_certificate_list_get_one(
+       CertSvcCertificateList handler,
+       size_t position,
+       CertSvcCertificate *certificate)
+{
+       return impl(handler.privateInstance)->
+                  getCertFromList(handler, position, certificate);
+}
+
+int certsvc_certificate_list_get_length(
+       CertSvcCertificateList handler,
+       size_t *size)
+{
+       return impl(handler.privateInstance)->getCertListLen(handler, size);
+}
+
+void certsvc_certificate_list_free(CertSvcCertificateList handler)
+{
+       impl(handler.privateInstance)->removeCertList(handler);
+}
+
+void certsvc_certificate_list_all_free(CertSvcCertificateList handler)
+{
+       impl(handler.privateInstance)->removeCertListAll(handler);
+}
+
+int certsvc_certificate_is_signed_by(
+       CertSvcCertificate child,
+       CertSvcCertificate parent,
+       int *status)
+{
+       if (child.privateInstance.privatePtr == parent.privateInstance.privatePtr) {
+               return impl(child.privateInstance)->isSignedBy(child, parent, status);
+       }
+
+       return CERTSVC_WRONG_ARGUMENT;
+}
+
+int certsvc_certificate_get_string_field(
+       CertSvcCertificate certificate,
+       CertSvcCertificateField field,
+       CertSvcString *buffer)
+{
+       try {
+               return impl(certificate.privateInstance)->getField(certificate, field, buffer);
+       } catch (std::bad_alloc &) {
+               return CERTSVC_BAD_ALLOC;
+       } catch (...) {}
+
+       return CERTSVC_FAIL;
+}
+
+int certsvc_certificate_get_not_after(
+       CertSvcCertificate certificate,
+       time_t *result)
+{
+       try {
+               return impl(certificate.privateInstance)->getNotAfter(certificate, result);
+       } catch (...) {}
+
+       return CERTSVC_FAIL;
+}
+
+int certsvc_certificate_get_not_before(
+       CertSvcCertificate certificate,
+       time_t *result)
+{
+       try {
+               return impl(certificate.privateInstance)->getNotBefore(certificate, result);
+       } catch (...) {}
+
+       return CERTSVC_FAIL;
+}
+
+int certsvc_certificate_is_root_ca(CertSvcCertificate certificate, int *status)
+{
+       return impl(certificate.privateInstance)->isRootCA(certificate, status);
+}
+
+int certsvc_string_list_get_one(
+       CertSvcStringList handler,
+       size_t position,
+       CertSvcString *buffer)
+{
+       try {
+               return impl(handler.privateInstance)->getStringFromList(handler, position, buffer);
+       } catch (std::bad_alloc &) {
+               return CERTSVC_BAD_ALLOC;
+       } catch (...) {}
+
+       return CERTSVC_FAIL;
+}
+
+int certsvc_string_list_get_length(
+       CertSvcStringList handler,
+       size_t *size)
+{
+       return impl(handler.privateInstance)->getStringListLen(handler, size);
+}
+
+void certsvc_string_list_free(CertSvcStringList handler)
+{
+       if (handler.privateHandler != 0) {
+               impl(handler.privateInstance)->removeStringList(handler);
+               handler.privateHandler = 0;
+       }
+}
+
+void certsvc_string_free(CertSvcString string)
+{
+       if (string.privateHandler)
+               impl(string.privateInstance)->removeString(string);
+}
+
+void certsvc_string_to_cstring(
+       CertSvcString string,
+       const char **buffer,
+       size_t *len)
+{
+       if (buffer) {
+               *buffer = string.privateHandler;
+       }
+
+       if (len) {
+               *len = string.privateLength;
+       }
+}
+
+int certsvc_certificate_chain_sort(
+       CertSvcCertificate *certificate_array,
+       size_t size)
+{
+       try {
+               if (!certificate_array) {
+                       return CERTSVC_WRONG_ARGUMENT;
+               }
+
+               return impl(certificate_array[0].privateInstance)->
+                          sortCollection(certificate_array, size);
+       } catch (std::bad_alloc &) {
+               return CERTSVC_BAD_ALLOC;
+       } catch (...) {}
+
+       return CERTSVC_FAIL;
+}
+
+int certsvc_certificate_dup_x509(CertSvcCertificate certificate, X509 **cert)
+{
+       try {
+               return impl(certificate.privateInstance)->getX509Copy(certificate, cert);
+       } catch (...) {}
+
+       return CERTSVC_FAIL;
+}
+
+void certsvc_certificate_free_x509(X509 *x509)
+{
+       if (x509)
+               X509_free(x509);
+}
+
+int certsvc_certificate_dup_pubkey_der(
+       CertSvcCertificate certificate,
+       unsigned char **pubkey,
+       size_t *len)
+{
+       try {
+               return impl(certificate.privateInstance)->getPubkeyDER(certificate, pubkey, len);
+       } catch (...) {}
+
+       return CERTSVC_FAIL;
+}
+
+void certsvc_pkcs12_free_evp_pkey(EVP_PKEY *pkey)
+{
+       EVP_PKEY_free(pkey);
+}
+
+int certsvc_message_verify(
+       CertSvcCertificate certificate,
+       CertSvcString message,
+       CertSvcString signature,
+       const char *algorithm,
+       int *status)
+{
+       try {
+               return impl(certificate.privateInstance)->verify(
+                                  certificate,
+                                  message,
+                                  signature,
+                                  algorithm,
+                                  status);
+       } catch (...) {}
+
+       return CERTSVC_FAIL;
+}
+
+int certsvc_base64_encode(CertSvcString message, CertSvcString *base64)
+{
+       try {
+               return impl(message.privateInstance)->base64Encode(message, base64);
+       } catch (...) {}
+
+       return CERTSVC_FAIL;
+}
+
+int certsvc_base64_decode(CertSvcString base64, CertSvcString *message)
+{
+       try {
+               return impl(base64.privateInstance)->base64Decode(base64, message);
+       } catch (...) {}
+
+       return CERTSVC_FAIL;
+}
+
+int certsvc_string_new(
+       CertSvcInstance instance,
+       const char *url,
+       size_t size,
+       CertSvcString *output)
+{
+       try {
+               return impl(instance)->stringNew(instance, url, size, output);
+       } catch (...) {}
+
+       return CERTSVC_FAIL;
+}
+
+int certsvc_string_not_managed(
+       CertSvcInstance instance,
+       const char *url,
+       size_t size,
+       CertSvcString *output)
+{
+       if (!output) {
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       output->privateHandler = const_cast<char *>(url);
+       output->privateLength = size;
+       output->privateInstance = instance;
+       return CERTSVC_SUCCESS;
+}
+
+int certsvc_certificate_verify(
+       CertSvcCertificate certificate,
+       const CertSvcCertificate *trusted,
+       size_t trustedSize,
+       const CertSvcCertificate *untrusted,
+       size_t untrustedSize,
+       int *status)
+{
+       try {
+               return impl(certificate.privateInstance)->certificateVerify(
+                                  certificate,
+                                  trusted,
+                                  trustedSize,
+                                  untrusted,
+                                  untrustedSize,
+                                  0,
+                                  status);
+       } catch (...) {}
+
+       return CERTSVC_FAIL;
+}
+
+int certsvc_certificate_verify_with_caflag(
+       CertSvcCertificate certificate,
+       const CertSvcCertificate *trusted,
+       size_t trustedSize,
+       const CertSvcCertificate *untrusted,
+       size_t untrustedSize,
+       int *status)
+{
+       try {
+               return impl(certificate.privateInstance)->certificateVerify(
+                                  certificate,
+                                  trusted,
+                                  trustedSize,
+                                  untrusted,
+                                  untrustedSize,
+                                  1,
+                                  status);
+       } catch (...) {}
+
+       return CERTSVC_FAIL;
+}
+
+int certsvc_certificate_get_visibility(CertSvcCertificate certificate,
+                                                                          CertSvcVisibility *visibility)
+{
+       try {
+               int result = impl(certificate.privateInstance)->getVisibility(certificate, visibility,
+                                        FINGERPRINT_LIST_PATH);
+
+               if (result != CERTSVC_SUCCESS) {
+                       LogDebug("Cannot find store id in FINGERPRINT_LIST_PATH. Find it in extention continue.");
+                       result = impl(certificate.privateInstance)->getVisibility(certificate, visibility,
+                                        FINGERPRINT_LIST_EXT_PATH);
+               }
+
+               return result;
+       } catch (...) {
+               LogError("exception occur");
+       }
+
+       return CERTSVC_FAIL;
+}
+
+int certsvc_get_certificate(CertSvcInstance instance,
+                                                       CertStoreType storeType,
+                                                       const char *gname,
+                                                       CertSvcCertificate *certificate)
+{
+       try {
+               size_t len = 0;
+               char *certbuf = nullptr;
+               int result = vcore_client_get_certificate_from_store(storeType, gname, &certbuf,
+                                                                                                                        &len, PEM_CRT);
+
+               if (result != CERTSVC_SUCCESS) {
+                       LogError("Failed to get certificate buffer from store.");
+                       return result;
+               }
+               std::unique_ptr<char, void(*)(void *)> certbufptr(certbuf, free);
+
+               LogInfo("certbuf: " << certbuf);
+
+               std::unique_ptr<BIO, int(*)(BIO *)> bioptr(BIO_new(BIO_s_mem()), BIO_free);
+               if (bioptr == nullptr) {
+                       LogError("Failed to allocate memory.");
+                       return CERTSVC_BAD_ALLOC;
+               }
+
+               len = BIO_write(bioptr.get(), (const void *)certbuf, (int)len);
+
+               if ((int)len < 1) {
+                       LogError("Failed to load cert into bio.");
+                       return CERTSVC_BAD_ALLOC;
+               }
+
+               std::unique_ptr<X509, void(*)(X509 *)> x509ptr(
+                               PEM_read_bio_X509_AUX(bioptr.get(), nullptr, nullptr, nullptr), X509_free);
+
+               CertificatePtr cert;
+
+               if (x509ptr != nullptr) {
+                       LogInfo("PEM_read_bio_X509_AUX returned x509 struct!");
+                       try {
+                               cert.reset(new Certificate(x509ptr.get()));
+                               LogInfo("Parse cert success with PEM(AUX) form!");
+                       } catch (...) {}
+               }
+
+               if (cert == nullptr) {
+                       x509ptr.reset(PEM_read_bio_X509(bioptr.get(), nullptr, nullptr, nullptr));
+                       if (x509ptr != nullptr) {
+                               LogInfo("PEM_read_bio_X509 returned x509 struct!");
+                               try {
+                                       cert.reset(new Certificate(x509ptr.get()));
+                                       LogInfo("Parse cert success with PEM form!");
+                               } catch (...) {}
+                       }
+               }
+
+               if (cert == nullptr) {
+                       try {
+                               cert.reset(new Certificate(certbuf, Certificate::FormType::FORM_BASE64));
+                               LogInfo("Parse cert success with Base64 form!");
+                       } catch (...) {}
+               }
+
+               if (cert == nullptr) {
+                       try {
+                               cert.reset(new Certificate(certbuf, Certificate::FormType::FORM_DER));
+                               LogInfo("Parse cert success with DER form!");
+                       } catch (...) {}
+               }
+
+               if (cert == nullptr) {
+                       LogError("Failed to parse cert on all of PEM/DER/Base64 form!");
+                       return CERTSVC_INVALID_CERTIFICATE;
+               }
+
+               certificate->privateInstance = instance;
+               certificate->privateHandler = impl(instance)->addCert(cert);
+
+               return CERTSVC_SUCCESS;
+       } catch (std::bad_alloc &) {
+               return CERTSVC_BAD_ALLOC;
+       } catch (...) {
+               return CERTSVC_FAIL;
+       }
+}
+
+int certsvc_pkcs12_check_alias_exists_in_store(CertSvcInstance instance,
+               CertStoreType storeType,
+               CertSvcString pfxIdString,
+               int *is_unique)
+{
+       if (pfxIdString.privateHandler == NULL || pfxIdString.privateLength <= 0) {
+               LogError("Invalid input parameter.");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       try {
+               if (!impl(instance)->checkValidStoreType(storeType)) {
+                       LogError("Invalid input parameter.");
+                       return CERTSVC_INVALID_STORE_TYPE;
+               }
+
+               return impl(instance)->pkcsNameIsUniqueInStore(storeType, pfxIdString, is_unique);
+       } catch (...) {}
+
+       return CERTSVC_FAIL;
+}
+
+int certsvc_pkcs12_free_certificate_list_loaded_from_store(CertSvcInstance instance,
+               CertSvcStoreCertList **certList)
+{
+       if (certList == NULL || *certList == NULL) {
+               LogError("Invalid input parameter.");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       try {
+               return impl(instance)->freePkcsIdListFromStore(certList);
+       } catch (...) {}
+
+       return CERTSVC_FAIL;
+}
+
+int certsvc_pkcs12_get_certificate_list_from_store(CertSvcInstance instance,
+               CertStoreType storeType,
+               int is_root_app,
+               CertSvcStoreCertList **certList,
+               size_t *length)
+{
+       if (certList == NULL || *certList != NULL) {
+               LogError("Invalid input parameter.");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       try {
+               if (!impl(instance)->checkValidStoreType(storeType)) {
+                       LogError("Invalid input parameter.");
+                       return CERTSVC_INVALID_STORE_TYPE;
+               }
+
+               return impl(instance)->getPkcsIdListFromStore(storeType, is_root_app, certList, length);
+       } catch (...) {}
+
+       return CERTSVC_FAIL;
+}
+
+int certsvc_pkcs12_get_end_user_certificate_list_from_store(CertSvcInstance instance,
+               CertStoreType storeType,
+               CertSvcStoreCertList **certList,
+               size_t *length)
+{
+       if (certList == NULL || *certList != NULL) {
+               LogError("Invalid input parameter.");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       try {
+               if (!impl(instance)->checkValidStoreType(storeType)) {
+                       LogError("Invalid input parameter.");
+                       return CERTSVC_INVALID_STORE_TYPE;
+               }
+
+               return impl(instance)->getPkcsIdEndUserListFromStore(storeType, certList, length);
+       } catch (...) {}
+
+       return CERTSVC_FAIL;
+}
+
+int certsvc_pkcs12_get_root_certificate_list_from_store(CertSvcInstance instance,
+               CertStoreType storeType,
+               CertSvcStoreCertList **certList,
+               size_t *length)
+{
+       if (certList == NULL || *certList != NULL) {
+               LogError("Invalid input parameter.");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       try {
+               if (!impl(instance)->checkValidStoreType(storeType)) {
+                       LogError("Invalid input parameter.");
+                       return CERTSVC_INVALID_STORE_TYPE;
+               }
+
+               return impl(instance)->getPkcsIdRootListFromStore(storeType, certList, length);
+       } catch (...) {}
+
+       return CERTSVC_FAIL;
+}
+
+int certsvc_pkcs12_get_certificate_info_from_store(CertSvcInstance instance,
+               CertStoreType storeType,
+               CertSvcString gname,
+               char **certBuffer,
+               size_t *certSize)
+{
+       if (certBuffer == NULL || *certBuffer != NULL) {
+               LogError("Invalid input parameter.");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       try {
+               if (!impl(instance)->checkValidStoreType(storeType)) {
+                       LogError("Invalid input parameter.");
+                       return CERTSVC_INVALID_STORE_TYPE;
+               }
+
+               return impl(instance)->getCertDetailFromStore(storeType, gname, certBuffer, certSize);
+       } catch (...) {}
+
+       return CERTSVC_FAIL;
+}
+
+int certsvc_pkcs12_delete_certificate_from_store(CertSvcInstance instance,
+               CertStoreType storeType,
+               CertSvcString gname)
+{
+       try {
+               if (!impl(instance)->checkValidStoreType(storeType)) {
+                       LogError("Invalid input parameter.");
+                       return CERTSVC_INVALID_STORE_TYPE;
+               }
+
+               return impl(instance)->pkcsDeleteCertFromStore(storeType, gname);
+       } catch (...) {}
+
+       return CERTSVC_FAIL;
+}
+
+int certsvc_pkcs12_import_from_file_to_store(CertSvcInstance instance,
+               CertStoreType storeType,
+               CertSvcString path,
+               CertSvcString password,
+               CertSvcString pfxIdString)
+{
+       try {
+               if (path.privateHandler == NULL || !impl(instance)->checkValidStoreType(storeType)) {
+                       LogError("Invalid input parameter.");
+                       return CERTSVC_INVALID_STORE_TYPE;
+               }
+
+               return impl(instance)->pkcsImportToStore(storeType, path, password, pfxIdString);
+       } catch (...) {
+               LogError("Exception occured from pkcsImportToStore");
+               return CERTSVC_FAIL;
+       }
+}
+
+int certsvc_pkcs12_get_alias_name_for_certificate_in_store(CertSvcInstance instance,
+               CertStoreType storeType,
+               CertSvcString gname,
+               char **alias)
+{
+       if (gname.privateHandler == NULL || gname.privateLength <= 0) {
+               LogError("Invalid input parameter.");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       try {
+               if (!impl(instance)->checkValidStoreType(storeType)) {
+                       LogError("Invalid input parameter.");
+                       return CERTSVC_INVALID_STORE_TYPE;
+               }
+
+               return impl(instance)->pkcsGetAliasNameForCertInStore(storeType, gname, alias);
+       } catch (...) {}
+
+       return CERTSVC_FAIL;
+}
+
+int certsvc_pkcs12_set_certificate_status_to_store(CertSvcInstance instance,
+               CertStoreType storeType,
+               int is_root_app,
+               CertSvcString gname,
+               CertStatus status)
+{
+       try {
+               if (!impl(instance)->checkValidStoreType(storeType)) {
+                       LogError("Invalid input parameter.");
+                       return CERTSVC_INVALID_STORE_TYPE;
+               }
+
+               return impl(instance)->pkcsSetCertStatusToStore(storeType, is_root_app, gname, status);
+       } catch (...) {}
+
+       return CERTSVC_FAIL;
+}
+
+int certsvc_pkcs12_get_certificate_status_from_store(
+       CertSvcInstance instance,
+       CertStoreType storeType,
+       CertSvcString gname,
+       CertStatus *status)
+{
+       try {
+               if (!impl(instance)->checkValidStoreType(storeType)) {
+                       LogError("Invalid input parameter.");
+                       return CERTSVC_INVALID_STORE_TYPE;
+               }
+
+               return impl(instance)->pkcsGetCertStatusFromStore(storeType, gname, status);
+       } catch (...) {}
+
+       return CERTSVC_FAIL;
+}
+
+int certsvc_pkcs12_get_certificate_from_store(CertSvcInstance instance,
+               CertStoreType storeType,
+               const char *gname,
+               CertSvcCertificate *certificate)
+{
+       try {
+               if (!impl(instance)->checkValidStoreType(storeType)) {
+                       LogError("Invalid input parameter.");
+                       return CERTSVC_INVALID_STORE_TYPE;
+               }
+
+               return impl(instance)->getCertFromStore(instance, storeType, gname, certificate);
+       } catch (...) {}
+
+       return CERTSVC_FAIL;
+}
+
+int certsvc_pkcs12_load_certificate_list_from_store(
+       CertSvcInstance instance,
+       CertStoreType storeType,
+       CertSvcString pfxIdString,
+       CertSvcCertificateList *certificateList)
+{
+       try {
+               if (!impl(instance)->checkValidStoreType(storeType)) {
+                       LogError("Invalid input parameter.");
+                       return CERTSVC_INVALID_STORE_TYPE;
+               }
+
+               return impl(instance)->getPkcsCertificateListFromStore(instance, storeType, pfxIdString,
+                               certificateList);
+       } catch (...) {}
+
+       return CERTSVC_FAIL;
+}
+
+int certsvc_pkcs12_private_key_dup_from_store(
+       CertSvcInstance instance,
+       CertStoreType storeType,
+       CertSvcString gname,
+       char **certBuffer,
+       size_t *certSize)
+{
+       try {
+               if (!impl(instance)->checkValidStoreType(storeType)) {
+                       LogError("Invalid input parameter.");
+                       return CERTSVC_INVALID_STORE_TYPE;
+               }
+
+               return impl(instance)->getPkcsPrivateKeyFromStore(storeType, gname, certBuffer, certSize);
+       } catch (...) {}
+
+       return CERTSVC_FAIL;
+}
+
+int certsvc_pkcs12_dup_evp_pkey_from_store(
+       CertSvcInstance instance,
+       CertStoreType storeType,
+       CertSvcString gname,
+       EVP_PKEY **pkey)
+{
+       char *buffer = NULL;
+       size_t size;
+       int result = certsvc_pkcs12_private_key_dup_from_store(instance, storeType, gname, &buffer, &size);
+
+       if (result != CERTSVC_SUCCESS) {
+               LogError("Error in certsvc_pkcs12_private_key_dup");
+               return result;
+       }
+
+       BIO *b = BIO_new(BIO_s_mem());
+
+       if ((int)size != BIO_write(b, buffer, size)) {
+               LogError("Error in BIO_write");
+               BIO_free_all(b);
+               certsvc_pkcs12_private_key_free(buffer);
+               return CERTSVC_FAIL;
+       }
+
+       certsvc_pkcs12_private_key_free(buffer);
+       *pkey = PEM_read_bio_PrivateKey(b, NULL, NULL, NULL);
+       BIO_free_all(b);
+
+       if (*pkey)
+               return CERTSVC_SUCCESS;
+
+       LogError("Result is null. Openssl REASON code is : " << ERR_GET_REASON(ERR_peek_last_error()));
+       return CERTSVC_FAIL;
+}
+
+int certsvc_pkcs12_has_password(
+       CertSvcInstance instance,
+       CertSvcString filepath,
+       int *has_password)
+{
+       try {
+               return impl(instance)->pkcsHasPassword(filepath, has_password);
+       } catch (...) {}
+
+       return CERTSVC_FAIL;
+}
+
+void certsvc_pkcs12_private_key_free(char *buffer)
+{
+       free(buffer);
+}
+
diff --git a/src/vcore/exception.cpp b/src/vcore/exception.cpp
new file mode 100644 (file)
index 0000000..b52655e
--- /dev/null
@@ -0,0 +1,46 @@
+/*
+ * Copyright (c) 2011 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      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation of exception system
+ */
+#include <vcore/exception.h>
+
+#include <dpl/log/log.h>
+
+#include <stddef.h>
+#include <cstdio>
+
+namespace ValidationCore {
+Exception *Exception::m_lastException = NULL;
+unsigned int Exception::m_exceptionCount = 0;
+void (*Exception::m_terminateHandler)() = NULL;
+
+void LogUnhandledException(const std::string &str)
+{
+       LogDebug("" << str);
+}
+
+void LogUnhandledException(const std::string &str,
+                                                  const char *filename,
+                                                  int line,
+                                                  const char *function)
+{
+       LogError("[" << filename << ":" << line << "][" << function << "]" << str);
+}
+} // namespace ValidationCore
diff --git a/src/vcore/exception.h b/src/vcore/exception.h
new file mode 100644 (file)
index 0000000..0129e0a
--- /dev/null
@@ -0,0 +1,382 @@
+/*
+ * Copyright (c) 2011 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  Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version 1.0
+ * @brief   Header file for base exception
+ */
+#ifndef ValidationCore_EXCEPTION_H
+#define ValidationCore_EXCEPTION_H
+
+#include <string>
+#include <cstring>
+#include <cstdio>
+#include <exception>
+#include <cstdlib>
+#include <sstream>
+
+namespace ValidationCore {
+void LogUnhandledException(const std::string &str);
+void LogUnhandledException(const std::string &str,
+                                                  const char *filename,
+                                                  int line,
+                                                  const char *function);
+}
+
+namespace ValidationCore {
+class Exception {
+private:
+       static unsigned int m_exceptionCount;
+       static Exception *m_lastException;
+       static void (*m_terminateHandler)();
+
+       static void AddRef(Exception *exception)
+       {
+               if (!m_exceptionCount) {
+                       m_terminateHandler = std::set_terminate(&TerminateHandler);
+               }
+
+               ++m_exceptionCount;
+               m_lastException = exception;
+       }
+
+       static void UnRef(Exception *e)
+       {
+               if (m_lastException == e) {
+                       m_lastException = NULL;
+               }
+
+               --m_exceptionCount;
+
+               if (!m_exceptionCount) {
+                       std::set_terminate(m_terminateHandler);
+                       m_terminateHandler = NULL;
+               }
+       }
+
+       static void TerminateHandler()
+       {
+               if (m_lastException != NULL) {
+                       DisplayKnownException(*m_lastException);
+                       abort();
+               } else {
+                       DisplayUnknownException();
+                       abort();
+               }
+       }
+
+       Exception *m_reason;
+       std::string m_path;
+       std::string m_function;
+       int m_line;
+
+protected:
+       std::string m_message;
+       std::string m_className;
+
+public:
+       static std::string KnownExceptionToString(const Exception &e)
+       {
+               std::ostringstream message;
+               message <<
+                               "\033[1;5;31m\n=== Unhandled DPL exception occurred ===\033[m\n\n";
+               message << "\033[1;33mException trace:\033[m\n\n";
+               message << e.DumpToString();
+               message << "\033[1;31m\n=== Will now abort ===\033[m\n";
+               return message.str();
+       }
+
+       static std::string UnknownExceptionToString()
+       {
+               std::ostringstream message;
+               message <<
+                               "\033[1;5;31m\n=== Unhandled non-DPL exception occurred ===\033[m\n\n";
+               message << "\033[1;31m\n=== Will now abort ===\033[m\n";
+               return message.str();
+       }
+
+       static void DisplayKnownException(const Exception &e)
+       {
+               LogUnhandledException(KnownExceptionToString(e).c_str());
+       }
+
+       static void DisplayUnknownException()
+       {
+               LogUnhandledException(UnknownExceptionToString().c_str());
+       }
+
+       Exception(const Exception &other)
+       {
+               // Deep copy
+               if (other.m_reason != NULL) {
+                       m_reason = new Exception(*other.m_reason);
+               } else {
+                       m_reason = NULL;
+               }
+
+               m_message = other.m_message;
+               m_path = other.m_path;
+               m_function = other.m_function;
+               m_line = other.m_line;
+               m_className = other.m_className;
+               AddRef(this);
+       }
+
+       const Exception &operator =(const Exception &other)
+       {
+               if (this == &other) {
+                       return *this;
+               }
+
+               // Deep copy
+               if (other.m_reason != NULL) {
+                       m_reason = new Exception(*other.m_reason);
+               } else {
+                       m_reason = NULL;
+               }
+
+               m_message = other.m_message;
+               m_path = other.m_path;
+               m_function = other.m_function;
+               m_line = other.m_line;
+               m_className = other.m_className;
+               AddRef(this);
+               return *this;
+       }
+
+       Exception(const char *path,
+                         const char *function,
+                         int line,
+                         const std::string &message) :
+               m_reason(NULL),
+               m_path(path),
+               m_function(function),
+               m_line(line),
+               m_message(message)
+       {
+               AddRef(this);
+       }
+
+       Exception(const char *path,
+                         const char *function,
+                         int line,
+                         const Exception &reason,
+                         const std::string &message) :
+               m_reason(new Exception(reason)),
+               m_path(path),
+               m_function(function),
+               m_line(line),
+               m_message(message)
+       {
+               AddRef(this);
+       }
+
+       virtual ~Exception() throw()
+       {
+               if (m_reason != NULL) {
+                       delete m_reason;
+                       m_reason = NULL;
+               }
+
+               UnRef(this);
+       }
+
+       void Dump() const
+       {
+               // Show reason first
+               if (m_reason != NULL) {
+                       m_reason->Dump();
+               }
+
+               // Afterward, dump exception
+               const char *file = strchr(m_path.c_str(), '/');
+
+               if (file == NULL) {
+                       file = m_path.c_str();
+               } else {
+                       ++file;
+               }
+
+               printf("\033[0;36m[%s:%i]\033[m %s() \033[4;35m%s\033[m: %s\033[m\n",
+                          file, m_line,
+                          m_function.c_str(),
+                          m_className.c_str(),
+                          m_message.empty() ? "<EMPTY>" : m_message.c_str());
+       }
+
+       std::string DumpToString() const
+       {
+               std::string ret;
+
+               if (m_reason != NULL) {
+                       ret = m_reason->DumpToString();
+               }
+
+               const char *file = strchr(m_path.c_str(), '/');
+
+               if (file == NULL) {
+                       file = m_path.c_str();
+               } else {
+                       ++file;
+               }
+
+               char buf[1024];
+               snprintf(buf,
+                                sizeof(buf),
+                                "\033[0;36m[%s:%i]\033[m %s() \033[4;35m%s\033[m: %s\033[m\n",
+                                file,
+                                m_line,
+                                m_function.c_str(),
+                                m_className.c_str(),
+                                m_message.empty() ? "<EMPTY>" : m_message.c_str());
+               buf[sizeof(buf) - 1] = '\n';
+               ret += buf;
+               return ret;
+       }
+
+       Exception *GetReason() const
+       {
+               return m_reason;
+       }
+
+       std::string GetPath() const
+       {
+               return m_path;
+       }
+
+       std::string GetFunction() const
+       {
+               return m_function;
+       }
+
+       int GetLine() const
+       {
+               return m_line;
+       }
+
+       std::string GetMessage() const
+       {
+               return m_message;
+       }
+
+       std::string GetClassName() const
+       {
+               return m_className;
+       }
+};
+} // namespace ValidationCore
+
+#define VcoreTry try
+
+#define VcoreThrow(ClassName) \
+       throw ClassName(__FILE__, __FUNCTION__, __LINE__)
+
+#define VcoreThrowMsg(ClassName, Message)                                            \
+       do                                                                               \
+       {                                                                                \
+               std::ostringstream dplLoggingStream;                                         \
+               dplLoggingStream << Message;                                                 \
+               throw ClassName(__FILE__, __FUNCTION__, __LINE__, dplLoggingStream.str());   \
+       } while (0)
+
+#define VcoreReThrow(ClassName) \
+       throw ClassName(__FILE__, __FUNCTION__, __LINE__, _rethrown_exception)
+
+#define VcoreReThrowMsg(ClassName, Message)                                          \
+       throw ClassName(__FILE__,                                                        \
+                                       __FUNCTION__,                                                    \
+                                       __LINE__,                                                        \
+                                       _rethrown_exception,                                             \
+                                       Message)
+
+#define VcoreCatch(ClassName)                                                        \
+       catch (const ClassName &_rethrown_exception)
+
+#define VCORE_DECLARE_EXCEPTION_TYPE(BaseClass, Class)                               \
+       class Class : public BaseClass {                                                 \
+       public:                                                                          \
+               Class(const char *path,                                                      \
+                         const char *function,                                                  \
+                         int line,                                                              \
+                         const std::string & message = std::string())                           \
+                       : BaseClass(path, function, line, message) {                               \
+                       \
+                       BaseClass::m_className = #Class;                                         \
+               }                                                                            \
+               \
+               Class(const char *path,                                                      \
+                         const char *function,                                                  \
+                         int line,                                                              \
+                         const ValidationCore::Exception & reason,                              \
+                         const std::string & message = std::string())                           \
+                       : BaseClass(path, function, line, reason, message) {                       \
+                       BaseClass::m_className = #Class;                                         \
+               }                                                                            \
+       };
+
+#define VCORE_UNHANDLED_EXCEPTION_HANDLER_BEGIN try
+
+#define VCORE_UNHANDLED_EXCEPTION_HANDLER_END                                        \
+       catch (const ValidationCore::Exception &exception)                               \
+       {                                                                                \
+               std::ostringstream msg;                                                      \
+               msg << ValidationCore::Exception::KnownExceptionToString(exception);         \
+               ValidationCore::LogUnhandledException(msg.str(),                             \
+                                                                                         __FILE__,                                    \
+                                                                                         __LINE__,                                    \
+                                                                                         __FUNCTION__);                                \
+               abort();                                                                     \
+       }                                                                                \
+       catch (std::exception& e)                                                        \
+       {                                                                                \
+               std::ostringstream msg;                                                      \
+               msg << e.what();                                                             \
+               msg << "\n";                                                                 \
+               msg << ValidationCore::Exception::UnknownExceptionToString();                \
+               ValidationCore::LogUnhandledException(msg.str(),                             \
+                                                                                         __FILE__,                                    \
+                                                                                         __LINE__,                                    \
+                                                                                         __FUNCTION__);                               \
+               abort();                                                                     \
+       }                                                                                \
+       catch (...)                                                                      \
+       {                                                                                \
+               std::ostringstream msg;                                                      \
+               msg << ValidationCore::Exception::UnknownExceptionToString();                \
+               ValidationCore::LogUnhandledException(msg.str(),                             \
+                                                                                         __FILE__,                                    \
+                                                                                         __LINE__,                                    \
+                                                                                         __FUNCTION__);                               \
+               abort();                                                                     \
+       }
+
+namespace ValidationCore {
+namespace CommonException {
+/**
+ * Internal exception definitions
+ *
+ * These should normally not happen.
+ * Usually, exception trace with internal error includes
+ * important messages.
+ */
+VCORE_DECLARE_EXCEPTION_TYPE(Exception, InternalError) ///< Unexpected error from
+// underlying libraries or
+// kernel
+}
+}
+
+#endif // ValidationCore_EXCEPTION_H
diff --git a/src/vcore/init-lib.cpp b/src/vcore/init-lib.cpp
new file mode 100644 (file)
index 0000000..4d3446b
--- /dev/null
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 2016 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        init-lib.cpp
+ * @author      Kyungwook Tak (k.tak@samsung.com)
+ * @version     1.0
+ * @brief       init/deinit global configuration for library
+ */
+
+#include <dpl/log/log.h>
+
+__attribute__((constructor))
+static void init_lib(void)
+{
+       try {
+               VcoreDPL::Log::LogSystemSingleton::Instance().SetTag("CERT_SVC");
+               VcoreDPL::Log::LogSystemSingleton::Instance().SetLogLevel(nullptr);
+       } catch (...) {
+               LogError("Failed to init lib for initialize log system");
+       }
+}
diff --git a/src/vcore/pkcs12.cpp b/src/vcore/pkcs12.cpp
new file mode 100644 (file)
index 0000000..5985005
--- /dev/null
@@ -0,0 +1,859 @@
+/**
+ * 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        pkcs12.cpp
+ * @author      Jacek Migacz (j.migacz@samsung.com)
+ * @author      Kyungwook Tak (k.tak@samsung.com)
+ * @version     1.0
+ * @brief       PKCS#12 container manipulation routines.
+ */
+
+#include <unistd.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <string.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <string>
+#include <memory>
+#include <functional>
+
+#include <openssl/err.h>
+#include <openssl/pkcs12.h>
+#include <openssl/sha.h>
+#include <openssl/x509.h>
+#include <openssl/pem.h>
+
+#include "dpl/log/log.h"
+#include "cert-svc/cerror.h"
+
+#include "vcore/Certificate.h"
+#include "vcore/Client.h"
+#include "vcore/pkcs12.h"
+
+#define SYSCALL(call) while (((call) == -1) && (errno == EINTR))
+
+namespace {
+
+static const std::string START_CERT    = "-----BEGIN CERTIFICATE-----";
+static const std::string END_CERT      = "-----END CERTIFICATE-----";
+static const std::string START_TRUSTED = "-----BEGIN TRUSTED CERTIFICATE-----";
+static const std::string END_TRUSTED   = "-----END TRUSTED CERTIFICATE-----";
+static const std::string START_KEY     = "-----BEGIN PRIVATE KEY-----";
+static const std::string END_KEY       = "-----END PRIVATE KEY-----";
+
+using ValidationCore::CertificatePtr;
+using ValidationCore::Certificate;
+
+using FileUniquePtr      = std::unique_ptr<FILE, std::function<int(FILE *)>>;
+using BioUniquePtr       = std::unique_ptr<BIO, std::function<void(BIO *)>>;
+using PKEYUniquePtr      = std::unique_ptr<EVP_PKEY, std::function<void(EVP_PKEY *)>>;
+using X509UniquePtr      = std::unique_ptr<X509, std::function<void(X509 *)>>;
+using X509StackUniquePtr = std::unique_ptr<STACK_OF(X509), std::function<void(STACK_OF(X509) *)>>;
+
+void X509_stack_free(STACK_OF(X509) *stack)
+{
+       sk_X509_free(stack);
+}
+
+inline bool hasStore(CertStoreType types, CertStoreType type)
+{
+       return (types & type) != 0;
+}
+
+inline CertStoreType nextStore(CertStoreType type)
+{
+       switch (type) {
+       case NONE_STORE:
+               return VPN_STORE;
+
+       case VPN_STORE:
+               return WIFI_STORE;
+
+       case WIFI_STORE:
+               return EMAIL_STORE;
+
+       case EMAIL_STORE:
+               return SYSTEM_STORE;
+
+       case SYSTEM_STORE:
+               return NONE_STORE;
+
+       default:
+               return NONE_STORE;
+       }
+}
+
+std::string generateGname(void)
+{
+       int generator;
+       int64_t random;
+       SHA_CTX ctx;
+       unsigned char d[SHA_DIGEST_LENGTH];
+       int result;
+       char *gname = NULL;
+       SYSCALL(generator = open("/dev/urandom", O_RDONLY));
+
+       if (generator == -1)
+               return std::string();
+
+       SYSCALL(result = read(generator, &random, sizeof(random)));
+
+       if (result == -1) {
+               SYSCALL(close(generator));
+               return std::string();
+       }
+
+       SYSCALL(result = close(generator));
+
+       if (result == -1)
+               return std::string();
+
+       SHA1_Init(&ctx);
+       SHA1_Update(&ctx, &random, sizeof(random));
+       SHA1_Final(d, &ctx);
+       result = asprintf(&gname,
+                                         "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x"
+                                         "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
+                                         d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], d[8], d[9],
+                                         d[10], d[11], d[12], d[13], d[14], d[15], d[16], d[17], d[18], d[19]);
+
+       if (result == -1)
+               return std::string();
+
+       std::string ret(gname);
+       free(gname);
+       return ret;
+}
+
+std::string getCommonName(CertType type, const std::string &cert)
+{
+       BioUniquePtr bio(BIO_new(BIO_s_mem()), BIO_free_all);
+
+       if (bio.get() == NULL) {
+               LogError("Failed to allocate memory.");
+               return std::string();
+       }
+
+       auto readCount = BIO_write(bio.get(), (const void *)cert.data(), (int)cert.length());
+
+       if (readCount < 1) {
+               LogError("Failed to load cert into bio.");
+               return std::string();
+       }
+
+       X509 *x509 = NULL;
+
+       switch (type) {
+       case P12_TRUSTED:
+       case P12_INTERMEDIATE:
+               x509 = PEM_read_bio_X509_AUX(bio.get(), NULL, 0, NULL);
+               break;
+
+       default:
+               x509 = PEM_read_bio_X509(bio.get(), NULL, 0, NULL);
+               break;
+       }
+
+       if (x509 == NULL) {
+               LogError("Failed to create x509 structure.");
+               return std::string();
+       }
+
+       X509UniquePtr x509Ptr(x509, X509_free);
+       const char *subject_c = X509_NAME_oneline(x509->cert_info->subject, NULL, 0);
+
+       if (subject_c == NULL) {
+               LogError("Failed to parse x509 structure");
+               return std::string();
+       }
+
+       return std::string(subject_c);
+}
+
+/*
+ *  column           / common name / associated gname / prikey gname /
+ *  PEM_CRT          : common name / gname            / none         /
+ *  P12_END_USER     : alias       / gname            / prikey gname /
+ *  P12_TRUSTED      : common name / end cert gname   / none         /
+ *  P12_INTERMEDIATE : common name / end cert gname   / none         /
+ */
+
+int installPKEY(CertStoreType storeType,
+                               const std::string &key,
+                               const std::string &gname)
+{
+       return vcore_client_install_certificate_to_store(
+                          storeType,
+                          gname.c_str(),
+                          NULL,
+                          NULL,
+                          NULL,
+                          key.c_str(),
+                          key.length(),
+                          P12_PKEY);
+}
+
+int installEndCert(CertStoreType storeType,
+                                  const std::string &cert,
+                                  const std::string &alias,
+                                  const std::string &gname,
+                                  const std::string &prikeyGname)
+{
+       return vcore_client_install_certificate_to_store(
+                          storeType,
+                          gname.c_str(),
+                          alias.c_str(),
+                          prikeyGname.c_str(),
+                          gname.c_str(),
+                          cert.c_str(),
+                          cert.length(),
+                          P12_END_USER);
+}
+
+int installChainCert(CertStoreType storeType,
+                                        const std::string &cert,
+                                        const std::string &gname,
+                                        const std::string &endCertGname,
+                                        CertType type)
+{
+       std::string commonName = getCommonName(type, cert);
+       return vcore_client_install_certificate_to_store(
+                          storeType,
+                          gname.c_str(),
+                          commonName.c_str(),
+                          NULL,
+                          endCertGname.c_str(),
+                          cert.c_str(),
+                          cert.length(),
+                          type);
+}
+int installCert(CertStoreType storeType,
+                               const std::string &cert,
+                               const std::string &gname)
+{
+       std::string commonName = getCommonName(PEM_CRT, cert);
+       return vcore_client_install_certificate_to_store(
+                          storeType,
+                          gname.c_str(),
+                          commonName.c_str(),
+                          NULL,
+                          NULL,
+                          cert.c_str(),
+                          cert.length(),
+                          PEM_CRT);
+}
+
+std::string readFromFile(const std::string &path)
+{
+       FILE *fp = NULL;
+
+       if ((fp = fopen(path.c_str(), "rb")) == NULL) {
+               LogError("Fail to open file for reading : " << path);
+               return std::string();
+       }
+
+       FileUniquePtr filePtr(fp, fclose);
+       fseek(fp, 0L, SEEK_END);
+       int len = ftell(fp);
+
+       if (len <= 0) {
+               LogError("Fail to get certificate length.");
+               return std::string();
+       }
+
+       rewind(fp);
+       char *content = (char *)malloc(sizeof(char) * (len + 1));
+
+       if (content == NULL) {
+               LogError("Fail to allocate memory");
+               return std::string();
+       }
+
+       memset(content, 0x00, len + 1);
+       size_t readLen = fread(content, sizeof(char), (size_t)len, fp);
+
+       if (readLen != (size_t)len) {
+               LogError("Fail to read file : " << path);
+               free(content);
+               return std::string();
+       }
+
+       content[len] = '\0';
+       std::string ret(content);
+       free(content);
+       return ret;
+}
+
+std::string parseCRT(const std::string &cert)
+{
+       size_t from = 0;
+       size_t to = 0;
+       size_t tailLen = 0;
+       from = cert.find(START_CERT);
+       to = cert.find(END_CERT);
+       tailLen = END_CERT.length();
+
+       if (from == std::string::npos || to == std::string::npos || from > to) {
+               from = cert.find(START_TRUSTED);
+               to = cert.find(END_TRUSTED);
+               tailLen = END_TRUSTED.length();
+       }
+
+       if (from == std::string::npos || to == std::string::npos || from > to)
+               return std::string();
+
+       return std::string(cert, from, to - from + tailLen);
+}
+
+#define _CERT_SVC_VERIFY_PKCS12
+int verify_cert_details(X509 *cert, STACK_OF(X509) *certv)
+{
+       int result = CERTSVC_SUCCESS;
+       char *pSubject = NULL;
+       char *pIssuerName = NULL;
+       X509_STORE_CTX *cert_ctx = NULL;
+       X509_STORE *cert_store = NULL;
+       int res = 0;
+#ifdef _CERT_SVC_VERIFY_PKCS12
+
+       if (certv == NULL) {
+               pSubject = X509_NAME_oneline(cert->cert_info->subject, NULL, 0);
+
+               if (!pSubject) {
+                       LogError("Failed to get subject name");
+                       result = CERTSVC_FAIL;
+                       goto free_memory;
+               }
+
+               pIssuerName = X509_NAME_oneline(cert->cert_info->issuer, NULL, 0);
+
+               if (!pIssuerName) {
+                       LogError("Failed to get issuer name");
+                       result = CERTSVC_FAIL;
+                       goto free_memory;
+               }
+
+               if (strcmp((const char *)pSubject, (const char *)pIssuerName) == 0) {
+                       /*self signed.. */
+                       EVP_PKEY *pKey = NULL;
+                       pKey = X509_get_pubkey(cert);
+
+                       if (!pKey) {
+                               LogError("Failed to get public key");
+                               result = CERTSVC_FAIL;
+                               goto free_memory;
+                       }
+
+                       if (X509_verify(cert, pKey) <= 0) {
+                               LogError("P12 verification failed");
+                               EVP_PKEY_free(pKey);
+                               result = CERTSVC_FAIL;
+                               goto free_memory;
+                       }
+
+                       LogDebug("P12 verification Success");
+                       EVP_PKEY_free(pKey);
+               } else {
+                       cert_store = X509_STORE_new();
+
+                       if (!cert_store) {
+                               LogError("Memory allocation failed");
+                               result = CERTSVC_FAIL;
+                               goto free_memory;
+                       }
+
+                       res = X509_STORE_load_locations(cert_store, NULL, TZ_SYS_CA_CERTS);
+
+                       if (res != 1) {
+                               LogError("P12 load certificate store failed");
+                               X509_STORE_free(cert_store);
+                               result = CERTSVC_FAIL;
+                               goto free_memory;
+                       }
+
+                       res = X509_STORE_set_default_paths(cert_store);
+
+                       if (res != 1) {
+                               LogError("P12 load certificate store path failed");
+                               X509_STORE_free(cert_store);
+                               result = CERTSVC_FAIL;
+                               goto free_memory;
+                       }
+
+                       /* initialise store and store context */
+                       cert_ctx = X509_STORE_CTX_new();
+
+                       if (cert_ctx == NULL) {
+                               LogError("Memory allocation failed");
+                               result = CERTSVC_FAIL;
+                               goto free_memory;
+                       }
+
+                       /* construct store context */
+                       if (!X509_STORE_CTX_init(cert_ctx, cert_store, cert, NULL)) {
+                               LogError("Memory allocation failed");
+                               result = CERTSVC_FAIL;
+                               goto free_memory;
+                       }
+
+#ifdef P12_VERIFICATION_NEEDED
+                       res = X509_verify_cert(cert_ctx);
+
+                       if (res != 1) {
+                               LogError("P12 verification failed");
+                               result = CERTSVC_FAIL;
+                               goto free_memory;
+                       }
+
+                       LogDebug("P12 verification Success");
+#endif
+               }
+       } else if (certv != NULL) {
+               /* Cert Chain */
+               cert_store = X509_STORE_new();
+
+               if (!cert_store) {
+                       LogError("Memory allocation failed");
+                       result = CERTSVC_FAIL;
+                       goto free_memory;
+               }
+
+               res = X509_STORE_load_locations(cert_store, NULL, TZ_SYS_CA_CERTS);
+
+               if (res != 1) {
+                       LogError("P12 load certificate store failed");
+                       result = CERTSVC_FAIL;
+                       goto free_memory;
+               }
+
+               res = X509_STORE_set_default_paths(cert_store);
+
+               if (res != 1) {
+                       LogError("P12 load certificate path failed");
+                       result = CERTSVC_FAIL;
+                       goto free_memory;
+               }
+
+               /* initialise store and store context */
+               cert_ctx = X509_STORE_CTX_new();
+
+               if (cert_ctx == NULL) {
+                       LogError("Memory allocation failed");
+                       result = CERTSVC_FAIL;
+                       goto free_memory;
+               }
+
+               /* construct store context */
+               if (!X509_STORE_CTX_init(cert_ctx, cert_store, cert, NULL)) {
+                       LogError("Memory allocation failed");
+                       result = CERTSVC_FAIL;
+                       goto free_memory;
+               }
+
+               X509_STORE_CTX_trusted_stack(cert_ctx, certv);
+#ifdef P12_VERIFICATION_NEEDED
+               res = X509_verify_cert(cert_ctx);
+
+               if (res != 1) {
+                       LogError("P12 verification failed");
+                       result = CERTSVC_FAIL;
+                       goto free_memory;
+               }
+
+               LogDebug("P12 verification Success");
+#endif
+       }
+
+#endif //_CERT_SVC_VERIFY_PKCS12
+free_memory:
+
+       if (cert_store != NULL)
+               X509_STORE_free(cert_store);
+
+       if (cert_ctx)
+               X509_STORE_CTX_free(cert_ctx);
+
+       free(pSubject);
+       free(pIssuerName);
+       return result;
+}
+
+enum class OsslType : int {
+       PKEY = 1,
+       X509,
+       X509AUX
+};
+
+std::string osslToPEM(OsslType type, void *data)
+{
+       std::vector<char> buf(4096);
+       BioUniquePtr bio(BIO_new(BIO_s_mem()), BIO_free_all);
+
+       if (bio.get() == NULL)
+               return std::string();
+
+       switch (type) {
+       case OsslType::PKEY:
+               PEM_write_bio_PrivateKey(bio.get(), static_cast<EVP_PKEY *>(data), NULL, NULL, 0, NULL, NULL);
+               break;
+
+       case OsslType::X509:
+               PEM_write_bio_X509(bio.get(), static_cast<X509 *>(data));
+               break;
+
+       case OsslType::X509AUX:
+               PEM_write_bio_X509_AUX(bio.get(), static_cast<X509 *>(data));
+               break;
+
+       default:
+               break;
+       }
+
+       int size = BIO_read(bio.get(), buf.data(), 4096);
+
+       if (size <= 0)
+               return std::string();
+
+       buf[size] = '\0';
+       return std::string(buf.data());
+}
+
+int extractPkcs12(const std::string &path,
+                                 const std::string &password,
+                                 PKEYUniquePtr &keyPtr,
+                                 X509UniquePtr &certPtr,
+                                 X509StackUniquePtr &certvPtr)
+{
+       FILE *stream = NULL;
+
+       if ((stream = fopen(path.c_str(), "rb")) == NULL) {
+               LogError("Unable to open the file for reading : " << path);
+               return CERTSVC_IO_ERROR;
+       }
+
+       PKCS12 *container = d2i_PKCS12_fp(stream, NULL);
+       fclose(stream);
+
+       if (container == NULL) {
+               LogError("Failed to parse the input file passed.");
+               return CERTSVC_FAIL;
+       }
+
+       EVP_PKEY *key = NULL;
+       X509 *cert = NULL;
+       STACK_OF(X509) *certv = NULL;
+       int result = PKCS12_parse(container, password.c_str(), &key, &cert, &certv);
+       PKCS12_free(container);
+
+       if (result != 1) {
+               unsigned long e = ERR_get_error();
+               char buf[1024];
+               ERR_error_string_n(e, buf, 1023);
+               LogError("Failed to parse the file passed. openssl err: " << buf);
+               return CERTSVC_FAIL;
+       }
+
+       keyPtr.reset(key);
+       certPtr.reset(cert);
+       certvPtr.reset(certv);
+       return CERTSVC_SUCCESS;
+}
+
+void rollbackStore(CertStoreType storeTypes, const std::string &endCertName)
+{
+       for (CertStoreType storeType = VPN_STORE; storeType < SYSTEM_STORE;
+                       storeType = nextStore(storeType)) {
+               if (!hasStore(storeTypes, storeType))
+                       continue;
+
+               char **certChainName = NULL;
+               size_t ncerts = 0;
+               int result = vcore_client_load_certificates_from_store(storeType, endCertName.c_str(),
+                                        &certChainName, &ncerts);
+
+               if (result != CERTSVC_SUCCESS) {
+                       LogError("Unable to load certificates from store. result : " << result);
+                       continue;
+               }
+
+               for (size_t i = 0; i < ncerts; i++) {
+                       if (certChainName[i] == NULL)
+                               continue;
+
+                       vcore_client_delete_certificate_from_store(storeType, certChainName[i]);
+                       free(certChainName[i]);
+               }
+
+               vcore_client_delete_certificate_from_store(storeType, endCertName.c_str());
+       }
+}
+
+int insertToStore(CertStoreType storeTypes,
+                                 const std::string &alias,
+                                 const std::string &prikeyName,
+                                 const std::string &prikeyBuffer,
+                                 const std::string &endCertName,
+                                 const std::string &endCertBuffer,
+                                 const std::vector<std::string> &certChainName,
+                                 const std::vector<std::string> &certChainBuffer)
+{
+       size_t ncerts = certChainName.size();
+
+       for (CertStoreType storeType = VPN_STORE; storeType < SYSTEM_STORE;
+                       storeType = nextStore(storeType)) {
+               if (!hasStore(storeTypes, storeType))
+                       continue;
+
+               LogDebug("Processing store type : " << storeType);
+               int result = installPKEY(storeType, prikeyBuffer, prikeyName);
+
+               if (result != CERTSVC_SUCCESS) {
+                       LogError("Failed to store the private key contents. result : " << result);
+                       return result;
+               }
+
+               result = installEndCert(storeType, endCertBuffer, alias, endCertName, prikeyName);
+
+               if (result != CERTSVC_SUCCESS) {
+                       LogError("Failed to install the end user certificate. result : " << result);
+                       return result;
+               }
+
+               for (size_t i = 0; i < ncerts; i++) {
+                       if (i == ncerts - 1)
+                               result = installChainCert(storeType, certChainBuffer[i], certChainName[i], endCertName,
+                                                                                 P12_INTERMEDIATE);
+                       else
+                               result = installChainCert(storeType, certChainBuffer[i], certChainName[i], endCertName,
+                                                                                 P12_TRUSTED);
+
+                       if (result != CERTSVC_SUCCESS) {
+                               LogError("Failed to install the ca certificates. result : " << result);
+                               return result;
+                       }
+               }
+       }
+
+       LogDebug("Success to insert extracted pkcs12 data to db");
+       return CERTSVC_SUCCESS;
+}
+
+int insertToStorePEM(CertStoreType storeTypes, const std::string &path, const std::string &gname)
+{
+       std::string content = readFromFile(path);
+
+       if (content.empty()) {
+               LogError("Failed to read the file : " << path);
+               return CERTSVC_IO_ERROR;
+       }
+
+       std::string parsed = parseCRT(content);
+
+       if (parsed.empty()) {
+               LogError("Failed to parse CRT : " << path);
+               return CERTSVC_FAIL;
+       }
+
+       for (CertStoreType storeType = VPN_STORE; storeType < SYSTEM_STORE;
+                       storeType = nextStore(storeType)) {
+               if (!hasStore(storeTypes, storeType))
+                       continue;
+
+               int result = installCert(storeType, parsed, gname);
+
+               if (result != CERTSVC_SUCCESS) {
+                       LogError("Failed to install PEM/CRT to db store : " << storeType << " result : " << result);
+                       rollbackStore(storeTypes, gname);
+                       return result;
+               }
+
+               LogDebug("Success to install PEM/CRT to db store : " << storeType);
+       }
+
+       LogDebug("Success to install PEM/CRT to db stores : " << storeTypes);
+       return CERTSVC_SUCCESS;
+}
+
+} // namespace anonymous
+
+
+int pkcs12_import_from_file_to_store(CertStoreType storeTypes,
+                                                                        const char *_path,
+                                                                        const char *_password,
+                                                                        const char *_alias)
+{
+       int result = 0;
+
+       if (_alias == NULL || _path == NULL || strlen(_path) < 4) {
+               LogError("Invalid input parameter.");
+               return CERTSVC_WRONG_ARGUMENT;
+       }
+
+       std::string path(_path);
+       std::string alias(_alias);
+       std::string password;
+
+       if (_password != NULL)
+               password = std::string(_password);
+
+       LogDebug("pkcs12_import_from_file_to_store start. path[" << path << "] password[" << password <<
+                        "] alias[" << alias << "]");
+
+       if (storeTypes & SYSTEM_STORE) {
+               LogError("User should not install any form of certificates in SYSTEM_STORE.");
+               return CERTSVC_INVALID_STORE_TYPE;
+       }
+
+       /*
+        * Installs CRT and PEM files.
+        * We will passing NULL for private_key_gname and associated_gname parameter
+        * in installFilePEM(). Which means that there is no private key involved
+        * in the certificate which we are installing and there are no other
+        * certificates related with the current certificate which is installed
+        */
+       std::string suffix = path.substr(path.length() - 4, 4);
+
+       if (strcasecmp(suffix.c_str(), ".pem") == 0 || strcasecmp(suffix.c_str(), ".crt") == 0) {
+               std::string gnamePEM = generateGname();
+               result = insertToStorePEM(storeTypes, path, gnamePEM);
+
+               if (result != CERTSVC_SUCCESS)
+                       LogError("Failed to install PEM/CRT file to store. gname : " << gnamePEM << " result : " << result);
+
+               return result;;
+       }
+
+       LogDebug("Convert ossl type to string start");
+       /* 0. extract pkcs12 data from file */
+       PKEYUniquePtr key(nullptr, EVP_PKEY_free);
+       X509UniquePtr cert(nullptr, X509_free);
+       X509StackUniquePtr certv(nullptr, X509_stack_free);
+       result = extractPkcs12(path, password, key, cert, certv);
+
+       if (result != CERTSVC_SUCCESS) {
+               LogError("Failed to extract pkcs12 file. result : " << result);
+               return result;
+       }
+
+       LogDebug("extract pkcs12 to unique ptr success");
+       result = verify_cert_details(cert.get(), certv.get());
+
+       if (result != CERTSVC_SUCCESS) {
+               LogError("Failed to verify p12 certificate. result : " << result);
+               return result;
+       }
+
+       /* 1. handling private key */
+       std::string prikeyName = generateGname();
+       std::string prikeyBuffer = osslToPEM(OsslType::PKEY, key.get());
+
+       if (prikeyName.empty() || prikeyBuffer.empty()) {
+               LogError("Failed to transform pkey to PEM. result : " << result);
+               return CERTSVC_FAIL;
+       }
+
+       LogDebug("Convert pkey to string success");
+       /* 2. handling end user certificate */
+       std::string endCertName = generateGname();
+       std::string endCertBuffer = osslToPEM(OsslType::X509, cert.get());
+
+       if (endCertName.empty() || endCertBuffer.empty()) {
+               LogError("Failed to transform x509 to PEM. result : " << result);
+               return CERTSVC_FAIL;
+       }
+
+       LogDebug("Convert end cert to string success");
+       /* 3. handling certificate chain */
+       std::vector<std::string> certChainName;
+       std::vector<std::string> certChainBuffer;
+       int ncerts = certv ? sk_X509_num(certv.get()) : 0;
+
+       for (int i = 0; i < ncerts; i++) {
+               std::string tempName = generateGname();
+               std::string tempBuffer = osslToPEM(OsslType::X509AUX, sk_X509_value(certv.get(), i));
+
+               if (tempName.empty() || tempBuffer.empty()) {
+                       LogError("Failed to transform x509 AUX to PEM");
+                       return CERTSVC_FAIL;
+               }
+
+               certChainName.push_back(std::move(tempName));
+               certChainBuffer.push_back(std::move(tempBuffer));
+       }
+
+       LogDebug("Convert cert chain to string success");
+       /* 4. insert extracted pkcs12 data to db */
+       result = insertToStore(storeTypes,
+                                                  alias,
+                                                  prikeyName,
+                                                  prikeyBuffer,
+                                                  endCertName,
+                                                  endCertBuffer,
+                                                  certChainName,
+                                                  certChainBuffer);
+
+       if (result != CERTSVC_SUCCESS)
+               rollbackStore(storeTypes, endCertName);
+
+       LogDebug("Success to import pkcs12 to store");
+       return result;
+}
+
+int pkcs12_has_password(const char *filepath, int *passworded)
+{
+       if (filepath == NULL || passworded == NULL)
+               return CERTSVC_WRONG_ARGUMENT;
+
+       FILE *stream;
+
+       if ((stream = fopen(filepath, "rb")) == NULL)
+               return CERTSVC_IO_ERROR;
+
+       PKCS12 *container = d2i_PKCS12_fp(stream, NULL);
+       fclose(stream);
+
+       if (container == NULL)
+               return CERTSVC_FAIL;
+
+       EVP_PKEY *pkey = NULL;
+       X509 *cert = NULL;
+       int result = PKCS12_parse(container, NULL, &pkey, &cert, NULL);
+       PKCS12_free(container);
+
+       if (pkey != NULL)
+               EVP_PKEY_free(pkey);
+
+       if (cert != NULL)
+               X509_free(cert);
+
+       if (result != 1) {
+               unsigned long e = ERR_get_error();
+               if (ERR_GET_REASON(e) == PKCS12_R_MAC_VERIFY_FAILURE) {
+                       LogInfo("verify failed without password. file(" << filepath << ") is password-protected.");
+                       *passworded = CERTSVC_TRUE;
+               } else {
+                       char buf[1024];
+                       ERR_error_string_n(e, buf, 1023);
+                       LogError("Error on PKCS12_pasre file(" << filepath << "): " << buf);
+                       return CERTSVC_FAIL;
+               }
+       } else {
+               *passworded = CERTSVC_FALSE;
+       }
+
+       return CERTSVC_SUCCESS;
+}
diff --git a/src/vcore/pkcs12.h b/src/vcore/pkcs12.h
new file mode 100644 (file)
index 0000000..f98ebf8
--- /dev/null
@@ -0,0 +1,45 @@
+/**
+ * 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        pkcs12.h
+ * @author      Jacek Migacz (j.migacz@samsung.com)
+ * @version     1.0
+ * @brief       PKCS#12 container manipulation routines.
+ */
+#pragma once
+
+#include <cert-svc/ccert.h>
+
+/**
+ * To import the p12/pfx/crt/pem file to specified store (WIFI_STORE/VPN_STORE/EMAIL_STORE).
+ *
+ * @param[in] storeType Refers to WIFI_STORE / VPN_STORE / EMAIL_STORE / ALL_STORE.
+ * @param[in] path Path to file.
+ * @param[in] password Password for opening the file.
+ * @param[in] alias Logical name for certificate bundle identification (can't be empty).
+ * @return CERTSVC_SUCCESS, CERTSVC_FAIL, CERTSVC_DUPLICATED_ALIAS, CERTSVC_IO_ERROR, CERTSVC_WRONG_ARGUMENT, CERTSVC_BAD_ALLOC.
+ */
+int pkcs12_import_from_file_to_store(CertStoreType storeType, const char *path,
+                                                                        const char *password, const char *alias);
+
+/**
+ * TO check if the p12/pfx file is protected by password or not.
+ *
+ * @param[in] filePath Where the file is located.
+ * @param[out] passworded A boolean value to state if the file is protected by password or not.
+ * @return CERTSVC_SUCCESS, CERTSVC_FAIL, CERTSVC_IO_ERROR, CERTSVC_WRONG_ARGUMENT.
+ */
+int pkcs12_has_password(const char *filepath, int *passworded);
index 58bfe1eac55607c6d9541f5ddb9cfbede4b648a7..11bdab1346639feb9641f7b50875e87d486c63a4 100644 (file)
@@ -45,7 +45,7 @@ SET(DPL_TEST_SOURCES
 INCLUDE_DIRECTORIES(
     SYSTEM
     ${TEST_DEP_INCLUDE_DIRS}
-    ${PROJECT_SOURCE_DIR}/vcore
+    ${PROJECT_SOURCE_DIR}/src
     ${TEST_DIR}/dpl/include
     )
 
diff --git a/vcore/CMakeLists.txt b/vcore/CMakeLists.txt
deleted file mode 100644 (file)
index 474e062..0000000
+++ /dev/null
@@ -1,153 +0,0 @@
-IF(TIZEN_PROFILE_MOBILE)
-    ADD_DEFINITIONS("-DTIZEN_PROFILE_MOBILE")
-    SET(LIB_CERT_CHECKER cert-checker)
-ENDIF(TIZEN_PROFILE_MOBILE)
-
-PKG_CHECK_MODULES(VCORE_DEPS
-    REQUIRED
-    libxml-2.0
-    libpcrecpp
-    openssl
-    xmlsec1
-    dlog
-    libsystemd-journal
-    ${LIB_CERT_CHECKER}
-    )
-
-ADD_DEFINITIONS(${VCORE_DEPS_CFLAGS})
-ADD_DEFINITIONS(${VCORE_DEPS_CFLAGS_OTHER})
-
-SET(VCORE_DIR ${CMAKE_CURRENT_SOURCE_DIR})
-
-SET(VCORE_SOURCES
-    ${VCORE_DIR}/dpl/core/src/assert.cpp
-    ${VCORE_DIR}/dpl/core/src/exception.cpp
-    ${VCORE_DIR}/dpl/core/src/singleton.cpp
-    ${VCORE_DIR}/dpl/core/src/colors.cpp
-
-    ${VCORE_DIR}/dpl/log/src/abstract_log_provider.cpp
-    ${VCORE_DIR}/dpl/log/src/old_style_log_provider.cpp
-    ${VCORE_DIR}/dpl/log/src/dlog_log_provider.cpp
-    ${VCORE_DIR}/dpl/log/src/journal_log_provider.cpp
-    ${VCORE_DIR}/dpl/log/src/log.cpp
-
-    ${VCORE_DIR}/vcore/api.cpp
-    ${VCORE_DIR}/vcore/Base64.cpp
-    ${VCORE_DIR}/vcore/Certificate.cpp
-    ${VCORE_DIR}/vcore/CertificateCollection.cpp
-    ${VCORE_DIR}/vcore/CertificateConfigReader.cpp
-    ${VCORE_DIR}/vcore/CertificateLoader.cpp
-    ${VCORE_DIR}/vcore/CertStoreType.cpp
-    ${VCORE_DIR}/vcore/ReferenceValidator.cpp
-    ${VCORE_DIR}/vcore/SaxReader.cpp
-    ${VCORE_DIR}/vcore/SignatureData.cpp
-    ${VCORE_DIR}/vcore/SignatureFinder.cpp
-    ${VCORE_DIR}/vcore/SignatureReader.cpp
-    ${VCORE_DIR}/vcore/TimeConversion.cpp
-    ${VCORE_DIR}/vcore/ValidatorFactories.cpp
-    ${VCORE_DIR}/vcore/SignatureValidator.cpp
-    ${VCORE_DIR}/vcore/XmlsecAdapter.cpp
-    ${VCORE_DIR}/vcore/pkcs12.cpp
-    ${VCORE_DIR}/vcore/exception.cpp
-    ${VCORE_DIR}/vcore/Client.cpp
-    ${VCORE_DIR}/vcore/Ocsp.cpp
-    ${VCORE_DIR}/vcore/CryptoInit.cpp
-    ${VCORE_DIR}/vcore/PluginHandler.cpp
-    ${VCORE_DIR}/vcore/init-lib.cpp
-    )
-
-SET(VCORE_INCLUDES
-    ${VCORE_DIR}/dpl/core/include
-    ${VCORE_DIR}/dpl/log/include
-    ${VCORE_DIR}
-    )
-
-########### VCORE SOURCES ########
-
-INCLUDE_DIRECTORIES(
-    SYSTEM
-    ${VCORE_DEPS_INCLUDE_DIRS}
-    ${VCORE_INCLUDES}
-    )
-
-ADD_LIBRARY(${TARGET_VCORE_LIB} SHARED ${VCORE_SOURCES})
-
-# TODO: visibility needed to be hidden
-SET_TARGET_PROPERTIES(${TARGET_VCORE_LIB}
-    PROPERTIES
-        COMPILE_FLAGS "-D_GNU_SOURCE -fPIC -fvisibility=default"
-        SOVERSION ${SO_VERSION}
-        VERSION ${VERSION})
-
-TARGET_LINK_LIBRARIES(${TARGET_VCORE_LIB}
-    ${VCORE_DEPS_LIBRARIES}
-    ${TARGET_CERT_SVC_LIB}
-    -ldl
-    )
-
-########## cert-server #############
-PKG_CHECK_MODULES(CERT_SERVER_DEP
-    REQUIRED
-    dlog
-    sqlite3
-    db-util
-    libsystemd-daemon
-    key-manager
-    )
-
-SET(CERT_SERVER_DIR ${CMAKE_CURRENT_SOURCE_DIR}/server)
-
-SET(CERT_SERVER_SRC
-    ${CERT_SERVER_DIR}/src/cert-server-main.c
-    ${CERT_SERVER_DIR}/src/cert-server-logic.c
-    ${CERT_SERVER_DIR}/src/cert-server-db.c
-    )
-
-INCLUDE_DIRECTORIES(
-    SYSTEM
-    ${CERT_SERVER_DEP_INCLUDE_DIRS}
-    ${VCORE_DIR}
-    ${CERT_SERVER_DIR}/include
-    )
-
-SET_SOURCE_FILES_PROPERTIES(
-    ${CERT_SERVER_SRC}
-    PROPERTIES
-        COMPILE_FLAGS "-D_GNU_SOURCE -fvisibility=hidden -fPIE"
-    )
-
-ADD_EXECUTABLE(${TARGET_CERT_SERVER} ${CERT_SERVER_SRC})
-
-TARGET_LINK_LIBRARIES(${TARGET_CERT_SERVER}
-    ${CERT_SERVER_DEP_LIBRARIES}
-    -pie
-    )
-
-INSTALL(TARGETS ${TARGET_CERT_SERVER} DESTINATION ${BIN_DIR})
-
-########################################################
-INSTALL(TARGETS ${TARGET_VCORE_LIB}
-    DESTINATION ${LIB_INSTALL_DIR}
-    )
-
-INSTALL(FILES
-    ${VCORE_DIR}/vcore/SignatureValidator.h
-    ${VCORE_DIR}/vcore/SignatureFinder.h
-    ${VCORE_DIR}/vcore/Certificate.h
-    ${VCORE_DIR}/vcore/SignatureData.h
-    ${VCORE_DIR}/vcore/CertStoreType.h
-    ${VCORE_DIR}/vcore/exception.h
-    ${VCORE_DIR}/vcore/ValidatorPluginApi.h
-    ${VCORE_DIR}/vcore/Error.h
-    DESTINATION ${INCLUDEDIR}/cert-svc/vcore
-    )
-
-INSTALL(FILES
-    ${VCORE_DIR}/cert-svc/ccert.h
-    ${VCORE_DIR}/cert-svc/cinstance.h
-    ${VCORE_DIR}/cert-svc/cerror.h
-    ${VCORE_DIR}/cert-svc/cpkcs12.h
-    ${VCORE_DIR}/cert-svc/cprimitives.h
-    ${VCORE_DIR}/cert-svc/cstring.h
-    DESTINATION ${INCLUDEDIR}/cert-svc/cert-svc
-    )
diff --git a/vcore/cert-svc/ccert.h b/vcore/cert-svc/ccert.h
deleted file mode 100644 (file)
index cc2f61b..0000000
+++ /dev/null
@@ -1,447 +0,0 @@
-/**
- * Copyright (c) 2016 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        ccert.h
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief       This is part of C api for ValidationCore.
- */
-#ifndef _CERTSVC_CCERT_H_
-#define _CERTSVC_CCERT_H_
-
-#include <time.h>
-
-#include <cert-svc/cinstance.h>
-#include <cert-svc/cstring.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-typedef struct CertSvcCertificate_t {
-       size_t privateHandler;
-       CertSvcInstance privateInstance;
-} CertSvcCertificate;
-
-typedef struct CertSvcCertificateList_t {
-       size_t privateHandler;
-       CertSvcInstance privateInstance;
-} CertSvcCertificateList;
-
-#define MAX_STORE_ENUMS 5
-typedef enum certImportType_t {
-       NONE_STORE   =  0,
-       VPN_STORE    =  1 << 0,
-       WIFI_STORE   =  1 << 1,
-       EMAIL_STORE  =  1 << 2,
-       SYSTEM_STORE =  1 << 3,
-       ALL_STORE    =  VPN_STORE | WIFI_STORE | EMAIL_STORE | SYSTEM_STORE
-} CertStoreType;
-
-typedef enum certStatus_t {
-       DISABLED     =  0,
-       ENABLED      =  1
-} CertStatus;
-
-typedef struct CertSvcStoreCertList_t {
-       char *gname;            // keyfile group name
-       char *title;            // common Name / Alias provided by the user
-       CertStatus status;
-       CertStoreType storeType;
-       struct CertSvcStoreCertList_t *next;
-} CertSvcStoreCertList;
-
-typedef enum certType_t {
-       PEM_CRT          = 1 << 0,
-       P12_END_USER     = 1 << 1,
-       P12_INTERMEDIATE = 1 << 2,
-       P12_TRUSTED      = 1 << 3,
-       P12_PKEY         = 1 << 4,
-       INVALID_DATA     = 1 << 5
-} CertType;
-
-typedef enum CertSvcCertificateForm_t {
-       /*    CERTSVC_FORM_PEM, */
-       CERTSVC_FORM_DER,
-       CERTSVC_FORM_DER_BASE64
-} CertSvcCertificateForm;
-
-typedef enum CertSvcCertificateField_t {
-       CERTSVC_SUBJECT,
-       CERTSVC_SUBJECT_COMMON_NAME,
-       CERTSVC_SUBJECT_COUNTRY_NAME,
-       CERTSVC_SUBJECT_STATE_NAME,
-       CERTSVC_SUBJECT_LOCALITY_NAME,
-       CERTSVC_SUBJECT_ORGANIZATION_NAME,
-       CERTSVC_SUBJECT_ORGANIZATION_UNIT_NAME,
-       CERTSVC_SUBJECT_EMAIL_ADDRESS,
-       /*    CERTSVC_SUBJECT_UID, */
-       CERTSVC_ISSUER,
-       CERTSVC_ISSUER_COMMON_NAME,
-       CERTSVC_ISSUER_COUNTRY_NAME,
-       CERTSVC_ISSUER_STATE_NAME,
-       CERTSVC_ISSUER_LOCALITY_NAME,
-       CERTSVC_ISSUER_ORGANIZATION_NAME,
-       CERTSVC_ISSUER_ORGANIZATION_UNIT_NAME,
-       CERTSVC_ISSUER_EMAIL_ADDRESS,
-       /*    CERTSVC_ISSUER_UID, */
-       CERTSVC_VERSION,
-       CERTSVC_SERIAL_NUMBER,
-       CERTSVC_KEY_USAGE,
-       CERTSVC_KEY,
-       CERTSVC_KEY_ALGO,
-       CERTSVC_SIGNATURE_ALGORITHM
-} CertSvcCertificateField;
-
-typedef enum CertSvcVisibility_t {
-       CERTSVC_VISIBILITY_DEVELOPER            = 1,
-       CERTSVC_VISIBILITY_PUBLIC               = 1 << 6,
-       CERTSVC_VISIBILITY_PARTNER              = 1 << 7,
-       CERTSVC_VISIBILITY_PLATFORM             = 1 << 10
-} CertSvcVisibility;
-
-/**
- * Get certificate with gname provided.
- *
- * @param[in]  instance     CertSvcInstance object
- * @param[in]  storeType    cert-svc store type to query
- * @oaran[in]  gname        Single certificate identifier
- * @param[out] certificate  Must be freed by certsvc_certificate_free() after use
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- *
- * @see certsvc_instance_new()
- * @see certsvc_instance_free()
- * @see certsvc_certificate_free()
- * @see #CertStoreType
- * @see #CertSvcCertificate
- */
-int certsvc_get_certificate(CertSvcInstance instance,
-                                                       CertStoreType storeType,
-                                                       const char *gname,
-                                                       CertSvcCertificate *certificate);
-
-/**
- * Load certificate to @a CertSvcCertificate from file.
- * Certificate must be in PEM/CER/DER format.
- *
- * @param[in]  instance     CertSvcInstance object
- * @param[in]  location     Path of file to load
- * @param[out] certificate  Certificate id assigned to loaded certificate
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- *
- * @see certsvc_instance_new()
- * @see certsvc_instance_free()
- * @see certsvc_certificate_free()
- * @see #CertSvcCertificate
- */
-int certsvc_certificate_new_from_file(CertSvcInstance instance,
-                                                                         const char *location,
-                                                                         CertSvcCertificate *certificate);
-
-/**
- * Load certificate to @a CertSvcCertificate from memory.
- *
- * @param[in]  instance     CertSvcInstance object
- * @param[in]  memory       Pointer to memory with certificate data
- * @param[in]  len          Size of certificate in @a memory
- * @param[in]  form         Certificate format in @a memory
- * @param[out] certificate  Must be freed by certsvc_certificate_free() after use
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- *
- * @see certsvc_instance_new()
- * @see certsvc_instance_free()
- * @see certsvc_certificate_free()
- * @see #CertSvcCertificate
- * @see #CertSvcCertificateForm
- */
-int certsvc_certificate_new_from_memory(CertSvcInstance instance,
-                                                                               const unsigned char *memory,
-                                                                               size_t len,
-                                                                               CertSvcCertificateForm form,
-                                                                               CertSvcCertificate *certificate);
-
-/**
- * Free structures connected with certificate.
- *
- * @param[in] certificate  Certificate to free
- */
-void certsvc_certificate_free(CertSvcCertificate certificate);
-
-/**
- * Save certificate to file in @a location in DER format.
- *
- * @param[in] certificate  Certificate
- * @param[in] location     Location
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- *
- * @see #CertSvcCertificate
- */
-int certsvc_certificate_save_file(CertSvcCertificate certificate, const char *location);
-
-/**
- * Get certificate from list founded by certsvc_certificate_search().
- * Can be called multiple times to get all results.
- * Returned certificate can be freed. certsvc_certificate_list_free() doesn't
- * free certificates in the list.
- *
- * @param[in]  hadler      Hander to search results.
- * @param[in]  position    List index start from 0
- * @param[out] certificate Certficate i
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- *
- * @see certsvc_certificate_search()
- * @see certsvc_certificate_free()
- * @see #CertSvcCertificate
- * @see #CertSvcCertificateList
- */
-int certsvc_certificate_list_get_one(CertSvcCertificateList handler,
-                                                                        size_t position,
-                                                                        CertSvcCertificate *certificate);
-
-/**
- * Return number of elements on the list.
- *
- * @param[in]  handler  Handler to certifiacte list
- * @param[out] length   Size of list
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- *
- * @see certsvc_certificate_search()
- * @see #CertSvcCertificateList
- */
-int certsvc_certificate_list_get_length(CertSvcCertificateList handler,
-                                                                               size_t *size);
-
-/**
- * Free @a CertSvcCertificateList. It will not free certificates on the list.
- * You may free each certificate with certsvc_certificate_free().
- *
- * @param[in] handler  Handler to search result
- *
- * @see certsvc_certificate_search()
- * @see certsvc_certificate_list_get_one()
- * @see certsvc_certificate_free()
- * @see #CertSvcCertificateList
- */
-void certsvc_certificate_list_free(CertSvcCertificateList handler);
-
-/**
- * This function will free list. It will free all certificates on the list.
- * You should ""NOT"" free each certificate with certsvc_certificate_free.
- *
- * @param[in] handler Handler to search result.
- */
-void certsvc_certificate_list_all_free(CertSvcCertificateList handler);
-
-/**
- * Compare parent certificate subject with child issuer field.
- *
- * @param[in]  child   Child certificate. Issuer field will be used
- * @param[in]  parent  Parent certificate. Subject field will be used
- * @param[out] status  #CERTSVC_TRUE if @a child is signed by @a parent,
- *                     else #CERTSVC_FALSE
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- *
- * @see #CertSvcCertificate
- */
-int certsvc_certificate_is_signed_by(CertSvcCertificate child,
-                                                                        CertSvcCertificate parent,
-                                                                        int *status);
-
-/**
- * Extract data field from certificate. Data in buffer could be free by
- * certsvc_string_free() function or by certsvc_instance_free or vcore_instance_reset.
- *
- * @param[in]  certificate  Certificate
- * @param[in]  field        Certificate field to get
- * @param[out] buffer       output string. Must be freed by certsvc_string_free()
- *                          or certsvc_instance_free() after use
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- *
- * @see certsvc_instance_free()
- * @see certsvc_string_free()
- * @see #CertSvcCertificate
- * @see #CertSvcCertificateField
- */
-int certsvc_certificate_get_string_field(CertSvcCertificate certificate,
-               CertSvcCertificateField field,
-               CertSvcString *buffer);
-
-/**
- * Extract NOT AFTER field from certificate.
- *
- * @param[in]  certificate  Certificate
- * @param[out] result       not after time_t
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- *
- * @see #CertSvcCertificate
- */
-int certsvc_certificate_get_not_after(CertSvcCertificate certificate, time_t *result);
-
-/**
- * Extract NOT BEFORE field from certificate.
- *
- * @param[in]   certificate  Certificate
- * @param[out]  result       not before time_t
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- */
-int certsvc_certificate_get_not_before(CertSvcCertificate certificate, time_t *result);
-
-/**
- * Check whether the certificate is root ca by checking self-signedness.
- * TODO: This fuction should also check ROOTCA field in certificate.
- *
- * @param[in]   certificate  Certificate
- * @param[out]  status       #CERTSVC_TRUE or #CERTSVC_FALSE
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- *
- * @see #CertSvcCertificate
- */
-int certsvc_certificate_is_root_ca(CertSvcCertificate certificate, int *status);
-
-/**
- * Sort certificates chain. This fuction modifies certificate_array.
- *
- * @param[in/out] unsortedChain  unsorted chain in form of @a CertSvcCertificate array
- *                               which will be sorted from end entity certificate on
- *                               the first position and (root) CA certificate on the
- *                               last position
- * @param[in]     size           Size of @a unsortedChain
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- *
- * @see #CertSvcCertificate
- */
-int certsvc_certificate_chain_sort(CertSvcCertificate *unsortedChain, size_t size);
-
-/**
- * Base64 string will be connected with same instance as message.
- *
- * @param[in]  message  Buffer with input data
- * @param[out] base64   Buffer with output data which must be freed by
- *                      certsvc_string_free() or certsvc_instance_free() after use
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- *
- * @see certsvc_instance_free()
- * @see certsvc_string_free()
- */
-int certsvc_base64_encode(CertSvcString message, CertSvcString *base64);
-
-/**
- * Message string will be connected with same certsvc instance as base64.
- *
- * @param[in]  base64   Buffer with input data
- * @param[out] message  Buffer with output data which must be freed by
- *                      certsvc_string_free() or certsvc_instance_free() after use
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- *
- * @see certsvc_instance_free()
- * @see certsvc_string_free()
- */
-int certsvc_base64_decode(CertSvcString base64, CertSvcString *message);
-
-/**
- * Verify signature with given arguments.
- *
- * @param[in]  certificate  Certificate
- * @param[in]  message      Message
- * @param[in]  signature    Signature to verify
- * @param[in]  algorithm    May be set to NULL
- * @param[out] status       #CERTSVC_SUCCESS if success, else #CERTSVC_INVALID_SIGNATURE
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- *
- */
-int certsvc_message_verify(
-       CertSvcCertificate certificate,
-       CertSvcString message,
-       CertSvcString signature,
-       const char *algorithm,
-       int *status);
-
-/**
- * Verify certificate. Root CA certificate should be stored in @a trusted.
- *
- * @param[in]  certificate    Certificate
- * @param[in]  trusted        Array with trusted certificates
- * @param[in]  trustedSize    Array size of @a trusted
- * @param[in]  untrusted      Array with untrusted certificates
- * @param[in]  untrustedSize  Array size of @a untrusted
- * @param[out] status         #CERTSVC_SUCCESS if success, else #CERTSVC_FAIL
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- */
-int certsvc_certificate_verify(
-       CertSvcCertificate certificate,
-       const CertSvcCertificate *trusted,
-       size_t trustedSize,
-       const CertSvcCertificate *untrusted,
-       size_t untrustedSize,
-       int *status);
-
-/**
- * Verify certificate with strict check of CA flag. Root CA certificate should
- * be stored in @a trusted.
- *
- * @param[in]  certificate    Certificate
- * @param[in]  trusted        Array with trusted certificates
- * @param[in]  trustedSize    Array size of @a trusted
- * @param[in]  untrusted      Array with untrusted certificates
- * @param[in]  untrustedSize  Array size of @a untrusted
- * @param[out] status         #CERTSVC_SUCCESS if success, else #CERTSVC_FAIL
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- */
-int certsvc_certificate_verify_with_caflag(
-       CertSvcCertificate certificate,
-       const CertSvcCertificate *trusted,
-       size_t trustedSize,
-       const CertSvcCertificate *untrusted,
-       size_t untrustedSize,
-       int *status);
-
-/**
- * Get visibility from Tizen app signing root certificate.
- *
- * @param[in]  certificate  Tizen app signing root certificate to get visibility
- * @param[out] visibility   Visibilitay level of @a certificate
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- *
- * @see #CertSvcVisibility
- */
-int certsvc_certificate_get_visibility(CertSvcCertificate certificate,
-                                                                          CertSvcVisibility *visibility);
-
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
-
diff --git a/vcore/cert-svc/cerror.h b/vcore/cert-svc/cerror.h
deleted file mode 100644 (file)
index 54c74f5..0000000
+++ /dev/null
@@ -1,51 +0,0 @@
-/**
- * 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        cerror.h
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief       This is part of C api for ValidationCore.
- */
-
-#ifndef _CERTSVC_CERROR_H_
-#define _CERTSVC_CERROR_H_
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#define CERTSVC_TRUE                 (1)
-#define CERTSVC_FALSE                (0)
-
-#define CERTSVC_SUCCESS              (1)
-#define CERTSVC_FAIL                 (0)    /* Openssl internal error. */
-#define CERTSVC_BAD_ALLOC            (-2)   /* Memmory allcation error. */
-#define CERTSVC_WRONG_ARGUMENT       (-4)   /* Function argumnet is wrong. */
-#define CERTSVC_INVALID_ALGORITHM    (-5)   /* Algorithm is not supported. */
-#define CERTSVC_INVALID_SIGNATURE    (-6)   /* Signature and message does not match. */
-#define CERTSVC_IO_ERROR             (-7)   /* Certificate file IO error. */
-#define CERTSVC_INVALID_PASSWORD     (-8)   /* Certificate container password mismatch. */
-#define CERTSVC_DUPLICATED_ALIAS     (-9)   /* User-provided alias is aleady taken. */
-#define CERTSVC_ALIAS_DOES_NOT_EXIST (-10)  /* Alias no exist in store. */
-#define CERTSVC_INVALID_STORE_TYPE   (-11)  /* User-provided invalid import type for storing in system/email/wifi/vpn store. */
-#define CERTSVC_INVALID_STATUS       (-12)  /* User-provided invalid status while stetting the status for the store system/email/wifi/vpn store. */
-#define CERTSVC_INVALID_CERTIFICATE  (-13)  /* Invalid certificate format or content */
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // _CERTSVC_CERROR_H_
diff --git a/vcore/cert-svc/cinstance.h b/vcore/cert-svc/cinstance.h
deleted file mode 100644 (file)
index 3ca455c..0000000
+++ /dev/null
@@ -1,74 +0,0 @@
-/**
- * Copyright (c) 2016 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        cinstance.h
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief       This is part of C api for ValidationCore.
- */
-#ifndef _CERTSVC_CINSTANCE_H_
-#define _CERTSVC_CINSTANCE_H_
-
-#include <cert-svc/cerror.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-typedef struct CertSvcInstance_t {
-       void *privatePtr;
-} CertSvcInstance;
-
-/**
- * Allocate internal data of CertSvc library and put it in the CertSvcInstance structure.
- * Initialize Openssl interanal structures.
- *
- * @param[out] instance  Pointer to CertSvcInstance
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- */
-int certsvc_instance_new(CertSvcInstance *instance);
-
-/**
- * Free all allocated data. All certificate identificator will be released and all
- * strings allocated by certsvc_certificate_get_string_field() will be released also.
- *
- * This fucntion does not release CertSvcInstnace itself!
- *
- * Plese note: It is safe to use this function after use certsvc_string_free().
- *
- * @param[in] instance  CertSvcInstance object
- */
-void certsvc_instance_reset(CertSvcInstance instance);
-
-/**
- * Free all allocated data. All certificate identificator will be released and all strings
- * allocated by certsvc_certificate_get_string_field() will be released also.
- *
- * This fucntion also release CertSvcInstnace!
- *
- * Please note: It is safe use this function after use certsvc_string_free().
- *
- * @param[in] instance CertSvcInstance object
- */
-void certsvc_instance_free(CertSvcInstance instance);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // _CERTSVC_CINSTANCE_H_
-
diff --git a/vcore/cert-svc/cpkcs12.h b/vcore/cert-svc/cpkcs12.h
deleted file mode 100644 (file)
index 101d2e3..0000000
+++ /dev/null
@@ -1,375 +0,0 @@
-/**
- * Copyright (c) 2016 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        cpkcs12.h
- * @author      Jacek Migacz (j.migacz@samsung.com)
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @brief       This is part of C api for PKCS#12/PFX storage routines.
- */
-#ifndef _CERTSVC_CPKCS12_H_
-#define _CERTSVC_CPKCS12_H_
-
-#include <cert-svc/cinstance.h>
-#include <cert-svc/cstring.h>
-#include <cert-svc/ccert.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * Check whenever PKCS#12 container is password protected.
- *
- * @param[in]  instance      CertSvcInstance object
- * @param[in]  filepath      File path to check
- * @param[out] has_password  #1 if password protectedm, else #0
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- *
- * @see certsvc_instance_new()
- * @see certsvc_instance_free()
- * @see certsvc_string_new()
- * @see certsvc_string_free()
- */
-int certsvc_pkcs12_has_password(CertSvcInstance instance,
-                                                               CertSvcString filepath,
-                                                               int *has_password);
-
-/**
- * Couter-routine for certsvc_pkcs12_private_key_dup.
- *
- * @param[in] buffer   Memory claimed by private key
- */
-void certsvc_pkcs12_private_key_free(char *buffer);
-
-/**
- * Load to memory of private key in cert-svc store with @a gname.
- *
- * @param[in]  instance   CertSvcInstance object
- * @param[in]  storeType  cert-svc store type to query
- * @param[in]  gname      Single certificate identifier. It has to be end user's
- *                        to extract private key
- * @param[out] buffer     Private key buffer which must be freed after use
- * @param[out] size       Size of the returned buffer. Zero when no key is found
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- *
- * @see certsvc_instance_new()
- * @see certsvc_instance_free()
- * @see certsvc_string_new()
- * @see certsvc_string_free()
- * @see #CertStoreType
- */
-int certsvc_pkcs12_private_key_dup_from_store(CertSvcInstance instance,
-               CertStoreType storeType,
-               CertSvcString gname,
-               char **buffer,
-               size_t *size);
-
-/**
- * Set the status for the specified certificate in cert-svc store.
- *
- * @param[in] instance     CertSvcInstance object
- * @param[in] storeType    cert-svc store type to query
- * @param[in] is_root_app  Should be #ENABLED if master application is changing the status,
- *                         else #DISABLED for other applications
- * @param[in] gname        Single certificate identifier
- * @param[in] status       Status of the certificate to set. [#ENABLED | #DISABLED]
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- *
- * @see certsvc_instance_new()
- * @see certsvc_instance_free()
- * @see certsvc_string_new()
- * @see certsvc_string_free()
- * @see #CertStoreType
- * @see #CertStatus
- */
-int certsvc_pkcs12_set_certificate_status_to_store(CertSvcInstance instance,
-               CertStoreType storeType,
-               int is_root_app,
-               CertSvcString gname,
-               CertStatus status);
-
-/**
- * Get the status for the specified certificate in cert-svc store.
- *
- * @param[in]  instance   CertSvcInstance object
- * @param[in]  storeType  cert-svc store type to query
- * @param[in[  gname      Single certificate identifier
- * @param[out] status     Status of the certificate. Enabled:1, Disabled:0, Fail:-1
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- *
- * @see certsvc_instance_new()
- * @see certsvc_instance_free()
- * @see certsvc_string_new()
- * @see certsvc_string_free()
- * @see #CertStroeType
- */
-int certsvc_pkcs12_get_certificate_status_from_store(CertSvcInstance instance,
-               CertStoreType storeType,
-               CertSvcString gname,
-               CertStatus *status);
-
-/**
- * Get the certificates in cert-svc store.
- *
- * @param[in]  instance     CertSvcInstance object
- * @param[in]  storeType    cert-svc store type to query
- * @param[in]  is_root_app  Should be #ENABLED if master application is changing the
- *                          status, else #DISABLED for other applications
- * @param[out] certList     cert list in store returned in linked list. Free by
- *                          certsvc_pkcs12_free_certificate_list_loaded_from_store()
- *                          after use
- * @param[out] length       length of output @a certList
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- *
- * @see certsvc_instance_new()
- * @see certsvc_instance_free()
- * @see #CertStoreType
- * @see #CertSvcStoreCertList
- */
-int certsvc_pkcs12_get_certificate_list_from_store(CertSvcInstance instance,
-               CertStoreType storeType,
-               int is_root_app,
-               CertSvcStoreCertList **certList,
-               size_t *length);
-
-/**
- * Get the end user certificates in cert-svc store.
- *
- * @param[in]  instance   CertSvcInstance object
- * @param[in]  storeType  cert-svc store type to query
- * @param[out] certList   cert list in store returned in linked list. Free by
- *                        certsvc_pkcs12_free_certificate_list_loaded_from_store() after use
- * @param[out] length     length of output @a certList
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- *
- * @see certsvc_instance_new()
- * @see certsvc_instance_free()
- * @see #CertStoreType
- * @see #CertSvcStoreCertList
- */
-int certsvc_pkcs12_get_end_user_certificate_list_from_store(CertSvcInstance instance,
-               CertStoreType storeType,
-               CertSvcStoreCertList **certList,
-               size_t *length);
-
-/**
- * Get the root/trusted certificates in cert-svc store.
- *
- * @param[in]  instance   CertSvcInstance object
- * @param[in]  storeType  cert-svc store type to query
- * @param[out] certList   cert list in store returned in linked list. Free by
- *                        certsvc_pkcs12_free_certificate_list_loaded_from_store() after use
- * @param[out] length     length of output @a certList
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- *
- * @see certsvc_instance_new()
- * @see certsvc_instance_free()
- * @see certsvc_pkcs12_free_certificate_list_loaded_from_store()
- * @see #CertStoreType
- * @see #CertSvcStoreCertList
- */
-int certsvc_pkcs12_get_root_certificate_list_from_store(CertSvcInstance instance,
-               CertStoreType storeType,
-               CertSvcStoreCertList **certList,
-               size_t *length);
-
-/**
- * Free all @a CertSvcStoreCertList in linked list of data structure.
- *
- * @param[in] instance  CertSvcInstance object
- * @param[in] certList  The structure which need to be freed
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- *
- * @see certsvc_instance_new()
- * @see certsvc_instance_free()
- * @see certsvc_pkcs12_get_certificate_list_from_store()
- * @see certsvc_pkcs12_get_end_user_certificate_list_from_store()
- * @see certsvc_pkcs12_get_root_certificate_list_from_store()
- * @see #CertSvcStoreCertList
- */
-int certsvc_pkcs12_free_certificate_list_loaded_from_store(CertSvcInstance instance,
-               CertSvcStoreCertList **certList);
-
-/**
- * Get the certificate with the gname provided from cert-svc store.
- *
- * @param[in]  instance     CertSvcInstance object
- * @param[in]  storeType    cert-svc store type to query
- * @param[in]  gname        Single certificate identifier
- * @param[out] certificate  output in @a CertSvcCertificate format
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- *
- * @see certsvc_instance_new()
- * @see certsvc_instance_free()
- * @see certsvc_certificate_free()
- * @see #CertStoreType
- */
-int certsvc_pkcs12_get_certificate_from_store(CertSvcInstance instance,
-               CertStoreType storeType,
-               const char *gname,
-               CertSvcCertificate *certificate);
-
-/**
- * Get the encoded certificate buffer with the gname provided from cert-svc store.
- *
- * @param[in]  instance   CertSvcInstance object
- * @param[in]  storeType  cert-svc store type to query
- * @param[in]  gname      Single certificate identifier
- * @param[out] buffer     The base64 encoded certificate which must be freed after
- *                        use
- * @param[out] size       Size of the buffer
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- *
- * @see certsvc_instance_new()
- * @see certsvc_instance_free()
- * @see certsvc_string_new()
- * @see certsvc_string_free()
- * @see #CertStoreType
- */
-int certsvc_pkcs12_get_certificate_info_from_store(CertSvcInstance instance,
-               CertStoreType storeType,
-               CertSvcString gname,
-               char **buffer,
-               size_t *size);
-
-/**
- * Import PKCS#12 bundle(with .pfx or .p12) or certificate(base64 form with .crt
- * or .pem suffix) from file to specified store. If password isn't needed, create
- * CertSvcString @a password with null input on certsvc_string_new(). Refer
- * certsvc_string_new() API description
- *
- * @param[in] instance   CertSvcInstance object
- * @param[in] storeType  cert-svc store type to query
- * @param[in] path       Path of the certificate which needs to be imported
- * @param[in] password   Password if the file to import is password-protected which can be
- *                       empty CertSvcString in case of not-password-protected
- * @param[in] alias      Primary key for certificate bundle identification (can't be empty)
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- *
- * @see certsvc_instance_new()
- * @see certsvc_instance_free()
- * @see certsvc_string_new()
- * @see certsvc_string_free()
- * @see #CertStoreType
- */
-int certsvc_pkcs12_import_from_file_to_store(CertSvcInstance instance,
-               CertStoreType storeType,
-               CertSvcString path,
-               CertSvcString password,
-               CertSvcString alias);
-
-/**
- * Delete the certificate with gname provided from cert-svc store.
- *
- * @param[in] instance   CertSvcInstance object
- * @param[in] storeType  cert-svc store type to query
- * @param[in] gname      Single certificate identifier
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- *
- * @see certsvc_instance_new()
- * @see certsvc_instance_free()
- * @see certsvc_string_new()
- * @see certsvc_string_free()
- * @see #CertStoreType
- */
-int certsvc_pkcs12_delete_certificate_from_store(CertSvcInstance instance,
-               CertStoreType storeType,
-               CertSvcString gname);
-
-/**
- * Check the uniqueness of the alias in cert-svc store.
- *
- * @param[in]  instance   CertSvcInstance object
- * @param[in]  storeType  cert-svc store type to query
- * @param[in]  alias      Certificates bundle identifier used when importing
- * @param[out] is_unique  #CERTSVC_TRUE if the alias is unique, else #CERTSVC_FALSE
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- *
- * @see certsvc_instance_new()
- * @see certsvc_instance_free()
- * @see certsvc_string_new()
- * @see certsvc_string_free()
- * @see #CertStoreType
- */
-int certsvc_pkcs12_check_alias_exists_in_store(CertSvcInstance instance,
-               CertStoreType storeType,
-               CertSvcString alias,
-               int *is_unique);
-
-/**
- * Get list of certificates from PKCS#12 bundle or single certificate which
- * is saved in cert-svc store with the alias.
- *
- * @param[in]  instance         CertSvcInstance object
- * @param[in]  alias            Certificates bundle identifier used when importing
- * @param[out] certificateList  List of certificates. Free by
- *                              certsvc_certificate_list_free() after use
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- *
- * @see certsvc_instance_new()
- * @see certsvc_instance_free()
- * @see certsvc_string_new()
- * @see certsvc_string_free()
- * @see certsvc_certificate_free()
- * @see certsvc_certificate_list_free()
- * @see #CertStoreType
- * @see #CertSvcStoreCertList
- */
-int certsvc_pkcs12_load_certificate_list_from_store(CertSvcInstance instance,
-               CertStoreType storeType,
-               CertSvcString alias,
-               CertSvcCertificateList *certificateList);
-
-/**
- * Get the alias name with the gname provided.
- *
- * @param[in]  instance  CertSvcInstance object
- * @param[in]  gname     Single certificate identifier which is associated with alias
- * @param[out] alias     Certificates bundle identifier used when importing which must
- *                       be freed after use
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- *
- * @see certsvc_instance_new()
- * @see certsvc_instance_free()
- * @see certsvc_string_new()
- * @see certsvc_string_free()
- * @see #CertStoreType
- */
-int certsvc_pkcs12_get_alias_name_for_certificate_in_store(CertSvcInstance instance,
-               CertStoreType storeType,
-               CertSvcString gname,
-               char **alias);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
diff --git a/vcore/cert-svc/cprimitives.h b/vcore/cert-svc/cprimitives.h
deleted file mode 100644 (file)
index 8feb9e9..0000000
+++ /dev/null
@@ -1,107 +0,0 @@
-/**
- * Copyright (c) 2016 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        cprimitives.h
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief       cert-svc capi primitives
- */
-#ifndef _CERTSVC_C_API_EXTENDED_H_
-#define _CERTSVC_C_API_EXTENDED_H_
-
-#include <openssl/evp.h>
-#include <openssl/x509.h>
-
-#include <cert-svc/ccert.h>
-#include <cert-svc/cstring.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-/**
- * Duplicate @a CertSvcCertificate structure to openssl X509 structure.
- * openssl X509 structure should be freed by certsvc_certificate_free_x509().
- * @a CertSvcInstance isn't free duplicated openssl X509 structure.
- *
- * @param[in]  certificate  Certificate
- * @param[out] x509         Duplicated @a certificate
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- *
- * @see certsvc_certificate_free_x509()
- */
-int certsvc_certificate_dup_x509(CertSvcCertificate certificate, X509 **x509);
-
-/**
- * Free openssl x509 structure duplicated by certsvc_certificate_dup_x509().
- *
- * @param[in] x509  openssl X509 structure to free
- *
- * @see certsvc_certificate_dup_x509()
- */
-void certsvc_certificate_free_x509(X509 *x509);
-
-/**
- * Duplicate pubkey in DER form from CertSvcCertificate.
- * Remarks: Free returned pubkey after use by free()
- *
- * @param[in]  certificate  Pointer to certificate.
- * @param[out] pubkey       Duplicated certificate in DER form which must be
- *                          freed after use
- * @param[out] len          Duplicated certificate length
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- */
-int certsvc_certificate_dup_pubkey_der(CertSvcCertificate certificate, unsigned char **pubkey,
-                                                                          size_t *len);
-
-/**
- * Get private key from cert-svc store in openssl EVP_PKEY structure.
- * openssl EVP_PKEY structure should be freed by certsvc_pkcs12_free_evp_pkey().
- * @a CertSvcInstance isn't free duplicated openssl EVP_PKEY structure.
- *
- * @param[in]  instance   CertSvcInstance object
- * @param[in]  storeType  cert-svc store type to query
- * @param[in]  gname      Single certificate identifier which is associated with
- *                        private key
- * @param[out] pkey       private key from storage which must be freed after use
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- *
- * @see certsvc_pkcs12_free_evp_pkey()
- */
-int certsvc_pkcs12_dup_evp_pkey_from_store(CertSvcInstance instance,
-               CertStoreType storeType,
-               CertSvcString gname,
-               EVP_PKEY **pkey);
-
-/**
- * Free openssl EVP_PKEY structure duplicated by certsvc_pkcs12_dup_ev_pkey()
- * or certsvc_pkcs12_dup_evp_pkey_from_store().
- *
- * @param[in] x509  openssl EVP_PKEY structure to free
- *
- * @see certsvc_pkcs12_dup_evp_pkey()
- * @see certsvc_pkcs12_dup_evp_pkey_from_store()
- */
-void certsvc_pkcs12_free_evp_pkey(EVP_PKEY *pkey);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
diff --git a/vcore/cert-svc/cstring.h b/vcore/cert-svc/cstring.h
deleted file mode 100644 (file)
index 4f3c37f..0000000
+++ /dev/null
@@ -1,151 +0,0 @@
-/**
- * Copyright (c) 2016 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        cstring.h
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief       This is part of C api for ValidationCore.
- */
-#ifndef _CERTSVC_CSTRING_H_
-#define _CERTSVC_CSTRING_H_
-
-#include <cert-svc/cinstance.h>
-#include <cert-svc/cstring.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-typedef struct CertSvcStringList_t {
-       size_t privateHandler;
-       CertSvcInstance privateInstance;
-} CertSvcStringList;
-
-typedef struct CertSvcString_t {
-       /*
-        * You are not allowed to use private fields of this structure. It is internal
-        * implementation of strings and it may change at any time without notice!
-        * To extract data use certsvc_string_to_cstring function!
-        */
-       char *privateHandler;
-       size_t privateLength;
-       CertSvcInstance privateInstance;
-} CertSvcString;
-
-/**
- * Create CertSvcString with input cstring and size. Newly allocated memory
- * is in same lifecycle with @a instance param unless freed by certsvc_string_free().
- * If empty string is needed, put NULL on @a input param and 0 on @a size param.
- *
- * @param[in]  instance  CertSvcInstance object
- * @param[in]  input     null-terminated string. Put #NULL if empty string needed
- * @param[in]  size      size of @a input to make. put #0 if empty string needed.
- *                       Can be smaller than length of @a input
- * @param[out] output    Output CertSvcString with newly allocated memory
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- *
- * @see certsvc_instance_new()
- * @see certsvc_instance_free()
- * @see certsvc_string_free()
- */
-int certsvc_string_new(
-       CertSvcInstance instance,
-       const char *input,
-       size_t size,
-       CertSvcString *output);
-
-/**
- * Create CertSvcString with @a input null-terminated string. @a output CertSvcString will
- * contain pointer to @a input so input could not be freed as long as ouput param is used.
- *
- * @param[in]  instance  CertSvcInstance object
- * @param[in]  input     null-terminated string. Put #NULL if empty string needed
- * @param[in]  size      size of @a input to make. put #0 if empty string needed.
- *                       Can be smaller than length of @a input
- * @param[out] output    Output CertSvcString based on @a input
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- *
- * @see certsvc_string_new()
- * @see certsvc_string_free()
- */
-int certsvc_string_not_managed(
-       CertSvcInstance instance,
-       const char *input,
-       size_t size,
-       CertSvcString *output);
-
-/**
- * Get CertSvcString from CertSvcStringList with newly allocated memory.
- * Output CertSvcString can be freed by certsvc_string_free() or reset/free instance
- * of CertSvcInstance which is used to get the CertSvcStringList.
- *
- * @param[in]  handler   Handler to string list
- * @param[in]  position  Index of CertSvcString to get in CertSvcStringList
- * @param[out] buffer    Output CertSvcString must be freed by
- *                       certsvc_string_free() after use
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- *
- * @see certsvc_instance_free()
- * @see certsvc_string_free()
- */
-int certsvc_string_list_get_one(CertSvcStringList hander,
-                                                               size_t position,
-                                                               CertSvcString *buffer);
-
-/**
- * Get list size of CertSvcStringList.
- *
- * @param[in]  handler  Handler to string list
- * @param[out] size     Number of elements on the list
- *
- * @return #CERTSVC_SUCCESS on success, otherwise a zero or negative error value
- */
-int certsvc_string_list_get_length(CertSvcStringList hander, size_t *size);
-
-/**
- * Free CertSvcString.
- *
- * @param[in]  string   CertSvcString to free
- */
-void certsvc_string_free(CertSvcString string);
-
-/**
- * Free CertSvcStringList.
- *
- * @param[in]  handler   Handler to string list
- */
-void certsvc_string_list_free(CertSvcStringList handler);
-
-/**
- * Convert CertSvcString into null-terminated C string. Please note that this pointer
- * is valid as long as CertSvcString is valid.
- *
- * @param[in]  string  CertSvcString
- * @param[out] buffer  null-terminated c string
- * @param[out] len     Length of string
- */
-void certsvc_string_to_cstring(CertSvcString string, const char **buffer, size_t *len);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
-
diff --git a/vcore/dpl/core/include/dpl/assert.h b/vcore/dpl/core/include/dpl/assert.h
deleted file mode 100644 (file)
index 14ef0b7..0000000
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (c) 2011 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        assert.h
- * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @version     1.0
- * @brief       This file is the implementation file of assert
- */
-#ifndef DPL_ASSERT_H
-#define DPL_ASSERT_H
-
-namespace VcoreDPL {
-// Assertion handler procedure
-// Do not call directly
-// Always use Assert macro
-void AssertProc(const char *condition,
-                               const char *file,
-                               int line,
-                               const char *function) __attribute__((__noreturn__));
-} // namespace VcoreDPL
-
-#define Assert(Condition)                                               \
-       do {                                                                    \
-               if (!(Condition)) {                                                 \
-                       VcoreDPL::AssertProc(#Condition, __FILE__, __LINE__, __FUNCTION__);  \
-               }                                                                   \
-       } while (0)
-
-#define AssertMsg(Condition, Msg)                                         \
-       do {                                                                  \
-               if (!(Condition)) {                                               \
-                       VcoreDPL::AssertProc(                                              \
-                                       (std::string(std::string(#Condition)+" ") + Msg).c_str(), \
-                                       __FILE__, __LINE__, __FUNCTION__);                        \
-               }                                                                 \
-       } while (0)
-
-#endif // DPL_ASSERT_H
diff --git a/vcore/dpl/core/include/dpl/colors.h b/vcore/dpl/core/include/dpl/colors.h
deleted file mode 100644 (file)
index 5d8e91c..0000000
+++ /dev/null
@@ -1,73 +0,0 @@
-/*
- * Copyright (c) 2011 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        colors.h
- * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
- * @version     1.0
- * @brief       Some constants with definition of colors for Console
- *              and html output
- */
-
-#ifndef DPL_COLORS_H
-#define DPL_COLORS_H
-
-namespace VcoreDPL {
-namespace Colors {
-namespace Text {
-extern const char *BOLD_GREEN_BEGIN;
-extern const char *BOLD_GREEN_END;
-extern const char *PURPLE_BEGIN;
-extern const char *PURPLE_END;
-extern const char *RED_BEGIN;
-extern const char *RED_END;
-extern const char *GREEN_BEGIN;
-extern const char *GREEN_END;
-extern const char *CYAN_BEGIN;
-extern const char *CYAN_END;
-extern const char *BOLD_RED_BEGIN;
-extern const char *BOLD_RED_END;
-extern const char *BOLD_YELLOW_BEGIN;
-extern const char *BOLD_YELLOW_END;
-extern const char *BOLD_GOLD_BEGIN;
-extern const char *BOLD_GOLD_END;
-extern const char *BOLD_WHITE_BEGIN;
-extern const char *BOLD_WHITE_END;
-} //namespace Text
-
-namespace Html {
-extern const char *BOLD_GREEN_BEGIN;
-extern const char *BOLD_GREEN_END;
-extern const char *PURPLE_BEGIN;
-extern const char *PURPLE_END;
-extern const char *RED_BEGIN;
-extern const char *RED_END;
-extern const char *GREEN_BEGIN;
-extern const char *GREEN_END;
-extern const char *CYAN_BEGIN;
-extern const char *CYAN_END;
-extern const char *BOLD_RED_BEGIN;
-extern const char *BOLD_RED_END;
-extern const char *BOLD_YELLOW_BEGIN;
-extern const char *BOLD_YELLOW_END;
-extern const char *BOLD_GOLD_BEGIN;
-extern const char *BOLD_GOLD_END;
-extern const char *BOLD_WHITE_BEGIN;
-extern const char *BOLD_WHITE_END;
-} //namespace Html
-} //namespace Colors
-} //namespace VcoreDPL
-
-#endif /* DPL_COLORS_H */
diff --git a/vcore/dpl/core/include/dpl/exception.h b/vcore/dpl/core/include/dpl/exception.h
deleted file mode 100644 (file)
index fba822a..0000000
+++ /dev/null
@@ -1,382 +0,0 @@
-/*
- * Copyright (c) 2011 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  Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @version 1.0
- * @brief   Header file for base exception
- */
-#ifndef VcoreDPL_EXCEPTION_H
-#define VcoreDPL_EXCEPTION_H
-
-#include <string>
-#include <cstring>
-#include <cstdio>
-#include <exception>
-#include <cstdlib>
-#include <sstream>
-
-namespace VcoreDPL {
-void LogUnhandledException(const std::string &str);
-void LogUnhandledException(const std::string &str,
-                                                  const char *filename,
-                                                  int line,
-                                                  const char *function);
-}
-
-namespace VcoreDPL {
-class Exception {
-private:
-       static unsigned int m_exceptionCount;
-       static Exception *m_lastException;
-       static void (*m_terminateHandler)();
-
-       static void AddRef(Exception *exception)
-       {
-               if (!m_exceptionCount) {
-                       m_terminateHandler = std::set_terminate(&TerminateHandler);
-               }
-
-               ++m_exceptionCount;
-               m_lastException = exception;
-       }
-
-       static void UnRef(Exception *e)
-       {
-               if (m_lastException == e) {
-                       m_lastException = NULL;
-               }
-
-               --m_exceptionCount;
-
-               if (!m_exceptionCount) {
-                       std::set_terminate(m_terminateHandler);
-                       m_terminateHandler = NULL;
-               }
-       }
-
-       static void TerminateHandler()
-       {
-               if (m_lastException != NULL) {
-                       DisplayKnownException(*m_lastException);
-                       abort();
-               } else {
-                       DisplayUnknownException();
-                       abort();
-               }
-       }
-
-       Exception *m_reason;
-       std::string m_path;
-       std::string m_function;
-       int m_line;
-
-protected:
-       std::string m_message;
-       std::string m_className;
-
-public:
-       static std::string KnownExceptionToString(const Exception &e)
-       {
-               std::ostringstream message;
-               message <<
-                               "\033[1;5;31m\n=== Unhandled DPL exception occurred ===\033[m\n\n";
-               message << "\033[1;33mException trace:\033[m\n\n";
-               message << e.DumpToString();
-               message << "\033[1;31m\n=== Will now abort ===\033[m\n";
-               return message.str();
-       }
-
-       static std::string UnknownExceptionToString()
-       {
-               std::ostringstream message;
-               message <<
-                               "\033[1;5;31m\n=== Unhandled non-DPL exception occurred ===\033[m\n\n";
-               message << "\033[1;31m\n=== Will now abort ===\033[m\n";
-               return message.str();
-       }
-
-       static void DisplayKnownException(const Exception &e)
-       {
-               LogUnhandledException(KnownExceptionToString(e).c_str());
-       }
-
-       static void DisplayUnknownException()
-       {
-               LogUnhandledException(UnknownExceptionToString().c_str());
-       }
-
-       Exception(const Exception &other)
-       {
-               // Deep copy
-               if (other.m_reason != NULL) {
-                       m_reason = new Exception(*other.m_reason);
-               } else {
-                       m_reason = NULL;
-               }
-
-               m_message = other.m_message;
-               m_path = other.m_path;
-               m_function = other.m_function;
-               m_line = other.m_line;
-               m_className = other.m_className;
-               AddRef(this);
-       }
-
-       const Exception &operator =(const Exception &other)
-       {
-               if (this == &other) {
-                       return *this;
-               }
-
-               // Deep copy
-               if (other.m_reason != NULL) {
-                       m_reason = new Exception(*other.m_reason);
-               } else {
-                       m_reason = NULL;
-               }
-
-               m_message = other.m_message;
-               m_path = other.m_path;
-               m_function = other.m_function;
-               m_line = other.m_line;
-               m_className = other.m_className;
-               AddRef(this);
-               return *this;
-       }
-
-       Exception(const char *path,
-                         const char *function,
-                         int line,
-                         const std::string &message) :
-               m_reason(NULL),
-               m_path(path),
-               m_function(function),
-               m_line(line),
-               m_message(message)
-       {
-               AddRef(this);
-       }
-
-       Exception(const char *path,
-                         const char *function,
-                         int line,
-                         const Exception &reason,
-                         const std::string &message) :
-               m_reason(new Exception(reason)),
-               m_path(path),
-               m_function(function),
-               m_line(line),
-               m_message(message)
-       {
-               AddRef(this);
-       }
-
-       virtual ~Exception() throw()
-       {
-               if (m_reason != NULL) {
-                       delete m_reason;
-                       m_reason = NULL;
-               }
-
-               UnRef(this);
-       }
-
-       void Dump() const
-       {
-               // Show reason first
-               if (m_reason != NULL) {
-                       m_reason->Dump();
-               }
-
-               // Afterward, dump exception
-               const char *file = strchr(m_path.c_str(), '/');
-
-               if (file == NULL) {
-                       file = m_path.c_str();
-               } else {
-                       ++file;
-               }
-
-               printf("\033[0;36m[%s:%i]\033[m %s() \033[4;35m%s\033[m: %s\033[m\n",
-                          file, m_line,
-                          m_function.c_str(),
-                          m_className.c_str(),
-                          m_message.empty() ? "<EMPTY>" : m_message.c_str());
-       }
-
-       std::string DumpToString() const
-       {
-               std::string ret;
-
-               if (m_reason != NULL) {
-                       ret = m_reason->DumpToString();
-               }
-
-               const char *file = strchr(m_path.c_str(), '/');
-
-               if (file == NULL) {
-                       file = m_path.c_str();
-               } else {
-                       ++file;
-               }
-
-               char buf[1024];
-               snprintf(buf,
-                                sizeof(buf),
-                                "\033[0;36m[%s:%i]\033[m %s() \033[4;35m%s\033[m: %s\033[m\n",
-                                file,
-                                m_line,
-                                m_function.c_str(),
-                                m_className.c_str(),
-                                m_message.empty() ? "<EMPTY>" : m_message.c_str());
-               buf[sizeof(buf) - 1] = '\n';
-               ret += buf;
-               return ret;
-       }
-
-       Exception *GetReason() const
-       {
-               return m_reason;
-       }
-
-       std::string GetPath() const
-       {
-               return m_path;
-       }
-
-       std::string GetFunction() const
-       {
-               return m_function;
-       }
-
-       int GetLine() const
-       {
-               return m_line;
-       }
-
-       std::string GetMessage() const
-       {
-               return m_message;
-       }
-
-       std::string GetClassName() const
-       {
-               return m_className;
-       }
-};
-} // namespace VcoreDPL
-
-#define Try try
-
-#define Throw(ClassName) \
-       throw ClassName(__FILE__, __FUNCTION__, __LINE__)
-
-#define ThrowMsg(ClassName, Message)                                                 \
-       do                                                                               \
-       {                                                                                \
-               std::ostringstream dplLoggingStream;                                         \
-               dplLoggingStream << Message;                                                 \
-               throw ClassName(__FILE__, __FUNCTION__, __LINE__, dplLoggingStream.str());   \
-       } while (0)
-
-#define ReThrow(ClassName) \
-       throw ClassName(__FILE__, __FUNCTION__, __LINE__, _rethrown_exception)
-
-#define ReThrowMsg(ClassName, Message)                                               \
-       throw ClassName(__FILE__,                                                        \
-                                       __FUNCTION__,                                                    \
-                                       __LINE__,                                                        \
-                                       _rethrown_exception,                                             \
-                                       Message)
-
-#define Catch(ClassName)                                                             \
-       catch (const ClassName &_rethrown_exception)
-
-#define DECLARE_EXCEPTION_TYPE(BaseClass, Class)                                     \
-       class Class : public BaseClass {                                                 \
-       public:                                                                          \
-               Class(const char *path,                                                      \
-                         const char *function,                                                  \
-                         int line,                                                              \
-                         const std::string & message = std::string())                           \
-                       : BaseClass(path, function, line, message) {                               \
-                       \
-                       BaseClass::m_className = #Class;                                         \
-               }                                                                            \
-               \
-               Class(const char *path,                                                      \
-                         const char *function,                                                  \
-                         int line,                                                              \
-                         const VcoreDPL::Exception & reason,                                    \
-                         const std::string & message = std::string())                           \
-                       : BaseClass(path, function, line, reason, message) {                       \
-                       BaseClass::m_className = #Class;                                         \
-               }                                                                            \
-       };
-
-#define UNHANDLED_EXCEPTION_HANDLER_BEGIN try
-
-#define UNHANDLED_EXCEPTION_HANDLER_END                                              \
-       catch (const VcoreDPL::Exception &exception)                                     \
-       {                                                                                \
-               std::ostringstream msg;                                                      \
-               msg << VcoreDPL::Exception::KnownExceptionToString(exception);               \
-               VcoreDPL::LogUnhandledException(msg.str(),                                   \
-                                                                               __FILE__,                                    \
-                                                                               __LINE__,                                    \
-                                                                               __FUNCTION__);                                \
-               abort();                                                                     \
-       }                                                                                \
-       catch (std::exception& e)                                                        \
-       {                                                                                \
-               std::ostringstream msg;                                                      \
-               msg << e.what();                                                             \
-               msg << "\n";                                                                 \
-               msg << VcoreDPL::Exception::UnknownExceptionToString();                      \
-               VcoreDPL::LogUnhandledException(msg.str(),                                   \
-                                                                               __FILE__,                                    \
-                                                                               __LINE__,                                    \
-                                                                               __FUNCTION__);                               \
-               abort();                                                                     \
-       }                                                                                \
-       catch (...)                                                                      \
-       {                                                                                \
-               std::ostringstream msg;                                                      \
-               msg << VcoreDPL::Exception::UnknownExceptionToString();                      \
-               VcoreDPL::LogUnhandledException(msg.str(),                                   \
-                                                                               __FILE__,                                    \
-                                                                               __LINE__,                                    \
-                                                                               __FUNCTION__);                               \
-               abort();                                                                     \
-       }
-
-namespace VcoreDPL {
-namespace CommonException {
-/**
- * Internal exception definitions
- *
- * These should normally not happen.
- * Usually, exception trace with internal error includes
- * important messages.
- */
-DECLARE_EXCEPTION_TYPE(Exception, InternalError) ///< Unexpected error from
-// underlying libraries or
-// kernel
-}
-}
-
-#endif // VcoreDPL_EXCEPTION_H
diff --git a/vcore/dpl/core/include/dpl/singleton.h b/vcore/dpl/core/include/dpl/singleton.h
deleted file mode 100644 (file)
index bec534a..0000000
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (c) 2011 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        singleton.h
- * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @version     1.0
- * @brief       This file is the implementation file of singleton
- */
-#ifndef DPL_SINGLETON_H
-#define DPL_SINGLETON_H
-
-namespace VcoreDPL {
-template<typename Class>
-class Singleton :
-       private Class {
-       //
-       // Note:
-       //
-       // To remove posibility of instantiating directly Class,
-       // make Class' default constructor protected
-       //
-
-private:
-       Singleton()
-       {}
-
-       static Singleton &InternalInstance();
-
-public:
-       virtual ~Singleton()
-       {}
-
-       static Class &Instance();
-};
-} // namespace VcoreDPL
-
-#endif // DPL_SINGLETON_H
diff --git a/vcore/dpl/core/include/dpl/singleton_impl.h b/vcore/dpl/core/include/dpl/singleton_impl.h
deleted file mode 100644 (file)
index 502d926..0000000
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * Copyright (c) 2011 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        singleton_impl.h
- * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
- * @version     1.0
- * @brief       This file is the implementation file of singleton
- */
-#ifndef DPL_SINGLETON_IMPL_H
-#define DPL_SINGLETON_IMPL_H
-
-#include <dpl/singleton.h>
-
-/*
- * WARNING!
- *
- * If some singleton's implementation uses another singletons implementation,
- * those templates make the second singleton a dubleton. Be warned. Try to use
- * singleton_safe_impl.h if possible.
- */
-
-namespace VcoreDPL {
-template<typename Class>
-Singleton<Class> &Singleton<Class>::InternalInstance()
-{
-       static Singleton<Class> instance;
-       return instance;
-}
-
-template<typename Class>
-Class &Singleton<Class>::Instance()
-{
-       Singleton<Class> &instance = Singleton<Class>::InternalInstance();
-       return instance;
-}
-} // namespace VcoreDPL
-
-#define IMPLEMENT_SINGLETON(Type)                                                     \
-       template VcoreDPL::Singleton<Type>&VcoreDPL::Singleton<Type>::InternalInstance(); \
-       template Type & VcoreDPL::Singleton<Type>::Instance();                            \
-
-#endif // DPL_SINGLETON_IMPL_H
diff --git a/vcore/dpl/core/src/assert.cpp b/vcore/dpl/core/src/assert.cpp
deleted file mode 100644 (file)
index 6e02192..0000000
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright (c) 2011 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        assert.cpp
- * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @version     1.0
- * @brief       This file is the implementation file of assert
- */
-#include <cstdlib>
-#include <sstream>
-#include <stddef.h>
-#include <dpl/assert.h>
-#include <dpl/exception.h>
-#include <dpl/log/log.h>
-
-namespace VcoreDPL {
-void AssertProc(const char *condition,
-                               const char *file,
-                               int line,
-                               const char *function)
-{
-       // Try to log failed assertion to log system
-       Try {
-               LogError("########################################################################");
-               LogError("###                      DPL assertion failed!                       ###");
-               LogError("########################################################################");
-               LogError("### Condition: " << condition);
-               LogError("### File: " << file);
-               LogError("### Line: " << line);
-               LogError("### Function: " << function);
-               LogError("########################################################################");
-       } catch (Exception) {
-               // Just ignore possible double errors
-       }
-
-       // Fail with c-library abort
-       abort();
-}
-} // namespace VcoreDPL
diff --git a/vcore/dpl/core/src/colors.cpp b/vcore/dpl/core/src/colors.cpp
deleted file mode 100644 (file)
index 2ec2749..0000000
+++ /dev/null
@@ -1,70 +0,0 @@
-/*
- * Copyright (c) 2011 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        colors.cpp
- * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
- * @version     1.0
- * @brief       Some constants with definition of colors for Console
- *              and html output
- */
-#include <stddef.h>
-#include <dpl/colors.h>
-
-namespace VcoreDPL {
-namespace Colors {
-namespace Text {
-const char *BOLD_GREEN_BEGIN = "\033[1;32m";
-const char *BOLD_GREEN_END = "\033[m";
-const char *RED_BEGIN = "\033[0;31m";
-const char *RED_END = "\033[m";
-const char *PURPLE_BEGIN = "\033[0;35m";
-const char *PURPLE_END = "\033[m";
-const char *GREEN_BEGIN = "\033[0;32m";
-const char *GREEN_END = "\033[m";
-const char *CYAN_BEGIN = "\033[0;36m";
-const char *CYAN_END = "\033[m";
-const char *BOLD_RED_BEGIN = "\033[1;31m";
-const char *BOLD_RED_END = "\033[m";
-const char *BOLD_YELLOW_BEGIN = "\033[1;33m";
-const char *BOLD_YELLOW_END = "\033[m";
-const char *BOLD_GOLD_BEGIN = "\033[0;33m";
-const char *BOLD_GOLD_END = "\033[m";
-const char *BOLD_WHITE_BEGIN = "\033[1;37m";
-const char *BOLD_WHITE_END = "\033[m";
-} //namespace Text
-
-namespace Html {
-const char *BOLD_GREEN_BEGIN = "<font color=\"green\"><b>";
-const char *BOLD_GREEN_END = "</b></font>";
-const char *PURPLE_BEGIN = "<font color=\"purple\"><b>";
-const char *PURPLE_END = "</b></font>";
-const char *RED_BEGIN = "<font color=\"red\"><b>";
-const char *RED_END = "</b></font>";
-const char *GREEN_BEGIN = "<font color=\"green\">";
-const char *GREEN_END = "</font>";
-const char *CYAN_BEGIN = "<font color=\"cyan\">";
-const char *CYAN_END = "</font>";
-const char *BOLD_RED_BEGIN = "<font color=\"red\"><b>";
-const char *BOLD_RED_END = "</b></font>";
-const char *BOLD_YELLOW_BEGIN = "<font color=\"yellow\"><b>";
-const char *BOLD_YELLOW_END = "</b></font>";
-const char *BOLD_GOLD_BEGIN = "<font color=\"gold\"><b>";
-const char *BOLD_GOLD_END = "</b></font>";
-const char *BOLD_WHITE_BEGIN = "<font color=\"white\"><b>";
-const char *BOLD_WHITE_END = "</b></font>";
-} //namespace Html
-} //namespace Colors
-} //namespace VcoreDPL
diff --git a/vcore/dpl/core/src/exception.cpp b/vcore/dpl/core/src/exception.cpp
deleted file mode 100644 (file)
index 7e9faa2..0000000
+++ /dev/null
@@ -1,47 +0,0 @@
-/*
- * Copyright (c) 2011 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      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @version     1.0
- * @brief       This file is the implementation of exception system
- */
-#include <stddef.h>
-#include <dpl/exception.h>
-#include <dpl/log/log.h>
-#include <cstdio>
-
-namespace VcoreDPL {
-Exception *Exception::m_lastException = NULL;
-unsigned int Exception::m_exceptionCount = 0;
-void (*Exception::m_terminateHandler)() = NULL;
-
-void LogUnhandledException(const std::string &str)
-{
-       LogDebug("" << str);
-}
-
-void LogUnhandledException(const std::string &str,
-                                                  const char *filename,
-                                                  int line,
-                                                  const char *function)
-{
-       LogError("Exception occured on file[" << filename
-                        << "] line[" << line
-                        << "] function[" << function
-                        << "] msg[" << str << "]");
-}
-} // namespace VcoreDPL
diff --git a/vcore/dpl/core/src/singleton.cpp b/vcore/dpl/core/src/singleton.cpp
deleted file mode 100644 (file)
index 54abd52..0000000
+++ /dev/null
@@ -1,31 +0,0 @@
-/*
- * Copyright (c) 2011 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        singleton.cpp
- * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @version     1.0
- * @brief       This file is the implementation file of singleton
- */
-#include <stddef.h>
-#include <dpl/singleton.h>
-
-//
-// Note:
-//
-// The file here is left blank to enable precompilation
-// of templates in corresponding header file.
-// Do not remove this file.
-//
diff --git a/vcore/dpl/log/include/dpl/log/abstract_log_provider.h b/vcore/dpl/log/include/dpl/log/abstract_log_provider.h
deleted file mode 100644 (file)
index b2bf970..0000000
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- * Copyright (c) 2011 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        abstract_log_provider.h
- * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @version     1.0
- * @brief       This file is the implementation file of abstract log provider
- */
-#ifndef DPL_ABSTRACT_LOG_PROVIDER_H
-#define DPL_ABSTRACT_LOG_PROVIDER_H
-
-namespace VcoreDPL {
-namespace Log {
-class AbstractLogProvider {
-public:
-       enum class LogLevel {
-               None,
-               Error,
-               Warning,
-               Info,
-               Debug,
-               Pedantic
-       };
-
-       virtual ~AbstractLogProvider() {}
-
-       virtual void SetTag(const char *tag);
-
-       virtual void Log(LogLevel level,
-                                        const char *message,
-                                        const char *fileName,
-                                        int line,
-                                        const char *function) const = 0;
-
-protected:
-       static const char *LocateSourceFileName(const char *filename);
-};
-}
-} // namespace VcoreDPL
-
-#endif // DPL_ABSTRACT_LOG_PROVIDER_H
diff --git a/vcore/dpl/log/include/dpl/log/dlog_log_provider.h b/vcore/dpl/log/include/dpl/log/dlog_log_provider.h
deleted file mode 100644 (file)
index e1e5be2..0000000
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * Copyright (c) 2011 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        dlog_log_provider.h
- * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @version     1.0
- * @brief       This file is the implementation file of DLOG log provider
- */
-#ifndef DPL_DLOG_LOG_PROVIDER_H
-#define DPL_DLOG_LOG_PROVIDER_H
-
-#include <dpl/log/abstract_log_provider.h>
-#include <memory>
-
-namespace VcoreDPL {
-namespace Log {
-class DLOGLogProvider : public AbstractLogProvider {
-public:
-       DLOGLogProvider();
-       virtual ~DLOGLogProvider();
-
-       virtual void Log(AbstractLogProvider::LogLevel level,
-                                        const char *message,
-                                        const char *fileName,
-                                        int line,
-                                        const char *function) const;
-
-       // Set global Tag according to DLOG
-       virtual void SetTag(const char *tag);
-
-private:
-       std::unique_ptr<char[]> m_tag;
-};
-}
-} // namespace VcoreDPL
-
-#endif // DPL_DLOG_LOG_PROVIDER_H
diff --git a/vcore/dpl/log/include/dpl/log/journal_log_provider.h b/vcore/dpl/log/include/dpl/log/journal_log_provider.h
deleted file mode 100644 (file)
index 3c2cc5a..0000000
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2014 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       journal_log_provider.h
- * @author     Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
- * @version    1.0
- */
-
-#pragma once
-
-#include <dpl/log/abstract_log_provider.h>
-
-namespace VcoreDPL {
-namespace Log {
-
-class JournalLogProvider: public AbstractLogProvider {
-public:
-       JournalLogProvider();
-       virtual ~JournalLogProvider();
-
-       virtual void Log(AbstractLogProvider::LogLevel level,
-                                        const char *message,
-                                        const char *fileName,
-                                        int line,
-                                        const char *function) const;
-};
-
-} /* namespace Log */
-} /* namespace VcoreDPL */
diff --git a/vcore/dpl/log/include/dpl/log/log.h b/vcore/dpl/log/include/dpl/log/log.h
deleted file mode 100644 (file)
index 07cac3d..0000000
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * Copyright (c) 2011 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        log.h
- * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @version     1.0
- * @brief       This file is the implementation file of log system
- */
-#ifndef DPL_LOG_H
-#define DPL_LOG_H
-
-#include <sstream>
-#include <list>
-#include <unordered_map>
-#include <string>
-
-#include <dpl/singleton.h>
-
-#include <dpl/log/abstract_log_provider.h>
-
-namespace VcoreDPL {
-namespace Log {
-/**
- * DPL log system
- *
- * To switch logs into old style, export
- * DPL_USE_OLD_STYLE_LOGS before application start
- */
-class LogSystem {
-public:
-       LogSystem();
-       virtual ~LogSystem();
-
-       LogSystem(const LogSystem &) = delete;
-       LogSystem &operator=(const LogSystem &) = delete;
-       LogSystem(LogSystem &&) = delete;
-       LogSystem &operator=(LogSystem &&) = delete;
-
-       AbstractLogProvider::LogLevel GetLogLevel() const
-       {
-               return m_level;
-       }
-
-       void Log(AbstractLogProvider::LogLevel level,
-                        const char *message,
-                        const char *filename,
-                        int line,
-                        const char *function) const;
-
-
-       /**
-        * Set default's DLOG provider Tag
-        */
-       void SetTag(const char *tag);
-
-       /**
-        * Add abstract provider to providers list
-        *
-        * @notice Ownership is transfered to LogSystem and deleted upon exit
-        */
-       void AddProvider(AbstractLogProvider *provider);
-
-       /**
-        * Remove abstract provider from providers list
-        */
-       void RemoveProvider(AbstractLogProvider *provider);
-
-       /**
-        * Selects given provider by name (overwrites environment setting)
-        *
-        * Throws std::out_of_range exception if not found.
-        */
-       void SelectProvider(const std::string &name);
-
-       /**
-        * Sets log level (overwrites environment settings)
-        */
-       void SetLogLevel(const char *level);
-
-private:
-       void RemoveProviders();
-
-       typedef std::list<AbstractLogProvider *> AbstractLogProviderPtrList;
-       AbstractLogProviderPtrList m_providers;
-       AbstractLogProvider::LogLevel m_level;
-
-       typedef AbstractLogProvider *(*ProviderFn)();
-       /*
-        * It cannot be global as it is used in library constructor and we can't be sure which
-        * constructor is called first: library's or new_provider's.
-        */
-       std::unordered_map<std::string, ProviderFn> m_providerCtor;
-};
-
-/*
- * Replacement low overhead null logging class
- */
-class NullStream {
-public:
-       NullStream() {}
-
-       template <typename T>
-       NullStream &operator<<(const T &)
-       {
-               return *this;
-       }
-};
-
-/**
- * Log system singleton
- */
-typedef Singleton<LogSystem> LogSystemSingleton;
-}
-} // namespace VcoreDPL
-
-
-/* avoid warnings about unused variables */
-#define DPL_MACRO_DUMMY_LOGGING(message, level)                                 \
-       do {                                                                        \
-               VcoreDPL::Log::NullStream ns;                                           \
-               ns << message;                                                          \
-       } while (0)
-
-#define DPL_MACRO_FOR_LOGGING(message, level)                                   \
-       do                                                                              \
-       {                                                                               \
-               if (level > VcoreDPL::Log::AbstractLogProvider::LogLevel::None &&           \
-                               VcoreDPL::Log::LogSystemSingleton::Instance().GetLogLevel() >= level)   \
-               {                                                                           \
-                       std::ostringstream platformLog;                                         \
-                       platformLog << message;                                                 \
-                       VcoreDPL::Log::LogSystemSingleton::Instance().Log(level,                \
-                                       platformLog.str().c_str(), \
-                                       __FILE__,                  \
-                                       __LINE__,                  \
-                                       __FUNCTION__);             \
-               }                                                                           \
-       } while (0)
-
-
-#ifdef TIZEN_ENGINEER_MODE
-#define LogDebug(message)    DPL_MACRO_FOR_LOGGING(message, VcoreDPL::Log::AbstractLogProvider::LogLevel::Debug)
-#define LogPedantic(message) DPL_MACRO_FOR_LOGGING(message, VcoreDPL::Log::AbstractLogProvider::LogLevel::Pedantic)
-#else
-#define LogDebug(message)    DPL_MACRO_DUMMY_LOGGING(message, VcoreDPL::Log::AbstractLogProvider::LogLevel::Debug)
-#define LogPedantic(message) DPL_MACRO_DUMMY_LOGGING(message, VcoreDPL::Log::AbstractLogProvider::LogLevel::Pedantic)
-#endif // TIZEN_ENGINEER_MODE
-
-#define LogInfo(message)    DPL_MACRO_FOR_LOGGING(message, VcoreDPL::Log::AbstractLogProvider::LogLevel::Info)
-#define LogWarning(message) DPL_MACRO_FOR_LOGGING(message, VcoreDPL::Log::AbstractLogProvider::LogLevel::Warning)
-#define LogError(message)   DPL_MACRO_FOR_LOGGING(message, VcoreDPL::Log::AbstractLogProvider::LogLevel::Error)
-
-#endif // DPL_LOG_H
diff --git a/vcore/dpl/log/include/dpl/log/old_style_log_provider.h b/vcore/dpl/log/include/dpl/log/old_style_log_provider.h
deleted file mode 100644 (file)
index e26da28..0000000
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * Copyright (c) 2011 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        old_style_log_provider.h
- * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @version     1.0
- * @brief       This file is the implementation file of old style log provider
- */
-#ifndef DPL_OLD_STYLE_LOG_PROVIDER_H
-#define DPL_OLD_STYLE_LOG_PROVIDER_H
-
-#include <dpl/log/abstract_log_provider.h>
-
-namespace VcoreDPL {
-namespace Log {
-class OldStyleLogProvider : public AbstractLogProvider {
-public:
-       OldStyleLogProvider();
-       virtual ~OldStyleLogProvider() {}
-
-       virtual void Log(AbstractLogProvider::LogLevel level,
-                                        const char *message,
-                                        const char *fileName,
-                                        int line,
-                                        const char *function) const;
-};
-}
-} // namespace VcoreDPL
-
-#endif // DPL_OLD_STYLE_LOG_PROVIDER_H
diff --git a/vcore/dpl/log/src/abstract_log_provider.cpp b/vcore/dpl/log/src/abstract_log_provider.cpp
deleted file mode 100644 (file)
index 21fd2f1..0000000
+++ /dev/null
@@ -1,37 +0,0 @@
-/*
- * Copyright (c) 2011 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        abstract_log_provider.cpp
- * @author      Pawel Sikorski (p.sikorski@samsung.com)
- * @version     1.0
- * @brief       This file is the implementation file of abstract log provider
- */
-#include <stddef.h>
-#include <dpl/log/abstract_log_provider.h>
-#include <cstring>
-
-namespace VcoreDPL {
-namespace Log {
-
-void AbstractLogProvider::SetTag(const char *) {}
-
-const char *AbstractLogProvider::LocateSourceFileName(const char *filename)
-{
-       const char *ptr = strrchr(filename, '/');
-       return ptr != NULL ? ptr + 1 : filename;
-}
-}
-}
diff --git a/vcore/dpl/log/src/dlog_log_provider.cpp b/vcore/dpl/log/src/dlog_log_provider.cpp
deleted file mode 100644 (file)
index 4f514b2..0000000
+++ /dev/null
@@ -1,108 +0,0 @@
-/*
- * Copyright (c) 2011 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        dlog_log_provider.cpp
- * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @version     1.0
- * @brief       This file is the implementation file of DLOG log provider
- */
-#include <stddef.h>
-#include <cstring>
-#include <sstream>
-#include <map>
-#include <stdexcept>
-
-#include <dlog.h>
-
-#include <dpl/log/dlog_log_provider.h>
-
-namespace VcoreDPL {
-namespace Log {
-
-namespace {
-typedef void (*dlogMacro)(const char *, const char *);
-
-void error(const char *tag, const char *msg)
-{
-       SLOG(LOG_ERROR, tag, "%s", msg);
-}
-
-void warning(const char *tag, const char *msg)
-{
-       SLOG(LOG_WARN, tag, "%s", msg);
-}
-
-void info(const char *tag, const char *msg)
-{
-       SLOG(LOG_INFO, tag, "%s", msg);
-}
-
-void debug(const char *tag, const char *msg)
-{
-       SLOG(LOG_DEBUG, tag, "%s", msg);
-}
-
-void pedantic(const char *tag, const char *msg)
-{
-       SLOG(LOG_VERBOSE, tag, "%s", msg);
-}
-
-std::map<AbstractLogProvider::LogLevel, dlogMacro> dlogMacros = {
-       // [](const char* tag, const char* msg) { SLOG(LOG_ERROR, tag, "%s", msg); } won't compile
-       { AbstractLogProvider::LogLevel::Error,     error },
-       { AbstractLogProvider::LogLevel::Warning,   warning },
-       { AbstractLogProvider::LogLevel::Info,      info },
-       { AbstractLogProvider::LogLevel::Debug,     debug},
-       { AbstractLogProvider::LogLevel::Pedantic,  pedantic}
-};
-
-} // namespace anonymous
-
-DLOGLogProvider::DLOGLogProvider()
-{}
-
-DLOGLogProvider::~DLOGLogProvider()
-{}
-
-void DLOGLogProvider::SetTag(const char *tag)
-{
-       size_t size = strlen(tag) + 1;
-       char *buff = new(std::nothrow) char[size];
-
-       if (buff)
-               memcpy(buff, tag, size);
-
-       m_tag.reset(buff);
-}
-
-void DLOGLogProvider::Log(AbstractLogProvider::LogLevel level,
-                                                 const char *message,
-                                                 const char *filename,
-                                                 int line,
-                                                 const char *function) const
-{
-       std::ostringstream val;
-       val << std::string("[") << LocateSourceFileName(filename) << std::string(":") << line <<
-               std::string("] ") << function << std::string("(): ") << message;
-
-       try {
-               dlogMacros.at(level)(m_tag.get(), val.str().c_str());
-       } catch (const std::out_of_range &) {
-               SLOG(LOG_ERROR, m_tag.get(), "Unsupported log level: %d", level);
-       }
-}
-}
-} // namespace VcoreDPL
diff --git a/vcore/dpl/log/src/journal_log_provider.cpp b/vcore/dpl/log/src/journal_log_provider.cpp
deleted file mode 100644 (file)
index 0abf8d8..0000000
+++ /dev/null
@@ -1,74 +0,0 @@
-/*
- *  Copyright (c) 2000 - 2014 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       journal_log_provider.cpp
- * @author     Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
- * @version    1.0
- */
-
-#include <dpl/log/journal_log_provider.h>
-#include <systemd/sd-journal.h>
-#include <map>
-#include <stdexcept>
-
-namespace VcoreDPL {
-namespace Log {
-
-namespace {
-std::map<AbstractLogProvider::LogLevel, int> journalLevel = {
-       { AbstractLogProvider::LogLevel::Error,     LOG_ERR     },
-       { AbstractLogProvider::LogLevel::Warning,   LOG_WARNING },
-       { AbstractLogProvider::LogLevel::Info,      LOG_INFO    },
-       { AbstractLogProvider::LogLevel::Debug,     LOG_DEBUG   },
-       { AbstractLogProvider::LogLevel::Pedantic,  LOG_DEBUG   }
-};
-
-} // namespace anonymous
-
-JournalLogProvider::JournalLogProvider()
-{}
-
-JournalLogProvider::~JournalLogProvider()
-{}
-
-void JournalLogProvider::Log(AbstractLogProvider::LogLevel level,
-                                                        const char *message,
-                                                        const char *fileName,
-                                                        int line,
-                                                        const char *function) const
-{
-       try {
-               sd_journal_send("PRIORITY=%d", journalLevel.at(level),
-                                               "CODE_FILE=%s", fileName,
-                                               "CODE_FUNC=%s", function,
-                                               "CODE_LINE=%d", line,
-                                               // add file, line & function info to log message
-                                               "MESSAGE=[%s:%d] %s(): %s", fileName, line, function, message,
-                                               NULL);
-       } catch (const std::out_of_range &) {
-               sd_journal_send(
-                       "PRIORITY=%d", LOG_ERR,
-                       "CODE_FILE=%s", fileName,
-                       "CODE_FUNC=%s", function,
-                       "CODE_LINE=%d", line,
-                       // add file, line & function info to log message
-                       "MESSAGE=[%s:%d] %s(): Unsupported log level %d", fileName, line, function, level,
-                       NULL);
-       }
-}
-
-} /* namespace Log */
-} /* namespace VcoreDPL */
diff --git a/vcore/dpl/log/src/log.cpp b/vcore/dpl/log/src/log.cpp
deleted file mode 100644 (file)
index 5bd61ed..0000000
+++ /dev/null
@@ -1,140 +0,0 @@
-/*
- * Copyright (c) 2011 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        log.cpp
- * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @version     1.0
- * @brief       This file is the implementation file of log system
- */
-#include <stddef.h>
-#include <string.h>
-#include <stdexcept>
-#include <cassert>
-
-#include <dpl/singleton_impl.h>
-#include <dpl/log/old_style_log_provider.h>
-#include <dpl/log/dlog_log_provider.h>
-#include <dpl/log/journal_log_provider.h>
-
-#include <dpl/log/log.h>
-
-IMPLEMENT_SINGLETON(VcoreDPL::Log::LogSystem)
-
-namespace VcoreDPL {
-namespace Log {
-namespace { // anonymous
-const char *const CERTSVC_LOG_LEVEL    = "CERTSVC_LOG_LEVEL";
-const char *const CERTSVC_LOG_PROVIDER = "CERTSVC_LOG_PROVIDER";
-
-const char *const CONSOLE  = "CONSOLE";
-const char *const DLOG     = "DLOG";
-const char *const JOURNALD = "JOURNALD";
-} // namespace anonymous
-
-LogSystem::LogSystem()
-       : m_providerCtor(
-{
-#ifdef TIZEN_ENGINEER_MODE
-       { CONSOLE,  []{ return static_cast<AbstractLogProvider *>(new OldStyleLogProvider()); }},
-#endif
-       { DLOG,     []{ return static_cast<AbstractLogProvider *>(new DLOGLogProvider());     }},
-       { JOURNALD, []{ return static_cast<AbstractLogProvider *>(new JournalLogProvider());  }}
-})
-{
-       SetLogLevel(getenv(CERTSVC_LOG_LEVEL));
-       AbstractLogProvider *prv = NULL;
-
-       try {
-               prv = m_providerCtor.at(getenv(CERTSVC_LOG_PROVIDER))();
-       } catch (const std::exception &) {
-               prv = m_providerCtor[DLOG]();
-       }
-
-       AddProvider(prv);
-}
-
-LogSystem::~LogSystem()
-{
-       RemoveProviders();
-}
-
-void LogSystem::SetTag(const char *tag)
-{
-       for (auto &it : m_providers)
-               it->SetTag(tag);
-}
-
-void LogSystem::AddProvider(AbstractLogProvider *provider)
-{
-       m_providers.push_back(provider);
-}
-
-void LogSystem::RemoveProvider(AbstractLogProvider *provider)
-{
-       m_providers.remove(provider);
-}
-
-void LogSystem::SelectProvider(const std::string &name)
-{
-       ProviderFn &prv = m_providerCtor.at(name);
-       RemoveProviders();
-       AddProvider(prv());
-}
-
-void LogSystem::SetLogLevel(const char *level)
-{
-       if (!level) {
-               m_level = AbstractLogProvider::LogLevel::Debug;
-       } else {
-               try {
-                       m_level = static_cast<AbstractLogProvider::LogLevel>(std::stoi(level));
-               } catch (const std::exception &) {
-                       m_level = AbstractLogProvider::LogLevel::Debug;
-               }
-       }
-
-       if (m_level < AbstractLogProvider::LogLevel::None)
-               m_level = AbstractLogProvider::LogLevel::None;
-       else if (m_level > AbstractLogProvider::LogLevel::Pedantic)
-               m_level = AbstractLogProvider::LogLevel::Pedantic;
-
-#ifndef TIZEN_ENGINEER_MODE
-
-       if (m_level > AbstractLogProvider::LogLevel::Error)
-               m_level = AbstractLogProvider::LogLevel::Error;
-
-#endif
-}
-
-void LogSystem::Log(AbstractLogProvider::LogLevel level,
-                                       const char *message,
-                                       const char *filename,
-                                       int line,
-                                       const char *function) const
-{
-       for (const auto &it : m_providers)
-               it->Log(level, message, filename, line, function);
-}
-
-void LogSystem::RemoveProviders()
-{
-       for (auto &it : m_providers)
-               delete it;
-
-       m_providers.clear();
-}
-}
-} // namespace VcoreDPL
diff --git a/vcore/dpl/log/src/old_style_log_provider.cpp b/vcore/dpl/log/src/old_style_log_provider.cpp
deleted file mode 100644 (file)
index f1dd0d0..0000000
+++ /dev/null
@@ -1,103 +0,0 @@
-/*
- * Copyright (c) 2011 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        old_style_log_provider.cpp
- * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @version     1.0
- * @brief       This file is the implementation file of old style log provider
- */
-#include <stddef.h>
-#include <unistd.h>
-#include <sys/time.h>
-#include <cstdio>
-#include <cstring>
-#include <sstream>
-#include <stdexcept>
-#include <map>
-
-#include <dpl/log/old_style_log_provider.h>
-#include <dpl/colors.h>
-
-namespace VcoreDPL {
-namespace Log {
-namespace { // anonymous
-using namespace VcoreDPL::Colors::Text;
-const char *DEBUG_BEGIN = GREEN_BEGIN;
-const char *DEBUG_END = GREEN_END;
-const char *INFO_BEGIN = CYAN_BEGIN;
-const char *INFO_END = CYAN_END;
-const char *ERROR_BEGIN = RED_BEGIN;
-const char *ERROR_END = RED_END;
-const char *WARNING_BEGIN = BOLD_GOLD_BEGIN;
-const char *WARNING_END = BOLD_GOLD_END;
-const char *PEDANTIC_BEGIN = PURPLE_BEGIN;
-const char *PEDANTIC_END = PURPLE_END;
-
-std::string GetFormattedTime()
-{
-       timeval tv;
-       tm localNowTime;
-       gettimeofday(&tv, NULL);
-       localtime_r(&tv.tv_sec, &localNowTime);
-       char format[64];
-       snprintf(format,
-                        sizeof(format),
-                        "%02i:%02i:%02i.%03i",
-                        localNowTime.tm_hour,
-                        localNowTime.tm_min,
-                        localNowTime.tm_sec,
-                        static_cast<int>(tv.tv_usec / 1000));
-       return format;
-}
-
-struct ColorMark {
-       const char *const begin;
-       const char *const end;
-};
-
-std::map<AbstractLogProvider::LogLevel, ColorMark> consoleLevel = {
-       { AbstractLogProvider::LogLevel::Error,     {ERROR_BEGIN,       ERROR_END} },
-       { AbstractLogProvider::LogLevel::Warning,   {WARNING_BEGIN,     WARNING_END} },
-       { AbstractLogProvider::LogLevel::Info,      {INFO_BEGIN,        INFO_END} },
-       { AbstractLogProvider::LogLevel::Debug,     {DEBUG_BEGIN,       DEBUG_END} },
-       { AbstractLogProvider::LogLevel::Pedantic,  {PEDANTIC_BEGIN,    PEDANTIC_END} }
-};
-
-} // namespace anonymous
-
-OldStyleLogProvider::OldStyleLogProvider() {}
-
-void OldStyleLogProvider::Log(AbstractLogProvider::LogLevel level,
-                                                         const char *message,
-                                                         const char *filename,
-                                                         int line,
-                                                         const char *function) const
-{
-       try {
-               const struct ColorMark &mark = consoleLevel.at(level);
-               std::ostringstream val;
-               val << mark.begin << std::string("[") << GetFormattedTime() << std::string("] [") <<
-                       static_cast<unsigned long>(pthread_self()) << "/" << static_cast<int>(getpid()) <<
-                       std::string("] [") << LocateSourceFileName(filename) << std::string(":") << line <<
-                       std::string("] ") << function << std::string("(): ") << message << mark.end;
-               fprintf(stdout, "%s\n", val.str().c_str());
-       } catch (const std::out_of_range &) {
-               fprintf(stdout, "Unsupported log level: %d\n", level);
-       }
-}
-
-}
-} // namespace VcoreDPL
diff --git a/vcore/server/include/cert-server-db.h b/vcore/server/include/cert-server-db.h
deleted file mode 100644 (file)
index 5aea447..0000000
+++ /dev/null
@@ -1,43 +0,0 @@
-/**
- * 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     cert-server-db.h
- * @author   Kyungwook Tak (k.tak@samsung.com)
- * @version  1.0
- * @brief    cert-server db utils.
- */
-
-#ifndef CERT_SERVER_DB_H_
-#define CERT_SERVER_DB_H_
-
-#include <sqlite3.h>
-#include <cert-svc/cerror.h>
-
-extern sqlite3 *cert_store_db;
-
-typedef enum schema_version_t {
-       TIZEN_2_4 =  1,
-       TIZEN_3_0 =  2
-} schema_version;
-
-int initialize_db(void);
-void deinitialize_db(void);
-int execute_insert_update_query(const char *query);
-int execute_select_query(const char *query, sqlite3_stmt **stmt);
-int get_schema_version(schema_version *version);
-int set_schema_version(schema_version version);
-
-#endif // CERT_SERVER_DB_H_
diff --git a/vcore/server/include/cert-server-debug.h b/vcore/server/include/cert-server-debug.h
deleted file mode 100644 (file)
index 1d91b41..0000000
+++ /dev/null
@@ -1,39 +0,0 @@
-/*
- *
- * Copyright (c) 2000 - 2015 Samsung Electronics Co., Ltd All Rights Reserved
- *
- * Contact: Kidong Kim <kd0228.kim@samsung.com>
- *
- * 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 CERT_SERVER_DEBUG_H
-#define CERT_SERVER_DEBUG_H
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifdef LOG_TAG
-#undef LOG_TAG
-#endif
-#define LOG_TAG "CERT_SVC_SERVER"
-
-#include <dlog.h>
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif // CERT_SERVER_DEBUG_H
diff --git a/vcore/server/include/cert-server-logic.h b/vcore/server/include/cert-server-logic.h
deleted file mode 100644 (file)
index e0a01a5..0000000
+++ /dev/null
@@ -1,54 +0,0 @@
-/**
- * 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     cert-server-logic.h
- * @author   Madhan A K (madhan.ak@samsung.com)
- * @version  1.0
- * @brief    cert-server routines.
- */
-
-#ifndef CERT_SERVER_LOGIC_H_
-#define CERT_SERVER_LOGIC_H_
-
-int getCertificateDetailFromStore(CertStoreType storeType, CertType certType, const char *gname,
-                                                                 char *cert);
-
-int getCertificateDetailFromSystemStore(const char *gname, char *cert);
-
-int deleteCertificateFromStore(CertStoreType storeType, const char *gname);
-
-int getCertificateStatusFromStore(CertStoreType storeType, const char *gname, CertStatus *status);
-
-int setCertificateStatusToStore(CertStoreType storeType, int is_root_app, const char *gname,
-                                                               CertStatus status);
-
-int checkAliasExistsInStore(CertStoreType storeType, const char *alias, int *punique);
-
-int installCertificateToStore(CertStoreType storeType, const char *gname, const char *common_name,
-                                                         const char *private_key_gname, const char *associated_gname, const char *pCertBuffer,
-                                                         CertType certType);
-
-int getCertificateListFromStore(int reqType, CertStoreType storeType, int is_root_app,
-                                                               char **ppCertListBuffer, size_t *bufferLen, size_t *certCount);
-
-int getCertificateAliasFromStore(CertStoreType storeType, const char *gname, char *alias);
-
-int loadCertificatesFromStore(CertStoreType storeType, const char *gname, char **ppCertBlockBuffer,
-                                                         size_t *bufferLen, size_t *certBlockCount);
-
-int update_ca_certificate_file(char *cert);
-
-#endif
diff --git a/vcore/server/src/cert-server-db.c b/vcore/server/src/cert-server-db.c
deleted file mode 100644 (file)
index 77a3246..0000000
+++ /dev/null
@@ -1,169 +0,0 @@
-/**
- * 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     cert-server-db.c
- * @author   Kyungwook Tak (k.tak@samsung.com)
- * @version  1.0
- * @brief    cert server db utils.
- */
-
-#include <db-util.h>
-#include <cert-server-debug.h>
-#include <cert-server-db.h>
-
-sqlite3 *cert_store_db = NULL;
-
-int initialize_db(void)
-{
-       if (cert_store_db != NULL)
-               return CERTSVC_SUCCESS;
-
-       int result = db_util_open(CERTSVC_SYSTEM_STORE_DB, &cert_store_db, 0);
-       if (result != SQLITE_OK) {
-               SLOGE("opening %s failed!", CERTSVC_SYSTEM_STORE_DB);
-               cert_store_db = NULL;
-               return CERTSVC_FAIL;
-       }
-
-       return CERTSVC_SUCCESS;
-}
-
-void deinitialize_db(void)
-{
-       if (cert_store_db == NULL)
-               return;
-
-       db_util_close(cert_store_db);
-       cert_store_db = NULL;
-}
-
-int execute_insert_update_query(const char *query)
-{
-       if (!cert_store_db) {
-               SLOGE("Database not initialised.");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       if (!query) {
-               SLOGE("Query is NULL.");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       /* Begin transaction */
-       int result = sqlite3_exec(cert_store_db, "BEGIN EXCLUSIVE", NULL, NULL, NULL);
-       if (result != SQLITE_OK) {
-               SLOGE("Failed to begin transaction.");
-               return CERTSVC_FAIL;
-       }
-
-       /* Executing command */
-       result = sqlite3_exec(cert_store_db, query, NULL, NULL, NULL);
-       if (result != SQLITE_OK) {
-               SLOGE("Failed to execute query (%s).", query);
-               return CERTSVC_FAIL;
-       }
-
-       /* Committing the transaction */
-       result = sqlite3_exec(cert_store_db, "COMMIT", NULL, NULL, NULL);
-       if (result) {
-               SLOGE("Failed to commit transaction. Roll back now.");
-               result = sqlite3_exec(cert_store_db, "ROLLBACK", NULL, NULL, NULL);
-               if (result != SQLITE_OK)
-                       SLOGE("Failed to commit transaction. Roll back now.");
-
-               return CERTSVC_FAIL;
-       }
-
-       SLOGD("Transaction Commit and End.");
-
-       return CERTSVC_SUCCESS;
-}
-
-int execute_select_query(const char *query, sqlite3_stmt **stmt)
-{
-       if (!cert_store_db || !query)
-               return CERTSVC_WRONG_ARGUMENT;
-
-       sqlite3_stmt *stmts = NULL;
-       if (sqlite3_prepare_v2(cert_store_db, query, strlen(query), &stmts, NULL) != SQLITE_OK) {
-               SLOGE("sqlite3_prepare_v2 failed [%s].", query);
-               return CERTSVC_FAIL;
-       }
-
-       *stmt = stmts;
-       return CERTSVC_SUCCESS;
-}
-
-int get_schema_version(schema_version *version)
-{
-       sqlite3_stmt *stmt = NULL;
-       char *query = NULL;
-
-       query = sqlite3_mprintf("SELECT version FROM schema_info WHERE version=%d",
-                                                       TIZEN_3_0);
-
-       if (!query) {
-               SLOGE("Failed to generate query");
-               return CERTSVC_BAD_ALLOC;
-       }
-
-       int result = execute_select_query(query, &stmt);
-       if (result != CERTSVC_SUCCESS) {
-               SLOGE("Failed to get schema version.");
-               goto exit;
-       }
-
-       if (sqlite3_step(stmt) == SQLITE_ROW) {
-               SLOGI("Database version is 2(Tizen 3.0)");
-               *version = TIZEN_3_0;
-       } else {
-               SLOGW("Database should be upgrade.");
-               *version = TIZEN_2_4;
-       }
-
-exit:
-
-       if (query)
-               sqlite3_free(query);
-       if (stmt)
-               sqlite3_finalize(stmt);
-
-       return result;
-}
-
-int set_schema_version(schema_version version)
-{
-       if (version != TIZEN_3_0) {
-               SLOGE("Schema version should be set as TIZEN_3_0");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       char *query = sqlite3_mprintf("INSERT INTO schema_info (version, description)"
-                                                               "VALUES (%d, 'Tizen 3.0')", (int)version);
-       if (!query) {
-               SLOGE("Failed to generate query");
-               return CERTSVC_BAD_ALLOC;
-       }
-
-       int result = execute_insert_update_query(query);
-       if (result != CERTSVC_SUCCESS)
-               SLOGE("Insert schema version to database failed.");
-
-       if (query)
-               sqlite3_free(query);
-
-       return result;
-}
diff --git a/vcore/server/src/cert-server-logic.c b/vcore/server/src/cert-server-logic.c
deleted file mode 100644 (file)
index adb07f8..0000000
+++ /dev/null
@@ -1,1587 +0,0 @@
-/**
- * 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     cert-server-logic.c
- * @author   Madhan A K (madhan.ak@samsung.com)
- *           Kyungwook Tak (k.tak@samsung.com)
- * @version  1.0
- * @brief    cert-server logic.
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <unistd.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <errno.h>
-#include <stdbool.h>
-#include <string.h>
-#include <dirent.h>
-#include <sys/smack.h>
-#include <sys/socket.h>
-
-#include <ckmc/ckmc-manager.h>
-#include <ckmc/ckmc-error.h>
-
-#include <cert-svc/cerror.h>
-#include <cert-svc/ccert.h>
-#include <vcore/Client.h>
-
-#include <cert-server-debug.h>
-#include <cert-server-logic.h>
-#include <cert-server-db.h>
-
-static CertStatus int_to_CertStatus(int intval)
-{
-       switch (intval) {
-       case 1:
-               return ENABLED;
-       case 0:
-       default:
-               return DISABLED;
-       }
-}
-
-static int CertStatus_to_int(CertStatus status)
-{
-       switch (status) {
-       case ENABLED:
-               return 1;
-       case DISABLED:
-       default:
-               return 0;
-       }
-}
-
-static const char *storetype_to_string(CertStoreType type)
-{
-       switch (type) {
-       case VPN_STORE:    return "vpn";
-       case EMAIL_STORE:  return "email";
-       case WIFI_STORE:   return "wifi";
-       case SYSTEM_STORE: return "ssl";
-       default:           return NULL;
-       }
-}
-
-static CertStoreType nextStore(CertStoreType type)
-{
-       switch (type) {
-       case NONE_STORE:   return VPN_STORE;
-       case VPN_STORE:    return WIFI_STORE;
-       case WIFI_STORE:   return EMAIL_STORE;
-       case EMAIL_STORE:  return SYSTEM_STORE;
-       case SYSTEM_STORE: return NONE_STORE;
-       default:           return NONE_STORE;
-       }
-}
-
-static bool hasStore(CertStoreType types, CertStoreType type)
-{
-       return (types & type) != 0 ? true : false;
-}
-
-char *add_shared_owner_prefix(const char *name)
-{
-       char *ckm_alias = NULL;
-       int result = asprintf(&ckm_alias, "%s%s%s", ckmc_owner_id_system, ckmc_owner_id_separator, name);
-       if (result < 0 || ckm_alias == NULL) {
-               SLOGE("Failed to allocate memory");
-               return NULL;
-       }
-
-       return ckm_alias;
-}
-
-int ckmc_remove_alias_with_shared_owner_prefix(const char *name)
-{
-       char *ckm_alias = add_shared_owner_prefix(name);
-       if (!ckm_alias) {
-               SLOGE("Failed to allocate memory");
-               return CKMC_ERROR_OUT_OF_MEMORY;
-       }
-
-       int result = ckmc_remove_alias(ckm_alias);
-
-       free(ckm_alias);
-
-       return result;
-}
-
-char *get_complete_path(const char *str1, const char *str2)
-{
-       char *result = NULL;
-       int as_result;
-
-       if (!str1 || !str2)
-               return NULL;
-
-       if (str1[strlen(str1) - 1] != '/')
-               as_result = asprintf(&result, "%s/%s", str1, str2);
-       else
-               as_result = asprintf(&result, "%s%s", str1, str2);
-
-       if (as_result < 0)
-               return NULL;
-
-       return result;
-}
-
-int add_file_to_system_cert_dir(const char *gname)
-{
-       int ret = CERTSVC_SUCCESS;
-
-       /* find certificate which filehash name is gname in root ca certs path. */
-       char *target = get_complete_path(TZ_SYS_CA_CERTS_ORIG, gname);
-       char *link = get_complete_path(TZ_SYS_CA_CERTS, gname);
-
-       if (target == NULL || link == NULL) {
-               SLOGE("Failed to get complete path.");
-               ret = CERTSVC_BAD_ALLOC;
-               goto out;
-       }
-
-       if (symlink(target, link) != 0) {
-               SLOGE("Failed to make symlink from[%s] to[%s]", target, link);
-               ret = CERTSVC_FAIL;
-               goto out;
-       }
-
-out:
-
-       free(target);
-       free(link);
-
-       return ret;
-}
-
-int del_file_from_system_cert_dir(const char *gname)
-{
-       int ret = CERTSVC_SUCCESS;
-       char *link = NULL;
-
-       link = get_complete_path(TZ_SYS_CA_CERTS, gname);
-       if (!link)   {
-               SLOGE("Failed to construct source file path.");
-               return CERTSVC_FAIL;
-       }
-
-       if (unlink(link) != 0) {
-               SLOGE("unlink %s failed. errno : %d", link, errno);
-               ret = CERTSVC_FAIL;
-               goto out;
-       }
-
-out:
-
-       free(link);
-
-       return ret;
-}
-
-int write_to_ca_cert_crt_file(const char *mode, const char *cert)
-{
-       int result = CERTSVC_SUCCESS;
-       FILE *fp = NULL;
-
-       if (cert == NULL || strlen(cert) == 0) {
-               SLOGE("Input buffer is NULL.");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       if (!(fp = fopen(TZ_SYS_CA_BUNDLE, mode))) {
-               SLOGE("Failed to open the file for writing, [%s].", TZ_SYS_CA_BUNDLE);
-               return CERTSVC_FAIL;
-       }
-
-       /* if mode of writing is to append, then goto end of file */
-       if (strcmp(mode,"ab") == 0)
-               fseek(fp, 0L, SEEK_END);
-
-       size_t cert_len = strlen(cert);
-       if (fwrite(cert, sizeof(char), cert_len, fp) != cert_len) {
-               SLOGE("Fail to write into file.");
-               result = CERTSVC_FAIL;
-               goto error;
-       }
-
-       /* adding empty line at the end */
-       fwrite("\n", sizeof(char), 1, fp);
-
-error:
-       if (fp)
-               fclose(fp);
-
-       return result;
-}
-
-int saveCertificateToStore(const char *gname, const char *cert)
-{
-       if (!gname || !cert) {
-               SLOGE("Invalid input parameter passed.");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       ckmc_policy_s cert_policy;
-       cert_policy.password = NULL;
-       cert_policy.extractable = true;
-
-       ckmc_raw_buffer_s cert_data;
-       cert_data.data = (unsigned char *)cert;
-       cert_data.size = strlen(cert);
-
-       char *ckm_alias = add_shared_owner_prefix(gname);
-       if (!ckm_alias) {
-               SLOGE("Failed to make alias. memory allocation error.");
-               return CERTSVC_BAD_ALLOC;
-       }
-
-       int result = ckmc_save_data(ckm_alias, cert_data, cert_policy);
-       free(ckm_alias);
-
-       if (result == CKMC_ERROR_DB_ALIAS_EXISTS) {
-               SLOGI("same alias with gname[%s] alrady exist in ckm. Maybe other store type have it. skip.", gname);
-               return CERTSVC_SUCCESS;
-       }
-
-       if (result != CKMC_ERROR_NONE) {
-               SLOGE("Failed to save trusted data. ckm errcode[%d]", result);
-               return CERTSVC_FAIL;
-       }
-
-       return CERTSVC_SUCCESS;
-}
-
-int saveCertificateToSystemStore(const char *gname)
-{
-       if (!gname) {
-               SLOGE("Invalid input parameter passed.");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       int result = add_file_to_system_cert_dir(gname);
-       if (result != CERTSVC_SUCCESS)
-               SLOGE("Failed to store the certificate in store.");
-
-       return result;
-}
-
-int get_certificate_buffer_from_store(CertStoreType storeType, const char *gname, char **pcert)
-{
-       int result = CERTSVC_SUCCESS;
-       int records = 0;
-       char *tempBuffer = NULL;
-       char *query = NULL;
-       sqlite3_stmt *stmt = NULL;
-
-       if (!gname) {
-               SLOGE("Invalid input parameter passed.");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       if (storeType != SYSTEM_STORE)
-               query = sqlite3_mprintf("select * from %Q where gname=%Q and enabled=%d and is_root_app_enabled=%d",
-                               storetype_to_string(storeType), gname, ENABLED, ENABLED);
-       else
-               query = sqlite3_mprintf("select certificate from ssl where gname=%Q and enabled=%d and is_root_app_enabled=%d",
-                               gname, ENABLED, ENABLED);
-
-       result = execute_select_query(query, &stmt);
-       if (result != CERTSVC_SUCCESS) {
-               SLOGE("Querying database failed.");
-               result = CERTSVC_FAIL;
-               goto error;
-       }
-
-       records = sqlite3_step(stmt);
-       if (records != SQLITE_ROW || records == SQLITE_DONE) {
-               SLOGE("No valid records found for given gname [%s].",gname);
-               result = CERTSVC_FAIL;
-               goto error;
-       }
-
-       tempBuffer = (char *)malloc(sizeof(char) * VCORE_MAX_RECV_DATA_SIZE);
-       if (!tempBuffer) {
-               SLOGE("Fail to allocate memory");
-               result = CERTSVC_FAIL;
-               goto error;
-       }
-
-       memset(tempBuffer, 0x00, VCORE_MAX_RECV_DATA_SIZE);
-
-       if (storeType == SYSTEM_STORE)
-               result = getCertificateDetailFromSystemStore(gname, tempBuffer);
-       else
-               result = getCertificateDetailFromStore(storeType, PEM_CRT, gname, tempBuffer);
-
-       if (result != CERTSVC_SUCCESS) {
-               SLOGE("Failed to set request data.");
-               result = CERTSVC_WRONG_ARGUMENT;
-               goto error;
-       }
-
-       *pcert = tempBuffer;
-
-error:
-       if (result != CERTSVC_SUCCESS)
-               free(tempBuffer);
-
-       if (query)
-               sqlite3_free(query);
-
-       if (stmt)
-               sqlite3_finalize(stmt);
-
-       return result;
-}
-
-int update_ca_certificate_file(char *cert)
-{
-       int result = CERTSVC_SUCCESS;
-       int records = 0;
-       int counter = 0;
-       char *gname = NULL;
-       char *query = NULL;
-       const char *text;
-       sqlite3_stmt *stmt = NULL;
-       CertStoreType storeType;
-
-       /*
-        * During install of a root certificate, the root certificate gets appended at
-        * the end to optimise the write operation onto ca-certificate.crt file.
-        */
-       if (cert != NULL && strlen(cert) > 0) {
-               result = write_to_ca_cert_crt_file("ab", cert);
-               if (result != CERTSVC_SUCCESS) {
-                       SLOGE("Failed to write to file. result[%d]", result);
-                       return result;
-               }
-
-               return CERTSVC_SUCCESS;
-       }
-
-       for (storeType = VPN_STORE; storeType != NONE_STORE; storeType = nextStore(storeType)) {
-               if (storeType == SYSTEM_STORE)
-                       query = sqlite3_mprintf("select certificate from ssl where enabled=%d and is_root_app_enabled=%d", ENABLED, ENABLED);
-               else
-                       query = sqlite3_mprintf("select gname from %Q where is_root_cert=%d and enabled=%d and is_root_app_enabled=%d",
-                                       storetype_to_string(storeType), ENABLED, ENABLED, ENABLED);
-
-               result = execute_select_query(query, &stmt);
-               if (query) {
-                       sqlite3_free(query);
-                       query = NULL;
-               }
-
-               if (result != CERTSVC_SUCCESS) {
-                       SLOGE("Querying database failed.");
-                       goto error_and_exit;
-               }
-
-               /* update the ca-certificate.crt file */
-               while (1) {
-                       records = sqlite3_step(stmt);
-                       if (records == SQLITE_DONE) {
-                               result = CERTSVC_SUCCESS;
-                               break;
-                       }
-
-                       if (records != SQLITE_ROW) {
-                               SLOGE("DB query error when select. result[%d].", records);
-                               result = CERTSVC_FAIL;
-                               goto error_and_exit;
-                       }
-
-                       cert = NULL;
-                       gname = NULL;
-
-                       if (storeType == SYSTEM_STORE) {
-                               text = (const char *)sqlite3_column_text(stmt, 0);
-                               if (text)
-                                       cert = strndup(text, strlen(text));
-                       } else {
-                               text = (const char *)sqlite3_column_text(stmt, 0);
-                               if (text)
-                                       gname = strndup(text, strlen(text));
-
-                               result = get_certificate_buffer_from_store(storeType, gname, &cert);
-                               if (result != CERTSVC_SUCCESS) {
-                                       SLOGE("Failed to get certificate buffer from key-manager. gname[%s]", gname);
-                                       goto error_and_exit;
-                               }
-                       }
-
-                       if (cert == NULL) {
-                               SLOGE("Failed to extract cert buffer to update ca-certificate.");
-                               result = CERTSVC_FAIL;
-                               goto error_and_exit;
-                       }
-
-                       if (counter++ == 0)
-                               result = write_to_ca_cert_crt_file("wb", cert);
-                       else
-                               result = write_to_ca_cert_crt_file("ab", cert);
-
-                       if (result != CERTSVC_SUCCESS) {
-                               SLOGE("Failed to write to file.");
-                               result = CERTSVC_FAIL;
-                               goto error_and_exit;
-                       }
-               }
-       }
-
-       SLOGD("Successfully updated ca-certificate.crt file. added cert num[%d]", counter);
-
-error_and_exit:
-       if (stmt)
-               sqlite3_finalize(stmt);
-
-       return result;
-}
-
-int enable_disable_cert_status(
-       CertStoreType storeType,
-       int is_root_app,
-       const char *gname,
-       CertStatus status)
-{
-       int result = CERTSVC_SUCCESS;
-       int records = 0;
-       char *cert = NULL;
-       char *query = NULL;
-       const char *text = NULL;
-       sqlite3_stmt *stmt = NULL;
-
-       if (status != DISABLED && status != ENABLED) {
-               SLOGE("Invalid cert status");
-               return CERTSVC_INVALID_STATUS;
-       }
-
-       query = sqlite3_mprintf("select * from %Q where gname=%Q", storetype_to_string(storeType), gname);
-       if (!query) {
-               SLOGE("Failed to generate query");
-               return CERTSVC_BAD_ALLOC;
-       }
-
-       result = execute_select_query(query, &stmt);
-       sqlite3_free(query);
-
-       if (result != CERTSVC_SUCCESS || !stmt) {
-               SLOGE("Querying database failed.");
-               return CERTSVC_FAIL;
-       }
-
-       records = sqlite3_step(stmt);
-       sqlite3_finalize(stmt);
-       stmt = NULL;
-
-       if (records != SQLITE_ROW) {
-               SLOGE("No valid records found.");
-               return CERTSVC_FAIL;
-       }
-
-       if (status == DISABLED) {
-               /* check certificate presence in disabled_certs table before inserting */
-               query = sqlite3_mprintf("select * from disabled_certs where gname=%Q", gname);
-               if (!query) {
-                       SLOGE("Failed to generate query");
-                       return CERTSVC_BAD_ALLOC;
-               }
-
-               result = execute_select_query(query, &stmt);
-               sqlite3_free(query);
-               query = NULL;
-
-               if (result != CERTSVC_SUCCESS) {
-                       SLOGE("Querying database failed.");
-                       return CERTSVC_FAIL;
-               }
-
-               records = sqlite3_step(stmt);
-               sqlite3_finalize(stmt);
-               stmt = NULL;
-
-               if (records == SQLITE_ROW) {
-                       SLOGE("Selected certificate identifier is already disabled. [%s]", gname);
-                       return CERTSVC_FAIL;
-               }
-
-               /* get certificate from keymanager*/
-               result = get_certificate_buffer_from_store(storeType, gname, &cert);
-               if (result != CERTSVC_SUCCESS) {
-                       SLOGE("Failed to get certificate buffer. result[%d]", result);
-                       return result;
-               }
-
-               /* inserting the disabled certificate to disabled_certs table */
-               query = sqlite3_mprintf("insert into disabled_certs (gname, certificate) values (%Q, %Q)", gname, cert);
-               free(cert);
-
-               if (!query) {
-                       SLOGE("Failed to generate query");
-                       return CERTSVC_BAD_ALLOC;
-               }
-
-               result = execute_insert_update_query(query);
-               sqlite3_free(query);
-
-               if (result != CERTSVC_SUCCESS) {
-                       SLOGE("Insert to database failed.");
-                       return result;
-               }
-
-               if (storeType != SYSTEM_STORE) {
-                       result = ckmc_remove_alias_with_shared_owner_prefix(gname);
-
-                       if (result != CKMC_ERROR_NONE) {
-                               SLOGE("Failed to delete certificate from key-manager. ckmc_result[%d]", result);
-                               return CERTSVC_FAIL;
-                       }
-
-               } else {
-                       result = del_file_from_system_cert_dir(gname);
-                       if (result != CERTSVC_SUCCESS) {
-                               SLOGE("Error in del_file_from_system_cert_dir. ret[%d]", result);
-                               return result;
-                       }
-               }
-       } else { /* moving the certificate to enabled state */
-               query = sqlite3_mprintf("select certificate from disabled_certs where gname=%Q", gname);
-               if (!query) {
-                       SLOGE("Failed to generate query");
-                       return CERTSVC_BAD_ALLOC;
-               }
-
-               result = execute_select_query(query, &stmt);
-               sqlite3_free(query);
-
-               if (result != CERTSVC_SUCCESS) {
-                       SLOGE("Querying database failed.");
-                       return CERTSVC_FAIL;
-               }
-
-               records = sqlite3_step(stmt);
-               if (records == SQLITE_ROW) {
-                       text = (const char *)sqlite3_column_text(stmt, 0);
-
-                       if (!text) {
-                               SLOGE("Invalid column text");
-                               sqlite3_finalize(stmt);
-                               return CERTSVC_FAIL;
-                       }
-
-                       cert = strndup(text, strlen(text));
-
-                       sqlite3_finalize(stmt);
-
-                       if (!cert) {
-                               SLOGE("Failed to allocate memory");
-                               return CERTSVC_BAD_ALLOC;
-                       }
-
-                       if (storeType == SYSTEM_STORE)
-                               result = saveCertificateToSystemStore(gname);
-                       else
-                               result = saveCertificateToStore(gname, cert);
-
-                       free(cert);
-
-                       if (result != CERTSVC_SUCCESS) {
-                               SLOGE("Failed to save certificate to key-manager. ret[%d]", result);
-                               return result;
-                       }
-
-                       query = sqlite3_mprintf("delete from disabled_certs where gname=%Q", gname);
-                       if (!query) {
-                               SLOGE("Failed to generate query");
-                               return CERTSVC_BAD_ALLOC;
-                       }
-
-                       result = execute_insert_update_query(query);
-                       sqlite3_free(query);
-
-                       if (result != CERTSVC_SUCCESS) {
-                               SLOGE("Unable to delete certificate entry from database. ret[%d]", result);
-                               return result;
-                       }
-               }
-       }
-
-       if (is_root_app == ENABLED)
-               query = sqlite3_mprintf("update %Q set is_root_app_enabled=%d , enabled=%d where gname=%Q",
-                               storetype_to_string(storeType), CertStatus_to_int(status), status, gname);
-       else
-               query = sqlite3_mprintf("update %Q set enabled=%d where gname=%Q",
-                               storetype_to_string(storeType), CertStatus_to_int(status), gname);
-
-       if (!query) {
-               SLOGE("Failed to generate query");
-               return CERTSVC_BAD_ALLOC;
-       }
-
-       result = execute_insert_update_query(query);
-       sqlite3_free(query);
-
-       if (result != CERTSVC_SUCCESS) {
-               SLOGE("Update failed. ret[%d]", result);
-               return result;
-       }
-
-       return result;
-}
-
-int setCertificateStatusToStore(
-       CertStoreType storeType,
-       int is_root_app,
-       const char *gname,
-       CertStatus status)
-{
-       if (!gname) {
-               SLOGE("Invalid input parameter passed.");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       int result = enable_disable_cert_status(storeType, is_root_app, gname, status);
-       if (result != CERTSVC_SUCCESS) {
-               SLOGE("Failed to disable certificate.");
-               return result;
-       }
-
-       SLOGD("Successfully updated the certificate status from %s to %s.",
-               (status == DISABLED) ? "ENABLED" : "DISABLED", (status == DISABLED) ? "DISABLED" : "ENABLED");
-       return CERTSVC_SUCCESS;
-}
-
-int getCertificateStatusFromStore(
-       CertStoreType storeType,
-       const char* gname,
-       CertStatus *status)
-{
-       if (!gname) {
-               SLOGE("Invalid input parameter passed.");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       char *query = sqlite3_mprintf("select gname, common_name, enabled from %Q where gname=%Q",
-                       storetype_to_string(storeType), gname);
-       if (!query) {
-               SLOGE("Failed to generate query");
-               return CERTSVC_BAD_ALLOC;
-       }
-
-       sqlite3_stmt *stmt = NULL;
-       int result = execute_select_query(query, &stmt);
-       sqlite3_free(query);
-
-       if (result != CERTSVC_SUCCESS || !stmt) {
-               SLOGE("Querying database failed.");
-               *status = DISABLED;
-               return CERTSVC_FAIL;
-       }
-
-       result = sqlite3_step(stmt);
-       if (result != SQLITE_ROW || result == SQLITE_DONE) {
-               SLOGE("No valid records found.");
-               *status = DISABLED;
-               sqlite3_finalize(stmt);
-               return CERTSVC_FAIL;
-       }
-
-       *status = int_to_CertStatus(sqlite3_column_int(stmt, 2));
-
-       sqlite3_finalize(stmt);
-
-       return CERTSVC_SUCCESS;
-}
-
-int check_alias_exist_in_database(
-       CertStoreType storeTypes,
-       const char *alias,
-       int *punique)
-{
-       char *query = NULL;
-       sqlite3_stmt *stmt = NULL;
-       int result = CERTSVC_SUCCESS;
-       CertStoreType storeType;
-       bool unique = false;
-
-       if (!alias || !punique) {
-               SLOGE("Invalid input parameter passed.");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       for (storeType = VPN_STORE; storeType < SYSTEM_STORE; storeType = nextStore(storeType)) {
-               if (!hasStore(storeTypes, storeType))
-                       continue;
-
-               query = sqlite3_mprintf("select * from %Q where common_name=%Q",
-                               storetype_to_string(storeType), alias);
-
-               if (!query) {
-                       SLOGE("Failed to generate query");
-                       return CERTSVC_BAD_ALLOC;
-               }
-
-               result = execute_select_query(query, &stmt);
-
-               sqlite3_free(query);
-               query = NULL;
-
-               if (result != CERTSVC_SUCCESS || !stmt) {
-                       SLOGE("Querying database failed. result[%d]", result);
-                       return CERTSVC_FAIL;
-               }
-
-               result = sqlite3_step(stmt);
-
-               sqlite3_finalize(stmt);
-               stmt = NULL;
-
-               if (result == SQLITE_DONE) {
-                       unique = true;
-                       break;
-               }
-       }
-
-       *punique = unique ? CERTSVC_TRUE : CERTSVC_FALSE;
-
-       return CERTSVC_SUCCESS;
-}
-
-int installCertificateToStore(
-       CertStoreType storeType,
-       const char *gname,
-       const char *common_name,
-       const char *private_key_gname,
-       const char *associated_gname,
-       const char *dataBlock,
-       CertType certType)
-{
-       if ((!gname)
-               || (certType == P12_END_USER && !common_name && !private_key_gname)
-               || (certType != P12_END_USER && !common_name && !associated_gname)) {
-               SLOGE("Invalid input parameter passed.");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       int result = CERTSVC_SUCCESS;
-
-       if (storeType != SYSTEM_STORE) {
-               result = saveCertificateToStore(gname, dataBlock);
-               if (result != CERTSVC_SUCCESS) {
-                       SLOGE("FAIL to save certificate to key-manager. result[%d]", result);
-                       return CERTSVC_FAIL;
-               }
-       }
-
-       if (certType == P12_PKEY) {
-               SLOGD("Don't save private key in store");
-               return CERTSVC_SUCCESS;
-       }
-
-       char *query = NULL;
-       if (certType == P12_END_USER && private_key_gname) {
-               query = sqlite3_mprintf("insert into %Q (gname, common_name, private_key_gname, associated_gname, enabled, is_root_app_enabled) "\
-                               "values (%Q, %Q, %Q, %Q, %d, %d)", storetype_to_string(storeType), gname, common_name, private_key_gname,
-                               gname, ENABLED, ENABLED);
-       } else if (certType == PEM_CRT || certType == P12_TRUSTED) {
-               query = sqlite3_mprintf("insert into %Q (gname, common_name, is_root_cert, associated_gname, enabled, is_root_app_enabled) values "\
-                               "(%Q, %Q, %d, %Q, %d, %d)", storetype_to_string(storeType), gname, common_name, ENABLED,
-                               associated_gname, ENABLED, ENABLED);
-       } else if (certType == P12_INTERMEDIATE) {
-               query = sqlite3_mprintf("insert into %Q (gname, common_name, associated_gname, enabled, is_root_app_enabled) values (%Q, %Q, %Q, %d, %d)",
-                               storetype_to_string(storeType), gname, common_name, associated_gname, ENABLED, ENABLED);
-       }
-
-       if (!query) {
-               SLOGE("Failed to generate query");
-               return CERTSVC_BAD_ALLOC;
-       }
-
-       result = execute_insert_update_query(query);
-       sqlite3_free(query);
-
-       if (result != CERTSVC_SUCCESS) {
-               SLOGE("Insert to database failed.");
-               return CERTSVC_FAIL;
-       }
-
-       return CERTSVC_SUCCESS;
-}
-
-int checkAliasExistsInStore(CertStoreType storeType, const char *alias, int *punique)
-{
-       if (!alias) {
-               SLOGE("Invalid input parameter passed.");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       *punique = CERTSVC_FAIL;
-       int result = check_alias_exist_in_database(storeType, alias, punique);
-       if (result != CERTSVC_SUCCESS) {
-               SLOGE("Failed to check_alias_exist_in_database. err[%d]", result);
-               return CERTSVC_FAIL;
-       }
-
-       if (*punique == CERTSVC_TRUE)
-               SLOGD("Alias (%s) does not exist in store(%d).", alias, storeType);
-       else
-               SLOGD("Alias (%s) exist in store(%d).", alias, storeType);
-
-       return CERTSVC_SUCCESS;
-}
-
-int getCertificateDetailFromStore(
-       CertStoreType storeType,
-       CertType certType,
-       const char *gname,
-       char *pOutData)
-{
-       int result = CERTSVC_SUCCESS;
-       int records = 0;
-       char *query = NULL;
-       const char *text = NULL;
-       sqlite3_stmt *stmt = NULL;
-       ckmc_raw_buffer_s *cert_data = NULL;
-
-       if (!gname || !pOutData) {
-               SLOGE("Invalid input parameter passed.");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       /* start constructing query */
-       if (certType == P12_PKEY) {
-               /* From the given certificate identifier, get the associated_gname for the certificate.
-                * Then query the database for records matching the associated_gname to get the private key */
-               query = sqlite3_mprintf("select associated_gname from %Q where gname=%Q",
-                               storetype_to_string(storeType), gname);
-               if (!query) {
-                       SLOGE("Failed to generate query");
-                       return CERTSVC_BAD_ALLOC;
-               }
-
-               result = execute_select_query(query, &stmt);
-               sqlite3_free(query);
-
-               if (result != CERTSVC_SUCCESS) {
-                       SLOGE("Querying database failed.");
-                       return result;
-               }
-
-               records = sqlite3_step(stmt);
-               if (records != SQLITE_ROW) {
-                       SLOGE("No valid records found.");
-                       sqlite3_finalize(stmt);
-                       return CERTSVC_FAIL;
-               }
-
-               text = (const char *)sqlite3_column_text(stmt, 0);
-
-               if (!text) {
-                       SLOGE("No valid column text");
-                       sqlite3_finalize(stmt);
-                       return CERTSVC_FAIL;
-               }
-
-               query = sqlite3_mprintf("select private_key_gname from %Q where gname=%Q and enabled=%d and is_root_app_enabled=%d",
-                               storetype_to_string(storeType), text, ENABLED, ENABLED);
-
-               sqlite3_finalize(stmt);
-       } else if (storeType != SYSTEM_STORE) {
-               query = sqlite3_mprintf("select * from %Q where gname=%Q and enabled=%d and is_root_app_enabled=%d",
-                               storetype_to_string(storeType), gname, ENABLED, ENABLED);
-       }
-
-       if (!query) {
-               SLOGE("Failed to generate query");
-               return CERTSVC_BAD_ALLOC;
-       }
-
-       result = execute_select_query(query, &stmt);
-       sqlite3_free(query);
-
-       if (result != CERTSVC_SUCCESS) {
-               SLOGE("Querying database failed.");
-               return result;
-       }
-
-       records = sqlite3_step(stmt);
-       if (records != SQLITE_ROW) {
-               SLOGE("No valid records found.");
-               sqlite3_finalize(stmt);
-               return CERTSVC_FAIL;
-       }
-
-       if (certType == P12_PKEY) {
-               if (!(text = (const char *)sqlite3_column_text(stmt, 0))) {
-                       SLOGE("No valid column text");
-                       sqlite3_finalize(stmt);
-                       return CERTSVC_FAIL;
-               }
-
-               gname = text;
-       }
-
-       char *ckm_alias = add_shared_owner_prefix(gname);
-       if (!ckm_alias) {
-               SLOGE("Failed to make alias. memory allocation error.");
-               return CERTSVC_BAD_ALLOC;
-       }
-
-       result = ckmc_get_data(ckm_alias, NULL, &cert_data);
-       free(ckm_alias);
-
-       sqlite3_finalize(stmt);
-
-       if (result != CKMC_ERROR_NONE) {
-               SLOGE("Failed to get certificate from key-manager. ckm ret[%d]", result);
-               return CERTSVC_FAIL;
-       }
-
-       memcpy(pOutData, cert_data->data, cert_data->size);
-       pOutData[cert_data->size] = 0;
-
-       ckmc_buffer_free(cert_data);
-
-       return CERTSVC_SUCCESS;
-}
-
-int getCertificateDetailFromSystemStore(const char *gname, char *pOutData)
-{
-       int result = CERTSVC_SUCCESS;
-       int records = 0;
-       char *query = NULL;
-       const char *text = NULL;
-       sqlite3_stmt *stmt = NULL;
-
-       if (!gname) {
-               SLOGE("Invalid input parameter passed.");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       query = sqlite3_mprintf("select certificate from ssl where gname=%Q and is_root_app_enabled=%d",
-                       gname, ENABLED, ENABLED);
-       if (!query) {
-               SLOGE("Query is NULL.");
-               return CERTSVC_FAIL;
-       }
-
-       result = execute_select_query(query, &stmt);
-       sqlite3_free(query);
-
-       if (result != CERTSVC_SUCCESS) {
-               SLOGE("Querying database failed.");
-               return result;
-       }
-
-       records = sqlite3_step(stmt);
-       if (records != SQLITE_ROW) {
-               SLOGE("No valid records found for passed gname [%s].", gname);
-               sqlite3_finalize(stmt);
-               return CERTSVC_FAIL;
-       }
-
-       text = (const char *)sqlite3_column_text(stmt, 0);
-
-       if (!text) {
-               SLOGE("Fail to sqlite3_column_text");
-               sqlite3_finalize(stmt);
-               return CERTSVC_FAIL;
-       }
-
-       size_t cert_len = strlen(text);
-       if (cert_len >= 4096) {
-               sqlite3_finalize(stmt);
-               SLOGE("certificate is too long");
-               return CERTSVC_FAIL;
-       }
-
-       memcpy(pOutData, text, cert_len);
-       pOutData[cert_len] = '\0';
-
-       sqlite3_finalize(stmt);
-
-       return CERTSVC_SUCCESS;
-}
-
-int deleteCertificateFromStore(CertStoreType storeType, const char *gname)
-{
-       int result = CERTSVC_SUCCESS;
-       int records = 0;
-       char *query = NULL;
-       char *private_key_name = NULL;
-       sqlite3_stmt *stmt = NULL;
-
-       SLOGD("Remove certificate of gname[%s] in store[%d]", gname, storeType);
-
-       if (!gname) {
-               SLOGE("Invalid input parameter passed.");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       if (storeType == SYSTEM_STORE) {
-               SLOGE("Invalid store type passed.");
-               return CERTSVC_INVALID_STORE_TYPE;
-       }
-
-       /* start constructing query */
-       query = sqlite3_mprintf("select private_key_gname from %Q where gname=%Q",
-                       storetype_to_string(storeType), gname);
-
-       result = execute_select_query(query, &stmt);
-       if (result != CERTSVC_SUCCESS) {
-               SLOGE("Querying database failed.");
-               result = CERTSVC_FAIL;
-               goto error;
-       }
-
-       records = sqlite3_step(stmt);
-       if (records != SQLITE_ROW) {
-               SLOGE("No valid records found for passed gname [%s]. result[%d].", gname, records);
-               result = CERTSVC_FAIL;
-               goto error;
-       }
-
-       /* if a cert is having private-key in it, the private key should
-        * be deleted first from key-manager, then the actual cert */
-       if (sqlite3_column_text(stmt, 0) != NULL)
-               private_key_name = strdup((const char *)sqlite3_column_text(stmt, 0));
-
-       query = sqlite3_mprintf("delete from disabled_certs where gname=%Q", gname);
-       result = execute_insert_update_query(query);
-       if (result != CERTSVC_SUCCESS) {
-               SLOGE("Unable to delete certificate entry from database. result[%d]", result);
-               goto error;
-       }
-
-       if (query) {
-               sqlite3_free(query);
-               query = NULL;
-       }
-
-       if (stmt) {
-               sqlite3_finalize(stmt);
-               stmt = NULL;
-       }
-
-       query = sqlite3_mprintf("delete from %Q where gname=%Q",
-                       storetype_to_string(storeType), gname);
-
-       result = execute_insert_update_query(query);
-       if (result != CERTSVC_SUCCESS) {
-               SLOGE("Unable to delete certificate entry from database. result[%d]", result);
-               goto error;
-       }
-
-       if (query) {
-               sqlite3_free(query);
-               query = NULL;
-       }
-
-       if (stmt) {
-               sqlite3_finalize(stmt);
-               stmt = NULL;
-       }
-
-       CertStoreType other = ALL_STORE & ~SYSTEM_STORE & ~storeType;
-       CertStoreType current;
-       int gname_exist = 0;
-       for (current = VPN_STORE; current < SYSTEM_STORE; current = nextStore(current)) {
-               if (!hasStore(other, current))
-                       continue;
-
-               query = sqlite3_mprintf("select * from %Q where gname=%Q",
-                               storetype_to_string(current), gname);
-               result = execute_select_query(query, &stmt);
-               if (result != CERTSVC_SUCCESS) {
-                       SLOGE("Querying database failed.");
-                       result = CERTSVC_FAIL;
-                       goto error;
-               }
-               records = sqlite3_step(stmt);
-               if (records == SQLITE_ROW) {
-                       SLOGI("Same gname[%s] exist on store[%d].", gname, current);
-                       gname_exist = 1;
-                       break;
-               }
-
-               sqlite3_free(query);
-               sqlite3_finalize(stmt);
-               query = NULL;
-               stmt = NULL;
-       }
-
-       if (!gname_exist) {
-               SLOGD("The gname[%s] which is in store[%d] is the last one. so remove it from ckm either.", gname, current);
-
-               if (private_key_name != NULL) {
-                       result = ckmc_remove_alias_with_shared_owner_prefix(private_key_name);
-                       if (result != CKMC_ERROR_NONE) {
-                               SLOGE("Failed to delete certificate from key-manager. ckmc_result[%d]", result);
-                               result = CERTSVC_FAIL;
-                               goto error;
-                       }
-               }
-
-               /* removing the actual cert */
-               result = ckmc_remove_alias_with_shared_owner_prefix(gname);
-               if (result != CKMC_ERROR_NONE) {
-                       SLOGE("Failed to remove data in ckm with gname[%s]. ckm_result[%d]", gname, result);
-                       result = CERTSVC_FAIL;
-                       goto error;
-               }
-       }
-
-       SLOGD("Success in deleting the certificate from store.");
-       result = CERTSVC_SUCCESS;
-
-error:
-       if (query)
-               sqlite3_free(query);
-
-       if (stmt)
-               sqlite3_finalize(stmt);
-
-       free(private_key_name);
-
-       return result;
-}
-
-static int makeCertListNode(
-       CertStoreType storeType,
-       const char *gname,
-       const char *title,
-       int statusInt,
-       CertSvcStoreCertList **out)
-{
-       CertSvcStoreCertList *node = NULL;
-       int result = CERTSVC_SUCCESS;
-       size_t gname_len = 0;
-       size_t title_len = 0;
-
-       if (out == NULL || gname == NULL || title == NULL) {
-               SLOGE("Failed to read texts from records");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       node = (CertSvcStoreCertList *)malloc(sizeof(CertSvcStoreCertList));
-       if (node == NULL) {
-               SLOGE("Failed to allocate memory.");
-               return CERTSVC_BAD_ALLOC;
-       }
-
-       gname_len = strlen(gname);
-       title_len = strlen(title);
-
-       node->gname = (char *)malloc(sizeof(char) * (gname_len + 1));
-       node->title = (char *)malloc(sizeof(char) * (title_len + 1));
-       if (node->title == NULL || node->gname == NULL) {
-               SLOGE("Failed to allocate memory");
-               result = CERTSVC_BAD_ALLOC;
-               goto error;
-       }
-
-       memcpy(node->gname, gname, gname_len);
-       memcpy(node->title, title, title_len);
-       node->gname[gname_len] = '\0';
-       node->title[title_len] = '\0';
-
-       node->storeType = storeType;
-       node->status = int_to_CertStatus(statusInt);
-       node->next = NULL;
-
-       *out = node;
-
-       return CERTSVC_SUCCESS;
-
-error:
-       if (node != NULL) {
-               free(node->gname);
-               free(node->title);
-       }
-       free(node);
-
-       return result;
-}
-
-int getCertificateListFromStore(
-       int reqType,
-       CertStoreType storeTypes,
-       int is_root_app,
-       char **certListBuffer,
-       size_t *bufferLen,
-       size_t *certCount)
-{
-       int result = CERTSVC_SUCCESS;
-       CertSvcStoreCertList *rootCertHead = NULL;
-       CertSvcStoreCertList *tmpNode = NULL;
-       CertSvcStoreCertList *currentNode = NULL;
-       sqlite3_stmt *stmt = NULL;
-       char *query = NULL;
-       int records = 0;
-       size_t count = 0;
-       size_t i = 0;
-
-       CertStoreType storeType;
-       for (storeType = VPN_STORE; storeType != NONE_STORE; storeType = nextStore(storeType)) {
-               if (!hasStore(storeTypes, storeType))
-                       continue;
-
-               SLOGD("Processing storetype [%s]", storetype_to_string(storeType));
-
-               if (reqType == CERTSVC_GET_ROOT_CERTIFICATE_LIST) {
-                       if (storeType == SYSTEM_STORE) {
-                               query = sqlite3_mprintf("select gname, common_name, enabled from %Q where enabled=%d "\
-                                               "and is_root_app_enabled=%d and order by common_name asc", "ssl", ENABLED, ENABLED);
-                       } else {
-                               query = sqlite3_mprintf("select gname, common_name, enabled from %Q where "\
-                                               "is_root_cert IS NOT NULL and is_root_app_enabled=%d and enabled=%d",
-                                               storetype_to_string(storeType), ENABLED, ENABLED);
-                       }
-               } else if (reqType == CERTSVC_GET_USER_CERTIFICATE_LIST) {
-                       if (storeType == SYSTEM_STORE) {
-                               SLOGE("Invalid store type passed.");
-                               return CERTSVC_WRONG_ARGUMENT;
-                       } else {
-                               query = sqlite3_mprintf("select gname, common_name, enabled from %Q where "\
-                                               "private_key_gname IS NOT NULL and is_root_app_enabled=%d and enabled=%d",
-                                               storetype_to_string(storeType), ENABLED, ENABLED);
-                       }
-               } else {
-                       if (is_root_app != ENABLED) {
-                       /* Gets only the list of certificates where is_root_app = 1 (which are enabled by the master application) */
-                               if (storeType == SYSTEM_STORE) {
-                                       query = sqlite3_mprintf("select gname, common_name, enabled from %Q where "\
-                                                       "is_root_app_enabled=%d order by common_name asc",
-                                                       storetype_to_string(storeType), ENABLED, ENABLED);
-                               } else {
-                                       query = sqlite3_mprintf("select gname, common_name, enabled from %Q where is_root_app_enabled=%d",
-                                                       storetype_to_string(storeType), ENABLED, ENABLED);
-                               }
-                       } else {
-                       /* Gets all the certificates from store without any restrictions */
-                               if (storeType == SYSTEM_STORE) {
-                                       query = sqlite3_mprintf("select gname, common_name, enabled from %Q order by common_name asc",
-                                                       storetype_to_string(storeType), ENABLED);
-                               } else {
-                                       query = sqlite3_mprintf("select gname, common_name, enabled from %Q",
-                                                       storetype_to_string(storeType), ENABLED);
-                               }
-                       }
-               }
-
-               result = execute_select_query(query, &stmt);
-               if (result != CERTSVC_SUCCESS) {
-                       SLOGE("Querying database failed.");
-                       result = CERTSVC_FAIL;
-                       goto error;
-               }
-
-               while ((records = sqlite3_step(stmt)) == SQLITE_ROW) {
-                       result = makeCertListNode(
-                                       storeType,
-                                       (const char *)sqlite3_column_text(stmt, 0),
-                                       (const char *)sqlite3_column_text(stmt, 1),
-                                       (int)sqlite3_column_int(stmt, 2),
-                                       &tmpNode);
-
-                       if (result != CERTSVC_SUCCESS) {
-                               SLOGE("Failed to make new cert list node. result[%d]", result);
-                               goto error;
-                       }
-
-                       if (count == 0)
-                               rootCertHead = tmpNode;
-                       else
-                               currentNode->next = tmpNode;
-
-                       currentNode = tmpNode;
-                       tmpNode = NULL;
-                       count++;
-               }
-
-               if (records != SQLITE_DONE) {
-                       SLOGE("Error in getting data from sqlite3 statement. result[%d]", records);
-                       result = CERTSVC_FAIL;
-                       goto error;
-               }
-
-               if (query) {
-                       sqlite3_free(query);
-                       query = NULL;
-               }
-
-               if (stmt) {
-                       sqlite3_finalize(stmt);
-                       stmt = NULL;
-               }
-       }
-
-       *certCount = count;
-       VcoreCertResponseData *respCertData = (VcoreCertResponseData *)malloc(count * sizeof(VcoreCertResponseData));
-       if (!respCertData) {
-               SLOGE("Failed to allocate memory");
-               result = CERTSVC_BAD_ALLOC;
-               goto error;
-       }
-       if (count > 0)
-               memset(respCertData, 0x00, count * sizeof(VcoreCertResponseData));
-       VcoreCertResponseData* currRespCertData = NULL;
-
-       currentNode = rootCertHead;
-       for (i = 0; i < count; i++) {
-          tmpNode = currentNode->next;
-
-          currRespCertData = respCertData + i;
-          if (strlen(currentNode->gname) > sizeof(currRespCertData->gname)
-                  || strlen(currentNode->title) > sizeof(currRespCertData->title)) {
-                  SLOGE("String is too long. [%s], [%s]", currentNode->gname, currentNode->title);
-                  result = CERTSVC_FAIL;
-                  *certListBuffer = NULL;
-                  free(respCertData);
-                  goto error;
-          }
-          strncpy(currRespCertData->gname, currentNode->gname, strlen(currentNode->gname));
-          strncpy(currRespCertData->title, currentNode->title, strlen(currentNode->title));
-          currRespCertData->status = currentNode->status;
-          currRespCertData->storeType = currentNode->storeType;
-
-          currentNode = tmpNode;
-       }
-
-       *certListBuffer = (char *) respCertData;
-       *bufferLen = count * sizeof(VcoreCertResponseData);
-
-       SLOGD("Success to create certificate list. cert_count=%d", count);
-       result = CERTSVC_SUCCESS;
-
-error:
-       if (query)
-               sqlite3_free(query);
-
-       if (stmt)
-               sqlite3_finalize(stmt);
-
-       if (rootCertHead) {
-               currentNode = rootCertHead;
-               while (currentNode) {
-                       tmpNode = currentNode->next;
-                       free(currentNode->title);
-                       free(currentNode->gname);
-                       free(currentNode);
-                       currentNode = tmpNode;
-               }
-       }
-
-       return result;
-}
-
-int getCertificateAliasFromStore(CertStoreType storeType, const char *gname, char *alias)
-{
-       int result = CERTSVC_SUCCESS;
-       int records = 0;
-       sqlite3_stmt *stmt = NULL;
-       char *query = NULL;
-       const char *text = NULL;
-
-       query = sqlite3_mprintf("select common_name from %Q where gname=%Q",
-                       storetype_to_string(storeType), gname);
-
-       result = execute_select_query(query, &stmt);
-       if (result != CERTSVC_SUCCESS) {
-               SLOGE("Querying database failed.");
-               result = CERTSVC_FAIL;
-               goto error;
-       }
-
-       records = sqlite3_step(stmt);
-       if (records != SQLITE_ROW || records == SQLITE_DONE) {
-               SLOGE("No valid records found for gname passed [%s].",gname);
-               result = CERTSVC_FAIL;
-               goto error;
-       }
-
-       if (!(text = (const char *)sqlite3_column_text(stmt, 0))) {
-               SLOGE("No column text in returned records");
-               result = CERTSVC_FAIL;
-               goto error;
-       }
-
-       strncpy(alias, text, strlen(text));
-
-       if (strlen(alias) == 0) {
-               SLOGE("Unable to get the alias name for the gname passed.");
-               result = CERTSVC_FAIL;
-               goto error;
-       }
-
-       result = CERTSVC_SUCCESS;
-
-       SLOGD("success : getCertificateAliasFromStore");
-error:
-       if (query)
-               sqlite3_free(query);
-
-       if (stmt)
-               sqlite3_finalize(stmt);
-
-       return result;
-}
-
-int loadCertificatesFromStore(
-       CertStoreType storeType,
-       const char* gname,
-       char **ppCertBlockBuffer,
-       size_t *bufferLen,
-       size_t *certBlockCount)
-{
-       int result = CERTSVC_SUCCESS;
-       size_t count = 0;
-       int records = 0;
-       sqlite3_stmt *stmt = NULL;
-       char *query = NULL;
-       char **certs = NULL;
-       const char *tmpText = NULL;
-       size_t i = 0;
-
-       query = sqlite3_mprintf("select associated_gname from %Q where gname=%Q",
-                       storetype_to_string(storeType), gname);
-
-       result = execute_select_query(query, &stmt);
-       if (result != CERTSVC_SUCCESS) {
-               SLOGE("Querying database failed.");
-               result = CERTSVC_FAIL;
-               goto error;
-       }
-
-       records = sqlite3_step(stmt);
-       if (records != SQLITE_ROW || records == SQLITE_DONE) {
-               SLOGE("No valid records found for gname passed [%s].",gname);
-               result = CERTSVC_FAIL;
-               goto error;
-       }
-
-
-       if (records == SQLITE_ROW) {
-               if (query)
-                       sqlite3_free(query);
-
-               const char *columnText = (const char *)sqlite3_column_text(stmt, 0);
-               if (!columnText) {
-                       SLOGE("Failed to sqlite3_column_text");
-                       result = CERTSVC_FAIL;
-                       goto error;
-               }
-
-               query = sqlite3_mprintf("select gname from %Q where associated_gname=%Q and enabled=%d and is_root_app_enabled=%d",
-                               storetype_to_string(storeType), columnText, ENABLED, ENABLED);
-
-               if (stmt)
-                       sqlite3_finalize(stmt);
-
-               result = execute_select_query(query, &stmt);
-               if (result != CERTSVC_SUCCESS) {
-                       SLOGE("Querying database failed.");
-                       result = CERTSVC_FAIL;
-                       goto error;
-               }
-
-               while (1) {
-                       records = sqlite3_step(stmt);
-                       if (records != SQLITE_ROW || records == SQLITE_DONE)
-                               break;
-
-                       if (count == 0) {
-                               certs = (char**) malloc(4 * sizeof(char *));
-                               if (!certs) {
-                                       SLOGE("Failed to allocate memory");
-                                       result = CERTSVC_BAD_ALLOC;
-                                       goto error;
-                               }
-                               memset(certs, 0x00, 4 * sizeof(char *));
-                       }
-
-                       if (records == SQLITE_ROW) {
-                               tmpText = (const char *)sqlite3_column_text(stmt, 0);
-                               if (!tmpText) {
-                                       SLOGE("Failed to sqlite3_column_text.");
-                                       result = CERTSVC_FAIL;
-                                       goto error;
-                               }
-
-                               if (!((certs)[count] = strdup(tmpText))) {
-                                       SLOGE("Failed to allocate memory");
-                                       result = CERTSVC_BAD_ALLOC;
-                                       goto error;
-                               }
-                       }
-
-                       count++;
-               }
-
-               if (count == 0) {
-                       SLOGE("No valid records found for the gname passed [%s].",gname);
-                       return CERTSVC_FAIL;
-               }
-       }
-
-       *certBlockCount = count;
-       *bufferLen = count * sizeof(ResponseCertBlock);
-       ResponseCertBlock *certBlockList = (ResponseCertBlock *) malloc(*bufferLen);
-       if (!certBlockList) {
-               SLOGE("Failed to allocate memory for ResponseCertBlock");
-               result = CERTSVC_BAD_ALLOC;
-               goto error;
-       }
-
-       if (count > 0)
-               memset(certBlockList, 0x00, *bufferLen);
-
-       ResponseCertBlock *currentBlock = NULL;
-       for (i = 0; i < count; i++) {
-               currentBlock = certBlockList + i;
-               if (sizeof(currentBlock->dataBlock) < strlen(certs[i])) {
-                       SLOGE("src is longer than dst. src[%s] dst size[%d]", certs[i], sizeof(currentBlock->dataBlock));
-                       free(certBlockList);
-                       result = CERTSVC_FAIL;
-                       goto error;
-               }
-               strncpy(currentBlock->dataBlock, certs[i], strlen(certs[i]));
-               currentBlock->dataBlockLen = strlen(certs[i]);
-       }
-       *ppCertBlockBuffer = (char *)certBlockList;
-
-       result = CERTSVC_SUCCESS;
-
-       SLOGD("success: loadCertificatesFromStore. CERT_COUNT=%d", count);
-
-error:
-       if (query)
-               sqlite3_free(query);
-
-       if (stmt)
-               sqlite3_finalize(stmt);
-
-       if (certs) {
-               for(i = 0; i < count; i++)
-                       free(certs[i]);
-
-               free(certs);
-       }
-
-       return result;
-}
diff --git a/vcore/server/src/cert-server-main.c b/vcore/server/src/cert-server-main.c
deleted file mode 100644 (file)
index 80dc700..0000000
+++ /dev/null
@@ -1,348 +0,0 @@
-/**
- * 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     cert-server-main.c
- * @author   Madhan A K (madhan.ak@samsung.com)
- *           Kyungwook Tak (k.tak@samsung.com)
- * @version  1.0
- * @brief    cert-svc server.
- */
-
-#include <stdlib.h>
-#include <signal.h>
-#include <unistd.h>
-#include <errno.h>
-#include <sys/un.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <sys/socket.h>
-#include <sys/time.h>
-#include <sys/select.h>
-#include <systemd/sd-daemon.h>
-
-#include <cert-svc/cerror.h>
-#include <cert-svc/ccert.h>
-#include <vcore/Client.h>
-
-#include <cert-server-debug.h>
-#include <cert-server-logic.h>
-#include <cert-server-db.h>
-
-void CertSigHandler(int signo)
-{
-       SLOGD("Got Signal %d, exiting now.", signo);
-
-       deinitialize_db();
-
-       exit(1);
-}
-
-int CertSvcGetSocketFromSystemd(int *pSockfd)
-{
-       int n = sd_listen_fds(0);
-       int fd;
-
-       for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START+n; ++fd) {
-               if (0 < sd_is_socket_unix(fd, SOCK_STREAM, 1, VCORE_SOCK_PATH, 0)) {
-                       LOGD("Get socket from systemd. fd[%d]", fd);
-                       *pSockfd = fd;
-                       return CERTSVC_SUCCESS;
-               }
-       }
-
-       return CERTSVC_FAIL;
-}
-
-void CertSvcServerComm(void)
-{
-       int server_sockfd = 0;
-       int client_sockfd = 0;
-       int read_len = 0;
-       int client_len = 0;
-       struct sockaddr_un clientaddr;
-       int result = CERTSVC_SUCCESS;
-       char *certListBuffer = NULL;
-       char *certBlockBuffer = NULL;
-       size_t bufferLen = 0;
-       size_t blockBufferLen = 0;
-
-       struct timeval timeout;
-       timeout.tv_sec = 10;
-       timeout.tv_usec = 0;
-
-       SLOGI("cert-server is starting...");
-
-       VcoreRequestData recv_data;
-       VcoreResponseData send_data;
-
-       if (CertSvcGetSocketFromSystemd(&server_sockfd) != CERTSVC_SUCCESS) {
-               SLOGE("Failed to get sockfd from systemd.");
-               return;
-       }
-
-       client_len = sizeof(clientaddr);
-       signal(SIGINT, (void*)CertSigHandler);
-
-       result = initialize_db();
-       if (result != CERTSVC_SUCCESS) {
-               SLOGE("Failed to initialize database.");
-               result = CERTSVC_IO_ERROR;
-               goto Error_close_exit;
-       }
-
-       // check schema version for consistent on platform upgrade
-       SLOGI("Start to check schema version.");
-       schema_version version;
-       result = get_schema_version(&version);
-       if (result != CERTSVC_SUCCESS) {
-               SLOGE("Failed to check schema version.");
-               result = CERTSVC_IO_ERROR;
-               goto Error_close_exit;
-       }
-
-       if (version != TIZEN_3_0) {
-               SLOGI("Start to update schema version and bundle.");
-               // remake bundle according to new DB
-               result = update_ca_certificate_file(NULL);
-               if (result != CERTSVC_SUCCESS) {
-                       SLOGE("Failed to migrate bundle.");
-                       result = CERTSVC_IO_ERROR;
-                       goto Error_close_exit;
-               }
-
-               // set DB schema version to TIZEN_3_O
-               set_schema_version(TIZEN_3_0);
-       }
-       SLOGI("Finish checking DB schema version.");
-
-       fd_set fd;
-       struct timeval tv;
-       while (1) {
-               errno = 0;
-
-               FD_ZERO(&fd);
-               FD_SET(server_sockfd, &fd);
-
-               tv.tv_sec = 10;
-               tv.tv_usec = 0;
-
-               memset(&recv_data, 0x00, sizeof(VcoreRequestData));
-               memset(&send_data, 0x00, sizeof(VcoreResponseData));
-
-               int ret = select(server_sockfd + 1, &fd, NULL, NULL, &tv);
-               if (ret == 0) { // timeout
-                       SLOGD("cert-server timeout. exit.");
-                       break;
-               }
-
-               if (ret == -1) {
-                       SLOGE("select() error.");
-                       break;
-               }
-
-               if ((client_sockfd = accept(server_sockfd, (struct sockaddr*)&clientaddr, (socklen_t*)&client_len)) < 0) {
-                       SLOGE("Error in function accept().[socket desc :%d, error no :%d].", client_sockfd, errno);
-                       continue;
-               }
-
-               SLOGD("cert-server Accept! client sock[%d]", client_sockfd);
-
-               if (setsockopt(client_sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)) < 0) {
-                       SLOGE("Error in Set SO_RCVTIMEO Socket Option");
-                       send_data.result = CERTSVC_FAIL;
-                       goto Error_close_exit;
-               }
-
-               if (setsockopt(client_sockfd, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(timeout)) < 0) {
-                       SLOGE("Error in Set SO_SNDTIMEO Socket Option");
-                       send_data.result = CERTSVC_FAIL;
-                       goto Error_close_exit;
-               }
-
-               SLOGD("Connected to a client...");
-
-               read_len = recv(client_sockfd, (char*)&recv_data, sizeof(recv_data), 0);
-               if (read_len < 0) {
-                       SLOGE("Error in function recv().");
-                       send_data.result = CERTSVC_FAIL;
-                       goto Error_close_exit;
-               }
-
-               SLOGD("revc request: reqType=%d", recv_data.reqType);
-
-               switch (recv_data.reqType) {
-               case CERTSVC_EXTRACT_CERT:
-               {
-                       send_data.result = getCertificateDetailFromStore(
-                                       recv_data.storeType,
-                                       recv_data.certType,
-                                       recv_data.gname,
-                                       send_data.dataBlock);
-                       send_data.dataBlockLen = strlen(send_data.dataBlock);
-                       result = send(client_sockfd, (char*)&send_data, sizeof(send_data), 0);
-                       break;
-               }
-
-               case CERTSVC_EXTRACT_SYSTEM_CERT:
-               {
-                       send_data.result = getCertificateDetailFromSystemStore(
-                                       recv_data.gname,
-                                       send_data.dataBlock);
-                       send_data.dataBlockLen = strlen(send_data.dataBlock);
-                       result = send(client_sockfd, (char*)&send_data, sizeof(send_data), 0);
-                       break;
-               }
-
-               case CERTSVC_DELETE_CERT:
-               {
-                       send_data.result = deleteCertificateFromStore(
-                                       recv_data.storeType,
-                                       recv_data.gname);
-                       if (send_data.result == CERTSVC_SUCCESS)
-                               send_data.result = update_ca_certificate_file(NULL);
-                       result = send(client_sockfd, (char*)&send_data, sizeof(send_data), 0);
-                       break;
-               }
-
-               case CERTSVC_GET_CERTIFICATE_STATUS:
-               {
-                       send_data.result = getCertificateStatusFromStore(
-                                       recv_data.storeType,
-                                       recv_data.gname,
-                                       &send_data.certStatus);
-                       result = send(client_sockfd, (char*)&send_data, sizeof(send_data), 0);
-                       break;
-               }
-
-               case CERTSVC_SET_CERTIFICATE_STATUS:
-               {
-                       send_data.result = setCertificateStatusToStore(
-                                       recv_data.storeType,
-                                       recv_data.is_root_app,
-                                       recv_data.gname,
-                                       recv_data.certStatus);
-                       if (send_data.result == CERTSVC_SUCCESS)
-                               send_data.result = update_ca_certificate_file(NULL);
-                       result = send(client_sockfd, (char*)&send_data, sizeof(send_data), 0);
-                       break;
-               }
-
-               case CERTSVC_CHECK_ALIAS_EXISTS:
-               {
-                       send_data.result = checkAliasExistsInStore(
-                                       recv_data.storeType,
-                                       recv_data.gname,
-                                       &send_data.isAliasUnique);
-                       result = send(client_sockfd, (char*)&send_data, sizeof(send_data), 0);
-                       break;
-               }
-
-               case CERTSVC_INSTALL_CERTIFICATE:
-               {
-                       send_data.result = installCertificateToStore(
-                                       recv_data.storeType,
-                                       recv_data.gname,
-                                       recv_data.common_name,
-                                       recv_data.private_key_gname,
-                                       recv_data.associated_gname,
-                                       recv_data.dataBlock,
-                                       recv_data.certType);
-
-                       if (send_data.result == CERTSVC_SUCCESS && (recv_data.certType == PEM_CRT || recv_data.certType == P12_TRUSTED))
-                               send_data.result = update_ca_certificate_file(recv_data.dataBlock);
-                       result = send(client_sockfd, (char*)&send_data, sizeof(send_data), 0);
-                       break;
-               }
-
-               case CERTSVC_GET_CERTIFICATE_LIST:
-               case CERTSVC_GET_USER_CERTIFICATE_LIST:
-               case CERTSVC_GET_ROOT_CERTIFICATE_LIST:
-               {
-                       send_data.result = getCertificateListFromStore(
-                                       recv_data.reqType,
-                                       recv_data.storeType,
-                                       recv_data.is_root_app,
-                                       &certListBuffer,
-                                       &bufferLen,
-                                       &send_data.certCount);
-                       result = send(client_sockfd, (char*)&send_data, sizeof(send_data), 0);
-                       if (bufferLen > 0)
-                               result = send(client_sockfd, certListBuffer, bufferLen, 0);
-                       break;
-               }
-
-               case CERTSVC_GET_CERTIFICATE_ALIAS:
-               {
-                       send_data.result = getCertificateAliasFromStore(
-                                       recv_data.storeType,
-                                       recv_data.gname,
-                                       send_data.common_name);
-                       result = send(client_sockfd, (char*)&send_data, sizeof(send_data), 0);
-                       break;
-               }
-
-               case CERTSVC_LOAD_CERTIFICATES:
-               {
-                       send_data.result = loadCertificatesFromStore(
-                                       recv_data.storeType,
-                                       recv_data.gname,
-                                       &certBlockBuffer,
-                                       &blockBufferLen,
-                                       &send_data.certBlockCount);
-                       result = send(client_sockfd, (char*)&send_data, sizeof(send_data), 0);
-                       if (blockBufferLen > 0)
-                               result = send(client_sockfd, certBlockBuffer, blockBufferLen, 0);
-                       break;
-               }
-
-               default:
-                       SLOGE("Input error. Please check request type");
-                       break;
-               }
-
-               if (result <= 0)
-                       SLOGE("send failed :%d, errno %d try once", result, errno);
-       }
-
-Error_close_exit:
-       close(server_sockfd);
-
-       deinitialize_db();
-
-       free(certListBuffer);
-       free(certBlockBuffer);
-
-       if (client_sockfd >= 0) {
-               result = send(client_sockfd, (char*)&send_data, sizeof(send_data), 0);
-               if (result <= 0)
-                       SLOGE("send failed :%d, errno %d try once", result, errno);
-
-               close(client_sockfd);
-       } else {
-               SLOGE("cannot connect to client socket.");
-       }
-
-       SLOGI("CertSvcServerComm done.");
-}
-
-int main(void)
-{
-       SLOGI("cert-server start");
-       CertSvcServerComm();
-       SLOGI("cert-server end");
-
-       return 0;
-}
diff --git a/vcore/vcore/Base64.cpp b/vcore/vcore/Base64.cpp
deleted file mode 100644 (file)
index e3b85ef..0000000
+++ /dev/null
@@ -1,229 +0,0 @@
-/*
- * Copyright (c) 2011 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.
- */
-#include <algorithm>
-#include <string>
-#include <memory>
-#include <string.h>
-#include <openssl/bio.h>
-#include <openssl/evp.h>
-#include <openssl/buffer.h>
-
-#include <dpl/log/log.h>
-
-#include <vcore/Base64.h>
-
-namespace ValidationCore {
-Base64Encoder::Base64Encoder() :
-       m_b64(0),
-       m_bmem(0),
-       m_finalized(false)
-{
-}
-
-void Base64Encoder::append(const std::string &data)
-{
-       if (m_finalized) {
-               LogWarning("Already finalized.");
-               VcoreThrowMsg(Exception::AlreadyFinalized, "Already finalized");
-       }
-
-       if (!m_b64) {
-               reset();
-       }
-
-       BIO_write(m_b64, data.c_str(), data.size());
-}
-
-void Base64Encoder::finalize()
-{
-       if (m_finalized) {
-               LogWarning("Already finalized.");
-               VcoreThrowMsg(Exception::AlreadyFinalized, "Already finalized.");
-       }
-
-       m_finalized = true;
-
-       if (BIO_flush(m_b64) != 1)
-               VcoreThrowMsg(Exception::InternalError, "Bio internal error");
-}
-
-std::string Base64Encoder::get()
-{
-       if (!m_finalized) {
-               LogWarning("Not finalized");
-               VcoreThrowMsg(Exception::NotFinalized, "Not finalized");
-       }
-
-       BUF_MEM *bptr = 0;
-       BIO_get_mem_ptr(m_b64, &bptr);
-
-       if (bptr == 0) {
-               LogError("Bio internal error");
-               VcoreThrowMsg(Exception::InternalError, "Bio internal error");
-       }
-
-       if (bptr->length > 0) {
-               return std::string(bptr->data, bptr->length);
-       }
-
-       return std::string();
-}
-
-void Base64Encoder::reset()
-{
-       m_finalized = false;
-       BIO_free_all(m_b64);
-       m_b64 = BIO_new(BIO_f_base64());
-       m_bmem = BIO_new(BIO_s_mem());
-
-       if (!m_b64 || !m_bmem) {
-               LogError("Error during allocation memory in BIO");
-               VcoreThrowMsg(Exception::InternalError,
-                                         "Error during allocation memory in BIO");
-       }
-
-       BIO_set_flags(m_b64, BIO_FLAGS_BASE64_NO_NL);
-       m_b64 = BIO_push(m_b64, m_bmem);
-}
-
-Base64Encoder::~Base64Encoder()
-{
-       BIO_free_all(m_b64);
-}
-
-Base64Decoder::Base64Decoder() :
-       m_finalized(false)
-{
-}
-
-void Base64Decoder::append(const std::string &data)
-{
-       if (m_finalized) {
-               LogWarning("Already finalized.");
-               VcoreThrowMsg(Exception::AlreadyFinalized, "Already finalized.");
-       }
-
-       m_input.append(data);
-}
-
-static bool whiteCharacter(char a)
-{
-       if (a == '\n')
-               return true;
-
-       return false;
-}
-
-bool Base64Decoder::finalize()
-{
-       if (m_finalized) {
-               LogWarning("Already finalized.");
-               VcoreThrowMsg(Exception::AlreadyFinalized, "Already finalized.");
-       }
-
-       m_finalized = true;
-       m_input.erase(std::remove_if(m_input.begin(),
-                                                                m_input.end(),
-                                                                whiteCharacter),
-                                 m_input.end());
-
-       for (size_t i = 0; i < m_input.size(); ++i) {
-               if (isalnum(m_input[i])
-                               || m_input[i] == '+'
-                               || m_input[i] == '/'
-                               || m_input[i] == '=')
-                       continue;
-
-               LogError("Base64 input contains illegal chars: " << m_input[i]);
-               return false;
-       }
-
-       BIO *b64, *bmem;
-       size_t len = m_input.size();
-       std::shared_ptr<char> buffer(new char[len], [](char *p) {
-               delete []p;
-       });
-
-       if (!buffer.get()) {
-               LogError("Error in new");
-               VcoreThrowMsg(Exception::InternalError, "Error in new");
-       }
-
-       memset(buffer.get(), 0, len);
-       b64 = BIO_new(BIO_f_base64());
-
-       if (!b64) {
-               LogError("Couldn't create BIO object.");
-               VcoreThrowMsg(Exception::InternalError, "Couldn't create BIO object.");
-       }
-
-       BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
-       std::shared_ptr<char> tmp(strdup(m_input.c_str()), [](char *p) {
-               free(p);
-       });
-
-       if (!tmp.get()) {
-               LogError("Error in strdup");
-               VcoreThrowMsg(Exception::InternalError, "Error in strdup");
-       }
-
-       m_input.clear();
-       bmem = BIO_new_mem_buf(tmp.get(), len);
-
-       if (!bmem) {
-               BIO_free(b64);
-               LogError("Internal error in BIO");
-               VcoreThrowMsg(Exception::InternalError, "Internal error in BIO");
-       }
-
-       bmem = BIO_push(b64, bmem);
-
-       if (!bmem) {
-               BIO_free(b64);
-               LogError("Internal error in BIO");
-               VcoreThrowMsg(Exception::InternalError, "Internal error in BIO");
-       }
-
-       int readlen = BIO_read(bmem, buffer.get(), len);
-       m_output.clear();
-       bool status = true;
-
-       if (readlen > 0)
-               m_output.append(buffer.get(), readlen);
-       else
-               status = false;
-
-       BIO_free_all(bmem);
-       return status;
-}
-
-std::string Base64Decoder::get() const
-{
-       if (!m_finalized) {
-               LogWarning("Not finalized.");
-               VcoreThrowMsg(Exception::NotFinalized, "Not finalized");
-       }
-
-       return m_output;
-}
-
-void Base64Decoder::reset()
-{
-       m_finalized = false;
-       m_input.clear();
-       m_output.clear();
-}
-} // namespace ValidationCore
diff --git a/vcore/vcore/Base64.h b/vcore/vcore/Base64.h
deleted file mode 100644 (file)
index d8f3817..0000000
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright (c) 2011 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.
- */
-#ifndef _BASE64_H_
-#define _BASE64_H_
-
-#include <string>
-#include <vcore/exception.h>
-
-struct bio_st;
-typedef bio_st BIO;
-
-namespace ValidationCore {
-class Base64Encoder {
-public:
-       class Exception {
-       public:
-               VCORE_DECLARE_EXCEPTION_TYPE(ValidationCore::Exception, Base)
-               VCORE_DECLARE_EXCEPTION_TYPE(Base, InternalError)
-               VCORE_DECLARE_EXCEPTION_TYPE(Base, NotFinalized)
-               VCORE_DECLARE_EXCEPTION_TYPE(Base, AlreadyFinalized)
-       };
-       Base64Encoder();
-       void append(const std::string &data);
-       void finalize();
-       std::string get();
-       void reset();
-       ~Base64Encoder();
-
-private:
-       Base64Encoder(const Base64Encoder &);
-       const Base64Encoder &operator=(const Base64Encoder &);
-
-       BIO *m_b64;
-       BIO *m_bmem;
-       bool m_finalized;
-};
-
-class Base64Decoder {
-public:
-       class Exception {
-       public:
-               VCORE_DECLARE_EXCEPTION_TYPE(ValidationCore::Exception, Base)
-               VCORE_DECLARE_EXCEPTION_TYPE(Base, InternalError)
-               VCORE_DECLARE_EXCEPTION_TYPE(Base, NotFinalized)
-               VCORE_DECLARE_EXCEPTION_TYPE(Base, AlreadyFinalized)
-       };
-       Base64Decoder();
-       void append(const std::string &data);
-
-       /*
-        *  Function will return false when BIO_read fails
-        *  (for example: when string was not in base64 format).
-        */
-       bool finalize();
-       std::string get() const;
-       void reset();
-       ~Base64Decoder() {}
-
-private:
-       Base64Decoder(const Base64Decoder &);
-       const Base64Decoder &operator=(const Base64Decoder &);
-
-       std::string m_input;
-       std::string m_output;
-       bool m_finalized;
-};
-} // namespace ValidationCore
-
-#endif
diff --git a/vcore/vcore/CertStoreType.cpp b/vcore/vcore/CertStoreType.cpp
deleted file mode 100644 (file)
index dbabf21..0000000
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright (c) 2011 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.
- */
-/*
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @file        CertStoreType.cpp
- * @version     1.0
- * @brief       Identification of certificate domain. Certificate domains
- *              were defined in WAC 1.0 documentation. This is a part
- *              should be implemented in wrt-installer.
- */
-#include <vcore/CertStoreType.h>
-
-namespace ValidationCore {
-namespace CertStoreId {
-
-Set::Set()
-       : m_certificateStorage(0)
-{}
-
-Set::~Set()
-{
-}
-
-void Set::add(Type second)
-{
-       m_certificateStorage |= second;
-}
-
-bool Set::contains(Type second) const
-{
-       return static_cast<bool>(m_certificateStorage & second);
-}
-
-bool Set::isContainsVis() const
-{
-       Type visType = VIS_PUBLIC;
-       visType |= VIS_PARTNER;
-       visType |= VIS_PLATFORM;
-       visType &= m_certificateStorage;
-
-       if (visType == 0)
-               return false;
-
-       return true;
-}
-
-bool Set::isEmpty() const
-{
-       return m_certificateStorage == 0;
-}
-
-std::string Set::typeToString() const
-{
-       std::string ret;
-
-       if (m_certificateStorage & TIZEN_DEVELOPER)
-               ret += "TIZEN_DEVELOPER ";
-
-       if (m_certificateStorage & TIZEN_TEST)
-               ret += "TIZEN_TEST ";
-
-       if (m_certificateStorage & TIZEN_VERIFY)
-               ret += "TIZEN_VERIFY ";
-
-       if (m_certificateStorage & TIZEN_STORE)
-               ret += "TIZEN_STORE ";
-
-       if (m_certificateStorage & TIZEN_REVOKED)
-               ret += "TIZEN_REVOKED ";
-
-       if (m_certificateStorage & VIS_PUBLIC)
-               ret += "VIS_PUBLIC ";
-
-       if (m_certificateStorage & VIS_PARTNER)
-               ret += "VIS_PARTNER ";
-
-       if (m_certificateStorage & VIS_PLATFORM)
-               ret += "VIS_PLATFORM ";
-
-       return ret;
-}
-
-} // namespace CertStoreId
-} // namespace ValidationCore
diff --git a/vcore/vcore/CertStoreType.h b/vcore/vcore/CertStoreType.h
deleted file mode 100644 (file)
index ea01f7b..0000000
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * Copyright (c) 2011 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.
- */
-/*
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @file        CertStoreType.h
- * @version     1.0
- * @brief       Identification of certificate domain. Certificate domains
- *              were defined in WAC 1.0 documentation. This is a part
- *              should be implemented in wrt-installer.
- */
-#ifndef _VALIDATION_CORE_CERTSTORETYPE_H_
-#define _VALIDATION_CORE_CERTSTORETYPE_H_
-
-#include <string>
-
-namespace ValidationCore {
-namespace CertStoreId {
-typedef unsigned int Type;
-
-// RootCA certificates for developer mode.
-const Type TIZEN_DEVELOPER = 1;
-// RootCA certificates for author signatures.
-const Type TIZEN_TEST = 1 << 1;
-const Type TIZEN_VERIFY = 1 << 2;
-const Type TIZEN_STORE = 1 << 3;
-const Type TIZEN_REVOKED = 1 << 4;
-// RootCA's visibility level : public
-const Type VIS_PUBLIC = 1 << 6;
-// RootCA's visibility level : partner
-const Type VIS_PARTNER = 1 << 7;
-// RootCA's visibility level : platform
-const Type VIS_PLATFORM = 1 << 10;
-
-class Set {
-public:
-       Set();
-       virtual ~Set();
-
-       void add(Type second);
-       bool contains(Type second) const;
-       bool isContainsVis() const;
-       bool isEmpty() const;
-
-       std::string typeToString() const;
-
-private:
-       Type m_certificateStorage;
-};
-
-} // namespace CertStoreId
-} // namespace ValidationCore
-
-#endif //  _VALIDATION_CORE_CERTSTORETYPE_H_
diff --git a/vcore/vcore/Certificate.cpp b/vcore/vcore/Certificate.cpp
deleted file mode 100644 (file)
index d2c5c01..0000000
+++ /dev/null
@@ -1,680 +0,0 @@
-/*
- * 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        Certificate.cpp
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief       Certificate class implementation
- */
-
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <unistd.h>
-
-#include <cstdio>
-#include <memory>
-#include <iomanip>
-
-#include <openssl/pem.h>
-#include <openssl/x509.h>
-#include <openssl/x509v3.h>
-#include <openssl/objects.h>
-
-#include <dpl/log/log.h>
-
-#include "vcore/Base64.h"
-#include "vcore/TimeConversion.h"
-
-#include "vcore/Certificate.h"
-
-namespace {
-
-typedef std::unique_ptr<X509, std::function<void(X509 *)>> ScopedX509;
-typedef std::unique_ptr<FILE, std::function<int(FILE *)>> ScopedFile;
-
-} // namespace anonymous
-
-namespace ValidationCore {
-
-Certificate::Certificate(X509 *cert)
-{
-       if (cert == NULL)
-               VcoreThrowMsg(Certificate::Exception::WrongParamError,
-                                         "Input X509 shouldn't be NULL.");
-
-       m_x509 = X509_dup(cert);
-
-       if (m_x509 == NULL)
-               VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
-                                         "Internal Openssl error in d2i_X509 function.");
-}
-
-Certificate::Certificate(const std::string &data,
-                                                Certificate::FormType form)
-{
-       if (data.size() == 0)
-               VcoreThrowMsg(Certificate::Exception::WrongParamError,
-                                         "Input data shouldn't be empty");
-
-       int size;
-       const unsigned char *ptr;
-       std::string tmp = data;
-
-       // transform to DER format
-       if (FORM_BASE64 == form) {
-               try {
-                       Base64Decoder base64;
-                       base64.reset();
-                       base64.append(data);
-
-                       if (!base64.finalize()) {
-                               LogWarning("Error during decoding");
-                       }
-
-                       tmp = base64.get();
-               } catch (const Base64Decoder::Exception::Base &e) {
-                       LogError("Exception in Certificate constructor : " << e.DumpToString());
-                       VcoreThrowMsg(Certificate::Exception::Base64Error, "Failed to Base64Decoder");
-               }
-       }
-
-       ptr = reinterpret_cast<const unsigned char *>(tmp.c_str());
-       size = static_cast<int>(tmp.size());
-       m_x509 = d2i_X509(NULL, &ptr, size);
-
-       if (!m_x509)
-               VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
-                                         "Internal Openssl error in d2i_X509 function.");
-}
-
-static off_t getFileSize(const std::string &location)
-{
-       struct stat status;
-       stat(location.c_str(), &status);
-       return status.st_size;
-}
-
-CertificatePtr Certificate::createFromFile(const std::string &location)
-{
-       FILE *fp = NULL;
-       X509 *x509 = NULL;
-       fp = fopen(location.c_str(), "rb");
-
-       if (fp == NULL)
-               VcoreThrowMsg(Certificate::Exception::WrongParamError,
-                                         "File cannot be opened : " << location);
-
-       ScopedFile filePtr(fp, fclose);
-       x509 = PEM_read_X509(fp, NULL, NULL, NULL);
-
-       if (x509 == NULL) {
-               rewind(fp);
-               x509 = PEM_read_X509_AUX(fp, NULL, NULL, NULL);
-       }
-
-       if (x509 != NULL) {
-               ScopedX509 x509Ptr(x509, X509_free);
-               return CertificatePtr(new Certificate(x509));
-       }
-
-       off_t filesize = getFileSize(location);
-
-       if (filesize == 0)
-               VcoreThrowMsg(Certificate::Exception::WrongParamError,
-                                         "File content is empty : " << location);
-
-       unsigned char *content = new unsigned char[filesize + 1];
-       if (content == NULL)
-               VcoreThrowMsg(Certificate::Exception::InternalError,
-                                         "Fail to allocate memory.");
-
-       memset(content, 0x00, filesize + 1);
-       rewind(fp);
-
-       if (fread(content, sizeof(unsigned char), filesize, fp) != static_cast<size_t>(filesize))
-               VcoreThrowMsg(Certificate::Exception::InternalError,
-                                         "file read failed. wrong size : " << location);
-
-       content[filesize] = '\0';
-       const unsigned char *ptr = reinterpret_cast<const unsigned char *>(content);
-       x509 = d2i_X509(NULL, &ptr, filesize);
-
-       if (x509 == NULL)
-               VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
-                                         "Internal Openssl error in d2i_X509 function.");
-
-       return CertificatePtr(new Certificate(x509));
-}
-
-Certificate::~Certificate()
-{
-       X509_free(m_x509);
-}
-
-X509 *Certificate::getX509(void) const
-{
-       return m_x509;
-}
-
-std::string Certificate::getDER(void) const
-{
-       unsigned char *rawDer = NULL;
-       int size = i2d_X509(m_x509, &rawDer);
-
-       if (!rawDer || size <= 0)
-               VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
-                                         "i2d_X509 failed");
-
-       std::string output(reinterpret_cast<char *>(rawDer), size);
-       OPENSSL_free(rawDer);
-       return output;
-}
-
-std::string Certificate::getBase64(void) const
-{
-       Base64Encoder base64;
-
-       try {
-               base64.reset();
-               base64.append(getDER());
-               base64.finalize();
-       } catch (const Base64Encoder::Exception::Base &e) {
-               LogError("Exception in Certificate getBase64 : " << e.DumpToString());
-               VcoreThrowMsg(Certificate::Exception::Base64Error, "Failed to Base64Encoder");
-       }
-
-       return base64.get();
-}
-
-bool Certificate::isSignedBy(const CertificatePtr &parent) const
-{
-       if (!parent) {
-               LogDebug("Invalid certificate parameter.");
-               return false;
-       }
-
-       return 0 == X509_NAME_cmp(X509_get_subject_name(parent->m_x509),
-                                                         X509_get_issuer_name(m_x509));
-}
-
-Certificate::Fingerprint Certificate::getFingerprint(
-       Certificate::FingerprintType type) const
-{
-       unsigned int fingerprintlength = EVP_MAX_MD_SIZE;
-       unsigned char fingerprint[EVP_MAX_MD_SIZE];
-       Fingerprint raw;
-
-       if (type == FINGERPRINT_MD5) {
-               if (!X509_digest(m_x509, EVP_md5(), fingerprint, &fingerprintlength))
-                       VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
-                                                 "MD5 digest counting failed!");
-       }
-
-       if (type == FINGERPRINT_SHA1) {
-               if (!X509_digest(m_x509, EVP_sha1(), fingerprint, &fingerprintlength))
-                       VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
-                                                 "SHA1 digest counting failed");
-       }
-
-       raw.resize(fingerprintlength); // improve performance
-       std::copy(fingerprint, fingerprint + fingerprintlength, raw.begin());
-       return raw;
-}
-
-X509_NAME *Certificate::getX509Name(FieldType type) const
-{
-       X509_NAME *name = NULL;
-
-       switch (type) {
-       case FIELD_ISSUER:
-               name = X509_get_issuer_name(m_x509);
-               break;
-
-       case FIELD_SUBJECT:
-               name = X509_get_subject_name(m_x509);
-               break;
-
-       default:
-               VcoreThrowMsg(Certificate::Exception::WrongParamError,
-                                         "Invalid field type param. type : " << type);
-       }
-
-       if (!name)
-               VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
-                                         "Error during x509 name extraction.");
-
-       return name;
-}
-
-std::string Certificate::getOneLine(FieldType type) const
-{
-       X509_NAME *name = getX509Name(type);
-       static const int MAXB = 1024;
-       char buffer[MAXB] = {0, };
-       X509_NAME_oneline(name, buffer, MAXB);
-       return std::string(buffer);
-}
-
-std::string Certificate::getField(FieldType type, int fieldNid) const
-{
-       X509_NAME *subjectName = getX509Name(type);
-       X509_NAME_ENTRY *subjectEntry = NULL;
-       std::string output;
-       int entryCount = X509_NAME_entry_count(subjectName);
-
-       for (int i = 0; i < entryCount; ++i) {
-               subjectEntry = X509_NAME_get_entry(subjectName,
-                                                                                  i);
-
-               if (!subjectEntry) {
-                       continue;
-               }
-
-               int nid = OBJ_obj2nid(
-                                         static_cast<ASN1_OBJECT *>(
-                                                 X509_NAME_ENTRY_get_object(subjectEntry)));
-
-               if (nid != fieldNid) {
-                       continue;
-               }
-
-               ASN1_STRING *pASN1Str = subjectEntry->value;
-               unsigned char *pData = NULL;
-               int nLength = ASN1_STRING_to_UTF8(&pData,
-                                                                                 pASN1Str);
-
-               if (nLength < 0)
-                       VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
-                                                 "Reading field error.");
-
-               if (!pData) {
-                       output = std::string();
-               } else {
-                       output = std::string(reinterpret_cast<char *>(pData), nLength);
-                       OPENSSL_free(pData);
-               }
-       }
-
-       return output;
-}
-
-std::string Certificate::getCommonName(FieldType type) const
-{
-       return getField(type, NID_commonName);
-}
-
-std::string Certificate::getCountryName(FieldType type) const
-{
-       return getField(type, NID_countryName);
-}
-
-std::string Certificate::getStateOrProvinceName(FieldType type) const
-{
-       return getField(type, NID_stateOrProvinceName);
-}
-
-std::string Certificate::getLocalityName(FieldType type) const
-{
-       return getField(type, NID_localityName);
-}
-
-std::string Certificate::getOrganizationName(FieldType type) const
-{
-       return getField(type, NID_organizationName);
-}
-
-std::string Certificate::getOrganizationalUnitName(FieldType type) const
-{
-       return getField(type, NID_organizationalUnitName);
-}
-
-std::string Certificate::getEmailAddres(FieldType type) const
-{
-       return getField(type, NID_pkcs9_emailAddress);
-}
-
-std::string Certificate::getNameHash(FieldType type) const
-{
-       unsigned long ulNameHash;
-       char buf[9] = {0};
-
-       if (type == FIELD_SUBJECT)
-               ulNameHash = X509_subject_name_hash(m_x509);
-       else
-               ulNameHash = X509_issuer_name_hash(m_x509);
-
-       snprintf(buf, 9, "%08lx", ulNameHash);
-       return std::string(buf);
-}
-
-std::string Certificate::getUID(FieldType type) const
-{
-       ASN1_BIT_STRING *uid = NULL;
-
-       if (type == FIELD_SUBJECT)
-               uid = m_x509->cert_info->subjectUID;
-       else
-               uid = m_x509->cert_info->issuerUID;
-
-       if (uid->data == NULL)
-               return std::string();
-
-       char *temp = new char[uid->length + 1];
-
-       if(temp == NULL) {
-               LogError("Fail to allocate memory.");
-               return std::string();
-       }
-
-       memcpy(temp, uid->data, uid->length);
-       temp[uid->length] = 0;
-       std::string uidStr(temp);
-       delete []temp;
-       return uidStr;
-}
-
-std::string Certificate::getOCSPURL() const
-{
-       // TODO verify this code
-       std::string retValue;
-       AUTHORITY_INFO_ACCESS *aia = static_cast<AUTHORITY_INFO_ACCESS *>(
-                                                                        X509_get_ext_d2i(m_x509,
-                                                                                        NID_info_access,
-                                                                                        NULL,
-                                                                                        NULL));
-
-       // no AIA extension in the cert
-       if (NULL == aia) {
-               return retValue;
-       }
-
-       int count = sk_ACCESS_DESCRIPTION_num(aia);
-
-       for (int i = 0; i < count; ++i) {
-               ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(aia, i);
-
-               if (OBJ_obj2nid(ad->method) == NID_ad_OCSP &&
-                               ad->location->type == GEN_URI) {
-                       void *data = ASN1_STRING_data(ad->location->d.ia5);
-
-                       if (!data)
-                               retValue = std::string();
-                       else
-                               retValue = std::string(static_cast<char *>(data));
-
-                       break;
-               }
-       }
-
-       sk_ACCESS_DESCRIPTION_free(aia);
-       return retValue;
-}
-
-Certificate::AltNameSet Certificate::getAlternativeNameDNS() const
-{
-       AltNameSet set;
-       GENERAL_NAME *namePart = NULL;
-       STACK_OF(GENERAL_NAME)* san =
-               static_cast<STACK_OF(GENERAL_NAME) *>(
-                       X509_get_ext_d2i(m_x509, NID_subject_alt_name, NULL, NULL));
-
-       while (sk_GENERAL_NAME_num(san) > 0) {
-               if ((namePart = sk_GENERAL_NAME_pop(san)) == NULL)
-                       VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
-                                                 "openssl sk_GENERAL_NAME_pop err.");
-
-               if (GEN_DNS == namePart->type) {
-                       char *temp = reinterpret_cast<char *>(ASN1_STRING_data(namePart->d.dNSName));
-
-                       if (!temp) {
-                               set.insert(std::string());
-                       } else {
-                               set.insert(std::string(temp));
-                               LogDebug("FOUND GEN_DNS: " << temp);
-                       }
-               } else {
-                       LogDebug("FOUND GEN TYPE ID: " << namePart->type);
-               }
-       }
-
-       return set;
-}
-
-ASN1_TIME *Certificate::getNotAfterTime() const
-{
-       auto timeafter = X509_get_notAfter(m_x509);
-
-       if (!timeafter)
-               VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
-                                         "Reading Not After error.");
-
-       LogDebug("Get notAfter ASN1_TIME : " <<
-                        reinterpret_cast<char *>(timeafter->data));
-       return timeafter;
-}
-
-ASN1_TIME *Certificate::getNotBeforeTime() const
-{
-       auto timebefore = X509_get_notBefore(m_x509);
-
-       if (!timebefore)
-               VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
-                                         "Reading Not Before error.");
-
-       LogDebug("Get notBefore ASN1_TIME : " <<
-                        reinterpret_cast<char *>(timebefore->data));
-       return timebefore;
-}
-
-time_t Certificate::getNotAfter() const
-{
-       auto time = getNotAfterTime();
-       time_t output;
-
-       if (asn1TimeToTimeT(time, &output) == 0)
-               VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
-                                         "Converting ASN1_time to time_t error.");
-
-       return output;
-}
-
-time_t Certificate::getNotBefore() const
-{
-       auto time = getNotBeforeTime();
-       time_t output;
-
-       if (asn1TimeToTimeT(time, &output) == 0)
-               VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
-                                         "Converting ASN1_time to time_t error.");
-
-       return output;
-}
-
-bool Certificate::isRootCert()
-{
-       // based on that root certificate has the same subject as issuer name
-       return isSignedBy(this->shared_from_this());
-}
-
-long Certificate::getVersion() const
-{
-       return X509_get_version(m_x509);
-}
-
-std::string Certificate::getSerialNumberString() const
-{
-       ASN1_INTEGER *ai = X509_get_serialNumber(m_x509);
-
-       if (!ai)
-               VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
-                                         "Error in X509_get_serialNumber");
-
-       std::stringstream stream;
-       stream << std::hex << std::setfill('0');
-
-       if (ai->type == V_ASN1_NEG_INTEGER) {
-               stream << "(Negetive) ";
-       }
-
-       for (int i = 0; i < ai->length; ++i) {
-               stream << std::setw(2) << (int)ai->data[i] << ":";
-       }
-
-       std::string data = stream.str();
-
-       if (!data.empty()) {
-               data.erase(--data.end());
-       }
-
-       return data;
-}
-
-std::string Certificate::getKeyUsageString() const
-{
-       // Extensions were defined in RFC 3280
-       const char *usage[] = {
-               "digitalSignature",
-               "nonRepudiation",
-               "keyEncipherment",
-               "dataEncipherment",
-               "keyAgreement",
-               "keyCertSign",
-               "cRLSign",
-               "encipherOnly",
-               "decipherOnly"
-       };
-       int crit = -1;
-       int idx = -1;
-       ASN1_BIT_STRING *keyUsage = (ASN1_BIT_STRING *)
-                                                               X509_get_ext_d2i(m_x509, NID_key_usage, &crit, &idx);
-       std::stringstream stream;
-
-       for (int i = 0; i < 9; ++i) {
-               if (ASN1_BIT_STRING_get_bit(keyUsage, i)) {
-                       stream << usage[i] << ",";
-               }
-       }
-
-       std::string result = stream.str();
-
-       if (!result.empty()) {
-               result.erase(--result.end());
-       }
-
-       return result;
-}
-
-std::string Certificate::getSignatureAlgorithmString() const
-{
-       std::unique_ptr<BIO, std::function<int(BIO *)>>
-                       b(BIO_new(BIO_s_mem()), BIO_free);
-
-       if (!b.get())
-               VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
-                                         "Error in BIO_new");
-
-       if (i2a_ASN1_OBJECT(b.get(), m_x509->cert_info->signature->algorithm) < 0)
-               VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
-                                         "Error in i2a_ASN1_OBJECT");
-
-       BUF_MEM *bptr = 0;
-       BIO_get_mem_ptr(b.get(), &bptr);
-
-       if (bptr == 0)
-               VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
-                                         "Error in BIO_get_mem_ptr");
-
-       std::string result(bptr->data, bptr->length);
-       return result;
-}
-
-std::string Certificate::getPublicKeyString() const
-{
-       std::unique_ptr<BIO, std::function<int(BIO *)>>
-                       b(BIO_new(BIO_s_mem()), BIO_free);
-
-       if (!b.get())
-               VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
-                                         "Error in BIO_new");
-
-       EVP_PKEY *pkey = X509_get_pubkey(m_x509);
-
-       if (!pkey)
-               VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
-                                         "Error in X509_get_pubkey");
-
-       EVP_PKEY_print_public(b.get(), pkey, 16, NULL);
-       EVP_PKEY_free(pkey);
-       BUF_MEM *bptr = 0;
-       BIO_get_mem_ptr(b.get(), &bptr);
-
-       if (bptr == 0)
-               VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
-                                         "Error in BIO_get_mem_ptr");
-
-       std::string result(bptr->data, bptr->length);
-       return result;
-}
-
-void Certificate::getPublicKeyDER(unsigned char **pubkey, size_t *len) const
-{
-       if (pubkey == NULL || len == NULL)
-               VcoreThrowMsg(Certificate::Exception::WrongParamError, "Wrong parameter");
-
-       EVP_PKEY *pkey = X509_get_pubkey(m_x509);
-       unsigned char *_pubkey = NULL;
-       int _len = i2d_PUBKEY(pkey, &_pubkey);
-       EVP_PKEY_free(pkey);
-
-       if (_pubkey == NULL || _len == 0)
-               VcoreThrowMsg(Certificate::Exception::OpensslInternalError,
-                                         "Error in i2d_PUBKEY");
-
-       *pubkey = _pubkey;
-       *len = static_cast<size_t>(_len);
-}
-
-std::string Certificate::getPublicKeyAlgoString() const
-{
-       return std::string(static_cast<const char *>(
-                                                  OBJ_nid2ln(OBJ_obj2nid(m_x509->cert_info->key->algor->algorithm))));
-}
-
-int Certificate::isCA() const
-{
-       return X509_check_ca(m_x509);
-}
-
-std::string Certificate::FingerprintToColonHex(
-       const Certificate::Fingerprint &fingerprint)
-{
-       std::string outString;
-       char buff[8];
-
-       for (size_t i = 0; i < fingerprint.size(); ++i) {
-               snprintf(buff,
-                                sizeof(buff),
-                                "%02X:",
-                                static_cast<unsigned int>(fingerprint[i]));
-               outString += buff;
-       }
-
-       // remove trailing ":"
-       outString.erase(outString.end() - 1);
-       return outString;
-}
-
-} //  namespace ValidationCore
diff --git a/vcore/vcore/Certificate.h b/vcore/vcore/Certificate.h
deleted file mode 100644 (file)
index 64673ab..0000000
+++ /dev/null
@@ -1,180 +0,0 @@
-/*
- * 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        Certificate.h
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.1
- * @brief       Certificate class
- */
-#pragma once
-
-#include <list>
-#include <set>
-#include <string>
-#include <vector>
-#include <ctime>
-#include <memory>
-
-#include <openssl/x509.h>
-
-#include "vcore/exception.h"
-
-extern "C" {
-       struct x509_st;
-       typedef struct x509_st X509;
-       struct X509_name_st;
-       typedef struct X509_name_st X509_NAME;
-}
-
-namespace ValidationCore {
-
-class Certificate;
-
-typedef std::shared_ptr<Certificate> CertificatePtr;
-typedef std::list<CertificatePtr> CertificateList;
-
-class Certificate : public std::enable_shared_from_this<Certificate> {
-public:
-       class Exception {
-       public:
-               VCORE_DECLARE_EXCEPTION_TYPE(ValidationCore::Exception, Base);
-               VCORE_DECLARE_EXCEPTION_TYPE(Base, OpensslInternalError);
-               VCORE_DECLARE_EXCEPTION_TYPE(Base, Base64Error);
-               VCORE_DECLARE_EXCEPTION_TYPE(Base, WrongParamError);
-               VCORE_DECLARE_EXCEPTION_TYPE(Base, InternalError);
-       };
-
-       typedef std::vector<unsigned char> Fingerprint;
-
-       // ascii string
-       typedef std::string AltName;
-       typedef std::set<AltName> AltNameSet;
-
-       enum FingerprintType {
-               FINGERPRINT_MD5,
-               FINGERPRINT_SHA1
-       };
-       enum FieldType {
-               FIELD_ISSUER,
-               FIELD_SUBJECT
-       };
-
-       enum FormType {
-               FORM_DER,
-               FORM_BASE64
-       };
-
-       static CertificatePtr createFromFile(const std::string &location);
-
-       explicit Certificate(X509 *cert);
-
-       explicit Certificate(const std::string &data,
-                                                FormType form = FORM_DER);
-
-       ~Certificate();
-
-       // It returns pointer to internal structure!
-       // Do not free this pointer!
-       X509 *getX509(void) const;
-
-       std::string getDER(void) const;
-
-       std::string getBase64(void) const;
-
-       // This const is cheating here because you have no
-       // guarantee that X509_get_subject_name will not
-       // change X509 object.
-       bool isSignedBy(const CertificatePtr &parent) const;
-
-       Fingerprint getFingerprint(FingerprintType type) const;
-
-       // getName uses deprecated functions. Usage is strongly discouraged.
-       // utf8 string
-       std::string getOneLine(FieldType type = FIELD_SUBJECT) const;
-       std::string getCommonName(FieldType type = FIELD_SUBJECT) const;
-       std::string getCountryName(FieldType type = FIELD_SUBJECT) const;
-       std::string getStateOrProvinceName(FieldType type = FIELD_SUBJECT) const;
-       std::string getLocalityName(FieldType type = FIELD_SUBJECT) const;
-       std::string getOrganizationName(FieldType type = FIELD_SUBJECT) const;
-       std::string getOrganizationalUnitName(FieldType type = FIELD_SUBJECT) const;
-       std::string getEmailAddres(FieldType type = FIELD_SUBJECT) const;
-
-       std::string getNameHash(FieldType type = FIELD_SUBJECT) const;
-
-       // TODO: UID type is unsigned char. std::string should be changed to unsigned char container
-       std::string getUID(FieldType type = FIELD_SUBJECT) const;
-       std::string getOCSPURL() const;
-
-
-
-       // Openssl supports 9 types of alternative name filed.
-       // 4 of them are "string similar" types so it is possible
-       // to create more generic function.
-       AltNameSet getAlternativeNameDNS() const;
-
-       time_t getNotAfter() const;
-
-       time_t getNotBefore() const;
-
-       ASN1_TIME *getNotAfterTime() const;
-
-       ASN1_TIME *getNotBeforeTime() const;
-
-       /**
-        * @brief This is convenient function.
-        *
-        * @details It can't be const function (however it doesn't change internal
-        * object). For details see #isSignedBy() function description.
-        */
-       bool isRootCert();
-
-       /**
-        * @brief Gets list of CRL distribution's points URIs
-        */
-       std::list<std::string> getCrlUris() const;
-
-       long getVersion() const;
-
-       // utf8 string
-       std::string getSerialNumberString() const;
-       std::string getKeyUsageString() const;
-       std::string getSignatureAlgorithmString() const;
-       std::string getPublicKeyAlgoString() const;
-       std::string getPublicKeyString() const;
-       void getPublicKeyDER(unsigned char **pubkey, size_t *len) const;
-
-       /*
-        * 0 - not CA
-        * 1 - CA
-        * 2 - deprecated and not used
-        * 3 - older version of CA
-        * 4 - older version of CA
-        * 5 - netscape CA
-        */
-       int isCA() const;
-
-       static std::string FingerprintToColonHex(
-               const Fingerprint &fingerprint);
-
-protected:
-       X509_NAME *getX509Name(FieldType type) const;
-
-       // utf8 string
-       std::string getField(FieldType type, int fieldNid) const;
-
-       X509 *m_x509;
-};
-} // namespace ValidationCore
diff --git a/vcore/vcore/CertificateCollection.cpp b/vcore/vcore/CertificateCollection.cpp
deleted file mode 100644 (file)
index f7734a3..0000000
+++ /dev/null
@@ -1,334 +0,0 @@
-/*
- * 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        CertificateCollection.cpp
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @author      Kyungwook Tak (k.tak@samsung.com)
- * @version     1.0
- * @brief       Handles certificate chain, make it complete and sort
- */
-
-#include <stdlib.h>
-#include <string.h>
-#include <stddef.h>
-#include <unistd.h>
-#include <dirent.h>
-
-#include <memory>
-#include <functional>
-
-#include <openssl/pem.h>
-#include <openssl/x509.h>
-
-#include <cert-svc/cinstance.h>
-#include <cert-svc/ccert.h>
-#include <cert-svc/cprimitives.h>
-
-#include <dpl/log/log.h>
-
-#include "vcore/Base64.h"
-
-#include "vcore/CertificateCollection.h"
-
-namespace {
-
-using namespace ValidationCore;
-
-inline std::string toBinaryString(int data)
-{
-       char buffer[sizeof(int)];
-       memcpy(buffer, &data, sizeof(int));
-       return std::string(buffer, sizeof(int));
-}
-
-bool isHashMatchedName(const std::string &name, const std::string &hash)
-{
-       if (name.compare(0, 8, hash) != 0)
-               return false;
-
-       return true;
-}
-
-bool isHashMatchedFile(const std::string &path, const std::string &hash)
-{
-       CertificatePtr certPtr = Certificate::createFromFile(path);
-       std::string name = certPtr->getNameHash(Certificate::FIELD_SUBJECT);
-       return isHashMatchedName(name, hash);
-}
-
-CertificatePtr searchCert(const std::string &dir, const CertificatePtr &certPtr, bool withHash)
-{
-       try {
-               std::string hash = certPtr->getNameHash(Certificate::FIELD_ISSUER);
-               std::unique_ptr<DIR, std::function<int(DIR *)>> dp(::opendir(dir.c_str()), ::closedir);
-
-               if (dp.get() == NULL) {
-                       LogError("Failed open dir[" << dir << "]");
-                       return CertificatePtr();
-               }
-
-               size_t len = offsetof(struct dirent, d_name) + pathconf(dir.c_str(), _PC_NAME_MAX) + 1;
-               std::unique_ptr<struct dirent, std::function<void(void *)>>
-                               pEntry(static_cast<struct dirent *>(::malloc(len)), ::free);
-               struct dirent *dirp = NULL;
-               int ret = 0;
-
-               while ((ret = readdir_r(dp.get(), pEntry.get(), &dirp)) == 0 && dirp) {
-                       if (dirp->d_type == DT_DIR)
-                               continue;
-
-                       std::string candidatePath(dir);
-                       candidatePath += "/";
-                       candidatePath += dirp->d_name;
-
-                       if (withHash) {
-                               if (!isHashMatchedName(dirp->d_name, hash))
-                                       continue;
-                       } else {
-                               if (!isHashMatchedFile(candidatePath, hash))
-                                       continue;
-                       }
-
-                       LogDebug("Found hash matched file! : " << candidatePath);
-                       CertificatePtr candidate = Certificate::createFromFile(candidatePath);
-
-                       if (candidate->getOneLine().compare(certPtr->getOneLine(Certificate::FIELD_ISSUER)) != 0)
-                               continue;
-
-                       return candidate;
-               }
-
-               if (ret != 0) {
-                       LogError("readdir_r error. ret[" << ret << "]");
-                       return CertificatePtr();
-               }
-
-               LogWarning("cert not found by hash[" << hash << "]");
-               return CertificatePtr();
-       } catch (const Certificate::Exception::Base &e) {
-               VcoreThrowMsg(
-                       CertificateCollection::Exception::CertificateError,
-                       "Error in handling certificate : " << e.DumpToString());
-       } catch (const std::exception &e) {
-               VcoreThrowMsg(
-                       CertificateCollection::Exception::InternalError,
-                       "std::exception occured : " << e.what());
-       } catch (...) {
-               VcoreThrowMsg(
-                       CertificateCollection::Exception::InternalError,
-                       "Unknown exception in CertificateCollection.");
-       }
-}
-
-CertificatePtr getIssuerCertFromStore(const CertificatePtr &certPtr)
-{
-       LogDebug("Start to get issuer from store.");
-       CertificatePtr found = searchCert(TZ_SYS_CA_CERTS_TIZEN, certPtr, false);
-
-       if (found.get() != NULL) {
-               LogDebug("Found issuer cert in tizen root CA dir");
-               return found;
-       }
-
-       return searchCert(TZ_SYS_CA_CERTS, certPtr, true);
-}
-
-} // namespace
-
-namespace ValidationCore {
-
-CertificateCollection::CertificateCollection()
-       : m_collectionStatus(COLLECTION_UNSORTED)
-{}
-
-void CertificateCollection::clear(void)
-{
-       m_collectionStatus = COLLECTION_UNSORTED;
-       m_certList.clear();
-}
-
-void CertificateCollection::load(const CertificateList &certList)
-{
-       m_collectionStatus = COLLECTION_UNSORTED;
-       std::copy(certList.begin(),
-                         certList.end(),
-                         std::back_inserter(m_certList));
-}
-
-std::string CertificateCollection::toBase64String() const
-{
-       std::ostringstream output;
-       int certNum = m_certList.size();
-       output << toBinaryString(certNum);
-
-       for (auto i = m_certList.begin(); i != m_certList.end(); ++i) {
-               std::string derCert = (*i)->getDER();
-               output << toBinaryString(derCert.size());
-               output << derCert;
-       }
-
-       Base64Encoder base64;
-       base64.reset();
-       base64.append(output.str());
-       base64.finalize();
-       return base64.get();
-}
-
-CertificateList CertificateCollection::getCertificateList() const
-{
-       return m_certList;
-}
-
-bool CertificateCollection::isChain() const
-{
-       if (COLLECTION_SORTED != m_collectionStatus)
-               VcoreThrowMsg(CertificateCollection::Exception::WrongUsage,
-                                         "You must sort certificate first");
-
-       return (COLLECTION_SORTED == m_collectionStatus) ? true : false;
-}
-
-bool CertificateCollection::sort()
-{
-       if (COLLECTION_UNSORTED == m_collectionStatus) {
-               sortCollection();
-       }
-
-       return (COLLECTION_SORTED == m_collectionStatus) ? true : false;
-}
-
-CertificateList CertificateCollection::getChain() const
-{
-       if (COLLECTION_SORTED != m_collectionStatus)
-               VcoreThrowMsg(CertificateCollection::Exception::WrongUsage,
-                                         "You must sort certificates first");
-
-       return m_certList;
-}
-
-void CertificateCollection::sortCollection()
-{
-       // sorting is not necessary
-       if (m_certList.empty()) {
-               m_collectionStatus = COLLECTION_SORTED;
-               return;
-       }
-
-       CertificateList sorted;
-       std::map<std::string, CertificatePtr> subTransl;
-       std::map<std::string, CertificatePtr> issTransl;
-
-       // Sort all certificate by subject
-       for (auto it = m_certList.begin(); it != m_certList.end(); ++it) {
-               subTransl.insert(std::make_pair((*it)->getOneLine(), (*it)));
-       }
-
-       // We need one start certificate
-       sorted.push_back(subTransl.begin()->second);
-       subTransl.erase(subTransl.begin());
-
-       // Get the issuer from front certificate and find certificate with this subject in subTransl.
-       // Add this certificate to the front.
-       while (!subTransl.empty()) {
-               std::string issuer = sorted.back()->getOneLine(Certificate::FIELD_ISSUER);
-               auto it = subTransl.find(issuer);
-
-               if (it == subTransl.end()) {
-                       break;
-               }
-
-               sorted.push_back(it->second);
-               subTransl.erase(it);
-       }
-
-       // Sort all certificates by issuer
-       for (auto it = subTransl.begin(); it != subTransl.end(); ++it) {
-               issTransl.insert(std::make_pair(it->second->getOneLine(Certificate::FIELD_ISSUER), it->second));
-       }
-
-       // Get the subject from last certificate and find certificate with such issuer in issTransl.
-       // Add this certificate at end.
-       while (!issTransl.empty()) {
-               std::string sub = sorted.front()->getOneLine();
-               auto it = issTransl.find(sub);
-
-               if (it == issTransl.end()) {
-                       break;
-               }
-
-               sorted.push_front(it->second);
-               issTransl.erase(it);
-       }
-
-       if (!issTransl.empty()) {
-               LogWarning("Certificates don't form a valid chain.");
-               m_collectionStatus = COLLECTION_CHAIN_BROKEN;
-               return;
-       }
-
-       m_collectionStatus = COLLECTION_SORTED;
-       m_certList = sorted;
-}
-
-/*
- *  Precondition : cert list sorted and has more than one cert
- */
-bool CertificateCollection::completeCertificateChain()
-{
-       CertificatePtr last = m_certList.back();
-
-       if (last->isRootCert())
-               return true;
-
-       CertificatePtr rootCert = getIssuerCertFromStore(last);
-
-       if (!rootCert.get())
-               return false;
-
-       if (!rootCert->isRootCert())
-               return false;
-
-       m_certList.push_back(rootCert);
-       return true;
-}
-
-size_t CertificateCollection::size() const
-{
-       return m_certList.size();
-}
-
-bool CertificateCollection::empty() const
-{
-       return m_certList.empty();
-}
-
-CertificateCollection::const_iterator CertificateCollection::begin() const
-{
-       return m_certList.begin();
-}
-
-CertificateCollection::const_iterator CertificateCollection::end() const
-{
-       return m_certList.end();
-}
-
-CertificatePtr CertificateCollection::back() const
-{
-       return m_certList.back();
-}
-
-} // namespace ValidationCore
-
diff --git a/vcore/vcore/CertificateCollection.h b/vcore/vcore/CertificateCollection.h
deleted file mode 100644 (file)
index 7ec3186..0000000
+++ /dev/null
@@ -1,172 +0,0 @@
-/*
- * Copyright (c) 2011 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        CertificateCollection.h
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     0.1
- * @brief
- */
-#ifndef _VALIDATION_CORE_CERTIFICATECOLLECTION_H_
-#define _VALIDATION_CORE_CERTIFICATECOLLECTION_H_
-
-#include <list>
-#include <string>
-#include <map>
-
-#include <vcore/exception.h>
-
-#include <vcore/Certificate.h>
-
-namespace ValidationCore {
-/*
- * This class is used to store Certificate Chain.
- * It could serialize chain to std::string in base64 form.
- * It could read chain written in base64 form.
- * It could check if collection creates certificate chain.
- */
-
-class CertificateCollection {
-public:
-       class Exception {
-       public:
-               VCORE_DECLARE_EXCEPTION_TYPE(ValidationCore::Exception, Base);
-               VCORE_DECLARE_EXCEPTION_TYPE(Base, InternalError);
-               VCORE_DECLARE_EXCEPTION_TYPE(Base, CertificateError);
-               VCORE_DECLARE_EXCEPTION_TYPE(Base, WrongUsage);
-       };
-
-       CertificateCollection();
-
-       typedef CertificateList::const_iterator const_iterator;
-
-       /*
-        * Remove all certificates from collection.
-        */
-       void clear();
-
-       /*
-        * In current implemenation this function MUST success.
-        *
-        * This function will add new certificate to collection.
-        * This function DOES NOT clean collection.
-        */
-       void load(const CertificateList &certList);
-
-       /*
-        * This function will return all certificates from
-        * collection encoded in base64 format.
-        */
-       std::string toBase64String() const;
-
-       /*
-        * This will return all certificate from collection.
-        */
-       CertificateList getCertificateList() const;
-
-       /*
-        * This function will return true if certificates
-        * in in this structure were sorted and create
-        * certificate chain.
-
-        * Note: You MUST sort certificates first.
-        */
-       bool isChain() const;
-
-       /*
-        * This function will return true if all certificate are
-        * able to create certificate chain.
-        *
-        * This function will sort certificates if collection
-        * is not sorted.
-        *
-        * Note: This function will make all iterators invalid.
-        */
-       bool sort();
-
-       /*
-        * Precondition : cert list sorted and has more than on cert.
-        * This function add root cert in cert list to complete cert chain
-        */
-       bool completeCertificateChain();
-
-       /*
-        * This function will return Certificate chain.
-        *
-        * First certificate on the list is EndEntity certificate.
-        *
-        * Last certificate on the list is RootCA certificate or
-        * CA certificate if RootCA is not present.
-        *
-        * Note: You MUST sort certificates first and
-        * check if certificates creates proper chain.
-        */
-       CertificateList getChain() const;
-
-       /*
-        * It returns size of certificate collection.
-        */
-       size_t size() const;
-
-       /*
-        * Return true if collection is empty.
-        */
-       bool empty() const;
-
-       /*
-        * This will return end iterator to internal collection.
-        *
-        * Note: this iterator will lose validity if you call non const
-        * method on CertificateCollection class.
-        */
-       const_iterator begin() const;
-
-       /*
-        * This will return end iterator to internal collection.
-        *
-        * Note: this iterator will lose validity if you call non const
-        * method on CertificateCollection class.
-        */
-       const_iterator end() const;
-
-       /*
-        * This function will return the last certificate from collection.
-        *
-        * Note: There is no point to call this function if certificate
-        * collection is not sorted!
-        */
-       CertificatePtr back() const;
-
-protected:
-       void sortCollection(void);
-
-       enum CollectionStatus {
-               // Certificate collection are not sorted in any way
-               COLLECTION_UNSORTED,
-               // Certificate collection creates certificate chain
-               COLLECTION_SORTED,
-               // Cerfificate collection is not able to create certificate chain
-               COLLECTION_CHAIN_BROKEN,
-       };
-
-       CollectionStatus m_collectionStatus;
-       CertificateList m_certList;
-};
-
-typedef std::list<CertificateCollection> CertificateCollectionList;
-
-} // namespace ValidationCore
-
-#endif // _VALIDATION_CORE_CERTIFICATECHAIN_H_
diff --git a/vcore/vcore/CertificateConfigReader.cpp b/vcore/vcore/CertificateConfigReader.cpp
deleted file mode 100644 (file)
index 856641f..0000000
+++ /dev/null
@@ -1,168 +0,0 @@
-/*
- * Copyright (c) 2011 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
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief
- */
-
-#include <vcore/CertificateConfigReader.h>
-
-#include <dpl/assert.h>
-
-#include <cstdlib>
-
-namespace {
-const std::string XML_EMPTY_NAMESPACE = "";
-
-const std::string TOKEN_CERTIFICATE_SET = "CertificateSet";
-const std::string TOKEN_CERTIFICATE_DOMAIN = "CertificateDomain";
-const std::string TOKEN_FINGERPRINT_SHA1 = "FingerprintSHA1";
-
-const std::string TOKEN_ATTR_NAME = "name";
-const std::string TOKEN_VALUE_TIZEN_DEVELOPER = "tizen-developer";
-const std::string TOKEN_VALUE_TIZEN_TEST = "tizen-test";
-const std::string TOKEN_VALUE_TIZEN_VERIFY = "tizen-verify";
-const std::string TOKEN_VALUE_TIZEN_STORE = "tizen-store";
-const std::string TOKEN_VALUE_TIZEN_REVOKED = "tizen-revoked";
-const std::string TOKEN_VALUE_VISIBILITY_PUBLIC = "tizen-public";
-const std::string TOKEN_VALUE_VISIBILITY_PARTNER = "tizen-partner";
-const std::string TOKEN_VALUE_VISIBILITY_PLATFORM = "tizen-platform";
-
-int hexCharToInt(char c)
-{
-       if (c >= 'a' && c <= 'f') {
-               return 10 + static_cast<int>(c) - 'a';
-       }
-
-       if (c >= 'A' && c <= 'F') {
-               return 10 + static_cast<int>(c) - 'A';
-       }
-
-       if (c >= '0' && c <= '9') {
-               return static_cast<int>(c) - '0';
-       }
-
-       return c;
-}
-} // anonymous namespace
-
-namespace ValidationCore {
-CertificateConfigReader::CertificateConfigReader()
-       : m_certificateDomain(0)
-       , m_parserSchema(this)
-{
-       m_parserSchema.addBeginTagCallback(
-               TOKEN_CERTIFICATE_SET,
-               XML_EMPTY_NAMESPACE,
-               &CertificateConfigReader::blankFunction);
-       m_parserSchema.addBeginTagCallback(
-               TOKEN_CERTIFICATE_DOMAIN,
-               XML_EMPTY_NAMESPACE,
-               &CertificateConfigReader::tokenCertificateDomain);
-       m_parserSchema.addBeginTagCallback(
-               TOKEN_FINGERPRINT_SHA1,
-               XML_EMPTY_NAMESPACE,
-               &CertificateConfigReader::blankFunction);
-       m_parserSchema.addEndTagCallback(
-               TOKEN_CERTIFICATE_SET,
-               XML_EMPTY_NAMESPACE,
-               &CertificateConfigReader::blankFunction);
-       m_parserSchema.addEndTagCallback(
-               TOKEN_CERTIFICATE_DOMAIN,
-               XML_EMPTY_NAMESPACE,
-               &CertificateConfigReader::blankFunction);
-       m_parserSchema.addEndTagCallback(
-               TOKEN_FINGERPRINT_SHA1,
-               XML_EMPTY_NAMESPACE,
-               &CertificateConfigReader::tokenEndFingerprintSHA1);
-}
-
-void CertificateConfigReader::initialize(
-       const std::string &file,
-       const std::string &scheme)
-{
-       m_parserSchema.initialize(file, true, SaxReader::VALIDATION_XMLSCHEME, scheme);
-}
-
-void CertificateConfigReader::read(CertificateIdentifier &identificator)
-{
-       m_parserSchema.read(identificator);
-}
-
-void CertificateConfigReader::blankFunction(CertificateIdentifier &)
-{
-}
-
-void CertificateConfigReader::tokenCertificateDomain(CertificateIdentifier &)
-{
-       std::string name = m_parserSchema.getReader().attribute(TOKEN_ATTR_NAME);
-
-       if (name.empty()) {
-               VcoreThrowMsg(CertificateConfigReader::Exception::InvalidFile,
-                                         "Invalid fingerprint file. Domain name is mandatory");
-       } else if (name == TOKEN_VALUE_TIZEN_DEVELOPER) {
-               m_certificateDomain = CertStoreId::TIZEN_DEVELOPER;
-       } else if (name == TOKEN_VALUE_TIZEN_TEST) {
-               m_certificateDomain = CertStoreId::TIZEN_TEST;
-       } else if (name == TOKEN_VALUE_TIZEN_VERIFY) {
-               m_certificateDomain = CertStoreId::TIZEN_VERIFY;
-       } else if (name == TOKEN_VALUE_TIZEN_STORE) {
-               m_certificateDomain = CertStoreId::TIZEN_STORE;
-       } else if (name == TOKEN_VALUE_TIZEN_REVOKED) {
-               m_certificateDomain = CertStoreId::TIZEN_REVOKED;
-       } else if (name == TOKEN_VALUE_VISIBILITY_PUBLIC) {
-               m_certificateDomain = CertStoreId::VIS_PUBLIC;
-       } else if (name == TOKEN_VALUE_VISIBILITY_PARTNER) {
-               m_certificateDomain = CertStoreId::VIS_PARTNER;
-       } else if (name == TOKEN_VALUE_VISIBILITY_PLATFORM) {
-               m_certificateDomain = CertStoreId::VIS_PLATFORM;
-       } else {
-               m_certificateDomain = 0;
-       }
-}
-
-void CertificateConfigReader::tokenEndFingerprintSHA1(
-       CertificateIdentifier &identificator)
-{
-       std::string text = m_parserSchema.getText();
-       text += ":"; // add guard at the end of fingerprint
-       Certificate::Fingerprint fingerprint;
-       int s = 0;
-       int byteDescLen = 0;
-
-       for (size_t i = 0; i < text.size(); ++i) {
-               if (isxdigit(text[i])) {
-                       s <<= 4;
-                       s += hexCharToInt(text[i]);
-                       byteDescLen++;
-
-                       if (byteDescLen > 2) {
-                               Assert(0 && "Unsupported fingerprint format in xml file.");
-                       }
-               } else if (text[i] == ':') {
-                       fingerprint.push_back(static_cast<unsigned char>(s));
-                       s = 0;
-                       byteDescLen = 0;
-               } else {
-                       Assert(0 && "Unussported fingerprint format in xml file.");
-               }
-       }
-
-       identificator.add(fingerprint, m_certificateDomain);
-}
-} // namespace ValidationCore
diff --git a/vcore/vcore/CertificateConfigReader.h b/vcore/vcore/CertificateConfigReader.h
deleted file mode 100644 (file)
index 0d31934..0000000
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * Copyright (c) 2011 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        CertificateConfigReader.h
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief
- */
-#ifndef _VALIDATION_CORE_CERTIFICATE_CONFIG_READER_H_
-#define _VALIDATION_CORE_CERTIFICATE_CONFIG_READER_H_
-
-#include <string>
-
-#include <vcore/CertificateIdentifier.h>
-#include <vcore/CertStoreType.h>
-#include <vcore/ParserSchema.h>
-#include <vcore/exception.h>
-
-namespace ValidationCore {
-class CertificateConfigReader {
-public:
-       class Exception {
-       public:
-               VCORE_DECLARE_EXCEPTION_TYPE(ValidationCore::Exception, Base);
-               VCORE_DECLARE_EXCEPTION_TYPE(Base, InvalidFile);
-       };
-
-       CertificateConfigReader();
-
-       void initialize(const std::string &file, const std::string &scheme);
-       void read(CertificateIdentifier &identificator);
-
-private:
-       void blankFunction(CertificateIdentifier &);
-       void tokenCertificateDomain(CertificateIdentifier &identificator);
-       void tokenEndFingerprintSHA1(CertificateIdentifier &identificator);
-
-       CertStoreId::Type m_certificateDomain;
-       ParserSchema<CertificateConfigReader, CertificateIdentifier> m_parserSchema;
-};
-} // namespace ValidationCore
-
-#endif // _VALIDATION_CORE_CERTIFICATE_CONFIG_READER_H_
diff --git a/vcore/vcore/CertificateIdentifier.h b/vcore/vcore/CertificateIdentifier.h
deleted file mode 100644 (file)
index adf05c7..0000000
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Copyright (c) 2011 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
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief
- */
-#ifndef \
-    _WRT_ENGINE_SRC_INSTALLER_CORE_VALIDATION_CORE_CERTIFICATEIDENTIFICATOR_H_
-#define \
-       _WRT_ENGINE_SRC_INSTALLER_CORE_VALIDATION_CORE_CERTIFICATEIDENTIFICATOR_H_
-
-#include <map>
-
-#include <vcore/Certificate.h>
-#include <vcore/CertStoreType.h>
-
-namespace ValidationCore {
-class CertificateIdentifier {
-public:
-       typedef std::map<Certificate::Fingerprint, CertStoreId::Set> FingerPrintMap;
-
-       CertificateIdentifier() = default;
-       ~CertificateIdentifier() = default;
-
-       CertificateIdentifier(const CertificateIdentifier &) = delete;
-       CertificateIdentifier &operator=(const CertificateIdentifier &) = delete;
-       CertificateIdentifier(CertificateIdentifier &&) = delete;
-       CertificateIdentifier &operator=(CertificateIdentifier &&) = delete;
-
-       void add(const Certificate::Fingerprint &fingerprint,
-                        CertStoreId::Type domain)
-       {
-               fingerPrintMap[fingerprint].add(domain);
-       }
-
-       CertStoreId::Set find(const Certificate::Fingerprint &fingerprint) const
-       {
-               FingerPrintMap::const_iterator iter = fingerPrintMap.find(fingerprint);
-
-               if (iter == fingerPrintMap.end()) {
-                       return CertStoreId::Set();
-               }
-
-               return iter->second;
-       }
-
-       CertStoreId::Set find(const CertificatePtr &certificate) const
-       {
-               return find(certificate->getFingerprint(Certificate::FINGERPRINT_SHA1));
-       }
-
-private:
-       FingerPrintMap fingerPrintMap;
-};
-} // namespace ValidationCore
-
-#endif // _WRT_ENGINE_SRC_INSTALLER_CORE_VALIDATION_CORE_CERTIFICATEIDENTIFICATOR_H_
diff --git a/vcore/vcore/CertificateLoader.cpp b/vcore/vcore/CertificateLoader.cpp
deleted file mode 100644 (file)
index 40c82b1..0000000
+++ /dev/null
@@ -1,131 +0,0 @@
-/*
- * Copyright (c) 2011 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.
- */
-#include <dpl/assert.h>
-#include <openssl/x509v3.h>
-#include <dpl/log/log.h>
-#include <openssl/ecdsa.h>
-#include <openssl/evp.h>
-
-#include <vcore/Base64.h>
-#include <vcore/CertificateLoader.h>
-
-namespace {
-const int MIN_RSA_KEY_LENGTH = 1024;
-} // namespace anonymous
-
-namespace ValidationCore {
-CertificateLoader::CertificateLoaderResult CertificateLoader::
-loadCertificateBasedOnExponentAndModulus(const std::string &m_modulus,
-               const std::string &m_exponent)
-{
-       (void) m_modulus;
-       (void) m_exponent;
-       LogError("Not implemented.");
-       return UNKNOWN_ERROR;
-}
-
-CertificateLoader::CertificateLoaderResult CertificateLoader::loadCertificate(
-       const std::string &storageName,
-       CertificateLoader::CertificateLoaderComparator *cmp)
-{
-       (void) storageName;
-       (void) cmp;
-       LogError("Not Implemented");
-       return UNKNOWN_ERROR;
-}
-
-CertificateLoader::CertificateLoaderResult CertificateLoader::
-loadCertificateBasedOnSubjectName(const std::string &subjectName)
-{
-       (void) subjectName;
-       LogError("Not implemented.");
-       return UNKNOWN_ERROR;
-}
-
-CertificateLoader::CertificateLoaderResult CertificateLoader::
-loadCertificateWithECKEY(const std::string &curveName,
-                                                const std::string &publicKey)
-{
-       (void) curveName;
-       (void) publicKey;
-       LogError("Not implemented.");
-       return UNKNOWN_ERROR;
-}
-
-CertificateLoader::CertificateLoaderResult CertificateLoader::loadCertificateFromRawData(
-       const std::string &rawData)
-{
-       VcoreTry {
-               m_certificatePtr = CertificatePtr(new Certificate(rawData, Certificate::FORM_BASE64));
-       } VcoreCatch(Certificate::Exception::Base) {
-               LogWarning("Error reading certificate by openssl.");
-               return UNKNOWN_ERROR;
-       }
-       // Check the key length if sig algorithm is RSA
-       EVP_PKEY *pKey = X509_get_pubkey(m_certificatePtr->getX509());
-
-       if (pKey != NULL) {
-               if (pKey->type == EVP_PKEY_RSA) {
-                       RSA *pRSA = pKey->pkey.rsa;
-
-                       if (pRSA) {
-                               int keyLength = RSA_size(pRSA);
-                               // key Length (modulus) is in bytes
-                               keyLength <<= 3;
-                               LogDebug("RSA key length: " << keyLength << " bits");
-
-                               if (keyLength < MIN_RSA_KEY_LENGTH) {
-                                       LogError("RSA key too short! Has only " << keyLength << " bits");
-                                       return CERTIFICATE_SECURITY_ERROR;
-                               }
-                       }
-               }
-       }
-
-       return NO_ERROR;
-}
-
-CertificateLoader::CertificateLoaderResult CertificateLoader::
-loadCertificateBasedOnDSAComponents(const std::string &strP,
-                                                                       const std::string &strQ,
-                                                                       const std::string &strG,
-                                                                       const std::string &strY,
-                                                                       const std::string &strJ,
-                                                                       const std::string &strSeed,
-                                                                       const std::string &strPGenCounter)
-{
-       (void) strP;
-       (void) strQ;
-       (void) strG;
-       (void) strY;
-       (void) strJ;
-       (void) strSeed;
-       (void) strPGenCounter;
-       LogError("Not implemented.");
-       return UNKNOWN_ERROR;
-}
-
-bool CertificateLoader::convertBase64NodeToBigNum(const std::string &strNode,
-               BIGNUM **ppBigNum)
-{
-       (void) strNode;
-       (void) ppBigNum;
-       LogError("Not implemented.");
-       return false;
-}
-
-} // namespace ValidationCore
-
diff --git a/vcore/vcore/CertificateLoader.h b/vcore/vcore/CertificateLoader.h
deleted file mode 100644 (file)
index d87ed7b..0000000
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * Copyright (c) 2011 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.
- */
-#ifndef _CERTIFICATELOADER_H_
-#define _CERTIFICATELOADER_H_
-
-#include <string>
-#include <string.h>
-
-#include <openssl/ssl.h>
-
-#include <vcore/Certificate.h>
-
-namespace ValidationCore {
-class CertificateLoader {
-public:
-       CertificateLoader() = default;
-       virtual ~CertificateLoader() = default;
-
-       CertificateLoader(const CertificateLoader &) = delete;
-       CertificateLoader &operator=(const CertificateLoader &) = delete;
-       CertificateLoader(CertificateLoader &&) = delete;
-       CertificateLoader &operator=(CertificateLoader &&) = delete;
-
-       class CertificateLoaderComparator {
-       public:
-               virtual bool compare(X509 *x509cert) = 0;
-               virtual ~CertificateLoaderComparator() = default;
-       };
-
-       enum CertificateLoaderResult {
-               NO_ERROR,
-               CERTIFICATE_NOT_FOUND,
-               UNSUPPORTED_CERTIFICATE_FIELD,
-               WRONG_ARGUMENTS,
-               CERTIFICATE_SECURITY_ERROR,                  //!< there are some issues with certificate security (i.e. key too short)
-               UNKNOWN_ERROR
-       };
-
-       CertificateLoaderResult loadCertificate(const std::string &storage,
-                                                                                       CertificateLoaderComparator *cmp);
-
-       CertificateLoaderResult loadCertificateBasedOnSubjectName(
-               const std::string &subjectName);
-       CertificateLoaderResult loadCertificateBasedOnExponentAndModulus(
-               const std::string &m_modulus,
-               const std::string  &m_exponent);
-       // KW     CertificateLoaderResult loadCertificateBasedOnIssuerName(const std::string &isserName,
-       // KW       const std::string &serialNumber);
-
-       CertificateLoaderResult loadCertificateFromRawData(
-               const std::string &rawData);
-
-       CertificateLoaderResult loadCertificateBasedOnDSAComponents(
-               const std::string &strP,
-               const std::string &strQ,
-               const std::string &strG,
-               const std::string &strY,
-               const std::string &strJ,
-               const std::string &strSeed,
-               const std::string &strPGenCounter);
-
-       CertificateLoaderResult loadCertificateWithECKEY(
-               const std::string &curveName,
-               const std::string &publicKey);
-
-       /**
-        * converts base64 encoded node to SSL bignum
-        * allocates mem on *ppBigNum, don't forget to free it later with BN_free!
-        * returns conversion status
-        */
-       static bool convertBase64NodeToBigNum(const std::string &strNode,
-                                                                                 BIGNUM **ppBigNum);
-
-       /*
-        * encodes SSL bignum into base64 octstring
-        * returns conversion status
-        */
-       // KW     static bool convertBigNumToBase64Node(const BIGNUM* pBigNum, std::string& strNode);
-
-       CertificatePtr getCertificatePtr() const
-       {
-               return m_certificatePtr;
-       }
-private:
-       CertificatePtr m_certificatePtr;
-};
-} // namespace ValidationCore
-
-#endif // _CERTIFICATELOADER_H_
diff --git a/vcore/vcore/Client.cpp b/vcore/vcore/Client.cpp
deleted file mode 100644 (file)
index d0f48ae..0000000
+++ /dev/null
@@ -1,674 +0,0 @@
-/**
- * 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     Client.cpp
- * @author   Madhan A K (madhan.ak@samsung.com)
- *           Kyungwook Tak (k.tak@samsung.com)
- * @version  1.0
- * @brief    cert-svc client interface for cert-server.
- */
-
-#include <sys/stat.h>
-#include <sys/un.h>
-#include <sys/types.h>
-#include <sys/socket.h>
-#include <errno.h>
-#include <unistd.h>
-#include <string.h>
-#include <stdlib.h>
-#include <memory>
-
-#include <dpl/log/log.h>
-
-#include <vcore/Client.h>
-
-namespace {
-
-void initialize_res_data(VcoreResponseData *pData)
-{
-       memset(pData->dataBlock, 0, VCORE_MAX_RECV_DATA_SIZE);
-       memset(pData->common_name, 0, VCORE_MAX_FILENAME_SIZE * 2 + 1);
-       pData->dataBlockLen = 0;
-       pData->certStatus = DISABLED;
-       pData->result = 0;
-       pData->isAliasUnique = 0;
-       pData->certList = NULL;
-       pData->certCount = 0;
-       pData->certBlockList = NULL;
-       pData->certBlockCount = 0;
-}
-
-void initialize_req_data(VcoreRequestData *pData)
-{
-       memset(pData->gname, 0, VCORE_MAX_FILENAME_SIZE + 1);
-       memset(pData->common_name, 0, VCORE_MAX_FILENAME_SIZE + 1);
-       memset(pData->private_key_gname, 0, VCORE_MAX_FILENAME_SIZE + 1);
-       memset(pData->associated_gname, 0, VCORE_MAX_FILENAME_SIZE + 1);
-       memset(pData->dataBlock, 0, VCORE_MAX_SEND_DATA_SIZE);
-       pData->certStatus = DISABLED;
-       pData->storeType = NONE_STORE;
-       pData->reqType = (VcoreRequestType) - 1;
-       pData->dataBlockLen = 0;
-       pData->is_root_app = -1;
-       pData->certType = INVALID_DATA;
-}
-
-CertSvcStoreCertList *createStoreListNode(VcoreCertResponseData *cert)
-{
-       if (cert == NULL)
-               return NULL;
-
-       CertSvcStoreCertList *node = (CertSvcStoreCertList *)malloc(sizeof(CertSvcStoreCertList));
-
-       if (node == NULL)
-               return NULL;
-
-       node->gname = strdup(cert->gname);
-       node->title = strdup(cert->title);
-       node->status = cert->status;
-       node->storeType = cert->storeType;
-       node->next = NULL;
-
-       if (node->gname == NULL || node->title == NULL) {
-               free(node->gname);
-               free(node->title);
-               free(node);
-               return NULL;
-       }
-
-       return node;
-}
-
-void destroyStoreList(CertSvcStoreCertList *list)
-{
-       while (list) {
-               CertSvcStoreCertList *next = list->next;
-               free(list);
-               list = next;
-       }
-}
-
-
-int _recv_fixed_lenghth(int sockfd, char *buff, int length)
-{
-       int offset = 0;
-       int remaining = length;
-       int read_len = 0;
-
-       while (remaining > 0) {
-               read_len = recv(sockfd, buff + offset, remaining, 0);
-
-               if (read_len <= 0)
-                       return offset;
-
-               remaining -= read_len;
-               offset += read_len;
-       }
-
-       return offset;
-}
-
-VcoreRequestData *set_request_data(
-       VcoreRequestType reqType,
-       CertStoreType storeType,
-       int is_root_app,
-       const char *pGroupName,
-       const char *common_name,
-       const char *private_key_gname,
-       const char *associated_gname,
-       const char *pData,
-       size_t dataLen,
-       CertType certType,
-       CertStatus certStatus)
-{
-       VcoreRequestData *pReqData = (VcoreRequestData *)malloc(sizeof(VcoreRequestData));
-
-       if (!pReqData) {
-               LogError("Failed to malloc VcoreRequestData");
-               return NULL;
-       }
-
-       initialize_req_data(pReqData);
-       pReqData->reqType = reqType;
-       pReqData->storeType = (CertStoreType) storeType;
-       pReqData->dataBlockLen = dataLen;
-       pReqData->certType = certType;
-       pReqData->certStatus = certStatus;
-       pReqData->is_root_app = is_root_app;
-
-       if (pGroupName) {
-               if (strlen(pGroupName) > VCORE_MAX_FILENAME_SIZE) {
-                       LogError("The data name is too long");
-                       free(pReqData);
-                       return NULL;
-               }
-
-               strncpy(pReqData->gname, pGroupName, VCORE_MAX_FILENAME_SIZE);
-               pReqData->gname[strlen(pGroupName)] = '\0';
-       }
-
-       if (common_name) {
-               if (strlen(common_name) > VCORE_MAX_FILENAME_SIZE) {
-                       LogError("The length of the path specified is too long");
-                       free(pReqData);
-                       return NULL;
-               }
-
-               strncpy(pReqData->common_name, common_name, VCORE_MAX_FILENAME_SIZE);
-               pReqData->common_name[strlen(common_name)] = '\0';
-       }
-
-       if (private_key_gname) {
-               if (strlen(private_key_gname) > VCORE_MAX_FILENAME_SIZE) {
-                       LogError("The private key gname is too long");
-                       free(pReqData);
-                       return NULL;
-               }
-
-               strncpy(pReqData->private_key_gname, private_key_gname, VCORE_MAX_FILENAME_SIZE);
-               pReqData->private_key_gname[strlen(private_key_gname)] = '\0';
-       }
-
-       if (associated_gname) {
-               if (strlen(associated_gname) > VCORE_MAX_FILENAME_SIZE) {
-                       LogError("The associated gname is too long");
-                       free(pReqData);
-                       return NULL;
-               }
-
-               strncpy(pReqData->associated_gname, associated_gname, VCORE_MAX_FILENAME_SIZE);
-               pReqData->associated_gname[strlen(associated_gname)] = '\0';
-       }
-
-       if (dataLen != 0 && pData != NULL) {
-               if (dataLen > VCORE_MAX_SEND_DATA_SIZE) {
-                       LogError("The data length is too long : " << dataLen);
-                       free(pReqData);
-                       return NULL;
-               }
-
-               memcpy(pReqData->dataBlock, pData, dataLen);
-       }
-
-       return pReqData;
-}
-
-VcoreResponseData cert_svc_client_comm(VcoreRequestData *pClientData)
-{
-       int sockfd = 0;
-       int clientLen = 0;
-       int tempSockLen = 0;
-       int read_len = 0;
-       size_t i = 0;
-       struct sockaddr_un clientaddr;
-       VcoreResponseData recvData;
-       initialize_res_data(&recvData);
-
-       if ((sockfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) {
-               LogError("Error in function socket()..");
-               recvData.result = VCORE_SOCKET_ERROR;
-               goto Error_exit;
-       }
-
-       tempSockLen = strlen(VCORE_SOCK_PATH);
-       bzero(&clientaddr, sizeof(clientaddr));
-       clientaddr.sun_family = AF_UNIX;
-       strncpy(clientaddr.sun_path, VCORE_SOCK_PATH, tempSockLen);
-       clientaddr.sun_path[tempSockLen] = '\0';
-       clientLen = sizeof(clientaddr);
-       struct timeval timeout;
-       timeout.tv_sec = 10;
-       timeout.tv_usec = 0;
-
-       if (setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, (char *)&timeout, sizeof(timeout)) < 0) {
-               LogError("Error in Set SO_RCVTIMEO Socket Option");
-               recvData.result = VCORE_SOCKET_ERROR;
-               goto Error_close_exit;
-       }
-
-       if (setsockopt(sockfd, SOL_SOCKET, SO_SNDTIMEO, (char *)&timeout, sizeof(timeout)) < 0) {
-               LogError("Error in Set SO_SNDTIMEO Socket Option");
-               recvData.result = VCORE_SOCKET_ERROR;
-               goto Error_close_exit;
-       }
-
-       if (connect(sockfd, (struct sockaddr *)&clientaddr, clientLen) < 0) {
-               LogError("Error in function connect()..");
-               recvData.result = VCORE_SOCKET_ERROR;
-               goto Error_close_exit;
-       }
-
-       if (write(sockfd, (char *)pClientData, sizeof(VcoreRequestData)) < 0) {
-               LogError("Error in function write()..");
-               recvData.result = VCORE_SOCKET_ERROR;
-               goto Error_close_exit;
-       }
-
-       read_len = _recv_fixed_lenghth(sockfd, (char *)&recvData, sizeof(recvData));
-
-       if (read_len < 0) {
-               LogError("Error in function read()..");
-               recvData.result = VCORE_SOCKET_ERROR;
-               goto Error_close_exit;
-       }
-
-       if (recvData.certCount > 0) {
-               recvData.certList = (VcoreCertResponseData *) malloc(recvData.certCount * sizeof(
-                                                               VcoreCertResponseData));
-
-               if (!recvData.certList) {
-                       LogError("Failed to allocate memory");
-                       recvData.result = VCORE_SOCKET_ERROR;
-                       goto Error_close_exit;
-               }
-
-               memset(recvData.certList, 0x00, recvData.certCount * sizeof(VcoreCertResponseData));
-
-               for (i = 0; i < recvData.certCount; i++) {
-                       read_len = _recv_fixed_lenghth(sockfd, (char *)(recvData.certList + i),
-                                                                                  sizeof(VcoreCertResponseData));
-
-                       if (read_len < 0) {
-                               LogError("Error in function read()..");
-                               recvData.result = VCORE_SOCKET_ERROR;
-                               goto Error_close_exit;
-                       }
-               }
-       }
-
-       if (recvData.certBlockCount > 0) {
-               recvData.certBlockList = (ResponseCertBlock *) malloc(recvData.certBlockCount * sizeof(
-                                                                        ResponseCertBlock));
-
-               if (!recvData.certBlockList) {
-                       LogError("Failed to allocate memory");
-                       recvData.result = VCORE_SOCKET_ERROR;
-                       goto Error_close_exit;
-               }
-
-               memset(recvData.certBlockList, 0x00, recvData.certBlockCount * sizeof(ResponseCertBlock));
-
-               for (i = 0; i < recvData.certBlockCount; i++) {
-                       read_len = _recv_fixed_lenghth(sockfd, (char *)(recvData.certBlockList + i),
-                                                                                  sizeof(ResponseCertBlock));
-
-                       if (read_len < 0) {
-                               LogError("Error in function read()..");
-                               recvData.result = VCORE_SOCKET_ERROR;
-                               goto Error_close_exit;
-                       }
-               }
-       }
-
-Error_close_exit:
-       close(sockfd);
-
-       if (recvData.result == VCORE_SOCKET_ERROR) {
-               free(recvData.certList);
-               recvData.certList = NULL;
-               recvData.certCount = 0;
-               free(recvData.certBlockList);
-               recvData.certBlockList = NULL;
-               recvData.certBlockCount = 0;
-       }
-
-Error_exit:
-       return recvData;
-}
-
-} /* anonymous namespace */
-
-
-int vcore_client_install_certificate_to_store(
-       CertStoreType storeType,
-       const char *gname,
-       const char *common_name,
-       const char *private_key_gname,
-       const char *associated_gname,
-       const char *certData,
-       size_t certSize,
-       CertType certType)
-{
-       VcoreRequestData *pSendData = NULL;
-       VcoreResponseData recvData;
-       initialize_res_data(&recvData);
-
-       if (!gname && !certData) {
-               LogError("Invalid input argument.");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       pSendData = set_request_data(
-                                       CERTSVC_INSTALL_CERTIFICATE,
-                                       storeType,
-                                       DISABLED,
-                                       gname,
-                                       common_name,
-                                       private_key_gname,
-                                       associated_gname,
-                                       certData,
-                                       certSize,
-                                       certType,
-                                       DISABLED);
-
-       if (pSendData == NULL) {
-               LogError("Failed to set request data");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       recvData = cert_svc_client_comm(pSendData);
-       free(pSendData);
-       return recvData.result;
-}
-
-int vcore_client_set_certificate_status_to_store(CertStoreType storeType, int is_root_app,
-               const char *gname, CertStatus status)
-{
-       VcoreRequestData *pSendData = NULL;
-       VcoreResponseData recvData;
-       initialize_res_data(&recvData);
-
-       if (gname == NULL) {
-               LogError("Invalid input parameter.");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       pSendData = set_request_data(CERTSVC_SET_CERTIFICATE_STATUS, storeType, is_root_app, gname, NULL,
-                                                                NULL, NULL, NULL, 0, INVALID_DATA, status);
-
-       if (pSendData == NULL) {
-               LogError("Failed to set request data");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       recvData = cert_svc_client_comm(pSendData);
-       free(pSendData);
-       return recvData.result;
-}
-
-int vcore_client_get_certificate_status_from_store(CertStoreType storeType, const char *gname,
-               CertStatus *status)
-{
-       VcoreRequestData *pSendData = NULL;
-       VcoreResponseData recvData;
-       initialize_res_data(&recvData);
-
-       if (gname == NULL) {
-               LogError("Invalid input parameter.");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       pSendData = set_request_data(CERTSVC_GET_CERTIFICATE_STATUS, storeType, DISABLED, gname, NULL, NULL,
-                                                                NULL, NULL, 0, INVALID_DATA, DISABLED);
-
-       if (pSendData == NULL) {
-               LogError("Failed to set request data");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       recvData = cert_svc_client_comm(pSendData);
-       free(pSendData);
-       *status = recvData.certStatus;
-       return recvData.result;
-}
-
-int vcore_client_check_alias_exist_in_store(CertStoreType storeType, const char *alias,
-               int *isUnique)
-{
-       VcoreRequestData *pSendData = NULL;
-       VcoreResponseData recvData;
-       initialize_res_data(&recvData);
-
-       if (alias == NULL) {
-               LogError("Invalid input parameter.");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       pSendData = set_request_data(CERTSVC_CHECK_ALIAS_EXISTS, storeType, DISABLED, alias, NULL, NULL,
-                                                                NULL, NULL, 0, INVALID_DATA, DISABLED);
-
-       if (pSendData == NULL) {
-               LogError("Failed to set request data");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       recvData = cert_svc_client_comm(pSendData);
-       free(pSendData);
-       *isUnique = recvData.isAliasUnique;
-       return recvData.result;
-}
-
-int vcore_client_get_certificate_from_store(CertStoreType storeType, const char *gname,
-               char **certData, size_t *certSize, CertType certType)
-{
-       char *outData = NULL;
-       VcoreRequestData *pSendData = NULL;
-       VcoreResponseData recvData;
-
-       if (!gname || !certData || !certSize) {
-               LogError("Invalid input argument.");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       initialize_res_data(&recvData);
-
-       if (storeType == SYSTEM_STORE)  /* for extracting certificate from system store */
-               pSendData = set_request_data(CERTSVC_EXTRACT_SYSTEM_CERT, storeType, DISABLED, gname, NULL, NULL,
-                                                                        NULL, NULL, 0, certType, DISABLED);
-       else /* for extracting certificate from other stores */
-               pSendData = set_request_data(CERTSVC_EXTRACT_CERT, storeType, DISABLED, gname, NULL, NULL, NULL,
-                                                                        NULL, 0, certType, DISABLED);
-
-       if (pSendData == NULL) {
-               LogError("Failed to set request data.");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       recvData = cert_svc_client_comm(pSendData);
-
-       if (recvData.result < 0) {
-               LogError("An error occurred from server side err : " << recvData.result);
-               free(pSendData);
-               return recvData.result;
-       }
-
-       free(pSendData);
-
-       if (recvData.dataBlockLen > 0 && recvData.dataBlockLen <= VCORE_MAX_RECV_DATA_SIZE) {
-               outData = (char *)malloc(recvData.dataBlockLen + 1);
-               if (outData == nullptr)
-                       return CERTSVC_BAD_ALLOC;
-
-               memset(outData, 0x00, recvData.dataBlockLen + 1);
-               memcpy(outData, recvData.dataBlock, recvData.dataBlockLen);
-               *certData = outData;
-               *certSize = recvData.dataBlockLen;
-
-               return recvData.result;
-       } else {
-               LogError("revcData length is wrong : " << recvData.dataBlockLen);
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-}
-
-int vcore_client_delete_certificate_from_store(CertStoreType storeType, const char *gname)
-{
-       VcoreRequestData *pSendData = NULL;
-       VcoreResponseData recvData;
-       initialize_res_data(&recvData);
-
-       if (gname == NULL) {
-               LogError("Invalid input parameter.");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       pSendData = set_request_data(CERTSVC_DELETE_CERT, storeType, DISABLED, gname, NULL, NULL, NULL,
-                                                                NULL, 0, INVALID_DATA, DISABLED);
-
-       if (pSendData == NULL) {
-               LogError("Failed to set request data");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       recvData = cert_svc_client_comm(pSendData);
-       free(pSendData);
-       return recvData.result;
-}
-
-int _vcore_client_get_certificate_list_from_store(VcoreRequestType reqType, CertStoreType storeType,
-               int is_root_app,
-               CertSvcStoreCertList **certList, size_t *length)
-{
-       std::unique_ptr<VcoreRequestData, void(*)(void *)> pSendData(set_request_data(
-                               reqType, storeType, is_root_app,
-                               NULL, NULL, NULL, NULL, NULL, 0, INVALID_DATA, DISABLED), free);
-
-       if (!pSendData) {
-               LogError("Failed to set request data");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       VcoreResponseData recvData;
-       initialize_res_data(&recvData);
-       recvData = cert_svc_client_comm(pSendData.get());
-       CertSvcStoreCertList *curr = NULL;
-       CertSvcStoreCertList *prev = NULL;
-       CertSvcStoreCertList *list = NULL;
-
-       for (size_t i = 0; i < recvData.certCount; i++) {
-               curr = createStoreListNode(recvData.certList + i);
-
-               if (curr == NULL) {
-                       destroyStoreList(list);
-                       free(recvData.certList);
-                       return CERTSVC_BAD_ALLOC;
-               }
-
-               if (list == NULL)
-                       list = curr;
-               else
-                       prev->next = curr;
-
-               prev = curr;
-       }
-
-       *length = recvData.certCount;
-       *certList = list;
-       LogDebug("get_certificate_list_from_store: result : " << recvData.result);
-       free(recvData.certList);
-       return recvData.result;
-}
-
-int vcore_client_get_certificate_list_from_store(CertStoreType storeType, int is_root_app,
-               CertSvcStoreCertList **certList, size_t *length)
-{
-       return _vcore_client_get_certificate_list_from_store(CERTSVC_GET_CERTIFICATE_LIST, storeType,
-                       is_root_app,
-                       certList, length);
-}
-
-int vcore_client_get_root_certificate_list_from_store(CertStoreType storeType,
-               CertSvcStoreCertList **certList, size_t *length)
-{
-       return _vcore_client_get_certificate_list_from_store(CERTSVC_GET_ROOT_CERTIFICATE_LIST, storeType,
-                       0,
-                       certList, length);
-}
-
-int vcore_client_get_end_user_certificate_list_from_store(CertStoreType storeType,
-               CertSvcStoreCertList **certList, size_t *length)
-{
-       return _vcore_client_get_certificate_list_from_store(CERTSVC_GET_USER_CERTIFICATE_LIST, storeType,
-                       0,
-                       certList, length);
-}
-
-int vcore_client_get_certificate_alias_from_store(CertStoreType storeType, const char *gname,
-               char **alias)
-{
-       VcoreRequestData *pSendData = NULL;
-       VcoreResponseData recvData;
-       initialize_res_data(&recvData);
-
-       if (gname == NULL) {
-               LogError("Invalid input parameter.");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       pSendData = set_request_data(CERTSVC_GET_CERTIFICATE_ALIAS, storeType, DISABLED, gname, NULL, NULL,
-                                                                NULL, NULL, 0, INVALID_DATA, DISABLED);
-
-       if (pSendData == NULL) {
-               LogError("Failed to set request data");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       recvData = cert_svc_client_comm(pSendData);
-       *alias = strndup(recvData.common_name, sizeof(recvData.common_name));
-       free(pSendData);
-       return recvData.result;
-}
-
-int vcore_client_load_certificates_from_store(CertStoreType storeType, const char *gname,
-               char ***certs, size_t *ncerts)
-{
-       VcoreResponseData recvData;
-       ResponseCertBlock *cert = NULL;
-       size_t i = 0;
-       size_t ncerts_out = 0;
-       char **certs_out = NULL;
-       initialize_res_data(&recvData);
-       std::unique_ptr<VcoreRequestData, void(*)(void *)> pSendData(set_request_data(
-                               CERTSVC_LOAD_CERTIFICATES, storeType, DISABLED, gname,
-                               NULL, NULL, NULL, NULL, 0, INVALID_DATA, DISABLED), free);
-
-       if (!pSendData) {
-               LogError("Failed to set request data");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       recvData = cert_svc_client_comm(pSendData.get());
-
-       if (recvData.result != CERTSVC_SUCCESS) {
-               LogError("Failed to CERTSVC_LOAD_CERTIFICATES. server retcode : " << recvData.result);
-               return recvData.result;
-       }
-
-       ncerts_out = recvData.certBlockCount;
-
-       if (ncerts_out == 0) {
-               LogError("No certificates exist with gname[" << gname << "] in store[" << storeType << "]");
-               return CERTSVC_ALIAS_DOES_NOT_EXIST;
-       }
-
-       certs_out = (char **)malloc((ncerts_out + 1) * sizeof(char *));
-
-       if (certs_out == NULL)
-               return CERTSVC_BAD_ALLOC;
-
-       certs_out[ncerts_out] = NULL;
-
-       for (i = 0; i < recvData.certBlockCount; i++) {
-               cert = recvData.certBlockList + i;
-               certs_out[i] = strndup(cert->dataBlock, cert->dataBlockLen);
-               LogDebug("vcore_client_load_certificates_from_store. cert[" << certs_out[i] << "]");
-       }
-
-       *certs = certs_out;
-       *ncerts = ncerts_out;
-       free(recvData.certBlockList);
-       return recvData.result;
-}
diff --git a/vcore/vcore/Client.h b/vcore/vcore/Client.h
deleted file mode 100644 (file)
index 0e62cf2..0000000
+++ /dev/null
@@ -1,127 +0,0 @@
-/**
- * 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        Client.h
- * @author      Madhan A K (madhan.ak@samsung.com)
- * @version     1.0
- * @brief       cert-svc client interface for cert-server.
- */
-
-#ifndef CERT_SVC_CLIENT_H_
-#define CERT_SVC_CLIENT_H_
-
-#include <cert-svc/cerror.h>
-#include <cert-svc/ccert.h>
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#define VCORE_MAX_FILENAME_SIZE     128
-#define VCORE_MAX_RECV_DATA_SIZE    8192    //4096, internal buffer = 4KB*2. /*Note:system store cert size is bigger than 4KB*/
-#define VCORE_MAX_SEND_DATA_SIZE    8192    //4096, internal buffer = 4KB*2.
-#define VCORE_MAX_GROUP_ID_SIZE     32
-#define VCORE_MAX_APPID_SIZE        32
-#define VCORE_MAX_PASSWORD_SIZE     32
-#define VCORE_SOCKET_ERROR          (-0x01C10000) // TIZEN_ERROR_CONNECTION  /*Connection error*/
-#define VCORE_SOCK_PATH             SERVER_STREAM
-#define VCORE_PKEY_TEMP_PATH        "/tmp/tmpData"
-
-typedef enum {
-       CERTSVC_EXTRACT_CERT,
-       CERTSVC_EXTRACT_SYSTEM_CERT,
-       CERTSVC_DELETE_CERT,
-       CERTSVC_INSTALL_CERTIFICATE,
-       CERTSVC_GET_CERTIFICATE_STATUS,
-       CERTSVC_SET_CERTIFICATE_STATUS,
-       CERTSVC_CHECK_ALIAS_EXISTS,
-       CERTSVC_GET_CERTIFICATE_LIST,
-       CERTSVC_GET_CERTIFICATE_ALIAS,
-       CERTSVC_GET_USER_CERTIFICATE_LIST,
-       CERTSVC_GET_ROOT_CERTIFICATE_LIST,
-       CERTSVC_LOAD_CERTIFICATES,
-} VcoreRequestType;
-
-typedef struct {
-       VcoreRequestType reqType;
-       CertStoreType    storeType;
-       char             gname[VCORE_MAX_FILENAME_SIZE * 2 + 1]; /* for gname */
-       char             common_name[VCORE_MAX_FILENAME_SIZE * 2 + 1]; /* for common_name */
-       char             private_key_gname[VCORE_MAX_FILENAME_SIZE * 2 + 1]; /* for private_key_gname */
-       char             associated_gname[VCORE_MAX_FILENAME_SIZE * 2 + 1]; /* for associated_gname */
-       char             dataBlock[VCORE_MAX_SEND_DATA_SIZE];    /* for cert & key buffer */
-       size_t           dataBlockLen;
-       CertStatus       certStatus;
-       int              is_root_app;
-       CertType         certType;
-} VcoreRequestData;
-
-typedef struct {
-       char             gname[VCORE_MAX_FILENAME_SIZE * 2 + 1];
-       char             title[VCORE_MAX_FILENAME_SIZE * 2 + 1];
-       CertStatus       status;
-       CertStoreType    storeType;
-} VcoreCertResponseData;
-
-
-typedef struct {
-       char             dataBlock[VCORE_MAX_RECV_DATA_SIZE];
-       size_t           dataBlockLen;
-} ResponseCertBlock;
-
-typedef struct {
-       char                   dataBlock[VCORE_MAX_RECV_DATA_SIZE];
-       size_t                 dataBlockLen;
-       CertStatus             certStatus;
-       char                   common_name[VCORE_MAX_FILENAME_SIZE * 2 + 1]; /*for common_name*/
-       int                    result;
-       int                    isAliasUnique;
-       size_t                 certCount;
-       VcoreCertResponseData *certList;
-       size_t                 certBlockCount;
-       ResponseCertBlock     *certBlockList; // array
-} VcoreResponseData;
-
-
-
-int vcore_client_set_certificate_status_to_store(CertStoreType storeType, int is_root_app,
-               const char *gname, CertStatus status);
-int vcore_client_get_certificate_status_from_store(CertStoreType storeType, const char *gname,
-               CertStatus *status);
-int vcore_client_check_alias_exist_in_store(CertStoreType storeType, const char *alias,
-               int *isUnique);
-int vcore_client_install_certificate_to_store(CertStoreType storeType, const char *gname,
-               const char *common_name, const char *private_key_gname, const char *associated_gname,
-               const char *dataBlock, size_t dataBlockLen, CertType certType);
-int vcore_client_get_certificate_from_store(CertStoreType storeType, const char *gname,
-               char **certData, size_t *certSize, CertType certType);
-int vcore_client_delete_certificate_from_store(CertStoreType storeType, const char *gname);
-int vcore_client_get_certificate_list_from_store(CertStoreType storeType, int is_root_app,
-               CertSvcStoreCertList **certList, size_t *length);
-int vcore_client_get_root_certificate_list_from_store(CertStoreType storeType,
-               CertSvcStoreCertList **certList, size_t *length);
-int vcore_client_get_end_user_certificate_list_from_store(CertStoreType storeType,
-               CertSvcStoreCertList **certList, size_t *length);
-int vcore_client_get_certificate_alias_from_store(CertStoreType storeType, const char *gname,
-               char **alias);
-int vcore_client_load_certificates_from_store(CertStoreType storeType, const char *gname,
-               char ***certs, size_t *ncerts);
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif
diff --git a/vcore/vcore/CryptoInit.cpp b/vcore/vcore/CryptoInit.cpp
deleted file mode 100644 (file)
index b1ad4cf..0000000
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- * 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        CryptoInit.cpp
- * @author      Kyungwook Tak (k.tak@samsung.com)
- * @version     1.0
- * @brief       Initialize openssl functions by singleton
- */
-
-#include <openssl/ssl.h>
-
-#include <dpl/singleton_impl.h>
-
-#include <vcore/CryptoInit.h>
-
-IMPLEMENT_SINGLETON(ValidationCore::CryptoInit)
-
-namespace ValidationCore {
-
-CryptoInit::CryptoInit()
-{
-       SSL_load_error_strings();
-       SSL_library_init();
-}
-
-CryptoInit::~CryptoInit()
-{
-}
-
-} // namespace ValidationCore
diff --git a/vcore/vcore/CryptoInit.h b/vcore/vcore/CryptoInit.h
deleted file mode 100644 (file)
index 05f8c62..0000000
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
- * 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        CryptoInit.h
- * @author      Kyungwook Tak (k.tak@samsung.com)
- * @version     1.0
- * @brief       Initialize openssl functions by singleton
- */
-#pragma once
-
-#include <dpl/singleton.h>
-
-namespace ValidationCore {
-
-class CryptoInit {
-public:
-       CryptoInit();
-       virtual ~CryptoInit();
-
-       CryptoInit(const CryptoInit &) = delete;
-       CryptoInit &operator=(const CryptoInit &) = delete;
-       CryptoInit(CryptoInit &&) = delete;
-       CryptoInit &operator=(CryptoInit &&) = delete;
-};
-
-typedef VcoreDPL::Singleton<CryptoInit> CryptoInitSingleton;
-
-} // namespace ValidationCore
diff --git a/vcore/vcore/Error.h b/vcore/vcore/Error.h
deleted file mode 100644 (file)
index 358f5c5..0000000
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * 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        Error.h
- * @author      Kyungwook Tak (k.tak@samsung.com)
- * @version     1.0
- * @brief       Error codes of signature validator.
- */
-#pragma once
-
-namespace ValidationCore {
-
-using VCerr = int;
-
-const VCerr E_SIG_NONE           = 0;
-const VCerr E_SIG_INVALID_FORMAT = -1;
-const VCerr E_SIG_INVALID_CERT   = -2;
-const VCerr E_SIG_INVALID_CHAIN  = -3;
-const VCerr E_SIG_INVALID_SIG    = -4;
-const VCerr E_SIG_INVALID_REF    = -5;
-const VCerr E_SIG_CERT_EXPIRED   = -6;
-const VCerr E_SIG_CERT_NOT_YET   = -7;
-const VCerr E_SIG_DISREGARDED    = -8;
-const VCerr E_SIG_REVOKED        = -9;
-const VCerr E_SIG_PLUGIN         = -10;
-const VCerr E_SIG_OUT_OF_MEM     = -11;
-const VCerr E_SIG_UNKNOWN        = -12;
-
-const VCerr E_SCOPE_FIRST        = E_SIG_INVALID_FORMAT;
-const VCerr E_SCOPE_LAST         = E_SIG_UNKNOWN;
-
-}
diff --git a/vcore/vcore/Ocsp.cpp b/vcore/vcore/Ocsp.cpp
deleted file mode 100644 (file)
index ae1dc87..0000000
+++ /dev/null
@@ -1,338 +0,0 @@
-/*
- *  Copyright (c) 2015 Samsung Electronics Co.
- *
- *  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        Ocsp.cpp
- * @author      Kyungwook Tak (k.tak@samsung.com)
- * @version     1.0
- * @brief       OCSP check for signature validator. It should be used only internally.
- */
-
-#include <memory>
-#include <functional>
-
-#include <openssl/ssl.h>
-#include <openssl/ocsp.h>
-#include <openssl/err.h>
-
-#include <dpl/log/log.h>
-#include <vcore/CryptoInit.h>
-
-#include <vcore/Ocsp.h>
-
-/* Maximum leeway in validity period : 5 minitues as a default */
-#define MAX_VALIDITY_PERIOD (5 * 60)
-
-namespace {
-
-typedef std::unique_ptr<X509_STORE_CTX, std::function<void(X509_STORE_CTX *)>> X509_STORE_CTX_PTR;
-typedef std::unique_ptr<STACK_OF(X509), std::function<void(STACK_OF(X509) *)>> X509_STACK_PTR;
-typedef std::unique_ptr<X509_STORE,     std::function<void(X509_STORE *)>> X509_STORE_PTR;
-typedef std::unique_ptr<SSL_CTX,        std::function<void(SSL_CTX *)>> SSL_CTX_PTR;
-typedef std::unique_ptr<BIO,            std::function<void(BIO *)>> BIO_PTR;
-typedef std::unique_ptr<char,           std::function<void(void *)>> RAIIstr;
-typedef std::unique_ptr<OCSP_REQUEST,   std::function<void(OCSP_REQUEST *)>> OCSP_REQUEST_PTR;
-typedef std::unique_ptr<OCSP_RESPONSE,  std::function<void(OCSP_RESPONSE *)>> OCSP_RESPONSE_PTR;
-typedef std::unique_ptr<OCSP_BASICRESP, std::function<void(OCSP_BASICRESP *)>> OCSP_BASICRESP_PTR;
-
-inline X509_STACK_PTR create_x509_stack()
-{
-       return X509_STACK_PTR(sk_X509_new_null(), [](STACK_OF(X509) * stack) {
-               sk_X509_free(stack);
-       });
-}
-
-inline X509_STORE_CTX_PTR create_x509_store_ctx()
-{
-       return X509_STORE_CTX_PTR(X509_STORE_CTX_new(), X509_STORE_CTX_free);
-}
-
-inline X509_STORE_PTR create_x509_store()
-{
-       return X509_STORE_PTR(X509_STORE_new(), X509_STORE_free);
-}
-
-inline SSL_CTX_PTR create_SSL_CTX()
-{
-       return SSL_CTX_PTR(SSL_CTX_new(SSLv23_client_method()), SSL_CTX_free);
-}
-
-inline RAIIstr create_RAIIstr(char *str)
-{
-       return RAIIstr(str, [](void *ptr) {
-               OPENSSL_free(ptr);
-       });
-}
-
-inline BIO_PTR create_BIO(BIO *bio)
-{
-       return BIO_PTR(bio, BIO_free_all);
-}
-
-inline OCSP_REQUEST_PTR create_OCSP_REQUEST()
-{
-       return OCSP_REQUEST_PTR(OCSP_REQUEST_new(), OCSP_REQUEST_free);
-}
-
-inline OCSP_RESPONSE_PTR create_OCSP_RESPONSE(OCSP_RESPONSE *resp)
-{
-       return OCSP_RESPONSE_PTR(resp, OCSP_RESPONSE_free);
-}
-
-inline OCSP_BASICRESP_PTR create_OCSP_BASICRESP(OCSP_BASICRESP *basicResp)
-{
-       return OCSP_BASICRESP_PTR(basicResp, OCSP_BASICRESP_free);
-}
-
-void BIO_write_and_free(BIO *bio)
-{
-       if (!bio)
-               return;
-
-       std::vector<char> message(1024);
-       int size = BIO_read(bio, message.data(), message.size());
-
-       if (size > 0) {
-               message.resize(size);
-               LogError("OCSP error description ["
-                                << std::string(message.begin(), message.end()) << "]");
-       }
-
-       BIO_free_all(bio);
-}
-
-} // namespace anonymous
-
-namespace ValidationCore {
-
-Ocsp::Ocsp()
-{
-}
-
-Ocsp::~Ocsp()
-{
-}
-
-Ocsp::Result checkInternal(
-       const CertificatePtr &_cert,
-       const CertificatePtr &_issuer,
-       X509_STACK_PTR &trustedCerts)
-{
-       /* initialize openssl library */
-       CryptoInitSingleton::Instance();
-       BIO_PTR bioLogger(BIO_new(BIO_s_mem()), BIO_write_and_free);
-       X509 *cert = _cert->getX509();
-       X509 *issuer = _issuer->getX509();
-       std::string ocspUrl = _cert->getOCSPURL();
-
-       if (ocspUrl.empty())
-               VcoreThrowMsg(Ocsp::Exception::OcspUnsupported,
-                                         "Certificate[" << _cert->getOneLine() << "] doesn't provide OCSP extension");
-
-       char *_ocspUrl = new char[ocspUrl.length() + 1];
-
-       if (_ocspUrl == NULL)
-               VcoreThrowMsg(Ocsp::Exception::UnknownError, "Failed to alloc memory");
-
-       strncpy(_ocspUrl, ocspUrl.c_str(), ocspUrl.length() + 1);
-       char *_host = NULL;
-       char *_port = NULL;
-       char *_path = NULL;
-       int use_ssl = 0;
-       int temp = OCSP_parse_url(_ocspUrl, &_host, &_port, &_path, &use_ssl);
-       LogDebug("ocspUrl[" << _ocspUrl
-                        << "] host[" << _host
-                        << "] port[" << _port
-                        << "] path[" << _path
-                        << "] use_ssl[" << use_ssl << "]");
-       delete []_ocspUrl;
-
-       if (temp == 0) {
-               ERR_print_errors(bioLogger.get());
-               VcoreThrowMsg(Ocsp::Exception::InvalidUrl, "ocsp url parsing failed. url : " << ocspUrl);
-       }
-
-       RAIIstr host = create_RAIIstr(_host);
-       RAIIstr port = create_RAIIstr(_port);
-       RAIIstr path = create_RAIIstr(_path);
-       BIO_PTR cbio = create_BIO(BIO_new_connect(host.get()));
-
-       if (cbio.get() == NULL) {
-               ERR_print_errors(bioLogger.get());
-               VcoreThrowMsg(Ocsp::Exception::UnknownError, "Failed to create bio connect");
-       }
-
-       if (port)
-               BIO_set_conn_port(cbio.get(), port.get());
-
-       if (use_ssl == 1) {
-               SSL_CTX_PTR ssl_ctx = create_SSL_CTX();
-
-               if (ssl_ctx.get() == NULL) {
-                       ERR_print_errors(bioLogger.get());
-                       VcoreThrowMsg(Ocsp::Exception::UnknownError, "Failed to SSL_CTX_new");
-               }
-
-               SSL_CTX_set_mode(ssl_ctx.get(), SSL_MODE_AUTO_RETRY);
-               BIO_PTR sbio = create_BIO(BIO_new_ssl(ssl_ctx.get(), 1));
-
-               if (sbio.get() == NULL) {
-                       ERR_print_errors(bioLogger.get());
-                       VcoreThrowMsg(Ocsp::Exception::UnknownError, "Failed to BIO_new_ssl");
-               }
-
-               cbio.reset(BIO_push(sbio.get(), cbio.get()));
-
-               if (cbio.get() == NULL) {
-                       ERR_print_errors(bioLogger.get());
-                       VcoreThrowMsg(Ocsp::Exception::UnknownError, "Failed to BIO_push");
-               }
-       }
-
-       if (BIO_do_connect(cbio.get()) <= 0) {
-               ERR_print_errors(bioLogger.get());
-               VcoreThrowMsg(Ocsp::Exception::NetworkError, "Failed to BIO_do_connect");
-       }
-
-       OCSP_REQUEST_PTR req = create_OCSP_REQUEST();
-
-       if (req.get() == NULL) {
-               ERR_print_errors(bioLogger.get());
-               VcoreThrowMsg(Ocsp::Exception::UnknownError, "Failed to OCSP_REQUEST_new");
-       }
-
-       OCSP_CERTID *certid = OCSP_cert_to_id(NULL, cert, issuer);
-
-       if (certid == NULL) {
-               ERR_print_errors(bioLogger.get());
-               VcoreThrowMsg(Ocsp::Exception::UnknownError, "Failed to OCSP_cert_to_id");
-       }
-
-       if (OCSP_request_add0_id(req.get(), certid) == NULL) {
-               ERR_print_errors(bioLogger.get());
-               VcoreThrowMsg(Ocsp::Exception::UnknownError, "Failed to OCSP_request_add0_id");
-       }
-
-       OCSP_RESPONSE_PTR resp =
-               create_OCSP_RESPONSE(OCSP_sendreq_bio(cbio.get(), path.get(), req.get()));
-
-       if (resp.get() == NULL) {
-               ERR_print_errors(bioLogger.get());
-               VcoreThrowMsg(Ocsp::Exception::NetworkError, "Failed to OCSP_sendreq_bio");
-       }
-
-       if (OCSP_response_status(resp.get()) != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
-               ERR_print_errors(bioLogger.get());
-               VcoreThrowMsg(Ocsp::Exception::ServerError, "Failed to OCSP_response_status");
-       }
-
-       OCSP_BASICRESP_PTR basicResp =
-               create_OCSP_BASICRESP(OCSP_response_get1_basic(resp.get()));
-
-       if (basicResp.get() == NULL) {
-               ERR_print_errors(bioLogger.get());
-               VcoreThrowMsg(Ocsp::Exception::InvalidResponse, "Failed to OCSP_response_get1_basic");
-       }
-
-       X509_STORE_PTR trustedStore = create_x509_store();
-
-       if (trustedCerts.get()) {
-               for (int idx = 0; idx < sk_X509_num(trustedCerts.get()); idx++)
-                       X509_STORE_add_cert(trustedStore.get(), sk_X509_value(trustedCerts.get(), idx));
-
-               X509_STORE_add_cert(trustedStore.get(), issuer);
-       }
-
-       if (OCSP_basic_verify(basicResp.get(), NULL, trustedStore.get(), 0) <= 0) {
-               ERR_print_errors(bioLogger.get());
-               VcoreThrowMsg(Ocsp::Exception::InvalidResponse, "Failed to OCSP_basic_verify");
-       }
-
-       if (OCSP_check_nonce(req.get(), basicResp.get()) == 0) {
-               ERR_print_errors(bioLogger.get());
-               VcoreThrowMsg(Ocsp::Exception::InvalidResponse, "nonce exists but not equal");
-       }
-
-       int ocspStatus = -1;
-       int reason = 0;
-       ASN1_GENERALIZEDTIME *rev = NULL;
-       ASN1_GENERALIZEDTIME *thisupd = NULL;
-       ASN1_GENERALIZEDTIME *nextupd = NULL;
-
-       if (OCSP_resp_find_status(
-                               basicResp.get(),
-                               certid,
-                               &ocspStatus,
-                               &reason,
-                               &rev,
-                               &thisupd,
-                               &nextupd) == 0) {
-               ERR_print_errors(bioLogger.get());
-               VcoreThrowMsg(Ocsp::Exception::InvalidResponse, "Failed to OCSP_resp_find_status");
-       }
-
-       if (OCSP_check_validity(thisupd, nextupd, MAX_VALIDITY_PERIOD, -1) == 0) {
-               ERR_print_errors(bioLogger.get());
-               VcoreThrowMsg(Ocsp::Exception::InvalidResponse, "Failed to OCSP_check_validity");
-       }
-
-       if (ocspStatus != V_OCSP_CERTSTATUS_GOOD && ocspStatus != V_OCSP_CERTSTATUS_REVOKED)
-               VcoreThrowMsg(Ocsp::Exception::InvalidResponse, "Unknown ocsp status.");
-
-       return ocspStatus == V_OCSP_CERTSTATUS_GOOD ?
-                  Ocsp::Result::GOOD : Ocsp::Result::REVOKED;
-}
-
-Ocsp::Result Ocsp::check(const SignatureData &data)
-{
-       if (!data.isCertListSorted())
-               VcoreThrowMsg(Exception::InvalidParam, "cert list should be sorted");
-
-       const CertificateList &certChain = data.getCertList();
-
-       if (certChain.size() < 3)
-               VcoreThrowMsg(Exception::InvalidParam, "cert chain is too short");
-
-       X509_STACK_PTR trustedCerts = create_x509_stack();
-       auto it = certChain.cbegin();
-       it++;
-       it++;
-
-       /* don't trust the user cert and the first intermediate CA cert */
-       for (; it != certChain.cend(); it++) {
-               const auto &cert = it->get();
-
-               if (cert->getDER().empty())
-                       VcoreThrowMsg(Exception::InvalidParam, "Broken certificate chain.");
-
-               sk_X509_push(trustedCerts.get(), cert->getX509());
-       }
-
-       auto itCert = certChain.cbegin();
-       auto itIssuer = certChain.cbegin();
-       itIssuer++;
-
-       /* check ocsp except except self-signed root CA cert */
-       for (; itIssuer != certChain.end(); itCert++, itIssuer++) {
-               if (checkInternal(*itCert, *itIssuer, trustedCerts) == Result::REVOKED)
-                       return Result::REVOKED;
-
-               LogDebug("ocsp status good for cert : " << (*itCert)->getOneLine());
-       }
-
-       return Result::GOOD;
-}
-
-}
diff --git a/vcore/vcore/Ocsp.h b/vcore/vcore/Ocsp.h
deleted file mode 100644 (file)
index d335e67..0000000
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- *  Copyright (c) 2015 Samsung Electronics Co.
- *
- *  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        Ocsp.h
- * @author      Kyungwook Tak (k.tak@samsung.com)
- * @version     1.0
- * @brief       OCSP check for signature validator. It should be used only internally.
- */
-#pragma once
-
-#include <vcore/SignatureData.h>
-#include <vcore/exception.h>
-
-namespace ValidationCore {
-
-class Ocsp {
-public:
-       virtual ~Ocsp();
-
-       class Exception {
-       public:
-               VCORE_DECLARE_EXCEPTION_TYPE(ValidationCore::Exception, Base);
-               VCORE_DECLARE_EXCEPTION_TYPE(Base, InvalidParam);
-               VCORE_DECLARE_EXCEPTION_TYPE(Base, OcspUnsupported);
-               VCORE_DECLARE_EXCEPTION_TYPE(Base, InvalidUrl);
-               VCORE_DECLARE_EXCEPTION_TYPE(Base, InvalidResponse);
-               VCORE_DECLARE_EXCEPTION_TYPE(Base, ServerError);
-               VCORE_DECLARE_EXCEPTION_TYPE(Base, NetworkError);
-               VCORE_DECLARE_EXCEPTION_TYPE(Base, UnknownError);
-       };
-
-       enum Result {
-               GOOD,
-               REVOKED
-       };
-
-       /*
-        *  Remarks: input cert chain should be sorted state.
-        */
-       static Result check(const SignatureData &data);
-
-private:
-       explicit Ocsp();
-};
-
-}
diff --git a/vcore/vcore/ParserSchema.h b/vcore/vcore/ParserSchema.h
deleted file mode 100644 (file)
index 02ff6ed..0000000
+++ /dev/null
@@ -1,198 +0,0 @@
-/*
- * Copyright (c) 2011 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        ParserSchema.h
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief
- */
-#ifndef _PARSERSCHEMA_H_
-#define _PARSERSCHEMA_H_
-
-#include <map>
-#include <string>
-
-#include <vcore/SaxReader.h>
-#include <vcore/exception.h>
-
-namespace ValidationCore {
-namespace ParserSchemaException {
-VCORE_DECLARE_EXCEPTION_TYPE(ValidationCore::Exception, Base);
-VCORE_DECLARE_EXCEPTION_TYPE(Base, XmlReaderError);
-VCORE_DECLARE_EXCEPTION_TYPE(Base, CertificateLoaderError);
-VCORE_DECLARE_EXCEPTION_TYPE(Base, UnsupportedAlgorithm);
-VCORE_DECLARE_EXCEPTION_TYPE(Base, UnsupportedValue);
-}
-
-template<typename ParserType, typename DataType>
-class ParserSchema {
-public:
-
-       struct TagDescription {
-               TagDescription(const std::string &tag,
-                                          const std::string &xmlNamespace) :
-                       tagName(tag),
-                       namespaceUri(xmlNamespace)
-               {
-               }
-
-               std::string tagName;
-               std::string namespaceUri;
-
-               bool operator<(const TagDescription &second) const
-               {
-                       if (tagName < second.tagName) {
-                               return true;
-                       }
-
-                       if (tagName > second.tagName) {
-                               return false;
-                       }
-
-                       if (namespaceUri < second.namespaceUri) {
-                               return true;
-                       }
-
-                       return false;
-               }
-       };
-
-
-       ParserSchema(ParserType *parser)
-               : m_functions(parser) {}
-
-       virtual ~ParserSchema() {}
-
-       void initialize(
-               const std::string &filename,
-               bool defaultArgs,
-               SaxReader::ValidationType valType,
-               const std::string &xmlschema)
-       {
-               VcoreTry {
-                       m_reader.initialize(filename, defaultArgs, valType, xmlschema);
-               }
-               VcoreCatch(SaxReader::Exception::Base) {
-                       VcoreReThrowMsg(ParserSchemaException::XmlReaderError, "XmlReaderError");
-               }
-       }
-
-       void deinitialize()
-       {
-               m_reader.deinitialize();
-       }
-
-       void read(DataType &dataContainer)
-       {
-               VcoreTry {
-                       while (m_reader.next())
-                       {
-                               switch (m_reader.type()) {
-                               case SaxReader::NODE_BEGIN:
-                                       beginNode(dataContainer);
-                                       break;
-
-                               case SaxReader::NODE_END:
-                                       endNode(dataContainer);
-                                       break;
-
-                               case SaxReader::NODE_TEXT:
-                                       textNode(dataContainer);
-                                       break;
-
-                               default:
-                                       break;
-                               }
-                       }
-               }
-               VcoreCatch(SaxReader::Exception::Base) {
-                       VcoreReThrowMsg(ParserSchemaException::XmlReaderError, "XmlReaderError");
-               }
-       }
-
-       typedef void (ParserType::*FunctionPtr)(DataType &data);
-       typedef std::map<TagDescription, FunctionPtr> FunctionMap;
-
-       void addBeginTagCallback(
-               const std::string &tag,
-               const std::string &namespaceUri,
-               FunctionPtr function)
-       {
-               TagDescription desc(tag, namespaceUri);
-               m_beginFunctionMap[desc] = function;
-       }
-
-       void addEndTagCallback(
-               const std::string &tag,
-               const std::string &namespaceUri,
-               FunctionPtr function)
-       {
-               TagDescription desc(tag, namespaceUri);
-               m_endFunctionMap[desc] = function;
-       }
-
-       SaxReader &getReader()
-       {
-               return m_reader;
-       }
-
-       std::string &getText()
-       {
-               return m_textNode;
-       }
-
-protected:
-       void beginNode(DataType &dataContainer)
-       {
-               TagDescription desc(m_reader.name(), m_reader.namespaceURI());
-               FunctionPtr fun = m_beginFunctionMap[desc];
-
-               if (fun == 0) {
-                       return;
-               }
-
-               (m_functions->*fun)(dataContainer);
-       }
-
-       void endNode(DataType &dataContainer)
-       {
-               TagDescription desc(m_reader.name(), m_reader.namespaceURI());
-               FunctionPtr fun = m_endFunctionMap[desc];
-
-               if (fun == 0) {
-                       return;
-               }
-
-               (m_functions->*fun)(dataContainer);
-       }
-
-       void textNode(DataType &dataContainer)
-       {
-               (void)dataContainer;
-               m_textNode = m_reader.value();
-       }
-
-       ParserType *m_functions;
-       SaxReader m_reader;
-       FunctionMap m_beginFunctionMap;
-       FunctionMap m_endFunctionMap;
-
-       // temporary values require due parsing textNode
-       std::string m_textNode;
-};
-
-} // namespace ValidationCore
-#endif
diff --git a/vcore/vcore/PluginHandler.cpp b/vcore/vcore/PluginHandler.cpp
deleted file mode 100644 (file)
index e722bfc..0000000
+++ /dev/null
@@ -1,106 +0,0 @@
-/*
- *  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        PluginHandler.cpp
- * @author      Kyungwook Tak (k.tak@samsung.com)
- * @version     1.0
- * @brief       Validator plugin handler.
- */
-
-#include <dlfcn.h>
-
-#include <dpl/log/log.h>
-
-#include <vcore/PluginHandler.h>
-
-namespace ValidationCore {
-
-PluginHandler::PluginHandler()
-       : m_dlhandle(nullptr)
-       , m_plugin(nullptr)
-       , m_destroy(nullptr)
-       , m_fail(true)
-{
-       m_dlhandle = dlopen(PLUGIN_PATH.c_str(), RTLD_NOW);
-
-       if (!m_dlhandle) {
-               LogInfo("Plugin library has not been found/opened : " << PLUGIN_PATH);
-               return;
-       }
-
-       CreateValidatorPlugin_t createFun =
-               reinterpret_cast<CreateValidatorPlugin_t>(dlsym(m_dlhandle, "create"));
-
-       if (!createFun) {
-               LogError("create symbol cannot found from " << PLUGIN_PATH
-                                << ". dlerror : " << dlerror());
-               return;
-       }
-
-       m_destroy =
-               reinterpret_cast<DestroyValidatorPlugin_t>(dlsym(m_dlhandle, "destroy"));
-
-       if (!m_destroy) {
-               LogError("destroy symbole cannot found from " << PLUGIN_PATH
-                                << ". dlerror : " << dlerror());
-               return;
-       }
-
-       m_plugin = createFun();
-
-       if (!m_plugin) {
-               LogError("cannot create plugin with create func.");
-               return;
-       }
-
-       LogDebug("create plugin with createFun success.");
-       m_fail = false;
-}
-
-PluginHandler::~PluginHandler()
-{
-       if (m_plugin && m_destroy)
-               m_destroy(m_plugin);
-
-       if (m_dlhandle)
-               dlclose(m_dlhandle);
-}
-
-bool PluginHandler::fail() const
-{
-       return m_fail;
-}
-
-VCerr PluginHandler::step(VCerr result, SignatureData &data)
-{
-       if (!m_plugin) {
-               LogError("Plugin is not initialized.");
-               return result;
-       }
-
-       return m_plugin->step(result, data);
-}
-
-std::string PluginHandler::errorToString(VCerr code)
-{
-       if (!m_plugin)
-               return "Plugin is not initialized";
-
-       return m_plugin->errorToString(code);
-}
-
-} // namespace ValidationCore
diff --git a/vcore/vcore/PluginHandler.h b/vcore/vcore/PluginHandler.h
deleted file mode 100644 (file)
index 1b83b02..0000000
+++ /dev/null
@@ -1,53 +0,0 @@
-/*
- *  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        PluginHandler.h
- * @author      Kyungwook Tak (k.tak@samsung.com)
- * @version     1.0
- * @brief       Validator plugin handler.
- */
-#pragma once
-
-#include <string>
-
-#include <vcore/SignatureData.h>
-#include <vcore/SignatureValidator.h>
-#include <vcore/ValidatorPluginApi.h>
-#include <vcore/Error.h>
-
-namespace ValidationCore {
-
-class PluginHandler {
-public:
-       PluginHandler();
-       PluginHandler(const PluginHandler &) = delete;
-       PluginHandler &operator=(const PluginHandler &) = delete;
-
-       virtual ~PluginHandler();
-
-       bool fail(void) const;
-       VCerr step(VCerr result, SignatureData &data);
-       std::string errorToString(VCerr code);
-
-private:
-       void *m_dlhandle;
-       ValidatorPlugin *m_plugin;
-       DestroyValidatorPlugin_t m_destroy;
-       bool m_fail;
-};
-
-} // namespace ValidationCore
diff --git a/vcore/vcore/ReferenceValidator.cpp b/vcore/vcore/ReferenceValidator.cpp
deleted file mode 100644 (file)
index b4f4713..0000000
+++ /dev/null
@@ -1,293 +0,0 @@
-/*
- * Copyright (c) 2011 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.
- */
-/*
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- *              Sangwan Kwon (sangwan.kwon@samsung.com)
- * @file        ReferenceValidator.cpp
- * @version     1.0
- * @brief       Compare signature reference list and list of widget file.
- */
-#include <vcore/ReferenceValidator.h>
-
-#include <dirent.h>
-#include <errno.h>
-#include <fstream>
-#include <memory>
-#include <unistd.h>
-#include <limits.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-
-#include <pcrecpp.h>
-
-#include <dpl/log/log.h>
-
-#ifndef PATH_MAX
-#define PATH_MAX 4096
-#endif
-
-namespace {
-
-const char *SPECIAL_SYMBOL_CURRENT_DIR = ".";
-const char *SPECIAL_SYMBOL_UPPER_DIR = "..";
-const char *SPECIAL_SYMBOL_AUTHOR_SIGNATURE_FILE = "author-signature.xml";
-const char *REGEXP_DISTRIBUTOR_SIGNATURE = "^signature[1-9][0-9]*\\.xml";
-
-const char MARK_ENCODED_CHAR = '%';
-
-} // namespace anonymous
-
-namespace ValidationCore {
-
-class ReferenceValidator::Impl {
-public:
-       Impl(const std::string &dirpath)
-               : m_dirpath(dirpath)
-               , m_signatureRegexp(REGEXP_DISTRIBUTOR_SIGNATURE)
-       {}
-
-       virtual ~Impl() {}
-
-       Result checkReferences(const SignatureData &signatureData)
-       {
-               const ReferenceSet &refSet = signatureData.getReferenceSet();
-               ReferenceSet refDecoded;
-
-               try {
-                       for (auto it = refSet.begin(); it != refSet.end(); ++it) {
-                               if (std::string::npos != it->find(MARK_ENCODED_CHAR))
-                                       refDecoded.insert(decodeProcent(*it));
-                               else
-                                       refDecoded.insert(*it);
-                       }
-               } catch (Result &) {
-                       return ERROR_DECODING_URL;
-               }
-
-               return dfsCheckDirectories(
-                                  refDecoded,
-                                  std::string(),
-                                  signatureData.isAuthorSignature());
-       }
-
-       Result checkOutbound(const std::string &linkPath, const std::string &appPath)
-       {
-               char resolvedPath[PATH_MAX];
-
-               if (realpath((appPath + "/" + linkPath).c_str(), resolvedPath) == NULL)
-                       return ERROR_READING_LNK;
-
-               std::string linkRealPath(resolvedPath);
-
-               if (linkRealPath.compare(0, appPath.size(), appPath) == 0)
-                       return NO_ERROR;
-               else
-                       return ERROR_OUTBOUND_LNK;
-       }
-
-private:
-       int hexToInt(char hex);
-       std::string decodeProcent(const std::string &path);
-
-       Result dfsCheckDirectories(
-               const ReferenceSet &referenceSet,
-               const std::string &directory,
-               bool isAuthorSignature);
-
-       inline bool isDistributorSignature(const char *cstring) const
-       {
-               return m_signatureRegexp.FullMatch(cstring);
-       }
-
-       std::string m_dirpath;
-       pcrecpp::RE m_signatureRegexp;
-};
-
-int ReferenceValidator::Impl::hexToInt(char a)
-{
-       if (a >= '0' && a <= '9') return a - '0';
-
-       if (a >= 'A' && a <= 'F') return a - 'A' + 10;
-
-       if (a >= 'a' && a <= 'f') return a - 'a' + 10;
-
-       LogError("Symbol '" << a << "' is out of scope.");
-       throw ERROR_DECODING_URL;
-}
-
-std::string ReferenceValidator::Impl::decodeProcent(const std::string &path)
-{
-       std::vector<int> input(path.begin(), path.end());
-       std::vector<char> output;
-
-       try {
-               size_t i = 0;
-
-               while (i < input.size()) {
-                       if (MARK_ENCODED_CHAR == input[i]) {
-                               if (i + 2 >= input.size())
-                                       throw ERROR_DECODING_URL;
-
-                               int result = hexToInt(input[i + 1]) * 16 + hexToInt(input[i + 2]);
-                               output.push_back(static_cast<char>(result));
-                               i += 3;
-                       } else {
-                               output.push_back(static_cast<char>(input[i]));
-                               ++i;
-                       }
-               }
-       } catch (Result &) {
-               LogError("Error while decoding url path : " << path);
-               throw ERROR_DECODING_URL;
-       }
-
-       return std::string(output.begin(), output.end());
-}
-
-ReferenceValidator::Result ReferenceValidator::Impl::dfsCheckDirectories(
-       const ReferenceSet &referenceSet,
-       const std::string &directory,
-       bool isAuthorSignature)
-{
-       int ret;
-       DIR *dirp;
-       struct dirent entry;
-       struct dirent *result;
-       std::string currentDir = m_dirpath;
-
-       if (!directory.empty()) {
-               currentDir += "/";
-               currentDir += directory;
-       }
-
-       if ((dirp = opendir(currentDir.c_str())) == NULL) {
-               LogError("Error opening directory : " << currentDir);
-               return ERROR_OPENING_DIR;
-       }
-
-       for (ret = readdir_r(dirp, &entry, &result);
-                       ret == 0 && result != NULL;
-                       ret = readdir_r(dirp, &entry, &result)) {
-               if (!strcmp(result->d_name, SPECIAL_SYMBOL_CURRENT_DIR)) {
-                       continue;
-               }
-
-               if (!strcmp(result->d_name, SPECIAL_SYMBOL_UPPER_DIR)) {
-                       continue;
-               }
-
-               if (result->d_type == DT_UNKNOWN) {
-                       // try to stat inode when readdir is not returning known type
-                       std::string path = currentDir + "/" + result->d_name;
-                       struct stat s;
-
-                       if (lstat(path.c_str(), &s) != 0) {
-                               closedir(dirp);
-                               return ERROR_LSTAT;
-                       }
-
-                       if (S_ISREG(s.st_mode)) {
-                               result->d_type = DT_REG;
-                       } else if (S_ISDIR(s.st_mode)) {
-                               result->d_type = DT_DIR;
-                       }
-               }
-
-               if (currentDir == m_dirpath && result->d_type == DT_REG &&
-                               !strcmp(result->d_name, SPECIAL_SYMBOL_AUTHOR_SIGNATURE_FILE) &&
-                               isAuthorSignature) {
-                       continue;
-               }
-
-               if (currentDir == m_dirpath && result->d_type == DT_REG &&
-                               isDistributorSignature(result->d_name)) {
-                       continue;
-               }
-
-               if (result->d_type == DT_DIR) {
-                       LogDebug("Open directory : " << (directory + result->d_name));
-                       std::string tmp_directory = directory + result->d_name + "/";
-                       Result result = dfsCheckDirectories(referenceSet,
-                                                                                               tmp_directory,
-                                                                                               isAuthorSignature);
-
-                       if (result != NO_ERROR) {
-                               closedir(dirp);
-                               return result;
-                       }
-               } else if (result->d_type == DT_REG) {
-                       if (referenceSet.end() ==
-                                       referenceSet.find(directory + result->d_name)) {
-                               LogDebug("Found file : " << (directory + result->d_name));
-                               LogError("Unknown ERROR_REFERENCE_NOT_FOUND.");
-                               closedir(dirp);
-                               return ERROR_REFERENCE_NOT_FOUND;
-                       }
-               } else if (result->d_type == DT_LNK) {
-                       std::string linkPath(directory + result->d_name);
-
-                       if (referenceSet.end() ==
-                                       referenceSet.find(linkPath)) {
-                               LogDebug("Found file : " << (directory + result->d_name));
-                               LogError("Unknown ERROR_REFERENCE_NOT_FOUND.");
-                               closedir(dirp);
-                               return ERROR_REFERENCE_NOT_FOUND;
-                       }
-
-                       Result ret = checkOutbound(linkPath, m_dirpath);
-
-                       if (ret != NO_ERROR) {
-                               LogError("Link file point wrong path");
-                               closedir(dirp);
-                               return ret;
-                       }
-               } else {
-                       LogError("Unknown file type.");
-                       closedir(dirp);
-                       return ERROR_UNSUPPORTED_FILE_TYPE;
-               }
-       }
-
-       if (ret != 0) {
-               closedir(dirp);
-               return ERROR_READING_DIR;
-       }
-
-       closedir(dirp);
-       return NO_ERROR;
-}
-
-ReferenceValidator::ReferenceValidator(const std::string &dirpath)
-       : m_impl(new Impl(dirpath))
-{}
-
-ReferenceValidator::~ReferenceValidator()
-{
-       delete m_impl;
-}
-
-ReferenceValidator::Result ReferenceValidator::checkReferences(
-       const SignatureData &signatureData)
-{
-       return m_impl->checkReferences(signatureData);
-}
-
-ReferenceValidator::Result ReferenceValidator::checkOutbound(
-       const std::string &linkPath, const std::string &appPath)
-{
-       return m_impl->checkOutbound(linkPath, appPath);
-}
-} // ValidationCore
diff --git a/vcore/vcore/ReferenceValidator.h b/vcore/vcore/ReferenceValidator.h
deleted file mode 100644 (file)
index 450e224..0000000
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright (c) 2011 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.
- */
-/*
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- *              Sangwan Kwon (sangwan.kwon@samsung.com)
- * @file        ReferenceValidator.h
- * @version     1.0
- * @brief       Compare signature reference list with widget package.
- */
-#ifndef _VALIDATION_CORE_REFERENCEVALIDATOR_H_
-#define _VALIDATION_CORE_REFERENCEVALIDATOR_H_
-
-#include <vcore/SignatureData.h>
-
-namespace ValidationCore {
-
-class ReferenceValidator {
-public:
-       enum Result {
-               NO_ERROR = 0,
-               ERROR_OPENING_DIR,
-               ERROR_READING_DIR,
-               ERROR_UNSUPPORTED_FILE_TYPE,
-               ERROR_REFERENCE_NOT_FOUND,
-               ERROR_DECODING_URL,
-               ERROR_OUTBOUND_LNK,
-               ERROR_READING_LNK,
-               ERROR_LSTAT
-       };
-
-       ReferenceValidator(const std::string &dirpath);
-       virtual ~ReferenceValidator();
-
-       ReferenceValidator(const ReferenceValidator &) = delete;
-       ReferenceValidator &operator=(const ReferenceValidator &) = delete;
-       ReferenceValidator(ReferenceValidator &&) = delete;
-       ReferenceValidator &operator=(ReferenceValidator &&) = delete;
-
-       Result checkReferences(const SignatureData &signatureData);
-       Result checkOutbound(const std::string &linkPath, const std::string &appPath);
-
-private:
-       class Impl;
-       Impl *m_impl;
-};
-}
-
-#endif // _VALIDATION_CORE_REFERENCEVALIDATOR_H_
diff --git a/vcore/vcore/SaxReader.cpp b/vcore/vcore/SaxReader.cpp
deleted file mode 100644 (file)
index 46dd690..0000000
+++ /dev/null
@@ -1,246 +0,0 @@
-/*
- * Copyright (c) 2011 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        SaxReader.cpp
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief       Simple c++ interface for libxml2.
- */
-#include <dpl/assert.h>
-#include <dpl/log/log.h>
-
-#include <vcore/SaxReader.h>
-
-namespace ValidationCore {
-
-
-SaxReader::SaxReader() :
-       m_reader(0)
-{
-}
-
-SaxReader::~SaxReader()
-{
-       if (m_reader) {
-               deinitialize();
-       }
-}
-
-void SaxReader::initialize(
-       const std::string &filename,
-       bool defaultArgs,
-       ValidationType validate,
-       const std::string &schema)
-{
-       Assert(m_reader == 0 && "Double initialization of SaxReader");
-       LogDebug("SaxReader opening file: " << filename);
-       m_reader = xmlNewTextReaderFilename(filename.c_str());
-
-       if (!m_reader) {
-               VcoreThrowMsg(SaxReader::Exception::FileOpeningError,
-                                         "opening file " << filename << " error");
-       }
-
-       if (validate == VALIDATION_XMLSCHEME &&
-                       xmlTextReaderSchemaValidate(m_reader, schema.c_str())) {
-               /*
-                * unable to turn on schema validation
-                */
-               VcoreThrowMsg(SaxReader::Exception::ParserInternalError,
-                                         "Turn on Schema validation failed");
-       }
-
-       // Path to DTD schema is taken from xml file.
-       if (validate == VALIDATION_DTD &&
-                       xmlTextReaderSetParserProp(m_reader, XML_PARSER_VALIDATE, 1)) {
-               /*
-                * unable to turn on DTD validation
-                */
-               VcoreThrowMsg(SaxReader::Exception::ParserInternalError,
-                                         "Turn on DTD validation failed!");
-       }
-
-       if (defaultArgs &&
-                       xmlTextReaderSetParserProp(m_reader, XML_PARSER_DEFAULTATTRS, 1)) {
-               /*
-                * unable to turn on default arguments
-                */
-               VcoreThrowMsg(SaxReader::Exception::ParserInternalError,
-                                         "Turn on default arguments failed");
-       }
-}
-
-void SaxReader::deinitialize()
-{
-       xmlFreeTextReader(m_reader);
-       m_reader = 0;
-}
-
-bool SaxReader::next()
-{
-       int res = xmlTextReaderRead(m_reader);
-
-       if (res < 0)
-               VcoreThrowMsg(SaxReader::Exception::ParserInternalError,
-                                         "xmlTextReaderRead error");
-
-       if (!xmlTextReaderIsValid(m_reader))
-               VcoreThrowMsg(SaxReader::Exception::FileNotValid,
-                                         "xmlTextReader is invalid");
-
-       return res ? true : false;
-}
-
-void SaxReader::next(const std::string &token)
-{
-       int res = xmlTextReaderRead(m_reader);
-
-       if (res < 0)
-               VcoreThrowMsg(SaxReader::Exception::ParserInternalError,
-                                         "xmlTextReaderRead error");
-
-       if (!xmlTextReaderIsValid(m_reader))
-               VcoreThrowMsg(SaxReader::Exception::FileNotValid,
-                                         "xmlTextReader is invalid");
-
-       xmlChar *name = xmlTextReaderName(m_reader);
-
-       if (!name)
-               VcoreThrowMsg(SaxReader::Exception::ParserInternalError,
-                                         "xmlTextReaderName returns NULL");
-
-       xmlChar *xmlToken = xmlCharStrdup(token.c_str());
-
-       if (xmlStrcmp(name, xmlToken)) {
-               xmlFree(name);
-               xmlFree(xmlToken);
-               VcoreThrowMsg(SaxReader::Exception::WrongToken, "Wrong Token");
-       }
-
-       xmlFree(name);
-       xmlFree(xmlToken);
-}
-
-bool SaxReader::isEmpty(void)
-{
-       int ret = xmlTextReaderIsEmptyElement(m_reader);
-
-       if (-1 == ret)
-               VcoreThrowMsg(SaxReader::Exception::ParserInternalError,
-                                         "xmlTextReaderIsEmptyElement error");
-
-       return ret ? true : false;
-}
-
-std::string SaxReader::attribute(const std::string &token, ThrowType throwStatus)
-{
-       xmlChar *attr = xmlTextReaderGetAttribute(m_reader, BAD_CAST(token.c_str()));
-
-       if (!attr) {
-               if (throwStatus == THROW_DISABLE) {
-                       return std::string();
-               } else {
-                       VcoreThrowMsg(SaxReader::Exception::ParserInternalError,
-                                                 "xmlTextReaderGetAttribute error");
-               }
-       }
-
-       std::string value = reinterpret_cast<const char *>(attr);
-       xmlFree(attr);
-       return value;
-}
-
-std::string SaxReader::name()
-{
-       xmlChar *name = xmlTextReaderName(m_reader);
-
-       if (!name)
-               VcoreThrowMsg(SaxReader::Exception::ReadingNameError,
-                                         "reading name error");
-
-       std::string value = reinterpret_cast<const char *>(name);
-       xmlFree(name);
-       size_t pos = value.find_last_of(":");
-
-       if (pos != std::string::npos) {
-               value.erase(0, pos + 1);
-       }
-
-       return value;
-}
-
-std::string SaxReader::namespaceURI()
-{
-       xmlChar *name = xmlTextReaderNamespaceUri(m_reader);
-
-       if (!name) {
-               return std::string();
-       }
-
-       std::string value = reinterpret_cast<const char *>(name);
-       xmlFree(name);
-       return value;
-}
-
-std::string SaxReader::value()
-{
-       xmlChar *text = xmlTextReaderValue(m_reader);
-
-       if (!text)
-               VcoreThrowMsg(SaxReader::Exception::ReadingValueError,
-                                         "reading value error");
-
-       std::string value = reinterpret_cast<const char *>(text);
-       xmlFree(text);
-       return value;
-}
-
-SaxReader::NodeType SaxReader::type()
-{
-       xmlReaderTypes type =
-               static_cast<xmlReaderTypes>(xmlTextReaderNodeType(m_reader));
-
-       switch (type) {
-       case XML_READER_TYPE_ELEMENT:
-               return NODE_BEGIN;
-
-       case XML_READER_TYPE_END_ELEMENT:
-               return NODE_END;
-
-       case XML_READER_TYPE_TEXT:
-               return NODE_TEXT;
-
-       case XML_READER_TYPE_NONE:
-       case XML_READER_TYPE_ATTRIBUTE:
-       case XML_READER_TYPE_CDATA:
-       case XML_READER_TYPE_ENTITY_REFERENCE:
-       case XML_READER_TYPE_ENTITY:
-       case XML_READER_TYPE_PROCESSING_INSTRUCTION:
-       case XML_READER_TYPE_COMMENT:
-       case XML_READER_TYPE_DOCUMENT:
-       case XML_READER_TYPE_DOCUMENT_TYPE:
-       case XML_READER_TYPE_DOCUMENT_FRAGMENT:
-       case XML_READER_TYPE_NOTATION:
-       case XML_READER_TYPE_WHITESPACE:
-       case XML_READER_TYPE_SIGNIFICANT_WHITESPACE:
-       case XML_READER_TYPE_END_ENTITY:
-       case XML_READER_TYPE_XML_DECLARATION:
-       default:
-               return NODE_UNSUPPORTED;
-       }
-}
-
-} // namespace ValidationCore
diff --git a/vcore/vcore/SaxReader.h b/vcore/vcore/SaxReader.h
deleted file mode 100644 (file)
index 8c7e975..0000000
+++ /dev/null
@@ -1,133 +0,0 @@
-/*
- * Copyright (c) 2011 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        SaxReader.h
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief       Simple c++ interface for libxml2.
- *              Its used in wrt-installer only and should be removed
- *              from cert-svc.
- */
-#ifndef _SAXREADER_H_
-#define _SAXREADER_H_
-
-#include <string>
-#include <libxml/xmlreader.h>
-
-#include <vcore/exception.h>
-
-namespace ValidationCore {
-class SaxReader {
-public:
-       SaxReader();
-       ~SaxReader();
-
-       class Exception {
-       public:
-               VCORE_DECLARE_EXCEPTION_TYPE(ValidationCore::Exception, Base);
-               VCORE_DECLARE_EXCEPTION_TYPE(Base, FileOpeningError);
-               VCORE_DECLARE_EXCEPTION_TYPE(Base, FileNotValid);
-               VCORE_DECLARE_EXCEPTION_TYPE(Base, ParserInternalError);
-               VCORE_DECLARE_EXCEPTION_TYPE(Base, WrongToken);
-               VCORE_DECLARE_EXCEPTION_TYPE(Base, ReadingValueError);
-               VCORE_DECLARE_EXCEPTION_TYPE(Base, ReadingNameError);
-               VCORE_DECLARE_EXCEPTION_TYPE(Base, UnsupportedType);
-       };
-
-       enum NodeType {
-               NODE_UNSUPPORTED,
-               NODE_BEGIN,
-               NODE_END,
-               NODE_TEXT
-       };
-
-       enum ThrowType {
-               THROW_ENABLE = 0,
-               THROW_DISABLE
-       };
-
-       /*
-        * xml validation modes
-        */
-       enum ValidationType {
-               VALIDATION_DISABLE,
-               VALIDATION_XMLSCHEME,
-               VALIDATION_DTD
-       };
-
-       /*
-        * initializes parser
-        */
-       void initialize(
-               const std::string &filename,
-               bool defaultArgs = false,
-               ValidationType validation = VALIDATION_DISABLE,
-               const std::string &schema = std::string());
-       /*
-        * deinitializes parser
-        */
-       void deinitialize();
-
-       /**
-        * Move to next xml node.
-        */
-       bool next();
-
-       /**
-        * Move to next xml node. If next node name is differ from token the exception wiil
-        * be thronw.
-        */
-       void next(const std::string &token);
-
-       /**
-        * Check if xml tag is empty.
-        */
-       bool isEmpty(void);
-
-       /**
-        * Read attribute tag.
-        */
-       std::string attribute(const std::string &token, ThrowType throwStatus = THROW_ENABLE);
-
-       /**
-        * Read xml tag name without namespace.
-        */
-       std::string name();
-
-       /**
-        * Read xml tag namespace URI
-        */
-       std::string namespaceURI();
-
-       /**
-        * Read xml tag value.
-        */
-       std::string value();
-
-       /**
-        * Return information about node type.
-        */
-       NodeType type();
-
-private:
-       /*
-        * internal libxml text reader
-        */
-       xmlTextReaderPtr m_reader;
-};
-}
-
-#endif // _SAXREADER_H_
diff --git a/vcore/vcore/SignatureData.cpp b/vcore/vcore/SignatureData.cpp
deleted file mode 100644 (file)
index 8663414..0000000
+++ /dev/null
@@ -1,156 +0,0 @@
-/*
- * Copyright (c) 2011 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        SignatureData.cpp
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief       SignatureData is used to storage data parsed from digsig file.
- */
-#include <vcore/SignatureData.h>
-
-#include <dpl/log/log.h>
-
-namespace ValidationCore {
-
-SignatureData::SignatureData()
-       : m_signatureNumber(-1)
-       , m_certificateSorted(false)
-{}
-
-SignatureData::SignatureData(const std::string &fileName, int fileNumber)
-       : m_signatureNumber(fileNumber)
-       , m_fileName(fileName)
-       , m_certificateSorted(false)
-{}
-
-SignatureData::~SignatureData()
-{}
-
-const ReferenceSet &SignatureData::getReferenceSet() const
-{
-       return m_referenceSet;
-}
-
-void SignatureData::setReference(const ReferenceSet &referenceSet)
-{
-       m_referenceSet = referenceSet;
-}
-
-CertificateList SignatureData::getCertList() const
-{
-       return m_certList;
-}
-
-void SignatureData::setSortedCertificateList(const CertificateList &list)
-{
-       m_certList = list;
-       m_certificateSorted = true;
-}
-
-bool SignatureData::isAuthorSignature() const
-{
-       return m_signatureNumber == -1;
-}
-
-std::string SignatureData::getSignatureFileName() const
-{
-       return m_fileName;
-}
-
-int SignatureData::getSignatureNumber() const
-{
-       return m_signatureNumber;
-}
-
-std::string SignatureData::getRoleURI() const
-{
-       return m_roleURI;
-}
-
-std::string SignatureData::getProfileURI() const
-{
-       return m_profileURI;
-}
-
-bool SignatureData::containObjectReference(const std::string &ref) const
-{
-       std::string rName = "#";
-       rName += ref;
-       return m_referenceSet.end() != m_referenceSet.find(rName);
-}
-
-ObjectList SignatureData::getObjectList() const
-{
-       return m_objectList;
-}
-
-void SignatureData::setStorageType(const CertStoreId::Set &storeIdSet)
-{
-       m_storeIdSet = storeIdSet;
-}
-
-bool SignatureData::isCertListSorted() const
-{
-       return m_certificateSorted;
-}
-
-const CertStoreId::Set &SignatureData::getStorageType() const
-{
-       return m_storeIdSet;
-}
-
-CertStoreId::Type SignatureData::getVisibilityLevel() const
-{
-       if (!m_storeIdSet.isContainsVis()) {
-               LogWarning("Visibility level was broken.");
-               return 0;
-       }
-
-       if (m_storeIdSet.contains(CertStoreId::VIS_PLATFORM))
-               return CertStoreId::VIS_PLATFORM;
-       else if (m_storeIdSet.contains(CertStoreId::VIS_PARTNER))
-               return CertStoreId::VIS_PARTNER;
-       else
-               return CertStoreId::VIS_PUBLIC;
-}
-
-const SignatureData::IMEIList &SignatureData::getIMEIList() const
-{
-       return m_imeiList;
-}
-
-const SignatureData::MEIDList &SignatureData::getMEIDList() const
-{
-       return m_meidList;
-}
-
-CertificatePtr SignatureData::getEndEntityCertificatePtr() const
-{
-       if (m_certificateSorted)
-               return m_certList.front();
-
-       return CertificatePtr();
-}
-
-CertificatePtr SignatureData::getRootCaCertificatePtr() const
-{
-       if (m_certificateSorted)
-               return m_certList.back();
-
-       return CertificatePtr();
-}
-
-} // ValidationCore
diff --git a/vcore/vcore/SignatureData.h b/vcore/vcore/SignatureData.h
deleted file mode 100644 (file)
index 52e39fa..0000000
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright (c) 2011 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        SignatureData.h
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief       SignatureData is used to storage data parsed from digsig file.
- */
-#ifndef _SIGNATUREDATA_H_
-#define _SIGNATUREDATA_H_
-
-#include <list>
-#include <set>
-#include <string>
-
-#include <vcore/Certificate.h>
-#include <vcore/CertStoreType.h>
-
-namespace ValidationCore {
-
-typedef std::set<std::string> ReferenceSet;
-typedef std::list<std::string> ObjectList;
-
-class SignatureData {
-public:
-       SignatureData();
-       SignatureData(const std::string &fileName, int fileNumber);
-
-       virtual ~SignatureData();
-
-       typedef std::list<std::string> IMEIList;
-       typedef std::list<std::string> MEIDList;
-
-       void setReference(const ReferenceSet &referenceSet);
-       void setSortedCertificateList(const CertificateList &list);
-       void setStorageType(const CertStoreId::Set &storeIdSet);
-       bool isCertListSorted() const;
-
-       const ReferenceSet &getReferenceSet() const;
-       CertificateList getCertList() const;
-       ObjectList getObjectList() const;
-       bool containObjectReference(const std::string &ref) const;
-       bool isAuthorSignature() const;
-       int getSignatureNumber() const;
-       std::string getSignatureFileName() const;
-       std::string getRoleURI() const;
-       std::string getProfileURI() const;
-       const CertStoreId::Set &getStorageType() const;
-       CertStoreId::Type getVisibilityLevel() const;
-       const IMEIList &getIMEIList() const;
-       const MEIDList &getMEIDList() const;
-       CertificatePtr getEndEntityCertificatePtr() const;
-       CertificatePtr getRootCaCertificatePtr() const;
-
-       friend class SignatureReader;
-
-private:
-       ReferenceSet m_referenceSet;
-       CertificateList m_certList;
-
-       //TargetRestriction
-       IMEIList m_imeiList;
-       MEIDList m_meidList;
-
-       /*
-        * This number is taken from distributor signature file name.
-        * Author signature do not contain any number on the file name.
-        * Author signature should have signature number equal to -1.
-        */
-       int m_signatureNumber;
-       std::string m_fileName;
-       std::string m_roleURI;
-       std::string m_profileURI;
-       std::string m_identifier;
-       ObjectList m_objectList;
-       CertStoreId::Set m_storeIdSet;
-       bool m_certificateSorted;
-};
-
-typedef std::set<SignatureData> SignatureDataSet;
-
-} // ValidationCore
-
-#endif
diff --git a/vcore/vcore/SignatureFinder.cpp b/vcore/vcore/SignatureFinder.cpp
deleted file mode 100644 (file)
index 5010563..0000000
+++ /dev/null
@@ -1,137 +0,0 @@
-/*
- * Copyright (c) 2011 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        SignatureFinder.cpp
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief       Search for author-signature.xml and signatureN.xml files.
- */
-#include <vcore/SignatureFinder.h>
-#include <dpl/log/log.h>
-
-#include <dirent.h>
-#include <errno.h>
-#include <istream>
-#include <sstream>
-
-#include <pcrecpp.h>
-
-namespace {
-
-}
-
-namespace ValidationCore {
-static const char *SIGNATURE_AUTHOR = "author-signature.xml";
-static const char *REGEXP_DISTRIBUTOR_SIGNATURE =
-       "^(signature)([1-9][0-9]*)(\\.xml)";
-
-class SignatureFinder::Impl {
-public:
-       Impl(const std::string &dir)
-               : m_dir(dir)
-               , m_signatureRegexp(REGEXP_DISTRIBUTOR_SIGNATURE)
-       {}
-
-       virtual ~Impl() {}
-
-       Result find(SignatureFileInfoSet &set);
-
-private:
-       std::string getFullPath(const std::string &file);
-
-       std::string m_dir;
-       pcrecpp::RE m_signatureRegexp;
-};
-
-std::string SignatureFinder::Impl::getFullPath(const std::string &file)
-{
-       std::string fullPath = m_dir;
-
-       if (fullPath.back() != '/')
-               fullPath += "/";
-
-       fullPath += file;
-       return fullPath;
-}
-
-SignatureFinder::Result SignatureFinder::Impl::find(SignatureFileInfoSet &set)
-{
-       int ret;
-       DIR *dirp;
-       struct dirent entry;
-       struct dirent *result;
-
-       if ((dirp = opendir(m_dir.c_str())) == NULL) {
-               LogError("Error opening directory: " << m_dir);
-               return ERROR_OPENING_DIR;
-       }
-
-       for (ret = readdir_r(dirp, &entry, &result);
-                       ret == 0 && result != NULL;
-                       ret = readdir_r(dirp, &entry, &result)) {
-               /* number for author signature is -1 */
-               if (!strcmp(result->d_name, SIGNATURE_AUTHOR)) {
-                       std::string fullPath = getFullPath(std::string(result->d_name));
-                       LogDebug("Found author signature file full path : " << fullPath);
-                       set.insert(SignatureFileInfo(fullPath, -1));
-                       continue;
-               }
-
-               std::string sig;
-               std::string num;
-               std::string xml; /* just for cutting out .xml */
-
-               if (m_signatureRegexp.FullMatch(result->d_name, &sig, &num, &xml)) {
-                       std::istringstream stream(num);
-                       int number;
-                       stream >> number;
-
-                       if (stream.fail()) {
-                               closedir(dirp);
-                               return ERROR_ISTREAM;
-                       }
-
-                       std::string fullPath = getFullPath(std::string(result->d_name));
-                       LogDebug("Found signature file full path : " << fullPath);
-                       set.insert(SignatureFileInfo(fullPath, number));
-               }
-       }
-
-       if (ret != 0) {
-               LogError("Error in readdir");
-               closedir(dirp);
-               return ERROR_READING_DIR;
-       }
-
-       closedir(dirp);
-       return NO_ERROR;
-}
-
-SignatureFinder::SignatureFinder(const std::string &dir)
-       : m_impl(new Impl(dir))
-{}
-
-SignatureFinder::~SignatureFinder()
-{
-       delete m_impl;
-}
-
-SignatureFinder::Result SignatureFinder::find(SignatureFileInfoSet &set)
-{
-       return m_impl->find(set);
-}
-
-} // namespace ValidationCore
diff --git a/vcore/vcore/SignatureFinder.h b/vcore/vcore/SignatureFinder.h
deleted file mode 100644 (file)
index 40881b9..0000000
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * Copyright (c) 2011 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        SignatureFinder.h
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief       Search for author-signature.xml and signatureN.xml files.
- *              This class is WAC 2.0 specific and shuld be moved to
- *              wrt-installer.
- */
-#ifndef _VALIDATION_CORE_SIGNATUREFINDER_H_
-#define _VALIDATION_CORE_SIGNATUREFINDER_H_
-
-#include <set>
-#include <string>
-
-namespace ValidationCore {
-
-class SignatureFileInfo {
-public:
-       SignatureFileInfo(const std::string &fileName, int num)
-               : m_fileName(fileName)
-               , m_fileNumber(num)
-       {}
-
-       std::string getFileName() const
-       {
-               return m_fileName;
-       }
-
-       int getFileNumber() const
-       {
-               return m_fileNumber;
-       }
-
-       bool operator<(const SignatureFileInfo &second) const
-       {
-               return m_fileNumber < second.m_fileNumber;
-       }
-
-private:
-       std::string m_fileName;
-       int m_fileNumber;
-};
-
-typedef std::set<SignatureFileInfo> SignatureFileInfoSet;
-
-class SignatureFinder {
-public:
-       enum Result {
-               NO_ERROR,
-               ERROR_OPENING_DIR,
-               ERROR_READING_DIR,
-               ERROR_ISTREAM
-       };
-
-       SignatureFinder() = delete;
-       explicit SignatureFinder(const std::string &dir);
-
-       virtual ~SignatureFinder();
-
-       Result find(SignatureFileInfoSet &set);
-
-private:
-       class Impl;
-       Impl *m_impl;
-
-       SignatureFinder(const SignatureFinder &);
-       const SignatureFinder &operator=(const SignatureFinder &);
-};
-
-} // namespace ValidationCore
-
-#endif // _VALIDATION_CORE_SIGNATUREFINDER_H_
diff --git a/vcore/vcore/SignatureReader.cpp b/vcore/vcore/SignatureReader.cpp
deleted file mode 100644 (file)
index 3fd1b58..0000000
+++ /dev/null
@@ -1,579 +0,0 @@
-/*
- * Copyright (c) 2011 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        SignatureReader.cpp
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief       SignatureReader is used to parse widget digital signature.
- */
-#include <vcore/SignatureReader.h>
-
-#include <vcore/CertificateLoader.h>
-
-namespace ValidationCore {
-static const std::string XML_NAMESPACE =
-       "http://www.w3.org/2000/09/xmldsig#";
-static const std::string XML_NAMESPACE_DIGITALSIG =
-       "http://wacapps.net/ns/digsig";
-static const std::string XML_OBJ_NS =
-       "http://www.w3.org/2009/xmldsig-properties";
-
-// TAG TOKENS
-static const std::string TOKEN_SIGNATURE = "Signature";
-static const std::string TOKEN_SIGNED_INFO = "SignedInfo";
-static const std::string TOKEN_CANONICALIZATION_METHOD =
-       "CanonicalizationMethod";
-static const std::string TOKEN_SIGNATURE_METHOD = "SignatureMethod";
-static const std::string TOKEN_REFERENCE = "Reference";
-static const std::string TOKEN_TRANSFORMS = "Transforms";
-static const std::string TOKEN_TRANSFORM = "Transform";
-static const std::string TOKEN_DIGEST_METHOD = "DigestMethod";
-static const std::string TOKEN_DIGEST_VALUE = "DigestValue";
-static const std::string TOKEN_SIGNATURE_VALUE = "SignatureValue";
-static const std::string TOKEN_KEY_INFO = "KeyInfo";
-static const std::string TOKEN_X509DATA = "X509Data";
-static const std::string TOKEN_X509CERTIFICATE = "X509Certificate";
-static const std::string TOKEN_KEY_VALUE = "KeyValue";
-static const std::string TOKEN_RSA_KEY_VALUE = "RSAKeyValue";
-static const std::string TOKEN_MODULUS_COMPONENT = "Modulus";
-static const std::string TOKEN_EXPONENT_COMPONENT = "Exponent";
-static const std::string TOKEN_ECKEY_VALUE = "ECKeyValue";
-static const std::string TOKEN_NAMED_CURVE = "NamedCurve";
-static const std::string TOKEN_PUBLIC_KEY = "PublicKey";
-static const std::string TOKEN_OBJECT = "Object";
-static const std::string TOKEN_SIGNATURE_PROPERTIES = "SignatureProperties";
-static const std::string TOKEN_SIGNATURE_PROPERTY = "SignatureProperty";
-static const std::string TOKEN_PROFILE = "Profile";
-static const std::string TOKEN_ROLE = "Role";
-static const std::string TOKEN_IDENTIFIER = "Identifier";
-static const std::string TOKEN_DSAKEYVALUE = "DSAKeyValue";
-static const std::string TOKEN_DSA_P_COMPONENT = "P";
-static const std::string TOKEN_DSA_Q_COMPONENT = "Q";
-static const std::string TOKEN_DSA_G_COMPONENT = "G";
-static const std::string TOKEN_DSA_Y_COMPONENT = "Y";
-static const std::string TOKEN_DSA_J_COMPONENT = "J";
-static const std::string TOKEN_DSA_SEED_COMPONENT = "Seed";
-static const std::string TOKEN_DSA_PGENCOUNTER_COMPONENT = "PgenCounter";
-static const std::string TOKEN_TARGET_RESTRICTION = "TargetRestriction";
-
-// ATTRIBUTTE TOKENS
-
-static const std::string TOKEN_ALGORITHM = "Algorithm";
-static const std::string TOKEN_URI = "URI";
-static const std::string TOKEN_ID = "Id";
-static const std::string TOKEN_TARGET = "Target";
-static const std::string TOKEN_IMEI = "IMEI";
-static const std::string TOKEN_MEID = "MEID";
-
-// ATTIRUBTE VALUES
-
-static const std::string TOKEN_ATTR_PROFILE = "profile";
-static const std::string TOKEN_ATTR_ROLE = "role";
-static const std::string TOKEN_ATTR_IDENTIFIER = "identifier";
-
-// ALGORITHMS
-
-//static const std::string TOKEN_ALGORITHM_XML_EXC_CAN   =
-//            "http://www.w3.org/2001/10/xml-exc-c14n#";
-//static const std::string TOKEN_ALGORITHM_RSA_SHA256    =
-//            "http://www.w3.org/2001/04/xmldsig-more#rsa-sha256";
-//static const std::string TOKEN_ALGORITHM_DSA_SHA1      =
-//            "http://www.w3.org/2000/09/xmldsig#dsa-sha1";
-//static const std::string TOKEN_ALGORITHM_ECDSA_SHA256  =
-//            "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256";
-//static const std::string TOKEN_ALGORITHM_SHA1          =
-//            "http://www.w3.org/2000/09/xmldsig#sha1";
-//static const std::string TOKEN_ALGORITHM_SHA256        =
-//            "http://www.w3.org/2001/04/xmlenc#sha256";
-//static const std::string TOKEN_ALGORITHM_SHA384        =
-//            "http://www.w3.org/2001/04/xmldsig-more#sha384";
-//static const std::string TOKEN_ALGORITHM_SHA512        =
-//            "http://www.w3.org/2001/04/xmlenc#sha512";
-
-SignatureReader::SignatureReader() :
-       m_signaturePropertiesCounter(0),
-       m_targetRestrictionObjectFound(false),
-       m_parserSchema(this)
-{
-       /**
-        * member func pointers map
-        */
-       m_parserSchema.addBeginTagCallback(TOKEN_SIGNATURE,
-                                                                          XML_NAMESPACE,
-                                                                          &SignatureReader::blankFunction);
-       m_parserSchema.addBeginTagCallback(TOKEN_SIGNED_INFO,
-                                                                          XML_NAMESPACE,
-                                                                          &SignatureReader::blankFunction);
-       m_parserSchema.addBeginTagCallback(TOKEN_CANONICALIZATION_METHOD,
-                                                                          XML_NAMESPACE,
-                                                                          &SignatureReader::blankFunction);
-       m_parserSchema.addBeginTagCallback(TOKEN_SIGNATURE_METHOD,
-                                                                          XML_NAMESPACE,
-                                                                          &SignatureReader::blankFunction);
-       m_parserSchema.addBeginTagCallback(TOKEN_REFERENCE,
-                                                                          XML_NAMESPACE,
-                                                                          &SignatureReader::blankFunction);
-       m_parserSchema.addBeginTagCallback(TOKEN_TRANSFORMS,
-                                                                          XML_NAMESPACE,
-                                                                          &SignatureReader::blankFunction);
-       m_parserSchema.addBeginTagCallback(TOKEN_TRANSFORM,
-                                                                          XML_NAMESPACE,
-                                                                          &SignatureReader::blankFunction);
-       m_parserSchema.addBeginTagCallback(TOKEN_DIGEST_METHOD,
-                                                                          XML_NAMESPACE,
-                                                                          &SignatureReader::blankFunction);
-       m_parserSchema.addBeginTagCallback(TOKEN_DIGEST_VALUE,
-                                                                          XML_NAMESPACE,
-                                                                          &SignatureReader::blankFunction);
-       m_parserSchema.addBeginTagCallback(TOKEN_SIGNATURE_VALUE,
-                                                                          XML_NAMESPACE,
-                                                                          &SignatureReader::blankFunction);
-       m_parserSchema.addBeginTagCallback(TOKEN_KEY_INFO,
-                                                                          XML_NAMESPACE,
-                                                                          &SignatureReader::tokenKeyInfo);
-       m_parserSchema.addBeginTagCallback(TOKEN_X509DATA,
-                                                                          XML_NAMESPACE,
-                                                                          &SignatureReader::tokenX509Data);
-       m_parserSchema.addBeginTagCallback(TOKEN_X509CERTIFICATE,
-                                                                          XML_NAMESPACE,
-                                                                          &SignatureReader::tokenX509Certificate);
-       m_parserSchema.addBeginTagCallback(TOKEN_ECKEY_VALUE,
-                                                                          XML_NAMESPACE,
-                                                                          &SignatureReader::blankFunction);
-       m_parserSchema.addBeginTagCallback(TOKEN_NAMED_CURVE,
-                                                                          XML_NAMESPACE,
-                                                                          &SignatureReader::tokenNamedCurve);
-       m_parserSchema.addBeginTagCallback(TOKEN_PUBLIC_KEY,
-                                                                          XML_NAMESPACE,
-                                                                          &SignatureReader::tokenPublicKey);
-       m_parserSchema.addBeginTagCallback(TOKEN_OBJECT,
-                                                                          XML_NAMESPACE,
-                                                                          &SignatureReader::tokenObject);
-       m_parserSchema.addBeginTagCallback(TOKEN_SIGNATURE_PROPERTIES,
-                                                                          XML_NAMESPACE,
-                                                                          &SignatureReader::tokenSignatureProperties);
-       m_parserSchema.addBeginTagCallback(TOKEN_SIGNATURE_PROPERTY,
-                                                                          XML_NAMESPACE,
-                                                                          &SignatureReader::blankFunction);
-       m_parserSchema.addBeginTagCallback(TOKEN_PROFILE,
-                                                                          XML_OBJ_NS,
-                                                                          &SignatureReader::tokenProfile);
-       m_parserSchema.addBeginTagCallback(TOKEN_ROLE,
-                                                                          XML_OBJ_NS,
-                                                                          &SignatureReader::tokenRole);
-       m_parserSchema.addBeginTagCallback(TOKEN_IDENTIFIER,
-                                                                          XML_OBJ_NS,
-                                                                          &SignatureReader::blankFunction);
-       m_parserSchema.addBeginTagCallback(TOKEN_KEY_VALUE,
-                                                                          XML_NAMESPACE,
-                                                                          &SignatureReader::blankFunction);
-       m_parserSchema.addBeginTagCallback(TOKEN_DSAKEYVALUE,
-                                                                          XML_NAMESPACE,
-                                                                          &SignatureReader::blankFunction);
-       m_parserSchema.addBeginTagCallback(TOKEN_DSA_P_COMPONENT,
-                                                                          XML_NAMESPACE,
-                                                                          &SignatureReader::blankFunction);
-       m_parserSchema.addBeginTagCallback(TOKEN_DSA_Q_COMPONENT,
-                                                                          XML_NAMESPACE,
-                                                                          &SignatureReader::blankFunction);
-       m_parserSchema.addBeginTagCallback(TOKEN_DSA_G_COMPONENT,
-                                                                          XML_NAMESPACE,
-                                                                          &SignatureReader::blankFunction);
-       m_parserSchema.addBeginTagCallback(TOKEN_DSA_Y_COMPONENT,
-                                                                          XML_NAMESPACE,
-                                                                          &SignatureReader::blankFunction);
-       m_parserSchema.addBeginTagCallback(TOKEN_DSA_J_COMPONENT,
-                                                                          XML_NAMESPACE,
-                                                                          &SignatureReader::blankFunction);
-       m_parserSchema.addBeginTagCallback(TOKEN_DSA_SEED_COMPONENT,
-                                                                          XML_NAMESPACE,
-                                                                          &SignatureReader::blankFunction);
-       m_parserSchema.addBeginTagCallback(TOKEN_DSA_PGENCOUNTER_COMPONENT,
-                                                                          XML_NAMESPACE,
-                                                                          &SignatureReader::blankFunction);
-       m_parserSchema.addBeginTagCallback(TOKEN_RSA_KEY_VALUE,
-                                                                          XML_NAMESPACE,
-                                                                          &SignatureReader::blankFunction);
-       m_parserSchema.addBeginTagCallback(TOKEN_MODULUS_COMPONENT,
-                                                                          XML_NAMESPACE,
-                                                                          &SignatureReader::blankFunction);
-       m_parserSchema.addBeginTagCallback(TOKEN_EXPONENT_COMPONENT,
-                                                                          XML_NAMESPACE,
-                                                                          &SignatureReader::blankFunction);
-       m_parserSchema.addBeginTagCallback(TOKEN_TARGET_RESTRICTION,
-                                                                          XML_NAMESPACE_DIGITALSIG,
-                                                                          &SignatureReader::tokenTargetRestriction);
-       m_parserSchema.addEndTagCallback(TOKEN_SIGNATURE,
-                                                                        XML_NAMESPACE,
-                                                                        &SignatureReader::blankFunction);
-       m_parserSchema.addEndTagCallback(TOKEN_SIGNED_INFO,
-                                                                        XML_NAMESPACE,
-                                                                        &SignatureReader::blankFunction);
-       m_parserSchema.addEndTagCallback(TOKEN_CANONICALIZATION_METHOD,
-                                                                        XML_NAMESPACE,
-                                                                        &SignatureReader::blankFunction);
-       m_parserSchema.addEndTagCallback(TOKEN_SIGNATURE_METHOD,
-                                                                        XML_NAMESPACE,
-                                                                        &SignatureReader::blankFunction);
-       m_parserSchema.addEndTagCallback(TOKEN_REFERENCE,
-                                                                        XML_NAMESPACE,
-                                                                        &SignatureReader::blankFunction);
-       m_parserSchema.addEndTagCallback(TOKEN_TRANSFORMS,
-                                                                        XML_NAMESPACE,
-                                                                        &SignatureReader::blankFunction);
-       m_parserSchema.addEndTagCallback(TOKEN_TRANSFORM,
-                                                                        XML_NAMESPACE,
-                                                                        &SignatureReader::blankFunction);
-       m_parserSchema.addEndTagCallback(TOKEN_DIGEST_METHOD,
-                                                                        XML_NAMESPACE,
-                                                                        &SignatureReader::blankFunction);
-       m_parserSchema.addEndTagCallback(TOKEN_DIGEST_VALUE,
-                                                                        XML_NAMESPACE,
-                                                                        &SignatureReader::blankFunction);
-       m_parserSchema.addEndTagCallback(TOKEN_SIGNATURE_VALUE,
-                                                                        XML_NAMESPACE,
-                                                                        &SignatureReader::blankFunction);
-       m_parserSchema.addEndTagCallback(TOKEN_KEY_INFO,
-                                                                        XML_NAMESPACE,
-                                                                        &SignatureReader::tokenEndKeyInfo);
-       m_parserSchema.addEndTagCallback(TOKEN_X509DATA,
-                                                                        XML_NAMESPACE,
-                                                                        &SignatureReader::tokenEndX509Data);
-       m_parserSchema.addEndTagCallback(TOKEN_X509CERTIFICATE,
-                                                                        XML_NAMESPACE,
-                                                                        &SignatureReader::tokenEndX509Certificate);
-       m_parserSchema.addEndTagCallback(TOKEN_ECKEY_VALUE,
-                                                                        XML_NAMESPACE,
-                                                                        &SignatureReader::tokenEndECKeyValue);
-       m_parserSchema.addEndTagCallback(TOKEN_PUBLIC_KEY,
-                                                                        XML_NAMESPACE,
-                                                                        &SignatureReader::tokenEndPublicKey);
-       m_parserSchema.addEndTagCallback(TOKEN_OBJECT,
-                                                                        XML_NAMESPACE,
-                                                                        &SignatureReader::tokenEndObject);
-       m_parserSchema.addEndTagCallback(TOKEN_SIGNATURE_PROPERTIES,
-                                                                        XML_NAMESPACE,
-                                                                        &SignatureReader::blankFunction);
-       m_parserSchema.addEndTagCallback(TOKEN_SIGNATURE_PROPERTY,
-                                                                        XML_NAMESPACE,
-                                                                        &SignatureReader::blankFunction);
-       m_parserSchema.addEndTagCallback(TOKEN_PROFILE,
-                                                                        XML_OBJ_NS,
-                                                                        &SignatureReader::blankFunction);
-       m_parserSchema.addEndTagCallback(TOKEN_ROLE,
-                                                                        XML_OBJ_NS,
-                                                                        &SignatureReader::blankFunction);
-       m_parserSchema.addEndTagCallback(TOKEN_IDENTIFIER,
-                                                                        XML_OBJ_NS,
-                                                                        &SignatureReader::tokenEndIdentifier);
-       m_parserSchema.addEndTagCallback(TOKEN_KEY_VALUE,
-                                                                        XML_NAMESPACE,
-                                                                        &SignatureReader::blankFunction);
-       m_parserSchema.addEndTagCallback(TOKEN_DSAKEYVALUE,
-                                                                        XML_NAMESPACE,
-                                                                        &SignatureReader::tokenEndDSAKeyValue);
-       m_parserSchema.addEndTagCallback(TOKEN_DSA_P_COMPONENT,
-                                                                        XML_NAMESPACE,
-                                                                        &SignatureReader::tokenEndDSAPComponent);
-       m_parserSchema.addEndTagCallback(TOKEN_DSA_Q_COMPONENT,
-                                                                        XML_NAMESPACE,
-                                                                        &SignatureReader::tokenEndDSAQComponent);
-       m_parserSchema.addEndTagCallback(TOKEN_DSA_G_COMPONENT,
-                                                                        XML_NAMESPACE,
-                                                                        &SignatureReader::tokenEndDSAGComponent);
-       m_parserSchema.addEndTagCallback(TOKEN_DSA_Y_COMPONENT,
-                                                                        XML_NAMESPACE,
-                                                                        &SignatureReader::tokenEndDSAYComponent);
-       m_parserSchema.addEndTagCallback(TOKEN_DSA_J_COMPONENT,
-                                                                        XML_NAMESPACE,
-                                                                        &SignatureReader::tokenEndDSAJComponent);
-       m_parserSchema.addEndTagCallback(TOKEN_DSA_SEED_COMPONENT,
-                                                                        XML_NAMESPACE,
-                                                                        &SignatureReader::tokenEndDSASeedComponent);
-       m_parserSchema.addEndTagCallback(TOKEN_DSA_PGENCOUNTER_COMPONENT,
-                                                                        XML_NAMESPACE,
-                                                                        &SignatureReader::tokenEndDSAPGenCounterComponent);
-       m_parserSchema.addEndTagCallback(TOKEN_RSA_KEY_VALUE,
-                                                                        XML_NAMESPACE,
-                                                                        &SignatureReader::tokenEndRSAKeyValue);
-       m_parserSchema.addEndTagCallback(TOKEN_MODULUS_COMPONENT,
-                                                                        XML_NAMESPACE,
-                                                                        &SignatureReader::tokenEndKeyModulus);
-       m_parserSchema.addEndTagCallback(TOKEN_EXPONENT_COMPONENT,
-                                                                        XML_NAMESPACE,
-                                                                        &SignatureReader::tokenEndKeyExponent);
-       m_parserSchema.addEndTagCallback(TOKEN_TARGET_RESTRICTION,
-                                                                        XML_NAMESPACE,
-                                                                        &SignatureReader::blankFunction);
-}
-
-
-void SignatureReader::initialize(
-       SignatureData &signatureData,
-       const std::string &xmlscheme)
-{
-       m_parserSchema.initialize(
-               signatureData.getSignatureFileName(),
-               true,
-               SaxReader::VALIDATION_XMLSCHEME,
-               xmlscheme);
-}
-
-void SignatureReader::read(SignatureData &signatureData)
-{
-       m_parserSchema.read(signatureData);
-}
-
-void SignatureReader::blankFunction(SignatureData &)
-{
-}
-
-void SignatureReader::tokenKeyInfo(SignatureData &)
-{
-}
-
-void SignatureReader::tokenX509Data(SignatureData &)
-{
-}
-
-void SignatureReader::tokenX509Certificate(SignatureData &)
-{
-}
-
-void SignatureReader::tokenPublicKey(SignatureData &)
-{
-}
-
-void SignatureReader::tokenNamedCurve(SignatureData &)
-{
-       m_nameCurveURI = m_parserSchema.getReader().attribute(TOKEN_URI);
-}
-
-void SignatureReader::tokenTargetRestriction(SignatureData &signatureData)
-{
-       std::string IMEI = m_parserSchema.getReader().attribute(TOKEN_IMEI);
-       std::string MEID = m_parserSchema.getReader().attribute(TOKEN_MEID);
-
-       //less verbose way to say (IMEI && MEID) || (!IMEI && !MEID)
-       if (IMEI.empty() == MEID.empty()) {
-               //WAC 2.0 WR-4650 point 4
-               VcoreThrowMsg(SignatureReader::Exception::TargetRestriction,
-                                         "TargetRestriction should contain exactly one attribute.");
-       }
-
-       if (!IMEI.empty()) {
-               signatureData.m_imeiList.push_back(IMEI);
-       }
-
-       if (!MEID.empty()) {
-               signatureData.m_meidList.push_back(MEID);
-       }
-}
-
-void SignatureReader::tokenEndKeyInfo(SignatureData &)
-{
-}
-
-void SignatureReader::tokenEndX509Data(SignatureData &)
-{
-}
-
-void SignatureReader::tokenEndX509Certificate(SignatureData &signatureData)
-{
-       CertificateLoader loader;
-
-       if (CertificateLoader::NO_ERROR !=
-                       loader.loadCertificateFromRawData(m_parserSchema.getText())) {
-               fprintf(stderr, "## [validate error]: Certificate could not be loaded\n");
-               VcoreThrowMsg(ParserSchemaException::CertificateLoaderError,
-                                         "Certificate could not be loaded");
-       }
-
-       signatureData.m_certList.push_back(loader.getCertificatePtr());
-}
-
-void SignatureReader::tokenEndRSAKeyValue(SignatureData &signatureData)
-{
-       CertificateLoader loader;
-
-       if (CertificateLoader::NO_ERROR !=
-                       loader.loadCertificateBasedOnExponentAndModulus(m_modulus,
-                                       m_exponent)) {
-               fprintf(stderr, "## [validate error]: Certificate could not be loaded\n");
-               VcoreThrowMsg(ParserSchemaException::CertificateLoaderError,
-                                         "Certificate could not be loaded");
-       }
-
-       signatureData.m_certList.push_back(loader.getCertificatePtr());
-}
-
-void SignatureReader::tokenEndKeyModulus(SignatureData &)
-{
-       m_modulus = m_parserSchema.getText();
-}
-
-void SignatureReader::tokenEndKeyExponent(SignatureData &)
-{
-       m_exponent = m_parserSchema.getText();
-}
-
-void SignatureReader::tokenEndPublicKey(SignatureData &)
-{
-       m_publicKey = m_parserSchema.getText();
-}
-
-void SignatureReader::tokenEndECKeyValue(SignatureData &signatureData)
-{
-       CertificateLoader loader;
-
-       if (CertificateLoader::NO_ERROR !=
-                       loader.loadCertificateWithECKEY(m_nameCurveURI, m_publicKey)) {
-               fprintf(stderr, "## [validate error]: Certificate could not be loaded\n");
-               VcoreThrowMsg(ParserSchemaException::CertificateLoaderError,
-                                         "Certificate could not be loaded");
-       }
-
-       signatureData.m_certList.push_back(loader.getCertificatePtr());
-}
-
-void SignatureReader::tokenEndObject(SignatureData &signatureData)
-{
-       m_signaturePropertiesCounter = 0;
-
-       if (((!signatureData.m_imeiList.empty()) ||
-                       (!signatureData.m_meidList.empty())) &&
-                       m_targetRestrictionObjectFound) {
-               //WAC 2.0 WR-4650 point 1
-               VcoreThrowMsg(SignatureReader::Exception::TargetRestriction,
-                                         "TargetRestriction should contain exactly one ds:Object "
-                                         "containing zero or more wac:TargetRestriction children.");
-       }
-
-       if ((!signatureData.m_imeiList.empty()) ||
-                       (!signatureData.m_meidList.empty())) {
-               m_targetRestrictionObjectFound = true;
-       }
-}
-void SignatureReader::tokenEndDSAPComponent(SignatureData &)
-{
-       m_dsaKeyPComponent = m_parserSchema.getText();
-}
-
-void SignatureReader::tokenEndDSAQComponent(SignatureData &)
-{
-       m_dsaKeyQComponent = m_parserSchema.getText();
-}
-
-void SignatureReader::tokenEndDSAGComponent(SignatureData &)
-{
-       m_dsaKeyGComponent = m_parserSchema.getText();
-}
-
-void SignatureReader::tokenEndDSAYComponent(SignatureData &)
-{
-       m_dsaKeyYComponent = m_parserSchema.getText();
-}
-
-void SignatureReader::tokenEndDSAJComponent(SignatureData &)
-{
-       m_dsaKeyJComponent = m_parserSchema.getText();
-}
-
-void SignatureReader::tokenEndDSASeedComponent(SignatureData &)
-{
-       m_dsaKeySeedComponent = m_parserSchema.getText();
-}
-
-void SignatureReader::tokenEndDSAPGenCounterComponent(SignatureData &)
-{
-       m_dsaKeyPGenCounter = m_parserSchema.getText();
-}
-
-void SignatureReader::tokenEndDSAKeyValue(SignatureData &signatureData)
-{
-       CertificateLoader loader;
-
-       if (CertificateLoader::NO_ERROR !=
-                       loader.loadCertificateBasedOnDSAComponents(m_dsaKeyPComponent,
-                                       m_dsaKeyQComponent,
-                                       m_dsaKeyGComponent,
-                                       m_dsaKeyYComponent,
-                                       m_dsaKeyJComponent,
-                                       m_dsaKeySeedComponent,
-                                       m_dsaKeyPGenCounter)) {
-               fprintf(stderr, "## [validate error]: Certificate could not be loaded\n");
-               VcoreThrowMsg(ParserSchemaException::CertificateLoaderError,
-                                         "Certificate could not be loaded.");
-       }
-
-       signatureData.m_certList.push_back(loader.getCertificatePtr());
-}
-
-void SignatureReader::tokenRole(SignatureData &signatureData)
-{
-       if (!signatureData.m_roleURI.empty()) {
-               fprintf(stderr, "## [validate error]: Multiple definition of Role is not allowed\n");
-               VcoreThrowMsg(ParserSchemaException::UnsupportedValue,
-                                         "Multiple definition of Role is not allowed.");
-       }
-
-       signatureData.m_roleURI = m_parserSchema.getReader().attribute(TOKEN_URI);
-}
-
-void SignatureReader::tokenProfile(SignatureData &signatureData)
-{
-       if (!signatureData.m_profileURI.empty()) {
-               fprintf(stderr, "## [validate error]: Multiple definition of Profile is not allowed\n");
-               VcoreThrowMsg(ParserSchemaException::UnsupportedValue,
-                                         "Multiple definition of Profile is not allowed.");
-       }
-
-       signatureData.m_profileURI = m_parserSchema.getReader().attribute(TOKEN_URI);
-}
-
-void SignatureReader::tokenEndIdentifier(SignatureData &signatureData)
-{
-       if (!signatureData.m_identifier.empty()) {
-               fprintf(stderr, "## [validate error]: Multiple definition of Identifier is not allowed\n");
-               VcoreThrowMsg(ParserSchemaException::UnsupportedValue,
-                                         "Multiple definition of Identifier is not allowed.");
-       }
-
-       signatureData.m_identifier = m_parserSchema.getText();
-}
-
-void SignatureReader::tokenObject(SignatureData &signatureData)
-{
-       std::string id = m_parserSchema.getReader().attribute(TOKEN_ID);
-
-       if (id.empty()) {
-               fprintf(stderr, "## [validate error]: Unsupported value of Attribute Id in Object tag\n");
-               VcoreThrowMsg(ParserSchemaException::UnsupportedValue,
-                                         "Unsupported value of Attribute Id in Object tag.");
-       }
-
-       signatureData.m_objectList.push_back(id);
-}
-
-void SignatureReader::tokenSignatureProperties(SignatureData &)
-{
-       if (++m_signaturePropertiesCounter > 1) {
-               fprintf(stderr, "## [validate error]: Only one SignatureProperties tag is allowed in Object\n");
-               VcoreThrowMsg(ParserSchemaException::UnsupportedValue,
-                                         "Only one SignatureProperties tag is allowed in Object");
-       }
-}
-} // namespace ValidationCore
diff --git a/vcore/vcore/SignatureReader.h b/vcore/vcore/SignatureReader.h
deleted file mode 100644 (file)
index 846db22..0000000
+++ /dev/null
@@ -1,115 +0,0 @@
-/*
- * Copyright (c) 2011 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        SignatureReader.h
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief       SignatureReader is used to parse widget digital signature.
- */
-#ifndef _VALIDATION_CORE_SIGNATUREREADER_H_
-#define _VALIDATION_CORE_SIGNATUREREADER_H_
-
-#include <vcore/SignatureData.h>
-#include <vcore/ParserSchema.h>
-#include <vcore/exception.h>
-
-#include <map>
-
-namespace ValidationCore {
-
-class SignatureReader {
-public:
-       class Exception {
-       public:
-               VCORE_DECLARE_EXCEPTION_TYPE(ValidationCore::Exception, Base);
-               VCORE_DECLARE_EXCEPTION_TYPE(Base, TargetRestriction);
-       };
-
-       SignatureReader();
-
-       void initialize(SignatureData &signatureData, const std::string &xmlscheme);
-
-       void read(SignatureData &signatureData);
-
-private:
-       void blankFunction(SignatureData &signatureData);
-
-       void tokenKeyInfo(SignatureData &signatureData);
-       void tokenKeyModulus(SignatureData &signatureData);
-       void tokenKeyExponent(SignatureData &signatureData);
-       void tokenX509Data(SignatureData &signatureData);
-       void tokenX509Certificate(SignatureData &signatureData);
-       void tokenPublicKey(SignatureData &signatureData);
-       void tokenNamedCurve(SignatureData &signatureData);
-       void tokenRole(SignatureData &signatureData);
-       void tokenProfile(SignatureData &signatureData);
-       void tokenObject(SignatureData &signatureData);
-       void tokenSignatureProperties(SignatureData &signatureData);
-
-       void tokenTargetRestriction(SignatureData &signatureData);
-
-       void tokenEndKeyInfo(SignatureData &signatureData);
-       // KW     void tokenEndKeyName(SignatureData &signatureData);
-
-       void tokenEndRSAKeyValue(SignatureData &signatureData);
-
-       void tokenEndKeyModulus(SignatureData &signatureData);
-       void tokenEndKeyExponent(SignatureData &signatureData);
-       void tokenEndX509Data(SignatureData &signatureData);
-
-       void tokenEndX509Certificate(SignatureData &signatureData);
-
-       void tokenEndPublicKey(SignatureData &signatureData);
-       void tokenEndECKeyValue(SignatureData &signatureData);
-       void tokenEndIdentifier(SignatureData &signatureData);
-       void tokenEndObject(SignatureData &signatureData);
-
-       // DSA key components
-       void tokenEndDSAPComponent(SignatureData &signatureData);
-       void tokenEndDSAQComponent(SignatureData &signatureData);
-       void tokenEndDSAGComponent(SignatureData &signatureData);
-       void tokenEndDSAYComponent(SignatureData &signatureData);
-       void tokenEndDSAJComponent(SignatureData &signatureData);
-
-       void tokenEndDSAKeyValue(SignatureData &signatureData);
-
-       void tokenEndDSASeedComponent(SignatureData &signatureData);
-       void tokenEndDSAPGenCounterComponent(SignatureData &signatureData);
-
-       // temporary values required due reference parsing process
-       // optional parameters for dsa
-       std::string m_dsaKeyPComponent;
-       std::string m_dsaKeyQComponent;
-       std::string m_dsaKeyGComponent;
-       std::string m_dsaKeyYComponent;
-       std::string m_dsaKeyJComponent;
-       std::string m_dsaKeySeedComponent;
-       std::string m_dsaKeyPGenCounter;
-       // temporary values of ecdsa key
-       std::string m_publicKey;
-       std::string m_nameCurveURI;
-       std::string m_modulus;
-       std::string m_exponent;
-
-       // temporary values required due Object parsing
-       int m_signaturePropertiesCounter;
-       bool m_targetRestrictionObjectFound;
-
-       ParserSchema<SignatureReader, SignatureData> m_parserSchema;
-};
-}
-
-#endif // _VALIDATION_CORE_SIGNATUREREADER_H_
diff --git a/vcore/vcore/SignatureValidator.cpp b/vcore/vcore/SignatureValidator.cpp
deleted file mode 100644 (file)
index 1007f95..0000000
+++ /dev/null
@@ -1,648 +0,0 @@
-/*
- * Copyright (c) 2011 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        SignatureValidator.cpp
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @author      Sangwan Kwon (sangwan.kwon@samsung.com)
- * @version     1.0
- * @brief       Implementatin of tizen signature validation protocol.
- */
-
-#include <memory>
-#include <string>
-#include <utility>
-
-#include <dpl/log/log.h>
-
-#include <vcore/CertificateCollection.h>
-#include <vcore/Certificate.h>
-#include <vcore/ReferenceValidator.h>
-#include <vcore/ValidatorFactories.h>
-#include <vcore/XmlsecAdapter.h>
-#include <vcore/SignatureReader.h>
-#include <vcore/SignatureFinder.h>
-#include <vcore/Ocsp.h>
-#include <vcore/PluginHandler.h>
-
-#include <vcore/SignatureValidator.h>
-
-#ifdef TIZEN_PROFILE_MOBILE
-#include <cchecker/ocsp.h>
-#endif
-
-using namespace ValidationCore::CertStoreId;
-
-namespace {
-
-const std::string TOKEN_PREFIX          = "http://www.w3.org/ns/widgets-digsig#";
-const std::string TOKEN_ROLE_AUTHOR_URI = TOKEN_PREFIX + "role-author";
-const std::string TOKEN_ROLE_DIST_URI   = TOKEN_PREFIX + "role-distributor";
-const std::string TOKEN_PROFILE_URI     = TOKEN_PREFIX + "profile";
-
-enum class CertTimeStatus : int {
-       VALID,
-       NOT_YET,
-       EXPIRED
-};
-
-inline time_t _getMidTime(time_t lower, time_t upper)
-{
-       return (lower >> 1) + (upper >> 1);
-}
-
-inline CertTimeStatus _timeValidation(time_t lower, time_t upper, time_t current)
-{
-       if (current < lower)
-               return CertTimeStatus::NOT_YET;
-       else if (current > upper)
-               return CertTimeStatus::EXPIRED;
-       else
-               return CertTimeStatus::VALID;
-}
-
-inline bool _isTimeStrict(const Set &stores)
-{
-       return (stores.contains(TIZEN_TEST) || stores.contains(TIZEN_VERIFY))
-                  ? true : false;
-}
-
-} // namespace anonymous
-
-
-namespace ValidationCore {
-
-class SignatureValidator::Impl {
-public:
-       Impl(const SignatureFileInfo &info);
-       virtual ~Impl() {};
-
-       VCerr check(
-               const std::string &contentPath,
-               bool checkOcsp,
-               bool checkReferences,
-               SignatureData &outData);
-
-       VCerr checkList(
-               bool checkOcsp,
-               const UriList &uriList,
-               SignatureData &outData);
-
-       VCerr makeChainBySignature(
-               bool completeWithSystemCert,
-               CertificateList &certList);
-
-       std::string errorToString(VCerr code);
-
-private:
-       VCerr baseCheck(
-               const std::string &contentPath,
-               bool checkOcsp,
-               bool checkReferences);
-
-       VCerr baseCheckList(
-               bool checkOcsp,
-               const UriList &uriList);
-
-       VCerr makeDataBySignature(bool completeWithSystemCert);
-       VCerr additionalCheck(VCerr result);
-
-       VCerr parseSignature(void);
-       VCerr preStep(void);
-       bool checkRoleURI(void);
-       bool checkProfileURI(void);
-       bool checkObjectReferences(void);
-
-       PluginHandler m_pluginHandler;
-       SignatureFileInfo m_fileInfo;
-       XmlSec::XmlSecContext m_context;
-       SignatureData m_data;
-       bool m_disregarded;
-};
-
-
-SignatureValidator::Impl::Impl(const SignatureFileInfo &info) :
-       m_fileInfo(info),
-       m_disregarded(false)
-{
-}
-
-bool SignatureValidator::Impl::checkRoleURI(void)
-{
-       std::string roleURI = m_data.getRoleURI();
-
-       if (roleURI.empty()) {
-               LogWarning("URI attribute in Role tag couldn't be empty.");
-               return false;
-       }
-
-       if (roleURI != TOKEN_ROLE_AUTHOR_URI && m_data.isAuthorSignature()) {
-               LogWarning("URI attribute in Role tag does not "
-                                  "match with signature filename.");
-               return false;
-       }
-
-       if (roleURI != TOKEN_ROLE_DIST_URI && !m_data.isAuthorSignature()) {
-               LogWarning("URI attribute in Role tag does not "
-                                  "match with signature filename.");
-               return false;
-       }
-
-       return true;
-}
-
-
-bool SignatureValidator::Impl::checkProfileURI(void)
-{
-       if (TOKEN_PROFILE_URI != m_data.getProfileURI()) {
-               LogWarning("Profile tag contains unsupported value "
-                                  "in URI attribute " << m_data.getProfileURI());
-               return false;
-       }
-
-       return true;
-}
-
-bool SignatureValidator::Impl::checkObjectReferences(void)
-{
-       for (const auto &object : m_data.getObjectList()) {
-               if (!m_data.containObjectReference(object)) {
-                       LogWarning("Signature does not contain reference for object " << object);
-                       return false;
-               }
-       }
-
-       return true;
-}
-
-VCerr SignatureValidator::Impl::additionalCheck(VCerr result)
-{
-       try {
-               if (m_pluginHandler.fail()) {
-                       LogInfo("No validator plugin found. Skip additional check.");
-                       return result;
-               }
-
-               return m_pluginHandler.step(result, m_data);
-       } catch (...) {
-               LogError("Exception in additional check by plugin.");
-               return E_SIG_PLUGIN;
-       }
-}
-
-VCerr SignatureValidator::Impl::parseSignature(void)
-{
-       try {
-               SignatureReader xml;
-               xml.initialize(m_data, SIGNATURE_SCHEMA_PATH);
-               xml.read(m_data);
-       } catch (ParserSchemaException::CertificateLoaderError &e) {
-               LogError("Certificate loader error: " << e.DumpToString());
-               return E_SIG_INVALID_CERT;
-       } catch (...) {
-               LogError("Failed to parse signature file by signature reader.");
-               return E_SIG_INVALID_FORMAT;
-       }
-
-       return E_SIG_NONE;
-}
-
-/*
- *  Make SignatureData by parsing signature file.
- *  and get certificate chain with attached certificate in signature
- */
-VCerr SignatureValidator::Impl::makeDataBySignature(bool completeWithSystemCert)
-{
-       LogDebug("Start to make chain.");
-       m_data = SignatureData(m_fileInfo.getFileName(), m_fileInfo.getFileNumber());
-
-       if (parseSignature()) {
-               LogError("Failed to parse signature.");
-               return E_SIG_INVALID_FORMAT;
-       }
-
-       if (!checkRoleURI() || !checkProfileURI())
-               return E_SIG_INVALID_FORMAT;
-
-       try {
-               CertificateCollection collection;
-               // Load Certificates and make chain.
-               collection.load(m_data.getCertList());
-
-               if (!collection.sort() || collection.empty()) {
-                       LogError("Certificates do not form valid chain.");
-                       return E_SIG_INVALID_CHAIN;
-               }
-
-               // Add root certificate to chain.
-               if (completeWithSystemCert && !collection.completeCertificateChain()) {
-                       if (m_data.isAuthorSignature() || m_data.getSignatureNumber() == 1) {
-                               LogError("Failed to complete cert chain with system cert");
-                               return E_SIG_INVALID_CHAIN;
-                       } else {
-                               LogDebug("Distributor N's certificate has got "
-                                                "unrecognized root CA certificate.");
-                               m_disregarded = true;
-                       }
-               }
-
-               m_data.setSortedCertificateList(collection.getChain());
-               LogDebug("Finish making chain successfully.");
-       } catch (const CertificateCollection::Exception::Base &e) {
-               LogError("CertificateCollection exception : " << e.DumpToString());
-               return E_SIG_INVALID_CHAIN;
-       } catch (const std::exception &e) {
-               LogError("std exception occured : " << e.what());
-               return E_SIG_UNKNOWN;
-       } catch (...) {
-               LogError("Unknown exception in SignatureValidator::makeChainBySignature");
-               return E_SIG_UNKNOWN;
-       }
-
-       return E_SIG_NONE;
-}
-
-VCerr SignatureValidator::Impl::preStep(void)
-{
-       // Make chain process.
-       VCerr result = makeDataBySignature(true);
-
-       if (result != E_SIG_NONE)
-               return result;
-
-       for (const auto &certptr : m_data.getCertList()) {
-               auto storeIdSet = createCertificateIdentifier().find(certptr);
-               if (!storeIdSet.contains(TIZEN_REVOKED))
-                       continue;
-
-               LogInfo("Revoked certificate: " << certptr->getOneLine());
-               return E_SIG_REVOKED;
-       }
-
-       // Get Identifier from fingerprint original, extention file.
-       LogDebug("Start to check certificate domain.");
-       auto certificatePtr = m_data.getCertList().back();
-       auto storeIdSet = createCertificateIdentifier().find(certificatePtr);
-       // Check root CA certificate has proper domain.
-       LogDebug("root certificate from " << storeIdSet.typeToString() << " domain");
-
-       if (m_data.isAuthorSignature()) {
-               if (!storeIdSet.contains(TIZEN_DEVELOPER)) {
-                       LogError("author-signature.xml's root certificate "
-                                        "isn't in tizen developer domain.");
-                       return E_SIG_INVALID_CHAIN;
-               }
-       } else {
-               if (storeIdSet.contains(TIZEN_DEVELOPER)) {
-                       LogError("distributor signautre root certificate "
-                                        "shouldn't be in tizen developer domain.");
-                       return E_SIG_INVALID_CHAIN;
-               }
-
-               if (m_data.getSignatureNumber() == 1 && !storeIdSet.isContainsVis()) {
-                       LogError("signature1.xml has got unrecognized root CA certificate.");
-                       return E_SIG_INVALID_CHAIN;
-               } else if (!storeIdSet.isContainsVis()) {
-                       LogDebug("signatureN.xml has got unrecognized root CA certificate.");
-                       m_disregarded = true;
-               }
-       }
-
-       m_data.setStorageType(storeIdSet);
-       LogDebug("Finish checking certificate domain.");
-       /*
-        * We add only Root CA certificate because the rest
-        * of certificates are present in signature files ;-)
-        */
-       m_context.signatureFile = m_data.getSignatureFileName();
-       m_context.certificatePtr = m_data.getCertList().back();
-       /* certificate time check */
-       time_t lower = m_data.getEndEntityCertificatePtr()->getNotBefore();
-       time_t upper = m_data.getEndEntityCertificatePtr()->getNotAfter();
-       time_t current = time(NULL);
-       CertTimeStatus status = _timeValidation(lower, upper, current);
-
-       if (status != CertTimeStatus::VALID) {
-               LogDebug("Certificate's time is invalid.");
-
-               if (_isTimeStrict(storeIdSet))
-                       return status == CertTimeStatus::EXPIRED
-                                  ? E_SIG_CERT_EXPIRED : E_SIG_CERT_NOT_YET;
-
-               time_t mid = _getMidTime(lower, upper);
-               LogInfo("Use middle notBeforeTime and notAfterTime."
-                               " lower: " << lower
-                               << " upper: " << upper
-                               << " mid: " << mid
-                               << " current: " << current);
-               m_context.validationTime = mid;
-       }
-
-       return E_SIG_NONE;
-}
-
-VCerr SignatureValidator::Impl::baseCheck(
-       const std::string &contentPath,
-       bool checkOcsp,
-       bool checkReferences)
-{
-       try {
-               // Make certificate chain, check certificate info
-               VCerr result = preStep();
-
-               if (result != E_SIG_NONE)
-                       return result;
-
-               // Since disregard case, uncheck root certs in signatureN.xml
-               if (!m_data.isAuthorSignature() && m_data.getSignatureNumber() != 1)
-                       m_context.allowBrokenChain = true;
-
-               // XmlSec validate
-               XmlSecSingleton::Instance().validate(m_context);
-               // Check reference of 'Object' tag - OID
-               m_data.setReference(m_context.referenceSet);
-
-               if (!checkObjectReferences()) {
-                       LogWarning("Failed to check Object References");
-                       return E_SIG_INVALID_REF;
-               }
-
-               // Check reference's existence
-               if (checkReferences) {
-                       ReferenceValidator fileValidator(contentPath);
-
-                       if (ReferenceValidator::NO_ERROR != fileValidator.checkReferences(m_data)) {
-                               LogWarning("Invalid package - file references broken");
-                               return E_SIG_INVALID_REF;
-                       }
-               }
-
-               // Check OCSP
-               if (checkOcsp && Ocsp::check(m_data) == Ocsp::Result::REVOKED) {
-                       LogError("Certificate is Revoked by OCSP server.");
-                       return E_SIG_REVOKED;
-               }
-
-               LogDebug("Signature validation check done successfully ");
-       } catch (const CertificateCollection::Exception::Base &e) {
-               LogError("CertificateCollection exception : " << e.DumpToString());
-               return E_SIG_INVALID_CHAIN;
-       } catch (const XmlSec::Exception::InternalError &e) {
-               LogError("XmlSec internal error : " << e.DumpToString());
-               return E_SIG_INVALID_FORMAT;
-       } catch (const XmlSec::Exception::InvalidFormat &e) {
-               LogError("XmlSec invalid format : " << e.DumpToString());
-               return E_SIG_INVALID_FORMAT;
-       } catch (const XmlSec::Exception::InvalidSig &e) {
-               LogError("XmlSec invalid signature : " << e.DumpToString());
-               return E_SIG_INVALID_SIG;
-       } catch (const XmlSec::Exception::OutOfMemory &e) {
-               LogError("XmlSec out of memory : " << e.DumpToString());
-               return E_SIG_OUT_OF_MEM;
-       } catch (const XmlSec::Exception::Base &e) {
-               LogError("XmlSec unknown exception : " << e.DumpToString());
-               return E_SIG_INVALID_FORMAT;
-       } catch (const Ocsp::Exception::OcspUnsupported &e) {
-               LogInfo("Ocsp unsupported : " << e.DumpToString());
-       } catch (const Ocsp::Exception::Base &e) {
-               LogInfo("Ocsp check throw exeption : " << e.DumpToString());
-#ifdef TIZEN_PROFILE_MOBILE
-               LogInfo("Launch cert-checker.");
-               try {
-                       if (cchecker_ocsp_request() != 0)
-                               LogError("Load cert-checker failed.");
-               } catch (const std::exception &e) {
-                       LogError("std exception occured while cchecker running : " << e.what());
-               } catch (...) {
-                       LogError("Unknown exception occuured while cchecker running. ");
-               }
-#endif
-       } catch (const std::exception &e) {
-               LogError("std exception occured : " << e.what());
-               return E_SIG_UNKNOWN;
-       } catch (...) {
-               LogError("Unknown exception in SignatureValidator::check");
-               return E_SIG_UNKNOWN;
-       }
-
-       return m_disregarded ? E_SIG_DISREGARDED : E_SIG_NONE;
-}
-
-VCerr SignatureValidator::Impl::baseCheckList(
-       bool checkOcsp,
-       const UriList &uriList)
-{
-       try {
-               // Make certificate chain, check certificate info
-               VCerr result = preStep();
-
-               if (result != E_SIG_NONE)
-                       return result;
-
-               // XmlSec validate
-               if (uriList.size() == 0)
-                       XmlSecSingleton::Instance().validateNoHash(m_context);
-               else
-                       XmlSecSingleton::Instance().validatePartialHash(m_context, uriList);
-
-               if (checkOcsp && Ocsp::check(m_data) == Ocsp::Result::REVOKED) {
-                       LogError("Certificate is Revoked by OCSP server.");
-                       return E_SIG_REVOKED;
-               }
-
-               LogDebug("Signature validation of check list done successfully ");
-       } catch (const CertificateCollection::Exception::Base &e) {
-               LogError("CertificateCollection exception : " << e.DumpToString());
-               return E_SIG_INVALID_CHAIN;
-       } catch (const XmlSec::Exception::InternalError &e) {
-               LogError("XmlSec internal error : " << e.DumpToString());
-               return E_SIG_INVALID_FORMAT;
-       } catch (const XmlSec::Exception::InvalidFormat &e) {
-               LogError("XmlSec invalid format : " << e.DumpToString());
-               return E_SIG_INVALID_FORMAT;
-       } catch (const XmlSec::Exception::InvalidSig &e) {
-               LogError("XmlSec invalid signature : " << e.DumpToString());
-               return E_SIG_INVALID_SIG;
-       } catch (const XmlSec::Exception::OutOfMemory &e) {
-               LogError("XmlSec out of memory : " << e.DumpToString());
-               return E_SIG_OUT_OF_MEM;
-       } catch (const XmlSec::Exception::Base &e) {
-               LogError("XmlSec unknown exception : " << e.DumpToString());
-               return E_SIG_INVALID_FORMAT;
-       } catch (const Ocsp::Exception::OcspUnsupported &e) {
-               LogInfo("Ocsp unsupported : " << e.DumpToString());
-       } catch (const Ocsp::Exception::Base &e) {
-               LogInfo("Ocsp check throw exeption : " << e.DumpToString());
-#ifdef TIZEN_PROFILE_MOBILE
-               LogInfo("Launch cert-checker.");
-               try {
-                       if (cchecker_ocsp_request() != 0)
-                               LogError("Load cert-checker failed.");
-               } catch (const std::exception &e) {
-                       LogError("std exception occured while cchecker running : " << e.what());
-               } catch (...) {
-                       LogError("Unknown exception occuured while cchecker running. ");
-               }
-#endif
-       } catch (...) {
-               LogError("Unknown exception in SignatureValidator::checkList");
-               return E_SIG_UNKNOWN;
-       }
-
-       return m_disregarded ? E_SIG_DISREGARDED : E_SIG_NONE;
-}
-
-VCerr SignatureValidator::Impl::check(
-       const std::string &contentPath,
-       bool checkOcsp,
-       bool checkReferences,
-       SignatureData &outData)
-{
-       VCerr result;
-       result = baseCheck(contentPath, checkOcsp, checkReferences);
-       result = additionalCheck(result);
-       outData = m_data;
-       return result;
-}
-
-VCerr SignatureValidator::Impl::checkList(
-       bool checkOcsp,
-       const UriList &uriList,
-       SignatureData &outData)
-{
-       VCerr result;
-       result = baseCheckList(checkOcsp, uriList);
-       result = additionalCheck(result);
-       outData = m_data;
-       return result;
-}
-
-VCerr SignatureValidator::Impl::makeChainBySignature(
-       bool completeWithSystemCert,
-       CertificateList &certList)
-{
-       VCerr result = makeDataBySignature(completeWithSystemCert);
-
-       if (result != E_SIG_NONE)
-               return result;
-
-       certList = m_data.getCertList();
-       return E_SIG_NONE;
-}
-
-std::string SignatureValidator::Impl::errorToString(VCerr code)
-{
-       switch (code) {
-       case E_SIG_NONE:
-               return "Success.";
-
-       case E_SIG_INVALID_FORMAT:
-               return "Invalid format of signature file.";
-
-       case E_SIG_INVALID_CERT:
-               return "Invalid format of certificate in signature.";
-
-       case E_SIG_INVALID_CHAIN:
-               return "Invalid certificate chain with certificate in signature.";
-
-       case E_SIG_INVALID_SIG:
-               return "Invalid signature. Signed with wrong key, changed signature file or changed package file.";
-
-       case E_SIG_INVALID_REF:
-               return "Invalid file reference. An unsinged file was found.";
-
-       case E_SIG_CERT_EXPIRED:
-               return "Certificate in signature was expired.";
-
-       case E_SIG_CERT_NOT_YET:
-               return "Certificate in signature is not valid yet.";
-
-       case E_SIG_DISREGARDED:
-               return "Signature validation can be disregarded in some cases.";
-
-       case E_SIG_REVOKED:
-               return "One of certificate was revoked in certificate chain.";
-
-       case E_SIG_PLUGIN:
-               return "Failed to load plugin for additional validation check.";
-
-       case E_SIG_OUT_OF_MEM:
-               return "Out of memory.";
-
-       case E_SIG_UNKNOWN:
-               return "Unknown error.";
-
-       default:
-               return m_pluginHandler.errorToString(code);
-       }
-}
-
-
-SignatureValidator::SignatureValidator(const SignatureFileInfo &info)
-{
-       std::unique_ptr<SignatureValidator::Impl> impl(new(std::nothrow) SignatureValidator::Impl(info));
-       m_pImpl = std::move(impl);
-}
-SignatureValidator::~SignatureValidator() {}
-
-std::string SignatureValidator::errorToString(VCerr code)
-{
-       if (!m_pImpl)
-               return "out of memory. error.";
-
-       return m_pImpl->errorToString(code);
-}
-
-VCerr SignatureValidator::check(
-       const std::string &contentPath,
-       bool checkOcsp,
-       bool checkReferences,
-       SignatureData &outData)
-{
-       if (!m_pImpl)
-               return E_SIG_OUT_OF_MEM;
-
-       return m_pImpl->check(
-                          contentPath,
-                          checkOcsp,
-                          checkReferences,
-                          outData);
-}
-
-VCerr SignatureValidator::checkList(
-       bool checkOcsp,
-       const UriList &uriList,
-       SignatureData &outData)
-{
-       if (!m_pImpl)
-               return E_SIG_OUT_OF_MEM;
-
-       return m_pImpl->checkList(
-                          checkOcsp,
-                          uriList,
-                          outData);
-}
-
-VCerr SignatureValidator::makeChainBySignature(
-       bool completeWithSystemCert,
-       CertificateList &certList)
-{
-       if (!m_pImpl)
-               return E_SIG_OUT_OF_MEM;
-
-       return m_pImpl->makeChainBySignature(completeWithSystemCert, certList);
-}
-
-} // namespace ValidationCore
diff --git a/vcore/vcore/SignatureValidator.h b/vcore/vcore/SignatureValidator.h
deleted file mode 100644 (file)
index 8dc4692..0000000
+++ /dev/null
@@ -1,102 +0,0 @@
-/*
- * Copyright (c) 2011 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        SignatureValidator.h
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.1
- * @brief       Implementatin of tizen signature validation protocol.
- */
-#ifndef _VALIDATION_CORE_SIGNATUREVALIDATOR_H_
-#define _VALIDATION_CORE_SIGNATUREVALIDATOR_H_
-
-#include <string>
-#include <list>
-#include <memory>
-
-#include <vcore/Certificate.h>
-#include <vcore/SignatureData.h>
-#include <vcore/SignatureFinder.h>
-#include <vcore/Error.h>
-
-namespace ValidationCore {
-
-using UriList = std::list<std::string>;
-
-/*
- *  Types of Reference checking
- *
- *  1. XmlSec validate (default)
- *        - check reference based on Reference tag on signature xml.
- *        - Get URI from Reference tag, generate digest value and compare it with value written
- *        - If value with calculated and written isn't same, validate fail returned.
- *        * What if file doesn't exist which is written on Reference tag?
- *        * What if Reference tag doesn't exist for existing file? -> cannot checked.
- *
- *  2. checkObjectReferences (default on check function, not checkList)
- *        - check Reference of 'Object' tag.
- *        - it's mutual-exclusive check with  1. XmlSec validate.
- *
- *  3. ReferenceValidator (enabled when flag on)
- *        - check file based on content path from parameter
- *        - check is all existing file is on the Reference tag list on signature xml
- *        - If file path(URI) cannot found on reference set, validate fail returned.
- *
- *  Signature validation disregarded case
- *
- *  - distributor signature: signature number is 1 and doesn't contain in store id set
- */
-
-/*
- *  Error code defined on vcore/Error.h
- */
-class SignatureValidator {
-public:
-       SignatureValidator(const SignatureFileInfo &info);
-       virtual ~SignatureValidator();
-
-       SignatureValidator() = delete;
-       SignatureValidator(const SignatureValidator &) = delete;
-       const SignatureValidator &operator=(const SignatureValidator &) = delete;
-
-       VCerr check(
-               const std::string &contentPath,
-               bool checkOcsp,
-               bool checkReferences,
-               SignatureData &outData);
-
-       VCerr checkList(
-               bool checkOcsp,
-               const UriList &uriList,
-               SignatureData &outData);
-
-       /*
-        *  @Remarks : cert list isn't completed with self-signed root CA system cert
-        *             if completeWithSystemCert is false.
-        */
-       VCerr makeChainBySignature(
-               bool completeWithSystemCert,
-               CertificateList &certList);
-
-       std::string errorToString(int code);
-
-private:
-       class Impl;
-       std::unique_ptr<Impl> m_pImpl;
-};
-
-} // namespace ValidationCore
-
-#endif // _VALIDATION_CORE_SIGNATUREVALIDATOR_H_
diff --git a/vcore/vcore/TimeConversion.cpp b/vcore/vcore/TimeConversion.cpp
deleted file mode 100644 (file)
index 45a642b..0000000
+++ /dev/null
@@ -1,360 +0,0 @@
-/*
- * 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        TimeConversion.cpp
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @author      Sangwan Kwon (sangwan.kwon@samsung.com)
- * @version     0.1
- * @brief
- */
-#include <vcore/TimeConversion.h>
-#include <dpl/log/log.h>
-
-#include <cstring>
-#include <climits>
-
-#define TIME_MAX LONG_MAX // time_t max value in arch 32bit
-
-namespace {
-
-void _gmtime_adj(struct tm *tm, int offset)
-{
-       time_t t = mktime(tm);
-       t += offset;
-       memset(tm, 0, sizeof(struct tm));
-       gmtime_r(&t, tm);
-}
-
-/*
- * from openssl/crypto/asn1/a_gentm.c, openssl version 1.0.2d
- * return 1 on success, 0 on error
- * 1. local time only                        : yyyymmddHHMMSS[.fff]
- * 2. UTC time only                          : yyyymmddHHMM[SS[.fff]]Z
- * 3. Difference between local and UTC times : yyyymmddHHMM[SS[.fff]](+|-)HHMM
- */
-int asn1_generalizedtime_to_tm(struct tm *tm, const ASN1_GENERALIZEDTIME *d)
-{
-       static const int min[9] = { 0, 0, 1, 1, 0, 0, 0, 0, 0 };
-       static const int max[9] = { 99, 99, 12, 31, 23, 59, 59, 12, 59 };
-       char *a;
-       int n, i, l, o;
-
-       if (d->type != V_ASN1_GENERALIZEDTIME)
-               return (0);
-
-       l = d->length;
-       a = (char *)d->data;
-       o = 0;
-
-       /*
-        * GENERALIZEDTIME is similar to UTCTIME except the year is represented
-        * as YYYY. This stuff treats everything as a two digit field so make
-        * first two fields 00 to 99
-        */
-       if (l < 13)
-               goto err;
-
-       for (i = 0; i < 7; i++) {
-               if ((i == 6) && ((a[o] == 'Z') || (a[o] == '+') || (a[o] == '-'))) {
-                       i++;
-
-                       if (tm)
-                               tm->tm_sec = 0;
-
-                       break;
-               }
-
-               if ((a[o] < '0') || (a[o] > '9'))
-                       goto err;
-
-               n = a[o] - '0';
-
-               if (++o > l)
-                       goto err;
-
-               if ((a[o] < '0') || (a[o] > '9'))
-                       goto err;
-
-               n = (n * 10) + a[o] - '0';
-
-               if (++o > l)
-                       goto err;
-
-               if ((n < min[i]) || (n > max[i]))
-                       goto err;
-
-               if (tm) {
-                       switch (i) {
-                       case 0:
-                               tm->tm_year = n * 100 - 1900;
-                               break;
-
-                       case 1:
-                               tm->tm_year += n;
-                               break;
-
-                       case 2:
-                               tm->tm_mon = n - 1;
-                               break;
-
-                       case 3:
-                               tm->tm_mday = n;
-                               break;
-
-                       case 4:
-                               tm->tm_hour = n;
-                               break;
-
-                       case 5:
-                               tm->tm_min = n;
-                               break;
-
-                       case 6:
-                               tm->tm_sec = n;
-                               break;
-                       }
-               }
-       }
-
-       /*
-        * Optional fractional seconds: decimal point followed by one or more
-        * digits.
-        */
-       if (a[o] == '.') {
-               if (++o > l)
-                       goto err;
-
-               i = o;
-
-               while ((a[o] >= '0') && (a[o] <= '9') && (o <= l))
-                       o++;
-
-               /* Must have at least one digit after decimal point */
-               if (i == o)
-                       goto err;
-       }
-
-       if (a[o] == 'Z') {
-               o++;
-       } else if ((a[o] == '+') || (a[o] == '-')) {
-               int offsign = a[o] == '-' ? -1 : 1, offset = 0;
-               o++;
-
-               if (o + 4 > l)
-                       goto err;
-
-               for (i = 7; i < 9; i++) {
-                       if ((a[o] < '0') || (a[o] > '9'))
-                               goto err;
-
-                       n = a[o] - '0';
-                       o++;
-
-                       if ((a[o] < '0') || (a[o] > '9'))
-                               goto err;
-
-                       n = (n * 10) + a[o] - '0';
-
-                       if ((n < min[i]) || (n > max[i]))
-                               goto err;
-
-                       if (tm) {
-                               if (i == 7)
-                                       offset = n * 3600;
-                               else if (i == 8)
-                                       offset += n * 60;
-                       }
-
-                       o++;
-               }
-
-               if (offset)
-                       _gmtime_adj(tm, offset * offsign);
-       } else if (a[o]) {
-               /* Missing time zone information. */
-               goto err;
-       }
-
-       return (o == l);
-err:
-       return (0);
-}
-
-/*
- * from openssl/crypto/asn1/a_utctm.c, openssl version 1.0.2d
- * return 1 on success, 0 on error
- * 1. yymmddHHMM[SS]Z
- * 2. yymmddHHMM[SS](+|-)HHMM
- */
-int asn1_utctime_to_tm(struct tm *tm, const ASN1_UTCTIME *d)
-{
-       static const int min[8] = { 0, 1, 1, 0, 0, 0, 0, 0 };
-       static const int max[8] = { 99, 12, 31, 23, 59, 59, 12, 59 };
-       char *a;
-       int n, i, l, o;
-
-       if (d->type != V_ASN1_UTCTIME)
-               return (0);
-
-       l = d->length;
-       a = (char *)d->data;
-       o = 0;
-
-       if (l < 11)
-               goto err;
-
-       for (i = 0; i < 6; i++) {
-               if ((i == 5) && ((a[o] == 'Z') || (a[o] == '+') || (a[o] == '-'))) {
-                       i++;
-
-                       if (tm)
-                               tm->tm_sec = 0;
-
-                       break;
-               }
-
-               if ((a[o] < '0') || (a[o] > '9'))
-                       goto err;
-
-               n = a[o] - '0';
-
-               if (++o > l)
-                       goto err;
-
-               if ((a[o] < '0') || (a[o] > '9'))
-                       goto err;
-
-               n = (n * 10) + a[o] - '0';
-
-               if (++o > l)
-                       goto err;
-
-               if ((n < min[i]) || (n > max[i]))
-                       goto err;
-
-               if (tm) {
-                       switch (i) {
-                       case 0:
-                               tm->tm_year = n < 50 ? n + 100 : n;
-                               break;
-
-                       case 1:
-                               tm->tm_mon = n - 1;
-                               break;
-
-                       case 2:
-                               tm->tm_mday = n;
-                               break;
-
-                       case 3:
-                               tm->tm_hour = n;
-                               break;
-
-                       case 4:
-                               tm->tm_min = n;
-                               break;
-
-                       case 5:
-                               tm->tm_sec = n;
-                               break;
-                       }
-               }
-       }
-
-       if (a[o] == 'Z') {
-               o++;
-       } else if ((a[o] == '+') || (a[o] == '-')) {
-               int offsign = a[o] == '-' ? -1 : 1, offset = 0;
-               o++;
-
-               if (o + 4 > l)
-                       goto err;
-
-               for (i = 6; i < 8; i++) {
-                       if ((a[o] < '0') || (a[o] > '9'))
-                               goto err;
-
-                       n = a[o] - '0';
-                       o++;
-
-                       if ((a[o] < '0') || (a[o] > '9'))
-                               goto err;
-
-                       n = (n * 10) + a[o] - '0';
-
-                       if ((n < min[i]) || (n > max[i]))
-                               goto err;
-
-                       if (tm) {
-                               if (i == 6)
-                                       offset = n * 3600;
-                               else if (i == 7)
-                                       offset += n * 60;
-                       }
-
-                       o++;
-               }
-
-               if (offset)
-                       _gmtime_adj(tm, offset * offsign);
-       }
-
-       return o == l;
-err:
-       return 0;
-}
-
-} // namespace anonymous
-
-namespace ValidationCore {
-
-int asn1TimeToTimeT(ASN1_TIME *t, time_t *res)
-{
-       if (res == NULL)
-               return 0;
-
-       int ret = 0;
-       struct tm tm;
-       memset(&tm, 0, sizeof(tm));
-
-       if (t->type == V_ASN1_UTCTIME)
-               ret = asn1_utctime_to_tm(&tm, t);
-       else if (t->type == V_ASN1_GENERALIZEDTIME)
-               ret = asn1_generalizedtime_to_tm(&tm, t);
-       else
-               ret = 0;
-
-       if (ret == 0)
-               return 0;
-
-       char buf[27]; // asctime_r return 26 characters
-       LogDebug("Convert asn1 to tm: " << asctime_r(&tm, buf));
-       *res = mktime(&tm);
-
-       // If time_t occured overflow, set TIME_MAX.
-       if (*res == -1) {
-               LogDebug("Occured overflow time_t. it may year 2038 problem.");
-               *res = TIME_MAX;
-       }
-
-       // For Debugging.
-       struct tm localTm;
-       localtime_r(res, &localTm);
-       LogDebug("Result time_t(tm format): " << asctime_r(&localTm, buf));
-       return 1;
-}
-
-} // namespace ValidationCore
diff --git a/vcore/vcore/TimeConversion.h b/vcore/vcore/TimeConversion.h
deleted file mode 100644 (file)
index 3cf2acd..0000000
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * Copyright (c) 2011 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        TimeConversion.h
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     0.1
- * @brief
- */
-#ifndef _VALIDATION_CORE_TIMECONVERSION_H_
-#define _VALIDATION_CORE_TIMECONVERSION_H_
-
-#include <ctime>
-#include <openssl/asn1.h>
-
-namespace ValidationCore {
-
-/*
- * openssl/crypto/asn1/a_time.c based version 1.0.2d
- * return 1 on success, 0 on error
- */
-int asn1TimeToTimeT(ASN1_TIME *t, time_t *res);
-
-} // namespace ValidationCore
-
-#endif // _VALIDATION_CORE_TIMECONVERSION_H_
diff --git a/vcore/vcore/ValidatorFactories.cpp b/vcore/vcore/ValidatorFactories.cpp
deleted file mode 100644 (file)
index 79c0e1c..0000000
+++ /dev/null
@@ -1,71 +0,0 @@
-/*
- * Copyright (c) 2011 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
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @author      Sangwan kwon (sangwan.kwon@samsung.com)
- * @version     1.0
- * @brief
- */
-#include <vcore/ValidatorFactories.h>
-
-#include <vcore/Certificate.h>
-#include <vcore/CertificateConfigReader.h>
-#include <dpl/log/log.h>
-
-#include <string>
-#include <fstream>
-#include <memory>
-
-namespace ValidationCore {
-
-const CertificateIdentifier &createCertificateIdentifier()
-{
-       static CertificateIdentifier certificateIdentifier;
-       static bool initialized = false;
-
-       if (initialized)
-               return certificateIdentifier;
-
-       std::string file(FINGERPRINT_LIST_PATH);
-       std::string schema(FINGERPRINT_LIST_SCHEMA_PATH);
-       LogDebug("File with fingerprint list is : " << file);
-       LogDebug("File with fingerprint list schema is : " << schema);
-       // Read the fingerprint original list.
-       CertificateConfigReader reader;
-       reader.initialize(file, schema);
-       reader.read(certificateIdentifier);
-
-       if (std::ifstream(FINGERPRINT_LIST_EXT_PATH)) {
-               LogInfo(FINGERPRINT_LIST_EXT_PATH << " exist, add it.");
-               CertificateConfigReader exReader;
-               exReader.initialize(FINGERPRINT_LIST_EXT_PATH, schema);
-               exReader.read(certificateIdentifier);
-       }
-
-       if (std::ifstream(FINGERPRINT_LIST_RW_PATH)) {
-               LogInfo(FINGERPRINT_LIST_RW_PATH << " exist, add it.");
-               CertificateConfigReader rwReader;
-               rwReader.initialize(FINGERPRINT_LIST_RW_PATH, schema);
-               rwReader.read(certificateIdentifier);
-       }
-
-       initialized = true;
-
-       return certificateIdentifier;
-}
-
-} // namespace ValidationCore
diff --git a/vcore/vcore/ValidatorFactories.h b/vcore/vcore/ValidatorFactories.h
deleted file mode 100644 (file)
index b5d87b4..0000000
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * Copyright (c) 2011 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
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     1.0
- * @brief
- */
-#ifndef _WRT_ENGINE_SRC_INSTALLER_CORE_VALIDATION_CORE_VALIDATORFACTORY_H_
-#define _WRT_ENGINE_SRC_INSTALLER_CORE_VALIDATION_CORE_VALIDATORFACTORY_H_
-
-#include <vcore/CertificateIdentifier.h>
-
-namespace ValidationCore {
-// First use of CertificateIdentificator should initialized it.
-// We do not want to create cyclic dependencies between
-// CertificateConfigReader and CertificateIdentificator so
-// we are using factory method to create CertificateIdentificator.
-
-const CertificateIdentifier &createCertificateIdentifier();
-} // namespace ValidationCore
-
-#endif // _WRT_ENGINE_SRC_INSTALLER_CORE_VALIDATION_CORE_VALIDATORFACTORY_H_
diff --git a/vcore/vcore/ValidatorPluginApi.h b/vcore/vcore/ValidatorPluginApi.h
deleted file mode 100644 (file)
index fb895b4..0000000
+++ /dev/null
@@ -1,54 +0,0 @@
-/*
- *  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        ValidatonPluginApi.h
- * @author      Kyungwook Tak (k.tak@samsung.com)
- * @version     1.0
- * @brief       Validator plugin interface.
- */
-#pragma once
-
-#include <string>
-
-#include <vcore/SignatureData.h>
-#include <vcore/SignatureValidator.h>
-#include <vcore/Error.h>
-
-namespace ValidationCore {
-
-const std::string PLUGIN_PATH = "/usr/lib/libcert-svc-validator-plugin.so";
-
-class ValidatorPlugin {
-public:
-       virtual ~ValidatorPlugin() {}
-       virtual VCerr step(VCerr result, SignatureData &data) = 0;
-       virtual std::string errorToString(VCerr)
-       {
-               return std::string("Plugin developer should implement if error code added");
-       }
-};
-
-/*
- *  plugin developer should implement create/destroy pair functions
- *
- *  1. function extern C named 'create' of CreateValidatorPlugin_t
- *  2. function extern C named 'destroy' of DestroyValidatorPlugin_t
- */
-typedef ValidatorPlugin *(*CreateValidatorPlugin_t)(void);
-typedef void (*DestroyValidatorPlugin_t)(ValidatorPlugin *ptr);
-
-} // namespace ValidatonCore
diff --git a/vcore/vcore/XmlsecAdapter.cpp b/vcore/vcore/XmlsecAdapter.cpp
deleted file mode 100644 (file)
index 1694f2e..0000000
+++ /dev/null
@@ -1,443 +0,0 @@
-/*
- * 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        XmlsecAdapter.cpp
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     2.0
- * @brief
- */
-#include <cstdlib>
-#include <cstring>
-#include <functional>
-
-#include <libxml/tree.h>
-#include <libxml/xmlmemory.h>
-#include <libxml/parser.h>
-
-#ifndef XMLSEC_NO_XSLT
-#include <libxslt/xslt.h>
-#endif
-
-#include <xmlsec/xmlsec.h>
-#include <xmlsec/xmltree.h>
-#include <xmlsec/xmldsig.h>
-#include <xmlsec/crypto.h>
-#include <xmlsec/io.h>
-#include <xmlsec/keyinfo.h>
-#include <xmlsec/errors.h>
-
-#include <dpl/assert.h>
-#include <dpl/log/log.h>
-#include <dpl/singleton_impl.h>
-
-#include <vcore/XmlsecAdapter.h>
-
-#define VCORE_ERRORS_BUFFER_SIZE 1024
-
-IMPLEMENT_SINGLETON(ValidationCore::XmlSec)
-
-namespace {
-
-template <typename Type>
-struct CustomPtr {
-       Type ptr;
-       std::function<void(Type)> deleter;
-
-       CustomPtr() = delete;
-
-       explicit CustomPtr(Type in, std::function<void(Type)> d)
-               : ptr(in)
-               , deleter(d) {}
-
-       ~CustomPtr()
-       {
-               deleter(ptr);
-       }
-
-       inline Type get(void) const
-       {
-               return ptr;
-       }
-
-       inline Type operator->() const
-       {
-               return ptr;
-       }
-
-       inline bool operator!() const
-       {
-               return (ptr == nullptr) ? true : false;
-       }
-};
-
-struct FileWrapper {
-       FileWrapper(void *argFile, bool argReleased)
-               : file(argFile)
-               , released(argReleased)
-       {}
-       void *file;
-       bool released;
-};
-
-} // anonymous namespace
-
-namespace ValidationCore {
-
-static const std::string DIGEST_MD5 = "md5";
-
-std::string XmlSec::s_prefixPath;
-
-int XmlSec::fileMatchCallback(const char *filename)
-{
-       std::string path = s_prefixPath + filename;
-       return xmlFileMatch(path.c_str());
-}
-
-void *XmlSec::fileOpenCallback(const char *filename)
-{
-       std::string path = s_prefixPath + filename;
-       LogDebug("Xmlsec opening : " << path);
-       return new FileWrapper(xmlFileOpen(path.c_str()), false);
-}
-
-int XmlSec::fileReadCallback(void *context,
-                                                        char *buffer,
-                                                        int len)
-{
-       FileWrapper *fw = static_cast<FileWrapper *>(context);
-
-       if (fw->released)
-               return 0;
-
-       int output = xmlFileRead(fw->file, buffer, len);
-
-       if (output == 0) {
-               fw->released = true;
-               xmlFileClose(fw->file);
-       }
-
-       return output;
-}
-
-int XmlSec::fileCloseCallback(void *context)
-{
-       FileWrapper *fw = static_cast<FileWrapper *>(context);
-       int output = 0;
-
-       if (!fw->released)
-               output = xmlFileClose(fw->file);
-
-       delete fw;
-       return output;
-}
-
-void XmlSec::fileExtractPrefix(XmlSecContext &context)
-{
-       if (!context.workingDirectory.empty()) {
-               s_prefixPath = context.workingDirectory;
-               return;
-       }
-
-       s_prefixPath = context.signatureFile;
-       size_t pos = s_prefixPath.rfind('/');
-
-       if (pos == std::string::npos)
-               s_prefixPath.clear();
-       else
-               s_prefixPath.erase(pos + 1, std::string::npos);
-}
-
-void LogDebugPrint(const char *file,
-                                  int line,
-                                  const char *func,
-                                  const char *errorObject,
-                                  const char *errorSubject,
-                                  int reason,
-                                  const char *msg)
-{
-       // Get error message from xmlsec.
-       const char *errorMsg = NULL;
-       for (xmlSecSize i = 0; (i < XMLSEC_ERRORS_MAX_NUMBER) &&
-                                                       (xmlSecErrorsGetMsg(i) != NULL); ++i) {
-               if (xmlSecErrorsGetCode(i) == reason) {
-                       errorMsg = xmlSecErrorsGetMsg(i);
-                       break;
-               }
-       }
-
-       // Make full error message.
-       char buff[VCORE_ERRORS_BUFFER_SIZE];
-       snprintf(buff,
-                       sizeof(buff),
-                       "[%s:%d] %s(): obj=%s, subj=%s, error=%d:%s:%s\n",
-                       file,
-                       line,
-                       func,
-                       (errorObject != NULL) ? errorObject : "",
-                       (errorSubject != NULL) ? errorSubject : "",
-                       reason,
-                       (errorMsg != NULL) ? errorMsg : "",
-                       (msg != NULL) ? msg : "");
-
-       if (reason == XMLSEC_ERRORS_MAX_NUMBER)
-               LogError(buff);
-       else
-               LogDebug(buff);
-}
-
-XmlSec::XmlSec()
-       : m_initialized(false)
-       , m_pList(nullptr)
-{
-       LIBXML_TEST_VERSION
-       xmlLoadExtDtdDefaultValue = XML_DETECT_IDS | XML_COMPLETE_ATTRS;
-       xmlSubstituteEntitiesDefault(1);
-#ifndef XMLSEC_NO_XSLT
-       xmlIndentTreeOutput = 1;
-#endif
-
-       if (xmlSecInit() < 0)
-               ThrowMsg(Exception::InternalError, "Xmlsec initialization failed.");
-
-       if (xmlSecCheckVersion() != 1) {
-               xmlSecShutdown();
-               ThrowMsg(Exception::InternalError,
-                                "Loaded xmlsec library version is not compatible.");
-       }
-
-#ifdef XMLSEC_CRYPTO_DYNAMIC_LOADING
-
-       if (xmlSecCryptoDLLoadLibrary(BAD_CAST XMLSEC_CRYPTO) < 0) {
-               xmlSecShutdown();
-               LogError(
-                       "Error: unable to load default xmlsec-crypto library. Make sure "
-                       "that you have it installed and check shared libraries path "
-                       "(LD_LIBRARY_PATH) envornment variable.");
-               ThrowMsg(Exception::InternalError,
-                                "Unable to load default xmlsec-crypto library.");
-       }
-
-#endif
-
-       if (xmlSecCryptoAppInit(nullptr) < 0) {
-               xmlSecShutdown();
-               ThrowMsg(Exception::InternalError, "Crypto initialization failed.");
-       }
-
-       if (xmlSecCryptoInit() < 0) {
-               xmlSecCryptoAppShutdown();
-               xmlSecShutdown();
-               ThrowMsg(Exception::InternalError,
-                                "Xmlsec-crypto initialization failed.");
-       }
-
-       m_initialized = true;
-}
-
-XmlSec::~XmlSec()
-{
-       if (m_initialized)
-               return;
-
-       xmlSecCryptoShutdown();
-       xmlSecCryptoAppShutdown();
-       xmlSecShutdown();
-#ifndef XMLSEC_NO_XSLT
-       xsltCleanupGlobals();
-#endif
-       s_prefixPath.clear();
-       m_initialized = false;
-}
-
-void XmlSec::validateFile(XmlSecContext &context, xmlSecKeysMngrPtr mngrPtr)
-{
-       fileExtractPrefix(context);
-       LogDebug("Prefix path : " << s_prefixPath);
-       xmlSecIOCleanupCallbacks();
-       xmlSecIORegisterCallbacks(
-               fileMatchCallback,
-               fileOpenCallback,
-               fileReadCallback,
-               fileCloseCallback);
-       CustomPtr<xmlDocPtr> docPtr(xmlParseFile(context.signatureFile.c_str()), xmlFreeDoc);
-
-       if (!docPtr || xmlDocGetRootElement(docPtr.get()) == nullptr)
-               ThrowMsg(Exception::InvalidFormat,
-                                "Unable to parse sig xml file: " << context.signatureFile);
-
-       xmlNodePtr node = xmlSecFindNode(
-                                                 xmlDocGetRootElement(docPtr.get()),
-                                                 xmlSecNodeSignature,
-                                                 xmlSecDSigNs);
-
-       if (node == nullptr)
-               ThrowMsg(Exception::InvalidFormat,
-                                "Start node not found in " << context.signatureFile);
-
-       CustomPtr<xmlSecDSigCtxPtr> dsigCtx(xmlSecDSigCtxCreate(mngrPtr), xmlSecDSigCtxDestroy);
-
-       if (!dsigCtx)
-               ThrowMsg(Exception::OutOfMemory, "Failed to create signature context.");
-
-       if (context.allowBrokenChain)
-               dsigCtx->keyInfoReadCtx.flags |= XMLSEC_KEYINFO_FLAGS_ALLOW_BROKEN_CHAIN;
-
-       if (context.validationTime) {
-               LogDebug("Setting validation time.");
-               dsigCtx->keyInfoReadCtx.certsVerificationTime = context.validationTime;
-       }
-
-       int res;
-
-       switch (m_mode) {
-       case ValidateMode::NORMAL:
-               res = xmlSecDSigCtxVerify(dsigCtx.get(), node);
-               break;
-
-       case ValidateMode::NO_HASH:
-               res = xmlSecDSigCtxVerifyEx(dsigCtx.get(), node, 1, nullptr);
-               break;
-
-       case ValidateMode::PARTIAL_HASH: {
-               size_t n = m_pList->size();
-               const char *pList[n + 1] = {0};
-               size_t i = 0;
-
-               for (auto uri : *m_pList)
-                       pList[i++] = uri.c_str();
-
-               res = xmlSecDSigCtxVerifyEx(dsigCtx.get(), node, 0, pList);
-               break;
-       }
-
-       default:
-               ThrowMsg(Exception::InternalError, "ValidateMode is invalid");
-       }
-
-       if (res != 0)
-               ThrowMsg(Exception::InvalidSig, "Signature verify error.");
-
-       if (dsigCtx->keyInfoReadCtx.flags2 & XMLSEC_KEYINFO_ERROR_FLAGS_BROKEN_CHAIN) {
-               LogWarning("Signature contains broken chain!");
-               context.errorBrokenChain = true;
-       }
-
-       if (dsigCtx->status != xmlSecDSigStatusSucceeded)
-               ThrowMsg(Exception::InvalidSig, "Signature status is not succedded.");
-
-       xmlSecSize refSize = xmlSecPtrListGetSize(&(dsigCtx->signedInfoReferences));
-
-       for (xmlSecSize i = 0; i < refSize; ++i) {
-               xmlSecDSigReferenceCtxPtr dsigRefCtx = static_cast<xmlSecDSigReferenceCtxPtr>(
-                               xmlSecPtrListGetItem(&(dsigCtx->signedInfoReferences), i));
-
-               if (!dsigRefCtx || !dsigRefCtx->uri)
-                       continue;
-
-               if (dsigRefCtx->digestMethod
-                               && dsigRefCtx->digestMethod->id
-                               && dsigRefCtx->digestMethod->id->name) {
-                       auto digest = reinterpret_cast<const char *const>(
-                                                         dsigRefCtx->digestMethod->id->name);
-
-                       if (DIGEST_MD5.compare(digest) == 0)
-                               ThrowMsg(Exception::InvalidFormat,
-                                                "MD5 digest method used! Please use sha");
-               }
-
-               context.referenceSet.emplace(reinterpret_cast<char *>(dsigRefCtx->uri));
-       }
-}
-
-void XmlSec::loadDERCertificateMemory(XmlSecContext &context, xmlSecKeysMngrPtr mngrPtr)
-{
-       std::string derCert;
-
-       try {
-               derCert = context.certificatePtr->getDER();
-       } catch (Certificate::Exception::Base &e) {
-               ThrowMsg(Exception::InternalError,
-                                "Failed during x509 conversion to der format: " << e.DumpToString());
-       }
-
-       if (xmlSecCryptoAppKeysMngrCertLoadMemory(
-                               mngrPtr,
-                               reinterpret_cast<const xmlSecByte *>(derCert.data()),
-                               static_cast<xmlSecSize>(derCert.length()),
-                               xmlSecKeyDataFormatDer,
-                               xmlSecKeyDataTypeTrusted) < 0)
-               ThrowMsg(Exception::InternalError, "Failed to load der cert from memory.");
-}
-
-void XmlSec::loadPEMCertificateFile(XmlSecContext &context, xmlSecKeysMngrPtr mngrPtr)
-{
-       if (xmlSecCryptoAppKeysMngrCertLoad(
-                               mngrPtr,
-                               context.certificatePath.c_str(),
-                               xmlSecKeyDataFormatPem,
-                               xmlSecKeyDataTypeTrusted) < 0)
-               ThrowMsg(Exception::InternalError, "Failed to load PEM cert from file.");
-}
-
-void XmlSec::validateInternal(XmlSecContext &context)
-{
-       LogDebug("Start to validate.");
-       Assert(!context.signatureFile.empty());
-       Assert(!!context.certificatePtr || !context.certificatePath.empty());
-       xmlSecErrorsSetCallback(LogDebugPrint);
-
-       if (!m_initialized)
-               ThrowMsg(Exception::InternalError, "XmlSec is not initialized");
-
-       CustomPtr<xmlSecKeysMngrPtr> mngrPtr(xmlSecKeysMngrCreate(), xmlSecKeysMngrDestroy);
-
-       if (!mngrPtr)
-               ThrowMsg(Exception::InternalError, "Failed to create keys manager.");
-
-       if (xmlSecCryptoAppDefaultKeysMngrInit(mngrPtr.get()) < 0)
-               ThrowMsg(Exception::InternalError, "Failed to initialize keys manager.");
-
-       context.referenceSet.clear();
-
-       if (!!context.certificatePtr)
-               loadDERCertificateMemory(context, mngrPtr.get());
-
-       if (!context.certificatePath.empty())
-               loadPEMCertificateFile(context, mngrPtr.get());
-
-       validateFile(context, mngrPtr.get());
-}
-
-void XmlSec::validate(XmlSecContext &context)
-{
-       m_mode = ValidateMode::NORMAL;
-       validateInternal(context);
-}
-
-void XmlSec::validateNoHash(XmlSecContext &context)
-{
-       m_mode = ValidateMode::NO_HASH;
-       validateInternal(context);
-}
-
-void XmlSec::validatePartialHash(XmlSecContext &context, const std::list<std::string> &targetUri)
-{
-       m_mode = ValidateMode::PARTIAL_HASH;
-       m_pList = &targetUri;
-       validateInternal(context);
-}
-
-} // namespace ValidationCore
diff --git a/vcore/vcore/XmlsecAdapter.h b/vcore/vcore/XmlsecAdapter.h
deleted file mode 100644 (file)
index 0a0a522..0000000
+++ /dev/null
@@ -1,135 +0,0 @@
-/*
- * 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        XmlSecAdapter.h
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @version     2.0
- * @brief
- */
-#pragma once
-
-#include <string>
-#include <list>
-
-#include <xmlsec/keysmngr.h>
-
-#include <dpl/exception.h>
-#include <dpl/singleton.h>
-
-#include <vcore/Certificate.h>
-#include <vcore/SignatureData.h>
-
-namespace ValidationCore {
-class XmlSec {
-
-public:
-       XmlSec();
-       virtual ~XmlSec();
-
-       XmlSec(const XmlSec &) = delete;
-       XmlSec &operator=(const XmlSec &) = delete;
-       XmlSec(XmlSec &&) = delete;
-       XmlSec &operator=(XmlSec &&) = delete;
-
-       struct XmlSecContext {
-               /* You _must_ set one of the value: certificatePath or certificate. */
-               XmlSecContext()
-                       : validationTime(0)
-                       , allowBrokenChain(false)
-                       , errorBrokenChain(false) {}
-
-               /*
-                * Absolute path to signature file.
-                */
-               std::string signatureFile;
-               /*
-                * Direcotory with signed data.
-                * If you leave it empty xmlsec will use directory extracted
-                * from signatureFile.
-                */
-               std::string workingDirectory;
-               /*
-                * Path to trusted certificate.
-                */
-               std::string certificatePath;
-               /*
-                * Trusted certificate. In most cases it should be Root CA certificate.
-                */
-               CertificatePtr certificatePtr;
-               /*
-                * Validation date.
-                * 0 - uses current time.
-                */
-               time_t validationTime;
-               /*
-                * Input parameter.
-                * If true, signature validation will not be interrupted by chain error.
-                * If true and chain is broken then the value errorBrokenChain will be
-                * set to true.
-                */
-               bool allowBrokenChain;
-               /*
-                * Output parameter.
-                * This will be set if chain is incomplete or broken.
-                */
-               bool errorBrokenChain;
-               /*
-                * Output parameter.
-                * Reference checked by xmlsec
-                */
-               ReferenceSet referenceSet;
-       };
-
-       struct Exception {
-               DECLARE_EXCEPTION_TYPE(VcoreDPL::Exception, Base)
-               DECLARE_EXCEPTION_TYPE(Base, InternalError)
-               DECLARE_EXCEPTION_TYPE(Base, InvalidFormat)
-               DECLARE_EXCEPTION_TYPE(Base, InvalidSig)
-               DECLARE_EXCEPTION_TYPE(Base, OutOfMemory)
-       };
-
-       /* context - input/output param. */
-       void validate(XmlSecContext &context);
-       void validateNoHash(XmlSecContext &context);
-       void validatePartialHash(XmlSecContext &context, const std::list<std::string> &targetUri);
-
-private:
-       enum class ValidateMode : int {
-               NORMAL,
-               NO_HASH,
-               PARTIAL_HASH
-       };
-
-       ValidateMode m_mode;
-       bool m_initialized;
-       const std::list<std::string> *m_pList;
-
-       void loadDERCertificateMemory(XmlSecContext &context, xmlSecKeysMngrPtr mngr);
-       void loadPEMCertificateFile(XmlSecContext &context, xmlSecKeysMngrPtr mngr);
-       void validateInternal(XmlSecContext &context);
-       void validateFile(XmlSecContext &context, xmlSecKeysMngrPtr mngr);
-
-       static std::string s_prefixPath;
-       static int fileMatchCallback(const char *filename);
-       static void *fileOpenCallback(const char *filename);
-       static int fileReadCallback(void *context, char *buffer, int len);
-       static int fileCloseCallback(void *context);
-       static void fileExtractPrefix(XmlSecContext &context);
-};
-
-typedef VcoreDPL::Singleton<XmlSec> XmlSecSingleton;
-
-} // namespace ValidationCore
diff --git a/vcore/vcore/api.cpp b/vcore/vcore/api.cpp
deleted file mode 100644 (file)
index 4554e77..0000000
+++ /dev/null
@@ -1,1969 +0,0 @@
-/**
- * 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        api.cpp
- * @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
- * @author      Jacek Migacz (j.migacz@samsung.com)
- * @author      Sangwan Kwon (sangwan.kwon@samsung.com)
- * @version     1.0
- * @brief       This is part of C-api proposition for cert-svc.
- */
-#include <unistd.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <fcntl.h>
-#include <errno.h>
-
-#include <algorithm>
-#include <fstream>
-#include <map>
-#include <memory>
-#include <set>
-#include <string>
-#include <vector>
-
-#include <openssl/pem.h>
-#include <openssl/ssl.h>
-#include <openssl/x509v3.h>
-#include <openssl/pkcs12.h>
-#include <openssl/err.h>
-#include <openssl/sha.h>
-#include <openssl/evp.h>
-#include <openssl/bio.h>
-#include <libxml/parser.h>
-#include <libxml/tree.h>
-
-#include "dpl/log/log.h"
-
-#include "vcore/Base64.h"
-#include "vcore/Certificate.h"
-#include "vcore/CertificateCollection.h"
-#include "vcore/pkcs12.h"
-#include "vcore/Client.h"
-
-#include "cert-svc/cinstance.h"
-#include "cert-svc/ccert.h"
-#include "cert-svc/cpkcs12.h"
-#include "cert-svc/cprimitives.h"
-
-#define START_CERT      "-----BEGIN CERTIFICATE-----"
-#define END_CERT        "-----END CERTIFICATE-----"
-#define START_TRUSTED   "-----BEGIN TRUSTED CERTIFICATE-----"
-#define END_TRUSTED     "-----END TRUSTED CERTIFICATE-----"
-
-using namespace ValidationCore;
-
-namespace {
-
-struct CharDeleter {
-       void operator()(char *str) const
-       {
-               free(str);
-       }
-};
-
-struct CharArrDeleter {
-       void operator()(char **arr) const
-       {
-               size_t i = 0;
-
-               if (arr == NULL)
-                       return;
-
-               while (arr[i])
-                       free(arr[i++]);
-
-               free(arr);
-       }
-};
-
-class CertSvcInstanceImpl {
-public:
-       CertSvcInstanceImpl()
-               : m_certificateCounter(0)
-               , m_idListCounter(0)
-               , m_stringListCounter(0)
-       {}
-
-       ~CertSvcInstanceImpl()
-       {
-               auto it = m_allocatedStringSet.begin();
-
-               for (; it != m_allocatedStringSet.end(); ++it)
-                       delete[] *it;
-       }
-
-       inline void reset()
-       {
-               m_certificateCounter = 0;
-               m_certificateMap.clear();
-               m_idListCounter = 0;
-               m_idListMap.clear();
-               m_stringListCounter = 0;
-               m_stringListMap.clear();
-               auto it = m_allocatedStringSet.begin();
-
-               for (; it != m_allocatedStringSet.end(); ++it)
-                       delete[] *it;
-
-               m_allocatedStringSet.clear();
-       }
-
-       inline size_t addCert(const CertificatePtr &cert)
-       {
-               m_certificateMap[m_certificateCounter] = cert;
-               return m_certificateCounter++;
-       }
-
-       inline void removeCert(const CertSvcCertificate &cert)
-       {
-               auto iter = m_certificateMap.find(cert.privateHandler);
-
-               if (iter != m_certificateMap.end()) {
-                       m_certificateMap.erase(iter);
-               }
-       }
-
-       inline int getCertFromList(
-               const CertSvcCertificateList &handler,
-               size_t position,
-               CertSvcCertificate *certificate)
-       {
-               auto iter = m_idListMap.find(handler.privateHandler);
-
-               if (iter == m_idListMap.end()) {
-                       return CERTSVC_WRONG_ARGUMENT;
-               }
-
-               if (position >= iter->second.size()) {
-                       return CERTSVC_WRONG_ARGUMENT;
-               }
-
-               certificate->privateInstance = handler.privateInstance;
-               certificate->privateHandler = (iter->second)[position];
-               return CERTSVC_SUCCESS;
-       }
-
-       inline int getCertListLen(const CertSvcCertificateList &handler, size_t *len)
-       {
-               auto iter = m_idListMap.find(handler.privateHandler);
-
-               if (iter == m_idListMap.end() || !len) {
-                       return CERTSVC_WRONG_ARGUMENT;
-               }
-
-               *len = (iter->second).size();
-               return CERTSVC_SUCCESS;
-       }
-
-       inline void removeCertList(const CertSvcCertificateList &handler)
-       {
-               auto iter = m_idListMap.find(handler.privateHandler);
-
-               if (iter != m_idListMap.end())
-                       m_idListMap.erase(iter);
-       }
-
-       inline void removeCertListAll(const CertSvcCertificateList &handler)
-       {
-               auto iter = m_idListMap.find(handler.privateHandler);
-
-               if (iter == m_idListMap.end())
-                       return;
-
-               for (size_t pos = 0; pos < iter->second.size(); ++pos) {
-                       auto iterCert = m_certificateMap.find((iter->second)[pos]);
-
-                       if (iterCert == m_certificateMap.end())
-                               return;
-
-                       m_certificateMap.erase(iterCert);
-               }
-
-               m_idListMap.erase(iter);
-       }
-
-       inline int isSignedBy(const CertSvcCertificate &child,
-                                                 const CertSvcCertificate &parent,
-                                                 int *status)
-       {
-               auto citer = m_certificateMap.find(child.privateHandler);
-
-               if (citer == m_certificateMap.end()) {
-                       return CERTSVC_WRONG_ARGUMENT;
-               }
-
-               auto piter = m_certificateMap.find(parent.privateHandler);
-
-               if (piter == m_certificateMap.end()) {
-                       return CERTSVC_WRONG_ARGUMENT;
-               }
-
-               if (citer->second->isSignedBy(piter->second)) {
-                       *status = CERTSVC_TRUE;
-               } else {
-                       *status = CERTSVC_FALSE;
-               }
-
-               return CERTSVC_SUCCESS;
-       }
-
-       inline int getField(const CertSvcCertificate &cert,
-                                               CertSvcCertificateField field,
-                                               CertSvcString *buffer)
-       {
-               auto iter = m_certificateMap.find(cert.privateHandler);
-
-               if (iter == m_certificateMap.end()) {
-                       return CERTSVC_WRONG_ARGUMENT;
-               }
-
-               auto certPtr = iter->second;
-               std::string result;
-
-               switch (field) {
-               case CERTSVC_SUBJECT:
-                       result = certPtr->getOneLine();
-                       break;
-
-               case CERTSVC_ISSUER:
-                       result = certPtr->getOneLine(Certificate::FIELD_ISSUER);
-                       break;
-
-               case CERTSVC_SUBJECT_COMMON_NAME:
-                       result = certPtr->getCommonName();
-                       break;
-
-               case CERTSVC_SUBJECT_COUNTRY_NAME:
-                       result = certPtr->getCountryName();
-                       break;
-
-               case CERTSVC_SUBJECT_STATE_NAME:
-                       result = certPtr->getStateOrProvinceName();
-                       break;
-
-               case CERTSVC_SUBJECT_LOCALITY_NAME:
-                       result = certPtr->getLocalityName();
-                       break;
-
-               case CERTSVC_SUBJECT_ORGANIZATION_NAME:
-                       result = certPtr->getOrganizationName();
-                       break;
-
-               case CERTSVC_SUBJECT_ORGANIZATION_UNIT_NAME:
-                       result = certPtr->getOrganizationalUnitName();
-                       break;
-
-               case CERTSVC_SUBJECT_EMAIL_ADDRESS:
-                       result = certPtr->getEmailAddres();
-                       break;
-
-               /*
-                           case CERTSVC_SUBJECT_UID:
-                               result = certPtr->getUID();
-                               break;
-               */
-               case CERTSVC_ISSUER_COMMON_NAME:
-                       result = certPtr->getCommonName(Certificate::FIELD_ISSUER);
-                       break;
-
-               case CERTSVC_ISSUER_COUNTRY_NAME:
-                       result = certPtr->getCountryName(Certificate::FIELD_ISSUER);
-                       break;
-
-               case CERTSVC_ISSUER_STATE_NAME:
-                       result = certPtr->getStateOrProvinceName(Certificate::FIELD_ISSUER);
-                       break;
-
-               case CERTSVC_ISSUER_LOCALITY_NAME:
-                       result = certPtr->getLocalityName(Certificate::FIELD_ISSUER);
-                       break;
-
-               case CERTSVC_ISSUER_ORGANIZATION_NAME:
-                       result = certPtr->getOrganizationName(Certificate::FIELD_ISSUER);
-                       break;
-
-               case CERTSVC_ISSUER_ORGANIZATION_UNIT_NAME:
-                       result = certPtr->getOrganizationalUnitName(Certificate::FIELD_ISSUER);
-                       break;
-
-               case CERTSVC_ISSUER_EMAIL_ADDRESS:
-                       result = certPtr->getEmailAddres(Certificate::FIELD_ISSUER);
-                       break;
-
-               /*
-                           case CERTSVC_ISSUER_UID:
-                               result = certPtr->getUID(Certificate::FIELD_ISSUER);
-                               break;
-               */
-               case CERTSVC_VERSION: {
-                       std::stringstream stream;
-                       stream << (certPtr->getVersion() + 1);
-                       result = stream.str();
-                       break;
-               }
-
-               case CERTSVC_SERIAL_NUMBER:
-                       result = certPtr->getSerialNumberString();
-                       break;
-
-               case CERTSVC_KEY_USAGE:
-                       result = certPtr->getKeyUsageString();
-                       break;
-
-               case CERTSVC_KEY:
-                       result = certPtr->getPublicKeyString();
-                       break;
-
-               case CERTSVC_KEY_ALGO:
-                       result = certPtr->getPublicKeyAlgoString();
-                       break;
-
-               case CERTSVC_SIGNATURE_ALGORITHM:
-                       result = certPtr->getSignatureAlgorithmString();
-                       break;
-
-               default:
-                       break;
-               }
-
-               if (result.empty()) {
-                       buffer->privateHandler = NULL;
-                       buffer->privateLength = 0;
-                       buffer->privateInstance = cert.privateInstance;
-                       return CERTSVC_SUCCESS;
-               }
-
-               char *cstring = new char[result.size() + 1];
-
-               if (cstring == NULL) {
-                       buffer->privateHandler = NULL;
-                       buffer->privateLength = 0;
-                       buffer->privateInstance = cert.privateInstance;
-                       return CERTSVC_BAD_ALLOC;
-               }
-
-               strncpy(cstring, result.c_str(), result.size() + 1);
-               buffer->privateHandler = cstring;
-               buffer->privateLength = result.size();
-               buffer->privateInstance = cert.privateInstance;
-               m_allocatedStringSet.insert(cstring);
-               return CERTSVC_SUCCESS;
-       }
-
-       inline int getNotAfter(const CertSvcCertificate &cert,
-                                                  time_t *time)
-       {
-               auto iter = m_certificateMap.find(cert.privateHandler);
-
-               if (iter == m_certificateMap.end()) {
-                       return CERTSVC_WRONG_ARGUMENT;
-               }
-
-               *time = iter->second->getNotAfter();
-               return CERTSVC_SUCCESS;
-       }
-
-       inline int getNotBefore(const CertSvcCertificate &cert,
-                                                       time_t *time)
-       {
-               auto iter = m_certificateMap.find(cert.privateHandler);
-
-               if (iter == m_certificateMap.end()) {
-                       return CERTSVC_WRONG_ARGUMENT;
-               }
-
-               *time = iter->second->getNotBefore();
-               return CERTSVC_SUCCESS;
-       }
-
-       inline int isRootCA(const CertSvcCertificate &cert, int *status)
-       {
-               auto iter = m_certificateMap.find(cert.privateHandler);
-
-               if (iter == m_certificateMap.end()) {
-                       return CERTSVC_WRONG_ARGUMENT;
-               }
-
-               if (iter->second->isRootCert()) {
-                       *status = CERTSVC_TRUE;
-               } else {
-                       *status = CERTSVC_FALSE;
-               }
-
-               return CERTSVC_SUCCESS;
-       }
-
-       inline int getStringFromList(
-               const CertSvcStringList &handler,
-               size_t position,
-               CertSvcString *buffer)
-       {
-               buffer->privateHandler = NULL;
-               buffer->privateLength = 0;
-               auto iter = m_stringListMap.find(handler.privateHandler);
-
-               if (iter == m_stringListMap.end()) {
-                       return CERTSVC_WRONG_ARGUMENT;
-               }
-
-               if (position >= iter->second.size()) {
-                       return CERTSVC_WRONG_ARGUMENT;
-               }
-
-               const std::string &data = iter->second.at(position);
-               size_t size = data.size();
-               char *cstring = new char[size + 1];
-
-               if (!cstring) {
-                       return CERTSVC_FAIL;
-               }
-
-               strncpy(cstring, data.c_str(), size + 1);
-               buffer->privateHandler = cstring;
-               buffer->privateLength = size;
-               buffer->privateInstance = handler.privateInstance;
-               m_allocatedStringSet.insert(cstring);
-               return CERTSVC_SUCCESS;
-       }
-
-       inline int getStringListLen(
-               const CertSvcStringList &handler,
-               size_t *size)
-       {
-               auto iter = m_stringListMap.find(handler.privateHandler);
-
-               if (iter == m_stringListMap.end()) {
-                       return CERTSVC_WRONG_ARGUMENT;
-               }
-
-               *size = iter->second.size();
-               return CERTSVC_SUCCESS;
-       }
-
-       inline void removeStringList(const CertSvcStringList &handler)
-       {
-               m_stringListMap.erase(m_stringListMap.find(handler.privateHandler));
-       }
-
-       inline void removeString(const CertSvcString &handler)
-       {
-               auto iter = m_allocatedStringSet.find(handler.privateHandler);
-
-               if (iter != m_allocatedStringSet.end()) {
-                       delete[] *iter;
-                       m_allocatedStringSet.erase(iter);
-               }
-       }
-
-       inline int sortCollection(CertSvcCertificate *certificate_array, size_t size)
-       {
-               if (size < 2) {
-                       return CERTSVC_WRONG_ARGUMENT;
-               }
-
-               for (size_t i = 1; i < size; ++i) {
-                       if (certificate_array[i - 1].privateInstance.privatePtr
-                                       != certificate_array[i].privateInstance.privatePtr) {
-                               return CERTSVC_WRONG_ARGUMENT;
-                       }
-               }
-
-               CertificateList certList;
-               std::map<Certificate *, size_t> translator;
-
-               for (size_t i = 0; i < size; ++i) {
-                       size_t pos = certificate_array[i].privateHandler;
-                       auto cert = m_certificateMap.find(pos);
-
-                       if (cert == m_certificateMap.end()) {
-                               return CERTSVC_WRONG_ARGUMENT;
-                       }
-
-                       translator[cert->second.get()] = pos;
-                       certList.push_back(cert->second);
-               }
-
-               CertificateCollection collection;
-               collection.load(certList);
-
-               if (!collection.sort()) {
-                       return CERTSVC_FAIL;
-               }
-
-               auto chain = collection.getChain();
-               size_t i = 0;
-
-               for (const auto &cert : collection.getChain())
-                       certificate_array[i++].privateHandler = translator[cert.get()];
-
-               return CERTSVC_SUCCESS;
-       }
-
-       inline int getX509Copy(const CertSvcCertificate &certificate, X509 **cert)
-       {
-               auto it = m_certificateMap.find(certificate.privateHandler);
-
-               if (it == m_certificateMap.end()) {
-                       return CERTSVC_WRONG_ARGUMENT;
-               }
-
-               *cert = X509_dup(it->second->getX509());
-               return CERTSVC_SUCCESS;
-       }
-
-       inline int getPubkeyDER(const CertSvcCertificate &certificate,
-                                                       unsigned char **pubkey,
-                                                       size_t *len)
-       {
-               auto it = m_certificateMap.find(certificate.privateHandler);
-
-               if (it == m_certificateMap.end() || pubkey == NULL || len == NULL)
-                       return CERTSVC_WRONG_ARGUMENT;
-
-               it->second->getPublicKeyDER(pubkey, len);
-               return CERTSVC_SUCCESS;
-       }
-
-       inline int saveToFile(const CertSvcCertificate &certificate,
-                                                 const char *location)
-       {
-               auto it = m_certificateMap.find(certificate.privateHandler);
-
-               if (it == m_certificateMap.end()) {
-                       return CERTSVC_WRONG_ARGUMENT;
-               }
-
-               FILE *out = fopen(location, "w");
-
-               if (out == NULL) {
-                       return CERTSVC_FAIL;
-               }
-
-               if (0 == i2d_X509_fp(out, it->second->getX509())) {
-                       fclose(out);
-                       return CERTSVC_FAIL;
-               }
-
-               fclose(out);
-               return CERTSVC_SUCCESS;
-       }
-
-       inline int verify(
-               CertSvcCertificate certificate,
-               CertSvcString &message,
-               CertSvcString &signature,
-               const char *algorithm,
-               int *status)
-       {
-               int result = CERTSVC_FAIL;
-
-               if (!status) {
-                       return CERTSVC_WRONG_ARGUMENT;
-               }
-
-               auto it = m_certificateMap.find(certificate.privateHandler);
-
-               if (it == m_certificateMap.end()) {
-                       return CERTSVC_WRONG_ARGUMENT;
-               }
-
-               OpenSSL_add_all_digests();
-               int temp;
-               EVP_MD_CTX *mdctx = NULL;
-               const EVP_MD *md = NULL;
-               X509 *cert = it->second->getX509();
-               EVP_PKEY *pkey = NULL;
-
-               if (cert == NULL) {
-                       goto err;
-               }
-
-               pkey = X509_get_pubkey(cert);
-
-               if (pkey == NULL) {
-                       goto err;
-               }
-
-               if (algorithm == NULL) {
-                       md = EVP_get_digestbyobj(cert->cert_info->signature->algorithm);
-               } else {
-                       md = EVP_get_digestbyname(algorithm);
-               }
-
-               if (md == NULL) {
-                       result = CERTSVC_INVALID_ALGORITHM;
-                       goto err;
-               }
-
-               mdctx = EVP_MD_CTX_create();
-
-               if (mdctx == NULL) {
-                       goto err;
-               }
-
-               if (EVP_VerifyInit_ex(mdctx, md, NULL) != 1) {
-                       goto err;
-               }
-
-               if (EVP_VerifyUpdate(mdctx, message.privateHandler, message.privateLength) != 1) {
-                       goto err;
-               }
-
-               temp = EVP_VerifyFinal(mdctx,
-                                                          reinterpret_cast<unsigned char *>(signature.privateHandler),
-                                                          signature.privateLength,
-                                                          pkey);
-
-               if (temp == 0) {
-                       *status = CERTSVC_INVALID_SIGNATURE;
-                       result = CERTSVC_SUCCESS;
-               } else if (temp == 1) {
-                       *status = CERTSVC_SUCCESS;
-                       result = CERTSVC_SUCCESS;
-               }
-
-err:
-
-               if (mdctx != NULL)
-                       EVP_MD_CTX_destroy(mdctx);
-
-               if (pkey != NULL)
-                       EVP_PKEY_free(pkey);
-
-               return result;
-       }
-
-       inline int base64Encode(
-               const CertSvcString &message,
-               CertSvcString *base64)
-       {
-               if (!base64) {
-                       return CERTSVC_WRONG_ARGUMENT;
-               }
-
-               std::string info(message.privateHandler, message.privateLength);
-               Base64Encoder base;
-               base.reset();
-               base.append(info);
-               base.finalize();
-               info = base.get();
-               char *ptr = new char[info.size() + 1];
-
-               if (ptr == NULL) {
-                       return CERTSVC_BAD_ALLOC;
-               }
-
-               memcpy(ptr, info.c_str(), info.size() + 1);
-               m_allocatedStringSet.insert(ptr);
-               base64->privateHandler = ptr;
-               base64->privateLength = info.size();
-               base64->privateInstance = message.privateInstance;
-               return CERTSVC_SUCCESS;
-       }
-
-       int base64Decode(
-               const CertSvcString &base64,
-               CertSvcString *message)
-       {
-               if (!message) {
-                       return CERTSVC_WRONG_ARGUMENT;
-               }
-
-               std::string info(base64.privateHandler, base64.privateLength);
-               Base64Decoder base;
-               base.reset();
-               base.append(info);
-
-               if (!base.finalize()) {
-                       return CERTSVC_FAIL;
-               }
-
-               info = base.get();
-               char *ptr = new char[info.size() + 1];
-
-               if (ptr == NULL) {
-                       return CERTSVC_BAD_ALLOC;
-               }
-
-               memcpy(ptr, info.c_str(), info.size() + 1);
-               m_allocatedStringSet.insert(ptr);
-               message->privateHandler = ptr;
-               message->privateLength = info.size();
-               message->privateInstance = base64.privateInstance;
-               return CERTSVC_SUCCESS;
-       }
-
-       inline int stringNew(
-               CertSvcInstance &instance,
-               const char *str,
-               size_t size,
-               CertSvcString *output)
-       {
-               if (!output)
-                       return CERTSVC_WRONG_ARGUMENT;
-
-               /* return struct for empty string */
-               if (size == 0 || str == NULL) {
-                       output->privateHandler = NULL;
-                       output->privateLength = 0;
-                       output->privateInstance = instance;
-                       return CERTSVC_SUCCESS;
-               }
-
-               if (strlen(str) < size)
-                       return CERTSVC_WRONG_ARGUMENT;
-
-               char *ptr = new(std::nothrow) char[size + 1];
-
-               if (ptr == NULL)
-                       return CERTSVC_BAD_ALLOC;
-
-               memcpy(ptr, str, size);
-               ptr[size] = '\0';
-               output->privateHandler = ptr;
-               output->privateLength = size;
-               output->privateInstance = instance;
-               m_allocatedStringSet.insert(ptr);
-               return CERTSVC_SUCCESS;
-       }
-
-       inline int certificateVerify(
-               CertSvcCertificate certificate,
-               const CertSvcCertificate *trusted,
-               size_t trustedSize,
-               const CertSvcCertificate *untrusted,
-               size_t untrustedSize,
-               int checkCaFlag,
-               int *status)
-       {
-               if (!trusted || !status) {
-                       return CERTSVC_WRONG_ARGUMENT;
-               }
-
-               auto iter = m_certificateMap.find(certificate.privateHandler);
-
-               if (iter == m_certificateMap.end()) {
-                       return CERTSVC_WRONG_ARGUMENT;
-               }
-
-               X509 *cert = iter->second->getX509();
-               X509_STORE *store = X509_STORE_new();
-               STACK_OF(X509) *ustore = sk_X509_new_null();
-
-               for (size_t i = 0; i < trustedSize; ++i) {
-                       auto iter = m_certificateMap.find(trusted[i].privateHandler);
-
-                       if (iter == m_certificateMap.end()) {
-                               X509_STORE_free(store);
-                               sk_X509_free(ustore);
-                               return CERTSVC_WRONG_ARGUMENT;
-                       }
-
-                       X509_STORE_add_cert(store, iter->second->getX509());
-               }
-
-               for (size_t i = 0; i < untrustedSize; ++i) {
-                       auto iter = m_certificateMap.find(untrusted[i].privateHandler);
-
-                       if (iter == m_certificateMap.end()) {
-                               X509_STORE_free(store);
-                               sk_X509_free(ustore);
-                               return CERTSVC_WRONG_ARGUMENT;
-                       }
-
-                       if (sk_X509_push(ustore, iter->second->getX509()) == 0)
-                               break;
-               }
-
-               X509_STORE_CTX context;
-               X509_STORE_CTX_init(&context, store, cert, ustore);
-               int result = X509_verify_cert(&context);
-
-               if (result == 1 && checkCaFlag) { // check strictly
-                       STACK_OF(X509) *resultChain = X509_STORE_CTX_get1_chain(&context);
-                       X509 *tmpCert = NULL;
-                       int caFlagValidity;
-
-                       while ((tmpCert = sk_X509_pop(resultChain))) {
-                               caFlagValidity = X509_check_ca(tmpCert);
-
-                               if (caFlagValidity != 1 && (tmpCert = sk_X509_pop(resultChain)) != NULL) {
-                                       // the last one is not a CA.
-                                       result = 0;
-                                       break;
-                               }
-                       }
-               }
-
-               X509_STORE_CTX_cleanup(&context);
-               X509_STORE_free(store);
-               sk_X509_free(ustore);
-
-               if (result == 1) {
-                       *status = CERTSVC_SUCCESS;
-               } else {
-                       *status = CERTSVC_FAIL;
-               }
-
-               return CERTSVC_SUCCESS;
-       }
-
-       // TODO : sangan.kwon, modify method by using CertificateIdentifier
-       int getVisibility(CertSvcCertificate certificate, CertSvcVisibility *visibility,
-                                         const char *fingerprintListPath)
-       {
-               int ret = CERTSVC_FAIL;
-               //xmlChar *xmlPathCertificateSet  = (xmlChar*) "CertificateSet"; /*unused variable*/
-               //xmlChar *xmlPathCertificateDomain = (xmlChar*) "CertificateDomain";// name=\"tizen-platform\""; /*unused variable*/
-               xmlChar *xmlPathDomainPlatform = (xmlChar *) "tizen-platform";
-               xmlChar *xmlPathDomainPublic = (xmlChar *) "tizen-public";
-               xmlChar *xmlPathDomainPartner = (xmlChar *) "tizen-partner";
-               xmlChar *xmlPathDomainDeveloper = (xmlChar *) "tizen-developer";
-               //xmlChar *xmlPathFingerPrintSHA1 = (xmlChar*) "FingerprintSHA1"; /*unused variable*/
-               auto iter = m_certificateMap.find(certificate.privateHandler);
-
-               if (iter == m_certificateMap.end()) {
-                       return CERTSVC_FAIL;
-               }
-
-               CertificatePtr certPtr = iter->second;
-               std::string fingerprint = Certificate::FingerprintToColonHex(certPtr->getFingerprint(
-                                                                         Certificate::FINGERPRINT_SHA1));
-               /*   load file */
-               xmlDocPtr doc = xmlParseFile(fingerprintListPath);
-
-               if ((doc == NULL) || (xmlDocGetRootElement(doc) == NULL)) {
-                       LogError("Failed to prase fingerprint_list.xml");
-                       return CERTSVC_IO_ERROR;
-               }
-
-               xmlNodePtr curPtr = xmlFirstElementChild(xmlDocGetRootElement(doc));
-
-               if (curPtr == NULL) {
-                       LogError("Can not find root");
-                       ret = CERTSVC_IO_ERROR;
-                       goto out;
-               }
-
-               while (curPtr != NULL) {
-                       xmlAttr *attr = curPtr->properties;
-
-                       if (!attr->children || !attr->children->content) {
-                               LogError("Failed to get fingerprints from list");
-                               ret = CERTSVC_FAIL;
-                               goto out;
-                       }
-
-                       xmlChar *strLevel = attr->children->content;
-                       xmlNodePtr FpPtr = xmlFirstElementChild(curPtr);
-
-                       if (FpPtr == NULL) {
-                               LogError("Could not find fingerprint");
-                               ret = CERTSVC_FAIL;
-                               goto out;
-                       }
-
-                       LogDebug("Retrieve level : " << strLevel);
-
-                       while (FpPtr) {
-                               xmlChar *content = xmlNodeGetContent(FpPtr);
-
-                               if (xmlStrcmp(content, (xmlChar *)fingerprint.c_str()) == 0) {
-                                       LogDebug("fingerprint : " << content << " are " << strLevel);
-
-                                       if (!xmlStrcmp(strLevel, xmlPathDomainPlatform)) {
-                                               *visibility = CERTSVC_VISIBILITY_PLATFORM;
-                                               ret = CERTSVC_SUCCESS;
-                                               goto out;
-                                       } else if (!xmlStrcmp(strLevel, xmlPathDomainPublic)) {
-                                               *visibility = CERTSVC_VISIBILITY_PUBLIC;
-                                               ret = CERTSVC_SUCCESS;
-                                               goto out;
-                                       } else if (!xmlStrcmp(strLevel, xmlPathDomainPartner)) {
-                                               *visibility = CERTSVC_VISIBILITY_PARTNER;
-                                               ret = CERTSVC_SUCCESS;
-                                               goto out;
-                                       } else if (!xmlStrcmp(strLevel, xmlPathDomainDeveloper)) {
-                                               *visibility = CERTSVC_VISIBILITY_DEVELOPER;
-                                               ret = CERTSVC_SUCCESS;
-                                               goto out;
-                                       }
-                               }
-
-                               FpPtr = xmlNextElementSibling(FpPtr);
-                       }
-
-                       curPtr = xmlNextElementSibling(curPtr);
-               }
-
-               xmlFreeDoc(doc);
-               return CERTSVC_FAIL;
-out:
-               xmlFreeDoc(doc);
-               return ret;
-       }
-
-       inline int pkcsNameIsUniqueInStore(
-               CertStoreType storeType,
-               CertSvcString pfxIdString,
-               int *is_unique)
-       {
-               return vcore_client_check_alias_exist_in_store(storeType, pfxIdString.privateHandler, is_unique);
-       }
-
-       inline int getCertDetailFromStore(CertStoreType storeType,
-                                                                         CertSvcString gname,
-                                                                         char **certBuffer,
-                                                                         size_t *certSize)
-       {
-               return vcore_client_get_certificate_from_store(storeType, gname.privateHandler, certBuffer,
-                               certSize, PEM_CRT);
-       }
-
-       inline int pkcsDeleteCertFromStore(
-               CertStoreType storeType,
-               CertSvcString gname
-       )
-       {
-               return vcore_client_delete_certificate_from_store(storeType, gname.privateHandler);
-       }
-
-       inline int pkcsHasPassword(
-               CertSvcString filepath,
-               int *has_password)
-       {
-               return pkcs12_has_password(filepath.privateHandler, has_password);
-       }
-
-       inline int pkcsImportToStore(
-               CertStoreType storeType,
-               CertSvcString path,
-               CertSvcString pass,
-               CertSvcString pfxIdString)
-       {
-               return pkcs12_import_from_file_to_store(storeType, path.privateHandler, pass.privateHandler,
-                                                                                               pfxIdString.privateHandler);
-       }
-
-       inline int pkcsGetAliasNameForCertInStore(CertStoreType storeType,
-                       CertSvcString gname,
-                       char **alias)
-       {
-               return vcore_client_get_certificate_alias_from_store(storeType, gname.privateHandler, alias);
-       }
-
-       inline int pkcsSetCertStatusToStore(CertStoreType storeType,
-                                                                               int is_root_app,
-                                                                               CertSvcString gname,
-                                                                               CertStatus status)
-       {
-               return vcore_client_set_certificate_status_to_store(storeType, is_root_app, gname.privateHandler,
-                               status);
-       }
-
-       inline int pkcsGetCertStatusFromStore(
-               CertStoreType storeType,
-               CertSvcString gname,
-               CertStatus *status)
-       {
-               return vcore_client_get_certificate_status_from_store(storeType, gname.privateHandler, status);
-       }
-
-       inline int getCertFromStore(CertSvcInstance instance,
-                                                               CertStoreType storeType,
-                                                               const char *gname,
-                                                               CertSvcCertificate *certificate)
-       {
-               return certsvc_get_certificate(instance, storeType, gname, certificate);
-       }
-
-       inline int freePkcsIdListFromStore(CertSvcStoreCertList **certList)
-       {
-               CertSvcStoreCertList *current;
-               CertSvcStoreCertList *next;
-
-               for (current = *certList; current != NULL; current = next) {
-                       next = current->next;
-                       free(current->title);
-                       free(current->gname);
-                       free(current);
-               }
-
-               *certList = NULL;
-               return CERTSVC_SUCCESS;
-       }
-
-       inline int getPkcsIdListFromStore(
-               CertStoreType storeType,
-               int is_root_app,
-               CertSvcStoreCertList **certList,
-               size_t *length)
-       {
-               return vcore_client_get_certificate_list_from_store(storeType, is_root_app, certList, length);
-       }
-
-       inline int getPkcsIdEndUserListFromStore(
-               CertStoreType storeType,
-               CertSvcStoreCertList **certList,
-               size_t *length)
-       {
-               return vcore_client_get_end_user_certificate_list_from_store(storeType, certList, length);
-       }
-
-       inline int getPkcsIdRootListFromStore(
-               CertStoreType storeType,
-               CertSvcStoreCertList **certList,
-               size_t *length)
-       {
-               return vcore_client_get_root_certificate_list_from_store(storeType, certList, length);
-       }
-
-       inline int getPkcsPrivateKeyFromStore(
-               CertStoreType storeType,
-               CertSvcString gname,
-               char **certBuffer,
-               size_t *certSize)
-       {
-               return vcore_client_get_certificate_from_store(storeType, gname.privateHandler, certBuffer,
-                               certSize, (CertType)P12_PKEY);
-       }
-
-       inline int getPkcsCertificateListFromStore(
-               CertSvcInstance &instance,
-               CertStoreType storeType,
-               CertSvcString &pfxIdString,
-               CertSvcCertificateList *handler)
-       {
-               char **certs = NULL;
-               size_t ncerts = 0;
-               int result = vcore_client_load_certificates_from_store(storeType, pfxIdString.privateHandler,
-                                        &certs, &ncerts);
-
-               if (result != CERTSVC_SUCCESS) {
-                       LogError("Unable to load certificates from store.");
-                       return result;
-               }
-
-               std::shared_ptr<char *> certsPtr(certs, CharArrDeleter());
-               std::vector<CertificatePtr> certPtrVector;
-
-               for (size_t i = 0; i < ncerts; i++) {
-                       CertSvcString Alias;
-                       Alias.privateHandler = certs[i];
-                       Alias.privateLength = strlen(certs[i]);
-                       char *certBuffer = NULL;
-                       size_t certLength = 0;
-                       result = certsvc_pkcs12_get_certificate_info_from_store(instance, storeType, Alias, &certBuffer,
-                                        &certLength);
-
-                       if (result != CERTSVC_SUCCESS || !certBuffer) {
-                               LogError("Failed to get certificate buffer.");
-                               return CERTSVC_FAIL;
-                       }
-
-                       std::shared_ptr<char> certBufferPtr(certBuffer, CharDeleter());
-                       const char *header = strstr(certBuffer, START_CERT);
-                       const char *headEnd = START_CERT;
-
-                       if (!header) {
-                               header = strstr(certBuffer, START_TRUSTED);
-                               headEnd = START_TRUSTED;
-
-                               if (!header) {
-                                       LogError("Invalid format of certificate. alias : " << certs[i]);
-                                       return CERTSVC_FAIL;
-                               }
-                       }
-
-                       const char *trailer = strstr(header, END_CERT);
-                       const char *tailEnd = END_CERT;
-
-                       if (!trailer) {
-                               trailer = strstr(header, END_TRUSTED);
-                               tailEnd = END_TRUSTED;
-
-                               if (!trailer) {
-                                       LogError("Invalid format of certificate. alias : " << certs[i]);
-                                       return CERTSVC_FAIL;
-                               }
-                       }
-
-                       if ((strcmp(headEnd, START_CERT) == 0 && strcmp(tailEnd, END_TRUSTED) == 0)
-                                       || (strcmp(headEnd, START_TRUSTED) == 0 && strcmp(tailEnd, END_CERT) == 0)) {
-                               LogError("Invalid format of certificate. alias : " << certs[i]);
-                               return CERTSVC_FAIL;
-                       }
-
-                       header += strlen(headEnd); /* cut headEnd */
-                       std::string certStr(header, strlen(header) - strlen(trailer));
-                       certPtrVector.push_back(CertificatePtr(new Certificate(certStr, Certificate::FORM_BASE64)));
-               }
-
-               std::vector<size_t> listId;
-
-               for (const auto &cert : certPtrVector)
-                       listId.push_back(addCert(cert));
-
-               size_t position = m_idListCounter++;
-               m_idListMap[position] = listId;
-               handler->privateInstance = instance;
-               handler->privateHandler = position;
-               return result;
-       }
-
-       inline bool checkValidStoreType(CertStoreType storeType)
-       {
-               if (storeType >= VPN_STORE && storeType <= ALL_STORE)
-                       return true;
-               else
-                       return false;
-       }
-
-private:
-       size_t m_certificateCounter;
-       std::map<size_t, CertificatePtr> m_certificateMap;
-
-       size_t m_idListCounter;
-       std::map<size_t, std::vector<size_t>> m_idListMap;
-
-       size_t m_stringListCounter;
-       std::map<size_t, std::vector<std::string>> m_stringListMap;
-
-       std::set<char *> m_allocatedStringSet;
-};
-
-inline CertSvcInstanceImpl *impl(CertSvcInstance instance)
-{
-       return static_cast<CertSvcInstanceImpl *>(instance.privatePtr);
-}
-
-} // namespace anonymous
-
-int certsvc_instance_new(CertSvcInstance *instance)
-{
-       static int init = 1;
-
-       if (init) {
-               OpenSSL_add_ssl_algorithms();
-               OpenSSL_add_all_digests();
-               init = 0;
-       }
-
-       try {
-               instance->privatePtr =
-                       reinterpret_cast<void *>(new CertSvcInstanceImpl);
-
-               if (instance->privatePtr)
-                       return CERTSVC_SUCCESS;
-       } catch (std::bad_alloc &) {
-               return CERTSVC_BAD_ALLOC;
-       } catch (...) {}
-
-       return CERTSVC_FAIL;
-}
-
-void certsvc_instance_reset(CertSvcInstance instance)
-{
-       impl(instance)->reset();
-}
-
-void certsvc_instance_free(CertSvcInstance instance)
-{
-       delete impl(instance);
-}
-
-int certsvc_certificate_new_from_file(
-       CertSvcInstance instance,
-       const char *location,
-       CertSvcCertificate *certificate)
-{
-       try {
-               CertificatePtr cert = Certificate::createFromFile(location);
-               certificate->privateInstance = instance;
-               certificate->privateHandler = impl(instance)->addCert(cert);
-               return CERTSVC_SUCCESS;
-               // TODO support for std exceptions
-       } catch (std::bad_alloc &) {
-               return CERTSVC_BAD_ALLOC;
-       } catch (...) {}
-
-       return CERTSVC_FAIL;
-}
-
-int certsvc_certificate_new_from_memory(
-       CertSvcInstance instance,
-       const unsigned char *memory,
-       size_t len,
-       CertSvcCertificateForm form,
-       CertSvcCertificate *certificate)
-{
-       try {
-               Certificate::FormType formType;
-               std::string binary((char *)memory, len);
-
-               if (CERTSVC_FORM_DER == form) {
-                       formType = Certificate::FORM_DER;
-               } else {
-                       formType = Certificate::FORM_BASE64;
-               }
-
-               CertificatePtr cert(new Certificate(binary, formType));
-               certificate->privateInstance = instance;
-               certificate->privateHandler = impl(instance)->addCert(cert);
-               return CERTSVC_SUCCESS;
-       } catch (std::bad_alloc &) {
-               return CERTSVC_BAD_ALLOC;
-       } catch (...) {}
-
-       return CERTSVC_FAIL;
-}
-
-void certsvc_certificate_free(CertSvcCertificate certificate)
-{
-       if (certificate.privateHandler != 0)
-               impl(certificate.privateInstance)->removeCert(certificate);
-}
-
-int certsvc_certificate_save_file(
-       CertSvcCertificate certificate,
-       const char *location)
-{
-       return impl(certificate.privateInstance)->saveToFile(certificate, location);
-}
-
-int certsvc_certificate_list_get_one(
-       CertSvcCertificateList handler,
-       size_t position,
-       CertSvcCertificate *certificate)
-{
-       return impl(handler.privateInstance)->
-                  getCertFromList(handler, position, certificate);
-}
-
-int certsvc_certificate_list_get_length(
-       CertSvcCertificateList handler,
-       size_t *size)
-{
-       return impl(handler.privateInstance)->getCertListLen(handler, size);
-}
-
-void certsvc_certificate_list_free(CertSvcCertificateList handler)
-{
-       impl(handler.privateInstance)->removeCertList(handler);
-}
-
-void certsvc_certificate_list_all_free(CertSvcCertificateList handler)
-{
-       impl(handler.privateInstance)->removeCertListAll(handler);
-}
-
-int certsvc_certificate_is_signed_by(
-       CertSvcCertificate child,
-       CertSvcCertificate parent,
-       int *status)
-{
-       if (child.privateInstance.privatePtr == parent.privateInstance.privatePtr) {
-               return impl(child.privateInstance)->isSignedBy(child, parent, status);
-       }
-
-       return CERTSVC_WRONG_ARGUMENT;
-}
-
-int certsvc_certificate_get_string_field(
-       CertSvcCertificate certificate,
-       CertSvcCertificateField field,
-       CertSvcString *buffer)
-{
-       try {
-               return impl(certificate.privateInstance)->getField(certificate, field, buffer);
-       } catch (std::bad_alloc &) {
-               return CERTSVC_BAD_ALLOC;
-       } catch (...) {}
-
-       return CERTSVC_FAIL;
-}
-
-int certsvc_certificate_get_not_after(
-       CertSvcCertificate certificate,
-       time_t *result)
-{
-       try {
-               return impl(certificate.privateInstance)->getNotAfter(certificate, result);
-       } catch (...) {}
-
-       return CERTSVC_FAIL;
-}
-
-int certsvc_certificate_get_not_before(
-       CertSvcCertificate certificate,
-       time_t *result)
-{
-       try {
-               return impl(certificate.privateInstance)->getNotBefore(certificate, result);
-       } catch (...) {}
-
-       return CERTSVC_FAIL;
-}
-
-int certsvc_certificate_is_root_ca(CertSvcCertificate certificate, int *status)
-{
-       return impl(certificate.privateInstance)->isRootCA(certificate, status);
-}
-
-int certsvc_string_list_get_one(
-       CertSvcStringList handler,
-       size_t position,
-       CertSvcString *buffer)
-{
-       try {
-               return impl(handler.privateInstance)->getStringFromList(handler, position, buffer);
-       } catch (std::bad_alloc &) {
-               return CERTSVC_BAD_ALLOC;
-       } catch (...) {}
-
-       return CERTSVC_FAIL;
-}
-
-int certsvc_string_list_get_length(
-       CertSvcStringList handler,
-       size_t *size)
-{
-       return impl(handler.privateInstance)->getStringListLen(handler, size);
-}
-
-void certsvc_string_list_free(CertSvcStringList handler)
-{
-       if (handler.privateHandler != 0) {
-               impl(handler.privateInstance)->removeStringList(handler);
-               handler.privateHandler = 0;
-       }
-}
-
-void certsvc_string_free(CertSvcString string)
-{
-       if (string.privateHandler)
-               impl(string.privateInstance)->removeString(string);
-}
-
-void certsvc_string_to_cstring(
-       CertSvcString string,
-       const char **buffer,
-       size_t *len)
-{
-       if (buffer) {
-               *buffer = string.privateHandler;
-       }
-
-       if (len) {
-               *len = string.privateLength;
-       }
-}
-
-int certsvc_certificate_chain_sort(
-       CertSvcCertificate *certificate_array,
-       size_t size)
-{
-       try {
-               if (!certificate_array) {
-                       return CERTSVC_WRONG_ARGUMENT;
-               }
-
-               return impl(certificate_array[0].privateInstance)->
-                          sortCollection(certificate_array, size);
-       } catch (std::bad_alloc &) {
-               return CERTSVC_BAD_ALLOC;
-       } catch (...) {}
-
-       return CERTSVC_FAIL;
-}
-
-int certsvc_certificate_dup_x509(CertSvcCertificate certificate, X509 **cert)
-{
-       try {
-               return impl(certificate.privateInstance)->getX509Copy(certificate, cert);
-       } catch (...) {}
-
-       return CERTSVC_FAIL;
-}
-
-void certsvc_certificate_free_x509(X509 *x509)
-{
-       if (x509)
-               X509_free(x509);
-}
-
-int certsvc_certificate_dup_pubkey_der(
-       CertSvcCertificate certificate,
-       unsigned char **pubkey,
-       size_t *len)
-{
-       try {
-               return impl(certificate.privateInstance)->getPubkeyDER(certificate, pubkey, len);
-       } catch (...) {}
-
-       return CERTSVC_FAIL;
-}
-
-void certsvc_pkcs12_free_evp_pkey(EVP_PKEY *pkey)
-{
-       EVP_PKEY_free(pkey);
-}
-
-int certsvc_message_verify(
-       CertSvcCertificate certificate,
-       CertSvcString message,
-       CertSvcString signature,
-       const char *algorithm,
-       int *status)
-{
-       try {
-               return impl(certificate.privateInstance)->verify(
-                                  certificate,
-                                  message,
-                                  signature,
-                                  algorithm,
-                                  status);
-       } catch (...) {}
-
-       return CERTSVC_FAIL;
-}
-
-int certsvc_base64_encode(CertSvcString message, CertSvcString *base64)
-{
-       try {
-               return impl(message.privateInstance)->base64Encode(message, base64);
-       } catch (...) {}
-
-       return CERTSVC_FAIL;
-}
-
-int certsvc_base64_decode(CertSvcString base64, CertSvcString *message)
-{
-       try {
-               return impl(base64.privateInstance)->base64Decode(base64, message);
-       } catch (...) {}
-
-       return CERTSVC_FAIL;
-}
-
-int certsvc_string_new(
-       CertSvcInstance instance,
-       const char *url,
-       size_t size,
-       CertSvcString *output)
-{
-       try {
-               return impl(instance)->stringNew(instance, url, size, output);
-       } catch (...) {}
-
-       return CERTSVC_FAIL;
-}
-
-int certsvc_string_not_managed(
-       CertSvcInstance instance,
-       const char *url,
-       size_t size,
-       CertSvcString *output)
-{
-       if (!output) {
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       output->privateHandler = const_cast<char *>(url);
-       output->privateLength = size;
-       output->privateInstance = instance;
-       return CERTSVC_SUCCESS;
-}
-
-int certsvc_certificate_verify(
-       CertSvcCertificate certificate,
-       const CertSvcCertificate *trusted,
-       size_t trustedSize,
-       const CertSvcCertificate *untrusted,
-       size_t untrustedSize,
-       int *status)
-{
-       try {
-               return impl(certificate.privateInstance)->certificateVerify(
-                                  certificate,
-                                  trusted,
-                                  trustedSize,
-                                  untrusted,
-                                  untrustedSize,
-                                  0,
-                                  status);
-       } catch (...) {}
-
-       return CERTSVC_FAIL;
-}
-
-int certsvc_certificate_verify_with_caflag(
-       CertSvcCertificate certificate,
-       const CertSvcCertificate *trusted,
-       size_t trustedSize,
-       const CertSvcCertificate *untrusted,
-       size_t untrustedSize,
-       int *status)
-{
-       try {
-               return impl(certificate.privateInstance)->certificateVerify(
-                                  certificate,
-                                  trusted,
-                                  trustedSize,
-                                  untrusted,
-                                  untrustedSize,
-                                  1,
-                                  status);
-       } catch (...) {}
-
-       return CERTSVC_FAIL;
-}
-
-int certsvc_certificate_get_visibility(CertSvcCertificate certificate,
-                                                                          CertSvcVisibility *visibility)
-{
-       try {
-               int result = impl(certificate.privateInstance)->getVisibility(certificate, visibility,
-                                        FINGERPRINT_LIST_PATH);
-
-               if (result != CERTSVC_SUCCESS) {
-                       LogDebug("Cannot find store id in FINGERPRINT_LIST_PATH. Find it in extention continue.");
-                       result = impl(certificate.privateInstance)->getVisibility(certificate, visibility,
-                                        FINGERPRINT_LIST_EXT_PATH);
-               }
-
-               return result;
-       } catch (...) {
-               LogError("exception occur");
-       }
-
-       return CERTSVC_FAIL;
-}
-
-int certsvc_get_certificate(CertSvcInstance instance,
-                                                       CertStoreType storeType,
-                                                       const char *gname,
-                                                       CertSvcCertificate *certificate)
-{
-       try {
-               size_t len = 0;
-               char *certbuf = nullptr;
-               int result = vcore_client_get_certificate_from_store(storeType, gname, &certbuf,
-                                                                                                                        &len, PEM_CRT);
-
-               if (result != CERTSVC_SUCCESS) {
-                       LogError("Failed to get certificate buffer from store.");
-                       return result;
-               }
-               std::unique_ptr<char, void(*)(void *)> certbufptr(certbuf, free);
-
-               LogInfo("certbuf: " << certbuf);
-
-               std::unique_ptr<BIO, int(*)(BIO *)> bioptr(BIO_new(BIO_s_mem()), BIO_free);
-               if (bioptr == nullptr) {
-                       LogError("Failed to allocate memory.");
-                       return CERTSVC_BAD_ALLOC;
-               }
-
-               len = BIO_write(bioptr.get(), (const void *)certbuf, (int)len);
-
-               if ((int)len < 1) {
-                       LogError("Failed to load cert into bio.");
-                       return CERTSVC_BAD_ALLOC;
-               }
-
-               std::unique_ptr<X509, void(*)(X509 *)> x509ptr(
-                               PEM_read_bio_X509_AUX(bioptr.get(), nullptr, nullptr, nullptr), X509_free);
-
-               CertificatePtr cert;
-
-               if (x509ptr != nullptr) {
-                       LogInfo("PEM_read_bio_X509_AUX returned x509 struct!");
-                       try {
-                               cert.reset(new Certificate(x509ptr.get()));
-                               LogInfo("Parse cert success with PEM(AUX) form!");
-                       } catch (...) {}
-               }
-
-               if (cert == nullptr) {
-                       x509ptr.reset(PEM_read_bio_X509(bioptr.get(), nullptr, nullptr, nullptr));
-                       if (x509ptr != nullptr) {
-                               LogInfo("PEM_read_bio_X509 returned x509 struct!");
-                               try {
-                                       cert.reset(new Certificate(x509ptr.get()));
-                                       LogInfo("Parse cert success with PEM form!");
-                               } catch (...) {}
-                       }
-               }
-
-               if (cert == nullptr) {
-                       try {
-                               cert.reset(new Certificate(certbuf, Certificate::FormType::FORM_BASE64));
-                               LogInfo("Parse cert success with Base64 form!");
-                       } catch (...) {}
-               }
-
-               if (cert == nullptr) {
-                       try {
-                               cert.reset(new Certificate(certbuf, Certificate::FormType::FORM_DER));
-                               LogInfo("Parse cert success with DER form!");
-                       } catch (...) {}
-               }
-
-               if (cert == nullptr) {
-                       LogError("Failed to parse cert on all of PEM/DER/Base64 form!");
-                       return CERTSVC_INVALID_CERTIFICATE;
-               }
-
-               certificate->privateInstance = instance;
-               certificate->privateHandler = impl(instance)->addCert(cert);
-
-               return CERTSVC_SUCCESS;
-       } catch (std::bad_alloc &) {
-               return CERTSVC_BAD_ALLOC;
-       } catch (...) {
-               return CERTSVC_FAIL;
-       }
-}
-
-int certsvc_pkcs12_check_alias_exists_in_store(CertSvcInstance instance,
-               CertStoreType storeType,
-               CertSvcString pfxIdString,
-               int *is_unique)
-{
-       if (pfxIdString.privateHandler == NULL || pfxIdString.privateLength <= 0) {
-               LogError("Invalid input parameter.");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       try {
-               if (!impl(instance)->checkValidStoreType(storeType)) {
-                       LogError("Invalid input parameter.");
-                       return CERTSVC_INVALID_STORE_TYPE;
-               }
-
-               return impl(instance)->pkcsNameIsUniqueInStore(storeType, pfxIdString, is_unique);
-       } catch (...) {}
-
-       return CERTSVC_FAIL;
-}
-
-int certsvc_pkcs12_free_certificate_list_loaded_from_store(CertSvcInstance instance,
-               CertSvcStoreCertList **certList)
-{
-       if (certList == NULL || *certList == NULL) {
-               LogError("Invalid input parameter.");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       try {
-               return impl(instance)->freePkcsIdListFromStore(certList);
-       } catch (...) {}
-
-       return CERTSVC_FAIL;
-}
-
-int certsvc_pkcs12_get_certificate_list_from_store(CertSvcInstance instance,
-               CertStoreType storeType,
-               int is_root_app,
-               CertSvcStoreCertList **certList,
-               size_t *length)
-{
-       if (certList == NULL || *certList != NULL) {
-               LogError("Invalid input parameter.");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       try {
-               if (!impl(instance)->checkValidStoreType(storeType)) {
-                       LogError("Invalid input parameter.");
-                       return CERTSVC_INVALID_STORE_TYPE;
-               }
-
-               return impl(instance)->getPkcsIdListFromStore(storeType, is_root_app, certList, length);
-       } catch (...) {}
-
-       return CERTSVC_FAIL;
-}
-
-int certsvc_pkcs12_get_end_user_certificate_list_from_store(CertSvcInstance instance,
-               CertStoreType storeType,
-               CertSvcStoreCertList **certList,
-               size_t *length)
-{
-       if (certList == NULL || *certList != NULL) {
-               LogError("Invalid input parameter.");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       try {
-               if (!impl(instance)->checkValidStoreType(storeType)) {
-                       LogError("Invalid input parameter.");
-                       return CERTSVC_INVALID_STORE_TYPE;
-               }
-
-               return impl(instance)->getPkcsIdEndUserListFromStore(storeType, certList, length);
-       } catch (...) {}
-
-       return CERTSVC_FAIL;
-}
-
-int certsvc_pkcs12_get_root_certificate_list_from_store(CertSvcInstance instance,
-               CertStoreType storeType,
-               CertSvcStoreCertList **certList,
-               size_t *length)
-{
-       if (certList == NULL || *certList != NULL) {
-               LogError("Invalid input parameter.");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       try {
-               if (!impl(instance)->checkValidStoreType(storeType)) {
-                       LogError("Invalid input parameter.");
-                       return CERTSVC_INVALID_STORE_TYPE;
-               }
-
-               return impl(instance)->getPkcsIdRootListFromStore(storeType, certList, length);
-       } catch (...) {}
-
-       return CERTSVC_FAIL;
-}
-
-int certsvc_pkcs12_get_certificate_info_from_store(CertSvcInstance instance,
-               CertStoreType storeType,
-               CertSvcString gname,
-               char **certBuffer,
-               size_t *certSize)
-{
-       if (certBuffer == NULL || *certBuffer != NULL) {
-               LogError("Invalid input parameter.");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       try {
-               if (!impl(instance)->checkValidStoreType(storeType)) {
-                       LogError("Invalid input parameter.");
-                       return CERTSVC_INVALID_STORE_TYPE;
-               }
-
-               return impl(instance)->getCertDetailFromStore(storeType, gname, certBuffer, certSize);
-       } catch (...) {}
-
-       return CERTSVC_FAIL;
-}
-
-int certsvc_pkcs12_delete_certificate_from_store(CertSvcInstance instance,
-               CertStoreType storeType,
-               CertSvcString gname)
-{
-       try {
-               if (!impl(instance)->checkValidStoreType(storeType)) {
-                       LogError("Invalid input parameter.");
-                       return CERTSVC_INVALID_STORE_TYPE;
-               }
-
-               return impl(instance)->pkcsDeleteCertFromStore(storeType, gname);
-       } catch (...) {}
-
-       return CERTSVC_FAIL;
-}
-
-int certsvc_pkcs12_import_from_file_to_store(CertSvcInstance instance,
-               CertStoreType storeType,
-               CertSvcString path,
-               CertSvcString password,
-               CertSvcString pfxIdString)
-{
-       try {
-               if (path.privateHandler == NULL || !impl(instance)->checkValidStoreType(storeType)) {
-                       LogError("Invalid input parameter.");
-                       return CERTSVC_INVALID_STORE_TYPE;
-               }
-
-               return impl(instance)->pkcsImportToStore(storeType, path, password, pfxIdString);
-       } catch (...) {
-               LogError("Exception occured from pkcsImportToStore");
-               return CERTSVC_FAIL;
-       }
-}
-
-int certsvc_pkcs12_get_alias_name_for_certificate_in_store(CertSvcInstance instance,
-               CertStoreType storeType,
-               CertSvcString gname,
-               char **alias)
-{
-       if (gname.privateHandler == NULL || gname.privateLength <= 0) {
-               LogError("Invalid input parameter.");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       try {
-               if (!impl(instance)->checkValidStoreType(storeType)) {
-                       LogError("Invalid input parameter.");
-                       return CERTSVC_INVALID_STORE_TYPE;
-               }
-
-               return impl(instance)->pkcsGetAliasNameForCertInStore(storeType, gname, alias);
-       } catch (...) {}
-
-       return CERTSVC_FAIL;
-}
-
-int certsvc_pkcs12_set_certificate_status_to_store(CertSvcInstance instance,
-               CertStoreType storeType,
-               int is_root_app,
-               CertSvcString gname,
-               CertStatus status)
-{
-       try {
-               if (!impl(instance)->checkValidStoreType(storeType)) {
-                       LogError("Invalid input parameter.");
-                       return CERTSVC_INVALID_STORE_TYPE;
-               }
-
-               return impl(instance)->pkcsSetCertStatusToStore(storeType, is_root_app, gname, status);
-       } catch (...) {}
-
-       return CERTSVC_FAIL;
-}
-
-int certsvc_pkcs12_get_certificate_status_from_store(
-       CertSvcInstance instance,
-       CertStoreType storeType,
-       CertSvcString gname,
-       CertStatus *status)
-{
-       try {
-               if (!impl(instance)->checkValidStoreType(storeType)) {
-                       LogError("Invalid input parameter.");
-                       return CERTSVC_INVALID_STORE_TYPE;
-               }
-
-               return impl(instance)->pkcsGetCertStatusFromStore(storeType, gname, status);
-       } catch (...) {}
-
-       return CERTSVC_FAIL;
-}
-
-int certsvc_pkcs12_get_certificate_from_store(CertSvcInstance instance,
-               CertStoreType storeType,
-               const char *gname,
-               CertSvcCertificate *certificate)
-{
-       try {
-               if (!impl(instance)->checkValidStoreType(storeType)) {
-                       LogError("Invalid input parameter.");
-                       return CERTSVC_INVALID_STORE_TYPE;
-               }
-
-               return impl(instance)->getCertFromStore(instance, storeType, gname, certificate);
-       } catch (...) {}
-
-       return CERTSVC_FAIL;
-}
-
-int certsvc_pkcs12_load_certificate_list_from_store(
-       CertSvcInstance instance,
-       CertStoreType storeType,
-       CertSvcString pfxIdString,
-       CertSvcCertificateList *certificateList)
-{
-       try {
-               if (!impl(instance)->checkValidStoreType(storeType)) {
-                       LogError("Invalid input parameter.");
-                       return CERTSVC_INVALID_STORE_TYPE;
-               }
-
-               return impl(instance)->getPkcsCertificateListFromStore(instance, storeType, pfxIdString,
-                               certificateList);
-       } catch (...) {}
-
-       return CERTSVC_FAIL;
-}
-
-int certsvc_pkcs12_private_key_dup_from_store(
-       CertSvcInstance instance,
-       CertStoreType storeType,
-       CertSvcString gname,
-       char **certBuffer,
-       size_t *certSize)
-{
-       try {
-               if (!impl(instance)->checkValidStoreType(storeType)) {
-                       LogError("Invalid input parameter.");
-                       return CERTSVC_INVALID_STORE_TYPE;
-               }
-
-               return impl(instance)->getPkcsPrivateKeyFromStore(storeType, gname, certBuffer, certSize);
-       } catch (...) {}
-
-       return CERTSVC_FAIL;
-}
-
-int certsvc_pkcs12_dup_evp_pkey_from_store(
-       CertSvcInstance instance,
-       CertStoreType storeType,
-       CertSvcString gname,
-       EVP_PKEY **pkey)
-{
-       char *buffer = NULL;
-       size_t size;
-       int result = certsvc_pkcs12_private_key_dup_from_store(instance, storeType, gname, &buffer, &size);
-
-       if (result != CERTSVC_SUCCESS) {
-               LogError("Error in certsvc_pkcs12_private_key_dup");
-               return result;
-       }
-
-       BIO *b = BIO_new(BIO_s_mem());
-
-       if ((int)size != BIO_write(b, buffer, size)) {
-               LogError("Error in BIO_write");
-               BIO_free_all(b);
-               certsvc_pkcs12_private_key_free(buffer);
-               return CERTSVC_FAIL;
-       }
-
-       certsvc_pkcs12_private_key_free(buffer);
-       *pkey = PEM_read_bio_PrivateKey(b, NULL, NULL, NULL);
-       BIO_free_all(b);
-
-       if (*pkey)
-               return CERTSVC_SUCCESS;
-
-       LogError("Result is null. Openssl REASON code is : " << ERR_GET_REASON(ERR_peek_last_error()));
-       return CERTSVC_FAIL;
-}
-
-int certsvc_pkcs12_has_password(
-       CertSvcInstance instance,
-       CertSvcString filepath,
-       int *has_password)
-{
-       try {
-               return impl(instance)->pkcsHasPassword(filepath, has_password);
-       } catch (...) {}
-
-       return CERTSVC_FAIL;
-}
-
-void certsvc_pkcs12_private_key_free(char *buffer)
-{
-       free(buffer);
-}
-
diff --git a/vcore/vcore/exception.cpp b/vcore/vcore/exception.cpp
deleted file mode 100644 (file)
index b52655e..0000000
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- * Copyright (c) 2011 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      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @version     1.0
- * @brief       This file is the implementation of exception system
- */
-#include <vcore/exception.h>
-
-#include <dpl/log/log.h>
-
-#include <stddef.h>
-#include <cstdio>
-
-namespace ValidationCore {
-Exception *Exception::m_lastException = NULL;
-unsigned int Exception::m_exceptionCount = 0;
-void (*Exception::m_terminateHandler)() = NULL;
-
-void LogUnhandledException(const std::string &str)
-{
-       LogDebug("" << str);
-}
-
-void LogUnhandledException(const std::string &str,
-                                                  const char *filename,
-                                                  int line,
-                                                  const char *function)
-{
-       LogError("[" << filename << ":" << line << "][" << function << "]" << str);
-}
-} // namespace ValidationCore
diff --git a/vcore/vcore/exception.h b/vcore/vcore/exception.h
deleted file mode 100644 (file)
index 0129e0a..0000000
+++ /dev/null
@@ -1,382 +0,0 @@
-/*
- * Copyright (c) 2011 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  Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
- * @version 1.0
- * @brief   Header file for base exception
- */
-#ifndef ValidationCore_EXCEPTION_H
-#define ValidationCore_EXCEPTION_H
-
-#include <string>
-#include <cstring>
-#include <cstdio>
-#include <exception>
-#include <cstdlib>
-#include <sstream>
-
-namespace ValidationCore {
-void LogUnhandledException(const std::string &str);
-void LogUnhandledException(const std::string &str,
-                                                  const char *filename,
-                                                  int line,
-                                                  const char *function);
-}
-
-namespace ValidationCore {
-class Exception {
-private:
-       static unsigned int m_exceptionCount;
-       static Exception *m_lastException;
-       static void (*m_terminateHandler)();
-
-       static void AddRef(Exception *exception)
-       {
-               if (!m_exceptionCount) {
-                       m_terminateHandler = std::set_terminate(&TerminateHandler);
-               }
-
-               ++m_exceptionCount;
-               m_lastException = exception;
-       }
-
-       static void UnRef(Exception *e)
-       {
-               if (m_lastException == e) {
-                       m_lastException = NULL;
-               }
-
-               --m_exceptionCount;
-
-               if (!m_exceptionCount) {
-                       std::set_terminate(m_terminateHandler);
-                       m_terminateHandler = NULL;
-               }
-       }
-
-       static void TerminateHandler()
-       {
-               if (m_lastException != NULL) {
-                       DisplayKnownException(*m_lastException);
-                       abort();
-               } else {
-                       DisplayUnknownException();
-                       abort();
-               }
-       }
-
-       Exception *m_reason;
-       std::string m_path;
-       std::string m_function;
-       int m_line;
-
-protected:
-       std::string m_message;
-       std::string m_className;
-
-public:
-       static std::string KnownExceptionToString(const Exception &e)
-       {
-               std::ostringstream message;
-               message <<
-                               "\033[1;5;31m\n=== Unhandled DPL exception occurred ===\033[m\n\n";
-               message << "\033[1;33mException trace:\033[m\n\n";
-               message << e.DumpToString();
-               message << "\033[1;31m\n=== Will now abort ===\033[m\n";
-               return message.str();
-       }
-
-       static std::string UnknownExceptionToString()
-       {
-               std::ostringstream message;
-               message <<
-                               "\033[1;5;31m\n=== Unhandled non-DPL exception occurred ===\033[m\n\n";
-               message << "\033[1;31m\n=== Will now abort ===\033[m\n";
-               return message.str();
-       }
-
-       static void DisplayKnownException(const Exception &e)
-       {
-               LogUnhandledException(KnownExceptionToString(e).c_str());
-       }
-
-       static void DisplayUnknownException()
-       {
-               LogUnhandledException(UnknownExceptionToString().c_str());
-       }
-
-       Exception(const Exception &other)
-       {
-               // Deep copy
-               if (other.m_reason != NULL) {
-                       m_reason = new Exception(*other.m_reason);
-               } else {
-                       m_reason = NULL;
-               }
-
-               m_message = other.m_message;
-               m_path = other.m_path;
-               m_function = other.m_function;
-               m_line = other.m_line;
-               m_className = other.m_className;
-               AddRef(this);
-       }
-
-       const Exception &operator =(const Exception &other)
-       {
-               if (this == &other) {
-                       return *this;
-               }
-
-               // Deep copy
-               if (other.m_reason != NULL) {
-                       m_reason = new Exception(*other.m_reason);
-               } else {
-                       m_reason = NULL;
-               }
-
-               m_message = other.m_message;
-               m_path = other.m_path;
-               m_function = other.m_function;
-               m_line = other.m_line;
-               m_className = other.m_className;
-               AddRef(this);
-               return *this;
-       }
-
-       Exception(const char *path,
-                         const char *function,
-                         int line,
-                         const std::string &message) :
-               m_reason(NULL),
-               m_path(path),
-               m_function(function),
-               m_line(line),
-               m_message(message)
-       {
-               AddRef(this);
-       }
-
-       Exception(const char *path,
-                         const char *function,
-                         int line,
-                         const Exception &reason,
-                         const std::string &message) :
-               m_reason(new Exception(reason)),
-               m_path(path),
-               m_function(function),
-               m_line(line),
-               m_message(message)
-       {
-               AddRef(this);
-       }
-
-       virtual ~Exception() throw()
-       {
-               if (m_reason != NULL) {
-                       delete m_reason;
-                       m_reason = NULL;
-               }
-
-               UnRef(this);
-       }
-
-       void Dump() const
-       {
-               // Show reason first
-               if (m_reason != NULL) {
-                       m_reason->Dump();
-               }
-
-               // Afterward, dump exception
-               const char *file = strchr(m_path.c_str(), '/');
-
-               if (file == NULL) {
-                       file = m_path.c_str();
-               } else {
-                       ++file;
-               }
-
-               printf("\033[0;36m[%s:%i]\033[m %s() \033[4;35m%s\033[m: %s\033[m\n",
-                          file, m_line,
-                          m_function.c_str(),
-                          m_className.c_str(),
-                          m_message.empty() ? "<EMPTY>" : m_message.c_str());
-       }
-
-       std::string DumpToString() const
-       {
-               std::string ret;
-
-               if (m_reason != NULL) {
-                       ret = m_reason->DumpToString();
-               }
-
-               const char *file = strchr(m_path.c_str(), '/');
-
-               if (file == NULL) {
-                       file = m_path.c_str();
-               } else {
-                       ++file;
-               }
-
-               char buf[1024];
-               snprintf(buf,
-                                sizeof(buf),
-                                "\033[0;36m[%s:%i]\033[m %s() \033[4;35m%s\033[m: %s\033[m\n",
-                                file,
-                                m_line,
-                                m_function.c_str(),
-                                m_className.c_str(),
-                                m_message.empty() ? "<EMPTY>" : m_message.c_str());
-               buf[sizeof(buf) - 1] = '\n';
-               ret += buf;
-               return ret;
-       }
-
-       Exception *GetReason() const
-       {
-               return m_reason;
-       }
-
-       std::string GetPath() const
-       {
-               return m_path;
-       }
-
-       std::string GetFunction() const
-       {
-               return m_function;
-       }
-
-       int GetLine() const
-       {
-               return m_line;
-       }
-
-       std::string GetMessage() const
-       {
-               return m_message;
-       }
-
-       std::string GetClassName() const
-       {
-               return m_className;
-       }
-};
-} // namespace ValidationCore
-
-#define VcoreTry try
-
-#define VcoreThrow(ClassName) \
-       throw ClassName(__FILE__, __FUNCTION__, __LINE__)
-
-#define VcoreThrowMsg(ClassName, Message)                                            \
-       do                                                                               \
-       {                                                                                \
-               std::ostringstream dplLoggingStream;                                         \
-               dplLoggingStream << Message;                                                 \
-               throw ClassName(__FILE__, __FUNCTION__, __LINE__, dplLoggingStream.str());   \
-       } while (0)
-
-#define VcoreReThrow(ClassName) \
-       throw ClassName(__FILE__, __FUNCTION__, __LINE__, _rethrown_exception)
-
-#define VcoreReThrowMsg(ClassName, Message)                                          \
-       throw ClassName(__FILE__,                                                        \
-                                       __FUNCTION__,                                                    \
-                                       __LINE__,                                                        \
-                                       _rethrown_exception,                                             \
-                                       Message)
-
-#define VcoreCatch(ClassName)                                                        \
-       catch (const ClassName &_rethrown_exception)
-
-#define VCORE_DECLARE_EXCEPTION_TYPE(BaseClass, Class)                               \
-       class Class : public BaseClass {                                                 \
-       public:                                                                          \
-               Class(const char *path,                                                      \
-                         const char *function,                                                  \
-                         int line,                                                              \
-                         const std::string & message = std::string())                           \
-                       : BaseClass(path, function, line, message) {                               \
-                       \
-                       BaseClass::m_className = #Class;                                         \
-               }                                                                            \
-               \
-               Class(const char *path,                                                      \
-                         const char *function,                                                  \
-                         int line,                                                              \
-                         const ValidationCore::Exception & reason,                              \
-                         const std::string & message = std::string())                           \
-                       : BaseClass(path, function, line, reason, message) {                       \
-                       BaseClass::m_className = #Class;                                         \
-               }                                                                            \
-       };
-
-#define VCORE_UNHANDLED_EXCEPTION_HANDLER_BEGIN try
-
-#define VCORE_UNHANDLED_EXCEPTION_HANDLER_END                                        \
-       catch (const ValidationCore::Exception &exception)                               \
-       {                                                                                \
-               std::ostringstream msg;                                                      \
-               msg << ValidationCore::Exception::KnownExceptionToString(exception);         \
-               ValidationCore::LogUnhandledException(msg.str(),                             \
-                                                                                         __FILE__,                                    \
-                                                                                         __LINE__,                                    \
-                                                                                         __FUNCTION__);                                \
-               abort();                                                                     \
-       }                                                                                \
-       catch (std::exception& e)                                                        \
-       {                                                                                \
-               std::ostringstream msg;                                                      \
-               msg << e.what();                                                             \
-               msg << "\n";                                                                 \
-               msg << ValidationCore::Exception::UnknownExceptionToString();                \
-               ValidationCore::LogUnhandledException(msg.str(),                             \
-                                                                                         __FILE__,                                    \
-                                                                                         __LINE__,                                    \
-                                                                                         __FUNCTION__);                               \
-               abort();                                                                     \
-       }                                                                                \
-       catch (...)                                                                      \
-       {                                                                                \
-               std::ostringstream msg;                                                      \
-               msg << ValidationCore::Exception::UnknownExceptionToString();                \
-               ValidationCore::LogUnhandledException(msg.str(),                             \
-                                                                                         __FILE__,                                    \
-                                                                                         __LINE__,                                    \
-                                                                                         __FUNCTION__);                               \
-               abort();                                                                     \
-       }
-
-namespace ValidationCore {
-namespace CommonException {
-/**
- * Internal exception definitions
- *
- * These should normally not happen.
- * Usually, exception trace with internal error includes
- * important messages.
- */
-VCORE_DECLARE_EXCEPTION_TYPE(Exception, InternalError) ///< Unexpected error from
-// underlying libraries or
-// kernel
-}
-}
-
-#endif // ValidationCore_EXCEPTION_H
diff --git a/vcore/vcore/init-lib.cpp b/vcore/vcore/init-lib.cpp
deleted file mode 100644 (file)
index 4d3446b..0000000
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright (c) 2016 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        init-lib.cpp
- * @author      Kyungwook Tak (k.tak@samsung.com)
- * @version     1.0
- * @brief       init/deinit global configuration for library
- */
-
-#include <dpl/log/log.h>
-
-__attribute__((constructor))
-static void init_lib(void)
-{
-       try {
-               VcoreDPL::Log::LogSystemSingleton::Instance().SetTag("CERT_SVC");
-               VcoreDPL::Log::LogSystemSingleton::Instance().SetLogLevel(nullptr);
-       } catch (...) {
-               LogError("Failed to init lib for initialize log system");
-       }
-}
diff --git a/vcore/vcore/pkcs12.cpp b/vcore/vcore/pkcs12.cpp
deleted file mode 100644 (file)
index 5985005..0000000
+++ /dev/null
@@ -1,859 +0,0 @@
-/**
- * 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        pkcs12.cpp
- * @author      Jacek Migacz (j.migacz@samsung.com)
- * @author      Kyungwook Tak (k.tak@samsung.com)
- * @version     1.0
- * @brief       PKCS#12 container manipulation routines.
- */
-
-#include <unistd.h>
-#include <fcntl.h>
-#include <errno.h>
-#include <string.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <string>
-#include <memory>
-#include <functional>
-
-#include <openssl/err.h>
-#include <openssl/pkcs12.h>
-#include <openssl/sha.h>
-#include <openssl/x509.h>
-#include <openssl/pem.h>
-
-#include "dpl/log/log.h"
-#include "cert-svc/cerror.h"
-
-#include "vcore/Certificate.h"
-#include "vcore/Client.h"
-#include "vcore/pkcs12.h"
-
-#define SYSCALL(call) while (((call) == -1) && (errno == EINTR))
-
-namespace {
-
-static const std::string START_CERT    = "-----BEGIN CERTIFICATE-----";
-static const std::string END_CERT      = "-----END CERTIFICATE-----";
-static const std::string START_TRUSTED = "-----BEGIN TRUSTED CERTIFICATE-----";
-static const std::string END_TRUSTED   = "-----END TRUSTED CERTIFICATE-----";
-static const std::string START_KEY     = "-----BEGIN PRIVATE KEY-----";
-static const std::string END_KEY       = "-----END PRIVATE KEY-----";
-
-using ValidationCore::CertificatePtr;
-using ValidationCore::Certificate;
-
-using FileUniquePtr      = std::unique_ptr<FILE, std::function<int(FILE *)>>;
-using BioUniquePtr       = std::unique_ptr<BIO, std::function<void(BIO *)>>;
-using PKEYUniquePtr      = std::unique_ptr<EVP_PKEY, std::function<void(EVP_PKEY *)>>;
-using X509UniquePtr      = std::unique_ptr<X509, std::function<void(X509 *)>>;
-using X509StackUniquePtr = std::unique_ptr<STACK_OF(X509), std::function<void(STACK_OF(X509) *)>>;
-
-void X509_stack_free(STACK_OF(X509) *stack)
-{
-       sk_X509_free(stack);
-}
-
-inline bool hasStore(CertStoreType types, CertStoreType type)
-{
-       return (types & type) != 0;
-}
-
-inline CertStoreType nextStore(CertStoreType type)
-{
-       switch (type) {
-       case NONE_STORE:
-               return VPN_STORE;
-
-       case VPN_STORE:
-               return WIFI_STORE;
-
-       case WIFI_STORE:
-               return EMAIL_STORE;
-
-       case EMAIL_STORE:
-               return SYSTEM_STORE;
-
-       case SYSTEM_STORE:
-               return NONE_STORE;
-
-       default:
-               return NONE_STORE;
-       }
-}
-
-std::string generateGname(void)
-{
-       int generator;
-       int64_t random;
-       SHA_CTX ctx;
-       unsigned char d[SHA_DIGEST_LENGTH];
-       int result;
-       char *gname = NULL;
-       SYSCALL(generator = open("/dev/urandom", O_RDONLY));
-
-       if (generator == -1)
-               return std::string();
-
-       SYSCALL(result = read(generator, &random, sizeof(random)));
-
-       if (result == -1) {
-               SYSCALL(close(generator));
-               return std::string();
-       }
-
-       SYSCALL(result = close(generator));
-
-       if (result == -1)
-               return std::string();
-
-       SHA1_Init(&ctx);
-       SHA1_Update(&ctx, &random, sizeof(random));
-       SHA1_Final(d, &ctx);
-       result = asprintf(&gname,
-                                         "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x"
-                                         "%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
-                                         d[0], d[1], d[2], d[3], d[4], d[5], d[6], d[7], d[8], d[9],
-                                         d[10], d[11], d[12], d[13], d[14], d[15], d[16], d[17], d[18], d[19]);
-
-       if (result == -1)
-               return std::string();
-
-       std::string ret(gname);
-       free(gname);
-       return ret;
-}
-
-std::string getCommonName(CertType type, const std::string &cert)
-{
-       BioUniquePtr bio(BIO_new(BIO_s_mem()), BIO_free_all);
-
-       if (bio.get() == NULL) {
-               LogError("Failed to allocate memory.");
-               return std::string();
-       }
-
-       auto readCount = BIO_write(bio.get(), (const void *)cert.data(), (int)cert.length());
-
-       if (readCount < 1) {
-               LogError("Failed to load cert into bio.");
-               return std::string();
-       }
-
-       X509 *x509 = NULL;
-
-       switch (type) {
-       case P12_TRUSTED:
-       case P12_INTERMEDIATE:
-               x509 = PEM_read_bio_X509_AUX(bio.get(), NULL, 0, NULL);
-               break;
-
-       default:
-               x509 = PEM_read_bio_X509(bio.get(), NULL, 0, NULL);
-               break;
-       }
-
-       if (x509 == NULL) {
-               LogError("Failed to create x509 structure.");
-               return std::string();
-       }
-
-       X509UniquePtr x509Ptr(x509, X509_free);
-       const char *subject_c = X509_NAME_oneline(x509->cert_info->subject, NULL, 0);
-
-       if (subject_c == NULL) {
-               LogError("Failed to parse x509 structure");
-               return std::string();
-       }
-
-       return std::string(subject_c);
-}
-
-/*
- *  column           / common name / associated gname / prikey gname /
- *  PEM_CRT          : common name / gname            / none         /
- *  P12_END_USER     : alias       / gname            / prikey gname /
- *  P12_TRUSTED      : common name / end cert gname   / none         /
- *  P12_INTERMEDIATE : common name / end cert gname   / none         /
- */
-
-int installPKEY(CertStoreType storeType,
-                               const std::string &key,
-                               const std::string &gname)
-{
-       return vcore_client_install_certificate_to_store(
-                          storeType,
-                          gname.c_str(),
-                          NULL,
-                          NULL,
-                          NULL,
-                          key.c_str(),
-                          key.length(),
-                          P12_PKEY);
-}
-
-int installEndCert(CertStoreType storeType,
-                                  const std::string &cert,
-                                  const std::string &alias,
-                                  const std::string &gname,
-                                  const std::string &prikeyGname)
-{
-       return vcore_client_install_certificate_to_store(
-                          storeType,
-                          gname.c_str(),
-                          alias.c_str(),
-                          prikeyGname.c_str(),
-                          gname.c_str(),
-                          cert.c_str(),
-                          cert.length(),
-                          P12_END_USER);
-}
-
-int installChainCert(CertStoreType storeType,
-                                        const std::string &cert,
-                                        const std::string &gname,
-                                        const std::string &endCertGname,
-                                        CertType type)
-{
-       std::string commonName = getCommonName(type, cert);
-       return vcore_client_install_certificate_to_store(
-                          storeType,
-                          gname.c_str(),
-                          commonName.c_str(),
-                          NULL,
-                          endCertGname.c_str(),
-                          cert.c_str(),
-                          cert.length(),
-                          type);
-}
-int installCert(CertStoreType storeType,
-                               const std::string &cert,
-                               const std::string &gname)
-{
-       std::string commonName = getCommonName(PEM_CRT, cert);
-       return vcore_client_install_certificate_to_store(
-                          storeType,
-                          gname.c_str(),
-                          commonName.c_str(),
-                          NULL,
-                          NULL,
-                          cert.c_str(),
-                          cert.length(),
-                          PEM_CRT);
-}
-
-std::string readFromFile(const std::string &path)
-{
-       FILE *fp = NULL;
-
-       if ((fp = fopen(path.c_str(), "rb")) == NULL) {
-               LogError("Fail to open file for reading : " << path);
-               return std::string();
-       }
-
-       FileUniquePtr filePtr(fp, fclose);
-       fseek(fp, 0L, SEEK_END);
-       int len = ftell(fp);
-
-       if (len <= 0) {
-               LogError("Fail to get certificate length.");
-               return std::string();
-       }
-
-       rewind(fp);
-       char *content = (char *)malloc(sizeof(char) * (len + 1));
-
-       if (content == NULL) {
-               LogError("Fail to allocate memory");
-               return std::string();
-       }
-
-       memset(content, 0x00, len + 1);
-       size_t readLen = fread(content, sizeof(char), (size_t)len, fp);
-
-       if (readLen != (size_t)len) {
-               LogError("Fail to read file : " << path);
-               free(content);
-               return std::string();
-       }
-
-       content[len] = '\0';
-       std::string ret(content);
-       free(content);
-       return ret;
-}
-
-std::string parseCRT(const std::string &cert)
-{
-       size_t from = 0;
-       size_t to = 0;
-       size_t tailLen = 0;
-       from = cert.find(START_CERT);
-       to = cert.find(END_CERT);
-       tailLen = END_CERT.length();
-
-       if (from == std::string::npos || to == std::string::npos || from > to) {
-               from = cert.find(START_TRUSTED);
-               to = cert.find(END_TRUSTED);
-               tailLen = END_TRUSTED.length();
-       }
-
-       if (from == std::string::npos || to == std::string::npos || from > to)
-               return std::string();
-
-       return std::string(cert, from, to - from + tailLen);
-}
-
-#define _CERT_SVC_VERIFY_PKCS12
-int verify_cert_details(X509 *cert, STACK_OF(X509) *certv)
-{
-       int result = CERTSVC_SUCCESS;
-       char *pSubject = NULL;
-       char *pIssuerName = NULL;
-       X509_STORE_CTX *cert_ctx = NULL;
-       X509_STORE *cert_store = NULL;
-       int res = 0;
-#ifdef _CERT_SVC_VERIFY_PKCS12
-
-       if (certv == NULL) {
-               pSubject = X509_NAME_oneline(cert->cert_info->subject, NULL, 0);
-
-               if (!pSubject) {
-                       LogError("Failed to get subject name");
-                       result = CERTSVC_FAIL;
-                       goto free_memory;
-               }
-
-               pIssuerName = X509_NAME_oneline(cert->cert_info->issuer, NULL, 0);
-
-               if (!pIssuerName) {
-                       LogError("Failed to get issuer name");
-                       result = CERTSVC_FAIL;
-                       goto free_memory;
-               }
-
-               if (strcmp((const char *)pSubject, (const char *)pIssuerName) == 0) {
-                       /*self signed.. */
-                       EVP_PKEY *pKey = NULL;
-                       pKey = X509_get_pubkey(cert);
-
-                       if (!pKey) {
-                               LogError("Failed to get public key");
-                               result = CERTSVC_FAIL;
-                               goto free_memory;
-                       }
-
-                       if (X509_verify(cert, pKey) <= 0) {
-                               LogError("P12 verification failed");
-                               EVP_PKEY_free(pKey);
-                               result = CERTSVC_FAIL;
-                               goto free_memory;
-                       }
-
-                       LogDebug("P12 verification Success");
-                       EVP_PKEY_free(pKey);
-               } else {
-                       cert_store = X509_STORE_new();
-
-                       if (!cert_store) {
-                               LogError("Memory allocation failed");
-                               result = CERTSVC_FAIL;
-                               goto free_memory;
-                       }
-
-                       res = X509_STORE_load_locations(cert_store, NULL, TZ_SYS_CA_CERTS);
-
-                       if (res != 1) {
-                               LogError("P12 load certificate store failed");
-                               X509_STORE_free(cert_store);
-                               result = CERTSVC_FAIL;
-                               goto free_memory;
-                       }
-
-                       res = X509_STORE_set_default_paths(cert_store);
-
-                       if (res != 1) {
-                               LogError("P12 load certificate store path failed");
-                               X509_STORE_free(cert_store);
-                               result = CERTSVC_FAIL;
-                               goto free_memory;
-                       }
-
-                       /* initialise store and store context */
-                       cert_ctx = X509_STORE_CTX_new();
-
-                       if (cert_ctx == NULL) {
-                               LogError("Memory allocation failed");
-                               result = CERTSVC_FAIL;
-                               goto free_memory;
-                       }
-
-                       /* construct store context */
-                       if (!X509_STORE_CTX_init(cert_ctx, cert_store, cert, NULL)) {
-                               LogError("Memory allocation failed");
-                               result = CERTSVC_FAIL;
-                               goto free_memory;
-                       }
-
-#ifdef P12_VERIFICATION_NEEDED
-                       res = X509_verify_cert(cert_ctx);
-
-                       if (res != 1) {
-                               LogError("P12 verification failed");
-                               result = CERTSVC_FAIL;
-                               goto free_memory;
-                       }
-
-                       LogDebug("P12 verification Success");
-#endif
-               }
-       } else if (certv != NULL) {
-               /* Cert Chain */
-               cert_store = X509_STORE_new();
-
-               if (!cert_store) {
-                       LogError("Memory allocation failed");
-                       result = CERTSVC_FAIL;
-                       goto free_memory;
-               }
-
-               res = X509_STORE_load_locations(cert_store, NULL, TZ_SYS_CA_CERTS);
-
-               if (res != 1) {
-                       LogError("P12 load certificate store failed");
-                       result = CERTSVC_FAIL;
-                       goto free_memory;
-               }
-
-               res = X509_STORE_set_default_paths(cert_store);
-
-               if (res != 1) {
-                       LogError("P12 load certificate path failed");
-                       result = CERTSVC_FAIL;
-                       goto free_memory;
-               }
-
-               /* initialise store and store context */
-               cert_ctx = X509_STORE_CTX_new();
-
-               if (cert_ctx == NULL) {
-                       LogError("Memory allocation failed");
-                       result = CERTSVC_FAIL;
-                       goto free_memory;
-               }
-
-               /* construct store context */
-               if (!X509_STORE_CTX_init(cert_ctx, cert_store, cert, NULL)) {
-                       LogError("Memory allocation failed");
-                       result = CERTSVC_FAIL;
-                       goto free_memory;
-               }
-
-               X509_STORE_CTX_trusted_stack(cert_ctx, certv);
-#ifdef P12_VERIFICATION_NEEDED
-               res = X509_verify_cert(cert_ctx);
-
-               if (res != 1) {
-                       LogError("P12 verification failed");
-                       result = CERTSVC_FAIL;
-                       goto free_memory;
-               }
-
-               LogDebug("P12 verification Success");
-#endif
-       }
-
-#endif //_CERT_SVC_VERIFY_PKCS12
-free_memory:
-
-       if (cert_store != NULL)
-               X509_STORE_free(cert_store);
-
-       if (cert_ctx)
-               X509_STORE_CTX_free(cert_ctx);
-
-       free(pSubject);
-       free(pIssuerName);
-       return result;
-}
-
-enum class OsslType : int {
-       PKEY = 1,
-       X509,
-       X509AUX
-};
-
-std::string osslToPEM(OsslType type, void *data)
-{
-       std::vector<char> buf(4096);
-       BioUniquePtr bio(BIO_new(BIO_s_mem()), BIO_free_all);
-
-       if (bio.get() == NULL)
-               return std::string();
-
-       switch (type) {
-       case OsslType::PKEY:
-               PEM_write_bio_PrivateKey(bio.get(), static_cast<EVP_PKEY *>(data), NULL, NULL, 0, NULL, NULL);
-               break;
-
-       case OsslType::X509:
-               PEM_write_bio_X509(bio.get(), static_cast<X509 *>(data));
-               break;
-
-       case OsslType::X509AUX:
-               PEM_write_bio_X509_AUX(bio.get(), static_cast<X509 *>(data));
-               break;
-
-       default:
-               break;
-       }
-
-       int size = BIO_read(bio.get(), buf.data(), 4096);
-
-       if (size <= 0)
-               return std::string();
-
-       buf[size] = '\0';
-       return std::string(buf.data());
-}
-
-int extractPkcs12(const std::string &path,
-                                 const std::string &password,
-                                 PKEYUniquePtr &keyPtr,
-                                 X509UniquePtr &certPtr,
-                                 X509StackUniquePtr &certvPtr)
-{
-       FILE *stream = NULL;
-
-       if ((stream = fopen(path.c_str(), "rb")) == NULL) {
-               LogError("Unable to open the file for reading : " << path);
-               return CERTSVC_IO_ERROR;
-       }
-
-       PKCS12 *container = d2i_PKCS12_fp(stream, NULL);
-       fclose(stream);
-
-       if (container == NULL) {
-               LogError("Failed to parse the input file passed.");
-               return CERTSVC_FAIL;
-       }
-
-       EVP_PKEY *key = NULL;
-       X509 *cert = NULL;
-       STACK_OF(X509) *certv = NULL;
-       int result = PKCS12_parse(container, password.c_str(), &key, &cert, &certv);
-       PKCS12_free(container);
-
-       if (result != 1) {
-               unsigned long e = ERR_get_error();
-               char buf[1024];
-               ERR_error_string_n(e, buf, 1023);
-               LogError("Failed to parse the file passed. openssl err: " << buf);
-               return CERTSVC_FAIL;
-       }
-
-       keyPtr.reset(key);
-       certPtr.reset(cert);
-       certvPtr.reset(certv);
-       return CERTSVC_SUCCESS;
-}
-
-void rollbackStore(CertStoreType storeTypes, const std::string &endCertName)
-{
-       for (CertStoreType storeType = VPN_STORE; storeType < SYSTEM_STORE;
-                       storeType = nextStore(storeType)) {
-               if (!hasStore(storeTypes, storeType))
-                       continue;
-
-               char **certChainName = NULL;
-               size_t ncerts = 0;
-               int result = vcore_client_load_certificates_from_store(storeType, endCertName.c_str(),
-                                        &certChainName, &ncerts);
-
-               if (result != CERTSVC_SUCCESS) {
-                       LogError("Unable to load certificates from store. result : " << result);
-                       continue;
-               }
-
-               for (size_t i = 0; i < ncerts; i++) {
-                       if (certChainName[i] == NULL)
-                               continue;
-
-                       vcore_client_delete_certificate_from_store(storeType, certChainName[i]);
-                       free(certChainName[i]);
-               }
-
-               vcore_client_delete_certificate_from_store(storeType, endCertName.c_str());
-       }
-}
-
-int insertToStore(CertStoreType storeTypes,
-                                 const std::string &alias,
-                                 const std::string &prikeyName,
-                                 const std::string &prikeyBuffer,
-                                 const std::string &endCertName,
-                                 const std::string &endCertBuffer,
-                                 const std::vector<std::string> &certChainName,
-                                 const std::vector<std::string> &certChainBuffer)
-{
-       size_t ncerts = certChainName.size();
-
-       for (CertStoreType storeType = VPN_STORE; storeType < SYSTEM_STORE;
-                       storeType = nextStore(storeType)) {
-               if (!hasStore(storeTypes, storeType))
-                       continue;
-
-               LogDebug("Processing store type : " << storeType);
-               int result = installPKEY(storeType, prikeyBuffer, prikeyName);
-
-               if (result != CERTSVC_SUCCESS) {
-                       LogError("Failed to store the private key contents. result : " << result);
-                       return result;
-               }
-
-               result = installEndCert(storeType, endCertBuffer, alias, endCertName, prikeyName);
-
-               if (result != CERTSVC_SUCCESS) {
-                       LogError("Failed to install the end user certificate. result : " << result);
-                       return result;
-               }
-
-               for (size_t i = 0; i < ncerts; i++) {
-                       if (i == ncerts - 1)
-                               result = installChainCert(storeType, certChainBuffer[i], certChainName[i], endCertName,
-                                                                                 P12_INTERMEDIATE);
-                       else
-                               result = installChainCert(storeType, certChainBuffer[i], certChainName[i], endCertName,
-                                                                                 P12_TRUSTED);
-
-                       if (result != CERTSVC_SUCCESS) {
-                               LogError("Failed to install the ca certificates. result : " << result);
-                               return result;
-                       }
-               }
-       }
-
-       LogDebug("Success to insert extracted pkcs12 data to db");
-       return CERTSVC_SUCCESS;
-}
-
-int insertToStorePEM(CertStoreType storeTypes, const std::string &path, const std::string &gname)
-{
-       std::string content = readFromFile(path);
-
-       if (content.empty()) {
-               LogError("Failed to read the file : " << path);
-               return CERTSVC_IO_ERROR;
-       }
-
-       std::string parsed = parseCRT(content);
-
-       if (parsed.empty()) {
-               LogError("Failed to parse CRT : " << path);
-               return CERTSVC_FAIL;
-       }
-
-       for (CertStoreType storeType = VPN_STORE; storeType < SYSTEM_STORE;
-                       storeType = nextStore(storeType)) {
-               if (!hasStore(storeTypes, storeType))
-                       continue;
-
-               int result = installCert(storeType, parsed, gname);
-
-               if (result != CERTSVC_SUCCESS) {
-                       LogError("Failed to install PEM/CRT to db store : " << storeType << " result : " << result);
-                       rollbackStore(storeTypes, gname);
-                       return result;
-               }
-
-               LogDebug("Success to install PEM/CRT to db store : " << storeType);
-       }
-
-       LogDebug("Success to install PEM/CRT to db stores : " << storeTypes);
-       return CERTSVC_SUCCESS;
-}
-
-} // namespace anonymous
-
-
-int pkcs12_import_from_file_to_store(CertStoreType storeTypes,
-                                                                        const char *_path,
-                                                                        const char *_password,
-                                                                        const char *_alias)
-{
-       int result = 0;
-
-       if (_alias == NULL || _path == NULL || strlen(_path) < 4) {
-               LogError("Invalid input parameter.");
-               return CERTSVC_WRONG_ARGUMENT;
-       }
-
-       std::string path(_path);
-       std::string alias(_alias);
-       std::string password;
-
-       if (_password != NULL)
-               password = std::string(_password);
-
-       LogDebug("pkcs12_import_from_file_to_store start. path[" << path << "] password[" << password <<
-                        "] alias[" << alias << "]");
-
-       if (storeTypes & SYSTEM_STORE) {
-               LogError("User should not install any form of certificates in SYSTEM_STORE.");
-               return CERTSVC_INVALID_STORE_TYPE;
-       }
-
-       /*
-        * Installs CRT and PEM files.
-        * We will passing NULL for private_key_gname and associated_gname parameter
-        * in installFilePEM(). Which means that there is no private key involved
-        * in the certificate which we are installing and there are no other
-        * certificates related with the current certificate which is installed
-        */
-       std::string suffix = path.substr(path.length() - 4, 4);
-
-       if (strcasecmp(suffix.c_str(), ".pem") == 0 || strcasecmp(suffix.c_str(), ".crt") == 0) {
-               std::string gnamePEM = generateGname();
-               result = insertToStorePEM(storeTypes, path, gnamePEM);
-
-               if (result != CERTSVC_SUCCESS)
-                       LogError("Failed to install PEM/CRT file to store. gname : " << gnamePEM << " result : " << result);
-
-               return result;;
-       }
-
-       LogDebug("Convert ossl type to string start");
-       /* 0. extract pkcs12 data from file */
-       PKEYUniquePtr key(nullptr, EVP_PKEY_free);
-       X509UniquePtr cert(nullptr, X509_free);
-       X509StackUniquePtr certv(nullptr, X509_stack_free);
-       result = extractPkcs12(path, password, key, cert, certv);
-
-       if (result != CERTSVC_SUCCESS) {
-               LogError("Failed to extract pkcs12 file. result : " << result);
-               return result;
-       }
-
-       LogDebug("extract pkcs12 to unique ptr success");
-       result = verify_cert_details(cert.get(), certv.get());
-
-       if (result != CERTSVC_SUCCESS) {
-               LogError("Failed to verify p12 certificate. result : " << result);
-               return result;
-       }
-
-       /* 1. handling private key */
-       std::string prikeyName = generateGname();
-       std::string prikeyBuffer = osslToPEM(OsslType::PKEY, key.get());
-
-       if (prikeyName.empty() || prikeyBuffer.empty()) {
-               LogError("Failed to transform pkey to PEM. result : " << result);
-               return CERTSVC_FAIL;
-       }
-
-       LogDebug("Convert pkey to string success");
-       /* 2. handling end user certificate */
-       std::string endCertName = generateGname();
-       std::string endCertBuffer = osslToPEM(OsslType::X509, cert.get());
-
-       if (endCertName.empty() || endCertBuffer.empty()) {
-               LogError("Failed to transform x509 to PEM. result : " << result);
-               return CERTSVC_FAIL;
-       }
-
-       LogDebug("Convert end cert to string success");
-       /* 3. handling certificate chain */
-       std::vector<std::string> certChainName;
-       std::vector<std::string> certChainBuffer;
-       int ncerts = certv ? sk_X509_num(certv.get()) : 0;
-
-       for (int i = 0; i < ncerts; i++) {
-               std::string tempName = generateGname();
-               std::string tempBuffer = osslToPEM(OsslType::X509AUX, sk_X509_value(certv.get(), i));
-
-               if (tempName.empty() || tempBuffer.empty()) {
-                       LogError("Failed to transform x509 AUX to PEM");
-                       return CERTSVC_FAIL;
-               }
-
-               certChainName.push_back(std::move(tempName));
-               certChainBuffer.push_back(std::move(tempBuffer));
-       }
-
-       LogDebug("Convert cert chain to string success");
-       /* 4. insert extracted pkcs12 data to db */
-       result = insertToStore(storeTypes,
-                                                  alias,
-                                                  prikeyName,
-                                                  prikeyBuffer,
-                                                  endCertName,
-                                                  endCertBuffer,
-                                                  certChainName,
-                                                  certChainBuffer);
-
-       if (result != CERTSVC_SUCCESS)
-               rollbackStore(storeTypes, endCertName);
-
-       LogDebug("Success to import pkcs12 to store");
-       return result;
-}
-
-int pkcs12_has_password(const char *filepath, int *passworded)
-{
-       if (filepath == NULL || passworded == NULL)
-               return CERTSVC_WRONG_ARGUMENT;
-
-       FILE *stream;
-
-       if ((stream = fopen(filepath, "rb")) == NULL)
-               return CERTSVC_IO_ERROR;
-
-       PKCS12 *container = d2i_PKCS12_fp(stream, NULL);
-       fclose(stream);
-
-       if (container == NULL)
-               return CERTSVC_FAIL;
-
-       EVP_PKEY *pkey = NULL;
-       X509 *cert = NULL;
-       int result = PKCS12_parse(container, NULL, &pkey, &cert, NULL);
-       PKCS12_free(container);
-
-       if (pkey != NULL)
-               EVP_PKEY_free(pkey);
-
-       if (cert != NULL)
-               X509_free(cert);
-
-       if (result != 1) {
-               unsigned long e = ERR_get_error();
-               if (ERR_GET_REASON(e) == PKCS12_R_MAC_VERIFY_FAILURE) {
-                       LogInfo("verify failed without password. file(" << filepath << ") is password-protected.");
-                       *passworded = CERTSVC_TRUE;
-               } else {
-                       char buf[1024];
-                       ERR_error_string_n(e, buf, 1023);
-                       LogError("Error on PKCS12_pasre file(" << filepath << "): " << buf);
-                       return CERTSVC_FAIL;
-               }
-       } else {
-               *passworded = CERTSVC_FALSE;
-       }
-
-       return CERTSVC_SUCCESS;
-}
diff --git a/vcore/vcore/pkcs12.h b/vcore/vcore/pkcs12.h
deleted file mode 100644 (file)
index f98ebf8..0000000
+++ /dev/null
@@ -1,45 +0,0 @@
-/**
- * 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        pkcs12.h
- * @author      Jacek Migacz (j.migacz@samsung.com)
- * @version     1.0
- * @brief       PKCS#12 container manipulation routines.
- */
-#pragma once
-
-#include <cert-svc/ccert.h>
-
-/**
- * To import the p12/pfx/crt/pem file to specified store (WIFI_STORE/VPN_STORE/EMAIL_STORE).
- *
- * @param[in] storeType Refers to WIFI_STORE / VPN_STORE / EMAIL_STORE / ALL_STORE.
- * @param[in] path Path to file.
- * @param[in] password Password for opening the file.
- * @param[in] alias Logical name for certificate bundle identification (can't be empty).
- * @return CERTSVC_SUCCESS, CERTSVC_FAIL, CERTSVC_DUPLICATED_ALIAS, CERTSVC_IO_ERROR, CERTSVC_WRONG_ARGUMENT, CERTSVC_BAD_ALLOC.
- */
-int pkcs12_import_from_file_to_store(CertStoreType storeType, const char *path,
-                                                                        const char *password, const char *alias);
-
-/**
- * TO check if the p12/pfx file is protected by password or not.
- *
- * @param[in] filePath Where the file is located.
- * @param[out] passworded A boolean value to state if the file is protected by password or not.
- * @return CERTSVC_SUCCESS, CERTSVC_FAIL, CERTSVC_IO_ERROR, CERTSVC_WRONG_ARGUMENT.
- */
-int pkcs12_has_password(const char *filepath, int *passworded);