tizen 2.3.1 release tizen_2.3.1 submit/tizen_2.3.1/20150915.091123 tizen_2.3.1_release
authorjk7744.park <jk7744.park@samsung.com>
Tue, 8 Sep 2015 16:34:24 +0000 (01:34 +0900)
committerjk7744.park <jk7744.park@samsung.com>
Tue, 8 Sep 2015 16:34:24 +0000 (01:34 +0900)
281 files changed:
AUTHORS [new file with mode: 0644]
CMakeLists.txt [new file with mode: 0644]
LICENSE [new file with mode: 0644]
ace/CMakeLists.txt [new file with mode: 0644]
ace/DESCRIPTION [new file with mode: 0644]
ace/configuration/UnrestrictedPolicy.xml [new file with mode: 0644]
ace/configuration/WAC2.0Policy.xml [new file with mode: 0644]
ace/configuration/bondixml.xsd [new file with mode: 0644]
ace/dao/AceDAO.cpp [new file with mode: 0644]
ace/dao/AceDAOConversions.cpp [new file with mode: 0644]
ace/dao/AceDAOReadOnly.cpp [new file with mode: 0644]
ace/dao/AceDAOUtilities.cpp [new file with mode: 0644]
ace/dao/AceDatabase.cpp [new file with mode: 0644]
ace/dao/BaseAttribute.cpp [new file with mode: 0644]
ace/dao/CMakeLists.txt [new file with mode: 0644]
ace/dao/PromptModel.cpp [new file with mode: 0644]
ace/engine/Attribute.cpp [new file with mode: 0644]
ace/engine/CombinerImpl.cpp [new file with mode: 0644]
ace/engine/Condition.cpp [new file with mode: 0644]
ace/engine/ConfigurationManager.cpp [new file with mode: 0644]
ace/engine/Policy.cpp [new file with mode: 0644]
ace/engine/PolicyEnforcementPoint.cpp [new file with mode: 0644]
ace/engine/PolicyEvaluator.cpp [new file with mode: 0644]
ace/engine/PolicyInformationPoint.cpp [new file with mode: 0644]
ace/engine/Rule.cpp [new file with mode: 0644]
ace/engine/SettingsLogic.cpp [new file with mode: 0644]
ace/engine/Subject.cpp [new file with mode: 0644]
ace/engine/TreeNode.cpp [new file with mode: 0644]
ace/engine/parser.cpp [new file with mode: 0644]
ace/include/ace-dao-ro/AceDAOConversions.h [new file with mode: 0644]
ace/include/ace-dao-ro/AceDAOReadOnly.h [new file with mode: 0644]
ace/include/ace-dao-ro/AceDAOUtilities.h [new file with mode: 0644]
ace/include/ace-dao-ro/AceDatabase.h [new file with mode: 0644]
ace/include/ace-dao-ro/AppTypes.h [new file with mode: 0644]
ace/include/ace-dao-ro/BaseAttribute.h [new file with mode: 0644]
ace/include/ace-dao-ro/BasePermission.h [new file with mode: 0644]
ace/include/ace-dao-ro/IRequest.h [new file with mode: 0644]
ace/include/ace-dao-ro/PreferenceTypes.h [new file with mode: 0644]
ace/include/ace-dao-ro/PromptModel.h [new file with mode: 0644]
ace/include/ace-dao-ro/TimedVerdict.h [new file with mode: 0644]
ace/include/ace-dao-ro/ValidityTypes.h [new file with mode: 0644]
ace/include/ace-dao-ro/VerdictTypes.h [new file with mode: 0644]
ace/include/ace-dao-ro/common_dao_types.h [new file with mode: 0644]
ace/include/ace-dao-rw/AceDAO.h [new file with mode: 0644]
ace/include/ace/AbstractPolicyEnforcementPoint.h [new file with mode: 0644]
ace/include/ace/AbstractPolicyInformationPoint.h [new file with mode: 0644]
ace/include/ace/AbstractTreeElement.h [new file with mode: 0644]
ace/include/ace/AsyncVerdictResultListener.h [new file with mode: 0644]
ace/include/ace/Attribute.h [new file with mode: 0644]
ace/include/ace/Combiner.h [new file with mode: 0644]
ace/include/ace/CombinerImpl.h [new file with mode: 0644]
ace/include/ace/Condition.h [new file with mode: 0644]
ace/include/ace/ConfigurationManager.h [new file with mode: 0644]
ace/include/ace/Constants.h [new file with mode: 0644]
ace/include/ace/Effect.h [new file with mode: 0644]
ace/include/ace/PermissionTriple.h [new file with mode: 0644]
ace/include/ace/Policy.h [new file with mode: 0644]
ace/include/ace/PolicyEffect.h [new file with mode: 0644]
ace/include/ace/PolicyEnforcementPoint.h [new file with mode: 0644]
ace/include/ace/PolicyEvaluator.h [new file with mode: 0644]
ace/include/ace/PolicyEvaluatorFactory.h [new file with mode: 0644]
ace/include/ace/PolicyInformationPoint.h [new file with mode: 0644]
ace/include/ace/PolicyResult.h [new file with mode: 0644]
ace/include/ace/PolicySet.h [new file with mode: 0644]
ace/include/ace/Preference.h [new file with mode: 0644]
ace/include/ace/PromptDecision.h [new file with mode: 0644]
ace/include/ace/Request.h [new file with mode: 0644]
ace/include/ace/Rule.h [new file with mode: 0644]
ace/include/ace/SettingsLogic.h [new file with mode: 0644]
ace/include/ace/Subject.h [new file with mode: 0644]
ace/include/ace/TestTimer.h [new file with mode: 0644]
ace/include/ace/TreeNode.h [new file with mode: 0644]
ace/include/ace/UserDecision.h [new file with mode: 0644]
ace/include/ace/Verdict.h [new file with mode: 0644]
ace/include/ace/WRT_INTERFACE.h [new file with mode: 0644]
ace/include/ace/WidgetUsageModel.h [new file with mode: 0644]
ace/include/ace/acf_consts.h [new file with mode: 0644]
ace/include/ace/parser.h [new file with mode: 0644]
ace/orm/ace_db [new file with mode: 0644]
ace/orm/ace_db_definitions [new file with mode: 0644]
ace/orm/ace_db_sql_generator.h [new file with mode: 0644]
ace/orm/gen_db_md5.sh [new file with mode: 0755]
ace/orm/orm_generator_ace.h [new file with mode: 0644]
ace/orm/version_db [new file with mode: 0644]
ace_client/CMakeLists.txt [new file with mode: 0644]
ace_client/include/ace-client/ace_client.h [new file with mode: 0644]
ace_client/include/ace-client/ace_client_helper.h [new file with mode: 0644]
ace_client/include/ace-client/ace_client_types.h [new file with mode: 0644]
ace_client/include/ace_api_client.h [new file with mode: 0644]
ace_client/include/ace_popup_handler.h [new file with mode: 0644]
ace_client/src/CMakeLists.txt [new file with mode: 0644]
ace_client/src/ace_api_client.cpp [new file with mode: 0644]
ace_client/src/ace_client.cpp [new file with mode: 0644]
ace_client/src/example/CMakeLists.txt [new file with mode: 0644]
ace_client/src/example/ace-thin-client-example.cpp [new file with mode: 0644]
ace_common/CMakeLists.txt [new file with mode: 0644]
ace_common/include/ace_api_common.h [new file with mode: 0644]
ace_install/CMakeLists.txt [new file with mode: 0644]
ace_install/include/ace_api_install.h [new file with mode: 0644]
ace_install/src/CMakeLists.txt [new file with mode: 0644]
ace_install/src/ace_api_install.cpp [new file with mode: 0644]
ace_popup_validation/CMakeLists.txt [new file with mode: 0644]
ace_popup_validation/include/ace_api_popup_validation.h [new file with mode: 0644]
ace_popup_validation/src/CMakeLists.txt [new file with mode: 0644]
ace_popup_validation/src/ace_api_popup_validation.cpp [new file with mode: 0644]
ace_settings/CMakeLists.txt [new file with mode: 0644]
ace_settings/include/ace_api_settings.h [new file with mode: 0644]
ace_settings/src/CMakeLists.txt [new file with mode: 0644]
ace_settings/src/ace_api_settings.cpp [new file with mode: 0644]
build/CMakeLists.txt [new file with mode: 0644]
build/ace/CMakeLists.txt [new file with mode: 0644]
build/ace/security-dao-ro.pc.in [new file with mode: 0644]
build/ace/security-dao-rw.pc.in [new file with mode: 0644]
build/ace/security.pc.in [new file with mode: 0644]
build/ace_client/CMakeLists.txt [new file with mode: 0644]
build/ace_client/security-client.pc.in [new file with mode: 0644]
build/ace_install/CMakeLists.txt [new file with mode: 0644]
build/ace_install/security-install.pc.in [new file with mode: 0644]
build/ace_popup_validation/CMakeLists.txt [new file with mode: 0644]
build/ace_popup_validation/security-popup-validation.pc.in [new file with mode: 0644]
build/ace_settings/CMakeLists.txt [new file with mode: 0644]
build/ace_settings/security-settings.pc.in [new file with mode: 0644]
build/communication_client/CMakeLists.txt [new file with mode: 0644]
build/communication_client/security-communication-client.pc.in [new file with mode: 0644]
build/wrt-security/CMakeLists.txt [new file with mode: 0644]
build/wrt-security/security-core.pc.in [new file with mode: 0644]
build/wrt_ocsp/CMakeLists.txt [new file with mode: 0644]
build/wrt_ocsp/security-wrt-ocsp.pc.in [new file with mode: 0644]
commons/CMakeLists.txt [new file with mode: 0644]
commons/LICENSE [new file with mode: 0644]
commons/NOTICE [new file with mode: 0644]
commons/build/CMakeLists.txt [new file with mode: 0644]
commons/build/core/CMakeLists.txt [new file with mode: 0644]
commons/build/core/DESCRIPTION [new file with mode: 0644]
commons/build/core/wrt-security-commons.pc.in [new file with mode: 0644]
commons/build/db/CMakeLists.txt [new file with mode: 0644]
commons/build/db/wrt-security-commons-db.pc.in [new file with mode: 0644]
commons/build/log/CMakeLists.txt [new file with mode: 0644]
commons/build/log/wrt-security-commons-log.pc.in [new file with mode: 0644]
commons/modules/CMakeLists.txt [new file with mode: 0644]
commons/modules/core/DESCRIPTION [new file with mode: 0644]
commons/modules/core/config.cmake [new file with mode: 0644]
commons/modules/core/include/DESCRIPTION [new file with mode: 0644]
commons/modules/core/include/dpl/assert.h [new file with mode: 0644]
commons/modules/core/include/dpl/availability.h [new file with mode: 0644]
commons/modules/core/include/dpl/char_traits.h [new file with mode: 0644]
commons/modules/core/include/dpl/colors.h [new file with mode: 0644]
commons/modules/core/include/dpl/errno_string.h [new file with mode: 0644]
commons/modules/core/include/dpl/exception.h [new file with mode: 0644]
commons/modules/core/include/dpl/foreach.h [new file with mode: 0644]
commons/modules/core/include/dpl/free_deleter.h [new file with mode: 0644]
commons/modules/core/include/dpl/generic_event.h [new file with mode: 0644]
commons/modules/core/include/dpl/mutex.h [new file with mode: 0644]
commons/modules/core/include/dpl/noncopyable.h [new file with mode: 0644]
commons/modules/core/include/dpl/optional_typedefs.h [new file with mode: 0644]
commons/modules/core/include/dpl/preprocessor.h [new file with mode: 0644]
commons/modules/core/include/dpl/recursive_mutex.h [new file with mode: 0644]
commons/modules/core/include/dpl/scoped_free.h [new file with mode: 0644]
commons/modules/core/include/dpl/scoped_resource.h [new file with mode: 0644]
commons/modules/core/include/dpl/serialization.h [new file with mode: 0644]
commons/modules/core/include/dpl/single_instance.h [new file with mode: 0644]
commons/modules/core/include/dpl/singleton.h [new file with mode: 0644]
commons/modules/core/include/dpl/singleton_impl.h [new file with mode: 0644]
commons/modules/core/include/dpl/singleton_safe_impl.h [new file with mode: 0644]
commons/modules/core/include/dpl/string.h [new file with mode: 0644]
commons/modules/core/include/dpl/thread.h [new file with mode: 0644]
commons/modules/core/include/dpl/type_list.h [new file with mode: 0644]
commons/modules/core/include/dpl/waitable_event.h [new file with mode: 0644]
commons/modules/core/include/dpl/waitable_handle.h [new file with mode: 0644]
commons/modules/core/include/dpl/waitable_handle_watch_support.h [new file with mode: 0644]
commons/modules/core/include/dpl/workaround.h [new file with mode: 0644]
commons/modules/core/src/DESCRIPTION [new file with mode: 0644]
commons/modules/core/src/assert.cpp [new file with mode: 0644]
commons/modules/core/src/colors.cpp [new file with mode: 0644]
commons/modules/core/src/errno_string.cpp [new file with mode: 0644]
commons/modules/core/src/exception.cpp [new file with mode: 0644]
commons/modules/core/src/mutex.cpp [new file with mode: 0644]
commons/modules/core/src/noncopyable.cpp [new file with mode: 0644]
commons/modules/core/src/recursive_mutex.cpp [new file with mode: 0644]
commons/modules/core/src/serialization.cpp [new file with mode: 0644]
commons/modules/core/src/single_instance.cpp [new file with mode: 0644]
commons/modules/core/src/singleton.cpp [new file with mode: 0644]
commons/modules/core/src/string.cpp [new file with mode: 0644]
commons/modules/core/src/thread.cpp [new file with mode: 0644]
commons/modules/core/src/waitable_event.cpp [new file with mode: 0644]
commons/modules/core/src/waitable_handle.cpp [new file with mode: 0644]
commons/modules/core/src/waitable_handle_watch_support.cpp [new file with mode: 0644]
commons/modules/db/config.cmake [new file with mode: 0644]
commons/modules/db/include/dpl/db/naive_synchronization_object.h [new file with mode: 0644]
commons/modules/db/include/dpl/db/orm.h [new file with mode: 0644]
commons/modules/db/include/dpl/db/orm_generator.h [new file with mode: 0644]
commons/modules/db/include/dpl/db/orm_interface.h [new file with mode: 0644]
commons/modules/db/include/dpl/db/orm_macros.h [new file with mode: 0644]
commons/modules/db/include/dpl/db/sql_connection.h [new file with mode: 0644]
commons/modules/db/include/dpl/db/thread_database_support.h [new file with mode: 0644]
commons/modules/db/src/naive_synchronization_object.cpp [new file with mode: 0644]
commons/modules/db/src/orm.cpp [new file with mode: 0644]
commons/modules/db/src/sql_connection.cpp [new file with mode: 0644]
commons/modules/db/src/thread_database_support.cpp [new file with mode: 0644]
commons/modules/log/config.cmake [new file with mode: 0644]
commons/modules/log/include/dpl/log/abstract_log_provider.h [new file with mode: 0644]
commons/modules/log/include/dpl/log/dlog_log_provider.h [new file with mode: 0644]
commons/modules/log/include/dpl/log/log.h [new file with mode: 0644]
commons/modules/log/include/dpl/log/secure_log.h [new file with mode: 0644]
commons/modules/log/src/abstract_log_provider.cpp [new file with mode: 0644]
commons/modules/log/src/dlog_log_provider.cpp [new file with mode: 0644]
commons/modules/log/src/log.cpp [new file with mode: 0644]
commons/wrt-commons [new file with mode: 0644]
communication_client/include/SecurityCommunicationClient.h [new file with mode: 0644]
communication_client/src/SecurityCommunicationClient.cpp [new file with mode: 0644]
etc/CMakeLists.txt [new file with mode: 0644]
etc/schema.xsd [new file with mode: 0644]
etc/wrt_security_change_policy.sh [new file with mode: 0644]
etc/wrt_security_create_clean_db.sh [new file with mode: 0644]
mockups/AceDAOReadOnly_mock.cpp [new file with mode: 0644]
mockups/AceDAOReadOnly_mock.h [new file with mode: 0644]
mockups/PolicyInformationPoint_mock.h [new file with mode: 0644]
mockups/communication_client_mock.cpp [new file with mode: 0644]
mockups/communication_client_mock.h [new file with mode: 0644]
packaging/wrt-security.changes [new file with mode: 0644]
packaging/wrt-security.manifest [new file with mode: 0644]
packaging/wrt-security.spec [new file with mode: 0644]
socket_connection/client/SecuritySocketClient.cpp [new file with mode: 0644]
socket_connection/client/SecuritySocketClient.h [new file with mode: 0644]
socket_connection/connection/SocketConnection.cpp [new file with mode: 0644]
socket_connection/connection/SocketConnection.h [new file with mode: 0644]
socket_connection/connection/SocketStream.cpp [new file with mode: 0644]
socket_connection/connection/SocketStream.h [new file with mode: 0644]
src/CMakeLists.txt [new file with mode: 0644]
src/TODO.txt [new file with mode: 0644]
src/daemon/dbus/org.tizen.SecurityDaemon.service [new file with mode: 0644]
src/daemon/dbus/security_daemon_dbus_config.h [new file with mode: 0644]
src/daemon/dbus/security_dbus_service.cpp [new file with mode: 0644]
src/daemon/dbus/security_dbus_service.h [new file with mode: 0644]
src/daemon/security_daemon.cpp [new file with mode: 0644]
src/daemon/security_daemon.h [new file with mode: 0644]
src/daemon/sockets/api/callback_api.h [new file with mode: 0644]
src/daemon/sockets/security_daemon_socket_config.h [new file with mode: 0644]
src/daemon/sockets/security_socket_service.cpp [new file with mode: 0644]
src/daemon/sockets/security_socket_service.h [new file with mode: 0644]
src/main.cpp [new file with mode: 0644]
src/services/ace/ace_server_api.h [new file with mode: 0644]
src/services/ace/ace_service.cpp [new file with mode: 0644]
src/services/ace/dbus/ace_server_dbus_interface.cpp [new file with mode: 0644]
src/services/ace/dbus/ace_server_dbus_interface.h [new file with mode: 0644]
src/services/ace/dbus/api/ace_server_dbus_api.h [new file with mode: 0644]
src/services/ace/logic/acf_consts.h [new file with mode: 0644]
src/services/ace/logic/attribute_facade.cpp [new file with mode: 0644]
src/services/ace/logic/attribute_facade.h [new file with mode: 0644]
src/services/ace/logic/security_controller.cpp [new file with mode: 0644]
src/services/ace/logic/security_controller.h [new file with mode: 0644]
src/services/ace/logic/security_logic.cpp [new file with mode: 0644]
src/services/ace/logic/security_logic.h [new file with mode: 0644]
src/services/ace/logic/simple_roaming_agent.cpp [new file with mode: 0644]
src/services/ace/logic/simple_roaming_agent.h [new file with mode: 0755]
src/services/ace/socket/ace_service_callbacks.cpp [new file with mode: 0644]
src/services/ace/socket/ace_service_callbacks.h [new file with mode: 0644]
src/services/ace/socket/api/ace_service_callbacks_api.h [new file with mode: 0644]
src/services/caller/security_caller.cpp [new file with mode: 0644]
src/services/caller/security_caller.h [new file with mode: 0644]
src/services/ocsp/dbus/api/ocsp_server_dbus_api.h [new file with mode: 0644]
src/services/ocsp/dbus/ocsp_server_dbus_interface.cpp [new file with mode: 0644]
src/services/ocsp/dbus/ocsp_server_dbus_interface.h [new file with mode: 0644]
src/services/ocsp/ocsp_server_api.h [new file with mode: 0644]
src/services/ocsp/ocsp_service.cpp [new file with mode: 0644]
src/services/ocsp/socket/api/ocsp_service_callbacks_api.h [new file with mode: 0644]
src/services/ocsp/socket/ocsp_service_callbacks.cpp [new file with mode: 0644]
src/services/ocsp/socket/ocsp_service_callbacks.h [new file with mode: 0644]
src/services/popup/dbus/popup_response_dbus_interface.cpp [new file with mode: 0644]
src/services/popup/dbus/popup_response_dbus_interface.h [new file with mode: 0644]
src/services/popup/popup_ace_data_types.h [new file with mode: 0644]
src/services/popup/popup_response_server_api.h [new file with mode: 0644]
src/services/popup/socket/api/popup_service_callbacks_api.h [new file with mode: 0644]
src/services/popup/socket/popup_service_callbacks.cpp [new file with mode: 0644]
src/services/popup/socket/popup_service_callbacks.h [new file with mode: 0644]
systemd/wrt-security-daemon.service [new file with mode: 0644]
systemd/wrt-security-daemon.socket [new file with mode: 0644]
wrt_ocsp/CMakeLists.txt [new file with mode: 0644]
wrt_ocsp/include/wrt_ocsp_api.h [new file with mode: 0644]
wrt_ocsp/src/CMakeLists.txt [new file with mode: 0644]
wrt_ocsp/src/wrt_ocsp_api.cpp [new file with mode: 0644]

diff --git a/AUTHORS b/AUTHORS
new file mode 100644 (file)
index 0000000..a62936f
--- /dev/null
+++ b/AUTHORS
@@ -0,0 +1 @@
+Bumjin Im <bj.i@samsung.com>
diff --git a/CMakeLists.txt b/CMakeLists.txt
new file mode 100644 (file)
index 0000000..c908d8e
--- /dev/null
@@ -0,0 +1,154 @@
+# 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        CMakeLists.txt
+# @author
+# @brief
+#
+
+############################# Check minimum CMake version #####################
+
+CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
+PROJECT("wrt-security")
+
+############################# cmake packages ##################################
+
+INCLUDE(FindPkgConfig)
+
+############################# compilation defines #############################
+
+# EMPTY
+
+############################# compiler flags ##################################
+
+SET(CMAKE_C_FLAGS_PROFILING    "-O0 -g -pg")
+SET(CMAKE_CXX_FLAGS_PROFILING  "-O0 -std=c++0x -g -pg")
+SET(CMAKE_C_FLAGS_DEBUG        "-O0 -g")
+SET(CMAKE_CXX_FLAGS_DEBUG      "-O0 -std=c++0x -g")
+SET(CMAKE_C_FLAGS_RELEASE      "-O2 -g")
+SET(CMAKE_CXX_FLAGS_RELEASE    "-O2 -std=c++0x -g")
+SET(CMAKE_C_FLAGS_CCOV         "-O2 -g --coverage")
+SET(CMAKE_CXX_FLAGS_CCOV       "-O2 -std=c++0x -g --coverage")
+
+#SET(SMACK_ENABLE ON)
+
+OPTION(DPL_LOG "DPL logs status" ON)
+IF(DPL_LOG)
+    MESSAGE(STATUS "Logging enabled for DPL")
+    ADD_DEFINITIONS("-DDPL_LOGS_ENABLED")
+ELSE(DPL_LOG)
+    MESSAGE(STATUS "Logging disabled for DPL")
+ENDIF(DPL_LOG)
+
+# If supported for the target machine, emit position-independent code,suitable
+# for dynamic linking and avoiding any limit on the size of the global offset
+# table. This option makes a difference on the m68k, PowerPC and SPARC.
+# (BJ: our ARM too?)
+ADD_DEFINITIONS("-fPIC")
+
+# Set the default ELF image symbol visibility to hidden - all symbols will be
+# marked with this unless overridden within the code.
+#ADD_DEFINITIONS("-fvisibility=hidden")
+
+# Set compiler warning flags
+#ADD_DEFINITIONS("-Werror")                      # Make all warnings into errors.
+ADD_DEFINITIONS("-Wall")                        # Generate all warnings
+ADD_DEFINITIONS("-Wextra")                      # Generate even more extra warnings
+ADD_DEFINITIONS("-Wno-variadic-macros")         # Inhibit variadic macros warnings (needed for ORM)
+ADD_DEFINITIONS("-Wno-deprecated")               # No warnings about deprecated features
+ADD_DEFINITIONS("-std=c++0x")               # No warnings about deprecated features
+
+# DBUS_CONNECTION and ENABLE_PRIVACY_MANAGER should be enabled together to make
+# dbus and privacy manager code enabled 
+ADD_DEFINITIONS("-DSOCKET_CONNECTION")        #defines sockets as used IPC
+#ADD_DEFINITIONS("-DDBUS_CONNECTION")         #defines DBus as used IPC
+IF(ENABLE_PRIVACY_MANAGER EQUAL 1)
+ADD_DEFINITIONS("-DENABLE_PRIVACY_MANAGER")  #disables privacy manager from wrt-secuirty-daemon
+ENDIF()
+
+
+STRING(REGEX MATCH "([^.]*)" API_VERSION "${VERSION}")
+ADD_DEFINITIONS("-DAPI_VERSION=\"$(API_VERSION)\"")
+
+IF(SMACK_ENABLE)
+    ADD_DEFINITIONS("-DWRT_SMACK_ENABLED")
+ENDIF(SMACK_ENABLE)
+
+############################# Targets names ###################################
+
+SET(TARGET_DAEMON "wrt-security-daemon")
+SET(TARGET_ACE_DAO_RO_LIB "ace-dao-ro")
+SET(TARGET_ACE_DAO_RW_LIB "ace-dao-rw")
+SET(TARGET_ACE_LIB "ace")
+SET(TARGET_ACE_CLIENT_LIB "ace-client")
+SET(TARGET_ACE_SETTINGS_LIB "ace-settings")
+SET(TARGET_ACE_INSTALL_LIB "ace-install")
+SET(TARGET_ACE_POPUP_VALIDATION_LIB "ace-popup-validation")
+SET(TARGET_COMMUNICATION_CLIENT_LIB "communication-client")
+SET(TARGET_WRT_OCSP_LIB "wrt-ocsp")
+SET(TARGET_SEC_SRV_LIB "sec-srv")
+
+############################# Communicatin Client #############################
+
+SET(COMMUNICATION_CLIENT_DIR
+    ${PROJECT_SOURCE_DIR}/communication_client
+    )
+
+SET(COMMUNICATION_CLIENT_SRC_DIR
+    ${COMMUNICATION_CLIENT_DIR}/src
+    )
+
+SET(COMMUNICATION_CLIENT_INCLUDE_DIR
+    ${COMMUNICATION_CLIENT_DIR}/include
+    )
+
+SET(COMMUNICATION_CLIENT_SOURCES
+    ${COMMUNICATION_CLIENT_SRC_DIR}/SecurityCommunicationClient.cpp
+    ${PROJECT_SOURCE_DIR}/socket_connection/client/SecuritySocketClient.cpp
+    ${PROJECT_SOURCE_DIR}/socket_connection/connection/SocketConnection.cpp
+    ${PROJECT_SOURCE_DIR}/socket_connection/connection/SocketStream.cpp
+    )
+
+SET(COMMUNICATION_CLIENT_INCLUDES
+    ${COMMUNICATION_CLIENT_DEPS_INCLUDE_DIRS}
+    ${COMMUNICATION_CLIENT_INCLUDE_DIR}
+    ${PROJECT_SOURCE_DIR}/src/daemon/sockets
+    ${PROJECT_SOURCE_DIR}/src/daemon/dbus
+    ${PROJECT_SOURCE_DIR}/src/daemon/socket
+    ${PROJECT_SOURCE_DIR}/src/daemon/socket/api
+    ${PROJECT_SOURCE_DIR}/socket_connection/client
+    ${PROJECT_SOURCE_DIR}/socket_connection/connection
+    )
+
+############################# subdirectories ##################################
+
+ADD_SUBDIRECTORY(commons)
+ADD_SUBDIRECTORY(ace)
+ADD_SUBDIRECTORY(ace_client)
+ADD_SUBDIRECTORY(ace_common)
+ADD_SUBDIRECTORY(ace_install)
+ADD_SUBDIRECTORY(ace_settings)
+ADD_SUBDIRECTORY(ace_popup_validation)
+ADD_SUBDIRECTORY(src)
+ADD_SUBDIRECTORY(build)
+ADD_SUBDIRECTORY(etc)
+IF(ENABLE_WRT_OCSP EQUAL 1)
+ADD_SUBDIRECTORY(wrt_ocsp)
+ENDIF()
+
+####################### systemd files installation ############################
+INSTALL(FILES 
+    ${CMAKE_CURRENT_SOURCE_DIR}/systemd/wrt-security-daemon.service
+    ${CMAKE_CURRENT_SOURCE_DIR}/systemd/wrt-security-daemon.socket 
+    DESTINATION /usr/lib/systemd/system)
diff --git a/LICENSE b/LICENSE
new file mode 100644 (file)
index 0000000..247c97d
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,203 @@
+Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   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.
diff --git a/ace/CMakeLists.txt b/ace/CMakeLists.txt
new file mode 100644 (file)
index 0000000..79bc8b3
--- /dev/null
@@ -0,0 +1,183 @@
+# 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.
+#
+######################################################################
+
+IF(DEFINED DBUS_CONNECTION)
+#DB vcore
+PKG_CHECK_MODULES(ACE_DB_DEP
+    dpl-efl
+    REQUIRED)
+ENDIF()
+
+#DB ace
+ADD_CUSTOM_COMMAND(
+    OUTPUT ${CMAKE_BINARY_DIR}/ace/database_checksum_ace.h
+    COMMAND ${CMAKE_SOURCE_DIR}/ace/orm/gen_db_md5.sh
+    ARGS ${CMAKE_BINARY_DIR}/ace/database_checksum_ace.h
+         ${CMAKE_SOURCE_DIR}/ace/orm/ace_db
+    DEPENDS ${CMAKE_SOURCE_DIR}/ace/orm/ace_db
+            ${CMAKE_SOURCE_DIR}/ace/orm/gen_db_md5.sh
+    COMMENT "Generating ACE database checksum"
+    )
+ADD_CUSTOM_TARGET(ACE_DB_CHECKSUM_HEADER DEPENDS ${CMAKE_BINARY_DIR}/ace/database_checksum_ace.h)
+
+STRING(REPLACE ";" ":" DEPENDENCIES "${ACE_DB_DEP_INCLUDE_DIRS}")
+
+IF(DEFINED DBUS_CONNECTION)
+ADD_CUSTOM_COMMAND( OUTPUT .ace.db
+  COMMAND rm -f ${CMAKE_CURRENT_BINARY_DIR}/.ace.db
+  COMMAND CPATH=${DEPENDENCIES} gcc -Wall -include ${CMAKE_BINARY_DIR}/ace/database_checksum_ace.h -I${PROJECT_SOURCE_DIR}/ace/orm -E ${PROJECT_SOURCE_DIR}/ace/orm/ace_db_sql_generator.h | grep --invert-match "^#" > ${CMAKE_CURRENT_BINARY_DIR}/ace_db.sql
+  COMMAND sqlite3 ${CMAKE_CURRENT_BINARY_DIR}/.ace.db ".read ${CMAKE_CURRENT_BINARY_DIR}/ace_db.sql" || rm -f ${CMAKE_CURRENT_BINARY_DIR}/.ace.db
+  DEPENDS ACE_DB_CHECKSUM_HEADER ${PROJECT_SOURCE_DIR}/ace/orm/ace_db_sql_generator.h ${PROJECT_SOURCE_DIR}/ace/orm/ace_db
+  )
+ELSE()
+ADD_CUSTOM_COMMAND( OUTPUT .ace.db
+  COMMAND rm -f ${CMAKE_CURRENT_BINARY_DIR}/.ace.db
+  COMMAND CPATH=${DEPENDENCIES} gcc -Wall -include ${CMAKE_BINARY_DIR}/ace/database_checksum_ace.h -I${PROJECT_SOURCE_DIR}/commons/modules/db/include -I${PROJECT_SOURCE_DIR}/ace/orm -E ${PROJECT_SOURCE_DIR}/ace/orm/ace_db_sql_generator.h | grep --invert-match "^#" > ${CMAKE_CURRENT_BINARY_DIR}/ace_db.sql
+  COMMAND sqlite3 ${CMAKE_CURRENT_BINARY_DIR}/.ace.db ".read ${CMAKE_CURRENT_BINARY_DIR}/ace_db.sql" || rm -f ${CMAKE_CURRENT_BINARY_DIR}/.ace.db
+  DEPENDS ACE_DB_CHECKSUM_HEADER ${PROJECT_SOURCE_DIR}/ace/orm/ace_db_sql_generator.h ${PROJECT_SOURCE_DIR}/ace/orm/ace_db
+  )
+ENDIF()
+
+ADD_CUSTOM_COMMAND( OUTPUT .ace.db-journal
+  COMMAND touch
+  ARGS  ${CMAKE_CURRENT_BINARY_DIR}/.ace.db-journal
+  )
+
+ADD_CUSTOM_TARGET(Sqlite3DbACE ALL DEPENDS .ace.db .ace.db-journal)
+
+INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/ace_db.sql
+    DESTINATION share/wrt-engine/
+    )
+
+###########################################################
+
+INCLUDE(FindPkgConfig)
+
+SET(ACE_TEST_PATH "/usr/apps/org.tizen.policy")
+
+INSTALL(FILES
+    ${CMAKE_CURRENT_SOURCE_DIR}/configuration/bondixml.xsd
+    ${CMAKE_CURRENT_SOURCE_DIR}/configuration/UnrestrictedPolicy.xml
+    ${CMAKE_CURRENT_SOURCE_DIR}/configuration/WAC2.0Policy.xml
+    DESTINATION /usr/etc/ace
+    PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ GROUP_WRITE)
+
+IF(DEFINED DBUS_CONNECTION)
+SET(ACE_LIB_DEPS_BASIC
+    dpl-efl
+    dpl-db-efl
+    dpl-event-efl
+    ecore
+    appcore-efl
+    openssl
+    sqlite3
+    dlog
+    vconf
+    db-util
+    libpcrecpp
+    icu-uc
+    libxml-2.0
+    )
+ELSE()
+SET(ACE_LIB_DEPS_BASIC
+    openssl
+    sqlite3
+    dlog
+    vconf
+    icu-uc
+    libxml-2.0
+    )
+ENDIF()
+
+IF(SMACK_ENABLED)
+    LIST(APPEND ACE_LIB_DEPS_BASIC libprivilege-control)
+ENDIF(SMACK_ENABLED)
+
+PKG_CHECK_MODULES(ACE_LIB_DEPS ${ACE_LIB_DEPS_BASIC} REQUIRED)
+
+SET(WRT_ACE_DIR ${PROJECT_SOURCE_DIR}/ace)
+
+SET(ACE_SOURCES
+  ${WRT_ACE_DIR}/engine/PolicyEvaluator.cpp
+  ${WRT_ACE_DIR}/engine/PolicyInformationPoint.cpp
+  ${WRT_ACE_DIR}/engine/CombinerImpl.cpp
+  ${WRT_ACE_DIR}/engine/parser.cpp
+  ${WRT_ACE_DIR}/engine/PolicyEnforcementPoint.cpp
+  ${WRT_ACE_DIR}/engine/SettingsLogic.cpp
+  ${WRT_ACE_DIR}/engine/Attribute.cpp
+  ${WRT_ACE_DIR}/engine/Condition.cpp
+  ${WRT_ACE_DIR}/engine/Policy.cpp
+  ${WRT_ACE_DIR}/engine/Rule.cpp
+  ${WRT_ACE_DIR}/engine/Subject.cpp
+  ${WRT_ACE_DIR}/engine/TreeNode.cpp
+  ${WRT_ACE_DIR}/engine/ConfigurationManager.cpp
+)
+
+INCLUDE_DIRECTORIES(${ACE_LIB_DEPS_INCLUDE_DIRS})
+INCLUDE_DIRECTORIES(${WRT_ACE_DIR}/include)
+
+IF(NOT DEFINED DBUS_CONNECTION)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/commons/modules/log/include)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/commons/modules/core/include)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/commons/modules/db/include)
+LINK_DIRECTORIES(
+    ${PROJECT_SOURCE_DIR}/commons/build/core
+    ${PROJECT_SOURCE_DIR}/commons/build/log
+    ${PROJECT_SOURCE_DIR}/commons/build/db
+    )
+ENDIF()
+
+SET(WITH_ACE_SETTINGS_SERVER_SOURCES
+   ${WITH_ACE_SETTINGS_SERVER_NONE_SOURCES}
+   )
+
+ADD_LIBRARY(${TARGET_ACE_LIB} SHARED
+    ${ACE_SOURCES}
+    ${WITH_ACE_SETTINGS_SERVER_SOURCES}
+)
+
+SET_TARGET_PROPERTIES(${TARGET_ACE_LIB} PROPERTIES
+    SOVERSION ${API_VERSION}
+    VERSION ${VERSION})
+
+SET_TARGET_PROPERTIES(${TARGET_ACE_LIB} PROPERTIES
+    COMPILE_FLAGS -fPIC)
+
+IF(DEFINED DBUS_CONNECTION)
+TARGET_LINK_LIBRARIES(${TARGET_ACE_LIB}
+    ${TARGET_ACE_DAO_RW_LIB}
+    ${ACE_LIB_DEPS_LIBRARIES}
+    )
+ELSE()
+TARGET_LINK_LIBRARIES(${TARGET_ACE_LIB}
+    ${TARGET_ACE_DAO_RW_LIB}
+    ${ACE_LIB_DEPS_LIBRARIES}
+    libwrt-security-commons
+    libwrt-security-commons-log
+    libwrt-security-commons-db
+    )
+ENDIF()
+
+INSTALL(TARGETS ${TARGET_ACE_LIB}
+    DESTINATION ${LIB_INSTALL_DIR})
+
+INSTALL(FILES
+    include/ace/WRT_INTERFACE.h
+    DESTINATION
+    include/ace
+    )
+
+add_subdirectory(dao)
diff --git a/ace/DESCRIPTION b/ace/DESCRIPTION
new file mode 100644 (file)
index 0000000..aac5ef6
--- /dev/null
@@ -0,0 +1,2 @@
+!!!options!!! stop
+ACE - Access Control Engine - security module for Device APIs
diff --git a/ace/configuration/UnrestrictedPolicy.xml b/ace/configuration/UnrestrictedPolicy.xml
new file mode 100644 (file)
index 0000000..558f2dc
--- /dev/null
@@ -0,0 +1,5 @@
+<policy-set id="Policy-1" combine="first-matching-target">
+    <policy>
+        <rule effect="permit" />
+    </policy>
+</policy-set>
diff --git a/ace/configuration/WAC2.0Policy.xml b/ace/configuration/WAC2.0Policy.xml
new file mode 100644 (file)
index 0000000..c8bd2bb
--- /dev/null
@@ -0,0 +1,175 @@
+<policy-set id="WAC-Policy" combine="first-matching-target">
+    <policy id="WAC-Policy-Trusted" description="WAC's policy for trusted domain" combine="permit-overrides">
+        <target>
+            <subject>
+                <!-- This is finger-print of certificate for WAC Test Widget (operator.root.cert.pem) --> 
+                <subject-match attr="distributor-key-root-fingerprint" func="equal">
+                    sha-1 4A:9D:7A:4B:3B:29:D4:69:0A:70:B3:80:EC:A9:44:6B:03:7C:9A:38
+                </subject-match>
+            </subject>
+            <subject>
+                <!-- This is finger-print of certificate for WAC Publish ID (wac.publisher.pem) --> 
+                <subject-match attr="author-key-root-fingerprint" func="equal">
+                    sha-1 A6:00:BC:53:AC:37:5B:6A:03:C3:7A:8A:E0:1B:87:8B:82:94:9B:C2
+                </subject-match>
+            </subject>
+            <subject>
+                <!-- This is finger-print of certificate for WAC Production (wac.root.production.pem) --> 
+                <subject-match attr="distributor-key-root-fingerprint" func="equal">
+                    sha-1 A0:59:D3:37:E8:C8:2E:7F:38:84:7D:21:A9:9E:19:A9:8E:EC:EB:E1
+                </subject-match>
+            </subject>
+            <subject>
+                <!-- This is finger-print of certificate for WAC Preproduction (wac.root.preproduction.pem) --> 
+                <subject-match attr="distributor-key-root-fingerprint" func="equal">
+                    sha-1 8D:1F:CB:31:68:11:DA:22:59:26:58:13:6C:C6:72:C9:F0:DE:84:2A
+                </subject-match>
+            </subject>
+        </target> 
+
+        <!-- access to external network -->
+        <!--
+        <rule effect="permit">
+            <condition combine="and">
+                <condition combine="or">
+                    <resource-match attr="device-cap" func="equal" match="XMLHttpRequest" />
+                    <resource-match attr="device-cap" func="equal" match="externalNetworkAccess" />
+                    <resource-match attr="device-cap" func="equal" match="messaging.send" />
+                </condition>
+                <environment-match attr="roaming" match="true" />
+            </condition>
+        </rule>
+        -->
+        <rule effect="permit" />
+    </policy>
+
+    <policy id="WAC-Policy-Untrusted" description="WAC's policy for untrusted domain" combine="deny-overrides">
+        <!-- Specific Untrusted Policy for WAC -->
+        <!-- access to accelerometer -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="accelerometer" />
+            </condition>
+        </rule>
+
+        <!-- access to calendar -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="pim.calendar.read" />
+                <resource-match attr="device-cap" func="equal" match="pim.calendar.write" />
+            </condition>
+        </rule>
+
+        <!-- access to camera -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="camera.show" />
+            </condition>
+        </rule>
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="camera.capture" />
+            </condition>
+        </rule>
+
+        <!-- access to contact -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="pim.contact.read" />
+                <resource-match attr="device-cap" func="equal" match="pim.contact.write" />
+            </condition>
+        </rule>
+
+        <!-- access to device-interaction -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="deviceinteraction" />
+            </condition>
+        </rule>
+
+        <!-- access to device-status -->
+        <rule effect="permit">
+             <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="devicestatus.deviceinfo" />
+                <resource-match attr="device-cap" func="equal" match="devicestatus.networkinfo" />
+            </condition>
+        </rule>
+
+        <!-- access to filesystem -->
+        <rule effect="permit">
+            <condition combine="and">
+                <condition combine="or">
+                    <resource-match attr="device-cap" func="equal" match="filesystem.read" />
+                    <resource-match attr="device-cap" func="equal" match="filesystem.write" />
+                </condition>
+                <condition combine="or">
+                    <resource-match attr="param:location" func="equal">wgt-private</resource-match>
+                    <resource-match attr="param:location" func="equal">wgt-private-tmp</resource-match>
+                    <resource-match attr="param:location" func="equal">wgt-package</resource-match>
+                </condition>
+            </condition>
+        </rule>
+
+        <!-- access to messaging -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="messaging.find" />
+                <resource-match attr="device-cap" func="equal" match="messaging.subscribe" />
+                <resource-match attr="device-cap" func="equal" match="messaging.write" />
+            </condition>
+        </rule>
+
+        <!-- access to message send on roaming status -->
+        <!--
+        <rule effect="deny">
+            <condition combine="and">
+                <resource-match attr="device-cap" func="equal" match="messaging.send" />
+                <environment-match attr="roaming" match="true" />
+            </condition>
+        </rule>
+        -->
+
+        <!-- access to geolocation -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="geolocation" />
+            </condition>
+        </rule>
+
+        <!-- access to orientation -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="orientation" />
+            </condition>
+        </rule>
+
+        <!-- access to task -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="pim.task.read" />
+                <resource-match attr="device-cap" func="equal" match="pim.task.write" />
+            </condition>
+        </rule>
+        <!-- access to external network -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="XMLHttpRequest" />
+                <resource-match attr="device-cap" func="equal" match="externalNetworkAccess" />
+            </condition>
+        </rule>
+
+        <!-- access to external network on roaming status -->
+        <!--
+        <rule effect="permit">
+            <condition combine="and">
+                <condition combine="or">
+                    <resource-match attr="device-cap" func="equal" match="XMLHttpRequest" />
+                    <resource-match attr="device-cap" func="equal" match="externalNetworkAccess" />
+                </condition>
+                <environment-match attr="roaming" match="true" />
+            </condition>
+        </rule>
+        -->
+
+    </policy>
+</policy-set>
diff --git a/ace/configuration/bondixml.xsd b/ace/configuration/bondixml.xsd
new file mode 100644 (file)
index 0000000..d16a14d
--- /dev/null
@@ -0,0 +1,184 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
+  <xs:element name="policy-set">
+    <xs:complexType>
+      <xs:sequence>
+        <xs:element minOccurs="0" ref="target"/>
+        <xs:choice minOccurs="0" maxOccurs="unbounded">
+          <xs:element ref="policy-set"/>
+          <xs:element ref="policy"/>
+        </xs:choice>
+      </xs:sequence>
+      <xs:attributeGroup ref="policy-set.attlist"/>
+    </xs:complexType>
+  </xs:element>
+  <xs:attributeGroup name="policy-set.attlist">
+    <xs:attribute name="combine" default="deny-overrides">
+      <xs:simpleType>
+        <xs:restriction base="xs:token">
+          <xs:enumeration value="deny-overrides"/>
+          <xs:enumeration value="permit-overrides"/>
+          <xs:enumeration value="first-matching-target"/>
+        </xs:restriction>
+      </xs:simpleType>
+    </xs:attribute>
+    <xs:attribute name="id"/>
+  </xs:attributeGroup>
+  <xs:element name="policy">
+    <xs:complexType>
+      <xs:sequence>
+        <xs:element minOccurs="0" ref="target"/>
+        <xs:element minOccurs="0" maxOccurs="unbounded" ref="rule"/>
+      </xs:sequence>
+      <xs:attributeGroup ref="policy.attlist"/>
+    </xs:complexType>
+  </xs:element>
+  <xs:attributeGroup name="policy.attlist">
+    <xs:attribute name="combine" default="deny-overrides">
+      <xs:simpleType>
+        <xs:restriction base="xs:token">
+          <xs:enumeration value="deny-overrides"/>
+          <xs:enumeration value="permit-overrides"/>
+          <xs:enumeration value="first-applicable"/>
+        </xs:restriction>
+      </xs:simpleType>
+    </xs:attribute>
+    <xs:attribute name="description"/>
+    <xs:attribute name="id"/>
+  </xs:attributeGroup>
+  <xs:element name="rule">
+    <xs:complexType>
+      <xs:sequence>
+        <xs:element minOccurs="0" ref="condition"/>
+      </xs:sequence>
+      <xs:attributeGroup ref="rule.attlist"/>
+    </xs:complexType>
+  </xs:element>
+  <xs:attributeGroup name="rule.attlist">
+    <xs:attribute name="effect" default="permit">
+      <xs:simpleType>
+        <xs:restriction base="xs:token">
+          <xs:enumeration value="permit"/>
+          <xs:enumeration value="prompt-blanket"/>
+          <xs:enumeration value="prompt-session"/>
+          <xs:enumeration value="prompt-oneshot"/>
+          <xs:enumeration value="deny"/>
+        </xs:restriction>
+      </xs:simpleType>
+    </xs:attribute>
+  </xs:attributeGroup>
+  <xs:element name="target">
+    <xs:complexType>
+      <xs:sequence>
+        <xs:element maxOccurs="unbounded" ref="subject"/>
+      </xs:sequence>
+    </xs:complexType>
+  </xs:element>
+  <xs:element name="subject">
+    <xs:complexType>
+      <xs:sequence>
+        <xs:element maxOccurs="unbounded" ref="subject-match"/>
+      </xs:sequence>
+    </xs:complexType>
+  </xs:element>
+  <xs:element name="condition">
+    <xs:complexType>
+      <xs:choice maxOccurs="unbounded">
+        <xs:element ref="condition"/>
+        <xs:element ref="subject-match"/>
+        <xs:element ref="resource-match"/>
+        <xs:element ref="environment-match"/>
+      </xs:choice>
+      <xs:attributeGroup ref="condition.attlist"/>
+    </xs:complexType>
+  </xs:element>
+  <xs:attributeGroup name="condition.attlist">
+    <xs:attribute name="combine" default="and">
+      <xs:simpleType>
+        <xs:restriction base="xs:token">
+          <xs:enumeration value="and"/>
+          <xs:enumeration value="or"/>
+        </xs:restriction>
+      </xs:simpleType>
+    </xs:attribute>
+  </xs:attributeGroup>
+  <xs:attributeGroup name="match-attrs">
+    <xs:attribute name="attr" use="required"/>
+    <xs:attribute name="match"/>
+    <xs:attribute name="func" default="glob">
+      <xs:simpleType>
+        <xs:restriction base="xs:token">
+          <xs:enumeration value="equal"/>
+          <xs:enumeration value="glob"/>
+          <xs:enumeration value="regexp"/>
+        </xs:restriction>
+      </xs:simpleType>
+    </xs:attribute>
+  </xs:attributeGroup>
+  <xs:element name="subject-match">
+    <xs:complexType mixed="true">
+      <xs:attributeGroup ref="subject-match.attlist"/>
+    </xs:complexType>
+  </xs:element>
+  <xs:attributeGroup name="subject-match.attlist">
+    <xs:attributeGroup ref="match-attrs"/>
+  </xs:attributeGroup>
+  <xs:complexType name="match-model" mixed="true">
+    <xs:choice minOccurs="0" maxOccurs="unbounded">
+      <xs:element ref="subject-attr"/>
+      <xs:element ref="resource-attr"/>
+      <xs:element ref="environment-attr"/>
+    </xs:choice>
+  </xs:complexType>
+  <xs:element name="resource-match">
+    <xs:complexType>
+      <xs:complexContent>
+        <xs:extension base="match-model">
+          <xs:attributeGroup ref="resource-match.attlist"/>
+        </xs:extension>
+      </xs:complexContent>
+    </xs:complexType>
+  </xs:element>
+  <xs:attributeGroup name="resource-match.attlist">
+    <xs:attributeGroup ref="match-attrs"/>
+  </xs:attributeGroup>
+  <xs:element name="environment-match">
+    <xs:complexType>
+      <xs:complexContent>
+        <xs:extension base="match-model">
+          <xs:attributeGroup ref="environment-match.attlist"/>
+        </xs:extension>
+      </xs:complexContent>
+    </xs:complexType>
+  </xs:element>
+  <xs:attributeGroup name="environment-match.attlist">
+    <xs:attributeGroup ref="match-attrs"/>
+  </xs:attributeGroup>
+  <xs:attributeGroup name="attr-attrs">
+    <xs:attribute name="attr" use="required"/>
+  </xs:attributeGroup>
+  <xs:element name="subject-attr">
+    <xs:complexType>
+      <xs:attributeGroup ref="subject-attr.attlist"/>
+    </xs:complexType>
+  </xs:element>
+  <xs:attributeGroup name="subject-attr.attlist">
+    <xs:attributeGroup ref="attr-attrs"/>
+  </xs:attributeGroup>
+  <xs:element name="resource-attr">
+    <xs:complexType>
+      <xs:attributeGroup ref="resource-attr.attlist"/>
+    </xs:complexType>
+  </xs:element>
+  <xs:attributeGroup name="resource-attr.attlist">
+    <xs:attributeGroup ref="attr-attrs"/>
+  </xs:attributeGroup>
+  <xs:element name="environment-attr">
+    <xs:complexType>
+      <xs:attributeGroup ref="environment-attr.attlist"/>
+    </xs:complexType>
+  </xs:element>
+  <xs:attributeGroup name="environment-attr.attlist">
+    <xs:attributeGroup ref="attr-attrs"/>
+  </xs:attributeGroup>
+</xs:schema>
diff --git a/ace/dao/AceDAO.cpp b/ace/dao/AceDAO.cpp
new file mode 100644 (file)
index 0000000..e7d8c6f
--- /dev/null
@@ -0,0 +1,474 @@
+/*
+ * 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       AceDAO.cpp
+ * @author     Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
+ * @version    0.1
+ * @brief
+ */
+
+#include <ace-dao-rw/AceDAO.h>
+
+#include <openssl/md5.h>
+#include <dpl/foreach.h>
+#include <dpl/string.h>
+#include <dpl/log/log.h>
+#include <dpl/db/orm.h>
+#include <ace-dao-ro/AceDAOUtilities.h>
+#include <ace-dao-ro/AceDAOConversions.h>
+#include <ace-dao-ro/AceDatabase.h>
+
+using namespace DPL::DB::ORM;
+using namespace DPL::DB::ORM::ace;
+using namespace AceDB::AceDaoUtilities;
+using namespace AceDB::AceDaoConversions;
+
+namespace {
+char const * const EMPTY_SESSION = "";
+} // namespace
+
+namespace AceDB{
+
+void AceDAO::setPromptDecision(
+    WidgetHandle widgetHandle,
+    int ruleId,
+    const boost::optional<DPL::String> &session,
+    PromptDecision decision)
+{
+    Try {
+        ScopedTransaction transaction(&AceDaoUtilities::m_databaseInterface);
+
+        ACE_DB_DELETE(del, AcePromptDecision, &AceDaoUtilities::m_databaseInterface);
+        del->Where(
+            And(
+                Equals<AcePromptDecision::app_id>(widgetHandle),
+                Equals<AcePromptDecision::rule_id>(ruleId)));
+        del->Execute();
+
+        AcePromptDecision::Row row;
+        row.Set_rule_id(ruleId);
+        row.Set_decision(promptDecisionToInt(decision));
+        row.Set_app_id(widgetHandle);
+        row.Set_session(session);
+        ACE_DB_INSERT(insert, AcePromptDecision, &AceDaoUtilities::m_databaseInterface);
+        insert->Values(row);
+        insert->Execute();
+
+        transaction.Commit();
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to setUserSetting");
+    }
+}
+
+void AceDAO::removePolicyResult(
+        const BaseAttributeSet &attributes)
+{
+    Try {
+        ScopedTransaction transaction(&AceDaoUtilities::m_databaseInterface);
+
+        auto attrHash =  convertToHash(attributes);
+
+        ACE_DB_DELETE(del,
+                      AcePolicyResult,
+                      &AceDaoUtilities::m_databaseInterface);
+        del->Where(Equals<AcePolicyResult::hash>(attrHash));
+        del->Execute();
+        transaction.Commit();
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to removeVerdict");
+    }
+}
+
+void AceDAO::clearAllSettings(void)
+{
+    clearWidgetDevCapSettings();
+    clearDevCapSettings();
+}
+
+void AceDAO::setDevCapSetting(const std::string &resource,
+                              PreferenceTypes preference)
+{
+    Try {
+        ACE_DB_UPDATE(update, AceDevCap, &AceDaoUtilities::m_databaseInterface);
+        AceDevCap::Row row;
+        row.Set_general_setting(preferenceToInt(preference));
+        update->Values(row);
+        update->Where(
+            Equals<AceDevCap::id_uri>(DPL::FromUTF8String(resource)));
+        update->Execute();
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to SetResourceSetting");
+    }
+}
+
+void AceDAO::removeDevCapSetting(const std::string &resource)
+{
+    Try {
+        ACE_DB_UPDATE(update, AceDevCap, &AceDaoUtilities::m_databaseInterface);
+        AceDevCap::Row row;
+        row.Set_general_setting(preferenceToInt(PreferenceTypes::PREFERENCE_DEFAULT));
+        update->Values(row);
+        update->Where(
+            Equals<AceDevCap::id_uri>(DPL::FromUTF8String(resource)));
+        update->Execute();
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to removeResourceSetting");
+    }
+}
+
+
+void AceDAO::setWidgetDevCapSetting(const std::string &resource,
+                                    WidgetHandle handler,
+                                    PreferenceTypes preference)
+{
+    Try {
+        ScopedTransaction transaction(&AceDaoUtilities::m_databaseInterface);
+        // TODO JOIN
+        AceDevCap::Row rrow;
+        if (!getResourceByUri(resource, rrow)) {
+            ThrowMsg(Exception::DatabaseError, "Resource not found");
+        }
+
+        ACE_DB_INSERT(insert,
+                      AceWidgetDevCapSetting,
+                      &AceDaoUtilities::m_databaseInterface);
+
+        AceWidgetDevCapSetting::Row row;
+        row.Set_app_id(handler);
+        int rid = rrow.Get_resource_id();
+        row.Set_resource_id(rid);
+        row.Set_access_value(preferenceToInt(preference));
+        insert->Values(row);
+        insert->Execute();
+
+        transaction.Commit();
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to setUserSetting");
+    }
+}
+
+void AceDAO::removeWidgetDevCapSetting(const std::string &resource,
+                                       WidgetHandle handler)
+{
+    Try {
+        ScopedTransaction transaction(&AceDaoUtilities::m_databaseInterface);
+        AceDevCap::Row rrow;
+        if (!getResourceByUri(resource, rrow)) {
+            ThrowMsg(Exception::DatabaseError, "resource not found");
+        }
+
+        ACE_DB_DELETE(del,
+                      AceWidgetDevCapSetting,
+                      &AceDaoUtilities::m_databaseInterface);
+
+        Equals<AceWidgetDevCapSetting::app_id> e1(handler);
+        Equals<AceWidgetDevCapSetting::resource_id> e2(rrow.Get_resource_id());
+        del->Where(And(e1, e2));
+        del->Execute();
+        transaction.Commit();
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to clearUserSettings");
+    }
+}
+
+
+void AceDAO::setPolicyResult(const BaseAttributeSet &attributes,
+                             const ExtendedPolicyResult &exResult)
+{
+    Try {
+        ScopedTransaction transaction(&AceDaoUtilities::m_databaseInterface);
+
+        // TODO: this call is connected with logic.
+        // It should be moved to PolicyEvaluator
+        addAttributes(attributes);
+
+        auto attrHash = convertToHash(attributes);
+
+        ACE_DB_DELETE(del, AcePolicyResult, &AceDaoUtilities::m_databaseInterface)
+        del->Where(Equals<AcePolicyResult::hash>(attrHash));
+        del->Execute();
+
+        ACE_DB_INSERT(insert, AcePolicyResult, &AceDaoUtilities::m_databaseInterface);
+        AcePolicyResult::Row row;
+        row.Set_decision(PolicyResult::serialize(exResult.policyResult));
+        row.Set_hash(attrHash);
+        row.Set_rule_id(exResult.ruleId);
+        insert->Values(row);
+        insert->Execute();
+
+        transaction.Commit();
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to addVerdict");
+    }
+}
+
+void AceDAO::resetDatabase(void)
+{
+    Try {
+        ScopedTransaction transaction(&AceDaoUtilities::m_databaseInterface);
+        ACE_DB_DELETE(del1, AcePolicyResult, &AceDaoUtilities::m_databaseInterface);
+        del1->Execute();
+        ACE_DB_DELETE(del2, AceWidgetDevCapSetting, &AceDaoUtilities::m_databaseInterface);
+        del2->Execute();
+        ACE_DB_DELETE(del3, AceDevCap, &AceDaoUtilities::m_databaseInterface);
+        del3->Execute();
+        ACE_DB_DELETE(del4, AceSubject, &AceDaoUtilities::m_databaseInterface);
+        del4->Execute();
+        ACE_DB_DELETE(del5, AceAttribute, &AceDaoUtilities::m_databaseInterface);
+        del5->Execute();
+        ACE_DB_DELETE(del6, AcePromptDecision, &AceDaoUtilities::m_databaseInterface);
+        del6->Execute();
+
+        transaction.Commit();
+
+        // TODO there is no such query yet in ORM.
+        //        GlobalConnection::DataCommandAutoPtr command =
+        //                GlobalConnectionSingleton::Instance().PrepareDataCommand(
+        //                        "VACUUM");
+        //        command->Step();
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to resetDatabase");
+    }
+}
+
+void AceDAO::clearPolicyCache(void)
+{
+    Try {
+        ScopedTransaction transaction(&AceDaoUtilities::m_databaseInterface);
+        ACE_DB_DELETE(del1, AcePolicyResult, &AceDaoUtilities::m_databaseInterface);
+        del1->Execute();
+        ACE_DB_DELETE(del2, AceAttribute, &AceDaoUtilities::m_databaseInterface);
+        del2->Execute();
+        ACE_DB_DELETE(del3, AcePromptDecision, &AceDaoUtilities::m_databaseInterface);
+        del3->Execute();
+
+        transaction.Commit();
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to clearPolicyCache");
+    }
+}
+
+void AceDAO::clearDevCapSettings()
+{
+    Try {
+        ACE_DB_UPDATE(update, AceDevCap, &AceDaoUtilities::m_databaseInterface);
+        AceDevCap::Row row;
+        row.Set_general_setting(-1);
+        update->Values(row);
+        update->Execute();
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to clearResourceSettings");
+    }
+}
+
+void AceDAO::clearWidgetDevCapSettings()
+{
+    Try {
+        ACE_DB_DELETE(del, AceWidgetDevCapSetting, &AceDaoUtilities::m_databaseInterface);
+        del->Execute();
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to clearUserSettings");
+    }
+}
+
+int AceDAO::addResource(const std::string &request)
+{
+    LogDebug("addResource: " << request);
+    Try {
+        ScopedTransaction transaction(&AceDaoUtilities::m_databaseInterface);
+        AceDevCap::Row rrow;
+        if (getResourceByUri(request, rrow)) {
+            transaction.Commit();
+            return rrow.Get_resource_id();
+        }
+
+        ACE_DB_INSERT(insert, AceDevCap, &AceDaoUtilities::m_databaseInterface);
+        AceDevCap::Row row;
+        row.Set_id_uri(DPL::FromUTF8String(request));
+        row.Set_general_setting(-1);
+        insert->Values(row);
+        int id = insert->Execute();
+        transaction.Commit();
+        return id;
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed in addResource");
+    }
+}
+
+void AceDAO::addAttributes(const BaseAttributeSet &attributes)
+{
+    Try {
+        BaseAttributeSet::const_iterator iter;
+
+        for (iter = attributes.begin(); iter != attributes.end(); ++iter) {
+            ACE_DB_SELECT(select, AceAttribute, &AceDaoUtilities::m_databaseInterface);
+            select->Where(Equals<AceAttribute::name>(DPL::FromUTF8String(
+                *(*iter)->getName())));
+            std::list<AceAttribute::Row> rows = select->GetRowList();
+            if (!rows.empty()) {
+                continue;
+            }
+
+            ACE_DB_INSERT(insert, AceAttribute, &AceDaoUtilities::m_databaseInterface);
+            AceAttribute::Row row;
+            row.Set_name(DPL::FromUTF8String(*(*iter)->getName()));
+            row.Set_type(attributeTypeToInt((*iter)->getType()));
+            insert->Values(row);
+            insert->Execute();
+        }
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed in addAttributes");
+    }
+}
+
+void AceDAO::setRequestedDevCaps(
+    WidgetHandle widgetHandle,
+    const RequestedDevCapsMap &permissions)
+{
+    Try {
+        FOREACH(it, permissions) {
+          ACE_DB_INSERT(insert, AceRequestedDevCaps,
+                        &AceDaoUtilities::m_databaseInterface);
+          AceRequestedDevCaps::Row row;
+          row.Set_app_id(widgetHandle);
+          row.Set_dev_cap(it->first);
+          row.Set_grant_smack(it->second ? 1 : 0);
+          insert->Values(row);
+          insert->Execute();
+        }
+    } Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed in setStaticDevCapPermissions");
+    }
+}
+
+void AceDAO::removeRequestedDevCaps(
+    WidgetHandle widgetHandle)
+{
+    Try {
+        ACE_DB_DELETE(del, AceRequestedDevCaps,
+                      &AceDaoUtilities::m_databaseInterface);
+        del->Where(Equals<AceRequestedDevCaps::app_id>(widgetHandle));
+        del->Execute();
+    } Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed in removeRequestedDevCaps");
+    }
+}
+
+void AceDAO::setAcceptedFeature(
+    WidgetHandle widgetHandle,
+    const FeatureNameVector &vector)
+{
+    Try {
+        ScopedTransaction transaction(&AceDaoUtilities::m_databaseInterface);
+        FOREACH(it, vector) {
+            ACE_DB_INSERT(insert, AceAcceptedFeature,
+                          &AceDaoUtilities::m_databaseInterface);
+            AceAcceptedFeature::Row row;
+            row.Set_app_id(widgetHandle);
+            row.Set_feature(*it);
+            insert->Values(row);
+            insert->Execute();
+        }
+        transaction.Commit();
+    } Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed in setAcceptedFeature");
+    }
+}
+
+void AceDAO::removeAcceptedFeature(
+    WidgetHandle widgetHandle)
+{
+    Try
+    {
+        ACE_DB_DELETE(del, AceAcceptedFeature,
+                      &AceDaoUtilities::m_databaseInterface);
+        del->Where(Equals<AceAcceptedFeature::app_id>(widgetHandle));
+        del->Execute();
+    } Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed in removeAcceptedFeature");
+    }
+}
+
+void AceDAO::registerWidgetInfo(WidgetHandle handle,
+                                const WidgetRegisterInfo& info,
+                                const WidgetCertificateDataList& dataList)
+{
+    Try
+    {
+        ScopedTransaction transaction(&AceDaoUtilities::m_databaseInterface);
+
+        ACE_DB_INSERT(insert, WidgetInfo, &AceDaoUtilities::m_databaseInterface);
+        WidgetInfo::Row wi;
+        wi.Set_app_id(handle);
+        wi.Set_widget_type(static_cast<int>(info.type));
+        wi.Set_widget_id(info.widget_id);
+        wi.Set_widget_version(info.version);
+        wi.Set_author_name(info.authorName);
+        wi.Set_share_href(info.shareHref);
+        insert->Values(wi);
+        insert->Execute();
+
+        WidgetCertificateDataList::const_iterator it;
+        for (it = dataList.begin(); it != dataList.end(); ++it)
+        {
+            WidgetCertificateFingerprint::Row wcf;
+            wcf.Set_app_id(handle);
+            wcf.Set_owner(it->owner);
+            wcf.Set_chainid(it->chainId);
+            wcf.Set_type(it->type);
+            wcf.Set_md5_fingerprint(DPL::FromUTF8String(it->strMD5Fingerprint));
+            wcf.Set_sha1_fingerprint(DPL::FromUTF8String(it->strSHA1Fingerprint));
+            wcf.Set_common_name(it->strCommonName);
+            ACE_DB_INSERT(insert, WidgetCertificateFingerprint, &AceDaoUtilities::m_databaseInterface);
+            insert->Values(wcf);
+            insert->Execute();
+        }
+        transaction.Commit();
+    } Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed in registerWidgetInfo");
+    }
+}
+
+void AceDAO::unregisterWidgetInfo(WidgetHandle handle)
+{
+    if(AceDAO::isWidgetInstalled(handle)) {
+        Try
+        {
+            ACE_DB_DELETE(del, WidgetInfo, &AceDaoUtilities::m_databaseInterface);
+            del->Where(Equals<WidgetInfo::app_id>(handle));
+            del->Execute();
+        } Catch(DPL::DB::SqlConnection::Exception::Base) {
+            ReThrowMsg(Exception::DatabaseError, "Failed in unregisterWidgetInfo");
+        }
+    }
+}
+
+}
diff --git a/ace/dao/AceDAOConversions.cpp b/ace/dao/AceDAOConversions.cpp
new file mode 100644 (file)
index 0000000..d4ccf8e
--- /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       AceDaoConversions.h
+ * @author     Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
+ * @author     Grzegorz Krawczyk (g.krawczyk@samsung.com)
+ * @version    0.1
+ * @brief
+ */
+
+#include <openssl/md5.h>
+#include <dpl/foreach.h>
+
+#include <ace-dao-ro/AceDAOConversions.h>
+
+namespace AceDB {
+
+DPL::String AceDaoConversions::convertToHash(const BaseAttributeSet &attributes)
+{
+    unsigned char attrHash[MD5_DIGEST_LENGTH];
+    std::string attrString;
+    FOREACH(it, attributes) {
+        // [CR] implementation of it->toString() is not secure, 24.03.2010
+        attrString.append((*it)->toString());
+    }
+
+    MD5((unsigned char *) attrString.c_str(), attrString.length(), attrHash);
+
+    char attrHashCoded[MD5_DIGEST_LENGTH*2 + 1];
+    for (int i = 0; i < MD5_DIGEST_LENGTH; ++i) {
+        snprintf(&attrHashCoded[i << 1], 3,
+                "%02X",
+                static_cast<int>(attrHash[i]));
+    }
+    return DPL::FromASCIIString(attrHashCoded);
+}
+
+
+}
diff --git a/ace/dao/AceDAOReadOnly.cpp b/ace/dao/AceDAOReadOnly.cpp
new file mode 100644 (file)
index 0000000..09795b7
--- /dev/null
@@ -0,0 +1,570 @@
+/*
+ * 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       AceDAOReadOnlyReadOnly.cpp
+ * @author     Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
+ * @author     Grzegorz Krawczyk (g.krawczyk@samsung.com)
+ * @version    0.1
+ * @brief
+ */
+
+#include <list>
+#include <utility>
+#include <dpl/optional_typedefs.h>
+#include <ace-dao-ro/AceDAOReadOnly.h>
+#include <ace-dao-ro/AceDAOUtilities.h>
+#include <ace-dao-ro/AceDAOConversions.h>
+#include <ace-dao-ro/AceDatabase.h>
+#include <dpl/foreach.h>
+
+using namespace DPL::DB::ORM;
+using namespace DPL::DB::ORM::ace;
+using namespace AceDB::AceDaoUtilities;
+using namespace AceDB::AceDaoConversions;
+
+namespace AceDB {
+
+static const int DB_ALLOW_ALWAYS = 0;
+static const int DB_ALLOW_FOR_SESSION = 1;
+static const int DB_ALLOW_THIS_TIME = 2;
+static const int DB_DENY_ALWAYS = 3;
+static const int DB_DENY_FOR_SESSION = 4;
+static const int DB_DENY_THIS_TIME = 5;
+
+static const int DB_APP_UNKNOWN = 0;
+static const int DB_APP_WAC20 = 1;
+static const int DB_APP_TIZEN = 2;
+
+int AceDAOReadOnly::promptDecisionToInt(PromptDecision decision)
+{
+    if (PromptDecision::ALLOW_ALWAYS == decision) {
+        return DB_ALLOW_ALWAYS;
+    } else if (PromptDecision::DENY_ALWAYS == decision) {
+        return DB_DENY_ALWAYS;
+    } else if (PromptDecision::ALLOW_THIS_TIME == decision) {
+        return DB_ALLOW_THIS_TIME;
+    } else if (PromptDecision::DENY_THIS_TIME == decision) {
+        return DB_DENY_THIS_TIME;
+    } else if (PromptDecision::ALLOW_FOR_SESSION == decision) {
+        return DB_ALLOW_FOR_SESSION;
+    }
+    // DENY_FOR_SESSION
+    return DB_DENY_FOR_SESSION;
+}
+
+PromptDecision AceDAOReadOnly::intToPromptDecision(int dec) {
+    if (dec == DB_ALLOW_ALWAYS) {
+        return PromptDecision::ALLOW_ALWAYS;
+    } else if (dec == DB_DENY_ALWAYS) {
+        return PromptDecision::DENY_ALWAYS;
+    } else if (dec == DB_ALLOW_THIS_TIME) {
+        return PromptDecision::ALLOW_THIS_TIME;
+    } else if (dec == DB_DENY_THIS_TIME) {
+        return PromptDecision::DENY_THIS_TIME;
+    } else if (dec == DB_ALLOW_FOR_SESSION) {
+        return PromptDecision::ALLOW_FOR_SESSION;
+    }
+    // DB_DENY_FOR_SESSION
+    return PromptDecision::DENY_FOR_SESSION;
+}
+
+int AceDAOReadOnly::appTypeToInt(AppTypes app_type)
+{
+    switch (app_type) {
+    case AppTypes::Unknown:
+        return DB_APP_UNKNOWN;
+    case AppTypes::WAC20:
+        return DB_APP_WAC20;
+    case AppTypes::Tizen:
+        return DB_APP_TIZEN;
+    default:
+        return DB_APP_UNKNOWN;
+    }
+
+}
+
+AppTypes AceDAOReadOnly::intToAppType(int app_type)
+{
+    switch (app_type) {
+    case DB_APP_UNKNOWN:
+        return AppTypes::Unknown;
+    case DB_APP_WAC20:
+        return AppTypes::WAC20;
+    case DB_APP_TIZEN:
+        return AppTypes::Tizen;
+    default:
+        return AppTypes::Unknown;
+    }
+}
+
+void AceDAOReadOnly::attachToThreadRO()
+{
+    AceDaoUtilities::m_databaseInterface.AttachToThread(
+        DPL::DB::SqlConnection::Flag::RO);
+}
+
+void AceDAOReadOnly::attachToThreadRW()
+{
+    AceDaoUtilities::m_databaseInterface.AttachToThread(
+        DPL::DB::SqlConnection::Flag::RW);
+}
+
+void AceDAOReadOnly::detachFromThread()
+{
+    AceDaoUtilities::m_databaseInterface.DetachFromThread();
+}
+
+OptionalCachedPromptDecision AceDAOReadOnly::getPromptDecision(
+    WidgetHandle widgetHandle,
+    int ruleId)
+{
+    Try {
+        // get matching subject verdict
+        ACE_DB_SELECT(select, AcePromptDecision, &AceDaoUtilities::m_databaseInterface);
+
+        select->Where(
+            And(
+                Equals<AcePromptDecision::rule_id>(ruleId),
+                Equals<AcePromptDecision::app_id>(widgetHandle)));
+
+        std::list<AcePromptDecision::Row> rows = select->GetRowList();
+        if (rows.empty()) {
+            return OptionalCachedPromptDecision();
+        }
+
+        AcePromptDecision::Row row = rows.front();
+        CachedPromptDecision decision;
+        decision.decision = intToPromptDecision(row.Get_decision());
+        decision.session = row.Get_session();
+
+        return OptionalCachedPromptDecision(decision);
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to getPromptDecision");
+    }
+}
+
+void AceDAOReadOnly::getAttributes(BaseAttributeSet *attributes)
+{
+    if (NULL == attributes) {
+        LogError("NULL pointer");
+        return;
+    }
+    attributes->clear();
+    std::string aname;
+    int type;
+    Try {
+        ACE_DB_SELECT(select, AceAttribute, &AceDaoUtilities::m_databaseInterface);
+        typedef std::list<AceAttribute::Row> RowList;
+        RowList list = select->GetRowList();
+
+        FOREACH(i, list) {
+            BaseAttributePtr attribute(new BaseAttribute());
+            DPL::String name = i->Get_name();
+            aname = DPL::ToUTF8String(name);
+            type = i->Get_type();
+
+            attribute->setName(&aname);
+            attribute->setType(intToAttributeType(type));
+            attributes->insert(attribute);
+        }
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to getAttributes");
+    }
+}
+
+OptionalExtendedPolicyResult AceDAOReadOnly::getPolicyResult(
+        const BaseAttributeSet &attributes)
+{
+
+    auto attrHash = convertToHash(attributes);
+    return getPolicyResult(attrHash);
+}
+
+OptionalExtendedPolicyResult AceDAOReadOnly::getPolicyResult(
+    const DPL::String &attrHash)
+{
+    Try {
+        // get matching subject verdict
+        ACE_DB_SELECT(select, AcePolicyResult, &AceDaoUtilities::m_databaseInterface);
+        Equals<AcePolicyResult::hash> e1(attrHash);
+        select->Where(e1);
+
+        std::list<AcePolicyResult::Row> rows = select->GetRowList();
+        if (rows.empty()) {
+            return OptionalExtendedPolicyResult();
+        }
+
+        AcePolicyResult::Row row = rows.front();
+        int decision = row.Get_decision();
+        ExtendedPolicyResult res;
+        res.policyResult = PolicyResult::deserialize(decision);
+        res.ruleId = row.Get_rule_id();
+        return OptionalExtendedPolicyResult(res);
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to getVerdict");
+    }
+}
+
+PreferenceTypes AceDAOReadOnly::getDevCapSetting(const std::string &resource)
+{
+    Try {
+        AceDevCap::Row row;
+        if (!getResourceByUri(resource, row)) {
+            return PreferenceTypes::PREFERENCE_DEFAULT;
+        }
+        return intToPreference(row.Get_general_setting());
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to getResourceSetting");
+    }
+}
+
+void AceDAOReadOnly::getDevCapSettings(PreferenceTypesMap *globalSettingsMap)
+{
+    if (NULL == globalSettingsMap) {
+        LogError("Null pointer");
+        return;
+    }
+    globalSettingsMap->clear();
+    Try {
+        ACE_DB_SELECT(select, AceDevCap, &AceDaoUtilities::m_databaseInterface);
+        typedef std::list<AceDevCap::Row> RowList;
+        RowList list = select->GetRowList();
+
+        FOREACH(i, list) {
+            PreferenceTypes p = intToPreference(i->Get_general_setting());
+            globalSettingsMap->insert(make_pair(DPL::ToUTF8String(
+                i->Get_id_uri()), p));
+        }
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to getResourceSettings");
+    }
+}
+
+void AceDAOReadOnly::getWidgetDevCapSettings(BasePermissionList *outputList)
+{
+    if (NULL == outputList) {
+        LogError("NULL pointer");
+        return;
+    }
+    outputList->clear();
+    Try {
+        std::string resourceName;
+        PreferenceTypes allowAccess;
+
+        ACE_DB_SELECT(select,
+                      AceWidgetDevCapSetting,
+                      &AceDaoUtilities::m_databaseInterface);
+
+        typedef std::list<AceWidgetDevCapSetting::Row> RowList;
+        RowList list = select->GetRowList();
+
+        // TODO JOIN
+        FOREACH(i, list) {
+            int app_id = i->Get_app_id();
+            int res_id = i->Get_resource_id();
+
+            ACE_DB_SELECT(resourceSelect, AceDevCap, &AceDaoUtilities::m_databaseInterface);
+            resourceSelect->Where(Equals<AceDevCap::resource_id>(res_id));
+            AceDevCap::Row rrow = resourceSelect->GetSingleRow();
+
+            resourceName = DPL::ToUTF8String(rrow.Get_id_uri());
+
+            if (!resourceName.empty()) {
+                allowAccess = intToPreference(i->Get_access_value());
+                outputList->push_back(
+                    BasePermission(app_id,
+                    resourceName,
+                    allowAccess));
+            }
+        }
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to findUserSettings");
+    }
+}
+
+PreferenceTypes AceDAOReadOnly::getWidgetDevCapSetting(
+        const std::string &resource,
+        WidgetHandle handler)
+{
+    Try {
+        AceDevCap::Row rrow;
+        if (!getResourceByUri(resource, rrow)) {
+            return PreferenceTypes::PREFERENCE_DEFAULT;
+        }
+        int resourceId = rrow.Get_resource_id();
+
+        // get matching user setting
+        ACE_DB_SELECT(select, AceWidgetDevCapSetting, &AceDaoUtilities::m_databaseInterface);
+
+        select->Where(And(Equals<AceWidgetDevCapSetting::resource_id>(resourceId),
+                Equals<AceWidgetDevCapSetting::app_id>(handler)));
+
+        std::list<int> values =
+            select->GetValueList<AceWidgetDevCapSetting::access_value>();
+        if (values.empty()) {
+            return PreferenceTypes::PREFERENCE_DEFAULT;
+        }
+        return intToPreference(values.front());
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed in getUserSetting");
+    }
+}
+
+void AceDAOReadOnly::getRequestedDevCaps(
+    WidgetHandle widgetHandle,
+    RequestedDevCapsMap *permissions)
+{
+    if (NULL == permissions) {
+        LogError("NULL pointer");
+        return;
+    }
+    permissions->clear();
+    Try {
+        ACE_DB_SELECT(select, AceRequestedDevCaps,
+                      &AceDaoUtilities::m_databaseInterface);
+        select->Where(
+            Equals<AceRequestedDevCaps::app_id>(widgetHandle));
+        std::list<AceRequestedDevCaps::Row> list = select->GetRowList();
+
+        FOREACH(i, list) {
+            permissions->insert(std::make_pair(i->Get_dev_cap(),
+                   i->Get_grant_smack() == 1));
+        }
+    } Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to getRequestedDevCaps");
+    }
+}
+
+void AceDAOReadOnly::getAcceptedFeature(
+    WidgetHandle widgetHandle,
+    FeatureNameVector *fvector)
+{
+    if (NULL == fvector) {
+        LogError("NULL pointer");
+        return;
+    }
+
+    fvector->clear();
+    Try {
+        ACE_DB_SELECT(select, AceAcceptedFeature,
+                      &AceDaoUtilities::m_databaseInterface);
+        select->Where(
+            Equals<AceAcceptedFeature::app_id>(widgetHandle));
+        std::list<AceAcceptedFeature::Row> list = select->GetRowList();
+
+        FOREACH(i, list) {
+            fvector->push_back(i->Get_feature());
+        }
+    } Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to getRequestedDevCaps");
+    }
+}
+
+AppTypes AceDAOReadOnly::getWidgetType(WidgetHandle handle)
+{
+    Try {
+        ACE_DB_SELECT(select, WidgetInfo, &AceDaoUtilities::m_databaseInterface);
+        select->Where(Equals<WidgetInfo::app_id>(handle));
+        WidgetInfo::Select::RowList rows = select->GetRowList();
+        DPL::OptionalInt res;
+        if (!rows.empty()) {
+            res = rows.front().Get_widget_type();
+            AppTypes retType = (!res ? AppTypes::Unknown : static_cast<AppTypes>(*res));
+            return retType;
+        } else {
+            LogDebug("Can not find widget type");
+            return AppTypes::Unknown;
+        }
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to getWidgetType");
+    }
+}
+
+std::string AceDAOReadOnly::getVersion(WidgetHandle widgetHandle)
+{
+    Try
+    {
+        ACE_DB_SELECT(select, WidgetInfo, &AceDaoUtilities::m_databaseInterface);
+        select->Where(Equals<WidgetInfo::app_id>(widgetHandle));
+        WidgetInfo::Select::RowList rows = select->GetRowList();
+        DPL::OptionalString res;
+        if(!rows.empty()) {
+            res = rows.front().Get_widget_version();
+            return (!res ? "" : DPL::ToUTF8String(*res));
+        } else {
+            LogDebug("Widget not installed");
+            return "";
+        }
+    } Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to getVersion");
+    }
+}
+
+std::string AceDAOReadOnly::getAuthorName(WidgetHandle widgetHandle)
+{
+    Try
+    {
+        ACE_DB_SELECT(select, WidgetInfo, &AceDaoUtilities::m_databaseInterface);
+        select->Where(Equals<WidgetInfo::app_id>(widgetHandle));
+        WidgetInfo::Select::RowList rows = select->GetRowList();
+        DPL::OptionalString res;
+        if(!rows.empty()) {
+            res = rows.front().Get_author_name();
+            return (!res ? "" : DPL::ToUTF8String(*res));
+        } else {
+            LogDebug("Widget not installed");
+            return "";
+        }
+    } Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to getAuthorName");
+    }
+}
+
+std::string AceDAOReadOnly::getGUID(WidgetHandle widgetHandle)
+{
+    Try
+    {
+        ACE_DB_SELECT(select, WidgetInfo, &AceDaoUtilities::m_databaseInterface);
+        select->Where(Equals<WidgetInfo::app_id>(widgetHandle));
+        WidgetInfo::Select::RowList rows = select->GetRowList();
+        DPL::OptionalString res;
+        if(!rows.empty()) {
+            res = rows.front().Get_widget_id();
+            return (!res ? "" : DPL::ToUTF8String(*res));
+        } else {
+            LogDebug("Widget not installed");
+            return "";
+        }
+    } Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to getGUID");
+    }
+}
+
+WidgetCertificateCNList AceDAOReadOnly::getKeyCommonNameList(
+        WidgetHandle widgetHandle,
+        WidgetCertificateData::Owner owner,
+        WidgetCertificateData::Type type)
+{
+    Try {
+        ACE_DB_SELECT(select, WidgetCertificateFingerprint, &AceDaoUtilities::m_databaseInterface);
+        select->Where(And(And(
+            Equals<WidgetCertificateFingerprint::app_id>(widgetHandle),
+            Equals<WidgetCertificateFingerprint::owner>(owner)),
+            Equals<WidgetCertificateFingerprint::type>(type)));
+        WidgetCertificateFingerprint::Select::RowList rows = select->GetRowList();
+
+        WidgetCertificateCNList out;
+        FOREACH(it, rows)
+        {
+            DPL::OptionalString cn = it->Get_common_name();
+            out.push_back(!cn ? "" : DPL::ToUTF8String(*cn));
+        }
+        return out;
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to getKeyCommonNameList");
+    }
+}
+
+FingerPrintList AceDAOReadOnly::getKeyFingerprints(
+        WidgetHandle widgetHandle,
+        WidgetCertificateData::Owner owner,
+        WidgetCertificateData::Type type)
+{
+    Try
+    {
+        ACE_DB_SELECT(select, WidgetCertificateFingerprint, &AceDaoUtilities::m_databaseInterface);
+        select->Where(And(And(
+            Equals<WidgetCertificateFingerprint::app_id>(widgetHandle),
+            Equals<WidgetCertificateFingerprint::owner>(owner)),
+            Equals<WidgetCertificateFingerprint::type>(type)));
+        WidgetCertificateFingerprint::Select::RowList rows = select->GetRowList();
+
+        FingerPrintList keys;
+        FOREACH(it, rows)
+        {
+            DPL::OptionalString sha1 = it->Get_sha1_fingerprint();
+            if (!!sha1)
+                keys.push_back(DPL::ToUTF8String(*sha1));
+            DPL::OptionalString md5 = it->Get_md5_fingerprint();
+            if (!!md5)
+                keys.push_back(DPL::ToUTF8String(*md5));
+        }
+        return keys;
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to getKeyFingerprints");
+    }
+}
+
+std::string AceDAOReadOnly::getShareHref(WidgetHandle widgetHandle)
+{
+    Try
+    {
+        ACE_DB_SELECT(select, WidgetInfo, &AceDaoUtilities::m_databaseInterface);
+        select->Where(Equals<WidgetInfo::app_id>(widgetHandle));
+        WidgetInfo::Select::RowList rows = select->GetRowList();
+
+        if(rows.empty())
+            ThrowMsg(Exception::DatabaseError, "Cannot find widget. Handle: " << widgetHandle);
+
+        DPL::OptionalString value = rows.front().Get_share_href();
+        std::string ret = "";
+        if(!!value)
+            ret = DPL::ToUTF8String(*value);
+        return ret;
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to getShareHref");
+    }
+}
+
+WidgetHandleList AceDAOReadOnly::getHandleList()
+{
+    LogDebug("Getting DbWidgetHandle List");
+    Try
+    {
+        ACE_DB_SELECT(select, WidgetInfo, &AceDaoUtilities::m_databaseInterface);
+        return select->GetValueList<WidgetInfo::app_id>();
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to list of widget handles");
+    }
+}
+
+bool AceDAOReadOnly::isWidgetInstalled(WidgetHandle handle)
+{
+    Try {
+        ACE_DB_SELECT(select, WidgetInfo, &AceDaoUtilities::m_databaseInterface);
+        select->Where(Equals<WidgetInfo::app_id>(handle));
+        WidgetInfo::Select::RowList rows = select->GetRowList();
+        return !rows.empty() ? true : false;
+    } Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed in isWidgetInstalled");
+    }
+}
+
+}
diff --git a/ace/dao/AceDAOUtilities.cpp b/ace/dao/AceDAOUtilities.cpp
new file mode 100644 (file)
index 0000000..4d5292e
--- /dev/null
@@ -0,0 +1,193 @@
+/*
+ * 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       AceDaoReadOnly.h
+ * @author     Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
+ * @author     Grzegorz Krawczyk (g.krawczyk@samsung.com)
+ * @version    0.1
+ * @brief
+ */
+
+#include <openssl/md5.h>
+#include <dpl/assert.h>
+#include <dpl/foreach.h>
+
+#include <ace-dao-ro/AceDatabase.h>
+#include <ace-dao-ro/AceDAOUtilities.h>
+#include <ace-dao-ro/AceDAOReadOnly.h>
+
+namespace AceDB {
+
+namespace {
+const char* ACE_DB_DATABASE = "/opt/dbspace/.ace.db";
+DPL::DB::SqlConnection::Flag::Type ACE_DB_FLAGS =
+    DPL::DB::SqlConnection::Flag::UseLucene;
+}
+
+DPL::DB::ThreadDatabaseSupport AceDaoUtilities::m_databaseInterface(
+        ACE_DB_DATABASE, ACE_DB_FLAGS);
+
+BaseAttribute::Type AceDaoUtilities::intToAttributeType(int val)
+{
+    switch (val) {
+    case 0:
+        return BaseAttribute::Type::Subject;
+    case 1:
+        return BaseAttribute::Type::Environment;
+    case 2:
+        return BaseAttribute::Type::Resource;
+    case 3:
+        return BaseAttribute::Type::FunctionParam;
+    case 4:
+        return BaseAttribute::Type::WidgetParam;
+
+    default:
+        Assert(0 && "Unknown Attribute type value");
+        return BaseAttribute::Type::Subject; //remove compilation warrning
+    }
+}
+
+int AceDaoUtilities::attributeTypeToInt(BaseAttribute::Type type)
+{
+    // we cannot cast enum -> int because this cast will be removed from next c++ standard
+    switch (type) {
+    case BaseAttribute::Type::Subject:
+        return 0;
+    case BaseAttribute::Type::Environment:
+        return 1;
+    case BaseAttribute::Type::Resource:
+        return 2;
+    case BaseAttribute::Type::FunctionParam:
+        return 3;
+    case BaseAttribute::Type::WidgetParam:
+        return 4;
+
+    default:
+        Assert(0 && "Unknown Attribute type!");
+        return 0; //remove compilation warrning
+    }
+}
+
+int AceDaoUtilities::preferenceToInt(PreferenceTypes p)
+{
+    switch (p) {
+        case PreferenceTypes::PREFERENCE_PERMIT:
+        return 1;
+    case PreferenceTypes::PREFERENCE_DENY:
+        return 0;
+    case PreferenceTypes::PREFERENCE_BLANKET_PROMPT:
+        return 2;
+    case PreferenceTypes::PREFERENCE_SESSION_PROMPT:
+        return 3;
+    case PreferenceTypes::PREFERENCE_ONE_SHOT_PROMPT:
+        return 4;
+
+    default:
+        return -1;
+    }
+}
+
+PreferenceTypes AceDaoUtilities::intToPreference(int p)
+{
+    switch (p) {
+    case 1:
+        return PreferenceTypes::PREFERENCE_PERMIT;
+    case 0:
+        return PreferenceTypes::PREFERENCE_DENY;
+    case 2:
+        return PreferenceTypes::PREFERENCE_BLANKET_PROMPT;
+    case 3:
+        return PreferenceTypes::PREFERENCE_SESSION_PROMPT;
+    case 4:
+        return PreferenceTypes::PREFERENCE_ONE_SHOT_PROMPT;
+
+    default:
+        return PreferenceTypes::PREFERENCE_DEFAULT;
+    }
+}
+
+VerdictTypes AceDaoUtilities::intToVerdict(int v)
+{
+    switch (v) {
+    case -1:
+        return VerdictTypes::VERDICT_UNKNOWN;
+    case 0:
+        return VerdictTypes::VERDICT_DENY;
+    case 1:
+        return VerdictTypes::VERDICT_PERMIT;
+    case 2:
+        return VerdictTypes::VERDICT_INAPPLICABLE;
+
+    default:
+        Assert(0 && "Cannot convert int to verdict");
+        return VerdictTypes::VERDICT_UNKNOWN; // remove compile warrning
+    }
+}
+
+int AceDaoUtilities::verdictToInt(VerdictTypes v)
+{
+    switch (v) {
+    case VerdictTypes::VERDICT_UNKNOWN:
+        return -1;
+    case VerdictTypes::VERDICT_DENY:
+        return 0;
+    case VerdictTypes::VERDICT_PERMIT:
+        return 1;
+    case VerdictTypes::VERDICT_INAPPLICABLE:
+        return 2;
+
+    default:
+        Assert(0 && "Unknown Verdict value");
+        return -1; // remove compile warrning
+    }
+}
+
+bool AceDaoUtilities::getSubjectByUri(const std::string &uri,
+                                      DPL::DB::ORM::ace::AceSubject::Row &row)
+{
+    using namespace DPL::DB::ORM;
+    using namespace DPL::DB::ORM::ace;
+    ACE_DB_SELECT(select, AceSubject, &m_databaseInterface);
+    select->Where(Equals<AceSubject::id_uri>(DPL::FromUTF8String(uri)));
+    std::list<AceSubject::Row> rows = select->GetRowList();
+    if (rows.empty()) {
+        return false;
+    }
+
+    row = rows.front();
+    return true;
+}
+
+bool AceDaoUtilities::getResourceByUri(const std::string &uri,
+                                       DPL::DB::ORM::ace::AceDevCap::Row &row)
+{
+    using namespace DPL::DB::ORM;
+    using namespace DPL::DB::ORM::ace;
+    ACE_DB_SELECT(select, AceDevCap, &m_databaseInterface);
+    select->Where(Equals<AceDevCap::id_uri>(DPL::FromUTF8String(uri)));
+    std::list<AceDevCap::Row> rows = select->GetRowList();
+    if (rows.empty()) {
+        return false;
+    }
+
+    row = rows.front();
+    return true;
+}
+
+
+}
diff --git a/ace/dao/AceDatabase.cpp b/ace/dao/AceDatabase.cpp
new file mode 100644 (file)
index 0000000..6c91951
--- /dev/null
@@ -0,0 +1,25 @@
+/*
+ * 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    AceDatabase.cpp
+ * @author  Lukasz Marek (l.marek@samsung.com)
+ * @version 1.0
+ * @brief   This file contains the declaration of ace database
+ */
+
+#include <ace-dao-ro/AceDatabase.h>
+
+DPL::Mutex g_aceDbQueriesMutex;
diff --git a/ace/dao/BaseAttribute.cpp b/ace/dao/BaseAttribute.cpp
new file mode 100644 (file)
index 0000000..e15785c
--- /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.
+ */
+/**
+ *
+ *
+ * @file       BaseAttribute.cpp
+ * @author     Lukasz Marek (l.marek@samsung.com)
+ * @version    0.1
+ * @brief
+ */
+
+#include <sstream>
+#include <string>
+
+#include <ace-dao-ro/BaseAttribute.h>
+
+namespace AceDB {
+
+const char* BaseAttribute::typeToString(Type type)
+{
+    const char * ret = NULL;
+    switch (type) {
+    case Type::Resource:
+        ret = "resource";
+        break;
+    case Type::Subject:
+        ret = "subject";
+        break;
+    case Type::Environment:
+        ret = "environment";
+        break;
+    default:
+        ret = "unknown type";
+        break;
+    }
+
+    return ret;
+}
+
+std::string BaseAttribute::toString() const
+{
+    std::string ret;
+    const char * SEPARATOR = ";";
+
+    ret.append(m_name);
+    ret.append(SEPARATOR);
+    ret.append(typeToString(m_typeId));
+    ret.append(SEPARATOR);
+    if (m_undetermindState) {
+        ret.append("true");
+    } else {
+        ret.append("false");
+    }
+    ret.append(SEPARATOR);
+    for (std::list<std::string>::const_iterator it = value.begin();
+         it != value.end();
+         ++it) {
+        std::stringstream num;
+        num << it->size();
+        ret.append(num.str());
+        ret.append(SEPARATOR);
+        ret.append(*it);
+        ret.append(SEPARATOR);
+    }
+
+    return ret;
+}
+
+}
diff --git a/ace/dao/CMakeLists.txt b/ace/dao/CMakeLists.txt
new file mode 100644 (file)
index 0000000..f106b3c
--- /dev/null
@@ -0,0 +1,114 @@
+
+IF(DEFINED DBUS_CONNECTION)
+SET(ACE_DAO_DEPS_LIST
+    dpl-efl
+    dpl-db-efl
+    ecore
+    appcore-efl
+    openssl
+    vconf
+    db-util
+    libpcrecpp
+    icu-uc
+    libxml-2.0
+    )
+ELSE()
+SET(ACE_DAO_DEPS_LIST
+    openssl
+    db-util
+    libpcrecpp
+    icu-uc
+    libxml-2.0
+    )
+ENDIF()
+
+PKG_CHECK_MODULES(ACE_DAO_DEPS ${ACE_DAO_DEPS_LIST} REQUIRED)
+
+set(ACE_SRC_DIR ${PROJECT_SOURCE_DIR}/ace/dao)
+
+set(ACE_DAO_RO_SOURCES
+    ${ACE_SRC_DIR}/AceDAOReadOnly.cpp
+    ${ACE_SRC_DIR}/AceDAOUtilities.cpp
+    ${ACE_SRC_DIR}/AceDAOConversions.cpp
+    ${ACE_SRC_DIR}/BaseAttribute.cpp
+    ${ACE_SRC_DIR}/AceDatabase.cpp
+    ${ACE_SRC_DIR}/PromptModel.cpp
+)
+
+set(ACE_DAO_RW_SOURCES
+    ${ACE_SRC_DIR}/AceDAO.cpp
+)
+
+INCLUDE_DIRECTORIES(${ACE_SRC_DIR})
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/ace/include)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/ace/orm)
+INCLUDE_DIRECTORIES(${ACE_DAO_DEPS_INCLUDE_DIRS})
+IF(NOT DEFINED DBUS_CONNECTION)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/commons/modules/log/include)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/commons/modules/core/include)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/commons/modules/db/include)
+LINK_DIRECTORIES(
+    ${PROJECT_SOURCE_DIR}/commons/build/core
+    ${PROJECT_SOURCE_DIR}/commons/build/db
+    ${PROJECT_SOURCE_DIR}/commons/build/log
+    )
+ENDIF()
+
+ADD_LIBRARY(${TARGET_ACE_DAO_RO_LIB} SHARED
+    ${ACE_DAO_RO_SOURCES}
+)
+
+SET_TARGET_PROPERTIES(${TARGET_ACE_DAO_RO_LIB} PROPERTIES
+    SOVERSION ${API_VERSION}
+    VERSION ${VERSION})
+
+SET_TARGET_PROPERTIES(${TARGET_ACE_DAO_RO_LIB} PROPERTIES
+    COMPILE_FLAGS -fPIC)
+
+SET_TARGET_PROPERTIES(${TARGET_ACE_DAO_RO_LIB} PROPERTIES
+    COMPILE_FLAGS "-include ${CMAKE_BINARY_DIR}/ace/database_checksum_ace.h")
+
+IF(DEFINED DBUS_CONNECTION)
+target_link_libraries(${TARGET_ACE_DAO_RO_LIB}
+    ${TARGET_DPL_EFL}
+    ${TARGET_DPL_DB_EFL}
+    ${ACE_DAO_DEPS_LIBRARY}
+    ${ACE_DAO_DEPS_LDFLAGS}
+    )
+ELSE()
+target_link_libraries(${TARGET_ACE_DAO_RO_LIB}
+    ${ACE_DAO_DEPS_LIBRARY}
+    ${ACE_DAO_DEPS_LDFLAGS}
+    libwrt-security-commons
+    libwrt-security-commons-db
+    libwrt-security-commons-log
+    )
+ENDIF()
+
+ADD_LIBRARY(${TARGET_ACE_DAO_RW_LIB} SHARED
+    ${ACE_DAO_RW_SOURCES}
+)
+SET_SOURCE_FILES_PROPERTIES(${CMAKE_BINARY_DIR}/ace/database_checksum_ace.h PROPERTIES GENERATED 1)
+ADD_DEPENDENCIES(${TARGET_ACE_DAO_RO_LIB} ACE_DB_CHECKSUM_HEADER)
+
+SET_TARGET_PROPERTIES(${TARGET_ACE_DAO_RW_LIB} PROPERTIES
+    SOVERSION ${API_VERSION}
+    VERSION ${VERSION})
+
+SET_TARGET_PROPERTIES(${TARGET_ACE_DAO_RW_LIB} PROPERTIES
+    COMPILE_FLAGS -fPIC)
+
+SET_TARGET_PROPERTIES(${TARGET_ACE_DAO_RW_LIB} PROPERTIES
+    COMPILE_FLAGS "-include ${CMAKE_BINARY_DIR}/ace/database_checksum_ace.h")
+
+target_link_libraries(${TARGET_ACE_DAO_RW_LIB}
+    ${ACE_DAO_DEPS_LIST_LIBRARIES}
+    ${TARGET_ACE_DAO_RO_LIB}
+)
+
+INSTALL(TARGETS ${TARGET_ACE_DAO_RO_LIB}
+    DESTINATION ${LIB_INSTALL_DIR})
+
+INSTALL(TARGETS ${TARGET_ACE_DAO_RW_LIB}
+    DESTINATION ${LIB_INSTALL_DIR})
+
diff --git a/ace/dao/PromptModel.cpp b/ace/dao/PromptModel.cpp
new file mode 100644 (file)
index 0000000..ee2a133
--- /dev/null
@@ -0,0 +1,178 @@
+/*
+ * 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        PromptModel.cpp
+ * @author      Justyna Mejzner (j.kwiatkowsk@samsung.com)
+ * @author      Jaroslaw Osmanski (j.osmanski@samsung.com)
+ * @version     1.0
+ *
+ */
+
+#include <ace-dao-ro/PromptModel.h>
+
+#include <algorithm>
+#include <dpl/log/log.h>
+#include <dpl/assert.h>
+
+namespace {
+
+const char INFO[] = "Widget requires access to:";
+const char DENY[] = "Deny";
+const char ALLOW[] = "Permit";
+
+const char BLANKET_CHECKBOX_LABEL[] = "Keep setting as permanent";
+const char SESSION_CHECKBOX_LABEL[] = "Remember for one run";
+
+Prompt::ButtonLabels aceQuestionLabel = {DENY, ALLOW};
+
+static Prompt::PromptLabels* getModel(
+        Prompt::PromptModel::PromptType promptType,
+        const std::string& resourceId)
+{
+    std::string strLabel;
+    strLabel = INFO;
+    strLabel += "<br>";
+    strLabel += resourceId;
+
+    return new Prompt::PromptLabels(promptType, aceQuestionLabel, strLabel);
+}
+
+Prompt::Validity fromPromptTypeToValidity(int aPromptType, bool checkClicked)
+{
+    using namespace Prompt;
+    PromptModel::PromptType promptTypeEnum =
+        static_cast<PromptModel::PromptType>(aPromptType);
+    switch (promptTypeEnum) {
+    case PromptModel::PROMPT_ONESHOT:
+        return Validity::ONCE;
+    case PromptModel::PROMPT_SESSION:
+        if (checkClicked)
+        {
+            return Validity::SESSION;
+        }
+        else
+        {
+            return Validity::ONCE;
+        }
+    case PromptModel::PROMPT_BLANKET:
+        if (checkClicked)
+        {
+            return Validity::ALWAYS;
+        }
+        else
+        {
+            return Validity::ONCE;
+        }
+    default:
+        Assert(0);
+        return Validity::ONCE;
+    }
+}
+} // namespace anonymous
+
+namespace Prompt {
+
+
+PromptLabels::PromptLabels(int promptType,
+                           const Prompt::ButtonLabels& questionLabel,
+                           const std::string& mainLabel) :
+               m_promptType(promptType),
+               m_buttonLabels(questionLabel),
+               m_mainLabel(mainLabel)
+{
+
+}
+
+int PromptLabels::getPromptType() const
+{
+    return m_promptType;
+}
+const ButtonLabels& PromptLabels::getButtonLabels() const
+{
+    return m_buttonLabels;
+}
+const std::string& PromptLabels::getMainLabel() const
+{
+    return m_mainLabel;
+}
+
+DPL::OptionalString PromptLabels::getCheckLabel() const
+{
+    if (PromptModel::PROMPT_BLANKET == m_promptType)
+    {
+        return DPL::OptionalString(
+                DPL::FromUTF8String(BLANKET_CHECKBOX_LABEL));
+    }
+    else if (PromptModel::PROMPT_SESSION == m_promptType)
+    {
+        return DPL::OptionalString(
+                DPL::FromUTF8String(SESSION_CHECKBOX_LABEL));
+    }
+
+    return DPL::OptionalString();
+}
+
+bool PromptLabels::isAllowed(const size_t buttonClicked) const
+{
+    Assert(buttonClicked < aceQuestionLabel.size() &&
+            "Button Clicked number is not in range of questionLabel");
+
+    return aceQuestionLabel[buttonClicked] == ALLOW;
+}
+
+PromptAnswer::PromptAnswer(bool isAccessAllowed, Validity validity) :
+        m_isAccessAllowed(isAccessAllowed),
+        m_validity(validity)
+{
+
+}
+
+PromptAnswer::PromptAnswer(
+        int aPromptType, unsigned int buttonAns, bool checkAns)
+{
+    Assert(buttonAns < aceQuestionLabel.size() &&
+            "Button Clicked number is not in range of questionLabel");
+
+    m_isAccessAllowed = aceQuestionLabel[buttonAns] == ALLOW;
+    m_validity = fromPromptTypeToValidity(aPromptType, checkAns);
+}
+
+bool PromptAnswer::isAccessAllowed() const
+{
+    return m_isAccessAllowed;
+}
+
+Validity PromptAnswer::getValidity() const
+{
+    return m_validity;
+}
+
+PromptLabels* PromptModel::getOneShotModel(const std::string& resourceId)
+{
+    return getModel(PROMPT_ONESHOT, resourceId);
+}
+
+PromptLabels* PromptModel::getSessionModel(const std::string& resourceId)
+{
+    return getModel(PROMPT_SESSION, resourceId);
+}
+
+PromptLabels* PromptModel::getBlanketModel(const std::string& resourceId)
+{
+    return getModel(PROMPT_BLANKET, resourceId);
+}
+
+
+} // Prompt
diff --git a/ace/engine/Attribute.cpp b/ace/engine/Attribute.cpp
new file mode 100644 (file)
index 0000000..bc96a2b
--- /dev/null
@@ -0,0 +1,892 @@
+/*
+ * 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 <fnmatch.h>
+#include <pcrecpp.h>
+#include <sstream>
+#include <dpl/foreach.h>
+#include <dpl/log/log.h>
+#include <ace/Attribute.h>
+
+const bool Attribute::alpha[256] = {
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,
+    0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
+    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0
+};
+const bool Attribute::digit[256] = {
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0
+};
+
+const bool Attribute::mark[256] = {
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 1, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
+    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0
+};
+
+bool Attribute::searchAndCut(const char *str)
+{
+    //TODO
+    size_t pos = m_name.rfind(str);
+    if (pos == std::string::npos) {
+        return false;
+    }
+    if ((strlen(str) + pos) == m_name.size()) {
+        m_name.erase(pos, std::string::npos);
+        return true;
+    }
+    return false;
+}
+
+Attribute::Attribute(const std::string *name,
+                     const Match matchFunc,
+                     const Type type_) :
+    matchFunction(matchFunc)
+{
+    m_name = *name;
+    m_typeId = type_;
+    m_undetermindState = false;
+    if (matchFunction != Match::Equal
+        && matchFunction != Match::Glob
+        && matchFunction != Match::Regexp)
+    {
+        //LogDebug("MID: " << matchFunction);
+        Assert(0 && "Match function problem");
+    }
+
+    if (searchAndCut(".scheme")) {
+        modifierFunction = Modifier::Scheme;
+    } else if (searchAndCut(".authority")) {
+        modifierFunction = Modifier::Authority;
+    } else if (searchAndCut(".scheme-authority")) {
+        modifierFunction = Modifier::SchemeAuthority;
+    } else if (searchAndCut(".host")) {
+        modifierFunction = Modifier::Host;
+    } else if (searchAndCut(".path")) {
+        modifierFunction = Modifier::Path;
+    } else {
+        modifierFunction = Modifier::Non;
+    }
+}
+
+static Attribute::MatchResult equal_comparator(const std::string *first,
+                                               const std::string *second)
+{
+    if((*first) == (*second)) {
+        return Attribute::MatchResult::MRTrue;
+    }
+    return  Attribute::MatchResult::MRFalse;
+}
+
+static Attribute::MatchResult glob_comparator(const std::string *first,
+        const std::string *second)
+{
+    // order is important
+    if (!fnmatch(first->c_str(), second->c_str(), 0)) {
+        return Attribute::MatchResult::MRTrue;
+    }
+    return  Attribute::MatchResult::MRFalse;
+}
+
+static Attribute::MatchResult regexp_comparator(const std::string *first,
+                                                const std::string *second)
+{
+    // order is important
+    pcrecpp::RE re(first->c_str());
+    if (re.FullMatch(second->c_str())) {
+        return Attribute::MatchResult::MRTrue;
+    }
+    return  Attribute::MatchResult::MRFalse;
+}
+
+Attribute::MatchResult Attribute::lists_comparator(
+        const std::list<std::string> *first,
+        const std::list<std::string> *second,
+        Attribute::MatchResult (*comparator)(const std::string *,
+                                             const std::string *)) const
+{
+    //NOTE: BONDI defines all availabe matching function as: if some string from first input bag
+    //matches some input string from second input bag, so it's required to find only one matching string
+    MatchResult result = MatchResult::MRFalse;
+
+    for (std::list<std::string>::const_iterator second_iter = second->begin();
+         (second_iter != second->end()) && (result != MatchResult::MRTrue);
+         ++second_iter)
+    {
+        std::string *modified_value = applyModifierFunction(&(*second_iter));
+        //Value was not an URI, it will be removed from the string bag (ignored)
+        if (modified_value == NULL) {
+            continue;
+        }
+
+        for (std::list<std::string>::const_iterator first_iter = first->begin();
+             first_iter != first->end();
+             ++first_iter) {
+            //Compare attributes
+            if ((*comparator)(&(*first_iter), modified_value) == MatchResult::MRTrue) {
+                result = MatchResult::MRTrue;
+                break; //Only one match is enough
+            }
+        }
+        if (modified_value) {
+            delete modified_value;
+            modified_value = NULL;
+        }
+    }
+
+    if (result == MatchResult::MRTrue) {
+        LogDebug("Returning TRUE");
+#ifdef ALL_LOGS
+    } else if (result == MatchResult::MRFalse) {
+        LogDebug("Returning FALSE");
+    } else if (result == MatchResult::MRUndetermined) {
+        LogDebug("Returning UNDETERMINED");
+#endif
+    }
+
+    return result;
+}
+
+std::string * Attribute::applyModifierFunction(const std::string * val) const
+{
+    std::string * result = NULL;
+    switch (modifierFunction) {
+    case Modifier::Scheme:
+        result = uriScheme(val);
+        break;
+    case Modifier::Authority:
+        result = uriAuthority(val);
+        break;
+    case Modifier::SchemeAuthority:
+        result = uriSchemeAuthority(val);
+        break;
+    case Modifier::Host:
+        result = uriHost(val);
+        break;
+    case Modifier::Path:
+        result = uriPath(val);
+        break;
+    default:
+        result = new std::string(*val);
+    }
+
+    return result;
+}
+
+/**
+ * this - attribute obtained from xmlPolicy tree
+ * attribute - attribute obtained from PIP
+ */
+Attribute::MatchResult Attribute::matchAttributes(
+        const BaseAttribute *attribute) const
+{
+    std::string tempNam = *(attribute->getName());
+    std::string tempVal;
+    std::string myVal;
+
+    if (!(attribute->getValue()->empty())) {
+        tempVal = attribute->getValue()->front();
+    }
+
+    if (!(this->value.empty())) {
+        myVal = this->value.front();
+    }
+
+#ifdef ALL_LOGS
+    LogDebug("Comparing attribute: " << this->m_name << "(" <<
+        myVal << ") with: " << tempNam <<
+        "(" << tempVal << ")");
+#endif
+    Assert(
+        (this->m_name == *(attribute->getName())) &&
+        "Two completely different attributes are being compared!");
+    Assert(
+        (this->m_typeId == attribute->getType()) &&
+        "Two completely different attributes are being compared!");
+
+    if (attribute->isUndetermind()) {
+        LogDebug("Attribute match undetermined");
+        return MatchResult::MRUndetermined;
+    }
+
+    //Regardles the algorithm used, if we have empty
+    //bag the result is always false
+    if (this->isValueEmpty() || attribute->isValueEmpty()) {
+        if (this->isValueEmpty()) {
+            LogDebug("empty bag in condition comparing");
+        }
+        if (attribute->isValueEmpty()) {
+            LogDebug("empty bag in attribute comparing");
+        }
+        return MatchResult::MRFalse;
+    }
+
+    if (this->matchFunction == Match::Equal) {
+        return lists_comparator(&(this->value),
+                                attribute->getValue(),
+                                equal_comparator);
+    } else if (this->matchFunction == Match::Glob) {
+        return lists_comparator(&(this->value),
+                                attribute->getValue(),
+                                glob_comparator);
+    } else if (this->matchFunction == Match::Regexp) {
+        return lists_comparator(&(this->value),
+                                attribute->getValue(),
+                                regexp_comparator);
+    }        //[CR] Change to Assert
+    Assert(false && " ** Critical :: no match function selected!");
+    return MatchResult::MRFalse; // to remove compilator warning
+}
+
+void Attribute::addValue(const std::string *val)
+{
+    this->getValue()->push_back(*val);
+}
+
+std::ostream & operator<<(std::ostream & out,
+                          const Attribute & attr)
+{
+    out << "attr: m_name: " << *(attr.getName())
+        << " type: " << Attribute::typeToString(attr.getType())
+        << " value: ";
+    if (attr.m_undetermindState) {
+        out << "Undetermined";
+    } else if (attr.getValue()->empty()) {
+        out << "Empty string bag";
+    } else {
+        FOREACH (it, *attr.getValue()) {
+            out << *it;
+        }
+    }
+    return out;
+}
+
+bool
+Attribute::parse(const std::string *input,
+                 std::string *val) const
+{
+    static const char *pattern =
+        "^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?";
+    pcrecpp::RE re(pattern);
+    if (!re.FullMatch(input->c_str(), &val[0], &val[1],
+                 &val[2], &val[3], &val[4],
+                 &val[5], &val[6], &val[7], &val[8])) {
+        LogDebug("Error: attribute parsing failed.");
+        return false;
+    }
+#ifdef ALL_LOGS
+    for (int i = 0; i < 9; i++) {
+        LogDebug("val " << i << " :" << val[i]);
+    }
+#endif
+
+    if (find_error(val)) {
+        LogDebug("Input is not an URI " << *input);
+        for (int i = 0; i < 9; ++i) {
+            val[i].clear();
+        }
+        return false;
+    }
+
+    return true;
+}
+
+Attribute::~Attribute()
+{
+}
+
+std::string * Attribute::uriScheme(const std::string *input) const
+{
+    std::string part[9];
+    if (!parse(input, part)) {
+        return NULL;
+    }
+    return new string(part[1]);
+}
+
+std::string *
+Attribute::uriAuthority(const std::string *input) const
+{
+    std::string part[9];
+    if (!parse(input, part)) {
+        return NULL;
+    }
+    return new string(part[3]);
+}
+
+std::string *
+Attribute::uriSchemeAuthority(const std::string *input) const
+{
+    std::string part[9];
+    if (!parse(input, part)) {
+        return NULL;
+    }
+
+    if (part[0].size() == 0 || part[2].size() == 0) {
+        return new std::string();
+    }
+    return new string(part[0] + part[2]);
+}
+
+std::string *
+Attribute::uriHost(const std::string *input) const
+{
+    std::string part[9];
+    if (!parse(input, part)) {
+        return NULL;
+    }
+    return getHost(&(part[3]));
+}
+
+std::string *
+Attribute::uriPath(const std::string *input) const
+{
+    //TODO right now uriPath leaves leading '/' in uri, this slash is removed from the string
+    //it's not clear if leading '/' is a part of path component or only the separator
+    std::string part[9];
+    if (!parse(input, part)) {
+        return NULL;
+    }
+
+    std::string * temp = NULL;
+
+    if (part[4].at(0) == '/') {
+        temp = new string(part[4].substr(1, part[4].length() - 1));
+    } else {
+        temp = new string(part[4]);
+    }
+
+    return temp;
+}
+
+bool Attribute::find_error(const std::string *tab) const
+{
+    //We are checking tab[1] which contains scheme without ':' at the end
+    if (!checkScheme(&(tab[1]))) {
+        LogDebug("Check scheme failed, URI is invalid");
+        return true; //error found
+    }
+    if (!checkAuthority(&(tab[3]))) {
+        LogDebug("Check authority failed, URI is invalid");
+        return true; //error found
+    }
+
+    if (!checkPath(&(tab[4]))) {
+        LogDebug("Check path failed, URI is invalid");
+        return true; //error found
+    }
+
+    return false;
+}
+
+bool Attribute::checkScheme(const std::string *part) const
+{
+    Assert(part != NULL && "Checking NULLable string. This should never happen");
+
+    bool result = true;
+
+    //TODO change part->at to data=part->c_str()
+    //TODO can scheme be empty? In absolute URI no, in relative URI yes
+    if (part->empty()) {
+        //Empty string is a correct schema
+        result = true;
+    } else if (alpha[(int) (part->at(0))] == 0) {
+        result = false; // First scheme character must be alpha
+    } else {
+        // rest must be alpha or digit or '+' or '-' or '.'
+        for (unsigned int i = 1; i < part->size(); ++i) {
+            int c = static_cast<int>(part->at(i));
+            if (!isSchemeAllowedCharacter(c)) {
+                result = false;
+                break;
+            }
+        }
+    }
+    return result;
+}
+
+bool Attribute::checkAuthority(const std::string *part) const
+{
+    Assert(part != NULL && "Checking NULLable string. This should never happen");
+
+    //Server is a subset of reg_m_names so here we only check if authority matches reg_m_name
+    //Additional check if authority is a valid 'server' component is done in getHost
+    if (part->empty()) {
+        return true; //empty authority is valid uri
+    }
+    bool result = true;
+
+    const char * data = part->c_str();
+    for (size_t i = 0; i < part->length(); ++i) {
+        int c = (int) data[i];
+        if (isUnreserved(c)) {
+            continue;
+        }
+        if (c == '$') {
+            continue;
+        }
+        if (c == ',') {
+            continue;
+        }
+        if (c == ';') {
+            continue;
+        }
+        if (c == ':') {
+            continue;
+        }
+        if (c == '@') {
+            continue;
+        }
+        if (c == '&') {
+            continue;
+        }
+        if (c == '=') {
+            continue;
+        }
+        if (c == '+') {
+            continue;
+        }
+        if (c == '%') {
+            if (isEscaped(data + i)) {
+                i += 2; //rewind the two escaped characters
+                continue;
+            }
+        }
+        result = false;
+        break;
+    }
+
+    return result;
+}
+
+std::string * Attribute::getHost(const std::string *part) const
+{
+    if (part->empty()) {
+        return new std::string("");
+    }
+
+    //Check userinfo
+    size_t userInfoPos = part->find("@");
+    if (userInfoPos != std::string::npos) {
+        std::string data = part->substr(0, userInfoPos);
+        if (!isUserInfoAllowedString(&data)) {
+            return new string(""); //the authority is not composed of 'server'  part
+        }
+    }
+
+    std::string host;
+    //If we use host modifier then authority is composed of 'server' part so
+    //the port must contain only digits
+    size_t portPos = part->find(":");
+    if (portPos != std::string::npos) {
+        for (unsigned int i = portPos + 1; i < part->size(); ++i) {
+            if (!digit[(int) part->at(i)]) {
+                return new string(""); //the authority is not composed of 'server'  part
+            }
+        }
+        host = part->substr(userInfoPos + 1, portPos - (userInfoPos + 1));
+    } else {
+        host = part->substr(userInfoPos + 1, part->length() - (userInfoPos + 1));
+    }
+
+    if (!isHostAllowedString(&host)) {
+        //Even if the string is not allowed for host this can still be a valid uri
+        return new string("");
+    }
+
+    return new std::string(host);
+}
+
+bool Attribute::checkPath(const std::string *part) const
+{
+    bool result = true;
+
+    const char * data = part->c_str();
+
+    for (unsigned int i = 0; i < part->size(); ++i) {
+        int c = data[i];
+        if (c == '/') {
+            //If we found slash then the next character must be a part of segment
+            //It cannot be '/' so we have to check it immediately
+            i++;
+            c = data[i];
+            if (!isSegmentAllowedCharacter(c)) {
+                result = false;
+                break;
+            }
+        } else if (c == ';') {
+            //Start param part of segment
+            i++; //Param can be empty so we don't have to check what's right after semicolon
+            continue;
+        } else if (c == '%') {
+            //We have to handle escaped characters differently than other segment allowed characters
+            //because we need an array
+            if (isEscaped(data + i)) {
+                i += 2;
+            } else {
+                result = false;
+                break;
+            }
+        } else {
+            if (!isSegmentAllowedCharacter(c)) {
+                result = false;
+                break;
+            }
+        }
+    }
+
+    return result;
+}
+
+bool Attribute::isSchemeAllowedCharacter(int c) const
+{
+    bool result = false;
+    if (isAlphanum(c)) {
+        result = true;
+    } else if (c == '+') {
+        result = true;
+    } else if (c == '-') {
+        result = true;
+    } else if (c == '.') {
+        result = true;
+    }
+
+    return result;
+}
+
+bool Attribute::isSegmentAllowedCharacter(int c) const
+{
+    bool result = true;
+
+    //    LogDebug("Checking is segment allowed for char "<<(char)c);
+
+    if (isUnreserved(c)) { //do nothing, result = true
+    } else if (c == ':') { //do nothing, result = true
+    } else if (c == '@') { //do nothing, result = true
+    } else if (c == '&') { //do nothing, result = true
+    } else if (c == '=') { //do nothing, result = true
+    } else if (c == '+') { //do nothing, result = true
+    } else if (c == '$') { //do nothing, result = true
+    } else if (c == ',') { //do nothing, result = true
+    } else {
+        result = false;
+    }
+
+    return result;
+}
+
+bool Attribute::isUserInfoAllowedString(const std::string * str) const
+{
+    bool result = false;
+
+    const char * data = str->c_str();
+
+    for (unsigned int i = 0; i < str->length(); ++i) {
+        int c = data[i];
+        if (isUnreserved(c)) {
+            result = true;
+        } else if (c == '%') {
+            //isEsacped method checks if we don't cross array bounds, so we can
+            //safely give data[i] here
+            result = isEscaped((data + i));
+            if (result == false) {
+                break;
+            }
+            i += 2; //rewind the next two characters sEsacped method checks if we don't cross array bounds, so we can safely rewind
+        } else if (c == ',') {
+            result = true;
+        } else if (c == '$') {
+            result = true;
+        } else if (c == '+') {
+            result = true;
+        } else if (c == '=') {
+            result = true;
+        } else if (c == '&') {
+            result = true;
+        } else if (c == '@') {
+            result = true;
+        } else if (c == ':') {
+            result = true;
+        }
+    }
+    return result;
+}
+
+bool Attribute::isUnreserved(int c) const
+{
+    return isAlphanum(c) || mark[c];
+}
+
+bool Attribute::isAlphanum(int c) const
+{
+    return alpha[c] || digit[c];
+}
+
+bool Attribute::isHex(int c) const
+{
+    bool result = false;
+
+    if (digit[c]) {
+        result = true;
+    } else if (c == 'A') {
+        result = true;
+    } else if (c == 'B') {
+        result = true;
+    } else if (c == 'C') {
+        result = true;
+    } else if (c == 'D') {
+        result = true;
+    } else if (c == 'E') {
+        result = true;
+    } else if (c == 'F') {
+        result = true;
+    } else if (c == 'a') {
+        result = true;
+    } else if (c == 'b') {
+        result = true;
+    } else if (c == 'c') {
+        result = true;
+    } else if (c == 'd') {
+        result = true;
+    } else if (c == 'e') {
+        result = true;
+    } else if (c == 'f') {
+        result = true;
+    }
+
+    return result;
+}
+
+bool Attribute::isEscaped(const char esc[3]) const
+{
+    if (esc == NULL) {
+        return false;
+    }
+
+    if ((esc[0] == 0) || (esc[1] == 0) || (esc[2] == 0)) {
+        //We get an array that seems to be out of bounds.
+        //To be on the safe side return here
+        LogDebug("HEX NULLS");
+        return false;
+    }
+
+    if (esc[0] != '%') {
+        LogDebug(
+            "Error: first character of escaped value must be a precent but is "
+            <<
+            esc[0]);
+        return false;
+    }
+
+#ifdef ALL_LOGS
+    for (int i = 0; i < 3; i++) {
+        LogDebug("HEX " << esc[i]);
+    }
+#endif
+    return isHex((int) esc[1]) && isHex((int) esc[2]);
+}
+
+bool Attribute::isHostAllowedString(const std::string * str) const
+{
+    bool result = true;
+
+    if (digit[(int) str->at(0)]) {
+        //IPv4 address
+        result = isIPv4AllowedString(str);
+    } else {
+        //Hostname
+        result = isHostNameAllowedString(str);
+    }
+
+    return result;
+}
+
+bool Attribute::isIPv4AllowedString(const std::string * str) const
+{
+    LogDebug("Is hostIPv4 allowed String for " << *str);
+
+    const char * data = str->c_str();
+    bool result = true;
+    int digitCounter = 0;
+    int dotCounter = 0;
+
+    for (unsigned int i = 0; i < str->length(); ++i) {
+        if (data[i] == '.') {
+            dotCounter++;
+            digitCounter = 0;
+        } else if (digit[(int) data[i]]) {
+            digitCounter++;
+            if ((digitCounter > 3) || !digitCounter) {
+                result = false;
+                break;
+            }
+        } else {
+            result = false;
+            break;
+        }
+    }
+    if (dotCounter != 3) {
+        result = false;
+    }
+    return result;
+}
+
+bool Attribute::isHostNameAllowedString(const std::string * str) const
+{
+    LogDebug("Is hostname allowed String for " << *str);
+
+    int lastPosition = 0; //the position of last dot + 1
+    const char * data = str->c_str();
+    bool finalDot = false;
+    size_t end = str->length();
+    bool result = false;
+
+    for (size_t i = 0; i < end; ++i) {
+        if (data[i] == '.') {
+            if (i == str->length() - 1) { //ending dot
+                //There can be a leading '.' int the hostm_name
+                finalDot = true;
+                break;
+            } else {
+                //we found domain label
+                if (!isDomainLabelAllowedString(data + lastPosition, i -
+                                                lastPosition)) {
+                    result = false;
+                    goto end;
+                }
+                lastPosition = i + 1; //Set position to position of last dot + 1
+            }
+        }
+    }
+
+    if (finalDot) {
+        //we have to rewind one position to check the rightmost string
+        //but only in case we find final dot
+        end--;
+    }
+    //Compare only the rightmost string aaa.bbbb.rightmostString.
+    result = isTopLabelAllowedString(data + lastPosition, end - lastPosition);
+
+end:
+
+    if (result) {
+        LogInfo("Hostname is allowed");
+    } else {
+        LogInfo("Hostname is NOT allowed");
+    }
+
+    return result;
+}
+
+bool Attribute::isDomainLabelAllowedString(const char * data,
+        int length) const
+{
+    LogDebug(
+        "Is domain allowed String for " << data << " taking first " <<
+        length <<
+        " chars");
+
+    if (!isAlphanum((int) data[0]) || !isAlphanum((int) data[length - 1])) {
+        return false;
+    }
+
+    for (int i = 0; i < length; i++) {
+        if ((!isAlphanum(data[i])) && !(data[i] == '-')) {
+            return false;
+        }
+    }
+    return true;
+}
+
+bool Attribute::isTopLabelAllowedString(const char * data,
+        int length) const
+{
+    if ((!alpha[(int) data[0]]) || (!isAlphanum((int) data[length - 1]))) {
+        return false;
+    }
+
+    for (int i = 1; i < length - 1; i++) {
+        if ((!isAlphanum(data[i])) && !(data[i] == '-')) {
+            return false;
+        }
+    }
+    return true;
+}
+
+void printAttributes(const AttributeSet& attrs)
+{
+    if (attrs.empty()) {
+        LogWarning("Empty attribute set");
+    } else {
+        LogDebug("PRINT ATTRIBUTES:");
+        for (AttributeSet::const_iterator it = attrs.begin();
+             it != attrs.end();
+             ++it)
+        {
+            LogDebug("name: " << *(*it)->getName());
+        }
+    }
+}
+
+void printAttributes(const std::list<Attribute> & attrs)
+{
+    if (attrs.empty()) {
+        LogWarning("Empty attribute set");
+    } else {
+        LogDebug("PRINT ATTRIBUTES:");
+        for (std::list<Attribute>::const_iterator it = attrs.begin();
+             it != attrs.end();
+             ++it
+             ) {
+            LogDebug(*it);
+        }
+    }
+}
+
+//KW const char * matchResultToString(Attribute::MatchResult result){
+//KW
+//KW     const char * ret = NULL;
+//KW
+//KW     switch(result){
+//KW
+//KW         case Attribute::MRTrue:
+//KW             ret = "true";
+//KW             break;
+//KW         case Attribute::MRFalse:
+//KW             ret = "false";
+//KW            break;
+//KW         case Attribute::MRUndetermined:
+//KW             ret = "undetermined";
+//KW             break;
+//KW         default:
+//KW             ret = "Wrong match result";
+//KW     }
+//KW
+//KW     return ret;
+//KW
+//KW }
diff --git a/ace/engine/CombinerImpl.cpp b/ace/engine/CombinerImpl.cpp
new file mode 100644 (file)
index 0000000..dab775f
--- /dev/null
@@ -0,0 +1,334 @@
+/*
+ * 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.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : CombinerImpl.cpp
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+
+#include <dpl/log/log.h>
+#include <dpl/assert.h>
+#include <dpl/foreach.h>
+
+#include <ace/CombinerImpl.h>
+#include <ace/Rule.h>
+#include <ace/Policy.h>
+
+namespace {
+
+bool denyOverridesPredecessor(
+    const ExtendedEffect &first,
+    const ExtendedEffect &second)
+{
+    if (first.getEffect() == second.getEffect())
+        return first.getRuleId() < second.getRuleId();
+    return first.getEffect() < second.getEffect();
+}
+
+bool permitOverridePredecessor(
+    const ExtendedEffect &first,
+    const ExtendedEffect &second)
+{
+    if (first.getEffect() == second.getEffect())
+        return first.getRuleId() < second.getRuleId();
+    return first.getEffect() > second.getEffect();
+}
+
+} //anonymous namespace
+
+ExtendedEffect CombinerImpl::denyOverrides(const ExtendedEffectList &effects)
+{
+    if (isError(effects)) {
+        return Error;
+    }
+
+    ExtendedEffect result(Inapplicable);
+
+    FOREACH(it, effects) {
+        if (denyOverridesPredecessor(*it, result)) {
+            result = *it;
+        }
+    }
+    return result;
+}
+
+ExtendedEffect CombinerImpl::permitOverrides(const ExtendedEffectList &effects)
+{
+    if (isError(effects)) {
+        return Error;
+    }
+
+    // This magic number must be bigger that the bigest ruleId number from policy file.
+    ExtendedEffect result(Deny, 999999);
+
+    //Flag used to indicate that any of Deny,prompt-*,permit options appear
+    //Consequently if flag is true then result should be return, otherwise inapplicable should be returned
+    bool flag = false;
+    bool flagUndetermined = false;
+
+    FOREACH(it,effects) {
+        ExtendedEffect effect = *it;
+
+        if (effect.getEffect() == Permit) {
+            return effect;
+        } // no need for further check if "permit" found
+        if (effect.getEffect() == Undetermined) {
+            flagUndetermined = true;
+        } //check for undetermined
+
+        //Set the flag and the result even if effect is equal to result
+        //It is done to mark if any "Deny" effect occured
+        if (permitOverridePredecessor(effect, result)
+            && effect.getEffect() != Inapplicable
+            && effect.getEffect() != Undetermined)
+        {
+            result = effect;
+            flag = true;
+        }
+    }
+
+    if (flagUndetermined) {
+        return ExtendedEffect(Undetermined);
+    }
+
+    if (!flag) {
+        return ExtendedEffect(Inapplicable);
+    }
+    return result;
+}
+
+ExtendedEffect CombinerImpl::firstApplicable(
+    const ExtendedEffectList & effects)
+{
+  if (isError(effects)) {
+      return Error;
+  }
+
+  FOREACH(it,effects) {
+      if (it->getEffect() != Inapplicable) {
+          return *it;
+      }
+  }
+  return Inapplicable;
+}
+
+ExtendedEffect CombinerImpl::firstMatchingTarget(
+    const ExtendedEffectList &effects)
+{
+    if (isError(effects)) {
+        return Error;
+    }
+    // effect list constains result of policies which target has been matched.
+    //
+    // If target does not match policy result is NotMatchingTarget
+    // NotMatchingTarget values are not stored on the effects list
+    // (you can check it in combinePolicies function).
+    //
+    // So we are intrested in first value on the list.
+    return effects.empty() ? Inapplicable : effects.front();
+}
+
+bool CombinerImpl::isError(const ExtendedEffectList &effects)
+{
+    FOREACH(it, effects)
+    {
+        if (Error == it->getEffect()) {
+            return true;
+        }
+    }
+    return false;
+}
+
+ExtendedEffect CombinerImpl::combineRules(const TreeNode * policy)
+{
+    const Policy * policyObj = dynamic_cast<const Policy *>(policy->getElement());
+    if (!policyObj) {
+        LogError("dynamic_cast failed. PolicyObj is null.");
+        return Error;
+    }
+
+    Policy::CombineAlgorithm algorithm = policyObj->getCombineAlgorithm();
+
+    Assert(
+        algorithm != Policy::FirstTargetMatching &&
+        "Policy cannot have algorithm first target matching");
+
+    bool isUndetermined = false;
+
+    if (!checkIfTargetMatches(policyObj->getSubjects(), isUndetermined)) {
+        if (isUndetermined) {
+            //TODO Target is undetermined what should we do now ??
+            //Right now simply return NotMatchingTarget
+        }
+        //Target doesn't match
+        return NotMatchingTarget;
+    }
+    //Get all rules
+    const ChildrenSet & children = policy->getChildrenSet();
+    ChildrenConstIterator it = children.begin();
+    ExtendedEffectList effects;
+
+    while (it != children.end()) {
+        const Rule * rule = dynamic_cast<const Rule *>((*it)->getElement());
+
+        if (!rule) {
+            LogError("Error in dynamic_cast. rule is null");
+            return ExtendedEffect(Error);
+        }
+
+        ExtendedEffect effect = rule->evaluateRule(this->getAttributeSet());
+        effects.push_back(effect);
+        if (algorithm == Policy::FirstApplicable && effect.getEffect() != Inapplicable) {
+            //For first applicable algorithm we may stop after evaluating first policy
+            //which has effect other than inapplicable
+            break;
+        }
+        ++it;
+    } //end policy children iteration
+
+    //Use combining algorithm
+    ExtendedEffect ef = combine(policyObj->getCombineAlgorithm(), effects);
+    return ef;
+}
+
+//WARNING this method makes an assumption that Policy target is a policy child
+ExtendedEffect CombinerImpl::combinePolicies(const TreeNode * policy)
+{
+    const Policy * policySet = dynamic_cast<const Policy *>(policy->getElement());
+
+    if (!policySet) {
+        LogError("dynamic_cast failed. Policy set is null.");
+        return Error;
+    }
+
+    bool isUndetermined = false;
+    Policy::CombineAlgorithm algorithm = policySet->getCombineAlgorithm();
+
+    if (!checkIfTargetMatches(policySet->getSubjects(), isUndetermined)) {
+        /*   I can't explain this...
+        if (isUndetermined) {
+            if (algorithm == Policy::FirstTargetMatching) {
+                return Undetermined;
+            }
+        }
+        */
+        //Target doesn't match
+        return NotMatchingTarget;
+    }
+
+    const ChildrenSet & children = policy->getChildrenSet();
+
+    ExtendedEffectList effects;
+
+    FOREACH(it, children) {
+        ExtendedEffect effect;
+
+        if ((*it)->getTypeID() == TreeNode::PolicySet) {
+            effect = combinePolicies(*it);
+            if (effect.getEffect() != NotMatchingTarget) {
+                effects.push_back(effect);
+            }
+        } else if ((*it)->getTypeID() == TreeNode::Policy) {
+            effect = combineRules(*it);
+            if (effect.getEffect() != NotMatchingTarget) {
+                effects.push_back(effect);
+            }
+        } else {
+            // [CR] fix it
+            LogError("effect value is not initialized!");
+            return ExtendedEffect(Error);
+        }
+
+        if (algorithm == Policy::FirstTargetMatching
+            && effect.getEffect() != NotMatchingTarget)
+        {
+            //In First matching target algorithm we may return when first result is found
+            break;
+        }
+    }
+
+    //Use combining algorithm
+    return combine(policySet->getCombineAlgorithm(), effects);
+}
+
+ExtendedEffect CombinerImpl::combine(
+    Policy::CombineAlgorithm algorithm,
+    ExtendedEffectList &effects)
+{
+#ifdef ALL_LOGS
+    LogDebug("Effects to be combined with algorithm: " << ::toString(algorithm));
+    showEffectList(effects);
+#endif
+    switch (algorithm) {
+    case Policy::DenyOverride:
+        return denyOverrides(effects);
+        break;
+    case Policy::PermitOverride:
+        return permitOverrides(effects);
+        break;
+    case Policy::FirstApplicable:
+        return firstApplicable(effects);
+        break;
+    case Policy::FirstTargetMatching:
+        return firstMatchingTarget(effects);
+        break;
+    default:
+        Assert(false && "Wrong combining algorithm used");
+        return Error;
+    }
+}
+
+/**
+ *
+ * @param attrSet set of Subject attributes in policy that identifies target
+ * @return true if target  is determined and matches, false and isUndertmined is set to true if the target is undetermined
+ * false and isUndetermined set to false if target is determined but doesn't match
+ */
+bool CombinerImpl::checkIfTargetMatches(
+        const std::list<const Subject *> * subjectsList,
+        bool &isUndetermined)
+{
+    if (subjectsList->empty()) {
+        return true;
+    }
+
+    std::list<const Subject *>::const_iterator it = subjectsList->begin();
+    bool match = false;
+    //According to BONDI 1.0 at least one target must match
+    while (it != subjectsList->end()) {
+        match = (*it)->matchSubject(this->getAttributeSet(), isUndetermined);
+        if (match) { //at least one match
+            break;
+        }
+        ++it;
+    }
+
+    #ifdef _DEBUG
+    if (match == Attribute::MRTrue) {
+        LogDebug("Target matches ");
+    } else if (match == Attribute::MRUndetermined) {
+        LogDebug("Target match undetermined ");
+    } else {
+        LogDebug("Target doesn't match");
+    }
+    #endif
+    return match;
+}
+
diff --git a/ace/engine/Condition.cpp b/ace/engine/Condition.cpp
new file mode 100644 (file)
index 0000000..e92e681
--- /dev/null
@@ -0,0 +1,238 @@
+/*
+ * 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: Condition.cpp
+// Author: notroot
+//
+// Created on June 3, 2009, 9:00 AM
+//
+
+#include <iostream>
+#include <dpl/log/log.h>
+#include <dpl/foreach.h>
+#include <ace/Condition.h>
+
+/**
+ * Check if attribute in condition matches the values obtained from PIP
+ * attrSet - attributes from PIP
+ */
+
+Attribute::MatchResult Condition::evaluateCondition(
+        const AttributeSet * attrSet) const
+{
+    //Condition may include either matches of attributes or other conditions
+    //in this method all attributes are matched at first and if possible the
+    //condition is evaluated. If evaluation is not possible based solely on
+    //attributes then we start recursion into child conditions.
+
+    Attribute::MatchResult match;
+    bool undeterminedMatchFound = false;
+    bool isFinalMatch = false;
+
+#ifdef ALL_LOGS
+    LogDebug("Attributes to be matched");
+    printAttributes(*attrSet);
+    LogDebug("Condition attributes values");
+    printAttributes(attributes);
+#endif
+
+    if (this->isEmpty()) {
+        LogDebug("Condition is empty, returning true");
+        //Condition is empty, it means it evaluates to TRUE
+        return Attribute::MatchResult::MRTrue;
+    }
+
+    match = evaluateAttributes(attrSet, isFinalMatch, undeterminedMatchFound);
+    if (isFinalMatch) {
+        LogDebug("Evaluate attributes returning verdict" ) ; //<< match);
+        return match;
+    }
+
+    match = evaluateChildConditions(attrSet,
+                                    isFinalMatch,
+                                    undeterminedMatchFound);
+    if (isFinalMatch) {
+        LogDebug("Evaluate child conditions returning verdict" ); // << match);
+        return match;
+    }
+
+    if (undeterminedMatchFound) {
+        //If any  child condition/attribute-match was undetermined and
+        //so far we couldn't make a decision then we must return undetermined
+        LogDebug("Evaluate condition returning MRUndetermined");
+        return Attribute::MatchResult::MRUndetermined;
+    }
+
+    if (this->isAndCondition()) {
+        match = Attribute::MatchResult::MRTrue;
+    } else if (this->isOrCondition()) {
+        match = Attribute::MatchResult::MRFalse;
+    } else {
+        Assert(false && "Condition has to be either AND or OR");
+    }
+    return match;
+}
+
+// KW Attribute::MatchResult Condition::performORalgorithm(const std::set<Attribute>* attrSet) const{
+// KW
+// KW     Attribute::MatchResult match;
+// KW     bool undeterminedMatchFound = false;
+// KW     bool isFinalMatch = false;
+// KW
+// KW     LogDebug("Performing OR algorithm");
+// KW
+// KW     match = evaluateAttributes(attrSet, isFinalMatch, undeterminedMatchFound);
+// KW     if(isFinalMatch){
+// KW         LogDebug("OR algorithm evaluate attributes returning verdict" << match);
+// KW         return match;
+// KW     }
+// KW
+// KW     match = evaluateChildConditions(attrSet, isFinalMatch, undeterminedMatchFound);
+// KW     if(isFinalMatch){
+// KW         return match;
+// KW     }
+// KW
+// KW     if(undeterminedMatchFound){
+// KW         //If any  child condition/attribute-match was undetermined and
+// KW         //so far we couldn't make a decision then we must return undetermined
+// KW         LogDebug("OR algorithm returning MRUndetermined");
+// KW         return Attribute::MRUndetermined;
+// KW     }
+// KW
+// KW     LogDebug("OR algorithm returning MRFalse");
+// KW     return Attribute::MRFalse;
+// KW }
+
+// KW Attribute::MatchResult Condition::performANDalgorithm(const std::set<Attribute>* attrSet) const{
+// KW
+// KW
+// KW     Attribute::MatchResult match;
+// KW     bool undeterminedMatchFound = false;
+// KW     bool isFinalMatch = false;
+// KW
+// KW     LogDebug("Performing AND algorithm");
+// KW     match = evaluateAttributes(attrSet, isFinalMatch, undeterminedMatchFound);
+// KW     if(isFinalMatch){
+// KW         LogDebug("AND algorithm evaluate attributes returning verdict" << match);
+// KW         return match;
+// KW     }
+// KW     match = evaluateChildConditions(attrSet, isFinalMatch, undeterminedMatchFound);
+// KW     if(isFinalMatch){
+// KW         LogDebug("AND algorithm evaluate child returning verdict " << match);
+// KW         return match;
+// KW     }
+// KW     if(undeterminedMatchFound){
+// KW         //If any child condition/attribute-match was undetermined and
+// KW         //so far we couldn't make a decision then we must return undetermined
+// KW         LogDebug("AND algorithm returning Undetermined");
+// KW         return Attribute::MRUndetermined;
+// KW     }
+// KW
+// KW     LogDebug("AND algorithm returning MRTrue");
+// KW     return Attribute::MRTrue;
+// KW
+// KW }
+
+Attribute::MatchResult Condition::evaluateAttributes(
+        const AttributeSet * attrSet,
+        bool& isFinalMatch,
+        bool & undeterminedMatchFound) const
+{
+    Attribute::MatchResult match = Attribute::MatchResult::MRUndetermined;
+
+    std::list<Attribute>::const_iterator condIt = this->attributes.begin();
+    while (condIt != this->attributes.end()) {
+        //Find the value of needed attribute, based on attribute name
+        AttributeSet::const_iterator attr =
+                std::find_if(attrSet->begin(),
+                             attrSet->end(),
+                             AceDB::BaseAttribute::UnaryPredicate(&(*condIt)));
+        if (attr == attrSet->end()) {
+            LogError("Couldn't find required attribute. This should not happen");
+            Assert(
+                false &&
+                "Couldn't find attribute required in condition. This should not happen"
+                "This means that some attributes has not been obtained from PIP");
+            //Return undetermined here because it seems one of the attributes is unknown/undetermined
+            isFinalMatch = true;
+            match = Attribute::MatchResult::MRUndetermined;
+            break;
+        }
+
+        match = condIt->matchAttributes(&(*(*attr)));
+        if ((match == Attribute::MatchResult::MRFalse) && isAndCondition()) {
+            //FALSE match found in AND condition
+            isFinalMatch = true;
+            break;
+        } else if ((match == Attribute::MatchResult::MRTrue) && isOrCondition()) {
+            //TRUE match found in OR condition
+            isFinalMatch = true;
+            break;
+        } else if (match == Attribute::MatchResult::MRUndetermined) {
+            //Just mark that there was undetermined value found
+            undeterminedMatchFound = true;
+        }
+        ++condIt;
+    }
+
+    return match;
+}
+
+Attribute::MatchResult Condition::evaluateChildConditions(
+        const AttributeSet * attrSet,
+        bool& isFinalMatch,
+        bool & undefinedMatchFound) const
+{
+    Attribute::MatchResult match = Attribute::MatchResult::MRUndetermined;
+
+    std::list<Condition>::const_iterator it = conditions.begin();
+    while (it != conditions.end()) {
+        match = it->evaluateCondition(attrSet);
+
+        if ((match == Attribute::MatchResult::MRFalse) && isAndCondition()) {
+            //FALSE match found in AND condition
+            LogDebug("Child conditions results MRFalse)");
+            isFinalMatch = true;
+            break;
+        } else if ((match == Attribute::MatchResult::MRTrue) && isOrCondition()) {
+            //TRUE match found in OR condition
+            LogDebug("Child conditions result MRTrue");
+            isFinalMatch = true;
+            break;
+        } else if (match == Attribute::MatchResult::MRUndetermined) {
+            undefinedMatchFound = true;
+        }
+        ++it;
+    }
+
+    return match;
+}
+
+void Condition::getAttributes(AttributeSet * attrSet)
+{
+    //Get attributes from current condition
+    FOREACH (it, attributes)
+    {
+        AceDB::BaseAttributePtr attr(new Attribute(it->getName(), it->getMatchFunction(), it->getType()));
+        attrSet->insert(attr);
+    }
+    //Get attributes from any child conditions
+    FOREACH (it, conditions)
+    {
+        it->getAttributes(attrSet);
+    }
+}
+
diff --git a/ace/engine/ConfigurationManager.cpp b/ace/engine/ConfigurationManager.cpp
new file mode 100644 (file)
index 0000000..b134e28
--- /dev/null
@@ -0,0 +1,154 @@
+/*
+ * 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 <dpl/log/log.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <error.h>
+#include <malloc.h>
+#include <sys/stat.h>
+#include <ace/ConfigurationManager.h>
+#include <unistd.h>
+
+using namespace std;
+
+namespace {
+const string currentXMLSchema("bondixml.xsd");
+}
+
+ConfigurationManager * ConfigurationManager::instance = NULL;
+
+
+string ConfigurationManager::getCurrentPolicyFile(void) const
+{
+    LogError("ConfigurationManager::getCurrentPolicyFile is DEPRECATED");
+    return "";
+}
+
+string ConfigurationManager::getFullPathToCurrentPolicyFile(void) const
+{
+    LogError("ConfigurationManager::getFullPathToCurrentPolicyFile"
+             "is DEPRECATED");
+    return "";
+}
+
+string ConfigurationManager::getFullPathToCurrentPolicyXMLSchema(void) const
+{
+    LogError("ConfigurationManager::getFullPathToCurrentPolicyXMLSchema"
+             "is DEPRECATED");
+    return "";
+}
+
+int ConfigurationManager::addPolicyFile(const string &)
+{
+    LogError("ConfigurationManager::addPolicyFile is DEPRECATED");
+    return CM_GENERAL_ERROR;
+}
+
+int ConfigurationManager::removePolicyFile(const string&)
+{
+    LogError("ConfigurationManager::removePolicyFile is DEPRECATED");
+    return CM_GENERAL_ERROR;
+}
+
+int ConfigurationManager::changeCurrentPolicyFile(const string&)
+{
+    LogError("ConfigurationManager::changeCurrentPolicyFile is DEPRECATED");
+    return CM_GENERAL_ERROR;
+}
+
+string ConfigurationManager::extractFilename(const string&) const
+{
+    LogError("ConfigurationManager::extractFilename is DEPRECATED");
+    return "";
+}
+
+
+int ConfigurationManager::parse(const string&)
+{
+    LogError("ConfigurationManager::parse is DEPRECATED");
+    return CM_GENERAL_ERROR;
+}
+
+bool ConfigurationManager::copyFile(FILE*, FILE*, int) const
+{
+    LogError("ConfigurationManager::copyFile is DEPRECATED");
+    return false;
+}
+
+bool ConfigurationManager::checkIfFileExistst(const string&) const
+{
+    LogError("ConfigurationManager::checkIfFileExistst is DEPRECATED");
+    return false;
+}
+
+const list<string> & ConfigurationManager::getPolicyFiles() const
+{
+    LogError("ConfigurationManager::getPolicyFiles is DEPRECATED");
+    static list<string> aList;
+    return aList;
+}
+
+const string & ConfigurationManager::getConfigFile() const
+{
+    LogError("ConfigurationManager::getConfigFile is DEPRECATED");
+    static string returnString("");
+    return returnString;
+}
+
+string ConfigurationManager::getFullPathToPolicyFile(PolicyType policy) const
+{
+    string cscStoragePath = getCscStoragePath();
+    string storagePath = getStoragePath();
+    string fileName;
+
+    switch (policy) {
+    case PolicyType::WAC2_0: {
+        fileName = ACE_WAC_POLICY_FILE_NAME;
+        break; }
+    case PolicyType::Tizen: {
+        fileName = ACE_TIZEN_POLICY_FILE_NAME;
+        break; }
+    default: {
+        LogError("Invalid policy file requested");
+        return ""; }
+    }
+    string cscPolicyFilePath = cscStoragePath + fileName;
+    if ( access(cscPolicyFilePath.c_str(), R_OK) == -1)
+        return storagePath + fileName;
+
+    return cscPolicyFilePath;
+}
+
+string ConfigurationManager::getFullPathToPolicyXMLSchema() const
+{
+    string storagePath = getStoragePath();
+    if (*(storagePath.rbegin()) == '/')
+    {
+        return storagePath + currentXMLSchema;
+    }
+    return storagePath + "/" + currentXMLSchema;
+}
+
+string ConfigurationManager::getStoragePath(void) const
+{
+    return ACE_MAIN_STORAGE;
+}
+
+string ConfigurationManager::getCscStoragePath(void) const
+{
+    return ACE_CSC_STORAGE;
+}
diff --git a/ace/engine/Policy.cpp b/ace/engine/Policy.cpp
new file mode 100644 (file)
index 0000000..7443090
--- /dev/null
@@ -0,0 +1,80 @@
+/*
+ * 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.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : Policy.cpp
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+
+#include <ace/Policy.h>
+
+Policy::~Policy()
+{
+    for (std::list<const Subject *>::iterator it = subjects->begin();
+         it != subjects->end();
+         ++it) {
+        delete *it;
+    }
+    delete subjects;
+}
+
+void Policy::printData()
+{
+    std::string subject;
+    if (subjects != NULL && subjects->size()) {
+        subject = (subjects->front())->getSubjectId();
+    }
+    std::string algorithm = printCombineAlgorithm(this->combineAlgorithm);
+
+    std::cout << "subject: " << subject << " algorithm: " << algorithm <<
+    std::endl;
+}
+
+std::string Policy::printCombineAlgorithm(CombineAlgorithm algorithm)
+{
+    switch (algorithm) {
+    case DenyOverride:
+        return "DenyOverride";
+    case PermitOverride:
+        return "PermitOverride";
+    case FirstApplicable:
+        return "FirstApplicable";
+    case FirstTargetMatching:
+        return "FirstTargetMatching";
+    default:
+        return "ERROR: Wrong Algorithm";
+    }
+}
+
+const char * toString(Policy::CombineAlgorithm algorithm)
+{
+    switch (algorithm) {
+    case Policy::DenyOverride:
+        return "DenyOverride";
+    case Policy::PermitOverride:
+        return "PermitOverride";
+    case Policy::FirstApplicable:
+        return "FirstApplicable";
+    case Policy::FirstTargetMatching:
+        return "FirstTargetMatching";
+    default:
+        return "ERROR: Wrong Algorithm";
+    }
+}
diff --git a/ace/engine/PolicyEnforcementPoint.cpp b/ace/engine/PolicyEnforcementPoint.cpp
new file mode 100644 (file)
index 0000000..1db8488
--- /dev/null
@@ -0,0 +1,139 @@
+/*
+ * 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    security_logic.cpp
+ * @author  Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @author  Ming Jin(ming79.jin@samsung.com)
+ * @version 1.0
+ * @brief   Implementation file for security logic
+ */
+#include <ace/PolicyEnforcementPoint.h>
+
+#include <sstream>
+#include <algorithm>
+#include <list>
+#include <string>
+#include <sstream>
+#include <stdexcept>
+#include <cstdlib>
+#include <map>
+
+#include <dpl/assert.h>
+#include <dpl/exception.h>
+#include <dpl/log/log.h>
+
+#include <ace/PolicyEvaluatorFactory.h>
+#include <ace/PolicyResult.h>
+#include <ace/Request.h>
+
+PolicyEnforcementPoint::PolicyEnforcementPoint() :
+    m_wrt(0),
+    m_res(0),
+    m_sys(0),
+    m_pdp(0),
+    m_pip(0)
+{}
+
+void PolicyEnforcementPoint::terminate()
+{
+    LogInfo("PolicyEnforcementPoint is being deinitialized.");
+
+    delete m_sys;
+    delete m_res;
+    delete m_wrt;
+    delete m_pdp;
+    delete m_pip;
+    m_sys = 0;
+    m_res = 0;
+    m_wrt = 0;
+    m_pdp = 0;
+    m_pip = 0;
+}
+
+PolicyEnforcementPoint::~PolicyEnforcementPoint()
+{
+    Assert((m_sys == 0) && "You must run "
+           "PolicyEnforcementPoint::Deinitialize before exit program!");
+}
+
+void PolicyEnforcementPoint::initialize(
+        IWebRuntime *wrt,
+        IResourceInformation *resource,
+        IOperationSystem *operation)
+{
+    if (m_wrt) {
+        ThrowMsg(PEPException::AlreadyInitialized,
+                 "Policy Enforcement Point is already initialzed");
+    }
+
+    m_wrt = wrt;
+    m_res = resource;
+    m_sys = operation;
+
+    if (this->m_pip != NULL) {
+        this->m_pip->update(m_wrt, m_res, m_sys);
+        return;
+    }
+
+    this->m_pip = new PolicyInformationPoint(wrt, m_res, m_sys);
+    this->m_pdp = new PolicyEvaluator(m_pip);
+
+    if (!this->m_pdp->initPDP()) {
+        Assert(0);
+    }
+}
+
+ExtendedPolicyResult PolicyEnforcementPoint::check(Request &request)
+{
+    return m_pdp->getPolicyForRequest(request);
+}
+
+void PolicyEnforcementPoint::updatePolicy(const std::string &policy)
+{
+    LogDebug("ACE updatePolicy: " << policy);
+    int errorCode = 0;
+
+    if (m_pdp == NULL) {
+        LogError("Evaluator not set. Ignoring message.");
+        Assert(false && "UpdateClient error on receiving event");
+    } else {
+        LogDebug("Emitting update signal.");
+        errorCode = m_pdp->updatePolicy(policy.c_str());
+    }
+
+    LogDebug("Sending reponse: " << errorCode);
+}
+
+void PolicyEnforcementPoint::updatePolicy()
+{
+    LogDebug("ACE updatePolicy");
+    if (m_pdp == NULL) {
+        LogError("Evaluator not set. Ignoring message.");
+    } else {
+        m_pdp->updatePolicy();
+    }
+}
+
+OptionalExtendedPolicyResult PolicyEnforcementPoint::checkFromCache(Request &request)
+{
+   return m_pdp->getPolicyForRequestFromCache(request);
+}
+
+OptionalExtendedPolicyResult PolicyEnforcementPoint::check(Request &request,
+                                                   bool fromCacheOnly)
+{
+   return m_pdp->getPolicyForRequest(request, fromCacheOnly);
+}
diff --git a/ace/engine/PolicyEvaluator.cpp b/ace/engine/PolicyEvaluator.cpp
new file mode 100644 (file)
index 0000000..342f257
--- /dev/null
@@ -0,0 +1,544 @@
+/*
+ * 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.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : PolicyEvaluator.cpp
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+#include <dpl/assert.h>
+#include <dpl/foreach.h>
+
+#include <ace/Attribute.h>
+#include <ace/PolicyEvaluator.h>
+#include <ace/TreeNode.h>
+#include <ace/Policy.h>
+#include <ace/Rule.h>
+#include <ace/Attribute.h>
+#include <ace/SettingsLogic.h>
+#include <ace-dao-rw/AceDAO.h>
+#include <ace-dao-ro/PreferenceTypes.h>
+#include <ace/parser.h>
+
+using namespace AceDB;
+
+PolicyEvaluator::~PolicyEvaluator()
+{
+    delete m_combiner;
+}
+
+PolicyEvaluator::PolicyEvaluator(PolicyInformationPoint * pip) :
+    m_uniform_policy(NULL),
+    m_wac_policy(NULL),
+    m_tizen_policy(NULL),
+    m_policy_to_use(PolicyType::WAC2_0),
+    m_combiner(new CombinerImpl()),
+    m_verdictListener(NULL),
+    m_pip(pip)
+{}
+
+bool PolicyEvaluator::initPDP()
+{
+    updatePolicy();
+    // TODO change return value someday to void?
+    return true;
+}
+
+bool PolicyEvaluator::fillAttributeWithPolicy()
+{
+    if (m_attributeSet.empty()) {
+        if (!extractAttributes(m_uniform_policy)) {
+            LogInfo("Warning attribute set cannot be extracted. "
+                    "Returning Deny");
+            return false;
+        }
+        // Adding widget type attribute to distinguish WAC/Tizen widgets
+        /**
+         * This special attribute of WidgetParam type is handled
+         * in PolicyInformationPoint, it is based on WidgetType
+         * fron WRT database.
+         *
+         * It is needed to distinguish cached policy results and cached prompt
+         * responses for different policies (WAC/Tizen/any possible
+         * other in the future).
+         */
+        AceDB::BaseAttributePtr attribute(new AceDB::BaseAttribute());
+        attribute->setName(POLICY_WIDGET_TYPE_ATTRIBUTE_NAME);
+        attribute->setType(AceDB::BaseAttribute::Type::WidgetParam);
+        m_attributeSet.insert(attribute);
+        AceDAO::addAttributes(m_attributeSet);
+    } else {
+        LogDebug("Required attribute set already loaded");
+    }
+    return true;
+}
+
+PolicyResult PolicyEvaluator::effectToPolicyResult(Effect effect)
+{
+    if (Effect::Deny == effect) {
+        return PolicyEffect::DENY;
+    }
+    if (Effect::Undetermined == effect) {
+        return PolicyResult::Value::UNDETERMINED;
+    }
+    if (Effect::PromptOneShot == effect) {
+        return PolicyEffect::PROMPT_ONESHOT;
+    }
+    if (Effect::PromptSession == effect) {
+        return PolicyEffect::PROMPT_SESSION;
+    }
+    if (Effect::PromptBlanket == effect) {
+        return PolicyEffect::PROMPT_BLANKET;
+    }
+    if (Effect::Permit == effect) {
+        return PolicyEffect::PERMIT;
+    }
+    if (Effect::Inapplicable == effect) {
+        return PolicyDecision::Value::NOT_APPLICABLE;
+    }
+    return PolicyEffect::DENY;
+}
+
+OptionalExtendedPolicyResult PolicyEvaluator::getPolicyForRequestInternal(
+        bool fromCacheOnly)
+{
+    //ADD_PROFILING_POINT("Search cached verdict in database", "start");
+
+    OptionalExtendedPolicyResult result = AceDAO::getPolicyResult(m_attributeSet);
+
+    //ADD_PROFILING_POINT("Search cached verdict in database", "stop");
+
+    if (fromCacheOnly || !!result) {
+        return result;
+    }
+
+    //ADD_PROFILING_POINT("EvaluatePolicy", "start");
+
+    ExtendedEffect policyEffect = evaluatePolicies(getCurrentPolicyTree());
+
+    //ADD_PROFILING_POINT("EvaluatePolicy", "stop");
+
+    LogDebug("Policy effect is: " << toString(policyEffect.getEffect()));
+
+    ExtendedPolicyResult exResult(
+        effectToPolicyResult(policyEffect.getEffect()),
+        policyEffect.getRuleId());
+
+    AceDAO::setPolicyResult(this->m_attributeSet, exResult);
+    return OptionalExtendedPolicyResult(exResult);
+}
+
+// +----------------+---------+---------+------+--------+
+// |\User setting   | PERMIT  | PROMPT* | DENY | DEF    |
+// |      \         |         |         |      |        |
+// |Policy result\  |         |         |      |        |
+// |----------------+---------+---------+------+--------+
+// |PERMIT          | PERMIT  | PROMPT* | DENY | PERMIT |
+// |----------------+---------+---------+------+--------+
+// |PROMPT*         | PROMPT* | PR MIN  | DENY | PROMPT*|
+// |----------------+---------+---------+------+--------+
+// |DENY            | DENY    | DENY    | DENY | DENY   |
+// |----------------+---------+---------+------+--------+
+// |UNDETERMIND     | UNDET   | UNDET   | DENY | UNDET  |
+// |----------------+---------+---------+------+--------+
+// |NOT_AP          | PEMIT   | PROMPT* | DENY | NOT_AP |
+// +----------------+---------+---------+------+--------+
+
+static PolicyResult getMostRestrict(
+        PreferenceTypes globalPreference,
+        const PolicyResult &policyResult)
+{
+    if (globalPreference == PreferenceTypes::PREFERENCE_PERMIT
+            && policyResult == PolicyEffect::PERMIT) {
+        return PolicyEffect::PERMIT;
+    }
+
+    if (globalPreference == PreferenceTypes::PREFERENCE_DENY
+            || policyResult == PolicyEffect::DENY) {
+        return PolicyEffect::DENY;
+    }
+
+    if (policyResult == PolicyResult::UNDETERMINED) {
+        return PolicyResult::UNDETERMINED;
+    }
+
+    if (globalPreference == PreferenceTypes::PREFERENCE_DEFAULT) {
+        return policyResult;
+    }
+
+    if (globalPreference == PreferenceTypes::PREFERENCE_ONE_SHOT_PROMPT
+            || policyResult == PolicyEffect::PROMPT_ONESHOT) {
+        return PolicyEffect::PROMPT_ONESHOT;
+    }
+
+    if (globalPreference == PreferenceTypes::PREFERENCE_SESSION_PROMPT
+            || policyResult == PolicyEffect::PROMPT_SESSION) {
+        return PolicyEffect::PROMPT_SESSION;
+    }
+
+    if (globalPreference == PreferenceTypes::PREFERENCE_BLANKET_PROMPT
+            || policyResult == PolicyEffect::PROMPT_BLANKET) {
+        return PolicyEffect::PROMPT_BLANKET;
+    }
+
+    return PolicyEffect::PERMIT;
+}
+
+OptionalExtendedPolicyResult PolicyEvaluator::getPolicyForRequestFromCache(
+        const Request &request)
+{
+    return getPolicyForRequest(request, true);
+}
+
+ExtendedPolicyResult PolicyEvaluator::getPolicyForRequest(const Request &request)
+{
+    auto result = this->getPolicyForRequest(request, false);
+    Assert(!!result
+                    && "Policy always has to be evaluated to valid state");
+    return *result;
+}
+
+OptionalExtendedPolicyResult PolicyEvaluator::getPolicyForRequest(
+        const Request &request,
+        bool fromCacheOnly)
+{
+    //ADD_PROFILING_POINT("getPolicyForRequest", "start");
+    m_attributeSet.clear();
+
+    switch (request.getAppType()) {
+        case Request::APP_TYPE_TIZEN:
+            m_policy_to_use = PolicyType::Tizen;
+            LogDebug("==== Using Tizen policy ====");
+            break;
+        case Request::APP_TYPE_WAC20:
+            m_policy_to_use = PolicyType::WAC2_0;
+            LogDebug("==== Using WAC policy ====");
+            break;
+        default:
+            LogError("Unsupported(unknown) widget type. Access denied.");
+            return OptionalExtendedPolicyResult(
+                ExtendedPolicyResult(PolicyEffect::DENY));
+    }
+
+    try {
+        // Check which attributes should be used
+        // memory alocated, free in destructor
+        //ADD_PROFILING_POINT("getAttributes", "start");
+        AceDB::AceDAO::getAttributes(&m_attributeSet);
+        //ADD_PROFILING_POINT("getAttributes", "stop");
+
+        // If attributes can't be resolved then check the policy
+        if (!fillAttributeWithPolicy()) {
+            //ADD_PROFILING_POINT("getPolicyForRequest", "stop");
+            return OptionalExtendedPolicyResult(
+                ExtendedPolicyResult(PolicyEffect::DENY));
+        }
+
+        //ADD_PROFILING_POINT("getAttributesValues", "start");
+        m_pip->getAttributesValues(&request, &m_attributeSet);
+        //ADD_PROFILING_POINT("getAttributesValues", "stop");
+        LogDebug("==== Attributes set by PIP ====");
+        printAttributes(m_attributeSet);
+        LogDebug("==== End of attributes set by PIP ====");
+
+        OptionalExtendedPolicyResult policyResult = getPolicyForRequestInternal(
+                fromCacheOnly);
+
+        if (!policyResult) {
+            if (!fromCacheOnly) {
+                LogError("Policy evaluated to NULL value");
+                Assert(false && "Policy evaluated to NULL value");
+            }
+            return OptionalExtendedPolicyResult();
+        }
+        LogDebug("==== getPolicyForRequestInternal result (PolicyResult): "
+                 << policyResult->policyResult << "=====");
+
+        PreferenceTypes globalPreference =
+                SettingsLogic::findGlobalUserSettings(request);
+
+        auto ret = getMostRestrict(globalPreference, policyResult->policyResult);
+        //ADD_PROFILING_POINT("getPolicyForRequest", "stop");
+        return OptionalExtendedPolicyResult(
+            ExtendedPolicyResult(ret, policyResult->ruleId));
+
+    } catch (AceDB::AceDAO::Exception::DatabaseError &e) {
+        LogError("Database error");
+        DPL::Exception::DisplayKnownException(e);
+        //ADD_PROFILING_POINT("getPolicyForRequest", "stop");
+        return OptionalExtendedPolicyResult(
+            ExtendedPolicyResult(PolicyEffect::DENY));
+    }
+}
+
+bool PolicyEvaluator::extractAttributes(TreeNode* policyTree)
+{
+    if (NULL == policyTree) {
+        return false;
+    }
+
+    //We check if root target matches. In general the root's target should
+    //be empty. Otherwise it would have to have all the subjects available
+    //specified but just to be on the safe side (and for tests) this checking
+    const Policy * policy =
+            dynamic_cast<const Policy *>(policyTree->getElement());
+    Assert(policy != NULL
+                  && "Policy element has been null while attribute extracting");
+
+    extractTargetAttributes(policy);
+    extractAttributesFromSubtree(policyTree); //Enter recursion
+
+    return true;
+}
+
+void PolicyEvaluator::extractTargetAttributes(const Policy *policy)
+{
+    std::list<const Subject *>::const_iterator it =
+            policy->getSubjects()->begin();
+    for (; it != policy->getSubjects()->end(); ++it) {
+        const std::list<Attribute> & attrList = (*it)->getTargetAttributes();
+        FOREACH(it2, attrList)
+        {
+            BaseAttributePtr attr(
+                    new Attribute((*it2).getName(), (*it2).getMatchFunction(),
+                            (*it2).getType()));
+            m_attributeSet.insert(attr);
+        }
+    }
+}
+
+TreeNode * PolicyEvaluator::getCurrentPolicyTree()
+{
+    TreeNode * currentPolicy = NULL;
+    switch (m_policy_to_use) {
+    case PolicyType::Tizen: {
+        currentPolicy = m_tizen_policy;
+        break;}
+    case PolicyType::WAC2_0: {
+        currentPolicy = m_wac_policy;
+        break;}
+    default: {
+        LogError("Invalid policy type to use");}
+    }
+    return currentPolicy;
+}
+
+/**
+ *
+ * @param *root - the root of the original (full) subtree of politics
+ * @param *newRoot - the pointer to the root of the copy (reduced) subtree of politics
+ */
+void PolicyEvaluator::extractAttributesFromSubtree(const TreeNode *root)
+{
+    const ChildrenSet & children = root->getChildrenSet();
+
+    for (std::list<TreeNode *>::const_iterator it = children.begin();
+            it != children.end(); ++it) {
+        TreeNode * node = *it;
+        if (node->getTypeID() != TreeNode::Policy
+                && node->getTypeID() != TreeNode::PolicySet) {
+            //It is not a policy so we may be sure that we have already
+            //checked that SubjectId matches
+            //Add new node to new tree and extract attributes
+
+            extractAttributesFromRules(node);
+        } else { //TreeNode is a Policy or PolicySet
+            const Policy * policy =
+                    dynamic_cast<const Policy *>(node->getElement());
+                    //We will be needing also the attributes from target
+            if (policy) {
+                extractTargetAttributes(policy);
+            } else {
+                LogError(" extractAttributesFromSubtree policy=NULL");
+            }
+            //Enter recursion
+            extractAttributesFromSubtree(node);
+        }
+    }
+}
+
+bool PolicyEvaluator::extractAttributesFromRules(const TreeNode *root)
+{
+    Assert(root->getTypeID() == TreeNode::Rule
+       && "Tree structure, extracting attributes from node that is not a rule");
+    Rule * rule = dynamic_cast<Rule *>(root->getElement());Assert
+    (rule != NULL);
+    //Get attributes from rule
+    rule->getAttributes(&m_attributeSet);
+
+    //[CR] consider returned value, because its added only to eliminate errors
+    return true;
+}
+
+ExtendedEffect PolicyEvaluator::evaluatePolicies(const TreeNode * root)
+{
+    if (root == NULL) {
+        LogInfo("Error: policy tree doesn't exist. "
+                "Probably xml file is missing");
+        return Deny;
+    }
+
+    if (m_attributeSet.empty()) {
+        LogInfo("Warning: evaluatePolicies: attribute set was empty");
+    }
+    m_combiner->setAttributeSet(&m_attributeSet);
+    return m_combiner->combinePolicies(root);
+}
+
+
+int PolicyEvaluator::updatePolicy(const char* newPolicy)
+{
+    LogError("PolicyEvaluator::updatePolicy is DEPRECATED");
+    ConfigurationManager* configMgr = ConfigurationManager::getInstance();
+    if (NULL == configMgr) {
+        LogError("ACE fatal error: failed to create configuration manager");
+        return POLICY_PARSING_ERROR;
+    }
+    int result = POLICY_PARSING_SUCCESS;
+    if (newPolicy == NULL) {
+        LogError("Policy Update: incorrect policy name");
+        return POLICY_FILE_ERROR;
+    }
+    LogDebug("Starting update policy: " << newPolicy);
+
+    Parser parser;
+    TreeNode *backup = m_uniform_policy;
+
+    m_uniform_policy = parser.parse(newPolicy,
+            configMgr->getFullPathToPolicyXMLSchema());
+
+    if (NULL == m_uniform_policy) {
+        m_uniform_policy = backup;
+        LogError("Policy Update: corrupted policy file");
+        result = POLICY_PARSING_ERROR;
+    } else {
+        m_currentPolicyFile = newPolicy;
+        m_wac_policy = m_uniform_policy;  //we must be able to use WAC widgets
+        m_tizen_policy = m_uniform_policy;//we must be able to use Tizen widgets
+        m_attributeSet.clear();
+        backup->releaseResources();
+        LogInfo("Policy Update: successful.");
+        try {
+            AceDAO::resetDatabase();   // TODO: this is strange, but this
+                                       // method is deprecated so not changing
+                                       // it (will disappear with entire method)
+        } catch (AceDAO::Exception::DatabaseError &e) {
+        }
+    }
+    return result;
+}
+
+TreeNode * PolicyEvaluator::getDefaultSafePolicyTree(void)
+{
+    Policy * policy = new Policy;
+    Rule * rule = new Rule;
+    TreeNode * mainTree = NULL,
+             * childTree = NULL;
+
+    policy->setCombineAlgorithm(Policy::CombineAlgorithm::DenyOverride);
+    rule->setEffect(Deny);
+
+    mainTree = new TreeNode(m_uniform_policy, TreeNode::Policy, policy);
+    childTree = new TreeNode(mainTree, TreeNode::Rule, rule);
+    mainTree->addChild(childTree);
+
+    LogError("Loading default safe policy tree");
+    return mainTree;
+}
+
+void PolicyEvaluator::updatePolicy()
+{
+    ConfigurationManager *configMgr = ConfigurationManager::getInstance();
+    Assert(NULL != configMgr && "ACE fatal error: failed to "
+           "create configuration manager");
+    AceDAO::clearPolicyCache();
+    if (NULL != m_uniform_policy) {
+        m_uniform_policy->releaseResources();
+    }
+    Parser parserWac, parserTizen;
+    m_wac_policy = parserWac.parse(
+            configMgr->getFullPathToPolicyFile(PolicyType::WAC2_0),
+            configMgr->getFullPathToPolicyXMLSchema());
+    if (NULL == m_wac_policy) {
+        LogError("ACE fatal error: cannot parse XML file (WAC policy)");
+        m_wac_policy = getDefaultSafePolicyTree();
+    }
+    m_tizen_policy = parserTizen.parse(
+            configMgr->getFullPathToPolicyFile(PolicyType::Tizen),
+            configMgr->getFullPathToPolicyXMLSchema());
+    if (NULL == m_tizen_policy) {
+        LogError("ACE fatal error: cannot parse XML file (Tizen policy)");
+        m_tizen_policy = getDefaultSafePolicyTree();
+    }
+    // Policy set is usefull for releasing all policies in case of
+    // policy change
+    Policy * policySet = new PolicySet();
+    policySet->setCombineAlgorithm(Policy::CombineAlgorithm::DenyOverride);
+    m_uniform_policy = new TreeNode(NULL, TreeNode::PolicySet, policySet);
+    m_uniform_policy->addChild(m_wac_policy);
+    m_uniform_policy->addChild(m_tizen_policy);
+
+    // Creating attribute set for the first time after loading policy
+    // to speed up queries
+    m_attributeSet.clear();
+    fillAttributeWithPolicy();
+}
+
+std::string PolicyEvaluator::getCurrentPolicy()
+{
+    LogError("PolicyEvaluator::getCurrentPolicy is DEPRECATED");
+    return m_currentPolicyFile;
+}
+
+const char * toString(Validity validity)
+{
+    switch (validity) {
+    case Validity::ONCE:
+        return "Once";
+        break;
+    case Validity::SESSION:
+        return "Session";
+    case Validity::ALWAYS:
+        return "Always";
+    default:
+        return "WRONG VALIDITY";
+    }
+}
+
+const char * toString(Verdict verdict)
+{
+    switch (verdict) {
+    case Verdict::VERDICT_PERMIT:
+        return "Permit";
+    case Verdict::VERDICT_DENY:
+        return "Deny";
+    case Verdict::VERDICT_INAPPLICABLE:
+        return "Inapplicable";
+    case Verdict::VERDICT_UNKNOWN:
+        return "Unknown";
+    case Verdict::VERDICT_UNDETERMINED:
+        return "Undetermined";
+    case Verdict::VERDICT_ERROR:
+        return "Error";
+    case Verdict::VERDICT_ASYNC:
+        return "Async";
+    default:
+        return "Wrong verdict value";
+    }
+}
diff --git a/ace/engine/PolicyInformationPoint.cpp b/ace/engine/PolicyInformationPoint.cpp
new file mode 100644 (file)
index 0000000..b273809
--- /dev/null
@@ -0,0 +1,278 @@
+/*
+ * 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.
+ */
+//
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : PolicyInformationPoint.cpp
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+#include <map>
+#include <string>
+#include <list>
+
+#include <ace/PolicyInformationPoint.h>
+#include <ace/ConfigurationManager.h>
+
+#include <dpl/log/log.h>
+#include <dpl/assert.h>
+#include <dpl/foreach.h>
+
+#include <ace/Attribute.h>
+#include <ace-dao-ro/BaseAttribute.h>
+#include <ace-dao-ro/AceDAOReadOnly.h>
+
+using namespace AceDB;
+
+PolicyInformationPoint::PolicyInformationPoint(IWebRuntime *wrt,
+        IResourceInformation *resource,
+        IOperationSystem *system) : wrtInterface(wrt),
+    resourceInformation(resource),
+    operationSystem(system)
+{
+    AceDB::AceDAOReadOnly::attachToThreadRO();
+}
+
+PolicyInformationPoint::~PolicyInformationPoint()
+{
+    AceDB::AceDAOReadOnly::detachFromThread();
+}
+
+/* gather attributes values from adequate interfaces */
+PipResponse PolicyInformationPoint::getAttributesValues(const Request* request,
+        AttributeSet* attributes)
+{
+    int subjectReturn = 0;
+    int resourceReturn = 0;
+    int operationReturn = 0;
+    int functionReturn = 0;
+    /* create query lists  */
+    createQueries(attributes);
+
+    /* check if subject attributes query has any elements*/
+    if (!subjectAttributesQuery.empty()) {
+        /* get Subject Attributes */
+        subjectReturn = wrtInterface->getAttributesValues(
+                *request,
+                &subjectAttributesQuery);
+    }
+
+    AttributeSet::const_iterator iter2;
+    FOREACH(iter, subjectAttributesQuery)
+    {
+        if (iter->second == NULL) {
+            Attribute attr(*(iter->first));
+            attr.setType(Attribute::Type::Subject);
+            iter2 = std::find_if(attributes->begin(),
+                                 attributes->end(),
+                                 BaseAttribute::UnaryPredicate(&attr));
+            Assert(iter2 != attributes->end() && "This should not happen, "
+                   "the attribute MUST be in attribute set");
+            (*iter2)->setUndetermind(true);
+        }
+    }
+
+    /* check if resource  attributes query has any elements*/
+    if (!resourceAttributesQuery.empty()) {
+        /* get Resource Attributes */
+        resourceReturn = resourceInformation->getAttributesValues(
+                *request,
+                &resourceAttributesQuery);
+        /* error analyzys*/
+        resourceReturn <<= ERROR_SHIFT_RESOURCE;
+    }
+
+    FOREACH(iter, resourceAttributesQuery)
+    {
+        if (iter->second == NULL) {
+            LogInfo("Found undetermined attribute");
+            Attribute attr(*(iter->first));
+            attr.setType(Attribute::Type::Resource);
+            iter2 = std::find_if(attributes->begin(),
+                                 attributes->end(),
+                                 BaseAttribute::UnaryPredicate(&attr));
+            Assert(iter2 != attributes->end() && "This should not happen, "
+                   "the attribute MUST be in attribute set");
+            (*iter2)->setUndetermind(true);
+        }
+    }
+
+    /* check if resource  attributes query has any elements*/
+    if (!environmentAttributesQuery.empty()) {
+        /* get enviroment attributes  */
+        operationReturn = operationSystem->getAttributesValues(
+                *request,
+                &environmentAttributesQuery);
+        /* error analyzys*/
+        operationReturn <<= ERROR_SHIFT_OS;
+    }
+
+    FOREACH(iter, environmentAttributesQuery)
+    {
+        if (iter->second == NULL) {
+            //it doesnt change uniqueness of a set element so we can const_cast
+            Attribute attr(*(iter->first));
+            attr.setType(Attribute::Type::Environment);
+            iter2 = find_if(attributes->begin(),
+                            attributes->end(),
+                            BaseAttribute::UnaryPredicate(&attr));
+            Assert(iter2 != attributes->end() && "This should not happen, "
+                   "the attribute MUST be in attribute set");
+            (*iter2)->setUndetermind(true);
+        }
+    }
+
+    /* check if functionParam attributes query has any elements*/
+    if (!functionParamAttributesQuery.empty() && request->getFunctionParam()) {
+        /* get params attributes  */
+        functionReturn = request->getFunctionParam()->getAttributesValues(
+                *request,
+                &functionParamAttributesQuery);
+        /* error analyzys*/
+        functionReturn <<= ERROR_SHIFT_FP;
+    }
+
+    FOREACH(iter, functionParamAttributesQuery)
+    {
+        if (iter->second == NULL) {
+            //it doesnt change uniqueness of a set element so we can const_cast
+            Attribute attr(*(iter->first));
+            attr.setType(Attribute::Type::FunctionParam);
+            iter2 = find_if(attributes->begin(),
+                            attributes->end(),
+                            BaseAttribute::UnaryPredicate(&attr));
+            Assert(iter2 != attributes->end() && "This should not happen, "
+                   "the attribute MUST be in attribute set");
+            (*iter2)->setUndetermind(true);
+        }
+    }
+
+    // Here we must add to attributes proper marking of policy type
+    // (Tizen or WAC widget)
+    /**
+     * This part of code seems odd here, but we don't want to keep it in
+     * attribute fascade, as it is maintained by ACE clients and we are not
+     * sure if this kind of distinction between different policies will be ok
+     * as final solution.
+     *
+     * This is somehow private part of ACE, so it may be moved into
+     * separate ACEAttributeFascade kind of a class in (already planned)
+     * refactoring, when moving to new, C-only API for ACE.
+     */
+    if (widgetParamAttributesQuery.empty()) {
+        LogError("No attrbutes of WidgetParam type present - "
+                 "should be widget type at least");
+    } else {
+        LogDebug("WidgetParam type atributes present, searching for widget type");
+        FOREACH(iter, widgetParamAttributesQuery) {
+            const std::string *name = iter->first;
+            if (POLICY_WIDGET_TYPE_ATTRIBUTE_NAME == *name) {
+                LogDebug("Widget type attribute found");
+
+                // Extracting widget type
+                std::list<std::string> attrValue;
+                Try {
+                    AceDB::AppTypes appType =
+                        AceDB::AceDAOReadOnly::getWidgetType(
+                            request->getWidgetHandle());
+                    switch (appType) {
+                    case AceDB::AppTypes::Tizen : {
+                        attrValue.push_back(POLICY_NAME_TIZEN);
+                        LogDebug("==== Using Tizen policy in PIP ====");
+                        break;}
+                    case AceDB::AppTypes::WAC20 : {
+                        attrValue.push_back(POLICY_NAME_WAC2_0);
+                        LogDebug("==== Using WAC policy in PIP ====");
+                        break;}
+                    default: {
+                        LogError("Invalid widget type");
+                        }
+                    }
+                } Catch (AceDB::AceDAOReadOnly::Exception::DatabaseError)
+                {
+                    LogError("Couldn't find widget for handle "
+                             << request->getWidgetHandle());
+                }
+
+                // Setting real attribute value
+                Attribute attr(*(iter->first));
+                attr.setType(Attribute::Type::WidgetParam);
+                iter2 = find_if(attributes->begin(),
+                                attributes->end(),
+                                BaseAttribute::UnaryPredicate(&attr));
+                Assert(iter2 != attributes->end() && "This should not happen, "
+                       "the attribute MUST be in attribute set");
+                (*iter2)->setUndetermind(false);
+                (*iter2)->setValue(attrValue);
+            }
+        }
+    }
+
+    /** clear query lists*/
+    resourceAttributesQuery.clear();
+    environmentAttributesQuery.clear();
+    subjectAttributesQuery.clear();
+    functionParamAttributesQuery.clear();
+    widgetParamAttributesQuery.clear();
+
+    return subjectReturn | resourceReturn | operationReturn | functionReturn;
+}
+
+/** create query lists */
+void PolicyInformationPoint::createQueries(AttributeSet* attributes)
+{
+    AttributeSet::const_iterator it;
+
+    enum Attribute::Type type;
+
+    /**iterate  all attributes and split them into adequate query  */
+    FOREACH (it, *attributes) {
+        type = (*it)->getType();
+
+        switch (type) {
+        case Attribute::Type::Subject:
+            subjectAttributesQuery.push_back(ATTRIBUTE((*it)->getName(),
+                                                       (*it)->getValue()));
+            break;
+
+        case Attribute::Type::Environment:
+            environmentAttributesQuery.push_back(ATTRIBUTE((*it)->getName(),
+                                                           (*it)->getValue()));
+            break;
+
+        case Attribute::Type::Resource:
+            resourceAttributesQuery.push_back(ATTRIBUTE((*it)->getName(),
+                                                        (*it)->getValue()));
+            break;
+
+        case Attribute::Type::FunctionParam:
+            functionParamAttributesQuery.push_back(ATTRIBUTE((*it)->getName(),
+                                                             (*it)->getValue()));
+            break;
+
+        case Attribute::Type::WidgetParam:
+            widgetParamAttributesQuery.push_back(ATTRIBUTE((*it)->getName(),
+                                                         (*it)->getValue()));
+            break;
+        default:
+            break;
+        }
+    }
+}
+
diff --git a/ace/engine/Rule.cpp b/ace/engine/Rule.cpp
new file mode 100644 (file)
index 0000000..c1703bb
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ * 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.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : Rule.h
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+
+#include <iostream>
+#include <dpl/log/log.h>
+
+#include <ace/Rule.h>
+
+void Rule::printData()
+{
+    std::cout << "Rule: effect: " << printEffect(this->effect) <<
+    " condition: " << this->condition;
+}
+
+std::string Rule::printEffect(const ExtendedEffect &effect) const
+{
+    switch (effect.getEffect()) {
+    case Deny:
+        return "Deny";
+    case PromptBlanket:
+        return "PromptBlanket";
+    case PromptOneShot:
+        return "PromptOneShot";
+    case PromptSession:
+        return "PromptSession";
+    case Permit:
+        return "Permit";
+    case Inapplicable:
+        return "Inapplicable";
+    case Error:
+        return "Error";
+    default:
+        return "ERROR";
+    }
+}
+
+ExtendedEffect Rule::evaluateRule(const AttributeSet * attrSet) const
+{
+    Attribute::MatchResult result = condition.evaluateCondition(attrSet);
+
+    if (result == Attribute::MatchResult::MRUndetermined) {
+        //        LogInfo("Rule is undetermined");
+        return ExtendedEffect(Undetermined);
+    } else if (result == Attribute::MatchResult::MRTrue) {
+        //       LogInfo("Rule effect "<<printEffect(effect));
+        return effect;
+    }
+    // LogInfo("Rule is inapplicable");
+    return Inapplicable;
+}
+
+
diff --git a/ace/engine/SettingsLogic.cpp b/ace/engine/SettingsLogic.cpp
new file mode 100644 (file)
index 0000000..2a19ce6
--- /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       SettingsLogic.cpp
+ * @author     Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version    0.1
+ * @brief      SettingsLogic implementation
+ */
+
+#include <ace/SettingsLogic.h>
+
+#include <dpl/log/log.h>
+#include <dpl/foreach.h>
+
+#include <ace/Preference.h>
+
+using namespace AceDB;
+
+Preference SettingsLogic::findGlobalUserSettings(
+        const std::string &resource,
+        WidgetHandle handler)
+{
+    Preference p = AceDAO::getWidgetDevCapSetting(resource, handler);
+    if (PreferenceTypes::PREFERENCE_DEFAULT == p) {
+        return AceDAO::getDevCapSetting(resource);
+    } else {
+        return p;
+    }
+}
+
+Preference SettingsLogic::findGlobalUserSettings(
+        const Request &request)
+{
+    Request::DeviceCapabilitySet devset = request.getDeviceCapabilitySet();
+    Assert(!devset.empty() && "No device cap set in request");
+    return findGlobalUserSettings(
+        *(devset.begin()),
+        request.getWidgetHandle());
+}
+
+Preference SettingsLogic::getDevCapSetting(const std::string &resource)
+{
+    return AceDAO::getDevCapSetting(resource);
+}
+
+void SettingsLogic::getDevCapSettings(PreferenceMap *globalSettingsMap)
+{
+    AceDAO::getDevCapSettings(globalSettingsMap); // NULL check inside
+}
+
+
+void SettingsLogic::setDevCapSetting(const std::string &resource,
+                                       Preference preference)
+{
+    if (resource.empty()) {
+        LogInfo("WARNING: setting resource settings for empty resource name");
+    }
+
+    AceDAO::addResource(resource);
+
+    if (preference == PreferenceTypes::PREFERENCE_DEFAULT) {
+        return;
+    }
+
+    Assert((PreferenceTypes::PREFERENCE_PERMIT == preference ||
+            PreferenceTypes::PREFERENCE_DENY == preference ||
+            PreferenceTypes::PREFERENCE_BLANKET_PROMPT == preference ||
+            PreferenceTypes::PREFERENCE_ONE_SHOT_PROMPT == preference ||
+            PreferenceTypes::PREFERENCE_SESSION_PROMPT == preference));
+
+    AceDAO::setDevCapSetting(resource,preference);
+}
+
+void SettingsLogic::setAllDevCapSettings(
+    const std::list < std::pair < const std::string*,
+    Preference > > &resourcesList)
+{
+    std::list < std::pair < const std::string*,
+        Preference > >::const_iterator iter;
+    for (iter = resourcesList.begin(); iter != resourcesList.end(); ++iter) {
+        SettingsLogic::setDevCapSetting(*(iter->first), iter->second);
+    }
+}
+
+void SettingsLogic::removeDevCapSetting(const std::string &resource)
+{
+    AceDAO::removeDevCapSetting(resource);
+}
+
+void SettingsLogic::updateDevCapSetting(const std::string &resource,
+                                        Preference p)
+{
+    if (PreferenceTypes::PREFERENCE_DEFAULT == p) {
+        SettingsLogic::removeDevCapSetting(resource);
+    } else {
+        SettingsLogic::setDevCapSetting(resource, p);
+    }
+}
+
+Preference SettingsLogic::getWidgetDevCapSetting(
+        const std::string &resource,
+        WidgetHandle handler)
+{
+    return AceDAO::getWidgetDevCapSetting(resource, handler);
+}
+
+void SettingsLogic::getWidgetDevCapSettings(PermissionList *outputList)
+{
+    AceDAO::getWidgetDevCapSettings(outputList); // NULL check inside
+}
+
+
+void SettingsLogic::setWidgetDevCapSetting(
+        const std::string &resource,
+        WidgetHandle handler,
+        Preference preference)
+{
+    if (resource.empty()) {
+        LogError("Empty resource");
+        return;
+    }
+
+    LogDebug("userSetting, resource: " << resource <<
+             " app_id: " << handler);
+
+    AceDAO::addResource(resource);
+    SettingsLogic::removeWidgetDevCapSetting(resource, handler);
+
+    if (PreferenceTypes::PREFERENCE_DEFAULT == preference) {
+        return;
+    }
+
+    Assert((PreferenceTypes::PREFERENCE_PERMIT == preference ||
+            PreferenceTypes::PREFERENCE_DENY == preference ||
+            PreferenceTypes::PREFERENCE_BLANKET_PROMPT == preference ||
+            PreferenceTypes::PREFERENCE_ONE_SHOT_PROMPT == preference ||
+            PreferenceTypes::PREFERENCE_SESSION_PROMPT == preference));
+
+    AceDAO::setWidgetDevCapSetting(resource, handler, preference);
+}
+
+
+void SettingsLogic::setWidgetDevCapSettings(const PermissionList &permissionsList)
+{
+    FOREACH(i, permissionsList) {
+        SettingsLogic::setWidgetDevCapSetting(i->devCap,
+                i->appId,
+                i->access);
+    }
+}
+
+
+void SettingsLogic::removeWidgetDevCapSetting(const std::string &resource,
+                                              WidgetHandle handler)
+{
+    AceDAO::removeWidgetDevCapSetting(resource, handler);
+}
diff --git a/ace/engine/Subject.cpp b/ace/engine/Subject.cpp
new file mode 100644 (file)
index 0000000..57724be
--- /dev/null
@@ -0,0 +1,65 @@
+/*
+ * 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/log/log.h>
+#include <dpl/foreach.h>
+
+#include <ace/Subject.h>
+
+bool Subject::matchSubject(const AttributeSet *attrSet,
+        bool &isUndetermined) const
+{
+    bool result = true;
+    Attribute::MatchResult match = Attribute::MatchResult::MRUndetermined;
+
+    FOREACH(it, targetAttributes)
+    {
+        AttributeSet::const_iterator attr =
+            std::find_if(attrSet->begin(),
+                         attrSet->end(),
+                         AceDB::BaseAttribute::UnaryPredicate(&(*it)));
+        if (attr == attrSet->end()) {
+            LogError("Cannot find attribute value for " << *(it->getName()));
+            Assert(false &&
+                   "Attribute for subject hasn't been found."
+                   "It shoud not happen. This attribute should be undetermined,"
+                   "not missing");
+            result = false; //According to BONDI 1.0 for signle subject all attributes must match
+            isUndetermined = true;
+            break;
+        }
+
+        match = it->matchAttributes(&(*(*attr)));
+
+        if (match == Attribute::MatchResult::MRUndetermined) {
+            result = false;
+            isUndetermined = true;
+            ///          LogError("Subject doesn match and UNDETERMINED");
+            break; //According to BONDI 1.0 for signle subject all attributes must match
+        } else if (match == Attribute::MatchResult::MRFalse) {
+            result = false;
+            //            LogError("Subject doesn match and DETERMINED");
+            break; //According to BONDI 1.0 for signle subject all attributes must match
+        }
+    }
+
+    return result;
+}
+
+const std::list<Attribute>& Subject::getTargetAttributes() const
+{
+    return targetAttributes;
+}
+
diff --git a/ace/engine/TreeNode.cpp b/ace/engine/TreeNode.cpp
new file mode 100644 (file)
index 0000000..0171f4d
--- /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.
+ */
+#include <ace/TreeNode.h>
+#include <dpl/assert.h>
+#include <dpl/log/log.h>
+
+//Tree node destructor is a tricky part, only the original tree should remove the elements
+//release resources should be called when we want to destroy the whole tree
+TreeNode::~TreeNode()
+{
+    delete element;
+}
+
+//TODO release resources is releaseTheSubtree and delete the element
+void TreeNode::releaseResources()
+{
+    Assert(this != 0);
+    delete element;
+    std::list<TreeNode*>::iterator it = this->children.begin();
+    while (it != children.end()) {
+        (*it)->releaseResources();
+        ++it;
+    }
+    delete this;
+}
+
+int TreeNode::level = 0;
+
+std::ostream & operator<<(std::ostream & out,
+        const TreeNode * node)
+{
+    std::string tmp;
+
+    switch (node->getTypeID()) {
+    case TreeNode::Policy:
+        tmp = "Policy";
+        break;
+    case TreeNode::PolicySet:
+        tmp = "PolicySet";
+        break;
+    case TreeNode::Rule:
+        tmp = "Rule";
+        break;
+    default:
+        break;
+    }
+
+    out << "" << tmp << "-> children count: " << node->children.size() <<
+    ": " << std::endl;
+    AbstractTreeElement * el = node->getElement();
+    if (el != NULL) {
+        el->printData();
+    } else {
+        std::cout << "Empty element!" << std::endl;
+    }
+
+    return out;
+}
+
diff --git a/ace/engine/parser.cpp b/ace/engine/parser.cpp
new file mode 100644 (file)
index 0000000..9447d24
--- /dev/null
@@ -0,0 +1,766 @@
+/*
+ * 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 <memory>
+#include <functional>
+#include <string.h>
+#include <stdarg.h>
+#include <dpl/log/log.h>
+
+#include <ace/parser.h>
+#include <string.h>
+
+namespace {
+
+class ParserWarningLogger
+{
+  public:
+    void operator()(const std::string& logMsg)
+    {
+        LogWarning(logMsg);
+    }
+};
+
+class ParserErrorLogger
+{
+  public:
+    void operator()(const std::string& logMsg)
+    {
+        LogError(logMsg);
+    }
+};
+
+template <class Logger>
+void xmlLogFunction(void* /*ctx*/, const char *msg, ...)
+{
+    const int BUFFER_SIZE = 1024;
+    char buffer[BUFFER_SIZE];
+    buffer[BUFFER_SIZE - 1] = '\0';
+    Logger l;
+
+    va_list va;
+    va_start(va, msg);
+    vsnprintf(buffer, BUFFER_SIZE - 1, msg, va);
+    va_end(va);
+
+    std::string logmsg(buffer);
+    l(logmsg);
+}
+
+}
+
+const char *Parser::TOKEN_PARAM = "param:";
+
+Parser::Parser() :
+    ruleId(0),
+    reader(NULL),
+    root(NULL),
+    currentRoot(NULL),
+    currentSubject(NULL),
+    currentCondition(NULL),
+    currentAttribute(NULL),
+    currentText(NULL),
+    processingSignature(false),
+    canonicalizeOnce(false)
+{
+    processingSignature = true;
+    canonicalizeOnce = true;
+}
+
+Parser::~Parser()
+{
+    /* parse function destroys reader */
+    //  free(this->xmlFilename);
+}
+
+TreeNode* Parser::parse(const std::string& filename, const std::string& schema)
+{
+    if(root != NULL) {
+        root->releaseResources();
+        root = NULL;
+    }
+
+    LogDebug("Parser: opening file " << filename);
+
+    xmlDocPtr xmlDocument = xmlParseFile(filename.c_str());
+    if (!xmlDocument) {
+        LogError("Couldn't parse file " << filename);
+        return root;
+    }
+
+    std::unique_ptr <xmlDoc, std::function<void(xmlDoc*)> >
+        doc(xmlDocument, xmlFreeDoc);
+
+    xmlSchemaParserCtxtPtr xmlSchemaParserContext =
+        xmlSchemaNewParserCtxt(schema.c_str());
+
+    if (!xmlSchemaParserContext) {
+        LogError("Couldn't load xml schema: " << schema);
+        return root;
+    }
+
+    std::unique_ptr <
+                     xmlSchemaParserCtxt,
+                     std::function<void(xmlSchemaParserCtxt*)> >
+                     schemaContext(
+                                   xmlSchemaParserContext,
+                                   xmlSchemaFreeParserCtxt);
+
+    LogDebug("Setting callbacks");
+
+    xmlSchemaSetParserErrors(
+        schemaContext.get(),
+        static_cast<xmlValidityErrorFunc>
+            (&xmlLogFunction<ParserErrorLogger>),
+        static_cast<xmlValidityWarningFunc>
+            (&xmlLogFunction<ParserWarningLogger>),
+        NULL);
+
+    xmlSchemaPtr xmlSchema = xmlSchemaParse(schemaContext.get());
+
+    if (!xmlSchema) {
+        LogError("Couldn't parse xml schema: " << xmlSchema);
+        return root;
+    }
+
+    xmlSchemaValidCtxtPtr xmlValidContext = xmlSchemaNewValidCtxt(xmlSchema);
+
+    if (!xmlValidContext) {
+        LogError("Couldn't create validation context!");
+        xmlSchemaFree(xmlSchema);
+        return root;
+    }
+
+    std::unique_ptr <
+                     xmlSchemaValidCtxt,
+                     std::function<void(xmlSchemaValidCtxt*)> >
+                     schemaValidContext(
+                                        xmlValidContext,
+                                        xmlSchemaFreeValidCtxt);
+
+    xmlSchemaSetValidErrors(
+        schemaValidContext.get(),
+        static_cast<xmlValidityErrorFunc>
+            (&xmlLogFunction<ParserErrorLogger>),
+        static_cast<xmlValidityWarningFunc>
+            (&xmlLogFunction<ParserWarningLogger>),
+        NULL);
+
+    xmlSchemaSetValidOptions(
+                             schemaValidContext.get(),
+                             XML_SCHEMA_VAL_VC_I_CREATE);
+
+    bool result =
+        (xmlSchemaValidateDoc(
+                              schemaValidContext.get(),
+                              xmlDocument) == 0 ? true : false);
+
+    xmlSchemaFree(xmlSchema);
+
+    if (!result) {
+        LogError("Couldn't validate policy file: " << filename <<
+                 " against xml schema: " << schema);
+
+        return root;
+    }
+
+    LogInfo("Policy file: " << filename << " validated!");
+
+    xmlTextReaderPtr xmlReader = xmlReaderWalker(xmlDocument);
+
+    //[CR] consider using ASSERT/DASSERT
+    if (NULL == xmlReader) {
+        LogError("Error, xml reader cannot be created. Probably xml file is missing (opening file " << filename << ")");
+        return root;
+    }
+
+    std::unique_ptr <xmlTextReader, std::function<void(xmlTextReader*)> >
+         reader(xmlReader, xmlFreeTextReader);
+
+    int ret;
+    ret = xmlTextReaderRead(reader.get());
+    while (ret == 1) {
+        std::unique_ptr<xmlChar, std::function<void(xmlChar*)> >
+            name(xmlTextReaderName(reader.get()), xmlFree);
+
+        if (!strcmp("policy-set", (const char *)name.get())) {
+            processingSignature = false;
+        } else if (!strcmp("SignedInfo",
+                           (const char *)name.get()) && canonicalizeOnce) {
+            #if 0 //TODO I think we don't need canonicalization in ACE only in PM,
+            //we have to  verify it tough
+            extractNodeToFile(reader, "output.xml");
+            //TODO we should be able to handle more than one canonicalization algorithm
+            canonicalize("output.xml", "canon.xml", Canonicalization::C14N);
+            canonicalizeOnce = false;
+            #endif
+        }
+        //Do not process signature of xml file
+        if(!processingSignature) {
+            processNode(reader.get());
+        }
+        ret = xmlTextReaderRead(reader.get());
+    }
+
+    if (ret != 0) {
+        LogError("Error while parsing XML file");
+        if (root) {
+            root->releaseResources();
+            root = NULL;
+        }
+    }
+
+    return root;
+}
+
+void Parser::processNode(xmlTextReaderPtr reader)
+{
+    //TODO this is interesting, xmlTextReaderNodeType returns int but I am pretty sure
+    //those integers coresponds to xmlReaderTypes
+    xmlReaderTypes type =
+        static_cast<xmlReaderTypes>(xmlTextReaderNodeType(reader));
+
+    switch (type) {
+    //Start element
+    case XML_READER_TYPE_ELEMENT:
+        startNodeHandler(reader);
+        break;
+    //End element
+    case XML_READER_TYPE_END_ELEMENT:
+        endNodeHandler(reader);
+        break;
+    //Text element
+    case XML_READER_TYPE_TEXT:
+        textNodeHandler(reader);
+        break;
+    default:
+        //Do not handle other xml tags
+        break;
+    }
+}
+
+void Parser::startNodeHandler(xmlTextReaderPtr reader)
+{
+    xmlChar *name = xmlTextReaderName(reader);
+
+    Assert(name != NULL && "xml is corrupted");
+    if (name == NULL)
+        return;
+
+    switch (*name) {
+    case 'p':     //policy and policy-set
+        if (*(name + 6) == 0) {
+            handlePolicy(reader, TreeNode::Policy);
+        } else {
+            handlePolicy(reader, TreeNode::PolicySet);
+        }
+        break;
+    case 'r':     //rule and resource-match
+        if (*(name + 1) == 'u') {
+            handleRule(reader);
+        } else if (*(name + 9) == 'm') {
+            handleMatch(reader, Attribute::Type::Resource);
+        } else {
+            handleAttr(reader);
+        }
+        break;
+    case 's':     //subject and subject-match
+        if (*(name + 7) == 0) {
+            handleSubject();
+        } else if (*(name + 8) == 'm') { //subject match
+            handleSubjectMatch(reader);
+        } else {  //subject attr
+            handleAttr(reader);
+        }
+        break;
+    case 'c':    //condition
+        handleCondition(reader);
+        break;
+    case 'e':    //environment-match
+        if (*(name + 12) == 'm') {
+            handleMatch(reader, Attribute::Type::Environment);
+        } else {  //env-attr
+            handleAttr(reader);
+        }
+        break;
+    }
+    xmlFree(name);
+}
+
+void Parser::endNodeHandler(xmlTextReaderPtr reader)
+{
+    xmlChar *name = xmlTextReaderName(reader);
+
+    Assert(name != NULL && "xml file corrupted");
+    if (name == NULL) return;
+
+    switch (*name) {
+    case 'p':     //policy and policy-set
+        //Restore old root
+        currentRoot = currentRoot->getParent();
+        break;
+    case 'r':     //Rule and resource match
+        if (*(name + 1) == 'u') { //Rule
+            currentRoot = currentRoot->getParent();
+        } else {  //Resource-match
+            consumeCurrentText();     //consume text if any available
+            consumeCurrentAttribute();     //consume attribute
+        }
+        break;
+    case 's':     //subject and subject-match
+        if (*(name + 7) == 0) { //handle subject
+            consumeCurrentSubject();
+        } else if (*(name + 8) == 'm') { //handle subject match
+            consumeCurrentText();
+            consumeSubjectMatch();
+        }
+        //Subject-match end doesn't require handling
+        break;
+    case 'c':    //condition
+        consumeCurrentCondition();
+        break;
+    case 'e':    //environment-match
+        consumeCurrentText();     //consume text if any available
+        consumeCurrentAttribute();     //consume attribute
+        break;
+    }
+    xmlFree(name);
+}
+
+void Parser::textNodeHandler(xmlTextReaderPtr reader)
+{
+    delete currentText;
+    xmlChar * text = xmlTextReaderValue(reader);
+    Assert(text != NULL && "Parser couldn't parse PCDATA");
+
+    currentText = new std::string(reinterpret_cast<const char * >(text));
+    trim(currentText);
+    xmlFree(text);
+}
+
+void Parser::handlePolicy(xmlTextReaderPtr reader,
+        TreeNode::TypeID type)
+{
+    Policy::CombineAlgorithm algorithm;
+
+    //Get first attribute
+    xmlChar * combAlg = xmlTextReaderGetAttribute(reader, BAD_CAST("combine"));
+
+    Assert(combAlg != NULL && "Parser error while getting attributes");
+    algorithm = convertToCombineAlgorithm(combAlg);
+
+    //Create TreeNode element
+    Policy * policy = NULL;
+    if (type == TreeNode::Policy) {
+        policy = new Policy();
+    } else {
+        policy = new PolicySet();
+    }
+    policy->setCombineAlgorithm(algorithm);
+    TreeNode * node = new TreeNode(currentRoot, type, policy);
+    //Add new tree node to current's root children set
+    if (currentRoot != NULL) {
+        currentRoot->addChild(node);
+    }
+
+    //Switch the current root to the new node
+    if (!xmlTextReaderIsEmptyElement(reader)) {
+        //Current root switching is necessary only if tag is not empty
+        currentRoot = node;
+    }
+    if (root == NULL) {
+        root = currentRoot;
+    }
+
+    if (NULL == currentRoot) {
+        node->releaseResources();
+    }
+
+    xmlFree(combAlg);
+}
+
+void Parser::handleRule(xmlTextReaderPtr reader)
+{
+    ExtendedEffect effect(Inapplicable);
+
+    //[CR] create macros for attribute names
+    xmlChar * eff = xmlTextReaderGetAttribute(reader, BAD_CAST("effect")); //get the rule attribute
+
+    Assert(eff != NULL && "Parser error while getting attributes");
+    effect = convertToEffect(eff);
+
+    Rule * rule = NULL;
+    rule = new Rule();
+    rule->setEffect(effect);
+
+    TreeNode * node = new TreeNode(currentRoot, TreeNode::Rule, rule);
+    //Add new tree node to current's root children set
+    if (currentRoot != NULL) { //
+        currentRoot->addChild(node);
+    }
+
+    if (!xmlTextReaderIsEmptyElement(reader)) {
+        currentRoot = node;
+    }
+
+    if (NULL == currentRoot) {
+        node->releaseResources();
+    }
+
+    xmlFree(eff);
+}
+
+void Parser::handleSubject()
+{
+    currentSubject = new Subject();
+    //TODO what about empty subject tag
+}
+
+void Parser::handleCondition(xmlTextReaderPtr reader)
+{
+    Condition::CombineType combineType = Condition::AND;
+
+    xmlChar * combine = xmlTextReaderGetAttribute(reader, BAD_CAST("combine")); //get the rule attribute
+
+    Assert(combine != NULL && "Parser error while getting attributes");
+
+    combineType = *combine == 'a' ? Condition::AND : Condition::OR;
+
+    Condition * condition = new Condition();
+    condition->setCombineType(combineType);
+    condition->setParent(currentCondition);
+
+    currentCondition = condition;
+    xmlFree(combine);
+    //TODO what about empty condition tag?
+}
+
+//Subject match is handled differently than resource or environment match
+//Because it cannot have any children tags and can only include PCDATA
+void Parser::handleSubjectMatch(xmlTextReaderPtr reader)
+{
+    //processing Subject
+    int attributes = xmlTextReaderAttributeCount(reader);
+
+    xmlChar * func = NULL;
+    xmlChar * value = NULL;
+    xmlChar * attrName = xmlTextReaderGetAttribute(reader, BAD_CAST("attr")); //get the first attribute
+
+    if (attributes == 2) {
+        //match attribute ommited, text value will be used
+        func = xmlTextReaderGetAttribute(reader, BAD_CAST("func"));
+    } else if (attributes == 3) {
+        value = xmlTextReaderGetAttribute(reader, BAD_CAST("match"));
+        func = xmlTextReaderGetAttribute(reader, BAD_CAST("func"));
+    } else {
+        Assert(false && "Wrong XML file format");
+    }
+
+    // creating temporiary object is not good idea
+    // but we have no choice untill Attribute have constructor taking std::string*
+    Assert(attrName != NULL && "XML file format is wrong");
+
+    Attribute *attr;
+    if (attrName != NULL) {
+        std::string temp(reinterpret_cast<const char *>(attrName));
+        attr = new Attribute(&temp, convertToMatchFunction(
+                    func), Attribute::Type::Subject);
+    }
+
+    if (value != NULL) { //add value of the attribute if possible
+        //[CR] consider create Attribute::addValue(char *) function
+        std::string temp(reinterpret_cast<const char *>(value));
+        attr->addValue(&temp);
+    }
+    currentAttribute = attr;
+
+    if (xmlTextReaderIsEmptyElement(reader)) {
+        Assert(value != NULL && "XML file format is wrong");
+        //Attribute value is required to obtain the match value easier
+        consumeSubjectMatch(value);
+    }
+
+    if (attributes == 2 || attributes == 3) {
+        xmlFree(func);
+    }
+    xmlFree(value);
+    xmlFree(attrName);
+}
+
+void Parser::handleMatch(xmlTextReaderPtr reader,
+        Attribute::Type type)
+{
+    int attributes = xmlTextReaderAttributeCount(reader);
+
+    xmlChar * func = NULL;
+    xmlChar * value = NULL;
+    xmlChar * attrName = xmlTextReaderGetAttribute(reader, BAD_CAST("attr")); //get the first attribute
+
+    if (attributes == 2) {
+        //match attribute ommited, text value will be used
+        func = xmlTextReaderGetAttribute(reader, BAD_CAST("func"));
+        //the content may be resource-attr or PCDATA
+    } else if (attributes == 3) {
+        value = xmlTextReaderGetAttribute(reader, BAD_CAST("match"));
+        func = xmlTextReaderGetAttribute(reader, BAD_CAST("func"));
+    } else {
+        Assert(false && "Wrong XML file format");
+    }
+
+    // FunctionParam type is sybtype of Resource.
+    // FunctionParam is used to storage attriburess of call functions.
+    if (0 ==
+        xmlStrncmp(attrName, BAD_CAST(TOKEN_PARAM),
+                   xmlStrlen(BAD_CAST(TOKEN_PARAM))) && type ==
+        Attribute::Type::Resource) {
+        type = Attribute::Type::FunctionParam;
+    }
+
+    Assert(attrName != NULL && "XML is currupted");
+    Attribute *attr;
+    if (attrName != NULL) {
+        std::string temp(reinterpret_cast<const char*>(attrName));
+        attr = new Attribute(&temp, convertToMatchFunction(func), type);
+        currentAttribute = attr;
+    }
+
+    if (xmlTextReaderIsEmptyElement(reader)) {
+        Assert(value != NULL && "XML is currupted");
+        std::string tempVal(reinterpret_cast<const char*>(value));
+        currentAttribute->addValue(&tempVal);
+        consumeCurrentAttribute();
+    }
+
+    if (attributes == 2 || attributes == 3) {
+        xmlFree(func);
+    }
+    xmlFree(value);
+    xmlFree(attrName);
+}
+
+Policy::CombineAlgorithm Parser::convertToCombineAlgorithm(xmlChar* algorithm)
+{
+    switch (*algorithm) {
+    case 'f':
+        if (*(algorithm + 6) == 'a') { //first applicable
+            return Policy::FirstApplicable;
+        }
+        return Policy::FirstTargetMatching;
+    case 'd':
+        return Policy::DenyOverride;
+    case 'p':
+        return Policy::PermitOverride;
+    default:
+        Assert(false && "Wrong combine algorithm name");
+        return Policy::DenyOverride;
+    }
+}
+
+ExtendedEffect Parser::convertToEffect(xmlChar *effect)
+{
+    switch (*effect) {
+    case 'd':     //deny
+        return Deny;
+        break;
+    case 'p':
+        //permit, prompt-blanket, prompt-session, prompt-oneshot
+        if (*(effect + 1) == 'e') {
+            return ExtendedEffect(Permit, ruleId++);
+        }
+        switch (*(effect + 7)) {
+        case 'b':
+            return ExtendedEffect(PromptBlanket, ruleId++);
+        case 's':
+            return ExtendedEffect(PromptSession, ruleId++);
+        case 'o':
+            return ExtendedEffect(PromptOneShot, ruleId++);
+        default:
+            Assert(false && "Effect is Error");
+            return ExtendedEffect();
+        }
+        break;
+    default:
+        Assert(false && "Effect is Error");
+        return ExtendedEffect();
+    }
+    //return ExtendedEffect(Inapplicable);
+}
+
+Attribute::Match Parser::convertToMatchFunction(xmlChar * func)
+{
+    if (func == NULL) {
+        LogError("[ERROR] match function value is NULL");
+        return Attribute::Match::Error;
+    }
+
+    if (*func == 'g') {
+        return Attribute::Match::Glob;
+    } else if (*func == 'e') {
+        return Attribute::Match::Equal;
+    } else if (*func == 'r') {
+        return Attribute::Match::Regexp;
+    } else {
+        LogError("[ERROR] match function value is NULL");
+        return Attribute::Match::Error;
+    }
+    //Assert(false);
+}
+
+void Parser::handleAttr(xmlTextReaderPtr reader)
+{
+    xmlChar * attrValue = xmlTextReaderGetAttribute(reader, BAD_CAST("attr")); //get the first attribute
+    Assert(attrValue != NULL && "Error while obtaining attribute");
+
+    std::string temp(reinterpret_cast<const char*>(attrValue));
+    currentAttribute->addValue(&temp);
+
+    xmlFree(attrValue);
+}
+
+void Parser::consumeCurrentText()
+{
+    Assert(currentText != NULL);
+    currentAttribute->addValue(currentText);
+    delete currentText;
+
+    currentText = NULL;
+}
+
+void Parser::consumeCurrentAttribute()
+{
+    Assert(currentAttribute != NULL);
+
+    currentCondition->addAttribute(*currentAttribute);
+    delete currentAttribute;
+
+    currentAttribute = NULL;
+}
+
+void Parser::consumeCurrentSubject()
+{
+    Policy * policy = dynamic_cast<Policy *>(currentRoot->getElement());
+    Assert(policy != NULL);
+    policy->addSubject(currentSubject);
+    //TODO maybe keep subjects not subject pointers in Policies and consume subjects here
+    currentSubject = NULL;
+}
+
+void Parser::consumeCurrentCondition()
+{
+    Condition * temp = NULL;
+    if (currentCondition != NULL) {
+        if (currentCondition->getParent() != NULL) { //Condition is a child of another condition
+            currentCondition->getParent()->addCondition(*currentCondition);
+        } else { //Condition parent is a Rule
+            Rule * rule = dynamic_cast<Rule *>(currentRoot->getElement());
+            Assert(rule != NULL);
+            rule->setCondition(*currentCondition);
+        }
+        temp = currentCondition->getParent();
+        delete currentCondition;
+    }
+    currentCondition = temp;  //switch current condition ( it may be switched to NULL if condition's parent was rule
+}
+
+void Parser::consumeSubjectMatch(xmlChar * value)
+{
+    Assert(
+        currentAttribute != NULL &&
+        "consuming subject match without attribute set");
+
+    if (currentSubject != NULL) {
+        currentSubject->addNewAttribute(*currentAttribute);
+        //[CR] matching/modyfing functions transform uri.host to uri ( etc. ) so strncmp is not needed, string equality will do
+        if (!strncmp(currentAttribute->getName()->c_str(), "uri",
+                     3) ||
+            !strncmp(currentAttribute->getName()->c_str(), "id", 2)) {
+            if (value != NULL) {
+                currentSubject->setSubjectId(reinterpret_cast<const char *>(
+                                                 value));
+            } else if (currentAttribute->getValue()->size()) {
+                currentSubject->setSubjectId(
+                    currentAttribute->getValue()->front());
+            } else {
+                Assert(false);
+            }
+        }
+    } else if (currentCondition != NULL) {
+        currentCondition->addAttribute(*currentAttribute);
+    }
+
+    delete currentAttribute;
+    currentAttribute = NULL;
+}
+
+void Parser::trim(std::string * str)
+{
+    std::string::size_type pos = str->find_last_not_of(whitespaces);
+    if (pos != std::string::npos) {
+        str->erase(pos + 1);
+        pos = str->find_first_not_of(whitespaces);
+        if (pos != std::string::npos) {
+            str->erase(0, pos);
+        }
+    } else {
+        str->erase(str->begin(), str->end());
+        LogInfo("Warning, empty string as attribute value");
+    }
+}
+
+// KW void Parser::canonicalize(const char * input, const char * output, CanonicalizationAlgorithm canonicalizationAlgorithm){
+// KW
+// KW     xmlDocPtr       doc =  xmlParseFile(input);
+// KW     //xmlDocDump(stdout, doc);
+// KW
+// KW     if(doc == NULL)
+// KW     {
+// KW         LogError("Canonicalization error, cannot parser xml file");
+// KW     }
+// KW
+// KW
+// KW     int mode = -1;
+// KW     if(canonicalizationAlgorithm == C14N)
+// KW     {
+// KW         mode = 0;
+// KW     }
+// KW     else if(canonicalizationAlgorithm == C14NEXCLUSIVE)
+// KW     {
+// KW         mode = 1;
+// KW     }
+// KW
+// KW
+// KW     xmlC14NDocSave(doc, NULL, mode, NULL, 0, output, 0);
+// KW
+// KW     xmlFreeDoc(doc);
+// KW
+// KW }
+
+// KW int Parser::extractNodeToFile(xmlTextReaderPtr reader, const char * filename){
+// KW
+// KW        xmlNodePtr node = xmlTextReaderExpand(reader);
+// KW        xmlBufferPtr buff = xmlBufferCreate();
+// KW        xmlNodeDump(buff, node->doc, node, 0, 0);
+// KW        FILE * file = fopen(filename, "w");
+// KW        if(file == NULL){
+// KW            LogError("Error while trying to open file "<<filename);
+// KW            return -1;
+// KW        }
+// KW        int ret = xmlBufferDump(file, buff);
+// KW        fclose(file);
+// KW        xmlBufferFree(buff);
+// KW        return ret;
+// KW
+// KW }
+
diff --git a/ace/include/ace-dao-ro/AceDAOConversions.h b/ace/include/ace-dao-ro/AceDAOConversions.h
new file mode 100644 (file)
index 0000000..e91c850
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * 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       AceDAOConversions.h
+ * @author     Grzegorz Krawczyk (g.krawczyk@samsung.com)
+ * @version    0.1
+ * @brief
+ */
+
+#ifndef WRT_ACE_DAO_CONVERSIONS_H_
+#define WRT_ACE_DAO_CONVERSIONS_H_
+
+#include <dpl/string.h>
+#include <ace-dao-ro/BaseAttribute.h>
+
+namespace AceDB {
+namespace AceDaoConversions {
+
+DPL::String convertToHash(const BaseAttributeSet &attributes);
+
+}
+}
+
+#endif
diff --git a/ace/include/ace-dao-ro/AceDAOReadOnly.h b/ace/include/ace-dao-ro/AceDAOReadOnly.h
new file mode 100644 (file)
index 0000000..cda83c8
--- /dev/null
@@ -0,0 +1,132 @@
+/*
+ * 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       AceDAOReadOnly.h
+ * @author     Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
+ * @author     Grzegorz Krawczyk (g.krawczyk@samsung.com)
+ * @version    0.1
+ * @brief
+ */
+
+#ifndef ACE_DAO_READ_ONLY_H_
+#define ACE_DAO_READ_ONLY_H_
+
+#include <map>
+
+#include <openssl/md5.h>
+#include <dpl/string.h>
+#include <dpl/exception.h>
+#include <ace-dao-ro/PreferenceTypes.h>
+#include <ace-dao-ro/BaseAttribute.h>
+#include <ace-dao-ro/BasePermission.h>
+#include <ace-dao-ro/AppTypes.h>
+#include <ace-dao-ro/IRequest.h>
+#include <ace/PolicyEffect.h>
+#include <ace/PolicyResult.h>
+#include <ace/PromptDecision.h>
+#include <ace-dao-ro/common_dao_types.h>
+
+namespace AceDB {
+
+typedef std::map<DPL::String, bool> RequestedDevCapsMap;
+typedef DPL::String FeatureName;
+typedef std::vector<FeatureName> FeatureNameVector;
+
+class AceDAOReadOnly
+{
+  public:
+    class Exception
+    {
+      public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, DatabaseError)
+    };
+
+    AceDAOReadOnly() {}
+
+    static void attachToThreadRO(void);
+    static void attachToThreadRW(void);
+    static void detachFromThread(void);
+
+    // policy effect/decision
+    static OptionalExtendedPolicyResult getPolicyResult(
+            const BaseAttributeSet &attributes);
+
+    static OptionalExtendedPolicyResult getPolicyResult(
+        const DPL::String &attrHash);
+
+    static OptionalCachedPromptDecision getPromptDecision(
+            WidgetHandle widgetHandle,
+            int ruleId);
+
+    // resource settings
+    static PreferenceTypes getDevCapSetting(const std::string &resource);
+    static void getDevCapSettings(PreferenceTypesMap *preferences);
+
+    // user settings
+    static void getWidgetDevCapSettings(BasePermissionList *permissions);
+    static PreferenceTypes getWidgetDevCapSetting(
+            const std::string &resource,
+            WidgetHandle handler);
+
+    static void getAttributes(BaseAttributeSet *attributes);
+
+    // Getter for device capabilities that are requested in widgets config.
+    //
+    // Additional boolean flag means whether widget will always get
+    // (at launch) the SMACK permissions needed to use the device cap).
+    //
+    // 'permissions' is the map of device cap names and smack status for
+    // given widget handle.
+    static void getRequestedDevCaps(
+        WidgetHandle widgetHandle,
+        RequestedDevCapsMap *permissions);
+
+    static void getAcceptedFeature(
+        WidgetHandle widgetHandle,
+        FeatureNameVector *featureVector);
+
+    static WidgetHandleList getHandleList();
+
+    static AppTypes getWidgetType(WidgetHandle handle);
+    static std::string getVersion(WidgetHandle widgetHandle);
+    static std::string getAuthorName(WidgetHandle widgetHandle);
+    static std::string getGUID(WidgetHandle widgetHandle);
+
+    static WidgetCertificateCNList getKeyCommonNameList(
+            WidgetHandle widgetHandle,
+            WidgetCertificateData::Owner owner,
+            WidgetCertificateData::Type type);
+    static FingerPrintList getKeyFingerprints(
+            WidgetHandle widgetHandle,
+            WidgetCertificateData::Owner owner,
+            WidgetCertificateData::Type type);
+
+    static std::string getShareHref(WidgetHandle widgetHandle);
+    static bool isWidgetInstalled(WidgetHandle handle);
+
+  protected:
+    static int promptDecisionToInt(PromptDecision decision);
+    static PromptDecision intToPromptDecision(int decision);
+    static int appTypeToInt(AppTypes app_type);
+    static AppTypes intToAppType(int app_type);
+};
+
+}
+
+#endif
diff --git a/ace/include/ace-dao-ro/AceDAOUtilities.h b/ace/include/ace-dao-ro/AceDAOUtilities.h
new file mode 100644 (file)
index 0000000..cae59a4
--- /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       AceDAOUtil.h
+ * @author     Grzegorz Krawczyk (g.krawczyk@samsung.com)
+ * @version    0.1
+ * @brief
+ */
+
+#ifndef WRT_ACE_DAO_UTILITIES_H_
+#define WRT_ACE_DAO_UTILITIES_H_
+
+#include <dpl/db/thread_database_support.h>
+#include <ace-dao-ro/BaseAttribute.h>
+#include <ace-dao-ro/PreferenceTypes.h>
+#include <ace-dao-ro/VerdictTypes.h>
+#include <orm_generator_ace.h>
+
+namespace AceDB {
+
+namespace AceDaoUtilities {
+
+BaseAttribute::Type intToAttributeType(int val);
+int attributeTypeToInt(BaseAttribute::Type type);
+int preferenceToInt(PreferenceTypes p);
+PreferenceTypes intToPreference(int p);
+VerdictTypes intToVerdict(int v);
+int verdictToInt(VerdictTypes v);
+bool getSubjectByUri(const std::string &uri,
+                     DPL::DB::ORM::ace::AceSubject::Row &row);
+bool getResourceByUri(const std::string &uri,
+                      DPL::DB::ORM::ace::AceDevCap::Row &row);
+
+extern DPL::DB::ThreadDatabaseSupport m_databaseInterface;
+
+}
+
+}
+
+#endif
diff --git a/ace/include/ace-dao-ro/AceDatabase.h b/ace/include/ace-dao-ro/AceDatabase.h
new file mode 100644 (file)
index 0000000..d5b2838
--- /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    AceDatabase.h
+ * @author  Lukasz Marek (l.marek@samsung.com)
+ * @version 1.0
+ * @brief   This file contains the declaration of ace database
+ */
+
+#ifndef WRT_ENGINE_SRC_ACCESS_CONTROL_ACE_DATABASE_H
+#define WRT_ENGINE_SRC_ACCESS_CONTROL_ACE_DATABASE_H
+
+#include <dpl/thread.h>
+#include <dpl/mutex.h>
+
+extern DPL::Mutex g_aceDbQueriesMutex;
+
+#define ACE_DB_INTERNAL(tlsCommand, InternalType, interface)                 \
+    static DPL::ThreadLocalVariable<InternalType> *tlsCommand ## Ptr = NULL; \
+    {                                                                        \
+        DPL::Mutex::ScopedLock lock(&g_aceDbQueriesMutex);                   \
+        if (!tlsCommand ## Ptr) {                                            \
+            static DPL::ThreadLocalVariable<InternalType> tmp;               \
+            tlsCommand ## Ptr = &tmp;                                        \
+        }                                                                    \
+    }                                                                        \
+    DPL::ThreadLocalVariable<InternalType> &tlsCommand = *tlsCommand ## Ptr; \
+    if (tlsCommand.IsNull()) { tlsCommand = InternalType(interface); }
+
+#define ACE_DB_SELECT(name, type, interface) \
+    ACE_DB_INTERNAL(name, type::Select, interface)
+
+#define ACE_DB_INSERT(name, type, interface) \
+    ACE_DB_INTERNAL(name, type::Insert, interface)
+
+#define ACE_DB_UPDATE(name, type, interface) \
+    ACE_DB_INTERNAL(name, type::Update, interface)
+
+#define ACE_DB_DELETE(name, type, interface) \
+    ACE_DB_INTERNAL(name, type::Delete, interface)
+
+
+#endif // WRT_ENGINE_SRC_ACCESS_CONTROL_ACE_DATABASE_H
diff --git a/ace/include/ace-dao-ro/AppTypes.h b/ace/include/ace-dao-ro/AppTypes.h
new file mode 100644 (file)
index 0000000..b8b56fa
--- /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       AppTypes.h
+ * @author     Tomasz Swierczek (t.swierczek@samsung.com)
+ */
+
+#ifndef ACCESS_CONTROL_DAO_APPTYPES_H_
+#define ACCESS_CONTROL_DAO_APPTYPES_H_
+
+namespace AceDB{
+
+enum class AppTypes
+{
+    Unknown,
+    WAC20,
+    Tizen
+};
+
+}
+
+#endif // ACCESS_CONTROL_DAO_APPTYPES_H_
diff --git a/ace/include/ace-dao-ro/BaseAttribute.h b/ace/include/ace-dao-ro/BaseAttribute.h
new file mode 100644 (file)
index 0000000..2b4ff89
--- /dev/null
@@ -0,0 +1,150 @@
+/*
+ * 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       IAttribute.h
+ * @author     Grzegorz Krawczyk (g.krawczyk@samsung.com)
+ * @version    0.1
+ * @brief
+ */
+
+#ifndef ACCESS_CONTROL_DAO_BASEATTRIBUTE_H_
+#define ACCESS_CONTROL_DAO_BASEATTRIBUTE_H_
+
+#include <list>
+#include <set>
+#include <string>
+#include <memory>
+#include <dpl/assert.h>
+
+namespace AceDB {
+
+class BaseAttribute;
+typedef std::shared_ptr<BaseAttribute> BaseAttributePtr;
+
+class BaseAttribute
+{
+
+  public:
+    /**
+     * Types of attributes
+     */
+    enum class Type { Subject, Environment, Resource, FunctionParam,
+                      WidgetParam, Undefined };
+
+    struct UnaryPredicate
+    {
+      public:
+        UnaryPredicate(const AceDB::BaseAttribute *comp = NULL) :
+            m_priv(comp)
+        {
+        }
+
+        bool operator()(const AceDB::BaseAttributePtr &comp)
+        {
+            Assert(m_priv != NULL);
+            if (m_priv->getName()->compare(*comp->getName()) != 0) {
+                return false;
+            }
+            return m_priv->getType() == comp->getType();
+        }
+
+        bool operator()(const AceDB::BaseAttributePtr &comp1,
+                        const AceDB::BaseAttributePtr &comp2)
+        {
+            if (comp1->getType() != comp2->getType()) {
+                return comp1->getType() < comp2->getType();
+            }
+            return comp1->getName()->compare(*comp2->getName()) < 0;
+        }
+
+      private:
+          const AceDB::BaseAttribute *m_priv;
+    };
+
+  public:
+    BaseAttribute() :
+        m_typeId(Type::Undefined),
+        m_undetermindState(false)
+    {}
+
+    virtual void setName(const std::string& name)
+    {
+        m_name = name;
+    }
+    virtual void setName(const std::string* name)
+    {
+        m_name = *name;
+    }
+
+    virtual void setType(const Type& type)
+    {
+        m_typeId = type;
+    }
+    virtual Type getType() const
+    {
+        return m_typeId;
+    }
+
+    virtual const std::string* getName() const
+    {
+        return &m_name;
+    }
+
+    //TODO think
+    virtual void setUndetermind(bool tmp)
+    {
+        m_undetermindState = tmp;
+    }
+    virtual bool isUndetermind() const
+    {
+        return m_undetermindState;
+    }
+    virtual std::list<std::string> * getValue() const
+    {
+        return const_cast<std::list<std::string>* >(&value);
+    }
+    virtual bool isValueEmpty() const
+    {
+        return value.empty();
+    }
+
+    virtual void setValue(const std::list<std::string>& arg)
+    {
+        value = arg;
+    }
+
+    virtual ~BaseAttribute()
+    {
+    }
+
+    static const char * typeToString(Type type);
+
+    virtual std::string toString() const;
+
+  protected:
+    std::string m_name;
+    Type m_typeId;
+    bool m_undetermindState;
+    std::list<std::string> value; //string bag list
+};
+
+typedef std::set<BaseAttributePtr, BaseAttribute::UnaryPredicate> BaseAttributeSet;
+
+}
+
+#endif
diff --git a/ace/include/ace-dao-ro/BasePermission.h b/ace/include/ace-dao-ro/BasePermission.h
new file mode 100644 (file)
index 0000000..103cc58
--- /dev/null
@@ -0,0 +1,53 @@
+/*
+ * 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       IPermission.h
+ * @author     Grzegorz Krawczyk (g.krawczyk@samsung.com)
+ * @version    0.1
+ * @brief
+ */
+
+#ifndef ACCESS_CONTROL_DAO_BASEPERMISSION_H_
+#define ACCESS_CONTROL_DAO_BASEPERMISSION_H_
+
+#include <ace-dao-ro/PreferenceTypes.h>
+#include <ace-dao-ro/common_dao_types.h>
+
+namespace AceDB{
+
+struct BasePermission
+{
+    BasePermission(WidgetHandle handler,
+                   const std::string& devCap,
+                   PreferenceTypes accessAllowed) :
+        appId(handler),
+        devCap(devCap),
+        access(accessAllowed)
+    {
+    }
+
+    WidgetHandle appId;
+    std::string devCap;
+    PreferenceTypes access;
+};
+
+typedef std::list<BasePermission> BasePermissionList;
+
+}
+
+#endif
diff --git a/ace/include/ace-dao-ro/IRequest.h b/ace/include/ace-dao-ro/IRequest.h
new file mode 100644 (file)
index 0000000..2975b8b
--- /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       IRequest.h
+ * @author     Grzegorz Krawczyk (g.krawczyk@samsung.com)
+ * @version    0.1
+ * @brief
+ */
+
+#ifndef ACCESS_CONTROL_DAO_IREQUEST_H_
+#define ACCESS_CONTROL_DAO_IREQUEST_H_
+
+namespace AceDB{
+
+class IRequest
+{
+public:
+    virtual ~IRequest(){}
+};
+
+}
+
+#endif
diff --git a/ace/include/ace-dao-ro/PreferenceTypes.h b/ace/include/ace-dao-ro/PreferenceTypes.h
new file mode 100644 (file)
index 0000000..0f96dc5
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ * 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       PreferenceTypes.h
+ * @author     Grzegorz Krawczyk (g.krawczyk@samsung.com)
+ * @version    0.1
+ * @brief
+ */
+
+#ifndef ACCESS_CONTROL_DAO_PREFERENCETYPES_H_
+#define ACCESS_CONTROL_DAO_PREFERENCETYPES_H_
+
+#include <map>
+#include <string>
+
+namespace AceDB{
+
+enum class PreferenceTypes
+{
+    PREFERENCE_PERMIT,
+    PREFERENCE_DENY,
+    PREFERENCE_DEFAULT,
+    PREFERENCE_BLANKET_PROMPT,
+    PREFERENCE_SESSION_PROMPT,
+    PREFERENCE_ONE_SHOT_PROMPT
+};
+
+
+typedef std::map<std::string, PreferenceTypes> PreferenceTypesMap;
+
+}
+
+#endif
diff --git a/ace/include/ace-dao-ro/PromptModel.h b/ace/include/ace-dao-ro/PromptModel.h
new file mode 100644 (file)
index 0000000..8819eae
--- /dev/null
@@ -0,0 +1,92 @@
+/*
+ * 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        PromptModel.h
+ * @author      Justyna Mejzner (j.kwiatkowsk@samsung.com)
+ * @author      Jaroslaw Osmanski (j.osmanski@samsung.com)
+ * @version     1.0
+ *
+ */
+
+#ifndef WRT_SRC_ACCESSCONTROL_ENGINE_PROMPT_MODEL_H_
+#define WRT_SRC_ACCESSCONTROL_ENGINE_PROMPT_MODEL_H_
+
+#include <memory>
+#include <string>
+#include <vector>
+
+#include <dpl/optional_typedefs.h>
+
+namespace Prompt {
+typedef std::vector<std::string> ButtonLabels;
+
+class PromptLabels
+{
+public:
+    PromptLabels(int promptType,
+                 const Prompt::ButtonLabels& questionLabel,
+                 const std::string& mainLabel);
+    DPL::OptionalString getCheckLabel() const;
+    bool isAllowed(const size_t buttonNumber) const;
+    int getPromptType() const;
+    const ButtonLabels& getButtonLabels() const;
+    const std::string& getMainLabel() const;
+
+private:
+    int m_promptType;
+    ButtonLabels m_buttonLabels;
+    std::string m_mainLabel;
+};
+
+typedef std::unique_ptr<PromptLabels> PromptLabelsPtr;
+
+enum Validity
+{
+    ONCE,
+    SESSION,
+    ALWAYS
+};
+
+class PromptAnswer
+{
+public:
+    PromptAnswer(bool isAccessAllowed, Validity validity);
+    PromptAnswer(int aPromptType, unsigned int buttonAns, bool checkAns);
+    bool isAccessAllowed() const;
+    Validity getValidity() const;
+
+private:
+    bool m_isAccessAllowed;
+    Validity m_validity;
+};
+
+class PromptModel
+{
+  public:
+    static PromptLabels* getOneShotModel(const std::string& resourceId);
+    static PromptLabels* getSessionModel(const std::string& resourceId);
+    static PromptLabels* getBlanketModel(const std::string& resourceId);
+
+    enum PromptType
+    {
+        PROMPT_ONESHOT,
+        PROMPT_SESSION,
+        PROMPT_BLANKET
+    };
+};
+
+} // Prompt
+
+#endif /* WRT_SRC_ACCESSCONTROL_ENGINE_PROMPT_MODEL_H_ */
diff --git a/ace/include/ace-dao-ro/TimedVerdict.h b/ace/include/ace-dao-ro/TimedVerdict.h
new file mode 100644 (file)
index 0000000..8f9be66
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * 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       TimedVerdict.h
+ * @author     Grzegorz Krawczyk (g.krawczyk@samsung.com)
+ * @version    0.1
+ * @brief
+ */
+
+#ifndef ACCESS_CONTROL_DAO_TIMEDVERDICT_H_
+#define ACCESS_CONTROL_DAO_TIMEDVERDICT_H_
+
+#include <ace-dao-ro/VerdictTypes.h>
+
+namespace AceDB{
+
+struct TimedVerdict
+{
+    VerdictTypes decision;
+    /*Below values are optional,its filled only when verdict depend on session*/
+    std::string session;
+    int subjectVerdictId;
+};
+
+}
+
+#endif
diff --git a/ace/include/ace-dao-ro/ValidityTypes.h b/ace/include/ace-dao-ro/ValidityTypes.h
new file mode 100644 (file)
index 0000000..1283cf1
--- /dev/null
@@ -0,0 +1,40 @@
+/*
+ * 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       ValidityTypes.h
+ * @author     Grzegorz Krawczyk (g.krawczyk@samsung.com)
+ * @version    0.1
+ * @brief
+ */
+
+#ifndef ACCESS_CONTROL_DAO_VALIDITYTYPES_H_
+#define ACCESS_CONTROL_DAO_VALIDITYTYPES_H_
+
+namespace AceDB{
+
+enum class ValidityTypes
+{
+     ONCE,
+     SESSION,
+     ALWAYS,
+     UNWRITEABLE
+};
+
+}
+
+#endif
diff --git a/ace/include/ace-dao-ro/VerdictTypes.h b/ace/include/ace-dao-ro/VerdictTypes.h
new file mode 100644 (file)
index 0000000..8a312b5
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * 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       VerdictTypes.h
+ * @author     Grzegorz Krawczyk (g.krawczyk@samsung.com)
+ * @version    0.1
+ * @brief
+ */
+
+#ifndef ACCESS_CONTROL_DAO_VERDICTTYPES_H_
+#define ACCESS_CONTROL_DAO_VERDICTTYPES_H_
+
+namespace AceDB{
+
+enum class VerdictTypes
+{
+    VERDICT_PERMIT,
+    VERDICT_DENY,
+    //Verdict is innapplicable if policy evaluate to INAPPLICABLE,
+    //in this case WRT should decide what to do
+    VERDICT_INAPPLICABLE,
+    VERDICT_UNDETERMINED,
+    VERDICT_UNKNOWN,  //Verdict is unknown if Verdicts manager cannot find it
+    VERDICT_ASYNC,
+    VERDICT_ERROR
+};
+
+}
+
+#endif
diff --git a/ace/include/ace-dao-ro/common_dao_types.h b/ace/include/ace-dao-ro/common_dao_types.h
new file mode 100644 (file)
index 0000000..94b4c5e
--- /dev/null
@@ -0,0 +1,93 @@
+/*
+ * 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    common_dao_types.h
+ * @author  Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version 1.1
+ * @brief   This file contains the declaration of common data types for ace database.
+ */
+#ifndef ACE_SRC_CONFIGURATION_COMMON_DAO_TYPES_H_
+#define ACE_SRC_CONFIGURATION_COMMON_DAO_TYPES_H_
+
+#include <list>
+#include <dpl/optional_typedefs.h>
+#include <dpl/string.h>
+#include "AppTypes.h"
+
+typedef int WidgetHandle;
+typedef std::list<WidgetHandle> WidgetHandleList;
+
+namespace AceDB {
+
+enum {
+    INVALID_PLUGIN_HANDLE = -1
+};
+typedef int DbPluginHandle;
+
+enum CertificateSource {
+    SIGNATURE_DISTRIBUTOR = 0,
+    SIGNATURE_AUTHOR = 1
+};
+
+struct WidgetRegisterInfo {
+    AppTypes type;
+    DPL::OptionalString widget_id;
+    DPL::OptionalString authorName;
+    DPL::OptionalString version;
+    DPL::OptionalString shareHref;
+};
+
+typedef std::list <std::string> WidgetCertificateCNList;
+
+struct WidgetCertificateData {
+    enum Owner { AUTHOR, DISTRIBUTOR, UNKNOWN };
+    enum Type { ROOT, ENDENTITY };
+
+    Owner owner;
+    Type type;
+
+    int chainId;
+    std::string strMD5Fingerprint;
+    std::string strSHA1Fingerprint;
+    DPL::String strCommonName;
+
+    bool operator== (const WidgetCertificateData& certData) const {
+        return certData.chainId == chainId &&
+           certData.owner == owner &&
+           certData.strCommonName == strCommonName &&
+           certData.strMD5Fingerprint == strMD5Fingerprint &&
+           certData.strSHA1Fingerprint == strSHA1Fingerprint;
+    }
+};
+typedef std::list<WidgetCertificateData> WidgetCertificateDataList;
+
+typedef std::list<std::string> FingerPrintList;
+
+typedef std::list<std::string> CertificateChainList;
+class IWacSecurity {
+  public:
+    virtual ~IWacSecurity() {}
+    virtual const WidgetCertificateDataList& getCertificateList() const = 0;
+    virtual bool isRecognized() const = 0;
+    virtual bool isDistributorSigned() const = 0;
+    virtual bool isWacSigned() const = 0;
+    virtual void getCertificateChainList(CertificateChainList& list) const = 0;
+};
+
+} //namespace AceDB
+
+#endif /* ACE_SRC_CONFIGURATION_COMMON_DAO_TYPES_H_ */
diff --git a/ace/include/ace-dao-rw/AceDAO.h b/ace/include/ace-dao-rw/AceDAO.h
new file mode 100644 (file)
index 0000000..bff6a51
--- /dev/null
@@ -0,0 +1,120 @@
+/*
+ * 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       AceDAO.h
+ * @author     Krzysztof Jackiewicz (k.jackiewicz@samsung.com)
+ * @version    0.1
+ * @brief
+ */
+
+#ifndef ACEDAO_H_
+#define ACEDAO_H_
+
+#include <list>
+#include <map>
+#include <string>
+
+#include <dpl/optional_typedefs.h>
+#include <dpl/string.h>
+#include <ace-dao-ro/AceDAOReadOnly.h>
+#include <ace-dao-ro/ValidityTypes.h>
+#include <ace-dao-ro/AppTypes.h>
+
+namespace AceDB {
+/*
+ *
+ */
+class AceDAO : public AceDAOReadOnly
+{
+  public:
+
+    AceDAO() {}
+
+    // Policy Decisions
+    static void setPolicyResult(
+            const BaseAttributeSet &attributes,
+            const ExtendedPolicyResult &policyResult);
+
+    static void removePolicyResult(
+            const BaseAttributeSet &attributes);
+
+    // PromptDecision
+    static void setPromptDecision(
+            WidgetHandle widgetHandle,
+            int ruleId,
+            const boost::optional<DPL::String> &session,
+            PromptDecision decision);
+
+    static void clearPromptDecisions(void);
+
+    // reseting database
+    static void clearWidgetDevCapSettings(void);
+    static void clearDevCapSettings(void);
+    static void clearAllSettings(void);
+    static void resetDatabase(void);
+    // clears all databse information relevant to policy cache
+    static void clearPolicyCache(void);
+
+    // resource settings
+    static void setDevCapSetting(const std::string &resource,
+            PreferenceTypes preference);
+    static void removeDevCapSetting(const std::string &resource);
+
+    // user settings
+    static void setWidgetDevCapSetting(
+            const std::string &resource,
+            WidgetHandle handler,
+            PreferenceTypes);
+    static void removeWidgetDevCapSetting(
+            const std::string &resource,
+            WidgetHandle handler);
+
+    // resource and subject management
+    static int addResource(const std::string &request);
+
+    // utilities
+    static void addAttributes(const BaseAttributeSet &attributes);
+
+    // Setter for device capabilities that are requested in widgets config.
+    //
+    // Additional boolean flag means whether widget will always get
+    // (at launch) the SMACK permissions needed to use the device cap).
+    //
+    // 'permissions' is the map of device cap names and smack status for
+    // given widget handle.
+    static void setRequestedDevCaps(
+        WidgetHandle widgetHandle,
+        const RequestedDevCapsMap &permissions);
+
+    static void removeRequestedDevCaps(
+        WidgetHandle widgetHandle);
+
+    static void setAcceptedFeature(
+        WidgetHandle widgetHandle,
+        const FeatureNameVector &vector);
+
+    static void removeAcceptedFeature(WidgetHandle widgetHandle);
+
+    static void registerWidgetInfo(WidgetHandle handle,
+                                   const WidgetRegisterInfo& info,
+                                   const WidgetCertificateDataList& dataList);
+    static void unregisterWidgetInfo(WidgetHandle handle);
+
+};
+}
+#endif /* ACEDAO_H_ */
diff --git a/ace/include/ace/AbstractPolicyEnforcementPoint.h b/ace/include/ace/AbstractPolicyEnforcementPoint.h
new file mode 100644 (file)
index 0000000..9482915
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+ * 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 WRT_SRC_ACCESS_CONTROL_LOGIC_ABSTRACT_POLICY_ENFORCEMENT_POINTS_H
+#define WRT_SRC_ACCESS_CONTROL_LOGIC_ABSTRACT_POLICY_ENFORCEMENT_POINTS_H
+
+#include <ace/WRT_INTERFACE.h>
+#include <ace/PolicyResult.h>
+#ifdef DBUS_CONNECTION
+#include <dpl/event/inter_context_delegate.h>
+#endif
+class AbstractPolicyEnforcementPoint
+{
+  public:
+#ifdef DBUS_CONNECTION
+    typedef DPL::Event::ICDelegate<PolicyResult> ResponseReceiver;
+#endif
+    virtual ExtendedPolicyResult check(Request &request) = 0;
+};
+
+#endif /* WRT_SRC_ACCESS_CONTROL_LOGIC_ABSTRACT_POLICY_ENFORCEMENT_POINTS_H */
diff --git a/ace/include/ace/AbstractPolicyInformationPoint.h b/ace/include/ace/AbstractPolicyInformationPoint.h
new file mode 100644 (file)
index 0000000..e8d95ed
--- /dev/null
@@ -0,0 +1,21 @@
+/*
+ * 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.
+ */
+
+class AbstractPolicyInformationPoint
+{
+  public:
+    virtual ~AbstractPolicyInformationPoint() {}
+};
diff --git a/ace/include/ace/AbstractTreeElement.h b/ace/include/ace/AbstractTreeElement.h
new file mode 100644 (file)
index 0000000..ffe2e89
--- /dev/null
@@ -0,0 +1,44 @@
+/*
+ * 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.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : AbstractTreeElement.h
+//  @ Date : 2009-05-25
+//  @ Author : Samsung
+//
+//
+#if !defined(_ABSTRACTTREEELEMENT_H)
+#define _ABSTRACTTREEELEMENT_H
+
+#include <list>
+#include "Effect.h"
+#include <iostream>
+
+class AbstractTreeElement
+{
+  public:
+
+    virtual ~AbstractTreeElement()
+    {
+    }
+
+    virtual void printData() = 0;
+  protected:
+};
+
+#endif  //_ABSTRACTTREEELEMENT_H
diff --git a/ace/include/ace/AsyncVerdictResultListener.h b/ace/include/ace/AsyncVerdictResultListener.h
new file mode 100644 (file)
index 0000000..47ef573
--- /dev/null
@@ -0,0 +1,33 @@
+/*
+ * 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 _ASYNCVERDICT_H
+#define _ASYNCVERDICT_H
+
+#include <ace/Verdict.h>
+#include <ace/WRT_INTERFACE.h>
+#include <ace/Request.h>
+
+class AsyncVerdictResultListener
+{
+  public:
+    virtual void onVerdict(const Verdict &verdict,
+            const Request *request) = 0;
+    virtual ~AsyncVerdictResultListener()
+    {
+    }
+};
+
+#endif
diff --git a/ace/include/ace/Attribute.h b/ace/include/ace/Attribute.h
new file mode 100644 (file)
index 0000000..e1a62b4
--- /dev/null
@@ -0,0 +1,212 @@
+/*
+ * 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.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : Attribute.h
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+
+#if !defined(_ATTRIBUTE_H)
+#define _ATTRIBUTE_H
+
+#include <string>
+#include <iostream>
+#include <set>
+#include <list>
+
+#include <ace-dao-ro/BaseAttribute.h>
+
+class Attribute : public AceDB::BaseAttribute
+{
+  public:
+    /**
+     * Types of match functions
+     */
+    enum class Match { Equal, Glob, Regexp, Error };
+    /**
+     * Types of attribute value modifiers
+     */
+    enum class Modifier { Non, Scheme, Authority, SchemeAuthority, Host, Path };
+    /**
+     * Possible match results
+     */
+    enum class MatchResult { MRUndetermined = -1, MRFalse = 0, MRTrue = 1};
+
+  public:
+
+    /**
+     * New attribute constructor
+     * @param name name of the new attribute
+     * @param matchFunction match function used in the attribute
+     * @param type attribute type
+     */
+    Attribute(const std::string *name,
+              const Match matchFunction,
+              const Type type);
+
+
+    /**
+     * Constructor used to create default attribute ( used for unit tests )
+     * @param nm name of the default attribute
+     */
+    Attribute(const std::string& nm) :
+        matchFunction(Match::Error),
+        modifierFunction(Modifier::Non)
+    {
+        m_name = nm;
+        m_typeId = Type::Subject;
+        m_undetermindState = false;
+    }
+
+    /**
+     * Destructor
+     */
+    virtual ~Attribute();
+
+    std::list<std::string> * getValue() const
+    {
+        return AceDB::BaseAttribute::getValue();
+    }
+    Match getMatchFunction() const
+    {
+        return matchFunction;
+    }
+
+    /*  --- Setters --- */
+    void addValue (const std::string *value);
+
+    MatchResult  matchAttributes(const BaseAttribute *) const;
+
+    /**
+     * Operator used in for attribute set,used to distinguished only attribute names
+     * It cannot take attribute type into consideration
+     */
+    bool operator< (const Attribute & obj) const
+    {
+        int result = this->m_name.compare(*obj.getName());
+        if (result == 0) { //If names are equal check attribute types
+            if (this->m_typeId < obj.getType()) {
+                result = -1;
+            } else if (this->m_typeId > obj.getType()) {
+                result = 1;
+            }
+        }
+        //If result is negative that means that 'this' was '<' than obj
+        return result < 0;
+    }
+
+     /** Checks if object type is equal to argument */
+    bool instanceOf(Type type_)
+    {
+        return type_ == m_typeId;
+    }
+
+    friend std::ostream & operator<<(std::ostream & out,
+                                     const Attribute & attr);
+
+  protected:
+
+    bool searchAndCut(const char *);
+
+    /*
+     *  URI definition from rfc2396
+     *
+     *  <scheme>://<authority><path>?<query>
+     *  Each of the components may be absent, apart from the scheme.
+     *  Host is a part of authority as in definition below:
+     *
+     *  authority     = server | reg_name
+     *  server        = [ [ userinfo "@" ] hostport ]
+     *  <userinfo>@<host>:<port>
+     *
+     *  Extract from rfc2396
+     *  The authority component is preceded by a double slash "//" and is
+     *  terminated by the next slash "/", question-mark "?", or by the end of
+     *  the URI.  Within the authority component, the characters ";", ":",
+     * "@", "?", and "/" are reserved.
+     *
+     *  Modifiers should return pointer to empty string if given part of string was empty.
+     *  Modifiers should return NULL if the string to be modified was not an URI.
+     */
+    std::string * uriScheme(const std::string *) const;
+    std::string * uriAuthority(const std::string *) const;
+    std::string * uriSchemeAuthority(const std::string *) const;
+    std::string * uriHost(const std::string *) const;
+    std::string * uriPath(const std::string *) const;
+    std::string * applyModifierFunction(const std::string * val) const;
+
+    bool parse(const std::string *input,
+            std::string *part) const;
+    bool find_error(const std::string *part) const;
+
+    bool checkScheme(const std::string *scheme) const;
+    bool checkAuthority(const std::string *scheme) const;
+    std::string * getHost(const std::string *scheme) const;
+    bool checkPath(const std::string *scheme) const;
+
+    bool isSchemeAllowedCharacter(int c) const;
+    bool isSegmentAllowedCharacter(int c) const;
+    bool isUserInfoAllowedString(const std::string *str) const;
+    bool isHostAllowedString(const std::string *str) const;
+    bool isHostNameAllowedString(const std::string * str) const;
+    bool isIPv4AllowedString(const std::string * str) const;
+    bool isDomainLabelAllowedString(const char * data,
+                                    int lenght) const;
+    bool isTopLabelAllowedString(const char* data,
+                                 int lenght) const;
+
+    bool isUnreserved(int c) const;
+    bool isAlphanum(int c) const;
+    bool isEscaped(const char esc[3]) const;
+    bool isHex(int c) const;
+
+    MatchResult lists_comparator(
+        const std::list<std::string> *first,
+        const std::list<std::string> *second,
+        MatchResult (*comparator)(const std::string *,
+                                  const std::string *)) const;
+
+    /**
+     *  Map used to check if character is a 'mark'
+     */
+    static const bool mark[256];
+    /**
+     *  Map used to check if character is a 'digit'
+     *
+     */
+    static const bool digit[256];
+    /**
+     * Map used to check if character is an 'alphanumeric' value
+     *
+     */
+    static const bool alpha[256];
+
+  protected:
+    Match matchFunction;
+    Modifier modifierFunction;
+};
+
+typedef AceDB::BaseAttributeSet AttributeSet;
+
+//TODO remove later or ifdef debug methods
+void printAttributes(const AttributeSet& attrs);
+void printAttributes(const std::list<Attribute> & attrs);
+
+#endif  //_ATTRIBUTE_H
diff --git a/ace/include/ace/Combiner.h b/ace/include/ace/Combiner.h
new file mode 100644 (file)
index 0000000..784dcea
--- /dev/null
@@ -0,0 +1,58 @@
+/*
+ * 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.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : Combiner.h
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+
+#if !defined(_COMBINER_H)
+#define _COMBINER_H
+
+#include <set>
+
+#include <ace/Attribute.h>
+#include <ace/TreeNode.h>
+
+class Combiner
+{
+  protected:
+
+    const AttributeSet * attrSet;
+
+  public:
+
+    virtual ExtendedEffect combineRules(const TreeNode * rule) = 0;
+    virtual ExtendedEffect combinePolicies(const TreeNode * policy) = 0;
+
+    const AttributeSet * getAttributeSet() const
+    {
+        return this->attrSet;
+    }
+    void setAttributeSet(const AttributeSet * attrSet)
+    {
+        this->attrSet = attrSet;
+    }
+    virtual ~Combiner()
+    {
+    }                       //attrSet is deleted elsewhere
+};
+
+#endif  //_COMBINER_H
diff --git a/ace/include/ace/CombinerImpl.h b/ace/include/ace/CombinerImpl.h
new file mode 100644 (file)
index 0000000..d7c2e21
--- /dev/null
@@ -0,0 +1,76 @@
+/*
+ * 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.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : CombinerImpl.h
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+
+#ifndef _COMBINER_IMPL_H
+#define _COMBINER_IMPL_H
+
+#include <list>
+#include <dpl/log/log.h>
+
+#include "Combiner.h"
+#include "Effect.h"
+#include "Policy.h"
+#include "Subject.h"
+
+class CombinerImpl : public Combiner
+{
+  public:
+
+    virtual ExtendedEffect combineRules(const TreeNode * rule);
+    virtual ExtendedEffect combinePolicies(const TreeNode * policy);
+
+    virtual ~CombinerImpl()
+    {
+    }
+
+  protected:
+
+    bool checkIfTargetMatches(const std::list<const Subject *> * subjectsSet,
+            bool &isUndetermined);
+
+    ExtendedEffect combine(Policy::CombineAlgorithm algorithm,
+            ExtendedEffectList &effects);
+
+    ExtendedEffect denyOverrides(const ExtendedEffectList &effects);
+    ExtendedEffect permitOverrides(const ExtendedEffectList &effects);
+    ExtendedEffect firstApplicable(const ExtendedEffectList &effects);
+    ExtendedEffect firstMatchingTarget(const ExtendedEffectList &effects);
+
+    std::list<int> * convertEffectsToInts(const std::list<Effect> * effects);
+    Effect convertIntToEffect(int intEffect);
+
+    void showEffectList(ExtendedEffectList & effects)
+    {
+        ExtendedEffectList::iterator it = effects.begin();
+        for (; it != effects.end(); ++it) {
+            LogDebug(toString(*it));
+        }
+    }
+
+  private:
+    bool isError(const ExtendedEffectList &effects);
+};
+
+#endif  //_COMBINERIMPL_H
diff --git a/ace/include/ace/Condition.h b/ace/include/ace/Condition.h
new file mode 100644 (file)
index 0000000..918c1fe
--- /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:   Condition.h
+// Author: notroot
+//
+// Created on June 3, 2009, 9:00 AM
+//
+#ifndef _CONDITION_H
+#define _CONDITION_H
+
+#include <list>
+#include <set>
+#include <iostream>
+#include <dpl/foreach.h>
+
+#include "Attribute.h"
+#include "Effect.h"
+#include "TreeNode.h"
+
+class Condition
+{
+  public:
+    enum CombineType
+    {
+        AND, OR
+    };
+
+    void addCondition(const Condition & condition)
+    {
+        this->conditions.push_back(condition);
+    }
+
+    void addAttribute(const Attribute & attribute)
+    {
+        this->attributes.push_back(attribute);
+    }
+
+    void setCombineType(CombineType type)
+    {
+        this->combineType = type;
+    }
+
+    Condition() : combineType(AND),
+        parent(NULL)
+    {
+    }
+
+    Condition(CombineType type) : combineType(type),
+        parent(NULL)
+    {
+    }
+
+    virtual ~Condition()
+    {
+    }
+
+    Condition * getParent()
+    {
+        return this->parent;
+    }
+
+    void setParent(Condition * condition)
+    {
+        this->parent = condition;
+    }
+
+    Attribute::MatchResult evaluateCondition(
+            const AttributeSet * attrSet) const;
+
+    friend std::ostream & operator<<(std::ostream & out,
+            Condition & condition)
+    {
+        FOREACH (it, condition.attributes)
+        {
+            out << *it;
+        }
+        return out;
+    }
+    //[CR] change function name
+    void getAttributes(AttributeSet * attrSet);
+
+  private:
+    Attribute::MatchResult evaluateChildConditions(
+            const AttributeSet * attrSet,
+            bool &isFinalMatch,
+            bool & undefinedMatchFound) const;
+
+    Attribute::MatchResult evaluateAttributes(
+            const AttributeSet * attrSet,
+            bool& isFinalMatch,
+            bool & undefinedMatchFound) const;
+
+    // KW     Attribute::MatchResult performANDalgorithm(const std::set<Attribute> * attributes) const;
+
+    // KW     Attribute::MatchResult performORalgorithm(const std::set<Attribute> * attributes) const;
+
+    bool isEmpty() const
+    {
+        return attributes.empty() && conditions.empty();
+    }
+
+    bool isAndCondition() const
+    {
+        return combineType == AND;
+    }
+
+    bool isOrCondition() const
+    {
+        return combineType == OR;
+    }
+
+    std::list<Condition> conditions;
+    CombineType combineType;
+    std::list<Attribute> attributes;
+    Condition *parent;
+};
+
+#endif    /* _CONDITION_H */
+
diff --git a/ace/include/ace/ConfigurationManager.h b/ace/include/ace/ConfigurationManager.h
new file mode 100644 (file)
index 0000000..627f9da
--- /dev/null
@@ -0,0 +1,122 @@
+/*
+ * 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 _CONFIGURATIONMANAGER_H_
+#define _CONFIGURATIONMANAGER_H_
+
+#include <list>
+#include <string.h>
+#include <string>
+#include "Constants.h"
+#include <iostream>
+#include <dpl/log/log.h>
+
+enum class PolicyType {
+    WAC2_0,
+    Tizen
+};
+
+#define POLICY_NAME_WAC2_0                  "WAC2.0"
+#define POLICY_NAME_TIZEN                   "Tizen"
+#define POLICY_WIDGET_TYPE_ATTRIBUTE_NAME   "WrtSecurity.WidgetPolicyType"
+
+#pragma message "ATTR_ACTIVE_POLICY BAD_CAST, PARSER_ERROR, PARSER_SUCCESS\
+ macros are DEPRECATED"
+#define ATTR_ACTIVE_POLICY BAD_CAST("active") // !! DEPRECATED !!
+#define PARSER_ERROR     1 // !! DEPRECATED !!
+#define PARSER_SUCCESS   0 // !! DEPRECATED !!
+
+class ConfigurationManager
+{
+  public:
+    // !! DEPRECATED !!
+    enum ConfigurationManagerResult
+    {
+        CM_OPERATION_SUCCESS = 0,
+        CM_GENERAL_ERROR = -1,
+        CM_FILE_EXISTS = -2,
+        CM_REMOVE_ERROR = -3,
+        CM_REMOVE_CURRENT = -4,
+        CM_REMOVE_NOT_EXISTING = -5
+    };
+
+    // !! DEPRECATED !!
+    std::string getCurrentPolicyFile(void) const;
+    std::string getFullPathToCurrentPolicyFile(void) const;
+    std::string getFullPathToCurrentPolicyXMLSchema(void) const;
+    int addPolicyFile(const std::string & filePath);
+    int removePolicyFile(const std::string& fileName);
+    int changeCurrentPolicyFile(const std::string& filePath);
+    std::string extractFilename(const std::string& path) const;
+
+    /**
+     * ACE policy file path getter
+     * @return Full path to policy file
+     */
+    std::string getFullPathToPolicyFile(PolicyType policy) const;
+
+    /**
+     * ACE policy dtd file path getter
+     * @return Full path to ACE current policy file
+     */
+    std::string getFullPathToPolicyXMLSchema(void) const;
+
+    /**
+     * ACE policy storage path getter
+     * @return Full path to ACE policy file storage
+     */
+    std::string getCscStoragePath(void) const;
+
+   /**
+     * ACE policy storage path getter
+     * @return Full path to ACE policy file storage
+     */
+    std::string getStoragePath(void) const;
+
+    /**
+     * Method to obtain instance of configuration manager
+     * @return retuns pointer to configuration manager or NULL in case of error
+     */
+    static ConfigurationManager * getInstance()
+    {
+        if (!instance) {
+            instance = new ConfigurationManager();
+        }
+        return instance;
+    }
+
+  protected:
+
+    // !! DEPRECATED !!
+    int parse(const std::string&);
+    bool copyFile(FILE*, FILE*, int lenght = 1024) const;
+    bool checkIfFileExistst(const std::string&) const;
+    const std::list<std::string> & getPolicyFiles() const;
+    const std::string & getConfigFile() const;
+
+    ConfigurationManager()
+    {
+    }
+    virtual ~ConfigurationManager()
+    {
+    }
+
+private:
+
+    static ConfigurationManager * instance;
+};
+
+#endif
+
diff --git a/ace/include/ace/Constants.h b/ace/include/ace/Constants.h
new file mode 100644 (file)
index 0000000..346bb0e
--- /dev/null
@@ -0,0 +1,60 @@
+/*
+ * 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        Constants.h
+ * @author      Piotr Fatyga (p.fatyga@samsung.com)
+ * @version     0.1
+ * @brief
+ */
+
+#ifndef _CONSTANTS_H
+#define _CONSTANTS_H
+
+#define ACE_MAIN_STORAGE "/usr/etc/ace"
+#define ACE_CSC_STORAGE "/opt/system/csc-default/usr/web"
+#define ACE_WAC_POLICY_FILE_NAME "/WAC2.0Policy.xml"
+#define ACE_TIZEN_POLICY_FILE_NAME "/TizenPolicy.xml"
+#define ACE_DTD_LOCATION ACE_MAIN_STORAGE "/bondixml.dtd"
+
+// !! DEPRECATED !!
+#pragma message "ACE_CONFIGURATION_PATH, ACE_CONFIGURATION_DTD \
+ macros are DEPRECATED"
+#define ACE_CONFIGURATION_PATH ACE_MAIN_STORAGE "/config.xml"
+#define ACE_CONFIGURATION_DTD ACE_MAIN_STORAGE "/config.dtd"
+
+/////////////////FOR GUI//////////////////////
+
+#define MYSTERIOUS_BITMAP "/usr/apps/org.tizen.policy/d.png"
+#define MYSTERIOUS_BITMAP2 "/usr/apps/org.tizen.policy/file.png"
+
+///////////////////FOR TESTS//////////////////////////
+
+#define COMBINER_TEST "/usr/etc/ace/CMTest/com_general-test.xml"
+#define CONFIGURATION_MGR_TEST_PATH "/usr/etc/ace/CMTest/"
+#define CONFIGURATION_MGR_TEST_CONFIG ACE_MAIN_STORAGE "/CMTest/pms_config.xml"
+#define CONFIGURATION_MGR_TEST_POLICY_STORAGE ACE_MAIN_STORAGE "/CMTest/active"
+#define CONFIGURATION_MGR_TEST_POLICY_STORAGE_MOVED ACE_MAIN_STORAGE \
+    "/CMTest/activeMoved"
+#define CONFIGURATION_MGR_TEST_POLICY CONFIGURATION_MGR_TEST_POLICY_STORAGE \
+    "/pms_general-test.xml"
+#define POLICIES_TO_SIGN_DIR ACE_MAIN_STORAGE "/SignerTests/"
+
+#define OUTPUT_DIR ACE_MAIN_STORAGE "/SignerTests/signedPolicies/"
+#define PRIVATE_KEY_DIR ACE_MAIN_STORAGE "/SignerTests/PrvKey/"
+#define X509_DATA_BASE_DIR ACE_MAIN_STORAGE "/SignerTests/X509Data/"
+
+#endif    /* _CONSTANTS_H */
+
diff --git a/ace/include/ace/Effect.h b/ace/include/ace/Effect.h
new file mode 100644 (file)
index 0000000..c771c15
--- /dev/null
@@ -0,0 +1,112 @@
+/*
+ * 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.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : Effect.h
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+
+#ifndef _EFFECT_H_
+#define _EFFECT_H_
+
+#include <list>
+
+typedef int RuleId;
+
+enum Effect
+{
+    Deny =0,
+    Undetermined=1,    // jk mb added this enum, so the ones below are inceremented!!!!!!!
+    PromptOneShot =2,
+    PromptSession =3,
+    PromptBlanket =4,
+    Permit =5,
+    Inapplicable =6,
+    NotMatchingTarget=7,
+    Error=8,
+};
+
+struct ExtendedEffect {
+public:
+    ExtendedEffect(Effect effect = Error, RuleId ruleId = -1)
+      : m_effect(effect)
+      , m_ruleId(ruleId)
+    {}
+
+    ExtendedEffect(const ExtendedEffect &second)
+      : m_effect(second.m_effect)
+      , m_ruleId(second.m_ruleId)
+    {}
+
+    ExtendedEffect& operator=(const ExtendedEffect &second) {
+        m_effect = second.m_effect;
+        m_ruleId = second.m_ruleId;
+        return *this;
+    }
+
+    Effect getEffect() const { return m_effect; }
+
+    RuleId getRuleId() const { return m_ruleId; }
+
+private:
+    Effect m_effect;
+    RuleId m_ruleId;
+};
+
+typedef std::list<ExtendedEffect> ExtendedEffectList;
+
+inline const char *toString(const ExtendedEffect &effect)
+{
+    const char * temp = "";
+
+    switch (effect.getEffect()) {
+    case Deny:
+        temp = "Deny";
+        break;
+    case Undetermined:
+        temp = "Undetermined";
+        break;
+    case PromptOneShot:
+        temp = "PromptOneShot";
+        break;
+    case PromptSession:
+        temp = "PromptSession";
+        break;
+    case PromptBlanket:
+        temp = "PromptBlanket";
+        break;
+    case Permit:
+        temp = "Permit";
+        break;
+    case Inapplicable:
+        temp = "Inapplicable";
+        break;
+    case NotMatchingTarget:
+        temp = "NotMatchingTarget";
+        break;
+    case Error:
+        temp = "Error";
+        break;
+    default:;
+    }
+    return temp;
+}
+
+#endif  //_EFFECT_H_
diff --git a/ace/include/ace/PermissionTriple.h b/ace/include/ace/PermissionTriple.h
new file mode 100644 (file)
index 0000000..fcb7e47
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ * 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.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : PermissionTriple.h
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+
+#if !defined(_PERMISSION_TRIPLE_H)
+#define _PERMISSION_TRIPLE_H
+
+#include <string>
+#include <list>
+#include <ace-dao-ro/PreferenceTypes.h>
+#include <ace-dao-ro/BasePermission.h>
+
+typedef AceDB::BasePermission PermissionTriple;
+typedef AceDB::BasePermissionList PermissionList;
+
+struct GeneralSetting
+{
+    GeneralSetting(const std::string& resourceName,
+            AceDB::PreferenceTypes accessAllowed) : generalSettingName(resourceName),
+        access(accessAllowed)
+    {
+    }
+    std::string generalSettingName;
+    AceDB::PreferenceTypes access;
+};
+
+#endif  //_PERMISSION_TRIPLE_H
diff --git a/ace/include/ace/Policy.h b/ace/include/ace/Policy.h
new file mode 100644 (file)
index 0000000..2c43bd5
--- /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.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : Policy.h
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+
+#if !defined(_POLICY_H)
+#define _POLICY_H
+
+#include <list>
+
+#include <ace/AbstractTreeElement.h>
+#include <ace/Effect.h>
+#include <ace/Attribute.h>
+#include <ace/Subject.h>
+#include <iostream>
+#include <dpl/noncopyable.h>
+
+class Policy : public AbstractTreeElement,
+    DPL::Noncopyable
+{
+  public:
+    enum CombineAlgorithm { DenyOverride, PermitOverride, FirstApplicable,
+                            FirstTargetMatching };
+
+    Policy()
+    {
+        combineAlgorithm = DenyOverride;
+        subjects = new std::list<const Subject *>();
+    }
+
+    CombineAlgorithm getCombineAlgorithm() const
+    {
+        return this->combineAlgorithm;
+    }
+
+    void setCombineAlgorithm(CombineAlgorithm algorithm)
+    {
+        this->combineAlgorithm = algorithm;
+    }
+
+    const std::list<const Subject *> * getSubjects() const
+    {
+        return this->subjects;
+    }
+
+    void addSubject(const Subject * subject)
+    {
+        if (this->subjects == NULL) {
+            return;
+        }
+        this->subjects->push_back(subject);
+    }
+
+    virtual ~Policy();
+
+    void printData();
+
+    std::string printCombineAlgorithm(CombineAlgorithm algorithm);
+
+  private:
+    std::list<const Subject *> *subjects;
+    CombineAlgorithm combineAlgorithm;
+};
+
+const char * toString(Policy::CombineAlgorithm algorithm);
+
+#endif  //_POLICY_H
diff --git a/ace/include/ace/PolicyEffect.h b/ace/include/ace/PolicyEffect.h
new file mode 100644 (file)
index 0000000..43c79d7
--- /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    PolicyEffect.h
+ * @author  B.Grzelewski (b.grzelewski@samsung.com)
+ * @version 1.0
+ * @brief   This file contains the declaration of PolicyEffect type.
+ */
+#ifndef _SRC_ACCESS_CONTROL_COMMON_POLICY_EFFECT_H_
+#define _SRC_ACCESS_CONTROL_COMMON_POLICY_EFFECT_H_
+
+enum class PolicyEffect {
+    DENY = 0,
+    PERMIT,
+    PROMPT_ONESHOT,
+    PROMPT_SESSION,
+    PROMPT_BLANKET
+};
+
+inline static std::ostream & operator<<(std::ostream& stream,
+                                        PolicyEffect effect)
+{
+    switch (effect) {
+        case PolicyEffect::DENY:           stream << "DENY"; break;
+        case PolicyEffect::PERMIT:         stream << "PERMIT"; break;
+        case PolicyEffect::PROMPT_ONESHOT: stream << "PROMPT_ONESHOT"; break;
+        case PolicyEffect::PROMPT_SESSION: stream << "PROMPT_SESSION"; break;
+        case PolicyEffect::PROMPT_BLANKET: stream << "PROMPT_BLANKET"; break;
+        default: Assert(false && "Invalid PolicyEffect constant");
+    }
+    return stream;
+}
+
+#endif // _SRC_ACCESS_CONTROL_COMMON_POLICY_EFFECT_H_
diff --git a/ace/include/ace/PolicyEnforcementPoint.h b/ace/include/ace/PolicyEnforcementPoint.h
new file mode 100644 (file)
index 0000000..79e8e5b
--- /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.
+ */
+/**
+ * This class simply redirects the access requests to access control engine.
+ * The aim is to hide access control engine specific details from WRT modules.
+ * It also implements WRT_INTERFACE.h interfaces, so that ACE could access
+ * WRT specific and other information during the decision making.
+ *
+ * @file    security_logic.h
+ * @author  Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @author  Ming Jin(ming79.jin@samsung.com)
+ * @brief   Implementation file for security logic
+ */
+#ifndef POLICY_ENFORCEMENT_POINT_H
+#define POLICY_ENFORCEMENT_POINT_H
+
+#include <memory>
+#include <string>
+#include <map>
+
+//#include <glib/gthread.h>
+//#include <glib/gerror.h>
+//#include <glib.h>
+
+#ifdef DBUS_CONNECTION
+#include <dpl/event/inter_context_delegate.h>
+#include <dpl/event/property.h>
+#endif
+
+#include <ace/AbstractPolicyEnforcementPoint.h>
+#include <ace/PolicyResult.h>
+
+// Forwards
+class IWebRuntime;
+class IResourceInformation;
+class IOperationSystem;
+class PolicyEvaluator;
+class PolicyInformationPoint;
+class Request;
+
+class PolicyEnforcementPoint : public AbstractPolicyEnforcementPoint
+{
+  public:
+    OptionalExtendedPolicyResult checkFromCache(Request &request);
+    ExtendedPolicyResult check(Request &request);
+    OptionalExtendedPolicyResult check(Request &request,
+                               bool fromCacheOnly);
+
+    virtual ~PolicyEnforcementPoint();
+
+    class PEPException
+    {
+      public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, AlreadyInitialized)
+    };
+
+    /**
+     * This function take ownership of objects pass in call.
+     * Object will be deleted after call Deinitialize function.
+     */
+    void initialize(IWebRuntime *wrt,
+                    IResourceInformation *resource,
+                    IOperationSystem *operation);
+    void terminate();
+
+    void updatePolicy(const std::string &policy);
+    void updatePolicy();
+
+    PolicyEvaluator *getPdp() const { return this->m_pdp; }
+    PolicyInformationPoint *getPip() const { return this->m_pip; }
+
+  protected:
+    PolicyEnforcementPoint();
+    friend class SecurityLogic;
+  private: // private data
+    IWebRuntime                     *m_wrt;
+    IResourceInformation            *m_res;
+    IOperationSystem                *m_sys;
+    PolicyEvaluator                 *m_pdp;
+    PolicyInformationPoint          *m_pip;
+};
+
+#endif // POLICY_ENFORCEMENT_POINT_H
diff --git a/ace/include/ace/PolicyEvaluator.h b/ace/include/ace/PolicyEvaluator.h
new file mode 100644 (file)
index 0000000..786b6a9
--- /dev/null
@@ -0,0 +1,155 @@
+/*
+ * 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.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : PolicyEvaluator.h
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+
+#ifndef _POLICY_EVALUATOR_H
+#define _POLICY_EVALUATOR_H
+
+#include <memory>
+#include <set>
+#include <string>
+
+#ifdef DBUS_CONNECTION
+#include <dpl/event/event_listener.h>
+#endif
+#include <dpl/log/log.h>
+#include <dpl/noncopyable.h>
+
+#include <ace/AsyncVerdictResultListener.h>
+#include <ace/Attribute.h>
+#include <ace/ConfigurationManager.h>
+#include <ace/Constants.h>
+#include <ace/Effect.h>
+#include <ace/Policy.h>
+#include <ace/PolicyInformationPoint.h>
+#include <ace/PolicyResult.h>
+#include <ace/Request.h>
+#include <ace/Subject.h>
+#include <ace/Verdict.h>
+#include <ace/UserDecision.h>
+#include <ace/CombinerImpl.h>
+
+
+class PolicyEvaluator : DPL::Noncopyable
+{
+  protected:
+
+    /**
+     * Internal method used to initiate policy evaluation. Called after attribute set has been fetched
+     * by PIP.
+     * @param root root of the policies tree to be evaluated
+     */
+    virtual ExtendedEffect evaluatePolicies(const TreeNode * root);
+
+    // !! DEPRECATED !!
+    enum updateErrors
+    {
+        POLICY_PARSING_SUCCESS = 0,
+        POLICY_FILE_ERROR = 1,
+        PARSER_CREATION_ERROR,
+        POLICY_PARSING_ERROR
+    };
+  private:
+    AttributeSet m_attributeSet;
+
+    TreeNode *m_uniform_policy, *m_wac_policy, *m_tizen_policy;
+    std::string m_currentPolicyFile;
+    PolicyType m_policy_to_use;
+
+    Combiner * m_combiner;
+    AsyncVerdictResultListener * m_verdictListener;
+    PolicyInformationPoint * m_pip;
+
+    /**
+     * @return current policy Tree acc. to m_policy_to_use
+     */
+    TreeNode * getCurrentPolicyTree();
+
+    /**
+     * Method used to extract attributes from subtree defined by PolicySet
+     * @param root original TreeStructure root node
+     * @param newRoot copy of TreeStructure containing only policies that matches current request
+     *
+     */
+    void extractAttributesFromSubtree(const TreeNode *root);
+
+    /**
+     * Method used to extract attributes from Tree Structure
+     * @return pointer to set of attributes needed to evaluate current request
+     * @return if extraction has been successful
+     * TODO return reducte tree structure
+     * TODO change comments
+     */
+    bool extractAttributesFromRules(const TreeNode *);
+
+    /**
+     * Extracts attributes from target of a given policy that are required to be fetched by PIP
+     */
+    void extractTargetAttributes(const Policy *policy);
+    bool extractAttributes(TreeNode*);
+
+    OptionalExtendedPolicyResult getPolicyForRequestInternal(bool fromCacheOnly);
+    PolicyResult effectToPolicyResult(Effect effect);
+
+    /**
+     * Return safe policy tree in case of error with loading policy from file
+     */
+    TreeNode * getDefaultSafePolicyTree(void);
+
+  public:
+    PolicyEvaluator(PolicyInformationPoint * pip);
+
+    bool extractAttributesTest()
+    {
+        m_attributeSet.clear();
+        if (!extractAttributes(m_uniform_policy)) {
+            LogInfo("Warnign attribute set cannot be extracted. Returning Deny");
+            return true;
+        }
+
+        return extractAttributes(m_uniform_policy);
+    }
+
+    AttributeSet * getAttributeSet()
+    {
+        return &m_attributeSet;
+    }
+
+    virtual bool initPDP();
+    virtual ~PolicyEvaluator();
+    virtual ExtendedPolicyResult getPolicyForRequest(const Request &request);
+    virtual OptionalExtendedPolicyResult getPolicyForRequestFromCache(
+        const Request &request);
+    virtual OptionalExtendedPolicyResult getPolicyForRequest(const Request &request,
+                                                     bool fromCacheOnly);
+    bool fillAttributeWithPolicy();
+
+    virtual int updatePolicy(const char *);
+    // This function updates policy from well known locations
+    virtual void updatePolicy();
+
+    std::string getCurrentPolicy();
+};
+
+#endif  //_POLICYEVALUATOR_H
diff --git a/ace/include/ace/PolicyEvaluatorFactory.h b/ace/include/ace/PolicyEvaluatorFactory.h
new file mode 100644 (file)
index 0000000..73e36a1
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * 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        AbstractObjectFactory.h
+ * @author      Piotr Fatyga (p.fatyga@samsung.com)
+ * @version     0.1
+ * @brief
+ */
+
+#ifndef _ABSTRACTOBJECTFACTORY_H
+#define    _ABSTRACTOBJECTFACTORY_H
+
+#include <ace/PolicyEvaluator.h>
+
+class AbstractPolicyEvaluatorFactory
+{
+  public:
+    virtual PolicyEvaluator * createPolicyEvaluator(PolicyInformationPoint *pip)
+    const = 0;
+};
+
+class PolicyEvaluatorFactory : public AbstractPolicyEvaluatorFactory
+{
+  public:
+    PolicyEvaluator * createPolicyEvaluator(PolicyInformationPoint *pip) const
+    {
+        return new PolicyEvaluator(pip);
+    }
+};
+
+#endif    /* _ABSTRACTOBJECTFACTORY_H */
+
diff --git a/ace/include/ace/PolicyInformationPoint.h b/ace/include/ace/PolicyInformationPoint.h
new file mode 100644 (file)
index 0000000..ccb9763
--- /dev/null
@@ -0,0 +1,101 @@
+/*
+ * 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.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : PolicyInformationPoint.h
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+
+#ifndef _POLICY_INFORMATION_POINT_H
+#define _POLICY_INFORMATION_POINT_H
+
+#include <set>
+
+#include <ace/Attribute.h>
+#include <ace/Request.h>
+#include <ace/WRT_INTERFACE.h>
+#include <ace-dao-ro/BaseAttribute.h>
+#include <dpl/noncopyable.h>
+
+typedef int PipResponse;
+
+class PolicyInformationPoint : public DPL::Noncopyable
+{
+  private:
+
+    /** queries for interfaces*/
+    std::list<ATTRIBUTE> resourceAttributesQuery;
+    std::list<ATTRIBUTE> environmentAttributesQuery;
+    std::list<ATTRIBUTE> subjectAttributesQuery;
+    std::list<ATTRIBUTE> functionParamAttributesQuery;
+    std::list<ATTRIBUTE> widgetParamAttributesQuery;
+
+    /** create queries */
+    void createQueries(AttributeSet* attributes);
+
+    IWebRuntime* wrtInterface;
+    IResourceInformation* resourceInformation;
+    IOperationSystem* operationSystem;
+
+  public:
+    static const int ERROR_SHIFT_RESOURCE = 3;
+    static const int ERROR_SHIFT_OS = 6;
+    static const int ERROR_SHIFT_FP = 9;
+
+    /** Mask used to identify PIP error */
+    enum ResponseTypeMask
+    {
+        SUCCESS               = 0,
+        /* WebRuntime Error */
+        WRT_UNKNOWN_SUBJECT   = 1 << 0,
+        WRT_UNKNOWN_ATTRIBUTE = 1 << 1,
+        WRT_INTERNAL_ERROR    = 1 << 2,
+        /* Resource Information Storage Error */
+        RIS_UNKNOWN_RESOURCE  = 1 << 3,
+        RIS_UNKNOWN_ATTRIBUTE = 1 << 4,
+        RIS_INTERNAL_ERROR    = 1 << 5,
+        /*Operating system */
+        OS_UNKNOWN_ATTRIBUTE  = 1 << 6,
+        OS_INTERNAL_ERROR     = 1 << 7
+    };
+
+    //TODO add checking values of attributes
+    /** gather attributes values from adequate interfaces */
+    virtual PipResponse getAttributesValues(const Request* request,
+            AttributeSet* attributes);
+    virtual ~PolicyInformationPoint();
+    PolicyInformationPoint(IWebRuntime *wrt,
+            IResourceInformation *resource,
+            IOperationSystem *system);
+    virtual void update(IWebRuntime *wrt,
+            IResourceInformation *resource,
+            IOperationSystem *system)
+    {
+        wrtInterface = wrt;
+        resourceInformation = resource;
+        operationSystem = system;
+    }
+    IWebRuntime * getWebRuntime()
+    {
+        return wrtInterface;
+    }
+};
+
+#endif  //_POLICY_INFORMATION_POINT_H
diff --git a/ace/include/ace/PolicyResult.h b/ace/include/ace/PolicyResult.h
new file mode 100644 (file)
index 0000000..dfaa5e7
--- /dev/null
@@ -0,0 +1,278 @@
+/*
+ * 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 _SRC_ACCESS_CONTROL_COMMON_POLICY_RESULT_H_
+#define _SRC_ACCESS_CONTROL_COMMON_POLICY_RESULT_H_
+
+#include <dpl/assert.h>
+#include <dpl/optional_typedefs.h>
+#include <boost/optional.hpp>
+#include <ace/PolicyEffect.h>
+
+typedef boost::optional<PolicyEffect> OptionalPolicyEffect;
+
+class PolicyDecision
+{
+public:
+    enum Value { NOT_APPLICABLE = -1 };
+
+    PolicyDecision(PolicyEffect effect)
+      : m_isPolicyEffect(true)
+      , m_effect(effect)
+    {}
+
+    PolicyDecision(const PolicyDecision &decision)
+      : m_isPolicyEffect(decision.m_isPolicyEffect)
+      , m_effect(decision.m_effect)
+    {}
+
+    PolicyDecision(Value)
+      : m_isPolicyEffect(false)
+    {}
+
+    PolicyDecision& operator=(const PolicyDecision &second) {
+        if (this == &second)
+            return *this;
+
+        m_isPolicyEffect = second.m_isPolicyEffect;
+        m_effect = second.m_effect;
+
+        return *this;
+    }
+
+    bool operator==(const PolicyDecision &decision) const {
+        return (m_isPolicyEffect
+                 && decision.m_isPolicyEffect
+                 && m_effect == decision.m_effect)
+               || (!m_isPolicyEffect && !decision.m_isPolicyEffect);
+    }
+
+    bool operator==(Value) const {
+        return !m_isPolicyEffect;
+    }
+
+    bool operator!=(const PolicyDecision &decision) const {
+        return !(*this == decision);
+    }
+
+    bool operator!=(Value value) const {
+        return !(*this == value);
+    }
+
+    OptionalPolicyEffect getEffect() const
+    {
+        if (!m_isPolicyEffect) {
+            return OptionalPolicyEffect();
+        }
+        return OptionalPolicyEffect(m_effect);
+    }
+
+    std::ostream & toStream(std::ostream& stream) {
+        if (m_isPolicyEffect)
+            stream << m_effect;
+        else
+            stream << "NOT-APPLICABLE";
+        return stream;
+    }
+
+private:
+    bool m_isPolicyEffect;
+    PolicyEffect m_effect;
+};
+
+inline static bool operator==(PolicyEffect e, const PolicyDecision &d) {
+  return d.operator==(e);
+}
+
+inline static bool operator!=(PolicyEffect e, const PolicyDecision &d) {
+  return !(e == d);
+}
+
+inline static std::ostream & operator<<(std::ostream& stream,
+                                        PolicyDecision decision)
+{
+    return decision.toStream(stream);
+}
+
+class PolicyResult {
+public:
+    enum Value { UNDETERMINED = -2 };
+
+    // This constructor is required by dpl controller and by dpl optional
+    PolicyResult()
+      : m_isDecision(false)
+      , m_decision(PolicyDecision::Value::NOT_APPLICABLE) // don't care
+    {}
+
+    PolicyResult(PolicyEffect effect)
+      : m_isDecision(true)
+      , m_decision(effect)
+    {}
+
+    PolicyResult(const PolicyDecision &decision)
+      : m_isDecision(true)
+      , m_decision(decision)
+    {}
+
+    PolicyResult(const PolicyResult &result)
+      : m_isDecision(result.m_isDecision)
+      , m_decision(result.m_decision)
+    {}
+
+    PolicyResult(PolicyDecision::Value value)
+      : m_isDecision(true)
+      , m_decision(value)
+    {}
+
+    PolicyResult(Value)
+      : m_isDecision(false)
+      , m_decision(PolicyDecision::Value::NOT_APPLICABLE) // don't care
+    {}
+
+    PolicyResult& operator=(const PolicyResult &second) {
+        if (this == &second)
+            return *this;
+
+        m_isDecision = second.m_isDecision;
+        m_decision = second.m_decision;
+
+        return *this;
+    }
+
+    bool operator==(const PolicyResult &result) const {
+          return (m_isDecision
+                && result.m_isDecision
+                && m_decision == result.m_decision)
+                || (!m_isDecision && !result.m_isDecision);
+    }
+
+    bool operator==(Value) const {
+        return !m_isDecision;
+    }
+
+    bool operator!=(const PolicyResult &result) const {
+        return !(*this == result);
+    }
+
+    bool operator!=(Value value) const {
+        return !(*this == value);
+    }
+
+    OptionalPolicyEffect getEffect() const
+    {
+        if (!m_isDecision) {
+            return OptionalPolicyEffect();
+        }
+        return m_decision.getEffect();
+    }
+
+    static int serialize(const PolicyResult &policyResult)
+    {
+        if (!policyResult.m_isDecision) {
+            return BD_UNDETERMINED;
+        } else if (policyResult.m_decision ==
+            PolicyDecision::Value::NOT_APPLICABLE)
+        {
+            return BD_NOT_APPLICABLE;
+        } else if (policyResult.m_decision == PolicyEffect::PROMPT_BLANKET) {
+            return BD_PROMPT_BLANKET;
+        } else if (policyResult.m_decision == PolicyEffect::PROMPT_SESSION) {
+            return BD_PROMPT_SESSION;
+        } else if (policyResult.m_decision == PolicyEffect::PROMPT_ONESHOT) {
+            return BD_PROMPT_ONESHOT;
+        } else if (policyResult.m_decision == PolicyEffect::PERMIT) {
+            return BD_PERMIT;
+        } else if (policyResult.m_decision == PolicyEffect::DENY) {
+            return BD_DENY;
+        }
+        Assert(false && "Unknown value of policyResult.");
+    }
+
+    static PolicyResult deserialize(int dec){
+        switch (dec) {
+            case BD_DENY:
+                return PolicyEffect::DENY;
+            case BD_PERMIT:
+                return PolicyEffect::PERMIT;
+            case BD_PROMPT_ONESHOT:
+                return PolicyEffect::PROMPT_ONESHOT;
+            case BD_PROMPT_SESSION:
+                return PolicyEffect::PROMPT_SESSION;
+            case BD_PROMPT_BLANKET:
+                return PolicyEffect::PROMPT_BLANKET;
+            case BD_NOT_APPLICABLE:
+                return PolicyDecision::Value::NOT_APPLICABLE;
+            case BD_UNDETERMINED:
+                return Value::UNDETERMINED;
+        }
+        Assert(false && "Broken database");
+    }
+
+    std::ostream & toStream(std::ostream& stream) {
+        if (m_isDecision)
+            stream << m_decision;
+        else
+            stream << "UNDETERMINED";
+        return stream;
+    }
+
+private:
+    static const int BD_UNDETERMINED = 6;
+    static const int BD_NOT_APPLICABLE = 5;
+    static const int BD_PROMPT_BLANKET = 4;
+    static const int BD_PROMPT_SESSION = 3;
+    static const int BD_PROMPT_ONESHOT = 2;
+    static const int BD_PERMIT = 1;
+    static const int BD_DENY = 0;
+
+    bool m_isDecision;
+    PolicyDecision m_decision;
+};
+
+inline static bool operator==(const PolicyDecision &d, const PolicyResult &r) {
+    return r == d;
+}
+
+inline static bool operator!=(const PolicyDecision &d, const PolicyResult &r) {
+    return !(d == r);
+}
+
+inline static bool operator==(const PolicyEffect &e, const PolicyResult &r) {
+    return e == r;
+}
+
+inline static bool operator!=(const PolicyEffect &e, const PolicyResult &r) {
+    return !(e == r);
+}
+
+inline static std::ostream & operator<<(std::ostream& stream,
+                                        PolicyResult result)
+{
+    return result.toStream(stream);
+}
+
+struct ExtendedPolicyResult {
+    ExtendedPolicyResult(const PolicyResult pr = PolicyEffect::DENY, int rule = -1)
+      : policyResult(pr)
+      , ruleId(rule)
+    {}
+    PolicyResult policyResult;
+    int ruleId;
+};
+
+typedef boost::optional<ExtendedPolicyResult> OptionalExtendedPolicyResult;
+
+#endif // _SRC_ACCESS_CONTROL_COMMON_POLICY_RESULT_H_
diff --git a/ace/include/ace/PolicySet.h b/ace/include/ace/PolicySet.h
new file mode 100644 (file)
index 0000000..de12394
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ * 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.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : PolicySet.h
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+
+#if !defined(_POLICYSET_H)
+#define _POLICYSET_H
+
+#include "Policy.h"
+#include <iostream>
+
+class PolicySet : public Policy
+{
+  public:
+
+    //TODO Clean this class
+    //PolicySet(CombineAlgorithm algorithm, std::list<Attribute> * targetAttr,const std::string & subjectId)
+    //        : Policy(algorithm,targetAttr,subjectId)
+    //    {}
+    PolicySet()
+    {
+    }
+    ~PolicySet()
+    {
+    }
+};
+
+#endif  //_POLICYSET_H
diff --git a/ace/include/ace/Preference.h b/ace/include/ace/Preference.h
new file mode 100644 (file)
index 0000000..c37fce8
--- /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.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : Preference.h
+//  @ Date : 2009-05-2
+//  @ Author : Samsung
+//
+//
+
+#ifndef _Preference_H_
+#define _Preference_H_
+
+#include <map>
+#include <string>
+
+#include <ace-dao-ro/PreferenceTypes.h>
+
+typedef AceDB::PreferenceTypes Preference;
+typedef AceDB::PreferenceTypesMap PreferenceMap;
+
+#endif  //_Preference_H
+
diff --git a/ace/include/ace/PromptDecision.h b/ace/include/ace/PromptDecision.h
new file mode 100644 (file)
index 0000000..9bdae43
--- /dev/null
@@ -0,0 +1,41 @@
+/*
+ * 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 _SRC_ACCESS_CONTROL_COMMON_PROMPT_DECISION_H_
+#define _SRC_ACCESS_CONTROL_COMMON_PROMPT_DECISION_H_
+
+#include <boost/optional.hpp>
+#include <dpl/optional_typedefs.h>
+
+enum class PromptDecision {
+    ALLOW_ALWAYS,
+    DENY_ALWAYS,
+    ALLOW_THIS_TIME,
+    DENY_THIS_TIME,
+    ALLOW_FOR_SESSION,
+    DENY_FOR_SESSION
+};
+
+typedef boost::optional<PromptDecision> OptionalPromptDecision;
+
+struct CachedPromptDecision {
+    PromptDecision decision;
+    DPL::OptionalString session;
+};
+
+typedef boost::optional<CachedPromptDecision> OptionalCachedPromptDecision;
+
+#endif // _SRC_ACCESS_CONTROL_COMMON_PROMPT_DECISION_H_
diff --git a/ace/include/ace/Request.h b/ace/include/ace/Request.h
new file mode 100644 (file)
index 0000000..5e5fa9a
--- /dev/null
@@ -0,0 +1,104 @@
+/*
+ * 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.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : Request.h
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+
+#ifndef _REQUEST_H_
+#define _REQUEST_H_
+
+#include <set>
+#include <string>
+#include <vector>
+
+#include <ace-dao-ro/IRequest.h>
+#include <ace/WRT_INTERFACE.h>
+
+class Request : public AceDB::IRequest
+{
+  public:
+    typedef std::string DeviceCapability;
+    typedef std::set<DeviceCapability> DeviceCapabilitySet;
+
+    enum ApplicationType {
+        APP_TYPE_TIZEN,
+        APP_TYPE_WAC20,
+        APP_TYPE_UNKNOWN
+    };
+
+    Request(WidgetHandle widgetHandle,
+            WidgetExecutionPhase phase,
+            IFunctionParam *functionParam = 0)
+      : m_widgetHandle(widgetHandle)
+      , m_phase(phase)
+      , m_functionParam(functionParam)
+      , m_appType(APP_TYPE_UNKNOWN)
+    {}
+
+    WidgetHandle getWidgetHandle() const
+    {
+        return m_widgetHandle;
+    }
+
+    WidgetExecutionPhase getExecutionPhase() const
+    {
+        return m_phase;
+    }
+
+    IFunctionParam *getFunctionParam() const
+    {
+        return m_functionParam;
+    }
+
+    void addDeviceCapability(const std::string& device)
+    {
+        m_devcapSet.insert(device);
+    }
+
+    DeviceCapabilitySet getDeviceCapabilitySet() const
+    {
+        return m_devcapSet;
+    }
+
+    void setAppType(ApplicationType appType)
+    {
+        m_appType = appType;
+    }
+
+    ApplicationType getAppType() const
+    {
+        return m_appType;
+    }
+
+  private:
+    WidgetHandle m_widgetHandle;
+    WidgetExecutionPhase m_phase;
+    //! \brief list of function param (only for intercept)
+    IFunctionParam *m_functionParam;
+    //! \brief Set of defice capabilities
+    DeviceCapabilitySet m_devcapSet;
+    ApplicationType m_appType;
+};
+
+typedef std::vector <Request> Requests;
+
+#endif  //_REQUEST_H_
diff --git a/ace/include/ace/Rule.h b/ace/include/ace/Rule.h
new file mode 100644 (file)
index 0000000..dc64389
--- /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.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : Rule.h
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+
+#if !defined(_RULE_H)
+#define _RULE_H
+
+#include "Attribute.h"
+#include "Effect.h"
+#include "Condition.h"
+#include <dpl/assert.h>
+
+class Rule : public AbstractTreeElement
+{
+  public:
+
+    ExtendedEffect evaluateRule(const AttributeSet * attrSet) const;
+
+    Rule()
+      : effect(Inapplicable)
+    {
+        //TODO we should set it to deny or smth, not inapplicable
+    }
+
+    void setEffect(ExtendedEffect effect)
+    {
+        //We should not allow to set "Inapplicable" effect.
+        //Rules cannot have effect that is inapplicable, evaluation of the rules may however
+        //render the effect inapplicable.
+        Assert(effect.getEffect() != Inapplicable);
+        this->effect = effect;
+    }
+    void setCondition(Condition condition)
+    {
+        this->condition = condition;
+    }
+    void getAttributes(AttributeSet * attrSet)
+    {
+        condition.getAttributes(attrSet);
+    }
+
+    //DEBUG methods
+    std::string printEffect(const ExtendedEffect &effect) const;
+    void printData();
+
+  private:
+
+    ExtendedEffect effect;
+    Condition condition;
+};
+
+#endif  //_RULE_H
diff --git a/ace/include/ace/SettingsLogic.h b/ace/include/ace/SettingsLogic.h
new file mode 100644 (file)
index 0000000..e0d1fdb
--- /dev/null
@@ -0,0 +1,88 @@
+/*
+ * 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       SettingsLogic.h
+ * @author     Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version    0.1
+ * @brief      Header file for class getting/setting user/global ACE settings
+ */
+
+#ifndef WRT_SRC_ACCESS_CONTROL_LOGIC_SETTINGS_LOGIC_H_
+#define WRT_SRC_ACCESS_CONTROL_LOGIC_SETTINGS_LOGIC_H_
+
+#include <set>
+#include <list>
+#include <map>
+#include <string>
+#include <ace-dao-ro/PreferenceTypes.h>
+#include <ace/Request.h>
+#include <ace/PermissionTriple.h>
+#include <ace-dao-rw/AceDAO.h>
+#include <ace-dao-ro/common_dao_types.h>
+
+class SettingsLogic
+{
+  public:
+    class Exception
+    {
+      public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, DatabaseError)
+    };
+
+    // global settings
+    static AceDB::PreferenceTypes findGlobalUserSettings(
+            const std::string &resource,
+            WidgetHandle handler);
+
+    static AceDB::PreferenceTypes findGlobalUserSettings(
+            const Request &request);
+
+    // resource settings
+    static AceDB::PreferenceTypes getDevCapSetting(
+            const std::string &request);
+    static void getDevCapSettings(AceDB::PreferenceTypesMap *preferences);
+    static void setDevCapSetting(const std::string &resource,
+            AceDB::PreferenceTypes preference);
+    static void setAllDevCapSettings(
+            const std::list<std::pair<const std::string *,
+                    AceDB::PreferenceTypes> > &resourcesList);
+    static void removeDevCapSetting(const std::string &resource);
+    static void updateDevCapSetting(const std::string &resource,
+            AceDB::PreferenceTypes p);
+
+    // user settings
+    static AceDB::PreferenceTypes getWidgetDevCapSetting(
+            const std::string &resource,
+            WidgetHandle handler);
+    static void getWidgetDevCapSettings(PermissionList *permissions);
+    static void setWidgetDevCapSetting(const std::string &resource,
+            WidgetHandle handler,
+            AceDB::PreferenceTypes preference);
+    static void setWidgetDevCapSettings(const PermissionList &tripleList);
+    static void removeWidgetDevCapSetting(const std::string &resource,
+            WidgetHandle handler);
+
+  private:
+    SettingsLogic()
+    {
+    }
+
+};
+
+#endif /* WRT_SRC_ACCESS_CONTROL_LOGIC_SETTINGS_LOGIC_H_ */
diff --git a/ace/include/ace/Subject.h b/ace/include/ace/Subject.h
new file mode 100644 (file)
index 0000000..5176c99
--- /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:   Subject.h
+// Author: notroot
+//
+// Created on June 2, 2009, 8:47 AM
+//
+
+#ifndef _SUBJECT_H
+#define    _SUBJECT_H
+
+#include <set>
+#include <list>
+#include <iostream>
+#include <dpl/assert.h>
+#include <dpl/noncopyable.h>
+
+#include "Attribute.h"
+
+class Subject : DPL::Noncopyable
+{
+    std::string subjectId;
+    std::list<Attribute> targetAttributes;
+
+  public:
+    Subject()
+    {}
+
+    const std::list<Attribute>& getTargetAttributes() const;
+
+    void setSubjectId(const std::string & subjectId)
+    {
+        this->subjectId = subjectId;
+    }
+
+    //TODO maybe we should remove that becuase this causes a memory leak right now!! [CR] maybe thats true, maybe whe can remove this fun
+    // KW    void setTargetAttributes(std::list<Attribute> * targetAttributes){ this->targetAttributes = targetAttributes; }
+
+    const std::string & getSubjectId() const
+    {
+        return this->subjectId;
+    }
+
+    void addNewAttribute(Attribute & attr)
+    {
+        this->targetAttributes.push_back(attr);
+    }
+
+    //TODO in 1.0 change to true/false/undetermined
+    bool matchSubject(const AttributeSet *attrSet,
+            bool &isUndetermined) const;
+
+    ~Subject()
+    {}
+};
+
+#endif    /* _SUBJECT_H */
+
diff --git a/ace/include/ace/TestTimer.h b/ace/include/ace/TestTimer.h
new file mode 100644 (file)
index 0000000..1f07e61
--- /dev/null
@@ -0,0 +1,41 @@
+/*
+ * 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 _TEST_TIMER_H
+#define _TEST_TIMER_H
+
+#include <time.h>
+
+class TestTimer
+{
+    time_t startt, endt;
+
+  public:
+    void start()
+    {
+        time(&startt);
+    }
+    void stop()
+    {
+        time(&endt);
+    }
+    double getTime()
+    {
+        return difftime(endt, startt);
+    }
+};
+
+#endif  //_TEST_TIMER_H
+
diff --git a/ace/include/ace/TreeNode.h b/ace/include/ace/TreeNode.h
new file mode 100644 (file)
index 0000000..473c26f
--- /dev/null
@@ -0,0 +1,130 @@
+/*
+ * 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.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : TreeNode.h
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+
+#ifndef _TREE_NODE_H
+#define _TREE_NODE_H
+
+#include <iostream>
+#include <list>
+
+#include <ace/AbstractTreeElement.h>
+
+class TreeNode;
+
+typedef std::list<TreeNode *> ChildrenSet;
+typedef std::list<TreeNode *>::iterator ChildrenIterator;
+typedef std::list<TreeNode *>::const_iterator ChildrenConstIterator;
+
+class TreeNode
+{
+  public:
+    //TODO nazwac pozadnie TYPY - moze jakas konwencja ... ??!!
+    enum TypeID { Policy =0, PolicySet=1, Rule=2};
+
+    const ChildrenSet  & getChildrenSet() const
+    {
+        return children;
+    }
+
+    TreeNode * getParent() const
+    {
+        return this->parent;
+    }
+
+    void setParent(TreeNode *parent)
+    {
+        this->parent = parent;
+    }
+
+    TypeID getTypeID() const
+    {
+        return this->typeID;
+    }
+
+    void addChild(TreeNode *child)
+    {
+        child->setParent(this);
+        children.push_back(child);
+    }
+
+    /**
+     * Clone the node
+     */
+    // KW        TreeNode * clone() { return new TreeNode(NULL,this->getTypeID(),this->getElement()); }
+
+    TreeNode(TreeNode * parent,
+            TypeID type,
+            AbstractTreeElement * element) :
+        parent(parent),
+        typeID(type),
+        element(element)
+    {
+    }
+
+    AbstractTreeElement * getElement() const
+    {
+        return element;
+    }
+
+  private:
+    virtual ~TreeNode();
+
+  public:
+    /*
+     * It is common that we create a copy of tree structure created out of xml file. However we don't want to
+     * copy abstract elements ( Policies and Rules ) because we need them only for reading. We want to modify the
+     * tree structure though. Therefore we copy TreeNode. When the copy of the original tree is being destroyed method
+     * releaseTheSubtree should be called on "root". It automatically traverse the tree and call TreeNode destructors for
+     * each TreeNode in the tree. It doesn't remove the abstract elements in the tree ( there is always at most one abstract
+     * element instance, when tree is copied it is a shallow copy.
+     * When we want to completely get rid of the the tree and abstract elements we have to call releaseResources on tree root.
+     * We may want to do this for instance when we want to serialize the tree to disc. releaseResource method traverses the tree
+     * and releses the resources, as well as the TreeNode so NO releaseTheSubtree is required any more
+     */
+    void releaseResources();
+
+    /**
+     * Used to delete the copies of tree structure. The original tree structure should be removed with releaseResources method.
+     * ReleaseTheSubtree method doesn't delete the abstract elements, only TreeNodes. It traverses the whole tree, so it should be
+     * called on behalf of root of the tree
+     */
+    // KW        void releaseTheSubtree();
+
+    friend std::ostream & operator<<(std::ostream & out,
+            const TreeNode * node);
+    // KW        void printSubtree();
+
+  private:
+    // KW    TreeNode(const TreeNode& pattern){ (void)pattern; }
+
+    std::list<TreeNode *> children;
+    TreeNode * parent;
+    //TODO standarize ID case
+    TypeID typeID;
+    AbstractTreeElement * element;
+    static int level;
+};
+
+#endif  //_TREE_NODE_H
diff --git a/ace/include/ace/UserDecision.h b/ace/include/ace/UserDecision.h
new file mode 100644 (file)
index 0000000..67bdbcf
--- /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.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : UserDecision.h
+//  @ Date : 2009-05-22
+//  @ Author : Samsung
+//
+//
+
+#ifndef _USERDECISION_H
+#define _USERDECISION_H
+
+#include <ace/Verdict.h>
+#include <ace-dao-ro/ValidityTypes.h>
+
+typedef AceDB::ValidityTypes Validity;
+
+const char * toString(Validity validity);
+
+#endif  //_USERDECISION_H
+
diff --git a/ace/include/ace/Verdict.h b/ace/include/ace/Verdict.h
new file mode 100644 (file)
index 0000000..83d2d79
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * 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.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : Verdict.h
+//  @ Date : 2009-05-2
+//  @ Author : Samsung
+//
+//
+
+#ifndef _VERDICT_H
+#define _VERDICT_H
+
+#include <string>
+#include <ace-dao-ro/VerdictTypes.h>
+#include <ace-dao-ro/TimedVerdict.h>
+
+typedef AceDB::VerdictTypes Verdict;
+//typedef AceDB::TimedVerdict TimedVerdict;
+
+const char * toString(Verdict verditct);
+
+#endif  //_VERDICT_H
+
diff --git a/ace/include/ace/WRT_INTERFACE.h b/ace/include/ace/WRT_INTERFACE.h
new file mode 100644 (file)
index 0000000..ac8ab93
--- /dev/null
@@ -0,0 +1,144 @@
+/*
+ * 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 _WRT_INERFACE_4_ACE_EXAMPLE_H_
+#define _WRT_INERFACE_4_ACE_EXAMPLE_H_
+
+#include <list>
+#include <map>
+#include <string>
+
+typedef int WidgetHandle;
+
+class Request;
+
+enum WidgetExecutionPhase
+{
+    WidgetExecutionPhase_Unknown           = 0,
+    WidgetExecutionPhase_WidgetInstall     = 1 << 0,
+    WidgetExecutionPhase_WidgetInstantiate = 1 << 1,
+    WidgetExecutionPhase_WebkitBind        = 1 << 2,
+    WidgetExecutionPhase_Invoke            = 1 << 3
+};
+
+struct RequestContext
+{
+    const WidgetHandle Handle;
+    WidgetExecutionPhase Phase;
+
+    RequestContext(WidgetHandle handle,
+            WidgetExecutionPhase phase) :
+        Handle(handle),
+        Phase(phase)
+    {
+    }
+};
+
+// Pair of pointer to attribute name and pointer to list of value for
+// this attribute name
+typedef std::pair< const std::string* const, std::list<std::string>* >
+ATTRIBUTE;
+
+/*
+ * Each function should return 0 as success and positive value as error
+ *
+ * Possible return value:
+ * 0 - succes
+ * 1 - subjectId/resourceId name unknown
+ * 2 - unknown attribute name
+ * 4 - interface error
+ **/
+
+/************** Web Runtime ********************/
+
+class IWebRuntime
+{
+  public:
+
+    /**
+     * gather and set attributes values for specified subjectId
+     * and attribute name
+     * @param subjectId is a name of subject (widget or internet site URI )
+     * @param attributes is a list of pairs(
+     *   first:   pointer to attribute name
+     *   second: list of values for attribute (std::string)   -
+     *   its a list of string (BONDI requirement), but usually there will
+     *   be only one string
+     * */
+    virtual int getAttributesValues(const Request &request,
+            std::list<ATTRIBUTE> *attributes) = 0;
+
+    /*return current sessionId */
+    virtual std::string getSessionId(const Request &request) = 0;
+
+    virtual ~IWebRuntime()
+    {
+    }
+};
+
+/************** Resource Information ********************/
+class IResourceInformation
+{
+  public:
+    /**
+     * gather and set attributes values for specified resourceId
+     * and attribute name
+     * @param resourceId is a name of subject (widget or internet site URI )
+     * @param attributes is a list of pairs(
+     *   first:   pointer to attribute name
+     *   second: list of values for attribute (std::string)  -
+     *   its a list of string (BONDI requirement), but usually there will
+     *   be only one string
+     * */
+    virtual int getAttributesValues(const Request &request,
+            std::list<ATTRIBUTE> *attributes) = 0;
+
+    virtual ~IResourceInformation()
+    {
+    }
+};
+
+/**************  Operation System  ********************/
+class IOperationSystem
+{
+  public:
+
+    /**
+     * gather and set attributes values for specified attribute name
+     * @param attributes is a list of pairs(
+     *   first:   pointer to attribute name
+     *   second: list of values for attribute (std::string)  -
+     *   its a list of string (BONDI requirement), but usually
+     *   there will be only one string
+     * */
+    virtual int getAttributesValues(const Request &request,
+            std::list<ATTRIBUTE> *attributes) = 0;
+
+    virtual ~IOperationSystem()
+    {
+    }
+};
+
+class IFunctionParam
+{
+  public:
+    virtual int getAttributesValues(const Request &request,
+            std::list<ATTRIBUTE> *attributes) = 0;
+    virtual ~IFunctionParam()
+    {
+    }
+};
+
+#endif //_WRT_INERFACE_4_ACE_EXAMPLE_H_
diff --git a/ace/include/ace/WidgetUsageModel.h b/ace/include/ace/WidgetUsageModel.h
new file mode 100644 (file)
index 0000000..094e6ab
--- /dev/null
@@ -0,0 +1,99 @@
+/*
+ * 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.
+ */
+//
+//  @ Project : Access Control Engine
+//  @ File Name : UserDecision.h
+//  @ Date : 2009-05-22
+//  @ Author : Samsung
+//
+//
+
+#ifndef _WIDGET_USAGE_H
+#define _WIDGET_USAGE_H
+
+#ifdef DBUS_CONNECTION
+#include <dpl/event/event_support.h>
+#endif
+
+#include "Request.h"
+#include "AsyncVerdictResultListener.h"
+
+enum UsageValidity
+{
+    USAGE_UNKNOWN,
+    USAGE_ONCE,
+    USAGE_SESSION,
+    USAGE_ALWAYS
+};
+
+enum UsageVerdict
+{
+    USAGE_VERDICT_PERMIT,
+    USAGE_VERDICT_DENY,
+    USAGE_VERDICT_INAPPLICABLE,
+    USAGE_VERDICT_UNDETERMINED,
+    USAGE_VERDICT_UNKNOWN,
+    USAGE_VERDICT_ERROR
+};
+//Forward declaration
+class PolicyEvaluator;
+
+class PolicyEvaluatorData
+{
+  private:
+    Request m_request;
+    UsageValidity m_validity;
+    UsageVerdict m_verdict;
+    AsyncVerdictResultListener *m_listener;
+  public:
+
+    PolicyEvaluatorData(const Request& request,
+            AsyncVerdictResultListener *listener) :
+        m_request(request),
+        m_validity(USAGE_UNKNOWN),
+        m_verdict(USAGE_VERDICT_ERROR),
+        m_listener(listener)
+    {
+    }
+
+    // KW     UsageValidity getValidity() const {
+    // KW         return m_validity;
+    // KW     }
+    // KW
+    // KW     UsageVerdict getVerdict() const {
+    // KW         return m_verdict;
+    // KW     }
+    // KW
+    // KW     void setValidity(UsageValidity validity) {
+    // KW         this->m_validity = validity;
+    // KW     }
+    // KW
+    // KW     void setVerdict(UsageVerdict verdict) {
+    // KW         this->m_verdict = verdict;
+    // KW     }
+
+    const Request& getRequest() const
+    {
+        return m_request;
+    }
+
+    AsyncVerdictResultListener* getListener() const
+    {
+        return m_listener;
+    }
+};
+
+#endif  //_USERDECISION_H
diff --git a/ace/include/ace/acf_consts.h b/ace/include/ace/acf_consts.h
new file mode 100644 (file)
index 0000000..93ecfae
--- /dev/null
@@ -0,0 +1,41 @@
+/*
+ * 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.
+ */
+/*
+ * This file contain consts for Signing Template and Policy Manager
+ * This values will be used to specified and identified algorithms in xml policy documents.
+ * Its consistent with BONDI 1.0 released requirements
+ *
+ * NOTE: This values should be verified when ACF will be updated to the latest version of BONDI requirements
+ * This values comes from widget digital signature 1.0 - required version of this doc is very important
+ *
+ **/
+
+#ifndef ACF_CONSTS_TYPES_H
+#define ACF_CONSTS_TYPES_H
+
+//Digest Algorithms
+extern const char* DIGEST_ALG_SHA256;
+
+//Canonicalization Algorithms
+extern const char* CANONICAL_ALG_C14N;
+
+//Signature Algorithms
+extern const char* SIGNATURE_ALG_RSA_with_SHA256;
+extern const char* SIGNATURE_ALG_DSA_with_SHA1;
+extern const char* SIGNATURE_ALG_ECDSA_with_SHA256;
+
+#endif
+
diff --git a/ace/include/ace/parser.h b/ace/include/ace/parser.h
new file mode 100644 (file)
index 0000000..26f15e2
--- /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.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : parser.h
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+
+#ifndef _PARSER_H_
+#define _PARSER_H_
+
+//#include "/usr/include/libxml2/libxml/parser.h"
+#include <string>
+#include <libxml/xmlreader.h>
+#include <libxml/c14n.h>
+#include <libxml/xpath.h>
+#include <libxml/xpathInternals.h>
+
+#include "Policy.h"
+#include "PolicySet.h"
+#include "Request.h"
+#include "Rule.h"
+#include "Attribute.h"
+#include "TreeNode.h"
+#include "Subject.h"
+#include "Condition.h"
+#include "Effect.h"
+
+#define whitespaces " \n\t\r"
+
+enum CanonicalizationAlgorithm
+{
+    C14N,
+    C14NEXCLUSIVE
+};
+
+class Parser
+{
+  private:
+    RuleId ruleId;
+    xmlTextReaderPtr reader;
+
+    TreeNode * root;
+    TreeNode * currentRoot;
+    Subject * currentSubject;
+    Condition * currentCondition;
+    Attribute * currentAttribute;
+    std::string * currentText;
+
+    bool processingSignature;
+    bool canonicalizeOnce;
+
+    void processNode(xmlTextReaderPtr reader);
+
+    //Node Handlers
+    void endNodeHandler(xmlTextReaderPtr reader);
+    void textNodeHandler(xmlTextReaderPtr reader);
+    void startNodeHandler(xmlTextReaderPtr reader);
+
+    //Node names handlers
+    void handleAttr(xmlTextReaderPtr reader);
+    void handleRule(xmlTextReaderPtr reader);
+    void handleSubject();
+    void handleCondition(xmlTextReaderPtr reader);
+    void handleSubjectMatch(xmlTextReaderPtr reader);
+    void handleMatch(xmlTextReaderPtr reader,
+            Attribute::Type);
+    void handlePolicy(xmlTextReaderPtr reader,
+            TreeNode::TypeID type);
+
+    //helpers
+    Policy::CombineAlgorithm convertToCombineAlgorithm(xmlChar*);
+    ExtendedEffect convertToEffect(xmlChar *effect);
+    Attribute::Match convertToMatchFunction(xmlChar * func);
+    void consumeCurrentText();
+    void consumeCurrentAttribute();
+    void consumeSubjectMatch(xmlChar * value = NULL);
+    void consumeCurrentSubject();
+    void consumeCurrentCondition();
+    void trim(std::string *);
+    // KW     void canonicalize(const char *, const char *, CanonicalizationAlgorithm canonicalizationAlgorithm);
+    // KW     int extractNodeToFile(xmlTextReaderPtr reader, const char * filename);
+
+    static const char *TOKEN_PARAM;
+  public:
+    Parser();
+    ~Parser();
+    TreeNode * parse(const std::string& filename, const std::string& schema);
+};
+
+#endif  //_PARSER_H
diff --git a/ace/orm/ace_db b/ace/orm/ace_db
new file mode 100644 (file)
index 0000000..7f90ed4
--- /dev/null
@@ -0,0 +1,92 @@
+SQL(
+    PRAGMA foreign_keys = ON;
+    BEGIN TRANSACTION;
+)
+
+CREATE_TABLE(AcePolicyResult)
+    COLUMN_NOT_NULL(decision,       INTEGER,    check(decision between 0 and 6))
+    COLUMN_NOT_NULL(hash,           TEXT,)
+    COLUMN_NOT_NULL(rule_id,        INTEGER)
+    TABLE_CONSTRAINTS(
+        PRIMARY KEY(hash)
+    )
+CREATE_TABLE_END()
+
+CREATE_TABLE(AcePromptDecision)
+    COLUMN_NOT_NULL(app_id,         INTEGER,)
+    COLUMN_NOT_NULL(decision,       INTEGER,   check(decision between 0 and 5))
+    COLUMN(session,                 TEXT,)
+    COLUMN_NOT_NULL(rule_id,        INTEGER,)
+    TABLE_CONSTRAINTS(
+        PRIMARY KEY(app_id,rule_id)
+    )
+CREATE_TABLE_END()
+
+CREATE_TABLE(AceAttribute)
+    COLUMN_NOT_NULL(attr_id,        INTEGER,    primary key autoincrement)
+    COLUMN_NOT_NULL(name,           TEXT,)
+    COLUMN_NOT_NULL(type,           INTEGER,    check(type between 0 and 4))
+
+    TABLE_CONSTRAINTS(unique(name,type))
+CREATE_TABLE_END()
+
+CREATE_TABLE(AceSubject)
+    COLUMN_NOT_NULL(subject_id,     INTEGER,    primary key autoincrement)
+    COLUMN_NOT_NULL(id_uri,         TEXT,       unique)
+CREATE_TABLE_END()
+
+CREATE_TABLE(AceDevCap)
+    COLUMN_NOT_NULL(resource_id,    INTEGER,    primary key autoincrement)
+    COLUMN_NOT_NULL(id_uri,         TEXT,       unique)
+    COLUMN_NOT_NULL(general_setting,INTEGER,    check(general_setting between -1 and 4))
+CREATE_TABLE_END()
+
+CREATE_TABLE(AceWidgetDevCapSetting)
+    COLUMN_NOT_NULL(app_id,         INTEGER,    not null)
+    COLUMN_NOT_NULL(resource_id,    INTEGER,    references AceDevCap(resource_id))
+    COLUMN_NOT_NULL(access_value,   INTEGER,    check(access_value between -1 and 4))
+
+    TABLE_CONSTRAINTS(unique(app_id,resource_id))
+CREATE_TABLE_END()
+
+CREATE_TABLE(AceRequestedDevCaps)
+    COLUMN_NOT_NULL(app_id,        INTEGER,  not null)
+    COLUMN_NOT_NULL(grant_smack,   INTEGER,  not null)
+    COLUMN_NOT_NULL(dev_cap,       TEXT,)
+
+    TABLE_CONSTRAINTS(unique(app_id,dev_cap))
+CREATE_TABLE_END()
+
+CREATE_TABLE(AceAcceptedFeature)
+    COLUMN_NOT_NULL(app_id,        INTEGER,  not null)
+    COLUMN_NOT_NULL(feature,       TEXT,     not null)
+
+    TABLE_CONSTRAINTS(unique(app_id,feature))
+CREATE_TABLE_END()
+
+CREATE_TABLE(WidgetInfo)
+    COLUMN_NOT_NULL(app_id,         INTEGER,      PRIMARY KEY)
+    COLUMN(widget_type,             INT,          DEFAULT 1)
+    COLUMN(widget_id,               VARCHAR(256), DEFAULT '')
+    COLUMN(widget_version,          VARCHAR(256), DEFAULT '')
+    COLUMN(author_name,             VARCHAR(256), DEFAULT '')
+    COLUMN(share_href,              VARCHAR(256), DEFAULT '')
+CREATE_TABLE_END()
+
+CREATE_TABLE(WidgetCertificateFingerprint)
+    COLUMN_NOT_NULL(app_id,     INT,)
+    COLUMN_NOT_NULL(owner,      INT,)
+    COLUMN_NOT_NULL(chainid,    INT,)
+    COLUMN_NOT_NULL(type,       INT,)
+    COLUMN(md5_fingerprint,     VARCHAR(64),)
+    COLUMN(sha1_fingerprint,    VARCHAR(64),)
+    COLUMN(common_name,         VARCHAR(64),)
+    TABLE_CONSTRAINTS(
+        PRIMARY KEY (app_id, chainid, owner, type)
+        FOREIGN KEY (app_id) REFERENCES WidgetInfo (app_id) ON DELETE CASCADE
+    )
+CREATE_TABLE_END()
+
+SQL(
+    COMMIT;
+)
diff --git a/ace/orm/ace_db_definitions b/ace/orm/ace_db_definitions
new file mode 100644 (file)
index 0000000..46836e9
--- /dev/null
@@ -0,0 +1,6 @@
+DATABASE_START(ace)
+
+#include "ace_db"
+#include "version_db"
+
+DATABASE_END()
diff --git a/ace/orm/ace_db_sql_generator.h b/ace/orm/ace_db_sql_generator.h
new file mode 100644 (file)
index 0000000..5af05ac
--- /dev/null
@@ -0,0 +1,27 @@
+/*
+ * 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        wrt_db_sql_generator.h
+ * @author      Bartosz Janiak (b.janiak@samsung.com)
+ * @version     1.0
+ * @brief       Macro definitions for generating the SQL input file from database definition.
+ */
+
+//Do not include this file directly! It is used only for SQL code generation.
+
+#include <dpl/db/orm_macros.h>
+
+#include "ace_db_definitions"
diff --git a/ace/orm/gen_db_md5.sh b/ace/orm/gen_db_md5.sh
new file mode 100755 (executable)
index 0000000..38587b7
--- /dev/null
@@ -0,0 +1,19 @@
+#!/bin/sh
+# 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.
+#
+CHECKSUM=`cat ${2} ${3} 2>/dev/null | md5sum 2>/dev/null | cut -d\  -f1 2>/dev/null`
+echo "#define DB_CHECKSUM DB_VERSION_${CHECKSUM}" > ${1}
+echo "#define DB_CHECKSUM_STR \"DB_VERSION_${CHECKSUM}\"" >> ${1}
+
diff --git a/ace/orm/orm_generator_ace.h b/ace/orm/orm_generator_ace.h
new file mode 100644 (file)
index 0000000..640dd35
--- /dev/null
@@ -0,0 +1,24 @@
+/*
+ * 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 ORM_GENERATOR_ACE_H
+#define ORM_GENERATOR_ACE_H
+
+#define ORM_GENERATOR_DATABASE_NAME ace_db_definitions
+#include <dpl/db/orm_generator.h>
+#undef ORM_GENERATOR_DATABASE_NAME
+
+#endif
diff --git a/ace/orm/version_db b/ace/orm/version_db
new file mode 100644 (file)
index 0000000..7e20d8d
--- /dev/null
@@ -0,0 +1,5 @@
+SQL(
+    BEGIN TRANSACTION;
+    CREATE TABLE DB_CHECKSUM (version INT);
+    COMMIT;
+)
diff --git a/ace_client/CMakeLists.txt b/ace_client/CMakeLists.txt
new file mode 100644 (file)
index 0000000..4b7537b
--- /dev/null
@@ -0,0 +1 @@
+ADD_SUBDIRECTORY(src)
diff --git a/ace_client/include/ace-client/ace_client.h b/ace_client/include/ace-client/ace_client.h
new file mode 100644 (file)
index 0000000..024be70
--- /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        ace_client.h
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This file contains definitions of AceThinClient API
+ */
+#ifndef WRT_ACE_CLIENT_H
+#define WRT_ACE_CLIENT_H
+
+#include <dpl/noncopyable.h>
+#include <dpl/singleton.h>
+#include <dpl/exception.h>
+#include <ace-client/ace_client_types.h>
+
+class WebRuntimeImpl;
+class ResourceInformationImpl;
+class OperationSystemImpl;
+
+namespace AceClient {
+
+class AceThinClientImpl;
+
+class AceThinClient : private DPL::Noncopyable {
+  public:
+    class Exception
+    {
+      public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, AceThinClientException)
+    };
+
+    bool checkFunctionCall(const AceRequest& ace_request) const;
+    bool checkPrivacy(const AceRequest& ace_request) const;
+    AcePreference getWidgetResourcePreference(
+            const AceResource& resource,
+            const AceWidgetHandle& handle) const;
+    AceResourcesPreferences* getGlobalResourcesPreferences() const;
+    bool isInitialized() const;
+
+  private:
+    AceThinClient();
+    virtual ~AceThinClient();
+
+    AceThinClientImpl* m_impl;
+    friend class DPL::Singleton<AceThinClient>;
+    WebRuntimeImpl* m_wrt;
+    ResourceInformationImpl* m_res;
+    OperationSystemImpl* m_sys;
+};
+
+typedef DPL::Singleton<AceThinClient> AceThinClientSingleton;
+
+} // namespace AceClient
+
+#endif // WRT_ACE_CLIENT_H
diff --git a/ace_client/include/ace-client/ace_client_helper.h b/ace_client/include/ace-client/ace_client_helper.h
new file mode 100644 (file)
index 0000000..14c5964
--- /dev/null
@@ -0,0 +1,139 @@
+/*
+ * 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        ace_client_helper.h
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This file contains definitions of AceClient helper types and
+ *              functions.
+ */
+#ifndef WRT_ACE_CLIENT_HELPER_H
+#define WRT_ACE_CLIENT_HELPER_H
+
+#include <string>
+#include <vector>
+#include <dpl/foreach.h>
+
+#include <ace-dao-ro/IRequest.h>
+#include <ace-dao-ro/PreferenceTypes.h>
+
+#include "ace_client_types.h"
+
+namespace AceClient {
+
+AcePreference toAcePreference(AceDB::PreferenceTypes preference)
+{
+    switch (preference) {
+    case AceDB::PreferenceTypes::PREFERENCE_PERMIT: {
+        return PREFERENCE_PERMIT; }
+    case AceDB::PreferenceTypes::PREFERENCE_DENY: {
+        return PREFERENCE_DENY; }
+    case AceDB::PreferenceTypes::PREFERENCE_DEFAULT: {
+        return PREFERENCE_DEFAULT; }
+    case AceDB::PreferenceTypes::PREFERENCE_BLANKET_PROMPT: {
+        return PREFERENCE_BLANKET_PROMPT; }
+    case AceDB::PreferenceTypes::PREFERENCE_SESSION_PROMPT: {
+        return PREFERENCE_SESSION_PROMPT; }
+    case AceDB::PreferenceTypes::PREFERENCE_ONE_SHOT_PROMPT: {
+        return PREFERENCE_ONE_SHOT_PROMPT; }
+    }
+    return PREFERENCE_DEFAULT;
+}
+
+typedef std::vector<std::string> AceParamKeys;
+typedef std::vector<std::string> AceParamValues;
+
+class AceFunctionParam
+{
+  public:
+    virtual ~AceFunctionParam()
+    {
+    }
+
+    void addAttribute(const std::string& key,
+                      const std::string& value)
+    {
+        m_paramMap.insert(std::make_pair(key, value));
+    }
+
+    AceParamKeys getKeys() const
+    {
+        AceParamKeys out;
+        FOREACH (it, m_paramMap) {
+            out.push_back(it->first);
+        }
+        return out;
+    }
+
+    AceParamValues getValues() const
+    {
+        AceParamValues out;
+        FOREACH (it, m_paramMap) {
+            out.push_back(it->second);
+        }
+        return out;
+    }
+
+    static std::string aceFunctionParamToken;
+
+  private:
+    typedef std::multimap<std::string, std::string> ParamMap;
+    ParamMap m_paramMap;
+};
+
+typedef std::vector <AceFunctionParam> AceFunctionParams;
+
+class AceBasicRequest : public AceDB::IRequest {
+  public:
+    AceBasicRequest(const AceSubject& subject,
+                    const AceResource& resource) :
+      m_subject(subject),
+      m_resource(resource)
+    {
+    }
+
+    AceBasicRequest(const AceSubject& subject,
+                    const AceResource& resource,
+                    const AceFunctionParam& param) :
+      m_subject(subject),
+      m_resource(resource),
+      m_param(param)
+    {
+    }
+    virtual const std::string& getSubjectId() const
+    {
+        return m_subject;
+    }
+    virtual const std::string& getResourceId() const
+    {
+        return m_resource;
+    }
+    virtual const AceFunctionParam& getFunctionParam() const
+    {
+        return m_param;
+    }
+
+  private:
+    AceSubject m_subject;
+    AceResource m_resource;
+    AceFunctionParam m_param;
+};
+
+typedef std::vector <AceBasicRequest> AceBasicRequests;
+
+} // namespace AceClient
+
+#endif // WRT_ACE_CLIENT_HELPER_H
diff --git a/ace_client/include/ace-client/ace_client_types.h b/ace_client/include/ace-client/ace_client_types.h
new file mode 100644 (file)
index 0000000..f27a4ba
--- /dev/null
@@ -0,0 +1,116 @@
+/*
+ * 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        ace_client_types.h
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This file contains definitions of AceClient types
+ */
+#ifndef WRT_ACE_CLIENT_TYPES_H
+#define WRT_ACE_CLIENT_TYPES_H
+
+#include <string>
+#include <utility>
+#include <map>
+
+namespace AceClient {
+
+typedef int   AceWidgetHandle;
+typedef void* AceJobWidgetInstallId;
+
+typedef std::string AceResource;
+typedef std::string AceSubject;
+typedef std::string AceSessionId;
+
+enum AcePreference
+{
+    PREFERENCE_PERMIT,
+    PREFERENCE_DENY,
+    PREFERENCE_DEFAULT,
+    PREFERENCE_BLANKET_PROMPT,
+    PREFERENCE_SESSION_PROMPT,
+    PREFERENCE_ONE_SHOT_PROMPT
+};
+
+typedef std::map<std::string, AcePreference>  AceResourcesPreferences;
+typedef std::pair<std::string, AcePreference> AceResurcePreference;
+
+struct AceParam
+{
+    const char *name;
+    const char *value;
+
+    AceParam():
+        name(NULL), value(NULL)
+    {}
+
+    AceParam(const char *name, const char *value):
+        name(name), value(value)
+    {}
+};
+
+struct AceParamList
+{
+    size_t    count;
+    AceParam* param;
+    AceParamList():
+        count(0),
+        param(NULL)
+    {}
+};
+
+struct AceDeviceCap
+{
+    size_t        devcapsCount;
+    const char**  devCapNames;
+    size_t        paramsCount;
+    AceParamList* params;
+    AceDeviceCap():
+        devcapsCount(0),
+        devCapNames(NULL),
+        paramsCount(0),
+        params(NULL)
+    {}
+};
+
+struct AceApiFeatures
+{
+    size_t       count;
+    const char** apiFeature;
+    AceApiFeatures():
+        count(0),
+        apiFeature(NULL)
+    {}
+};
+
+struct AceRequest
+{
+    AceSessionId    sessionId;
+    AceWidgetHandle widgetHandle;
+    AceApiFeatures  apiFeatures;
+    const char*     functionName;
+    AceDeviceCap    deviceCapabilities;
+    AceRequest():
+        widgetHandle(0),
+        apiFeatures(),
+        functionName(NULL),
+        deviceCapabilities()
+    {}
+};
+
+} // namespace AceClient
+
+#endif // WRT_ACE_CLIENT_TYPES_H
diff --git a/ace_client/include/ace_api_client.h b/ace_client/include/ace_api_client.h
new file mode 100644 (file)
index 0000000..a952add
--- /dev/null
@@ -0,0 +1,118 @@
+/*
+ * 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        ace_api_client.h
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This is C api for Access Control Engine (ACE), client mode
+ *              (RO part).
+ */
+
+#ifndef ACE_API_CLIENT_H
+#define ACE_API_CLIENT_H
+
+#include <ace_api_common.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * API defined in this header should be used only from one thread. If used
+ * otherwise, unexpected behaviour may occur, including segmentation faults and
+ * escalation of global warming. Be warned.
+ */
+
+// --------------- Initialization and deinitialization -------------------------
+
+/*
+ * Function type that must be implemented externally and passed to ACE
+ * on initialization. This function must show to the user a popup with
+ * information on access request to single device capability. Will be used by
+ * implementation of ace_check_access API, when policy requires to display
+ * popup.
+ *
+ * Function must be synchronous and must behave accordingly:
+ *
+ * Function may return value other than ACE_OK, but it will be treated as
+ * denial of access.
+ *
+ * If returned value is ACE_OK, then 'validation_result' must hold information
+ * on whether the access was granted or not.
+ *
+ * Executed function must display a popup with readable information presented to
+ * user, covering 'resource_name' that is to be accessed for 'handle' widget
+ * which is requesting the access.
+ *
+ * In its implementation, after the user answered to displayed question,
+ * UI handler must call popup answer validation API (ace_validate_answer)
+ * from separate, ace-popup-validation library, with passed 'param_list',
+ * 'session_id', 'handle' and given answer as arguments. Validation result
+ * returned by ace_validate_answer needs to be returned in 'validation_result'
+ * parameter of UI handler.
+ *
+ * 'popup_type' describes what kind of options should be given to user - i.e.
+ * ONESHOT prompt only gives possibility to answer Permit/Deny and returned
+ * validity for this prompt must be ONCE. PER_SESSION prompt allows to return
+ * validity ONCE or PER_SESSION. BLANKET prompt allows to return any validity,
+ * as defined in ace_validity_t.
+ *
+ * This call must be made from properly SMACK labelled, safe process - otherwise
+ * the validation will not occur in security daemon and caller will not be
+ * granted access to requested device capability.
+ */
+typedef ace_return_t (*ace_popup_handler_func_t)(
+        ace_popup_t popup_type,
+        const ace_resource_t resource_name,
+        const ace_session_id_t session_id,
+        const ace_param_list_t* param_list,
+        ace_widget_handle_t handle,
+        ace_bool_t* validation_result);
+
+/*
+ * Initializes ACE for check access API (client mode). Must be called only once.
+ * Keep in mind that initializing ACE in client mode disallows usage of API
+ * defined in ace_api.h and ace_api_settings.h (RW part).
+ *
+ * 'handler' must not be NULL, see definition of ace_popup_handler_func_t for
+ * more information.
+ *
+ * Returns error or ACE_OK.
+ */
+ace_return_t ace_client_initialize(ace_popup_handler_func_t handler);
+
+/*
+ * Deinitializes ACE client for check access API. Can be called only once.
+ */
+ace_return_t ace_client_shutdown(void);
+
+// --------------- Check Access API --------------------------------------------
+
+/*
+ * Does ACE check with set of device capabilities and function parameters.
+ * Checks cache first, if it is non-existent, does full ACE check.
+ *
+ * Returns error or ACE_OK and information if access was allowed or not
+ * (value ACE_TRUE or ACE_FALSE is in 'access' argument, only if returned value
+ * is ACE_OK - otherwise, 'access' value is undefined)
+ */
+ace_return_t ace_check_access_ex(const ace_request_t* request, ace_check_result_t* result);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // ACE_API_CLIENT_H
diff --git a/ace_client/include/ace_popup_handler.h b/ace_client/include/ace_popup_handler.h
new file mode 100644 (file)
index 0000000..e63630d
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * 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        ace_popup_handler.h
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       Private header for access to UI handling function.
+ *              (RO part).
+ */
+
+#ifndef ACE_POPUP_HANDLER_H
+#define ACE_POPUP_HANDLER_H
+
+#include <ace_api_client.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern ace_popup_handler_func_t popup_func;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // ACE_POPUP_HANDLER_H
diff --git a/ace_client/src/CMakeLists.txt b/ace_client/src/CMakeLists.txt
new file mode 100644 (file)
index 0000000..f59e995
--- /dev/null
@@ -0,0 +1,75 @@
+include(FindPkgConfig)
+
+PKG_CHECK_MODULES(ACE_CLIENT_DEPS
+    dpl-efl
+    dpl-event-efl
+    dpl-dbus-efl
+    privacy-manager-client
+    capi-appfw-app-manager
+    capi-appfw-package-manager
+    dpl-wrt-dao-ro
+    REQUIRED
+    )
+
+SET(ACE_CLIENT_DIR
+    ${PROJECT_SOURCE_DIR}/ace_client
+    )
+
+SET(ACE_CLIENT_SRC_DIR
+    ${ACE_CLIENT_DIR}/src
+    )
+
+SET(ACE_CLIENT_INCLUDE_DIR
+    ${ACE_CLIENT_DIR}/include
+    )
+
+SET(ACE_CLIENT_SOURCES
+    ${COMMUNICATION_CLIENT_SOURCES}
+    ${ACE_CLIENT_SRC_DIR}/ace_client.cpp
+    ${ACE_CLIENT_SRC_DIR}/ace_api_client.cpp
+    ${PROJECT_SOURCE_DIR}/src/services/ace/logic/attribute_facade.cpp
+    ${PROJECT_SOURCE_DIR}/src/services/ace/logic/simple_roaming_agent.cpp
+    )
+
+SET(ACE_CLIENT_INCLUDES
+    ${COMMUNICATION_CLIENT_INCLUDES}
+    ${ACE_CLIENT_DEPS_INCLUDE_DIRS}
+    ${ACE_CLIENT_INCLUDE_DIR}
+    ${PROJECT_SOURCE_DIR}/ace_common/include
+    ${PROJECT_SOURCE_DIR}/src/services/ace
+    ${PROJECT_SOURCE_DIR}/src/services/ace/
+    ${PROJECT_SOURCE_DIR}/src/services/ace/logic
+    ${PROJECT_SOURCE_DIR}/src/services/popup
+    ${PROJECT_SOURCE_DIR}/popup_process
+    ${PROJECT_SOURCE_DIR}/ace/include
+    )
+
+ADD_DEFINITIONS(${ACE_CLIENT_DEPS_CFLAGS})
+ADD_DEFINITIONS(${ACE_CLIENT_CFLAGS_OTHER})
+
+INCLUDE_DIRECTORIES(${ACE_CLIENT_INCLUDES})
+
+ADD_LIBRARY(${TARGET_ACE_CLIENT_LIB} SHARED ${ACE_CLIENT_SOURCES})
+
+SET_TARGET_PROPERTIES(${TARGET_ACE_CLIENT_LIB} PROPERTIES
+    SOVERSION ${API_VERSION}
+    VERSION ${VERSION})
+
+SET_TARGET_PROPERTIES(${TARGET_ACE_CLIENT_LIB} PROPERTIES
+    COMPILE_FLAGS -fPIC)
+
+TARGET_LINK_LIBRARIES(${TARGET_ACE_CLIENT_LIB}
+    ${ACE_CLIENT_DEPS_LIBRARIES}
+    ${TARGET_ACE_DAO_RO_LIB}
+    ${TARGET_ACE_LIB}
+    )
+
+INSTALL(TARGETS ${TARGET_ACE_CLIENT_LIB}
+    DESTINATION ${LIB_INSTALL_DIR})
+
+INSTALL(FILES
+#    ${ACE_CLIENT_INCLUDE_DIR}/ace-client/ace_client.h
+#    ${ACE_CLIENT_INCLUDE_DIR}/ace-client/ace_client_types.h
+    ${ACE_CLIENT_INCLUDE_DIR}/ace_api_client.h
+    DESTINATION include/ace-client
+    )
diff --git a/ace_client/src/ace_api_client.cpp b/ace_client/src/ace_api_client.cpp
new file mode 100644 (file)
index 0000000..4e8c256
--- /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.
+ */
+/**
+ * @file        ace_api_client.cpp
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This file contains implementation of ACE client API
+ */
+
+#include <dpl/log/log.h>
+#include <ace_popup_handler.h>
+#include "ace_api_client.h"
+#include "ace-client/ace_client.h"
+
+#include <string>
+#include <vector>
+#include "popup_response_server_api.h"
+#ifdef DBUS_CONNECTION
+#include <dpl/dbus/dbus_client.h>
+#include "security_daemon_dbus_config.h"
+//#include "PromptModel.h"
+#endif
+
+
+ace_return_t ace_client_initialize(ace_popup_handler_func_t handler)
+{
+    if (!AceClient::AceThinClientSingleton::Instance().isInitialized()) {
+        return ACE_INTERNAL_ERROR;
+    }
+    popup_func = handler;
+    // Changed order of checks to make API run with old popup implementation
+    // instead of always needing the popup handler to be implemented.
+    if (NULL == handler) {
+        LogError("NULL argument(s) passed");
+        return ACE_INVALID_ARGUMENTS;
+    }
+    return ACE_OK;
+}
+
+ace_return_t ace_client_shutdown(void)
+{
+    popup_func = NULL;
+    return ACE_OK;
+}
+
+ace_return_t ace_check_access_ex(const ace_request_t* request, ace_check_result_t* result)
+{
+    if (NULL == request || NULL == result) {
+        LogError("NULL argument(s) passed");
+        return ACE_INVALID_ARGUMENTS;
+    }
+
+    AceClient::AceRequest aceRequest;
+    aceRequest.sessionId = request->session_id;
+    aceRequest.widgetHandle = request->widget_handle;
+
+    aceRequest.apiFeatures.count = request->feature_list.count;
+    aceRequest.apiFeatures.apiFeature =
+            const_cast<const char**>(request->feature_list.items);
+    aceRequest.functionName = NULL; // TODO will  be removed
+    aceRequest.deviceCapabilities.devcapsCount = request->dev_cap_list.count;
+    aceRequest.deviceCapabilities.paramsCount = request->dev_cap_list.count;
+
+    char** devCapNames = new char*[request->dev_cap_list.count];
+    AceClient::AceParamList* paramList =
+            new AceClient::AceParamList[request->dev_cap_list.count];
+
+    unsigned int i;
+    for (i = 0; i < request->dev_cap_list.count; ++i) {
+        devCapNames[i] = request->dev_cap_list.items[i].name;
+        paramList[i].count = request->dev_cap_list.items[i].param_list.count;
+
+        paramList[i].param = new AceClient::AceParam[
+                               request->dev_cap_list.items[i].param_list.count];
+
+        unsigned int j;
+        for (j = 0; j < request->dev_cap_list.items[i].param_list.count; ++j) {
+            paramList[i].param[j].name =
+                    request->dev_cap_list.items[i].param_list.items[j].name;
+            paramList[i].param[j].value =
+                    request->dev_cap_list.items[i].param_list.items[j].value;
+
+        }
+    }
+
+    aceRequest.deviceCapabilities.devCapNames =
+            const_cast<const char**>(devCapNames);
+    aceRequest.deviceCapabilities.params = paramList;
+
+    bool ret = false;
+
+    Try {
+        ret = AceClient::AceThinClientSingleton::
+                Instance().checkFunctionCall(aceRequest);
+        *result = ret ? ACE_ACCESS_GRANTED : ACE_PRIVILEGE_DENIED;
+
+        if (*result == ACE_ACCESS_GRANTED) {
+            ret = AceClient::AceThinClientSingleton::
+                Instance().checkPrivacy(aceRequest);
+            *result = ret ? ACE_ACCESS_GRANTED : ACE_PRIVACY_DENIED;
+        }
+    } Catch (AceClient::AceThinClient::Exception::AceThinClientException) {
+        LogError("Ace client exception");
+        delete [] devCapNames;
+        for (i = 0; i < request->dev_cap_list.count; ++i) {
+            delete [] paramList[i].param;
+        }
+        delete [] paramList;
+        return ACE_INTERNAL_ERROR;
+    }
+
+    delete [] devCapNames;
+    for (i = 0; i < request->dev_cap_list.count; ++i) {
+        delete [] paramList[i].param;
+    }
+    delete [] paramList;
+    return ACE_OK;
+}
diff --git a/ace_client/src/ace_client.cpp b/ace_client/src/ace_client.cpp
new file mode 100644 (file)
index 0000000..7be8eeb
--- /dev/null
@@ -0,0 +1,703 @@
+/*
+ * 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        ace_client.cpp
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This file contains implementation of AceThinClient class
+ */
+
+#include <memory>
+#include <set>
+#include <map>
+
+#include <dpl/string.h>
+#include <dpl/optional_typedefs.h>
+#include <boost/optional.hpp>
+#include <dpl/log/log.h>
+#include <dpl/singleton_safe_impl.h>
+#include <ace-dao-ro/PromptModel.h>
+
+#include <ace_popup_handler.h>
+
+#include "ace_server_api.h"
+#include "popup_response_server_api.h"
+#include "ace-client/ace_client.h"
+#include "ace-client/ace_client_helper.h"
+#include <attribute_facade.h>
+#include <ace/Request.h>
+
+#include <app_manager.h>
+#include <package_manager.h>
+#include <privacy_checker_client.h>
+#include <unistd.h>
+#include <dpl/wrt-dao-ro/widget_dao_read_only.h>
+// ACE tests need to use mock implementations
+#ifdef ACE_CLIENT_TESTS
+
+#include "AceDAOReadOnly_mock.h"
+#include "communication_client_mock.h"
+#include "PolicyInformationPoint_mock.h"
+
+#else
+
+#include <ace-dao-ro/AceDAOReadOnly.h>
+#include "SecurityCommunicationClient.h"
+#include <ace/PolicyInformationPoint.h>
+
+#endif // ACE_CLIENT_TESTS
+
+IMPLEMENT_SAFE_SINGLETON(AceClient::AceThinClient)
+
+ace_popup_handler_func_t popup_func = NULL;
+
+namespace AceClient {
+
+namespace {
+// These devcaps actually are not requested in config file, so should be treaded
+// as if were requested (access tags/WARP will block request if desired)
+const std::string DEVCAP_EXTERNAL_NETWORK_ACCESS = "externalNetworkAccess";
+const std::string DEVCAP_XML_HTTP_REQUEST = "XMLHttpRequest";
+} // anonymous
+
+
+std::string AceFunctionParam::aceFunctionParamToken = "param:function";
+
+// popup cache result
+
+enum class AceCachedPromptResult {
+    PERMIT,
+    DENY,
+    ASK_POPUP
+};
+
+// AceThinClient implementation singleton
+class AceThinClientImpl {
+  public:
+    bool checkFunctionCall(const AceRequest& ace_request);
+    AcePreference getWidgetResourcePreference(
+            const AceResource& resource,
+            const AceWidgetHandle& handle) const;
+    bool checkPrivacy(const AceRequest& ace_request);
+    AceResourcesPreferences* getGlobalResourcesPreferences() const;
+    bool isInitialized() const;
+
+    AceThinClientImpl();
+    ~AceThinClientImpl();
+
+  protected:
+    bool containsNetworkDevCap(const AceRequest &ace_request);
+    bool checkFeatureList(const AceRequest& ace_request);
+    
+  private:
+    WebRuntimeImpl* m_wrt;
+    ResourceInformationImpl* m_res;
+    OperationSystemImpl* m_sys;
+    WrtSecurity::Communication::Client *m_communicationClient, *m_popupValidationClient;
+
+    AceSubject getSubjectForHandle(AceWidgetHandle handle) const;
+    AceCachedPromptResult getCachedPromptResult(
+            WidgetHandle widgetHandle,
+            int ruleId,
+            const AceSessionId& sessionId) const;
+    bool askUser(PolicyEffect popupType,
+                const AceRequest& ace_request,
+                const AceBasicRequest& request);
+    // Prompt validation
+    bool validatePopupResponse(
+                const AceRequest& ace_request,
+                const AceBasicRequest& request,
+                bool answer = true,
+                Prompt::Validity validity = Prompt::Validity::ALWAYS);
+    mutable PolicyInformationPoint m_pip;
+    boost::optional<std::set<DPL::String>> m_grantedDevCaps;
+    std::set<std::string> m_acceptedFeatures;
+};
+
+AceThinClientImpl::AceThinClientImpl()
+  : m_wrt(new WebRuntimeImpl()),
+    m_res(new ResourceInformationImpl()),
+    m_sys(new OperationSystemImpl()),
+    m_communicationClient(NULL),
+    m_popupValidationClient(NULL),
+    m_pip(m_wrt, m_res, m_sys)
+{
+    AceDB::AceDAOReadOnly::attachToThreadRO();
+    Try {
+        m_communicationClient = new WrtSecurity::Communication::Client(WrtSecurity::AceServerApi::INTERFACE_NAME());
+        m_popupValidationClient = new WrtSecurity::Communication::Client(WrtSecurity::PopupServerApi::INTERFACE_NAME());
+    } Catch (WrtSecurity::Communication::Client::Exception::SecurityCommunicationClientException) {
+        if(m_communicationClient) delete m_communicationClient;
+        if(m_popupValidationClient) delete m_popupValidationClient;
+        delete m_wrt;
+        delete m_res;
+        delete m_sys;
+        ReThrowMsg(AceThinClient::Exception::AceThinClientException,
+                "Failed to call security daemon");
+    }
+}
+
+AceThinClientImpl::~AceThinClientImpl()
+{
+    Assert(NULL != m_communicationClient);
+    Assert(NULL != m_popupValidationClient);
+    delete m_communicationClient;
+    delete m_popupValidationClient;
+    delete m_wrt;
+    delete m_res;
+    delete m_sys;
+    m_communicationClient = NULL;
+    m_popupValidationClient = NULL;
+    AceDB::AceDAOReadOnly::detachFromThread();
+
+}
+
+bool AceThinClientImpl::isInitialized() const
+{
+    return NULL != m_communicationClient && NULL != m_popupValidationClient;
+}
+
+bool AceThinClientImpl::containsNetworkDevCap(const AceRequest &ace_request)
+{
+    AceDeviceCap deviceCap = ace_request.deviceCapabilities;
+    for (size_t j=0; j<deviceCap.devcapsCount; ++j) {
+        if (!deviceCap.devCapNames[j]) {
+            continue;
+        }
+        if (DEVCAP_XML_HTTP_REQUEST == deviceCap.devCapNames[j]
+            || DEVCAP_EXTERNAL_NETWORK_ACCESS == deviceCap.devCapNames[j])
+        {
+            return true;
+        }
+    }
+    return false;
+}
+
+bool AceThinClientImpl::checkFeatureList(const AceRequest& ace_request)
+{
+    for (size_t i=0; i<ace_request.apiFeatures.count; ++i) {
+        Assert(ace_request.apiFeatures.apiFeature[i]);
+        std::string featureName(ace_request.apiFeatures.apiFeature[i]);
+        LogInfo("Api feature: " << featureName);
+        if (0 != m_acceptedFeatures.count(featureName)) {
+            return true;
+        }
+        LogInfo("Api-feature was not requested in widget config: " <<
+          featureName);
+    }
+    return false;
+}
+
+bool AceThinClientImpl::checkPrivacy(const AceRequest& ace_request)
+{
+    int res;
+
+    WrtDB::WidgetDAOReadOnly dao(ace_request.widgetHandle);
+    std::string tzPkgId = DPL::ToUTF8String(dao.getTizenPkgId());
+
+    LogInfo("Checking pkg_id : " << tzPkgId.c_str());
+
+    for (size_t i = 0; i < ace_request.apiFeatures.count; ++i) {
+        res = privacy_checker_check_package_by_privilege(tzPkgId.c_str(), ace_request.apiFeatures.apiFeature[i]);
+        LogInfo(" privilege : " << ace_request.apiFeatures.apiFeature[i] << " : " << ((res == PRIV_MGR_ERROR_SUCCESS) ? "true" : "false"));
+        if (res != PRIV_MGR_ERROR_SUCCESS)
+            return false;
+    }
+
+    return true;
+}
+
+bool AceThinClientImpl::checkFunctionCall(const AceRequest& ace_request)
+{
+    LogInfo("Enter");
+
+    // fill the m_grantedDevCaps, if not yet initialized
+    // TODO: This is not so pretty. AceThinClient is not explicitly
+    // tied to a widget handle, yet we assume it is always used
+    // with the same handle. This will be amended in a future
+    // refactoring (already planned).
+    if (!m_grantedDevCaps) {
+        m_grantedDevCaps = std::set<DPL::String>();
+        m_acceptedFeatures.clear();
+
+        AceDB::FeatureNameVector fvector;
+        Try {
+            AceDB::AceDAOReadOnly::getAcceptedFeature(ace_request.widgetHandle, &fvector);
+        } Catch (AceDB::AceDAOReadOnly::Exception::DatabaseError) {
+            LogError("Failed to read DB");
+            return false;
+        }
+        for(size_t i=0; i<fvector.size(); ++i) {
+            m_acceptedFeatures.insert(DPL::ToUTF8String(fvector[i]));
+         }
+    }
+
+    AceSubject subject = getSubjectForHandle(ace_request.widgetHandle);
+
+    // Create function params
+    const AceDeviceCap& devcaps = ace_request.deviceCapabilities;
+
+    LogInfo("Checking against config requested api-features.");
+
+    // Network device caps are not connected with api-features.
+    // We must pass empty api-feature when network dev cap is set.
+    if (!containsNetworkDevCap(ace_request) && !checkFeatureList(ace_request)) {
+        return false;
+    }
+
+    AceFunctionParams functionParams(devcaps.devcapsCount);
+    for (size_t i = 0; i < devcaps.devcapsCount; ++i) {
+        AceFunctionParam functionParam;
+        functionParam.addAttribute(AceFunctionParam::aceFunctionParamToken,
+                                   NULL == ace_request.functionName ?
+                                   "" : ace_request.functionName);
+        if (devcaps.paramsCount) {
+            Assert(devcaps.params);
+            for (size_t j = 0; j < devcaps.params[i].count; ++j) {
+                Assert(devcaps.params[i].param &&
+                       devcaps.params[i].param[j].name &&
+                       devcaps.params[i].param[j].value);
+                functionParam.addAttribute(
+                    std::string(devcaps.params[i].param[j].name),
+                    std::string(devcaps.params[i].param[j].value));
+            }
+        }
+        functionParams.push_back(functionParam);
+    }
+
+    // Convert AceRequest to array of AceBasicRequests
+    AceBasicRequests requests;
+
+    for (size_t i = 0; i < devcaps.devcapsCount; ++i) {
+        // Adding dev cap name here as resource id
+        Assert(devcaps.devCapNames[i]);
+        LogInfo("Device cap: " << devcaps.devCapNames[i]);
+        AceBasicRequest request(subject,
+                                devcaps.devCapNames[i],
+                                functionParams[i]);
+        requests.push_back(request);
+    }
+
+    // true means access granted, false - denied
+    bool result = true;
+
+    FOREACH(it, requests){
+        // Getting attributes from ACE DAO
+        AceBasicRequest& request = *it;
+        AceDB::BaseAttributeSet attributeSet;
+        AceDB::AceDAOReadOnly::getAttributes(&attributeSet);
+
+        // If true, we need to make popup IPC and ask user for decision
+        bool askPopup = false;
+        // If true, we need to make IPC to security daemon for policy
+        // decision on granting access
+        bool askServer = false;
+        // If askPopup == true, this is the kind of popup to  be opened
+        PolicyEffect popupType = PolicyEffect::PROMPT_ONESHOT;
+
+        if (attributeSet.empty()) {
+            // Treat this case as missed cache - ask security daemon
+            LogInfo("Empty attribute set");
+            askServer = true;
+        } else {
+            // Filling attributes with proper values
+            FunctionParamImpl params;
+            AceParamKeys keys = request.getFunctionParam().getKeys();
+            AceParamValues values = request.getFunctionParam().getValues();
+            for (size_t i = 0; i < keys.size(); ++i) {
+                params.addAttribute(keys[i], values[i]);
+            }
+            Request req(ace_request.widgetHandle,
+                        WidgetExecutionPhase_Invoke,
+                        &params);
+            req.addDeviceCapability(request.getResourceId());
+
+            m_pip.getAttributesValues(&req, &attributeSet);
+
+            // Getting cached policy result
+            OptionalExtendedPolicyResult exPolicyResult =
+                    AceDB::AceDAOReadOnly::getPolicyResult(attributeSet);
+
+            if (!exPolicyResult) {
+                // Missed cache - ask security daemon
+                LogInfo("Missed policy result cache");
+                askServer = true;
+            } else {
+                // Cached value found - now interpret it
+                LogInfo("Result in cache");
+                OptionalPolicyEffect effect = exPolicyResult->policyResult.getEffect();
+                if (!effect) {
+                    // PolicyDecision is UNDETERMINED or NOT_APPLICABLE
+                    result = false;
+                    break;
+                } else if (*effect == PolicyEffect::DENY) {
+                    // Access denied
+                    result = false;
+                    break;
+                } else if (*effect == PolicyEffect::PERMIT) {
+                    // Access granted
+                    if (m_grantedDevCaps->find(
+                           DPL::FromASCIIString(request.getResourceId()))
+                        != m_grantedDevCaps->end())
+                    {
+                        continue;
+                    } else
+                        askServer = true;
+                } else {
+                    // Check for cached popup response
+                    LogInfo("Checking cached popup response");
+                    AceCachedPromptResult promptCached =
+                     getCachedPromptResult(ace_request.widgetHandle,
+                                           exPolicyResult->ruleId,
+                                           ace_request.sessionId);
+                    if (promptCached == AceCachedPromptResult::PERMIT) {
+                        // Granted by previous popup
+                        LogDebug("Cache found OK");
+                        if (m_grantedDevCaps->find(
+                               DPL::FromASCIIString(request.getResourceId()))
+                            != m_grantedDevCaps->end())
+                        {
+                            LogDebug("SMACK given previously");
+                            continue;
+                        } else {
+                            if (*effect != PolicyEffect::PROMPT_BLANKET) {
+                                // This should not happen.
+                                LogDebug("This should not happen.");
+                                result = false;
+                                break;
+                            }
+                            if (!validatePopupResponse(ace_request,
+                                                             request)) {
+                                LogDebug("Daemon has not validated response.");
+                                result = false;
+                                break;
+                            } else {
+                                // Access granted, move on to next request
+                                LogDebug("SMACK granted, all OK");
+                                m_grantedDevCaps->insert(
+                                    DPL::FromASCIIString(
+                                            request.getResourceId()));
+                                continue;
+                            }
+                        }
+                    }
+                    if (promptCached == AceCachedPromptResult::DENY) {
+                        // Access denied by earlier popup
+                        result = false;
+                        break;
+                    }
+                    if (promptCached == AceCachedPromptResult::ASK_POPUP) {
+                        askPopup = true;
+                        popupType = *effect;
+                    }
+                }
+            }
+        }
+
+        if (askServer) {
+            // IPC to security daemon
+            // here we must check if we have a SMACK permission for
+            // the device cap requested
+            LogInfo("Asking security daemon");
+            int serializedPolicyResult = 0;
+            Try {
+                m_communicationClient->call(WrtSecurity::AceServerApi::CHECK_ACCESS_METHOD(),
+                                   ace_request.widgetHandle,
+                                   request.getSubjectId(),
+                                   request.getResourceId(),
+                                   request.getFunctionParam().getKeys(),
+                                   request.getFunctionParam().getValues(),
+                                   ace_request.sessionId,
+                                   &serializedPolicyResult);
+            } Catch (WrtSecurity::Communication::Client::Exception::SecurityCommunicationClientException) {
+                ReThrowMsg(AceThinClient::Exception::AceThinClientException,
+                         "Failed to call security daemon");
+            }
+            PolicyResult policyResult = PolicyResult::
+                    deserialize(serializedPolicyResult);
+            OptionalPolicyEffect effect = policyResult.getEffect();
+            if (!effect) {
+                // PolicyDecision is UNDETERMINED or NOT_APPLICABLE
+                result = false;
+                break;
+            }
+            if (*effect == PolicyEffect::DENY) {
+                // Access denied
+                result = false;
+                break;
+            }
+            if (*effect == PolicyEffect::PERMIT) {
+                // Access granted, move on to next request
+                m_grantedDevCaps->insert(
+                    DPL::FromASCIIString(request.getResourceId()));
+
+                continue;
+            }
+            // Policy says: ask user - setup popup kind
+            popupType = *effect;
+            askPopup = true;
+        }
+
+        if (askPopup) {
+            result = askUser(popupType, ace_request, request);
+        }
+    }
+
+    LogInfo("Result: " << (result ? "GRANTED" : "DENIED"));
+    return result;
+}
+
+bool AceThinClientImpl::askUser(PolicyEffect popupType,
+                                const AceRequest& ace_request,
+                                const AceBasicRequest& request)
+{
+    LogInfo("Asking popup");
+    Assert(NULL != popup_func);
+
+    const AceFunctionParam& fParam = request.getFunctionParam();
+    AceParamKeys keys = fParam.getKeys();
+    AceParamValues values = fParam.getValues();
+
+    ace_popup_t ace_popup_type;
+    ace_resource_t resource = const_cast<ace_session_id_t>(
+            request.getResourceId().c_str());
+    ace_session_id_t session = const_cast<ace_session_id_t>(
+            ace_request.sessionId.c_str());;
+    ace_param_list_t parameters;
+    ace_widget_handle_t handle = ace_request.widgetHandle;
+
+    parameters.count = keys.size();
+    parameters.items = new ace_param_t[parameters.count];
+    unsigned int i;
+    for (i = 0; i < parameters.count; ++i) {
+        parameters.items[i].name =
+                const_cast<ace_string_t>(keys[i].c_str());
+        parameters.items[i].value =
+                const_cast<ace_string_t>(values[i].c_str());
+    }
+
+    switch (popupType) {
+    case PolicyEffect::PROMPT_ONESHOT: {
+        ace_popup_type = ACE_ONESHOT;
+        break; }
+    case PolicyEffect::PROMPT_SESSION: {
+        ace_popup_type = ACE_SESSION;
+        break; }
+    case PolicyEffect::PROMPT_BLANKET: {
+        ace_popup_type = ACE_BLANKET;
+        break; }
+    default: {
+        LogError("Unknown popup type passed!");
+        LogError("Maybe effect isn't a popup?");
+        LogError("Effect number is: " << static_cast<int>(popupType));
+        Assert(0); }
+    }
+
+    ace_bool_t answer = ACE_FALSE;
+    ace_return_t ret = popup_func(ace_popup_type,
+                    resource,
+                    session,
+                    &parameters,
+                    handle,
+                    &answer);
+
+    delete [] parameters.items;
+
+    if (ACE_OK != ret) {
+        LogError("Error in popup handler");
+        return false;
+    }
+
+    if (ACE_TRUE == answer) {
+        m_grantedDevCaps->insert(
+            DPL::FromASCIIString(request.getResourceId()));
+        return true;
+    }
+
+    return false;
+}
+
+bool AceThinClientImpl::validatePopupResponse(
+        const AceRequest& ace_request,
+        const AceBasicRequest& request,
+        bool answer,
+        Prompt::Validity validity
+        )
+{
+    bool response = false;
+    Try{
+        m_popupValidationClient->call(
+                           WrtSecurity::PopupServerApi::VALIDATION_METHOD(),
+                           answer,
+                           static_cast<int>(validity),
+                           ace_request.widgetHandle,
+                           request.getSubjectId(),
+                           request.getResourceId(),
+                           request.getFunctionParam().getKeys(),
+                           request.getFunctionParam().getValues(),
+                           ace_request.sessionId,
+                           &response);
+    } Catch (WrtSecurity::Communication::Client::Exception::SecurityCommunicationClientException) {
+        ReThrowMsg(AceThinClient::Exception::AceThinClientException,
+                 "Failed to call security daemon");
+    }
+    return response;
+}
+
+AcePreference AceThinClientImpl::getWidgetResourcePreference (
+        const AceResource& resource,
+        const AceWidgetHandle& handle) const
+{
+    return toAcePreference(
+            AceDB::AceDAOReadOnly::getWidgetDevCapSetting(resource, handle));
+}
+
+AceResourcesPreferences* AceThinClientImpl::getGlobalResourcesPreferences()
+const
+{
+    AceDB::PreferenceTypesMap globalSettingsMap;
+    AceResourcesPreferences* acePreferences = new AceResourcesPreferences();
+    AceDB::AceDAOReadOnly::getDevCapSettings(&globalSettingsMap);
+    FOREACH(it, globalSettingsMap) {
+        acePreferences->insert(
+                AceResurcePreference((*it).first,
+                        toAcePreference((*it).second)));
+    }
+    return acePreferences;
+}
+
+AceSubject AceThinClientImpl::getSubjectForHandle(AceWidgetHandle handle) const
+{
+    try
+    {
+        return AceDB::AceDAOReadOnly::getGUID(handle);
+    }
+    catch (AceDB::AceDAOReadOnly::Exception::DatabaseError& /*ex*/)
+    {
+        LogError("Couldn't find GIUD for handle " << handle);
+        return "";
+    }
+}
+
+AceCachedPromptResult AceThinClientImpl::getCachedPromptResult(
+        WidgetHandle widgetHandle,
+        int ruleId,
+        const AceSessionId& sessionId) const
+{
+    OptionalCachedPromptDecision promptDecision =
+    AceDB::AceDAOReadOnly::getPromptDecision(
+            widgetHandle,
+            ruleId);
+    if (!promptDecision) {
+        LogDebug("No cache");
+        return AceCachedPromptResult::ASK_POPUP;
+    } else {
+        // These should not be stored in DB!
+        Assert(PromptDecision::ALLOW_THIS_TIME
+                != (*promptDecision).decision);
+        Assert(PromptDecision::DENY_THIS_TIME
+                != (*promptDecision).decision);
+        if ((*promptDecision).decision ==
+                PromptDecision::ALLOW_ALWAYS) {
+            // Access granted via earlier popup
+            LogDebug("ALLOW_ALWAYS");
+            return AceCachedPromptResult::PERMIT;
+        }
+        if ((*promptDecision).decision ==
+                PromptDecision::DENY_ALWAYS) {
+            LogDebug("DENY_ALWAYS");
+            // Access denied via earlier popup
+            return AceCachedPromptResult::DENY;
+        }
+        // Only thing left is per session prompts
+        if (!(*promptDecision).session) {
+            LogDebug("NO SESSION");
+            return AceCachedPromptResult::ASK_POPUP;
+        }
+        AceSessionId cachedSessionId = DPL::ToUTF8String(*((*promptDecision).session));
+        if ((*promptDecision).decision ==
+                PromptDecision::ALLOW_FOR_SESSION) {
+            if (cachedSessionId == sessionId) {
+                // Access granted for this session.
+                LogDebug("SESSION OK, PERMIT");
+                return AceCachedPromptResult::PERMIT;
+            } else {
+                LogDebug("SESSION NOT OK, ASKING");
+                return AceCachedPromptResult::ASK_POPUP;
+            }
+        }
+        if ((*promptDecision).decision ==
+                PromptDecision::DENY_FOR_SESSION) {
+            if (cachedSessionId == sessionId) {
+                // Access denied for this session.
+                LogDebug("SESSION OK, DENY");
+                return AceCachedPromptResult::DENY;
+            } else {
+                LogDebug("SESSION NOT OK, ASKING");
+                return AceCachedPromptResult::ASK_POPUP;
+            }
+        }
+    }
+    LogDebug("NO RESULT, ASKING");
+    return AceCachedPromptResult::ASK_POPUP;
+}
+
+// AceThinClient
+
+bool AceThinClient::checkFunctionCall(
+        const AceRequest& ace_request) const
+{
+    return m_impl->checkFunctionCall(ace_request);
+}
+
+bool AceThinClient::checkPrivacy(
+        const AceRequest& ace_request) const
+{
+    return m_impl->checkPrivacy(ace_request);
+}
+
+AcePreference AceThinClient::getWidgetResourcePreference(
+        const AceResource& resource,
+        const AceWidgetHandle& handle) const
+{
+    return m_impl->getWidgetResourcePreference(
+            resource, handle);
+}
+
+AceResourcesPreferences* AceThinClient::getGlobalResourcesPreferences()
+const
+{
+    return m_impl->getGlobalResourcesPreferences();
+}
+
+AceThinClient::AceThinClient()
+{
+    m_impl = new AceThinClientImpl();
+}
+
+AceThinClient::~AceThinClient()
+{
+    Assert(NULL != m_impl);
+    delete m_impl;
+}
+
+bool AceThinClient::isInitialized() const
+{
+    return NULL != m_impl && m_impl->isInitialized();
+}
+
+
+} // namespace AceClient
diff --git a/ace_client/src/example/CMakeLists.txt b/ace_client/src/example/CMakeLists.txt
new file mode 100644 (file)
index 0000000..b3e9259
--- /dev/null
@@ -0,0 +1,26 @@
+cmake_minimum_required(VERSION 2.6)
+project(ace-thin-client-example)
+
+include(FindPkgConfig)
+
+pkg_check_modules(DEPS
+                  dpl-efl
+                  REQUIRED)
+
+pkg_search_module(wrt-ace-client REQUIRED wrt-ace-client)
+
+set(TARGET_NAME "ace-thin-client-example")
+
+set(SRCS
+    ace-thin-client-example.cpp)
+
+include_directories(${DEPS_INCLUDE_DIRS})
+include_directories(${wrt-ace-client_INCLUDE_DIRS})
+
+add_definitions("-DDPL_LOGS_ENABLED")
+
+add_executable(${TARGET_NAME} ${SRCS})
+
+target_link_libraries(${TARGET_NAME}
+    ${DEPS_LDFLAGS}
+    ${wrt-ace-client_LDFLAGS})
diff --git a/ace_client/src/example/ace-thin-client-example.cpp b/ace_client/src/example/ace-thin-client-example.cpp
new file mode 100644 (file)
index 0000000..aa4c4a8
--- /dev/null
@@ -0,0 +1,33 @@
+/*
+ * 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        ace-thin-client-example.cpp
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       Example usage of ACE thin client.
+ */
+
+#include <ace_client.h>
+
+int main(int argc, char **argv)
+{
+    AceClient::AceThinClient& client =
+            AceClient::AceThinClientSingleton::Instance();
+    client.initialize(); // this fires echo method - see logs
+    client.deinitialize();
+    return 0;
+}
+
diff --git a/ace_common/CMakeLists.txt b/ace_common/CMakeLists.txt
new file mode 100644 (file)
index 0000000..7e7926a
--- /dev/null
@@ -0,0 +1,4 @@
+INSTALL(FILES
+    ${PROJECT_SOURCE_DIR}/ace_common/include/ace_api_common.h
+    DESTINATION include/ace-common
+    )
diff --git a/ace_common/include/ace_api_common.h b/ace_common/include/ace_api_common.h
new file mode 100644 (file)
index 0000000..b42d048
--- /dev/null
@@ -0,0 +1,132 @@
+/*
+ * 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        ace_api_common.h
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This is header for basic ACE data types and error codes
+ */
+
+#ifndef ACE_API_COMMON_H
+#define ACE_API_COMMON_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// --------------- Boolean type and errors -------------------------------------
+
+/*
+ * Order and values of enum constants are part of API
+ */
+typedef enum
+{
+    ACE_FALSE,
+    ACE_TRUE
+} ace_bool_t;
+
+typedef enum
+{
+    ACE_ACCESS_GRANTED,
+    ACE_PRIVILEGE_DENIED,
+    ACE_PRIVACY_DENIED
+} ace_check_result_t;
+
+typedef enum
+{
+    ACE_OK,                 // Operation succeeded
+    ACE_INVALID_ARGUMENTS,  // Invalid input parameters
+    ACE_INTERNAL_ERROR,     // ACE internal error
+    ACE_ACE_UNKNOWN_ERROR   // Unexpected operation
+} ace_return_t;
+
+// --------------- Basic types -------------------------------------------------
+
+typedef size_t  ace_size_t;
+typedef char*   ace_string_t;           // NULL-terminated string
+typedef int     ace_widget_handle_t;
+typedef char*   ace_resource_t;
+typedef char*   ace_subject_t;
+typedef char*   ace_session_id_t;
+typedef void*   ace_private_data_t;
+
+// --------------- Access requests ---------------------------------------------
+
+typedef struct
+{
+    ace_size_t        count;
+    ace_string_t*     items;
+} ace_feature_list_t;
+
+typedef struct
+{
+    ace_string_t name;
+    ace_string_t value;
+} ace_param_t;
+
+typedef struct
+{
+    ace_size_t      count;
+    ace_param_t*    items;
+} ace_param_list_t;
+
+typedef struct
+{
+    ace_string_t     name;
+    ace_param_list_t param_list;
+} ace_dev_cap_t;
+
+typedef struct
+{
+    ace_size_t        count;
+    ace_dev_cap_t*    items;
+} ace_dev_cap_list_t;
+
+typedef struct
+{
+    ace_session_id_t    session_id;         // DEPRECATED will be removed
+    ace_widget_handle_t widget_handle;      // DEPRECATED will be removed
+    ace_feature_list_t  feature_list;
+    ace_dev_cap_list_t  dev_cap_list;
+} ace_request_t;
+
+// --------------- Popup data types --------------------------------------------
+
+/*
+ * Popup types that can be requested to be displayed by ACE
+ */
+typedef enum
+{
+    ACE_ONESHOT,
+    ACE_SESSION,
+    ACE_BLANKET
+} ace_popup_t;
+
+/*
+ * Validity of answer that can be returned by ACE popup
+ */
+typedef enum
+{
+    ACE_ONCE,
+    ACE_PER_SESSION,
+    ACE_ALWAYS
+} ace_validity_t;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // ACE_API_COMMON_H
diff --git a/ace_install/CMakeLists.txt b/ace_install/CMakeLists.txt
new file mode 100644 (file)
index 0000000..4b7537b
--- /dev/null
@@ -0,0 +1 @@
+ADD_SUBDIRECTORY(src)
diff --git a/ace_install/include/ace_api_install.h b/ace_install/include/ace_api_install.h
new file mode 100644 (file)
index 0000000..734861c
--- /dev/null
@@ -0,0 +1,185 @@
+/*
+ * 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        ace_api_setup.h
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This is C api for Access Control Engine (ACE), installer mode
+ *              (RW part).
+ *
+ */
+
+#ifndef ACE_API_H
+#define ACE_API_H
+
+#include <ace_api_common.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * API defined in this header should be used only from one thread. If used
+ * otherwise, unexpected behaviour may occur, including segmentation faults and
+ * escalation of global warming. Be warned.
+ */
+
+// --------------- Initialization and policy update ----------------------------
+
+/*
+ * Initializes ACE - connects (RW) to the database. Must be called only once.
+ * Returns ACE_OK or error
+ */
+ace_return_t ace_install_initialize(void);
+
+/*
+ * Deinitializes ACE - deinitialize internal structures, detach DB, etc.
+ * Must be called only once.
+ * Returns ACE_OK or error
+ */
+ace_return_t ace_install_shutdown(void);
+
+/*
+ * Updates policy - parses XML files from known locations (reason for no arguments),
+ * also clears policy and prompt caches.
+ * Returns ACE_OK or error
+ */
+ace_return_t ace_update_policy(void);
+
+// --------------- Requested device capabilities API for installer -------------
+
+typedef struct
+{
+    ace_string_t   device_capability;
+    ace_bool_t     smack_granted;
+} ace_requested_dev_cap_t;
+
+typedef struct
+{
+    ace_size_t              count;
+    ace_requested_dev_cap_t*  items;
+} ace_requested_dev_cap_list_t;
+
+/*
+ * Deletes data allocated by ace_get_requested_dev_caps - a helper function
+ */
+ace_return_t ace_free_requested_dev_caps(ace_requested_dev_cap_list_t* caps);
+
+/*
+ * Returns ACE_OK or error; 'caps' will hold device capabilities information.
+ * To free allcated resources in 'caps', use ace_free_requested_dev_caps
+ */
+ace_return_t ace_get_requested_dev_caps(ace_widget_handle_t handle,
+                                        ace_requested_dev_cap_list_t* caps);
+
+/*
+ * Returns error or ACE_OK
+ */
+ace_return_t ace_set_requested_dev_caps(ace_widget_handle_t handle,
+                                        const ace_requested_dev_cap_list_t* caps);
+
+ace_return_t ace_rem_requested_dev_caps(ace_widget_handle_t handle);
+
+// ---------------- Accepted Api featuresk API for installer ----------------
+
+
+ace_return_t ace_set_accepted_feature(ace_widget_handle_t handle,
+                                      const ace_feature_list_t* flist);
+
+ace_return_t ace_rem_accepted_feature(ace_widget_handle_t handle);
+
+// --------------- Widget data setup for installation --------------------------
+
+typedef enum
+{
+    WAC20 = 0,
+    Tizen
+} ace_widget_type_t;
+
+struct widget_info {
+    ace_widget_type_t type;
+    ace_string_t id;
+    ace_string_t version;
+    ace_string_t author;
+    ace_string_t shareHerf;
+};
+
+typedef enum
+{
+    AUTHOR,
+    DISTRIBUTOR,
+    UNKNOWN
+} ace_cert_owner_t;
+
+typedef enum
+{
+    ROOT,
+    ENDENTITY
+} ace_cert_type_t;
+
+typedef struct certificate_data {
+    ace_cert_owner_t owner;
+    ace_cert_type_t type;
+    int chain_id;
+    ace_string_t md5_fp;
+    ace_string_t sha1_fp;
+    ace_string_t common_name;
+} ace_certificate_data;
+
+/*
+ * Register widget info into database.
+ * @param cert_data NULL terminated list of widget certificates
+ */
+
+ace_return_t ace_register_widget(ace_widget_handle_t handle,
+                                 struct widget_info* info,
+                                 ace_certificate_data* cert_data[]);
+
+ace_return_t ace_unregister_widget(ace_widget_handle_t handle);
+
+ace_return_t ace_is_widget_installed(ace_widget_handle_t handle, bool *installed);
+
+/*
+ * Gets widget type in 'type'. Use in installer to determine which policy will be used
+ * by ACE for this widget.
+ * Returns error or ACE_OK
+ */
+ace_return_t ace_get_widget_type(ace_widget_handle_t handle,
+                                 ace_widget_type_t* type);
+
+// --------------- Installation time policy check ------------------------------
+
+typedef enum
+{
+    ACE_PERMIT,
+    ACE_DENY,
+    ACE_PROMPT,
+    ACE_UNDEFINED
+} ace_policy_result_t;
+
+/*
+ * Gets current policy evaluation for given device capability and given widget.
+ * Returns error or ACE_OK
+ */
+ace_return_t ace_get_policy_result(const ace_resource_t,
+                                   ace_widget_handle_t handle,
+                                   ace_policy_result_t* result);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // ACE_API_H
diff --git a/ace_install/src/CMakeLists.txt b/ace_install/src/CMakeLists.txt
new file mode 100644 (file)
index 0000000..2414b6c
--- /dev/null
@@ -0,0 +1,81 @@
+include(FindPkgConfig)
+
+IF(DEFINED DBUS_CONNECTION)
+PKG_CHECK_MODULES(ACE_INSTALL_DEPS
+    dpl-efl
+    dpl-dbus-efl
+    REQUIRED
+    )
+ENDIF()
+
+SET(ACE_INSTALL_DIR
+    ${PROJECT_SOURCE_DIR}/ace_install
+    )
+
+SET(ACE_INSTALL_SRC_DIR
+    ${ACE_INSTALL_DIR}/src
+    )
+
+SET(ACE_INSTALL_INCLUDE_DIR
+    ${ACE_INSTALL_DIR}/include
+    )
+
+SET(ACE_INSTALL_SOURCES
+    ${COMMUNICATION_CLIENT_SOURCES}
+    ${ACE_INSTALL_SRC_DIR}/ace_api_install.cpp    
+    )
+
+SET(ACE_INSTALL_INCLUDES
+    ${COMMUNICATION_CLIENT_INCLUDES}
+    ${ACE_INSTALL_DEPS_INCLUDE_DIRS}
+    ${ACE_INSTALL_INCLUDE_DIR}
+    ${PROJECT_SOURCE_DIR}/ace_common/include
+    ${PROJECT_SOURCE_DIR}/ace/include
+    ${PROJECT_SOURCE_DIR}/src/services/ace
+    ${PROJECT_SOURCE_DIR}/src/services/ace/dbus/api
+    ${PROJECT_SOURCE_DIR}/src/daemon/dbus
+    )
+
+ADD_DEFINITIONS(${ACE_INSTALL_DEPS_CFLAGS})
+ADD_DEFINITIONS(${ACE_INSTALL_CFLAGS_OTHER})
+
+INCLUDE_DIRECTORIES(${ACE_INSTALL_INCLUDES})
+IF(NOT DEFINED DBUS_CONNECTION)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/commons/modules/log/include)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/commons/modules/core/include)
+LINK_DIRECTORIES(
+    ${PROJECT_SOURCE_DIR}/commons/build/core
+    ${PROJECT_SOURCE_DIR}/commons/build/log
+    )
+ENDIF()
+
+ADD_LIBRARY(${TARGET_ACE_INSTALL_LIB} SHARED ${ACE_INSTALL_SOURCES})
+
+SET_TARGET_PROPERTIES(${TARGET_ACE_INSTALL_LIB} PROPERTIES
+    SOVERSION ${API_VERSION}
+    VERSION ${VERSION})
+
+SET_TARGET_PROPERTIES(${TARGET_ACE_INSTALL_LIB} PROPERTIES
+    COMPILE_FLAGS -fPIC)
+
+IF(DEFINED DBUS_CONNECTION)
+TARGET_LINK_LIBRARIES(${TARGET_ACE_INSTALL_LIB}
+    ${ACE_INSTALL_DEPS_LIBRARIES}
+    ${TARGET_ACE_DAO_RW_LIB}
+    )
+ELSE()
+TARGET_LINK_LIBRARIES(${TARGET_ACE_INSTALL_LIB}
+    ${ACE_INSTALL_DEPS_LIBRARIES}
+    ${TARGET_ACE_DAO_RW_LIB}
+    libwrt-security-commons
+    libwrt-security-commons-log
+    )
+ENDIF()
+
+INSTALL(TARGETS ${TARGET_ACE_INSTALL_LIB}
+    DESTINATION ${LIB_INSTALL_DIR})
+
+INSTALL(FILES
+    ${ACE_INSTALL_INCLUDE_DIR}/ace_api_install.h
+    DESTINATION include/ace-install
+    )
diff --git a/ace_install/src/ace_api_install.cpp b/ace_install/src/ace_api_install.cpp
new file mode 100644 (file)
index 0000000..a18d452
--- /dev/null
@@ -0,0 +1,357 @@
+/*
+ * 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        ace_api_install.cpp
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This file contains implementation ACE installator API
+ */
+
+#include <string>
+#include <utility>
+#include <string.h>
+#include <dpl/log/log.h>
+#include <dpl/foreach.h>
+#include <dpl/string.h>
+#include "SecurityCommunicationClient.h"
+#include <ace-dao-rw/AceDAO.h>
+#include "ace_server_api.h"
+
+#include "ace_api_install.h"
+
+static WrtSecurity::Communication::Client *communicationClient = NULL;
+
+// helper functions
+
+static AceDB::AppTypes to_db_app_type(ace_widget_type_t widget_type)
+{
+    switch (widget_type) {
+    case WAC20:
+        return AceDB::AppTypes::WAC20;
+    case Tizen:
+        return AceDB::AppTypes::Tizen;
+    default:
+        return AceDB::AppTypes::Unknown;
+    }
+}
+
+static ace_widget_type_t to_ace_widget_type(AceDB::AppTypes app_type)
+{
+    switch (app_type) {
+    case AceDB::AppTypes::WAC20:
+        return WAC20;
+    case AceDB::AppTypes::Tizen:
+        return Tizen;
+    default:
+        LogError("Invalid app type for widget");
+        return WAC20;
+    }
+}
+
+ace_return_t ace_install_initialize(void)
+{
+    if (NULL != communicationClient) {
+        LogError("ace_api_install already initialized");
+        return ACE_INTERNAL_ERROR;
+    }
+    AceDB::AceDAO::attachToThreadRW();
+    Try {
+        communicationClient = new WrtSecurity::Communication::Client(
+                   WrtSecurity::AceServerApi::INTERFACE_NAME());
+    } Catch (WrtSecurity::Communication::Client::Exception::SecurityCommunicationClientException) {
+        LogError("Can't connect to daemon");
+        return ACE_INTERNAL_ERROR;
+    }
+    return ACE_OK;
+}
+
+ace_return_t ace_install_shutdown(void)
+{
+    if (NULL == communicationClient) {
+        LogError("ace_api_install not initialized");
+        return ACE_INTERNAL_ERROR;
+    }
+    delete communicationClient;
+    communicationClient = NULL;
+    AceDB::AceDAO::detachFromThread();
+    return ACE_OK;
+}
+
+ace_return_t ace_update_policy(void)
+{
+    Try {
+        communicationClient->call(WrtSecurity::AceServerApi::UPDATE_POLICY_METHOD());
+    } Catch (WrtSecurity::Communication::Client::Exception::SecurityCommunicationClientException) {
+        LogError("Problem with connection to daemon");
+        return ACE_INTERNAL_ERROR;
+    }
+    return ACE_OK;
+}
+
+ace_return_t ace_free_requested_dev_caps(ace_requested_dev_cap_list_t* caps)
+{
+    if (NULL == caps || NULL == caps->items) {
+        LogError("Invalid arguments");
+        return ACE_INVALID_ARGUMENTS;
+    }
+    unsigned int i;
+    for (i = 0; i < caps->count; ++i) {
+        delete [] caps->items[i].device_capability;
+    }
+    delete [] caps->items;
+    return ACE_OK;
+}
+
+ace_return_t ace_get_requested_dev_caps(ace_widget_handle_t handle,
+                                        ace_requested_dev_cap_list_t* caps)
+{
+    if (NULL == caps) {
+        LogError("Invalid arguments");
+        return ACE_INVALID_ARGUMENTS;
+    }
+    AceDB::RequestedDevCapsMap permissions;
+    Try {
+        AceDB::AceDAO::getRequestedDevCaps(
+                handle, &permissions);
+    } Catch(AceDB::AceDAOReadOnly::Exception::DatabaseError) {
+        return ACE_INTERNAL_ERROR;
+    }
+    caps->items = new ace_requested_dev_cap_t[permissions.size()];
+    caps->count = permissions.size();
+    unsigned int i = 0;
+    FOREACH (it, permissions) {
+        std::string devCapRequested = DPL::ToUTF8String(it->first);
+        int length = strlen(devCapRequested.c_str());
+        caps->items[i].device_capability =
+                new char[length + 1];
+        memset(caps->items[i].device_capability, 0, length + 1);
+        strncpy(caps->items[i].device_capability, devCapRequested.c_str(), length);
+        caps->items[i].smack_granted = it->second ? ACE_TRUE : ACE_FALSE;
+        ++i;
+    }
+    return ACE_OK;
+}
+
+ace_return_t ace_set_requested_dev_caps(
+        ace_widget_handle_t handle,
+        const ace_requested_dev_cap_list_t* caps)
+{
+    if (NULL == caps) {
+        LogError("Invalid arguments");
+        return ACE_INVALID_ARGUMENTS;
+    }
+    AceDB::RequestedDevCapsMap db_permissions;
+    unsigned int i;
+    for (i = 0; i < caps->count; ++i) {
+        std::string devCap = std::string(caps->items[i].device_capability);
+        db_permissions.insert(std::make_pair(DPL::FromUTF8String(devCap),
+                              caps->items[i].smack_granted == ACE_TRUE));
+    }
+    Try {
+        AceDB::AceDAO::setRequestedDevCaps(
+                handle, db_permissions);
+    } Catch(AceDB::AceDAOReadOnly::Exception::DatabaseError) {
+        return ACE_INTERNAL_ERROR;
+    }
+    return ACE_OK;
+}
+ace_return_t ace_rem_requested_dev_caps(
+        ace_widget_handle_t handle)
+{
+    Try {
+        AceDB::AceDAO::removeRequestedDevCaps(handle);
+    } Catch(AceDB::AceDAOReadOnly::Exception::DatabaseError) {
+        return ACE_INTERNAL_ERROR;
+    }
+    return ACE_OK;
+}
+
+ace_return_t ace_set_accepted_feature(
+        ace_widget_handle_t handle,
+        const ace_feature_list_t *feature)
+{
+    if (NULL == feature) {
+        LogError("Invalid argument");
+        return ACE_INVALID_ARGUMENTS;
+    }
+    AceDB::FeatureNameVector fvector;
+    ace_size_t i;
+    for (i = 0; i < feature->count; ++i) {
+        fvector.push_back(
+            DPL::FromUTF8String(feature->items[i]));
+    }
+    Try {
+        AceDB::AceDAO::setAcceptedFeature(handle, fvector);
+    } Catch(AceDB::AceDAOReadOnly::Exception::DatabaseError) {
+        return ACE_INTERNAL_ERROR;
+    }
+    return ACE_OK;
+}
+
+ace_return_t ace_rem_accepted_feature(
+        ace_widget_handle_t handle)
+{
+    Try {
+        AceDB::AceDAO::removeAcceptedFeature(handle);
+    } Catch(AceDB::AceDAOReadOnly::Exception::DatabaseError) {
+        return ACE_INTERNAL_ERROR;
+    }
+    return ACE_OK;
+}
+
+ace_return_t ace_register_widget(ace_widget_handle_t handle,
+                                 struct widget_info *info,
+                                 ace_certificate_data* cert_data[])
+{
+    LogDebug("enter");
+
+    if (NULL == info || AceDB::AceDAOReadOnly::isWidgetInstalled(handle))
+        return ACE_INVALID_ARGUMENTS;
+
+    AceDB::WidgetRegisterInfo wri;
+    wri.type = to_db_app_type(info->type);
+
+    if (info->id)
+        wri.widget_id = DPL::FromUTF8String(info->id);
+    if (info->version)
+        wri.version = DPL::FromUTF8String(info->version);
+    if (info->author)
+        wri.authorName = DPL::FromUTF8String(info->author);
+    if (info->shareHerf)
+        wri.shareHref = DPL::FromUTF8String(info->shareHerf);
+
+    AceDB::WidgetCertificateDataList dataList;
+    if (NULL != cert_data) {
+        AceDB::WidgetCertificateData wcd;
+        ace_certificate_data* cd;
+        int i = 0;
+        while (cert_data[i] != NULL)
+        {
+            cd = cert_data[i++]; //increment
+            switch(cd->type) {
+            case ROOT:
+                wcd.type = AceDB::WidgetCertificateData::Type::ROOT;
+                break;
+            case ENDENTITY:
+                wcd.type = AceDB::WidgetCertificateData::Type::ENDENTITY;
+                break;
+            }
+            switch(cd->owner) {
+            case AUTHOR:
+                wcd.owner = AceDB::WidgetCertificateData::Owner::AUTHOR;
+                break;
+            case DISTRIBUTOR:
+                wcd.owner = AceDB::WidgetCertificateData::Owner::DISTRIBUTOR;
+                break;
+            case UNKNOWN: default:
+                wcd.owner = AceDB::WidgetCertificateData::Owner::UNKNOWN;
+                break;
+            }
+            wcd.chainId = cd->chain_id;
+            if (cd->md5_fp)
+                wcd.strMD5Fingerprint = cd->md5_fp;
+            if (cd->sha1_fp)
+                wcd.strSHA1Fingerprint = cd->sha1_fp;
+            if (cd->common_name)
+                wcd.strCommonName = DPL::FromUTF8String(cd->common_name);
+            dataList.push_back(wcd);
+        }
+        LogDebug("All data set. Inserting into database.");
+    }
+
+    Try {
+        AceDB::AceDAO::registerWidgetInfo((WidgetHandle)(handle), wri, dataList);
+        LogDebug("AceDB entry done");
+    } Catch(AceDB::AceDAOReadOnly::Exception::DatabaseError) {
+        return ACE_INTERNAL_ERROR;
+    }
+    return ACE_OK;
+}
+
+ace_return_t ace_unregister_widget(ace_widget_handle_t handle)
+{
+    Try {
+        AceDB::AceDAO::unregisterWidgetInfo((WidgetHandle)(handle));
+    } Catch(AceDB::AceDAOReadOnly::Exception::DatabaseError) {
+        return ACE_INTERNAL_ERROR;
+    }
+    return ACE_OK;
+}
+
+ace_return_t ace_is_widget_installed(ace_widget_handle_t handle, bool *installed)
+{
+    Try {
+        *installed = AceDB::AceDAO::isWidgetInstalled((WidgetHandle)(handle));
+    } Catch(AceDB::AceDAOReadOnly::Exception::DatabaseError) {
+        return ACE_INTERNAL_ERROR;
+    }
+    return ACE_OK;
+}
+
+ace_return_t ace_get_widget_type(ace_widget_handle_t handle,
+                                 ace_widget_type_t* type)
+{
+    if (NULL == type) {
+        LogError("Invalid arguments");
+        return ACE_INVALID_ARGUMENTS;
+    }
+    Try {
+        AceDB::AppTypes db_type = AceDB::AceDAO::getWidgetType(handle);
+        *type = to_ace_widget_type(db_type);
+    } Catch(AceDB::AceDAOReadOnly::Exception::DatabaseError) {
+        return ACE_INTERNAL_ERROR;
+    }
+    return ACE_OK;
+}
+
+ace_return_t ace_get_policy_result(const ace_resource_t resource,
+                                   ace_widget_handle_t handle,
+                                   ace_policy_result_t* result)
+{
+    if (NULL == result) {
+        LogError("Invalid arguments");
+        return ACE_INVALID_ARGUMENTS;
+    }
+    int serializedPolicyResult = 0;
+    Try {
+       std::string resource_str(resource);
+       communicationClient->call(WrtSecurity::AceServerApi::CHECK_ACCESS_INSTALL_METHOD(),
+                        handle,
+                        resource_str,
+                        &serializedPolicyResult);
+   } Catch (WrtSecurity::Communication::Client::Exception::SecurityCommunicationClientException) {
+       LogError("Can't connect to daemon");
+       return ACE_INTERNAL_ERROR;
+   }
+   PolicyResult policyResult = PolicyResult::
+           deserialize(serializedPolicyResult);
+   OptionalPolicyEffect effect = policyResult.getEffect();
+   if (!effect) {
+       *result = ACE_UNDEFINED;
+   } else if (*effect == PolicyEffect::DENY) {
+       *result = ACE_DENY;
+   } else if (*effect == PolicyEffect::PERMIT) {
+       *result = ACE_PERMIT;
+   } else if (*effect == PolicyEffect::PROMPT_ONESHOT ||
+              *effect == PolicyEffect::PROMPT_BLANKET ||
+              *effect == PolicyEffect::PROMPT_SESSION){
+       *result = ACE_PROMPT;
+   } else {
+       *result = ACE_UNDEFINED;
+   }
+
+   return ACE_OK;
+}
diff --git a/ace_popup_validation/CMakeLists.txt b/ace_popup_validation/CMakeLists.txt
new file mode 100644 (file)
index 0000000..4b7537b
--- /dev/null
@@ -0,0 +1 @@
+ADD_SUBDIRECTORY(src)
diff --git a/ace_popup_validation/include/ace_api_popup_validation.h b/ace_popup_validation/include/ace_api_popup_validation.h
new file mode 100644 (file)
index 0000000..f06dfcf
--- /dev/null
@@ -0,0 +1,76 @@
+/*
+ * 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        ace_popup_validation_api.h
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This is C api for Access Control Engine (ACE), popup
+ *              validation library.
+ *
+ */
+
+#ifndef ACE_API_H
+#define ACE_API_H
+
+#include <ace_api_common.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+// --------------- Initialization and deinitialization -------------------------
+
+/*
+ * Initializes the library.
+ *
+ * Returns error or ACE_OK.
+ */
+ace_return_t ace_popup_validation_initialize(void);
+
+/*
+ * Deinitializes the library.
+ *
+ * Returns error or ACE_OK.
+ */
+ace_return_t ace_popup_validation_shutdown(void);
+
+// --------------- Popup answer validation API ---------------------------------
+
+/*
+ * Validation of popup answer. This API must be called by implementation of
+ * UI handler. The call must be made from safe process, specially labelled by
+ * SMACK. If returned value is ACE_OK, 'validation_result' holds validation
+ * result that needs to be passed by UI handler as validation result. Otherwise
+ * value of 'validation_result' is undefined.
+ *
+ * See header ace_api_client.h for more details on where this function needs to
+ * be called and what arguments need to be passed here.
+ *
+ * Returns error or ACE_OK.
+ */
+ace_return_t ace_validate_answer(ace_bool_t answer,
+                                 ace_validity_t validity,
+                                 const ace_resource_t resource_name,
+                                 const ace_session_id_t session_id,
+                                 const ace_param_list_t* param_list,
+                                 ace_widget_handle_t handle,
+                                 ace_bool_t* validation_result);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // ACE_API_H
diff --git a/ace_popup_validation/src/CMakeLists.txt b/ace_popup_validation/src/CMakeLists.txt
new file mode 100644 (file)
index 0000000..5811176
--- /dev/null
@@ -0,0 +1,81 @@
+include(FindPkgConfig)
+
+IF(DEFINED DBUS_CONNECTION)
+PKG_CHECK_MODULES(ACE_POPUP_VALIDATION_DEPS
+    dpl-efl
+    dpl-dbus-efl
+    REQUIRED
+    )
+ENDIF()
+
+SET(ACE_POPUP_VALIDATION_DIR
+    ${PROJECT_SOURCE_DIR}/ace_popup_validation
+    )
+
+SET(ACE_POPUP_VALIDATION_SRC_DIR
+    ${ACE_POPUP_VALIDATION_DIR}/src
+    )
+
+SET(ACE_POPUP_VALIDATION_INCLUDE_DIR
+    ${ACE_POPUP_VALIDATION_DIR}/include
+    )
+
+SET(ACE_POPUP_VALIDATION_SOURCES
+    ${COMMUNICATION_CLIENT_SOURCES}
+    ${ACE_POPUP_VALIDATION_SRC_DIR}/ace_api_popup_validation.cpp    
+    )
+
+SET(ACE_POPUP_VALIDATION_INCLUDES
+    ${COMMUNICATION_CLIENT_INCLUDES}
+    ${ACE_POPUP_VALIDATION_DEPS_INCLUDE_DIRS}
+    ${ACE_POPUP_VALIDATION_INCLUDE_DIR}
+    ${PROJECT_SOURCE_DIR}/ace_common/include
+    ${PROJECT_SOURCE_DIR}/ace/include
+    ${PROJECT_SOURCE_DIR}/src/services/ace/dbus/api        
+    ${PROJECT_SOURCE_DIR}/src/services/ace
+    ${PROJECT_SOURCE_DIR}/src/services/popup/
+    ${PROJECT_SOURCE_DIR}/src/daemon/dbus    
+    )
+
+ADD_DEFINITIONS(${ACE_POPUP_VALIDATION_DEPS_CFLAGS})
+ADD_DEFINITIONS(${ACE_POPUP_VALIDATION_CFLAGS_OTHER})
+
+INCLUDE_DIRECTORIES(${ACE_POPUP_VALIDATION_INCLUDES})
+IF(NOT DEFINED DBUS_CONNECTION)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/commons/modules/log/include)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/commons/modules/core/include)
+LINK_DIRECTORIES(
+    ${PROJECT_SOURCE_DIR}/commons/build/core
+    ${PROJECT_SOURCE_DIR}/commons/build/log
+    )
+ENDIF()
+ADD_LIBRARY(${TARGET_ACE_POPUP_VALIDATION_LIB} SHARED ${ACE_POPUP_VALIDATION_SOURCES})
+
+SET_TARGET_PROPERTIES(${TARGET_ACE_POPUP_VALIDATION_LIB} PROPERTIES
+    SOVERSION ${API_VERSION}
+    VERSION ${VERSION})
+
+SET_TARGET_PROPERTIES(${TARGET_ACE_POPUP_VALIDATION_LIB} PROPERTIES
+    COMPILE_FLAGS -fPIC)
+
+IF(DEFINED DBUS_CONNECTION)
+TARGET_LINK_LIBRARIES(${TARGET_ACE_POPUP_VALIDATION_LIB}
+    ${ACE_POPUP_VALIDATION_DEPS_LIBRARIES} 
+    ${ACE_POPUP_VALIDATION_DEPS_LDFLAGS}
+    )
+ELSE()
+TARGET_LINK_LIBRARIES(${TARGET_ACE_POPUP_VALIDATION_LIB}
+    ${ACE_POPUP_VALIDATION_DEPS_LIBRARIES} 
+    ${ACE_POPUP_VALIDATION_DEPS_LDFLAGS}
+    libwrt-security-commons
+    libwrt-security-commons-log
+    )
+ENDIF()
+
+INSTALL(TARGETS ${TARGET_ACE_POPUP_VALIDATION_LIB}
+    DESTINATION ${LIB_INSTALL_DIR})
+
+INSTALL(FILES
+    ${ACE_POPUP_VALIDATION_INCLUDE_DIR}/ace_api_popup_validation.h
+    DESTINATION include/ace-popup-validation
+    )
diff --git a/ace_popup_validation/src/ace_api_popup_validation.cpp b/ace_popup_validation/src/ace_api_popup_validation.cpp
new file mode 100644 (file)
index 0000000..32e8b13
--- /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        ace_api_popup_validation.cpp
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This file contains implementation of ACE popup validation API.
+ */
+
+#include <string>
+#include <vector>
+#include <dpl/log/log.h>
+#include "SecurityCommunicationClient.h"
+#include "popup_response_server_api.h"
+#ifdef DBUS_CONNECTION
+#include "security_daemon_dbus_config.h"
+#endif
+#include "ace_api_popup_validation.h"
+
+namespace {
+static WrtSecurity::Communication::Client *communicationClient = NULL;
+static const int VALIDITY_ONCE_VALUE = 0;
+static const int VALIDITY_SESSION_VALUE = 1;
+static const int VALIDITY_ALWAYS_VALUE = 1;
+} // anonymous
+
+ace_return_t ace_popup_validation_initialize(void)
+{
+    if (NULL != communicationClient) {
+        LogError("ace_api_popup_validation already initialized");
+        return ACE_INTERNAL_ERROR;
+    }
+    Try {
+        communicationClient = new WrtSecurity::Communication::Client(
+                   WrtSecurity::PopupServerApi::INTERFACE_NAME());
+    } Catch (WrtSecurity::Communication::Client::Exception::SecurityCommunicationClientException) {
+        LogError("Can't connect to daemon");
+        return ACE_INTERNAL_ERROR;
+    }
+
+    return ACE_OK; 
+}
+
+ace_return_t ace_popup_validation_shutdown(void)
+{
+    if (NULL == communicationClient) {
+        LogError("ace_api_popup_validation not initialized");
+        return ACE_INTERNAL_ERROR;
+    }
+    delete communicationClient;
+    communicationClient = NULL;
+
+    return ACE_OK;
+}
+
+ace_return_t ace_validate_answer(ace_bool_t answer,
+                                 ace_validity_t validity,
+                                 const ace_resource_t resource_name,
+                                 const ace_session_id_t session_id,
+                                 const ace_param_list_t* param_list,
+                                 ace_widget_handle_t handle,
+                                 ace_bool_t* validation_result)
+{
+    if (NULL == resource_name ||
+        NULL == session_id ||
+        NULL == param_list ||
+        NULL == validation_result)
+    {
+        LogError("NULL argument(s) passed");
+        return ACE_INVALID_ARGUMENTS;
+    }
+
+    bool dbusAnswer = answer == ACE_TRUE;
+    int dbusValidity = 0;
+
+    switch (validity) {
+    case ACE_ONCE: {
+        dbusValidity = VALIDITY_ONCE_VALUE;
+        //static_cast<int>(Prompt::Validity::ONCE);
+        break; }
+    case ACE_SESSION: {
+        dbusValidity = VALIDITY_SESSION_VALUE;
+        //static_cast<int>(Prompt::Validity::SESSION);
+        break; }
+    case ACE_ALWAYS: {
+        dbusValidity = VALIDITY_ALWAYS_VALUE;
+        //static_cast<int>(Prompt::Validity::ALWAYS);
+        break; }
+    default: {
+        LogError("Invalid validity passed");
+        return ACE_INVALID_ARGUMENTS; }
+    }
+
+    std::string subjectId;
+    std::string resourceId(resource_name);
+    std::string sessionId(session_id);
+    std::vector<std::string> keys, values;
+    unsigned int i;
+    for (i = 0; i < param_list->count; ++i) {
+        keys.push_back(std::string(param_list->items[i].name));
+        values.push_back(std::string(param_list->items[i].value));
+    }
+
+    bool response = false;
+    Try{
+        communicationClient->call(WrtSecurity::PopupServerApi::VALIDATION_METHOD(),
+                         dbusAnswer,
+                         dbusValidity,
+                         handle,
+                         subjectId,
+                         resourceId,
+                         keys,
+                         values,
+                         sessionId,
+                         &response);
+    } Catch (WrtSecurity::Communication::Client::Exception::SecurityCommunicationClientException) {
+        LogError("Can't call daemon");
+        return ACE_INTERNAL_ERROR;
+    }
+
+    *validation_result = response ? ACE_TRUE : ACE_FALSE;
+
+    return ACE_OK;
+}
diff --git a/ace_settings/CMakeLists.txt b/ace_settings/CMakeLists.txt
new file mode 100644 (file)
index 0000000..4b7537b
--- /dev/null
@@ -0,0 +1 @@
+ADD_SUBDIRECTORY(src)
diff --git a/ace_settings/include/ace_api_settings.h b/ace_settings/include/ace_api_settings.h
new file mode 100644 (file)
index 0000000..a3c72ab
--- /dev/null
@@ -0,0 +1,121 @@
+/*
+ * 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        ace_api_settings.h
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This is header for ACE settings API (RW part).
+ */
+
+#ifndef ACE_API_SETTINGS_H
+#define ACE_API_SETTINGS_H
+
+#include <ace_api_common.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * API defined in this header should be used only from one thread. If used
+ * otherwise, unexpected behaviour may occur, including segmentation faults and
+ * escalation of global warming. Be warned.
+ */
+
+// --------------- Initialization ----------------------------------------------
+
+/*
+ * Initializes ACE - connects (RW) to the database. Must be called only once.
+ * Returns ACE_OK or error
+ */
+ace_return_t ace_settings_initialize(void);
+
+/*
+ * Deinitializes ACE - deinitialize internal structures, detach DB, etc.
+ * Must be called only once.
+ * Returns ACE_OK or error
+ */
+ace_return_t ace_settings_shutdown(void);
+
+// --------------- Resource settings API ---------------------------------------
+
+/*
+ * Order and values of enum constants are part of API
+ */
+typedef enum
+{
+    ACE_PREFERENCE_PERMIT,
+    ACE_PREFERENCE_DENY,
+    ACE_PREFERENCE_DEFAULT,         // means: not set
+    ACE_PREFERENCE_BLANKET_PROMPT,
+    ACE_PREFERENCE_SESSION_PROMPT,
+    ACE_PREFERENCE_ONE_SHOT_PROMPT
+} ace_preference_t;
+
+/*
+ * Returns error or ACE_OK
+ * If return value is ACE_OK, 'prerefence' value is the queried one, otherwise
+ * 'preference' value is undefined
+ */
+ace_return_t ace_get_widget_resource_preference(ace_widget_handle_t handle,
+                                                const ace_resource_t resource,
+                                                ace_preference_t* preference);
+
+/*
+ * Returns error or ACE_OK
+ * If return value is ACE_OK, 'prerefence' value is the queried one, otherwise
+ * 'preference' value is undefined
+ */
+ace_return_t ace_get_global_resource_preference(const ace_resource_t resource,
+        ace_preference_t* preference);
+
+/*
+ * To reset setting, pass ACE_PREFERENCE_DEFAULT
+ * Returns error or ACE_OK
+ */
+ace_return_t ace_set_widget_resource_preference(ace_widget_handle_t handle,
+                                                const ace_resource_t resource,
+                                                ace_preference_t preference);
+
+/*
+ * To reset setting, pass ACE_PREFERENCE_DEFAULT
+ * Returns error or ACE_OK
+ */
+ace_return_t ace_set_global_resource_preference(const ace_resource_t resource,
+                                                ace_preference_t preference);
+
+/*
+ * Resets per widget resource settings to ACE_PREFERENCE_DEFAULT
+ */
+ace_return_t ace_reset_widget_resource_settings(void);
+
+/*
+ * Resets global resource settings to ACE_PREFERENCE_DEFAULT
+ */
+ace_return_t ace_reset_global_resource_settings(void);
+
+/*
+ * After execution, is_privacy_api is ACE_TRUE if resource_name is the name
+ * of Privacy API
+ */
+ace_return_t ace_is_private_api(const ace_resource_t resource_name,
+                       ace_bool_t* is_private_api);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif // ACE_API_SETTINGS_H
diff --git a/ace_settings/src/CMakeLists.txt b/ace_settings/src/CMakeLists.txt
new file mode 100644 (file)
index 0000000..e4d527d
--- /dev/null
@@ -0,0 +1,75 @@
+include(FindPkgConfig)
+
+IF(DEFINED DBUS_CONNECTION)
+PKG_CHECK_MODULES(ACE_SETTINGS_DEPS
+    dpl-efl
+    REQUIRED
+    )
+ENDIF()
+
+SET(ACE_SETTINGS_DIR
+    ${PROJECT_SOURCE_DIR}/ace_settings
+    )
+
+SET(ACE_SETTINGS_SRC_DIR
+    ${ACE_SETTINGS_DIR}/src
+    )
+
+SET(ACE_SETTINGS_INCLUDE_DIR
+    ${ACE_SETTINGS_DIR}/include
+    )
+
+SET(ACE_SETTINGS_SOURCES
+    ${ACE_SETTINGS_SRC_DIR}/ace_api_settings.cpp    
+    )
+
+SET(ACE_SETTINGS_INCLUDES
+    ${ACE_SETTINGS_DEPS_INCLUDE_DIRS}
+    ${ACE_SETTINGS_INCLUDE_DIR}
+    ${PROJECT_SOURCE_DIR}/ace_common/include
+    ${PROJECT_SOURCE_DIR}/ace/include
+    )
+
+ADD_DEFINITIONS(${ACE_SETTINGS_DEPS_CFLAGS})
+ADD_DEFINITIONS(${ACE_SETTINGS_CFLAGS_OTHER})
+
+INCLUDE_DIRECTORIES(${ACE_SETTINGS_INCLUDES})
+IF(NOT DEFINED DBUS_CONNECTION)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/commons/modules/core/include)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/commons/modules/log/include)
+LINK_DIRECTORIES(
+    ${PROJECT_SOURCE_DIR}/commons/build/core
+    ${PROJECT_SOURCE_DIR}/commons/build/log
+    )
+ENDIF()
+
+ADD_LIBRARY(${TARGET_ACE_SETTINGS_LIB} SHARED ${ACE_SETTINGS_SOURCES})
+
+SET_TARGET_PROPERTIES(${TARGET_ACE_SETTINGS_LIB} PROPERTIES
+    SOVERSION ${API_VERSION}
+    VERSION ${VERSION})
+
+SET_TARGET_PROPERTIES(${TARGET_ACE_SETTINGS_LIB} PROPERTIES
+    COMPILE_FLAGS -fPIC)
+
+IF(DEFINED DBUS_CONNECTION)
+TARGET_LINK_LIBRARIES(${TARGET_ACE_SETTINGS_LIB}
+    ${ACE_SETTINGS_DEPS_LIBRARIES}
+    ${TARGET_ACE_DAO_RW_LIB}
+    )
+ELSE()
+TARGET_LINK_LIBRARIES(${TARGET_ACE_SETTINGS_LIB}
+    ${ACE_SETTINGS_DEPS_LIBRARIES}
+    ${TARGET_ACE_DAO_RW_LIB}
+    wrt-security-commons
+    wrt-security-commons-log
+    )
+ENDIF()
+
+INSTALL(TARGETS ${TARGET_ACE_SETTINGS_LIB}
+    DESTINATION ${LIB_INSTALL_DIR})
+
+INSTALL(FILES
+    ${ACE_SETTINGS_INCLUDE_DIR}/ace_api_settings.h
+    DESTINATION include/ace-settings
+    )
diff --git a/ace_settings/src/ace_api_settings.cpp b/ace_settings/src/ace_api_settings.cpp
new file mode 100644 (file)
index 0000000..a1a811d
--- /dev/null
@@ -0,0 +1,203 @@
+/*
+ * 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        ace_api_settings.cpp
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This file contains implementation ACE settings API
+ */
+
+#include <string>
+#include <dpl/log/log.h>
+#include <ace-dao-rw/AceDAO.h>
+
+#include "ace_api_settings.h"
+
+// helper functions
+static ace_preference_t to_ace_preference(const AceDB::PreferenceTypes& db_preference)
+{
+    switch (db_preference) {
+    case AceDB::PreferenceTypes::PREFERENCE_BLANKET_PROMPT: {
+        return ACE_PREFERENCE_BLANKET_PROMPT; }
+    case AceDB::PreferenceTypes::PREFERENCE_DEFAULT: {
+        return ACE_PREFERENCE_DEFAULT;}
+    case AceDB::PreferenceTypes::PREFERENCE_DENY: {
+        return ACE_PREFERENCE_DENY;}
+    case AceDB::PreferenceTypes::PREFERENCE_ONE_SHOT_PROMPT: {
+        return ACE_PREFERENCE_ONE_SHOT_PROMPT;}
+    case AceDB::PreferenceTypes::PREFERENCE_PERMIT: {
+        return ACE_PREFERENCE_PERMIT;}
+    case AceDB::PreferenceTypes::PREFERENCE_SESSION_PROMPT: {
+        return ACE_PREFERENCE_SESSION_PROMPT;}
+    default: {
+        return ACE_PREFERENCE_DEFAULT;}
+    }
+}
+
+
+static AceDB::PreferenceTypes to_ace_db_preference(const ace_preference_t& preference)
+{
+    switch (preference) {
+    case ACE_PREFERENCE_BLANKET_PROMPT: {
+        return AceDB::PreferenceTypes::PREFERENCE_BLANKET_PROMPT; }
+    case ACE_PREFERENCE_DEFAULT: {
+        return AceDB::PreferenceTypes::PREFERENCE_DEFAULT;}
+    case ACE_PREFERENCE_DENY: {
+        return AceDB::PreferenceTypes::PREFERENCE_DENY;}
+    case ACE_PREFERENCE_ONE_SHOT_PROMPT: {
+        return AceDB::PreferenceTypes::PREFERENCE_ONE_SHOT_PROMPT;}
+    case ACE_PREFERENCE_PERMIT: {
+        return AceDB::PreferenceTypes::PREFERENCE_PERMIT;}
+    case ACE_PREFERENCE_SESSION_PROMPT: {
+        return AceDB::PreferenceTypes::PREFERENCE_SESSION_PROMPT;}
+    default: {
+        return AceDB::PreferenceTypes::PREFERENCE_DEFAULT;}
+    }
+}
+
+ace_return_t ace_settings_initialize(void)
+{
+    AceDB::AceDAO::attachToThreadRW();
+    return ACE_OK;
+}
+
+ace_return_t ace_settings_shutdown(void)
+{
+    AceDB::AceDAO::detachFromThread();
+    return ACE_OK;
+}
+
+ace_return_t ace_get_widget_resource_preference(ace_widget_handle_t handle,
+                                                const ace_resource_t resource,
+                                                ace_preference_t* preference)
+{
+    if (NULL == resource || NULL == preference) {
+        LogError("NULL argument(s) passed");
+        return ACE_INVALID_ARGUMENTS;
+    }
+    Try {
+        std::string resource_str(resource);
+        AceDB::PreferenceTypes db_preference =
+                AceDB::AceDAO::getWidgetDevCapSetting(resource_str, handle);
+        *preference = to_ace_preference(db_preference);
+    } Catch(AceDB::AceDAOReadOnly::Exception::DatabaseError) {
+        return ACE_INTERNAL_ERROR;
+    }
+    return ACE_OK;
+}
+
+ace_return_t ace_get_global_resource_preference(const ace_resource_t resource,
+                                                ace_preference_t* preference)
+{
+    if (NULL == resource || NULL == preference) {
+        LogError("NULL argument(s) passed");
+        return ACE_INVALID_ARGUMENTS;
+    }
+    Try {
+        AceDB::PreferenceTypes db_preference =
+                AceDB::AceDAO::getDevCapSetting(resource);
+        *preference = to_ace_preference(db_preference);
+    } Catch(AceDB::AceDAOReadOnly::Exception::DatabaseError) {
+        return ACE_INTERNAL_ERROR;
+    }
+    return ACE_OK;
+}
+
+ace_return_t ace_set_widget_resource_preference(ace_widget_handle_t handle,
+                                                const ace_resource_t resource,
+                                                ace_preference_t preference)
+{
+    if (NULL == resource) {
+        LogError("NULL argument passed");
+        return ACE_INVALID_ARGUMENTS;
+    }
+    Try {
+        AceDB::AceDAO::addResource(resource);
+        AceDB::PreferenceTypes db_preference = to_ace_db_preference(preference);
+        AceDB::AceDAO::removeWidgetDevCapSetting(resource, handle);
+        AceDB::AceDAO::setWidgetDevCapSetting(resource, handle, db_preference);
+    } Catch(AceDB::AceDAO::Exception::DatabaseError) {
+        return ACE_INTERNAL_ERROR;
+    }
+    return ACE_OK;
+}
+
+ace_return_t ace_set_global_resource_preference(const ace_resource_t resource,
+                                                ace_preference_t preference)
+{
+    if (NULL == resource) {
+        LogError("NULL argument passed");
+        return ACE_INVALID_ARGUMENTS;
+    }
+    Try {
+        AceDB::AceDAO::addResource(resource);
+        AceDB::PreferenceTypes db_preference = to_ace_db_preference(preference);
+        AceDB::AceDAO::setDevCapSetting(resource, db_preference);
+    } Catch(AceDB::AceDAO::Exception::DatabaseError) {
+        return ACE_INTERNAL_ERROR;
+    }
+    return ACE_OK;
+}
+
+ace_return_t ace_reset_widget_resource_settings()
+{
+    Try {
+        AceDB::AceDAO::clearWidgetDevCapSettings();
+    } Catch(AceDB::AceDAO::Exception::DatabaseError) {
+        return ACE_INTERNAL_ERROR;
+    }
+    return ACE_OK;
+}
+
+ace_return_t ace_reset_global_resource_settings(void)
+{
+    Try {
+        AceDB::AceDAO::clearDevCapSettings();
+    } Catch(AceDB::AceDAO::Exception::DatabaseError) {
+        return ACE_INTERNAL_ERROR;
+    }
+    return ACE_OK;
+}
+
+ace_return_t ace_is_private_api(const ace_resource_t resource_name, ace_bool_t* is_private_api)
+{
+    static const char * const private_api[] = {
+        "bluetooth.admin",
+        "bluetooth.gap",
+        "bluetooth.spp",
+        "calendar.read",
+        "calendar.write",
+        "callhistory.read",
+        "callhistory.write",
+        "contact.read",
+        "contact.write",
+        "nfc.admin",
+        "nfc.common",
+        "nfc.cardemulation",
+        "nfc.p2p",
+        "nfc.tag",
+        NULL
+    };
+
+    *is_private_api = ACE_TRUE;
+    for (int i=0; private_api[i]; ++i)
+        if (!strcmp(resource_name, private_api[i]))
+            return ACE_OK;
+
+    *is_private_api = ACE_FALSE;
+    return ACE_OK;
+}
+
diff --git a/build/CMakeLists.txt b/build/CMakeLists.txt
new file mode 100644 (file)
index 0000000..35766cc
--- /dev/null
@@ -0,0 +1,27 @@
+# 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        CMakeLists.txt
+# @author      Tomasz Swierczek (t.swierczek@samsung.com)
+#
+ADD_SUBDIRECTORY(ace)
+ADD_SUBDIRECTORY(ace_client)
+ADD_SUBDIRECTORY(ace_settings)
+ADD_SUBDIRECTORY(ace_install)
+ADD_SUBDIRECTORY(ace_popup_validation)
+ADD_SUBDIRECTORY(communication_client)
+ADD_SUBDIRECTORY(wrt-security)
+IF(ENABLE_WRT_OCSP EQUAL 1)
+ADD_SUBDIRECTORY(wrt_ocsp)
+ENDIF()
diff --git a/build/ace/CMakeLists.txt b/build/ace/CMakeLists.txt
new file mode 100644 (file)
index 0000000..a6b2c58
--- /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        CMakeLists.txt
+# @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+# @author      Tomasz Swierczek (t.swierczek@samsung.com)
+# @brief
+#
+
+CONFIGURE_FILE(security-dao-ro.pc.in security-dao-ro.pc @ONLY)
+CONFIGURE_FILE(security-dao-rw.pc.in security-dao-rw.pc @ONLY)
+CONFIGURE_FILE(security.pc.in security.pc @ONLY)
+INSTALL(FILES
+    ${CMAKE_BINARY_DIR}/build/ace/security-dao-ro.pc
+    ${CMAKE_BINARY_DIR}/build/ace/security-dao-rw.pc
+    ${CMAKE_BINARY_DIR}/build/ace/security.pc
+    DESTINATION
+    ${LIB_INSTALL_DIR}/pkgconfig
+    )
+  
diff --git a/build/ace/security-dao-ro.pc.in b/build/ace/security-dao-ro.pc.in
new file mode 100644 (file)
index 0000000..98c237a
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=@CMAKE_INSTALL_PREFIX@
+exec_prefix=${prefix}
+libdir=@LIB_INSTALL_DIR@
+includedir=${prefix}/include
+
+Name: ace-dao-ro
+Description: ace-dao-ro
+Version: @VERSION@
+Requires: dpl-efl openssl
+Libs: -lace-dao-ro -L${libdir}
+Cflags: -I${includedir}
diff --git a/build/ace/security-dao-rw.pc.in b/build/ace/security-dao-rw.pc.in
new file mode 100644 (file)
index 0000000..64ff12e
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=@CMAKE_INSTALL_PREFIX@
+exec_prefix=${prefix}
+libdir=@LIB_INSTALL_DIR@
+includedir=${prefix}/include
+
+Name: aco-dao-rw
+Description: ace-dao-rw
+Version: @VERSION@
+Requires: security-dao-ro
+Libs: -lace-dao-rw -L${libdir}
+Cflags: -I${includedir}
diff --git a/build/ace/security.pc.in b/build/ace/security.pc.in
new file mode 100644 (file)
index 0000000..366066a
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=@CMAKE_INSTALL_PREFIX@
+exec_prefix=${prefix}
+libdir=@LIB_INSTALL_DIR@
+includedir=${prefix}/include
+
+Name: ace
+Description: ace
+Version: @VERSION@
+Requires: dpl-efl openssl
+Libs: -lace -L${libdir}
+Cflags: -I${includedir}
diff --git a/build/ace_client/CMakeLists.txt b/build/ace_client/CMakeLists.txt
new file mode 100644 (file)
index 0000000..8f74532
--- /dev/null
@@ -0,0 +1,26 @@
+# 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        CMakeLists.txt
+# @author      Tomasz Swierczek (t.swierczek@samsung.com)
+# @brief
+#
+
+CONFIGURE_FILE(security-client.pc.in security-client.pc @ONLY)
+INSTALL(FILES
+    ${CMAKE_BINARY_DIR}/build/ace_client/security-client.pc
+    DESTINATION
+    ${LIB_INSTALL_DIR}/pkgconfig
+    )
+  
diff --git a/build/ace_client/security-client.pc.in b/build/ace_client/security-client.pc.in
new file mode 100644 (file)
index 0000000..804dc6d
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=@CMAKE_INSTALL_PREFIX@
+exec_prefix=${prefix}
+libdir=@LIB_INSTALL_DIR@
+includedir=${prefix}/include
+
+Name: ace-client
+Description: ACE thin client library
+Version: @VERSION@
+Requires: dpl-wrt-dao-ro dpl-efl dpl-event-efl dpl-dbus-efl security-dao-ro
+Libs: -lace-client -L${libdir}
+Cflags: -I${includedir}/ace-client -I${includedir}/ace-common
diff --git a/build/ace_install/CMakeLists.txt b/build/ace_install/CMakeLists.txt
new file mode 100644 (file)
index 0000000..c9266b3
--- /dev/null
@@ -0,0 +1,26 @@
+# 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        CMakeLists.txt
+# @author      Tomasz Swierczek (t.swierczek@samsung.com)
+# @brief
+#
+
+CONFIGURE_FILE(security-install.pc.in security-install.pc @ONLY)
+INSTALL(FILES
+    ${CMAKE_BINARY_DIR}/build/ace_install/security-install.pc
+    DESTINATION
+    ${LIB_INSTALL_DIR}/pkgconfig
+    )
+  
diff --git a/build/ace_install/security-install.pc.in b/build/ace_install/security-install.pc.in
new file mode 100644 (file)
index 0000000..5c41da5
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=@CMAKE_INSTALL_PREFIX@
+exec_prefix=${prefix}
+libdir=@LIB_INSTALL_DIR@
+includedir=${prefix}/include
+
+Name: ace-install
+Description: ACE insall library to be used by installer
+Version: @VERSION@
+Requires: dpl-efl dpl-dbus-efl security-dao-rw
+Libs: -lace-install -L${libdir}
+Cflags: -I${includedir}/ace-install -I${includedir}/ace-common
diff --git a/build/ace_popup_validation/CMakeLists.txt b/build/ace_popup_validation/CMakeLists.txt
new file mode 100644 (file)
index 0000000..720ea06
--- /dev/null
@@ -0,0 +1,26 @@
+# 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        CMakeLists.txt
+# @author      Tomasz Swierczek (t.swierczek@samsung.com)
+# @brief
+#
+
+CONFIGURE_FILE(security-popup-validation.pc.in security-popup-validation.pc @ONLY)
+INSTALL(FILES
+    ${CMAKE_BINARY_DIR}/build/ace_popup_validation/security-popup-validation.pc
+    DESTINATION
+    ${LIB_INSTALL_DIR}/pkgconfig
+    )
+  
diff --git a/build/ace_popup_validation/security-popup-validation.pc.in b/build/ace_popup_validation/security-popup-validation.pc.in
new file mode 100644 (file)
index 0000000..fc1e7ab
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=@CMAKE_INSTALL_PREFIX@
+exec_prefix=${prefix}
+libdir=@LIB_INSTALL_DIR@
+includedir=${prefix}/include
+
+Name: ace-popup-validation
+Description: ACE popup validation library
+Version: @VERSION@
+Requires: dpl-efl dpl-dbus-efl
+Libs: -lace-popup-validation -L${libdir}
+Cflags: -I${includedir}/ace-popup-validation -I${includedir}/ace-common
diff --git a/build/ace_settings/CMakeLists.txt b/build/ace_settings/CMakeLists.txt
new file mode 100644 (file)
index 0000000..1830467
--- /dev/null
@@ -0,0 +1,26 @@
+# 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        CMakeLists.txt
+# @author      Tomasz Swierczek (t.swierczek@samsung.com)
+# @brief
+#
+
+CONFIGURE_FILE(security-settings.pc.in security-settings.pc @ONLY)
+INSTALL(FILES
+    ${CMAKE_BINARY_DIR}/build/ace_settings/security-settings.pc
+    DESTINATION
+    ${LIB_INSTALL_DIR}/pkgconfig
+    )
+  
diff --git a/build/ace_settings/security-settings.pc.in b/build/ace_settings/security-settings.pc.in
new file mode 100644 (file)
index 0000000..aab9f6f
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=@CMAKE_INSTALL_PREFIX@
+exec_prefix=${prefix}
+libdir=@LIB_INSTALL_DIR@
+includedir=${prefix}/include
+
+Name: ace-settings
+Description: ACE settings library
+Version: @VERSION@
+Requires:
+Libs: -lace-settings -lace-dao-rw -L${libdir}
+Cflags: -I${includedir}/ace-settings -I${includedir}/ace-common
diff --git a/build/communication_client/CMakeLists.txt b/build/communication_client/CMakeLists.txt
new file mode 100644 (file)
index 0000000..8942a30
--- /dev/null
@@ -0,0 +1,26 @@
+# Copyright (c) 2012 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      Zofia Abramowska (z.abramowska@samsung.com)
+# @brief
+#
+
+CONFIGURE_FILE(security-communication-client.pc.in security-communication-client.pc @ONLY)
+INSTALL(FILES
+    ${CMAKE_BINARY_DIR}/build/communication_client/security-communication-client.pc
+    DESTINATION
+    ${LIB_INSTALL_DIR}/pkgconfig
+    )
+
diff --git a/build/communication_client/security-communication-client.pc.in b/build/communication_client/security-communication-client.pc.in
new file mode 100644 (file)
index 0000000..b86a4a4
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=@CMAKE_INSTALL_PREFIX@
+exec_prefix=${prefix}
+libdir=@LIB_INSTALL_DIR@
+includedir=${prefix}/include
+
+Name: communication-client
+Description: Security communication client library
+Version: @VERSION@
+Requires: dpl-efl dpl-dbus-efl
+Libs: -lcommunication-client  -L${libdir}
+Cflags: -I${includedir}/communication-client
diff --git a/build/wrt-security/CMakeLists.txt b/build/wrt-security/CMakeLists.txt
new file mode 100644 (file)
index 0000000..3ac02e1
--- /dev/null
@@ -0,0 +1,19 @@
+# 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        CMakeLists.txt
+# @author      Tomasz Swierczek (t.swierczek@samsung.com)
+#
+CONFIGURE_FILE(security-core.pc.in security-core.pc @ONLY)
+INSTALL(FILES ${CMAKE_BINARY_DIR}/build/wrt-security/security-core.pc DESTINATION ${LIB_INSTALL_DIR}/pkgconfig)
diff --git a/build/wrt-security/security-core.pc.in b/build/wrt-security/security-core.pc.in
new file mode 100644 (file)
index 0000000..e99ba9e
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=@CMAKE_INSTALL_PREFIX@
+exec_prefix=${prefix}
+libdir=@LIB_INSTALL_DIR@
+includedir=${prefix}/include/wrt-security
+
+Name: wrt-security
+Description: wrt-security
+Version: @VERSION@
+Requires: dpl-efl dpl-wrt-dao-rw dpl-dbus-efl
+Libs: -L${libdir} -ldpl-dbus-efl
+Cflags: -I${includedir}
diff --git a/build/wrt_ocsp/CMakeLists.txt b/build/wrt_ocsp/CMakeLists.txt
new file mode 100644 (file)
index 0000000..ab11f72
--- /dev/null
@@ -0,0 +1,26 @@
+# 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        CMakeLists.txt
+# @author      Zofia Abramowska (z.abramowska@samsung.com)
+# @brief
+#
+
+CONFIGURE_FILE(security-wrt-ocsp.pc.in security-wrt-ocsp.pc @ONLY)
+INSTALL(FILES
+    ${CMAKE_BINARY_DIR}/build/wrt_ocsp/security-wrt-ocsp.pc
+    DESTINATION
+    ${LIB_INSTALL_DIR}/pkgconfig
+    )
+
diff --git a/build/wrt_ocsp/security-wrt-ocsp.pc.in b/build/wrt_ocsp/security-wrt-ocsp.pc.in
new file mode 100644 (file)
index 0000000..e965e8e
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=@CMAKE_INSTALL_PREFIX@
+exec_prefix=${prefix}
+libdir=@LIB_INSTALL_DIR@
+includedir=${prefix}/include
+
+Name: wrt-ocsp
+Description: WRT OCSP library to be used by wrt-client
+Version: @VERSION@
+Requires: dpl-efl dpl-dbus-efl
+Libs: -lwrt-ocsp -L${libdir}
+Cflags: -I${includedir}/wrt-ocsp
diff --git a/commons/CMakeLists.txt b/commons/CMakeLists.txt
new file mode 100644 (file)
index 0000000..a345c4e
--- /dev/null
@@ -0,0 +1,126 @@
+# 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        CMakeLists.txt
+# @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+# @version     1.0
+# @brief
+#
+
+# Check minimum CMake version
+CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
+
+# Project name
+PROJECT(wrt-security-commons)
+
+STRING(REGEX MATCH "([^.]*)" API_VERSION "${VERSION}")
+ADD_DEFINITIONS("-DAPI_VERSION=\"$(API_VERSION)\"")
+
+# Comment this to disable control of global settings with environment variable
+ADD_DEFINITIONS("-DGLOBAL_SETTINGS_CONTROL")
+
+# Build type
+IF(NOT CMAKE_BUILD_TYPE)
+    SET(CMAKE_BUILD_TYPE "Release")
+ENDIF(NOT CMAKE_BUILD_TYPE)
+
+# Options
+OPTION(DPL_LOG "DPL logs status" OFF)
+IF(DPL_LOG AND NOT CMAKE_BUILD_TYPE MATCHES "profiling")
+    MESSAGE(STATUS "Logging enabled for DPL")
+    ADD_DEFINITIONS("-DDPL_LOGS_ENABLED")
+ELSE(DPL_LOG AND NOT CMAKE_BUILD_TYPE MATCHES "profiling")
+    MESSAGE(STATUS "Logging disabled for DPL")
+ENDIF(DPL_LOG AND NOT CMAKE_BUILD_TYPE MATCHES "profiling")
+
+OPTION(WITH_TESTS "Build tests" OFF)
+OPTION(WITH_CHILD "Build additional test subdirectory. WITH_TEST must be ON" OFF)
+
+# Compiler flags
+SET(CMAKE_C_FLAGS_PROFILING    "-O2")
+SET(CMAKE_CXX_FLAGS_PROFILING  "-O2 -std=c++0x")
+SET(CMAKE_C_FLAGS_DEBUG        "-O0 -g")
+SET(CMAKE_CXX_FLAGS_DEBUG      "-O0 -std=c++0x -g")
+SET(CMAKE_C_FLAGS_RELEASE      "-O2 -g")
+SET(CMAKE_CXX_FLAGS_RELEASE    "-O2 -std=c++0x -g -fvisibility-inlines-hidden")
+SET(CMAKE_CXX_FLAGS_CCOV       "-O0 -std=c++0x -g --coverage")
+
+ADD_DEFINITIONS("-fPIC")                        # If supported for the target machine, emit position-independent code, suitable for dynamic linking and avoiding any limit on the size of the global offset table. This option makes a difference on the m68k, PowerPC and SPARC. (BJ: our ARM too?)
+
+# Compiler flags
+ADD_DEFINITIONS("-fvisibility=default")         # mark all exported symbols as visible
+
+# Warnings mode
+#ADD_DEFINITIONS("-Werror")                      # Make all warnings into errors.
+
+# Warning flags
+ADD_DEFINITIONS("-Wall")                        # Generate all warnings
+ADD_DEFINITIONS("-Wextra")                      # Generate even more extra warnings
+ADD_DEFINITIONS("-pedantic")                    # Accept only pedantic code
+#ADD_DEFINITIONS("-Weffc++")                     # Accept only effective C++ code
+ADD_DEFINITIONS("-Wwrite-strings")              # Do not accept writing to contant string memory
+ADD_DEFINITIONS("-Winit-self")                  # Do not accept initializing variable with itself
+ADD_DEFINITIONS("-Wcast-align")                 # Do not accept misaligning with casting
+ADD_DEFINITIONS("-Wcast-qual")                  # Do not accept removing qualifiers with casting
+#ADD_DEFINITIONS("-Wold-style-cast")             # Do not accept old style casting
+ADD_DEFINITIONS("-Wpointer-arith")              # Warn about void pointer arthimetic
+ADD_DEFINITIONS("-Wstrict-aliasing")            # Ensure strict aliasing
+ADD_DEFINITIONS("-Wuninitialized")              # Do not accept uninitialized variables
+ADD_DEFINITIONS("-Wmissing-declarations")       # Warn about global and non-accesible functions
+ADD_DEFINITIONS("-Woverloaded-virtual")         # Warn about incidental overiding non-virtual base methods
+ADD_DEFINITIONS("-Wnon-virtual-dtor")           # Warn about non-virtual destructor
+ADD_DEFINITIONS("-Wctor-dtor-privacy")          # Warn about useless and non-constructible classes
+#ADD_DEFINITIONS("-Wlong-long")                  # Do not allow using long long
+#ADD_DEFINITIONS("-Wunreachable-code")           # Warn about unreachable code
+ADD_DEFINITIONS("-Wfloat-equal")                # Do not accept comparing floating points with equal operator
+ADD_DEFINITIONS("-Wabi")                        # Warn about possible ABI problems
+ADD_DEFINITIONS("-Wswitch-enum")                # Check switch enumeration
+ADD_DEFINITIONS("-Wformat=2")                   # Check printf formatting
+ADD_DEFINITIONS("-Wundef")                      # Warn if an undefined identifier is evaluated in an @if directive.
+ADD_DEFINITIONS("-Wshadow")                     # Warn whenever a local variable shadows another local variable, parameter or global variable or whenever a built-in function is shadowed
+ADD_DEFINITIONS("-Wconversion")                 # Warn for implicit conversions that may alter a value
+ADD_DEFINITIONS("-Wlogical-op")                 # Warn about suspicious uses of logical operators in expressions
+#ADD_DEFINITIONS("-Waggregate-return")           # Warn if any functions that return structures or unions are defined or called.
+ADD_DEFINITIONS("-Wmissing-field-initializers") # Warn if a structure's initializer has some fields missing.
+ADD_DEFINITIONS("-Wredundant-decls")            # Warn if anything is declared more than once in the same scope, even in cases where multiple declaration is valid and changes nothing.
+#ADD_DEFINITIONS("-Wmissing-include-dirs")       # Warn if a user-supplied include directory does not exist.
+ADD_DEFINITIONS("-Wswitch-default")             # Warn whenever a switch statement does not have a default case.
+ADD_DEFINITIONS("-Wsync-nand")                  # Warn when __sync_fetch_and_nand and __sync_nand_and_fetch built-in functions are used. These functions changed semantics in GCC 4.4.
+ADD_DEFINITIONS("-Wunused")                     # All the above -Wunused options combined.
+ADD_DEFINITIONS("-Wstrict-overflow=5")          # Also warn about cases where the compiler reduces the magnitude of a constant involved in a comparison.
+ADD_DEFINITIONS("-Wdisabled-optimization")      # Warn if a requested optimization pass is disabled.
+ADD_DEFINITIONS("-std=c++0x")
+
+#
+# Core library files
+#
+# Define all core library headers and sources. As detail files
+# are usually templated and though recompiled in each file, we
+# have to compile full source for each target.
+#
+
+# Set names of binaries being created
+SET(TARGET_DPL_EFL "lib${PROJECT_NAME}")
+SET(TARGET_DPL_DB_EFL "lib${PROJECT_NAME}-db")
+SET(TARGET_DPL_LOG_EFL "lib${PROJECT_NAME}-log")
+
+macro(configure_and_install_pkg PKG_FILE)
+    CONFIGURE_FILE(${PKG_FILE}.in ${PKG_FILE} @ONLY)
+    INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/${PKG_FILE} DESTINATION lib/pkgconfig)
+endmacro(configure_and_install_pkg)
+
+ADD_SUBDIRECTORY(modules)
+ADD_SUBDIRECTORY(build)
+
diff --git a/commons/LICENSE b/commons/LICENSE
new file mode 100644 (file)
index 0000000..247c97d
--- /dev/null
@@ -0,0 +1,203 @@
+Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   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.
diff --git a/commons/NOTICE b/commons/NOTICE
new file mode 100644 (file)
index 0000000..ded3804
--- /dev/null
@@ -0,0 +1 @@
+Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
\ No newline at end of file
diff --git a/commons/build/CMakeLists.txt b/commons/build/CMakeLists.txt
new file mode 100644 (file)
index 0000000..cf24bfa
--- /dev/null
@@ -0,0 +1,23 @@
+# 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        CMakeLists.txt
+# @author      Lukasz Marek (l.marek@samsung.com)
+# @version     1.0
+# @brief
+#
+MESSAGE("*****************************************compiling for commons*********************************")
+ADD_SUBDIRECTORY(core)
+ADD_SUBDIRECTORY(log)
+ADD_SUBDIRECTORY(db)
diff --git a/commons/build/core/CMakeLists.txt b/commons/build/core/CMakeLists.txt
new file mode 100644 (file)
index 0000000..fa78765
--- /dev/null
@@ -0,0 +1,65 @@
+# 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        CMakeLists.txt
+# @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+# @version     1.0
+# @brief
+#
+
+# Check required modules
+INCLUDE(FindPkgConfig)
+PKG_CHECK_MODULES(SYS_EFL
+  icu-uc
+  openssl
+  dlog
+#  minizip
+  REQUIRED
+)
+
+# Add core include directories
+INCLUDE_DIRECTORIES(
+    ${DPL_LOG_INCLUDE_DIR}
+    ${DPL_CORE_INCLUDE_DIR}
+)
+
+INCLUDE_DIRECTORIES(SYSTEM ${SYS_EFL_INCLUDE_DIRS})
+
+LINK_DIRECTORIES(${SYS_EFL_LIBRARY_DIRS})
+
+# Base EFL based DPL library
+SET(DPL_EFL_LIBRARY "${PROJECT_NAME}")
+
+# Build shared library
+ADD_LIBRARY(${TARGET_DPL_EFL} SHARED
+    ${DPL_CORE_SOURCES}
+    ${DPL_LOG_SOURCES}
+)
+
+TARGET_LINK_LIBRARIES(${TARGET_DPL_EFL} ${SYS_EFL_LIBRARIES} "-lrt")
+
+# Target library properties
+SET_TARGET_PROPERTIES(${TARGET_DPL_EFL} PROPERTIES
+    SOVERSION ${API_VERSION} 
+ VERSION ${VERSION}
+    CLEAN_DIRECT_OUTPUT 1
+    OUTPUT_NAME ${DPL_EFL_LIBRARY})
+
+# Install libraries
+INSTALL(TARGETS ${TARGET_DPL_EFL}
+        DESTINATION ${LIB_INSTALL_DIR})
+
+
+# Install pkgconfig script
+configure_and_install_pkg(wrt-security-commons.pc)
diff --git a/commons/build/core/DESCRIPTION b/commons/build/core/DESCRIPTION
new file mode 100644 (file)
index 0000000..f7f1581
--- /dev/null
@@ -0,0 +1,2 @@
+!!!options!!! stop
+EFL support
diff --git a/commons/build/core/wrt-security-commons.pc.in b/commons/build/core/wrt-security-commons.pc.in
new file mode 100644 (file)
index 0000000..d3a7eba
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=/usr
+exec_prefix=${prefix}
+libdir=${prefix}/lib
+includedir=${prefix}/include
+
+Name: wrt-security-commons
+Description: wrt-security-commons library
+Version: @VERSION@
+Requires: openssl dlog 
+Libs: -L${libdir} -lwrt-security-commons
+Cflags: -I${includedir}/wrt-security-commons
diff --git a/commons/build/db/CMakeLists.txt b/commons/build/db/CMakeLists.txt
new file mode 100644 (file)
index 0000000..40f3e38
--- /dev/null
@@ -0,0 +1,67 @@
+# 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        CMakeLists.txt
+# @author      Lukasz Marek (l.marek@samsung.com)
+# @version     1.0
+# @brief
+#
+
+# Check required modules
+INCLUDE(FindPkgConfig)
+PKG_CHECK_MODULES(SYS_EFL_DB
+    sqlite3
+    db-util
+    REQUIRED)
+
+# Add core include directories
+INCLUDE_DIRECTORIES(
+    ${DPL_LOG_INCLUDE_DIR}
+    ${DPL_CORE_INCLUDE_DIR}
+    ${DPL_DB_INCLUDE_DIR}
+)
+
+INCLUDE_DIRECTORIES(SYSTEM ${SYS_EFL_INCLUDE_DIRS})
+INCLUDE_DIRECTORIES(SYSTEM ${SYS_EFL_DB_INCLUDE_DIRS})
+
+LINK_DIRECTORIES(
+    ${SYS_EFL_DB_LIBRARY_DIRS}
+)
+
+# Base EFL based DPL library
+SET(DPL_EFL_DB_LIBRARY "${PROJECT_NAME}-db")
+
+# Build shared library
+
+ADD_LIBRARY(${TARGET_DPL_DB_EFL} SHARED  ${DPL_DB_SOURCES})
+
+TARGET_LINK_LIBRARIES(${TARGET_DPL_DB_EFL}
+    ${SYS_EFL_DB_LIBRARIES}
+    ${TARGET_DPL_EFL}
+)
+
+# Target library properties
+SET_TARGET_PROPERTIES(${TARGET_DPL_DB_EFL} PROPERTIES
+    SOVERSION ${API_VERSION}
+    VERSION ${VERSION}
+    CLEAN_DIRECT_OUTPUT 1
+    OUTPUT_NAME ${DPL_EFL_DB_LIBRARY})
+
+# Install libraries
+INSTALL(TARGETS ${TARGET_DPL_DB_EFL}
+        DESTINATION ${LIB_INSTALL_DIR})
+#        DESTINATION lib)
+
+# Install pkgconfig script
+configure_and_install_pkg(wrt-security-commons-db.pc)
diff --git a/commons/build/db/wrt-security-commons-db.pc.in b/commons/build/db/wrt-security-commons-db.pc.in
new file mode 100644 (file)
index 0000000..5b0b8ee
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=/usr
+exec_prefix=${prefix}
+libdir=${prefix}/lib
+includedir=${prefix}/include
+
+Name: wrt-security-commons-db
+Description: wrt security common library
+Version: @VERSION@
+Requires: wrt-security-commons sqlite3 db-util
+Libs: -L${libdir} -lwrt-security-commons
+Cflags: -I${includedir}/wrt-security-commons
diff --git a/commons/build/log/CMakeLists.txt b/commons/build/log/CMakeLists.txt
new file mode 100644 (file)
index 0000000..148f66e
--- /dev/null
@@ -0,0 +1,63 @@
+# 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        CMakeLists.txt
+# @author      Lukasz Marek (l.marek@samsung.com)
+# @version     1.0
+# @brief
+#
+
+# Check required modules
+INCLUDE(FindPkgConfig)
+PKG_CHECK_MODULES(SYS_EFL_LOG
+    dlog
+    REQUIRED
+)
+
+# Add core include directories
+INCLUDE_DIRECTORIES(
+    ${DPL_LOG_INCLUDE_DIR}
+)
+
+INCLUDE_DIRECTORIES(SYSTEM ${SYS_EFL_LOG_INCLUDE_DIRS})
+
+LINK_DIRECTORIES(
+    ${SYS_EFL_LOG_LIBRARY_DIRS}
+)
+
+# Base EFL based DPL library
+SET(DPL_EFL_LOG_LIBRARY "${PROJECT_NAME}-log")
+
+# Build shared library
+
+ADD_LIBRARY(${TARGET_DPL_LOG_EFL} SHARED  ${DPL_LOG_SOURCES})
+
+TARGET_LINK_LIBRARIES(${TARGET_DPL_LOG_EFL}
+    ${SYS_EFL_LOG_LIBRARIES}
+)
+
+# Target library properties
+SET_TARGET_PROPERTIES(${TARGET_DPL_LOG_EFL} PROPERTIES
+    SOVERSION ${API_VERSION}
+    VERSION ${VERSION}
+    CLEAN_DIRECT_OUTPUT 1
+    OUTPUT_NAME ${DPL_EFL_LOG_LIBRARY})
+
+# Install libraries
+INSTALL(TARGETS ${TARGET_DPL_LOG_EFL}
+        DESTINATION ${LIB_INSTALL_DIR})
+#        DESTINATION lib)
+
+# Install pkgconfig script
+configure_and_install_pkg(wrt-security-commons-log.pc)
diff --git a/commons/build/log/wrt-security-commons-log.pc.in b/commons/build/log/wrt-security-commons-log.pc.in
new file mode 100644 (file)
index 0000000..7f18689
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=/usr
+exec_prefix=${prefix}
+libdir=${prefix}/lib
+includedir=${prefix}/include
+
+Name: dpl-log-efl
+Description: DPL Log Engine - EFL based
+Version: @VERSION@
+Requires: dpl-efl dlog
+Libs: -L${libdir} -ldpl-log-efl
+Cflags: -I${includedir}/dpl-efl
diff --git a/commons/modules/CMakeLists.txt b/commons/modules/CMakeLists.txt
new file mode 100644 (file)
index 0000000..4ee8728
--- /dev/null
@@ -0,0 +1,24 @@
+# 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        CMakeLists.txt
+# @author      Lukasz Marek (l.marek@samsung.com)
+# @version     1.0
+# @brief
+#
+
+include(core/config.cmake)
+include(log/config.cmake)
+include(db/config.cmake)
diff --git a/commons/modules/core/DESCRIPTION b/commons/modules/core/DESCRIPTION
new file mode 100644 (file)
index 0000000..1369c40
--- /dev/null
@@ -0,0 +1 @@
+Main library code
diff --git a/commons/modules/core/config.cmake b/commons/modules/core/config.cmake
new file mode 100644 (file)
index 0000000..038f3b7
--- /dev/null
@@ -0,0 +1,122 @@
+# 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        config.cmake
+# @author      Lukasz Marek (l.marek@samsung.com)
+# @version     1.0
+# @brief
+#
+
+# Set DPL core sources
+SET(DPL_CORE_SOURCES
+    ${PROJECT_SOURCE_DIR}/modules/core/src/assert.cpp
+    ${PROJECT_SOURCE_DIR}/modules/core/src/colors.cpp
+    ${PROJECT_SOURCE_DIR}/modules/core/src/errno_string.cpp
+    ${PROJECT_SOURCE_DIR}/modules/core/src/exception.cpp
+    ${PROJECT_SOURCE_DIR}/modules/core/src/mutex.cpp
+    ${PROJECT_SOURCE_DIR}/modules/core/src/noncopyable.cpp
+    ${PROJECT_SOURCE_DIR}/modules/core/src/recursive_mutex.cpp
+    ${PROJECT_SOURCE_DIR}/modules/core/src/serialization.cpp
+    ${PROJECT_SOURCE_DIR}/modules/core/src/single_instance.cpp
+    ${PROJECT_SOURCE_DIR}/modules/core/src/singleton.cpp
+    ${PROJECT_SOURCE_DIR}/modules/core/src/string.cpp
+    ${PROJECT_SOURCE_DIR}/modules/core/src/thread.cpp
+    ${PROJECT_SOURCE_DIR}/modules/core/src/waitable_event.cpp
+    ${PROJECT_SOURCE_DIR}/modules/core/src/waitable_handle.cpp
+    ${PROJECT_SOURCE_DIR}/modules/core/src/waitable_handle_watch_support.cpp
+    PARENT_SCOPE
+)
+
+
+# Set DPL core headers
+SET(DPL_CORE_HEADERS
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/abstract_input.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/abstract_input_output.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/abstract_output.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/abstract_waitable_input_adapter.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/abstract_waitable_input.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/abstract_waitable_input_output_adapter.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/abstract_waitable_input_output.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/abstract_waitable_output_adapter.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/abstract_waitable_output.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/address.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/aligned.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/apply.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/assert.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/atomic.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/availability.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/binary_queue.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/bind.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/bool_operator.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/char_traits.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/colors.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/copy.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/errno_string.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/exception.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/file_input.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/file_output.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/foreach.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/free_deleter.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/generic_event.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/lexical_cast.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/mutable_task_list.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/mutex.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/named_base_pipe.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/named_input_pipe.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/named_output_pipe.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/noncopyable.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/once.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/optional_typedefs.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/platform.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/preprocessor.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/read_write_mutex.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/recursive_mutex.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/scope_guard.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/scoped_resource.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/scoped_close.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/scoped_dir.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/scoped_fclose.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/scoped_free.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/serialization.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/semaphore.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/single_instance.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/singleton.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/singleton_impl.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/singleton_safe_impl.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/static_block.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/string.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/sstream.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/task.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/thread.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/type_list.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/union_cast.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/workaround.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/zip_input.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/application.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/framework_appcore.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/framework_efl.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/framework_vconf.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/main.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/waitable_event.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/waitable_handle.h
+    ${PROJECT_SOURCE_DIR}/modules/core/include/dpl/waitable_handle_watch_support.h
+    PARENT_SCOPE
+)
+
+SET(DPL_CORE_INCLUDE_DIR
+    ${PROJECT_SOURCE_DIR}/modules/core/include
+    PARENT_SCOPE
+)
+
diff --git a/commons/modules/core/include/DESCRIPTION b/commons/modules/core/include/DESCRIPTION
new file mode 100644 (file)
index 0000000..6dfd446
--- /dev/null
@@ -0,0 +1,2 @@
+!!!options!!! stop
+Header files, including template implementations
diff --git a/commons/modules/core/include/dpl/assert.h b/commons/modules/core/include/dpl/assert.h
new file mode 100644 (file)
index 0000000..abdb481
--- /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        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 DPL {
+// 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 DPL
+
+#define Assert(Condition) do { if (!(Condition)) { DPL::AssertProc(#Condition, \
+                                                                   __FILE__, \
+                                                                   __LINE__, \
+                                                                   __FUNCTION__); \
+                               } } while (0)
+
+#define AssertMsg(Condition, Msg)                                         \
+    do {                                                                  \
+        if (!(Condition)) {                                               \
+            DPL::AssertProc(                                              \
+                (std::string(std::string(#Condition)+" ") + Msg).c_str(), \
+                __FILE__, __LINE__, __FUNCTION__);                        \
+        }                                                                 \
+    } while (0)
+
+#endif // DPL_ASSERT_H
diff --git a/commons/modules/core/include/dpl/availability.h b/commons/modules/core/include/dpl/availability.h
new file mode 100644 (file)
index 0000000..0813892
--- /dev/null
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2013 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        availability.h
+ * @author      Jihoon Chung (jihoon.chung@samsung.com)
+ * @version     1.0
+ */
+#ifndef DPL_AVAILABILITY_H
+#define DPL_AVAILABILITY_H
+
+#define DPL_DEPRECATED __attribute__((deprecated))
+#define DPL_DEPRECATED_WITH_MESSAGE(msg) __attribute__((deprecated(msg)))
+
+#define DPL_UNUSED __attribute__((unused))
+#define DPL_UNUSED_PARAM(variable) (void)variable
+
+#endif // DPL_AVAILABILITY_H
diff --git a/commons/modules/core/include/dpl/char_traits.h b/commons/modules/core/include/dpl/char_traits.h
new file mode 100644 (file)
index 0000000..eb2988f
--- /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        char_traits.h
+ * @author      Piotr Marcinkiewicz (p.marcinkiew@samsung.com)
+ * @version     1.0
+ * @brief       Char traits are used to create basic_string extended with
+ * additional features
+ *              Current char traits could be extended in feature to boost
+ * performance
+ */
+#ifndef DPL_CHAR_TRAITS
+#define DPL_CHAR_TRAITS
+
+#include <cstring>
+#include <string>
+#include <ostream>
+#include <algorithm>
+#include <dpl/exception.h>
+
+namespace DPL {
+typedef std::char_traits<wchar_t> CharTraits;
+} // namespace DPL
+
+#endif // DPL_CHAR_TRAITS
diff --git a/commons/modules/core/include/dpl/colors.h b/commons/modules/core/include/dpl/colors.h
new file mode 100644 (file)
index 0000000..c7cfd53
--- /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 DPL {
+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 DPL
+
+#endif /* DPL_COLORS_H */
diff --git a/commons/modules/core/include/dpl/errno_string.h b/commons/modules/core/include/dpl/errno_string.h
new file mode 100644 (file)
index 0000000..446dbc9
--- /dev/null
@@ -0,0 +1,35 @@
+/*
+ * 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        errno_string.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of errno string
+ */
+#ifndef DPL_ERRNO_STRING_H
+#define DPL_ERRNO_STRING_H
+
+#include <dpl/exception.h>
+#include <string>
+#include <cerrno>
+
+namespace DPL {
+DECLARE_EXCEPTION_TYPE(DPL::Exception, InvalidErrnoValue)
+
+std::string GetErrnoString(int error = errno);
+} // namespace DPL
+
+#endif // DPL_ERRNO_STRING_H
diff --git a/commons/modules/core/include/dpl/exception.h b/commons/modules/core/include/dpl/exception.h
new file mode 100644 (file)
index 0000000..cdbdc53
--- /dev/null
@@ -0,0 +1,385 @@
+/*
+ * 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 DPL_EXCEPTION_H
+#define DPL_EXCEPTION_H
+
+#include <string>
+#include <cstring>
+#include <cstdio>
+#include <exception>
+#include <cstdlib>
+#include <sstream>
+
+namespace DPL {
+void LogUnhandledException(const std::string &str);
+void LogUnhandledException(const std::string &str,
+                           const char *filename,
+                           int line,
+                           const char *function);
+}
+
+namespace DPL {
+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 DPL
+
+#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 DPL::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 DPL::Exception &exception)                                                               \
+    {                                                                                                     \
+        std::ostringstream msg;                                                                           \
+        msg << DPL::Exception::KnownExceptionToString(exception);                                         \
+        DPL::LogUnhandledException(msg.str(), __FILE__, __LINE__, __FUNCTION__);                          \
+        abort();                                                                                          \
+    }                                                                                                     \
+    catch (std::exception& e)                                                                             \
+    {                                                                                                     \
+        std::ostringstream msg;                                                                           \
+        msg << e.what();                                                                                  \
+        msg << "\n";                                                                                      \
+        msg << DPL::Exception::UnknownExceptionToString();                                                \
+        DPL::LogUnhandledException(msg.str(), __FILE__, __LINE__, __FUNCTION__);                          \
+        abort();                                                                                          \
+    }                                                                                                     \
+    catch (...)                                                                                           \
+    {                                                                                                     \
+        std::ostringstream msg;                                                                           \
+        msg << DPL::Exception::UnknownExceptionToString();                                                \
+        DPL::LogUnhandledException(msg.str(), __FILE__, __LINE__, __FUNCTION__);                          \
+        abort();                                                                                          \
+    }
+
+namespace DPL {
+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 // DPL_EXCEPTION_H
diff --git a/commons/modules/core/include/dpl/foreach.h b/commons/modules/core/include/dpl/foreach.h
new file mode 100644 (file)
index 0000000..bbe477a
--- /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.
+ */
+/*
+ * @file        foreach.h
+ * @author      Bartosz Janiak (b.janiak@samsung.com)
+ * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of foreach macro for stl
+ * containers
+ */
+#ifndef DPL_FOREACH_H
+#define DPL_FOREACH_H
+
+#include <dpl/preprocessor.h>
+
+namespace DPL {
+namespace Private {
+/*
+ * Used to detect type of valid reference to value object.
+ */
+template <typename T>
+T& ValueReference(T& t)
+{
+    return(t);
+}
+
+template <typename T>
+const T& ValueReference(const T& t)
+{
+    return(t);
+}
+} //Private
+} //DPL
+
+#define DPL_FOREACH_IMPL(temporaryName, iterator, container)            \
+    __typeof__ (DPL::Private::ValueReference((container))) &            \
+    temporaryName = (container);                                        \
+    for (__typeof__ (temporaryName.begin())iterator =                  \
+             temporaryName.begin();                                     \
+         (iterator) != temporaryName.end(); ++iterator)
+
+#define FOREACH(iterator, container)                                    \
+    DPL_FOREACH_IMPL(                                                   \
+        DPL_MACRO_CONCAT(foreachContainerReference, __COUNTER__),       \
+        iterator,                                      \
+        container)
+
+#endif // DPL_FOREACH_H
diff --git a/commons/modules/core/include/dpl/free_deleter.h b/commons/modules/core/include/dpl/free_deleter.h
new file mode 100644 (file)
index 0000000..4a09904
--- /dev/null
@@ -0,0 +1,33 @@
+/*
+ * Copyright (c) 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        free_deleter.h
+ * @author      Pawel Czajkowski (p.czajkowski@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file deleter with use std::free()
+ */
+#ifndef FREE_DELETER_H
+#define FREE_DELETER_H
+
+#include <cstdlib>
+namespace DPL
+{
+struct free_deleter
+{
+    void operator()(void *p) { std::free(p); }
+};
+}// DPL
+#endif // FREE_DELETER_H
diff --git a/commons/modules/core/include/dpl/generic_event.h b/commons/modules/core/include/dpl/generic_event.h
new file mode 100644 (file)
index 0000000..b20d913
--- /dev/null
@@ -0,0 +1,639 @@
+/*
+ * 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        generic_event.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of MVC generic event
+ */
+#ifndef DPL_GENERIC_EVENT_H
+#define DPL_GENERIC_EVENT_H
+
+namespace DPL {
+class EventSender
+{
+  public:
+    explicit EventSender(void *sender) :
+        m_sender(sender)
+    {}
+
+    void* GetSender() const
+    {
+        return m_sender;
+    }
+
+  private:
+    void *m_sender;
+};
+
+class GenericEvent
+{
+  protected:
+    void *m_sender;
+
+  public:
+    explicit GenericEvent(const EventSender &sender) :
+        m_sender(sender.GetSender())
+    {}
+
+    virtual ~GenericEvent()
+    {}
+
+    void *GetSender() const
+    {
+        return m_sender;
+    }
+};
+
+class GenericEvent0 :
+    public GenericEvent
+{
+  public:
+    explicit GenericEvent0(const EventSender &sender) :
+        GenericEvent(sender)
+    {}
+
+    virtual ~GenericEvent0()
+    {}
+};
+
+template<typename Arg0Type>
+class GenericEvent1 :
+    public GenericEvent0
+{
+  public:
+    typedef Arg0Type Arg0;
+
+  protected:
+    Arg0 m_arg0;
+
+  public:
+    explicit GenericEvent1(const EventSender &sender) :
+        GenericEvent0(sender)
+    {}
+
+    GenericEvent1(Arg0 arg0, const EventSender &sender) :
+        GenericEvent0(sender),
+        m_arg0(arg0)
+    {}
+
+    virtual ~GenericEvent1()
+    {}
+
+    Arg0 GetArg0() const
+    {
+        return m_arg0;
+    }
+};
+
+template<typename Arg0Type, typename Arg1Type>
+class GenericEvent2 :
+    public GenericEvent1<Arg0Type>
+{
+  public:
+    typedef Arg0Type Arg0;
+    typedef Arg1Type Arg1;
+
+  protected:
+    Arg1 m_arg1;
+
+  public:
+    explicit GenericEvent2(const EventSender &sender) :
+        GenericEvent1<Arg0Type>(sender)
+    {}
+
+    GenericEvent2(Arg0 arg0, Arg1 arg1, const EventSender &sender) :
+        GenericEvent1<Arg0Type>(arg0, sender),
+        m_arg1(arg1)
+    {}
+
+    virtual ~GenericEvent2()
+    {}
+
+    Arg1 GetArg1() const
+    {
+        return m_arg1;
+    }
+};
+
+template<typename Arg0Type, typename Arg1Type, typename Arg2Type>
+class GenericEvent3 :
+    public GenericEvent2<Arg0Type, Arg1Type>
+{
+  public:
+    typedef Arg0Type Arg0;
+    typedef Arg1Type Arg1;
+    typedef Arg2Type Arg2;
+
+  protected:
+    Arg2 m_arg2;
+
+  public:
+    explicit GenericEvent3(const EventSender &sender) :
+        GenericEvent2<Arg0Type, Arg1Type>(sender)
+    {}
+
+    GenericEvent3(Arg0 arg0, Arg1 arg1, Arg2 arg2, const EventSender &sender) :
+        GenericEvent2<Arg0Type, Arg1Type>(arg0, arg1, sender),
+        m_arg2(arg2)
+    {}
+
+    virtual ~GenericEvent3()
+    {}
+
+    Arg2 GetArg2() const
+    {
+        return m_arg2;
+    }
+};
+
+template<typename Arg0Type, typename Arg1Type, typename Arg2Type,
+         typename Arg3Type>
+class GenericEvent4 :
+    public GenericEvent3<Arg0Type, Arg1Type, Arg2Type>
+{
+  public:
+    typedef Arg0Type Arg0;
+    typedef Arg1Type Arg1;
+    typedef Arg2Type Arg2;
+    typedef Arg3Type Arg3;
+
+  protected:
+    Arg3 m_arg3;
+
+  public:
+    explicit GenericEvent4(const EventSender &sender) :
+        GenericEvent3<Arg0Type, Arg1Type, Arg2Type>(sender)
+    {}
+
+    GenericEvent4(Arg0 arg0,
+                  Arg1 arg1,
+                  Arg2 arg2,
+                  Arg3 arg3,
+                  const EventSender &sender) :
+        GenericEvent3<Arg0Type, Arg1Type, Arg2Type>(arg0, arg1, arg2, sender),
+        m_arg3(arg3)
+    {}
+
+    virtual ~GenericEvent4()
+    {}
+
+    Arg3 GetArg3() const
+    {
+        return m_arg3;
+    }
+};
+
+template<typename Arg0Type, typename Arg1Type, typename Arg2Type,
+         typename Arg3Type, typename Arg4Type>
+class GenericEvent5 :
+    public GenericEvent4<Arg0Type, Arg1Type, Arg2Type, Arg3Type>
+{
+  public:
+    typedef Arg0Type Arg0;
+    typedef Arg1Type Arg1;
+    typedef Arg2Type Arg2;
+    typedef Arg3Type Arg3;
+    typedef Arg4Type Arg4;
+
+  protected:
+    Arg4 m_arg4;
+
+  public:
+    explicit GenericEvent5(const EventSender &sender) :
+        GenericEvent4<Arg0Type, Arg1Type, Arg2Type, Arg3Type>(sender)
+    {}
+
+    GenericEvent5(Arg0 arg0,
+                  Arg1 arg1,
+                  Arg2 arg2,
+                  Arg3 arg3,
+                  Arg4 arg4,
+                  const EventSender &sender) :
+        GenericEvent4<Arg0Type, Arg1Type, Arg2Type, Arg3Type>(arg0, arg1, arg2,
+                                                              arg3, sender),
+        m_arg4(arg4)
+    {}
+
+    virtual ~GenericEvent5()
+    {}
+
+    Arg4 GetArg4() const
+    {
+        return m_arg4;
+    }
+};
+
+template<typename Arg0Type, typename Arg1Type, typename Arg2Type,
+         typename Arg3Type, typename Arg4Type, typename Arg5Type>
+class GenericEvent6 :
+    public GenericEvent5<Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type>
+{
+  public:
+    typedef Arg0Type Arg0;
+    typedef Arg1Type Arg1;
+    typedef Arg2Type Arg2;
+    typedef Arg3Type Arg3;
+    typedef Arg4Type Arg4;
+    typedef Arg5Type Arg5;
+
+  protected:
+    Arg5 m_arg5;
+
+  public:
+    explicit GenericEvent6(const EventSender &sender) :
+        GenericEvent5<Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type>(sender)
+    {}
+
+    GenericEvent6(Arg0 arg0,
+                  Arg1 arg1,
+                  Arg2 arg2,
+                  Arg3 arg3,
+                  Arg4 arg4,
+                  Arg5 arg5,
+                  const EventSender &sender) :
+        GenericEvent5<Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type>(arg0,
+                                                                        arg1,
+                                                                        arg2,
+                                                                        arg3,
+                                                                        arg4,
+                                                                        sender),
+        m_arg5(arg5)
+    {}
+
+    virtual ~GenericEvent6()
+    {}
+
+    Arg5 GetArg5() const
+    {
+        return m_arg5;
+    }
+};
+
+template<typename Arg0Type, typename Arg1Type, typename Arg2Type,
+         typename Arg3Type, typename Arg4Type, typename Arg5Type,
+         typename Arg6Type>
+class GenericEvent7 :
+    public GenericEvent6<Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type,
+                         Arg5Type>
+{
+  public:
+    typedef Arg0Type Arg0;
+    typedef Arg1Type Arg1;
+    typedef Arg2Type Arg2;
+    typedef Arg3Type Arg3;
+    typedef Arg4Type Arg4;
+    typedef Arg5Type Arg5;
+    typedef Arg6Type Arg6;
+
+  protected:
+    Arg6 m_arg6;
+
+  public:
+    explicit GenericEvent7(const EventSender &sender) :
+        GenericEvent6<Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type,
+                      Arg5Type>(sender)
+    {}
+
+    GenericEvent7(Arg0 arg0,
+                  Arg1 arg1,
+                  Arg2 arg2,
+                  Arg3 arg3,
+                  Arg4 arg4,
+                  Arg5 arg5,
+                  Arg6 arg6,
+                  const EventSender &sender) :
+        GenericEvent6<Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type,
+                      Arg5Type>(arg0, arg1, arg2, arg3, arg4, arg5, sender),
+        m_arg6(arg6)
+    {}
+
+    virtual ~GenericEvent7()
+    {}
+
+    Arg6 GetArg6() const
+    {
+        return m_arg6;
+    }
+};
+
+template<typename Arg0Type, typename Arg1Type, typename Arg2Type,
+         typename Arg3Type, typename Arg4Type, typename Arg5Type,
+         typename Arg6Type,
+         typename Arg7Type>
+class GenericEvent8 :
+    public GenericEvent7<Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type,
+                         Arg5Type, Arg6Type>
+{
+  public:
+    typedef Arg0Type Arg0;
+    typedef Arg1Type Arg1;
+    typedef Arg2Type Arg2;
+    typedef Arg3Type Arg3;
+    typedef Arg4Type Arg4;
+    typedef Arg5Type Arg5;
+    typedef Arg6Type Arg6;
+    typedef Arg7Type Arg7;
+
+  protected:
+    Arg7 m_arg7;
+
+  public:
+    explicit GenericEvent8(const EventSender &sender) :
+        GenericEvent7<Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type,
+                      Arg5Type, Arg6Type>(sender)
+    {}
+
+    GenericEvent8(Arg0 arg0,
+                  Arg1 arg1,
+                  Arg2 arg2,
+                  Arg3 arg3,
+                  Arg4 arg4,
+                  Arg5 arg5,
+                  Arg6 arg6,
+                  Arg7 arg7,
+                  const EventSender &sender) :
+        GenericEvent7<Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type,
+                      Arg5Type, Arg6Type>(arg0, arg1, arg2, arg3, arg4, arg5,
+                                          arg6, sender),
+        m_arg7(arg7)
+    {}
+
+    virtual ~GenericEvent8()
+    {}
+
+    Arg7 GetArg7() const
+    {
+        return m_arg7;
+    }
+};
+} // namespace DPL
+
+#define DECLARE_GENERIC_EVENT_0(ClassName)                                  \
+    class ClassName :                                                                   \
+        public DPL::GenericEvent0                                         \
+    {                                                                       \
+      public:                                                                 \
+        explicit ClassName(const DPL::EventSender & sender = \
+                               DPL::EventSender(NULL)) :                                                                       \
+            DPL::GenericEvent0(sender)                                    \
+        {                                                                   \
+        }                                                                   \
+    };
+
+#define DECLARE_GENERIC_EVENT_1(ClassName, Arg0Type)                          \
+    class ClassName :                                                                     \
+        public DPL::GenericEvent1<Arg0Type>                                 \
+    {                                                                         \
+      public:                                                                   \
+        explicit ClassName(const DPL::EventSender & sender = \
+                               DPL::EventSender(NULL)) :                                                                       \
+            DPL::GenericEvent1<Arg0Type>(sender)                            \
+        {                                                                     \
+        }                                                                     \
+                                                                              \
+        explicit ClassName(Arg0Type arg0,                                     \
+                           const DPL::EventSender & sender = \
+                               DPL::EventSender(NULL)) :                                                                 \
+            DPL::GenericEvent1<Arg0Type>(arg0, sender)                      \
+        {                                                                     \
+        }                                                                     \
+    };
+
+#define DECLARE_GENERIC_EVENT_2(ClassName, Arg0Type, Arg1Type)                \
+    class ClassName :                                                                     \
+        public DPL::GenericEvent2<Arg0Type, Arg1Type>                       \
+    {                                                                         \
+      public:                                                                   \
+        explicit ClassName(const DPL::EventSender & sender = \
+                               DPL::EventSender(NULL)) :                                                                       \
+            DPL::GenericEvent2<Arg0Type, Arg1Type>(sender)                  \
+        {                                                                     \
+        }                                                                     \
+                                                                              \
+        ClassName(Arg0Type arg0, Arg1Type arg1,                               \
+                  const DPL::EventSender & sender = DPL::EventSender(NULL)) :                                                                 \
+            DPL::GenericEvent2<Arg0Type, Arg1Type>(arg0, arg1, sender)      \
+        {                                                                     \
+        }                                                                     \
+    };
+
+#define DECLARE_GENERIC_EVENT_3(ClassName, Arg0Type, Arg1Type, Arg2Type)                      \
+    class ClassName :                                                                                     \
+        public DPL::GenericEvent3<Arg0Type, Arg1Type, Arg2Type>                             \
+    {                                                                                         \
+      public:                                                                                   \
+        explicit ClassName(const DPL::EventSender & sender = \
+                               DPL::EventSender(NULL)) :                                                                                 \
+            DPL::GenericEvent3<Arg0Type, Arg1Type, Arg2Type>(sender)                        \
+        {                                                                                     \
+        }                                                                                     \
+                                                                                              \
+        ClassName(Arg0Type arg0, Arg1Type arg1, Arg2Type arg2,                                \
+                  const DPL::EventSender & sender = DPL::EventSender(NULL)) :                                                                                 \
+            DPL::GenericEvent3<Arg0Type, Arg1Type, Arg2Type>(arg0, \
+                                                             arg1, \
+                                                             arg2, \
+                                                             sender)      \
+        {                                                                                     \
+        }                                                                                     \
+    };
+
+#define DECLARE_GENERIC_EVENT_4(ClassName, \
+                                Arg0Type, \
+                                Arg1Type, \
+                                Arg2Type, \
+                                Arg3Type)                            \
+    class ClassName :                                                                                                     \
+        public DPL::GenericEvent4<Arg0Type, Arg1Type, Arg2Type, Arg3Type>                                   \
+    {                                                                                                         \
+      public:                                                                                                   \
+        explicit ClassName(const DPL::EventSender & sender = \
+                               DPL::EventSender(NULL)) :                                                                                                 \
+            DPL::GenericEvent4<Arg0Type, Arg1Type, Arg2Type, Arg3Type>(sender)                              \
+        {                                                                                                     \
+        }                                                                                                     \
+                                                                                                              \
+        ClassName(Arg0Type arg0, Arg1Type arg1, Arg2Type arg2, Arg3Type arg3,                                 \
+                  const DPL::EventSender & sender = DPL::EventSender(NULL)) :                                                                                                 \
+            DPL::GenericEvent4<Arg0Type, Arg1Type, Arg2Type, Arg3Type>(arg0, \
+                                                                       arg1, \
+                                                                       arg2, \
+                                                                       arg3, \
+                                                                       sender)      \
+        {                                                                                                     \
+        }                                                                                                     \
+    };
+
+#define DECLARE_GENERIC_EVENT_5(ClassName, \
+                                Arg0Type, \
+                                Arg1Type, \
+                                Arg2Type, \
+                                Arg3Type, \
+                                Arg4Type)                                  \
+    class ClassName :                                                                                                                     \
+        public DPL::GenericEvent5<Arg0Type, Arg1Type, Arg2Type, Arg3Type, \
+                                  Arg4Type>                                         \
+    {                                                                                                                         \
+      public:                                                                                                                   \
+        explicit ClassName(const DPL::EventSender & sender = \
+                               DPL::EventSender(NULL)) :                                                                                                                 \
+            DPL::GenericEvent5<Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type>( \
+                sender)                                    \
+        {                                                                                                                     \
+        }                                                                                                                     \
+                                                                                                                              \
+        ClassName(Arg0Type arg0, \
+                  Arg1Type arg1, \
+                  Arg2Type arg2, \
+                  Arg3Type arg3, \
+                  Arg4Type arg4,                                  \
+                  const DPL::EventSender & sender = DPL::EventSender(NULL)) :                                                                                                                 \
+            DPL::GenericEvent5<Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type>( \
+                arg0, \
+                arg1, \
+                arg2, \
+                arg3, \
+                arg4, \
+                sender)      \
+        {                                                                                                                     \
+        }                                                                                                                     \
+    };
+
+#define DECLARE_GENERIC_EVENT_6(ClassName, \
+                                Arg0Type, \
+                                Arg1Type, \
+                                Arg2Type, \
+                                Arg3Type, \
+                                Arg4Type, \
+                                Arg5Type)                                        \
+    class ClassName :                                                                                                                                     \
+        public DPL::GenericEvent6<Arg0Type, Arg1Type, Arg2Type, Arg3Type, \
+                                  Arg4Type, Arg5Type>                                               \
+    {                                                                                                                                         \
+      public:                                                                                                                                   \
+        explicit ClassName(const DPL::EventSender & sender = \
+                               DPL::EventSender(NULL)) :                                                                                                                                 \
+            DPL::GenericEvent6<Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type, \
+                               Arg5Type>(sender)                                          \
+        {                                                                                                                                     \
+        }                                                                                                                                     \
+                                                                                                                                              \
+        ClassName(Arg0Type arg0, \
+                  Arg1Type arg1, \
+                  Arg2Type arg2, \
+                  Arg3Type arg3, \
+                  Arg4Type arg4, \
+                  Arg5Type arg5,                                   \
+                  const DPL::EventSender & sender = DPL::EventSender(NULL)) :                                                                                                                                 \
+            DPL::GenericEvent6<Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type, \
+                               Arg5Type>(arg0, \
+                                         arg1, \
+                                         arg2, \
+                                         arg3, \
+                                         arg4, \
+                                         arg5, \
+                                         sender)      \
+        {                                                                                                                                     \
+        }                                                                                                                                     \
+    };
+
+#define DECLARE_GENERIC_EVENT_7(ClassName, \
+                                Arg0Type, \
+                                Arg1Type, \
+                                Arg2Type, \
+                                Arg3Type, \
+                                Arg4Type, \
+                                Arg5Type, \
+                                Arg6Type)                                              \
+    class ClassName :                                                                                                                                                     \
+        public DPL::GenericEvent7<Arg0Type, Arg1Type, Arg2Type, Arg3Type, \
+                                  Arg4Type, Arg5Type, Arg6Type>                                                     \
+    {                                                                                                                                                         \
+      public:                                                                                                                                                   \
+        explicit ClassName(const DPL::EventSender & sender = \
+                               DPL::EventSender(NULL)) :                                                                                                                                                 \
+            DPL::GenericEvent7<Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type, \
+                               Arg5Type, Arg6Type>(sender)                                                \
+        {                                                                                                                                                     \
+        }                                                                                                                                                     \
+                                                                                                                                                              \
+        ClassName(Arg0Type arg0, \
+                  Arg1Type arg1, \
+                  Arg2Type arg2, \
+                  Arg3Type arg3, \
+                  Arg4Type arg4, \
+                  Arg5Type arg5, \
+                  Arg6Type arg6,                                    \
+                  const DPL::EventSender & sender = DPL::EventSender(NULL)) :                                                                                                                                                 \
+            DPL::GenericEvent7<Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type, \
+                               Arg5Type, Arg6Type>(arg0, \
+                                                   arg1, \
+                                                   arg2, \
+                                                   arg3, \
+                                                   arg4, \
+                                                   arg5, \
+                                                   arg6, \
+                                                   sender)      \
+        {                                                                                                                                                     \
+        }                                                                                                                                                     \
+    };
+
+#define DECLARE_GENERIC_EVENT_8(ClassName, \
+                                Arg0Type, \
+                                Arg1Type, \
+                                Arg2Type, \
+                                Arg3Type, \
+                                Arg4Type, \
+                                Arg5Type, \
+                                Arg6Type, \
+                                Arg7Type)                                                    \
+    class ClassName :                                                                                                                                                                     \
+        public DPL::GenericEvent8<Arg0Type, Arg1Type, Arg2Type, Arg3Type, \
+                                  Arg4Type, Arg5Type, Arg6Type, Arg7Type>                                                           \
+    {                                                                                                                                                                         \
+      public:                                                                                                                                                                   \
+        explicit ClassName(const DPL::EventSender & sender = \
+                               DPL::EventSender(NULL)) :                                                                                                                                                                 \
+            DPL::GenericEvent8<Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type, \
+                               Arg5Type, Arg6Type, Arg7Type>(sender)                                                      \
+        {                                                                                                                                                                     \
+        }                                                                                                                                                                     \
+                                                                                                                                                                              \
+        ClassName(Arg0Type arg0, \
+                  Arg1Type arg1, \
+                  Arg2Type arg2, \
+                  Arg3Type arg3, \
+                  Arg4Type arg4, \
+                  Arg5Type arg5, \
+                  Arg6Type arg6, \
+                  Arg7Type arg7,                                     \
+                  const DPL::EventSender & sender = DPL::EventSender(NULL)) :                                                                                                                                                                 \
+            DPL::GenericEvent8<Arg0Type, Arg1Type, Arg2Type, Arg3Type, Arg4Type, \
+                               Arg5Type, Arg6Type, Arg7Type>(arg0, \
+                                                             arg1, \
+                                                             arg2, \
+                                                             arg3, \
+                                                             arg4, \
+                                                             arg5, \
+                                                             arg6, \
+                                                             arg7, \
+                                                             sender)      \
+        {                                                                                                                                                                     \
+        }                                                                                                                                                                     \
+    };
+
+#endif // DPL_GENERIC_EVENT_H
diff --git a/commons/modules/core/include/dpl/mutex.h b/commons/modules/core/include/dpl/mutex.h
new file mode 100644 (file)
index 0000000..d55871f
--- /dev/null
@@ -0,0 +1,67 @@
+/*
+ * 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        mutex.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of mutex
+ */
+#ifndef DPL_MUTEX_H
+#define DPL_MUTEX_H
+
+#include <dpl/noncopyable.h>
+#include <dpl/exception.h>
+#include <dpl/availability.h>
+#include <pthread.h>
+
+namespace DPL {
+class Mutex :
+    private Noncopyable
+{
+  public:
+    class ScopedLock :
+        private Noncopyable
+    {
+      private:
+        Mutex *m_mutex;
+
+      public:
+        explicit ScopedLock(Mutex *mutex);
+        ~ScopedLock();
+    };
+
+    class Exception
+    {
+      public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, CreateFailed)
+        DECLARE_EXCEPTION_TYPE(Base, LockFailed)
+        DECLARE_EXCEPTION_TYPE(Base, UnlockFailed)
+    };
+
+  private:
+    mutable pthread_mutex_t m_mutex;
+
+    void Lock() const;
+    void Unlock() const;
+
+  public:
+    Mutex();
+    ~Mutex();
+} DPL_DEPRECATED_WITH_MESSAGE("Use std::mutex instead");
+} // namespace DPL
+
+#endif // DPL_MUTEX_H
diff --git a/commons/modules/core/include/dpl/noncopyable.h b/commons/modules/core/include/dpl/noncopyable.h
new file mode 100644 (file)
index 0000000..98d57dd
--- /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        noncopyable
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of noncopyable
+ */
+#ifndef DPL_NONCOPYABLE_H
+#define DPL_NONCOPYABLE_H
+
+namespace DPL {
+class Noncopyable
+{
+  private:
+    Noncopyable(const Noncopyable &);
+    const Noncopyable &operator=(const Noncopyable &);
+
+  public:
+    Noncopyable();
+    virtual ~Noncopyable();
+};
+} // namespace DPL
+
+#endif // DPL_NONCOPYABLE_H
diff --git a/commons/modules/core/include/dpl/optional_typedefs.h b/commons/modules/core/include/dpl/optional_typedefs.h
new file mode 100644 (file)
index 0000000..dd68dc2
--- /dev/null
@@ -0,0 +1,33 @@
+/*
+ * 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 DPL_OPTIONAL_TYPEDEFS_H
+#define DPL_OPTIONAL_TYPEDEFS_H
+
+#include <string>
+#include <dpl/string.h>
+#include <boost/optional.hpp>
+
+namespace DPL {
+typedef boost::optional<String> OptionalString;
+typedef boost::optional<int> OptionalInt;
+typedef boost::optional<unsigned int> OptionalUInt;
+typedef boost::optional<bool> OptionalBool;
+typedef boost::optional<float> OptionalFloat;
+typedef boost::optional<std::string> OptionalStdString;
+} //namespace DPL
+
+#endif /* DPL_OPTIONAL_TYPEDEFS_H */
+
diff --git a/commons/modules/core/include/dpl/preprocessor.h b/commons/modules/core/include/dpl/preprocessor.h
new file mode 100644 (file)
index 0000000..6fca34c
--- /dev/null
@@ -0,0 +1,35 @@
+/*
+ * 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        preprocessor.h
+ * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
+ * @version     1.0
+ * @brief       This file contains some usefull macros.
+ */
+
+#ifndef DPL_PREPROCESSOR_H
+#define DPL_PREPROCESSOR_H
+
+#define DPL_MACRO_CONCAT_IMPL(x, y) x##y
+#define DPL_MACRO_CONCAT(x, y) DPL_MACRO_CONCAT_IMPL(x, y)
+
+#ifdef __COUNTER__
+#define DPL_ANONYMOUS_VARIABLE(name) DPL_MACRO_CONCAT(name, __COUNTER__)
+#else
+#define DPL_ANONYMOUS_VARIABLE(name) DPL_MACRO_CONCAT(name, __LINE__)
+#endif
+
+#endif //DPL_PREPROCESSOR_H
diff --git a/commons/modules/core/include/dpl/recursive_mutex.h b/commons/modules/core/include/dpl/recursive_mutex.h
new file mode 100644 (file)
index 0000000..a950ee5
--- /dev/null
@@ -0,0 +1,68 @@
+/*
+ * 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        recursive_mutex.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of recursive mutex
+ */
+#ifndef DPL_RECURSIVE_MUTEX_H
+#define DPL_RECURSIVE_MUTEX_H
+
+#include <dpl/availability.h>
+#include <dpl/noncopyable.h>
+#include <dpl/exception.h>
+#include <pthread.h>
+
+namespace DPL {
+class RecursiveMutex :
+    private Noncopyable
+{
+  public:
+    class ScopedLock :
+        private Noncopyable
+    {
+      private:
+        RecursiveMutex *m_mutex;
+
+      public:
+        ScopedLock(RecursiveMutex *mutex);
+        virtual ~ScopedLock();
+    };
+
+    class Exception
+    {
+      public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, CreateFailed)
+        DECLARE_EXCEPTION_TYPE(Base, DestroyFailed)
+        DECLARE_EXCEPTION_TYPE(Base, LockFailed)
+        DECLARE_EXCEPTION_TYPE(Base, UnlockFailed)
+    };
+
+  private:
+    mutable pthread_mutex_t m_mutex;
+
+    void Lock() const;
+    void Unlock() const;
+
+  public:
+    explicit RecursiveMutex();
+    virtual ~RecursiveMutex();
+} DPL_DEPRECATED_WITH_MESSAGE("Use std::recursive_mutex instead");
+} // namespace DPL
+
+#endif // DPL_RECURSIVE_MUTEX_H
diff --git a/commons/modules/core/include/dpl/scoped_free.h b/commons/modules/core/include/dpl/scoped_free.h
new file mode 100644 (file)
index 0000000..7bebe39
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * 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        scoped_free.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of scoped free RAII
+ */
+
+#ifndef DPL_SCOPED_FREE_H
+#define DPL_SCOPED_FREE_H
+
+#include <malloc.h>
+#include <cstddef>
+
+#include <dpl/scoped_resource.h>
+
+namespace DPL {
+template<typename Class>
+struct ScopedFreePolicy
+{
+    typedef Class* Type;
+    static Type NullValue()
+    {
+        return NULL;
+    }
+    static void Destroy(Type ptr)
+    {
+        free(ptr);
+    }
+};
+
+template<typename Memory>
+class ScopedFree : public ScopedResource<ScopedFreePolicy<Memory> >
+{
+    typedef ScopedFreePolicy<Memory> Policy;
+    typedef ScopedResource<Policy> BaseType;
+
+  public:
+    explicit ScopedFree(Memory *ptr = Policy::NullValue()) : BaseType(ptr) { }
+};
+} // namespace DPL
+
+#endif // DPL_SCOPED_FREE_H
diff --git a/commons/modules/core/include/dpl/scoped_resource.h b/commons/modules/core/include/dpl/scoped_resource.h
new file mode 100644 (file)
index 0000000..63287da
--- /dev/null
@@ -0,0 +1,80 @@
+/*
+ * 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        scoped_resource.h
+ * @author      Piotr Marcinkiewicz (p.marcinkiew@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of scoped resource pattern
+ */
+#ifndef DPL_SCOPED_RESOURCE_H
+#define DPL_SCOPED_RESOURCE_H
+
+#include <dpl/noncopyable.h>
+
+namespace DPL {
+template<typename ClassPolicy>
+class ScopedResource :
+    private Noncopyable
+{
+  public:
+    typedef typename ClassPolicy::Type ValueType;
+    typedef ScopedResource<ClassPolicy> ThisType;
+
+  protected:
+    ValueType m_value;
+
+  public:
+    explicit ScopedResource(ValueType value) : m_value(value) { }
+
+    ~ScopedResource()
+    {
+        ClassPolicy::Destroy(m_value);
+    }
+
+    ValueType Get() const
+    {
+        return m_value;
+    }
+
+    void Reset(ValueType value = ClassPolicy::NullValue())
+    {
+        ClassPolicy::Destroy(m_value);
+        m_value = value;
+    }
+
+    ValueType Release()
+    {
+        ValueType value = m_value;
+        m_value = ClassPolicy::NullValue();
+        return value;
+    }
+    typedef ValueType ThisType::*UnknownBoolType;
+
+    operator UnknownBoolType() const
+    {
+        return m_value == ClassPolicy::NullValue() ?
+               0 : //0 is valid here because it converts to false
+               &ThisType::m_value; //it converts to true
+    }
+
+    bool operator !() const
+    {
+        return m_value == ClassPolicy::NullValue();
+    }
+};
+} // namespace DPL
+
+#endif // DPL_SCOPED_RESOURCE_H
diff --git a/commons/modules/core/include/dpl/serialization.h b/commons/modules/core/include/dpl/serialization.h
new file mode 100644 (file)
index 0000000..d72c488
--- /dev/null
@@ -0,0 +1,327 @@
+/*
+ * 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    serialization.h
+ * @author  Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version 1.0
+ * @brief   Interfaces and templates used for data serialization.
+ */
+#ifndef SERIALIZATION_H
+#define SERIALIZATION_H
+
+#include <string>
+#include <vector>
+#include <list>
+#include <map>
+
+namespace DPL {
+// Abstract data stream buffer
+class IStream
+{
+  public:
+    virtual void Read(size_t num, void * bytes) = 0;
+    virtual void Write(size_t num, const void * bytes) = 0;
+    virtual ~IStream(){}
+};
+
+// Serializable interface
+class ISerializable
+{
+  public:
+    /*    ISerializable(){};
+     *    ISerializable(IStream&){}; */
+    virtual void Serialize(IStream &) const = 0;
+    virtual ~ISerializable(){}
+};
+
+struct Serialization {
+    // serialization
+    // normal functions
+
+    // ISerializable objects
+    static void Serialize(IStream& stream, const ISerializable& object)
+    {
+        object.Serialize(stream);
+    }
+    static void Serialize(IStream& stream, const ISerializable* const object)
+    {
+        object->Serialize(stream);
+    }
+
+    // unsigned int
+    static void Serialize(IStream& stream, const unsigned value)
+    {
+        stream.Write(sizeof(value), &value);
+    }
+    static void Serialize(IStream& stream, const unsigned* const value)
+    {
+        stream.Write(sizeof(*value), value);
+    }
+
+    // int
+    static void Serialize(IStream& stream, const int value)
+    {
+        stream.Write(sizeof(value), &value);
+    }
+    static void Serialize(IStream& stream, const int* const value)
+    {
+        stream.Write(sizeof(*value), value);
+    }
+
+    // bool
+    static void Serialize(IStream& stream, const bool value)
+    {
+        stream.Write(sizeof(value), &value);
+    }
+    static void Serialize(IStream& stream, const bool* const value)
+    {
+        stream.Write(sizeof(*value), value);
+    }
+
+    // std::string
+    static void Serialize(IStream& stream, const std::string& str)
+    {
+        int length = str.size();
+        stream.Write(sizeof(length), &length);
+        stream.Write(length, str.c_str());
+    }
+    static void Serialize(IStream& stream, const std::string* const str)
+    {
+        int length = str->size();
+        stream.Write(sizeof(length), &length);
+        stream.Write(length, str->c_str());
+    }
+
+    // STL templates
+
+    // std::list
+    template <typename T>
+    static void Serialize(IStream& stream, const std::list<T>& list)
+    {
+        int length = list.size();
+        stream.Write(sizeof(length), &length);
+        for (typename std::list<T>::const_iterator list_iter = list.begin();
+             list_iter != list.end(); list_iter++)
+        {
+            Serialize(stream, *list_iter);
+        }
+    }
+    template <typename T>
+    static void Serialize(IStream& stream, const std::list<T>* const list)
+    {
+        Serialize(stream, *list);
+    }
+
+    // std::vector
+    template <typename T>
+    static void Serialize(IStream& stream, const std::vector<T>& vec)
+    {
+        int length = vec.size();
+        stream.Write(sizeof(length), &length);
+        for (typename std::vector<T>::const_iterator vec_iter = vec.begin();
+             vec_iter != vec.end(); vec_iter++)
+        {
+            Serialize(stream, *vec_iter);
+        }
+    }
+    template <typename T>
+    static void Serialize(IStream& stream, const std::vector<T>* const vec)
+    {
+        Serialize(stream, *vec);
+    }
+
+    // std::pair
+    template <typename A, typename B>
+    static void Serialize(IStream& stream, const std::pair<A, B>& p)
+    {
+        Serialize(stream, p.first);
+        Serialize(stream, p.second);
+    }
+    template <typename A, typename B>
+    static void Serialize(IStream& stream, const std::pair<A, B>* const p)
+    {
+        Serialize(stream, *p);
+    }
+
+    // std::map
+    template <typename K, typename T>
+    static void Serialize(IStream& stream, const std::map<K, T>& map)
+    {
+        int length = map.size();
+        stream.Write(sizeof(length), &length);
+        typename std::map<K, T>::const_iterator it;
+        for (it = map.begin(); it != map.end(); ++it) {
+            Serialize(stream, (*it).first);
+            Serialize(stream, (*it).second);
+        }
+    }
+    template <typename K, typename T>
+    static void Serialize(IStream& stream, const std::map<K, T>* const map)
+    {
+        Serialize(stream, *map);
+    }
+}; // struct Serialization
+
+struct Deserialization {
+    // deserialization
+    // normal functions
+
+    // ISerializable objects
+    // T instead of ISerializable is needed to call proper constructor
+    template <typename T>
+    static void Deserialize(IStream& stream, T& object)
+    {
+        object = T(stream);
+    }
+    template <typename T>
+    static void Deserialize(IStream& stream, T*& object)
+    {
+        object = new T(stream);
+    }
+
+    // unsigned int
+    static void Deserialize(IStream& stream, unsigned& value)
+    {
+        stream.Read(sizeof(value), &value);
+    }
+    static void Deserialize(IStream& stream, unsigned*& value)
+    {
+        value = new unsigned;
+        stream.Read(sizeof(*value), value);
+    }
+
+    // int
+    static void Deserialize(IStream& stream, int& value)
+    {
+        stream.Read(sizeof(value), &value);
+    }
+    static void Deserialize(IStream& stream, int*& value)
+    {
+        value = new int;
+        stream.Read(sizeof(*value), value);
+    }
+
+    // bool
+    static void Deserialize(IStream& stream, bool& value)
+    {
+        stream.Read(sizeof(value), &value);
+    }
+    static void Deserialize(IStream& stream, bool*& value)
+    {
+        value = new bool;
+        stream.Read(sizeof(*value), value);
+    }
+
+    // std::string
+    static void Deserialize(IStream& stream, std::string& str)
+    {
+        int length;
+        stream.Read(sizeof(length), &length);
+        char * buf = new char[length + 1];
+        stream.Read(length, buf);
+        buf[length] = 0;
+        str = std::string(buf);
+        delete[] buf;
+    }
+    static void Deserialize(IStream& stream, std::string*& str)
+    {
+        int length;
+        stream.Read(sizeof(length), &length);
+        char * buf = new char[length + 1];
+        stream.Read(length, buf);
+        buf[length] = 0;
+        str = new std::string(buf);
+        delete[] buf;
+    }
+
+    // STL templates
+
+    // std::list
+    template <typename T>
+    static void Deserialize(IStream& stream, std::list<T>& list)
+    {
+        int length;
+        stream.Read(sizeof(length), &length);
+        for (int i = 0; i < length; ++i) {
+            T obj;
+            Deserialize(stream, obj);
+            list.push_back(obj);
+        }
+    }
+    template <typename T>
+    static void Deserialize(IStream& stream, std::list<T>*& list)
+    {
+        list = new std::list<T>;
+        Deserialize(stream, *list);
+    }
+
+    // std::vector
+    template <typename T>
+    static void Deserialize(IStream& stream, std::vector<T>& vec)
+    {
+        int length;
+        stream.Read(sizeof(length), &length);
+        for (int i = 0; i < length; ++i) {
+            T obj;
+            Deserialize(stream, obj);
+            vec.push_back(obj);
+        }
+    }
+    template <typename T>
+    static void Deserialize(IStream& stream, std::vector<T>*& vec)
+    {
+        vec = new std::vector<T>;
+        Deserialize(stream, *vec);
+    }
+
+    // std::pair
+    template <typename A, typename B>
+    static void Deserialize(IStream& stream, std::pair<A, B>& p)
+    {
+        Deserialize(stream, p.first);
+        Deserialize(stream, p.second);
+    }
+    template <typename A, typename B>
+    static void Deserialize(IStream& stream, std::pair<A, B>*& p)
+    {
+        p = new std::pair<A, B>;
+        Deserialize(stream, *p);
+    }
+
+    // std::map
+    template <typename K, typename T>
+    static void Deserialize(IStream& stream, std::map<K, T>& map)
+    {
+        int length;
+        stream.Read(sizeof(length), &length);
+        for (int i = 0; i < length; ++i) {
+            K key;
+            T obj;
+            Deserialize(stream, key);
+            Deserialize(stream, obj);
+            map[key] = obj;
+        }
+    }
+    template <typename K, typename T>
+    static void Deserialize(IStream& stream, std::map<K, T>*& map)
+    {
+        map = new std::map<K, T>;
+        Deserialize(stream, *map);
+    }
+}; // struct Deserialization
+} // namespace DPL
+
+#endif // SERIALIZATION_H
diff --git a/commons/modules/core/include/dpl/single_instance.h b/commons/modules/core/include/dpl/single_instance.h
new file mode 100644 (file)
index 0000000..afcaf52
--- /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        single_instance.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of single instance
+ */
+#ifndef DPL_SINGLE_INSTANCE_H
+#define DPL_SINGLE_INSTANCE_H
+
+#include <dpl/noncopyable.h>
+#include <dpl/exception.h>
+#include <string>
+
+namespace DPL {
+class SingleInstance :
+    private Noncopyable
+{
+  public:
+    class Exception
+    {
+      public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, LockError)
+        DECLARE_EXCEPTION_TYPE(Base, ReleaseError)
+    };
+
+  private:
+    bool m_locked;
+    int m_fdLock;
+
+  public:
+    SingleInstance();
+    virtual ~SingleInstance();
+
+    bool TryLock(const std::string &lockName);
+    void Release();
+};
+} // namespace DPL
+
+#endif // DPL_SINGLE_INSTANCE_H
diff --git a/commons/modules/core/include/dpl/singleton.h b/commons/modules/core/include/dpl/singleton.h
new file mode 100644 (file)
index 0000000..5cd2d32
--- /dev/null
@@ -0,0 +1,57 @@
+/*
+ * 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
+
+#include <boost/optional.hpp>
+#include <dpl/thread.h>
+#include <dpl/assert.h>
+
+namespace DPL {
+template<typename Class>
+class Singleton :
+    private Class
+{
+    //
+    // Note:
+    //
+    // To remove posibility of instantiating directly Class,
+    // make Class' default constructor protected
+    //
+
+  private:
+    Singleton()
+    {}
+
+    typedef boost::optional<Thread *> OptionalThreadPtr;
+
+    static Singleton &InternalInstance();
+
+  public:
+    virtual ~Singleton()
+    {}
+
+    static Class &Instance();
+};
+} // namespace DPL
+
+#endif // DPL_SINGLETON_H
diff --git a/commons/modules/core/include/dpl/singleton_impl.h b/commons/modules/core/include/dpl/singleton_impl.h
new file mode 100644 (file)
index 0000000..12dbf32
--- /dev/null
@@ -0,0 +1,53 @@
+/*
+ * 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
+
+/*
+ * 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 DPL {
+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 DPL
+
+#define IMPLEMENT_SINGLETON(Type)                                           \
+    template DPL::Singleton<Type>&DPL::Singleton<Type>::InternalInstance();    \
+    template Type & DPL::Singleton<Type>::Instance();                            \
+
+#endif // DPL_SINGLETON_IMPL_H
diff --git a/commons/modules/core/include/dpl/singleton_safe_impl.h b/commons/modules/core/include/dpl/singleton_safe_impl.h
new file mode 100644 (file)
index 0000000..c8923b7
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * 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_safe_impl.h
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of singleton
+ */
+#ifndef DPL_SINGLETON_SAFE_IMPL_H
+#define DPL_SINGLETON_SAFE_IMPL_H
+
+#define IMPLEMENT_SAFE_SINGLETON(Class)                                        \
+    namespace DPL {                                                                \
+    template<>                                                                     \
+    Singleton<Class>&Singleton<Class>::InternalInstance()                         \
+    {                                                                              \
+        static Singleton<Class> instance;                                          \
+        return instance;                                                           \
+    }                                                                              \
+                                                                               \
+    template<>                                                                     \
+    Class & Singleton<Class>::Instance()                                            \
+    {                                                                              \
+        Singleton<Class>& instance = Singleton<Class>::InternalInstance();         \
+        return instance;                                                           \
+    }                                                                              \
+                                                                               \
+    template Singleton<Class>&Singleton<Class>::InternalInstance();               \
+    template Class & Singleton<Class>::Instance();                                  \
+    } // namespace DPL
+
+#endif // DPL_SINGLETON_SAFE_IMPL_H
diff --git a/commons/modules/core/include/dpl/string.h b/commons/modules/core/include/dpl/string.h
new file mode 100644 (file)
index 0000000..e4dc923
--- /dev/null
@@ -0,0 +1,157 @@
+/*
+ * 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        string.h
+ * @author      Piotr Marcinkiewicz (p.marcinkiew@samsung.com)
+ * @version     1.0
+ */
+#ifndef DPL_STRING
+#define DPL_STRING
+
+#include <dpl/exception.h>
+#include <dpl/char_traits.h>
+#include <string>
+#include <ostream>
+#include <numeric>
+
+namespace DPL {
+// @brief DPL string
+typedef std::basic_string<wchar_t, CharTraits> String;
+
+// @brief String exception class
+class StringException
+{
+  public:
+    DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+
+    // @brief Invalid init for UTF8 to UTF32 converter
+    DECLARE_EXCEPTION_TYPE(Base, IconvInitErrorUTF8ToUTF32)
+
+    // @brief Invalid taStdContainerinit for UTF32 to UTF32 converter
+    DECLARE_EXCEPTION_TYPE(Base, IconvInitErrorUTF32ToUTF8)
+
+    // @brief Invalid conversion for UTF8 to UTF32 converter
+    DECLARE_EXCEPTION_TYPE(Base, IconvConvertErrorUTF8ToUTF32)
+
+    // @brief Invalid conversion for UTF8 to UTF32 converter
+    DECLARE_EXCEPTION_TYPE(Base, IconvConvertErrorUTF32ToUTF8)
+
+    // @brief Invalid ASCII character detected in FromASCII
+    DECLARE_EXCEPTION_TYPE(Base, InvalidASCIICharacter)
+
+    // @brief Invalid ASCII character detected in FromASCII
+    DECLARE_EXCEPTION_TYPE(Base, ICUInvalidCharacterFound)
+};
+
+//!\brief convert ASCII string to DPL::String
+String FromASCIIString(const std::string& aString);
+
+//!\brief convert UTF32 string to DPL::String
+String FromUTF32String(const std::wstring& aString);
+
+//@brief Returns String object created from UTF8 string
+//@param[in] aString input UTF-8 string
+String FromUTF8String(const std::string& aString);
+
+//@brief Returns String content as std::string
+std::string ToUTF8String(const String& aString);
+
+//@brief Compare two unicode strings
+int StringCompare(const String &left,
+                  const String &right,
+                  bool caseInsensitive = false);
+
+//@brief Splits the string into substrings.
+//@param[in] str Input string
+//@param[in] delimiters array or string containing a sequence of substring
+// delimiters. Can be also a single delimiter character.
+//@param[in] it InserterIterator that is used to save the generated substrings.
+template<typename StringType, typename Delimiters, typename InserterIterator>
+void Tokenize(const StringType& str,
+              const Delimiters& delimiters,
+              InserterIterator it,
+              bool ignoreEmpty = false)
+{
+    typename StringType::size_type nextSearchStart = 0;
+    typename StringType::size_type pos;
+    typename StringType::size_type length;
+
+    while (true) {
+        pos = str.find_first_of(delimiters, nextSearchStart);
+        length =
+            ((pos == StringType::npos) ? str.length() : pos) - nextSearchStart;
+
+        if (!ignoreEmpty || length > 0) {
+            *it = str.substr(nextSearchStart, length);
+            it++;
+        }
+
+        if (pos == StringType::npos) {
+            return;
+        }
+
+        nextSearchStart = pos + 1;
+    }
+}
+
+namespace Utils {
+
+template<typename T> class ConcatFunc : public std::binary_function<T, T, T>
+{
+public:
+    explicit ConcatFunc(const T & val) : m_delim(val) {}
+    T operator()(const T & arg1, const T & arg2) const
+    {
+        return arg1 + m_delim + arg2;
+    }
+private:
+    T m_delim;
+};
+
+}
+
+template<typename ForwardIterator>
+typename ForwardIterator::value_type Join(ForwardIterator begin, ForwardIterator end, typename ForwardIterator::value_type delim)
+{
+    typedef typename ForwardIterator::value_type value;
+    if(begin == end) return value();
+    Utils::ConcatFunc<value> func(delim);
+    ForwardIterator init = begin;
+    return std::accumulate(++begin, end, *init, func);
+}
+
+template<class StringType> void TrimLeft(StringType & obj, typename StringType::const_pointer separators)
+{
+    obj.erase(0, obj.find_first_not_of(separators));
+}
+
+template<class StringType> void TrimRight(StringType & obj, typename StringType::const_pointer separators)
+{
+    obj.erase(obj.find_last_not_of(separators)+1);
+}
+
+template<class StringType> void Trim(StringType & obj, typename StringType::const_pointer separators)
+{
+    TrimLeft(obj, separators);
+    TrimRight(obj, separators);
+}
+
+
+} //namespace DPL
+
+std::ostream& operator<<(std::ostream& aStream, const DPL::String& aString);
+
+#endif // DPL_STRING
diff --git a/commons/modules/core/include/dpl/thread.h b/commons/modules/core/include/dpl/thread.h
new file mode 100644 (file)
index 0000000..d61b79d
--- /dev/null
@@ -0,0 +1,396 @@
+/*
+ * 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        thread.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of thread
+ */
+#ifndef DPL_THREAD_H
+#define DPL_THREAD_H
+
+#include <dpl/waitable_handle_watch_support.h>
+//#include <dpl/waitable_event.h>
+//#include <dpl/waitable_handle.h>
+#include <dpl/noncopyable.h>
+#include <dpl/exception.h>
+#include <dpl/assert.h>
+#include <boost/optional.hpp>
+#include <stdint.h>
+#include <cstdlib>
+#include <pthread.h>
+#include <thread>
+#include <vector>
+#include <list>
+#include <mutex>
+
+namespace DPL {
+class Thread :
+    private Noncopyable,
+    public WaitableHandleWatchSupport
+{
+  public:
+    class Exception
+    {
+      public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, CreateFailed)
+        DECLARE_EXCEPTION_TYPE(Base, DestroyFailed)
+        DECLARE_EXCEPTION_TYPE(Base, RunFailed)
+        DECLARE_EXCEPTION_TYPE(Base, QuitFailed)
+        DECLARE_EXCEPTION_TYPE(Base, UnmanagedThread)
+    };
+
+    typedef void (*EventDeleteProc)(void *event, void *userParam);
+    typedef void (*EventDispatchProc)(void *event, void *userParam);
+
+  protected:
+    /**
+     * Main thread entry
+     * The method is intended to be overloaded with custom code.
+     * Default implementation just executes Exec method to process
+     * all thread exents
+     */
+    virtual int ThreadEntry();
+
+    /**
+     * Start processing of thread events
+     */
+    int Exec();
+
+  private:
+    struct InternalEvent
+    {
+        void *event;
+        void *userParam;
+        EventDispatchProc eventDispatchProc;
+        EventDeleteProc eventDeleteProc;
+
+        InternalEvent(void *eventArg,
+                      void *userParamArg,
+                      EventDispatchProc eventDispatchProcArg,
+                      EventDeleteProc eventDeleteProcArg) :
+            event(eventArg),
+            userParam(userParamArg),
+            eventDispatchProc(eventDispatchProcArg),
+            eventDeleteProc(eventDeleteProcArg)
+        {}
+    };
+
+    struct InternalTimedEvent :
+        InternalEvent
+    {
+        unsigned long dueTimeMiliseconds;
+        unsigned long registerTimeMiliseconds;
+
+        InternalTimedEvent(void *eventArg,
+                           void *userParamArg,
+                           unsigned long dueTimeMilisecondsArg,
+                           unsigned long registerTimeMilisecondsArg,
+                           EventDispatchProc eventDispatchProcArg,
+                           EventDeleteProc eventDeleteProcArg) :
+            InternalEvent(eventArg,
+                          userParamArg,
+                          eventDispatchProcArg,
+                          eventDeleteProcArg),
+            dueTimeMiliseconds(dueTimeMilisecondsArg),
+            registerTimeMiliseconds(registerTimeMilisecondsArg)
+        {}
+
+        bool operator<(const InternalTimedEvent &other)
+        {
+            return registerTimeMiliseconds + dueTimeMiliseconds >
+                   other.registerTimeMiliseconds + other.dueTimeMiliseconds;
+        }
+    };
+
+    // Internal event list
+    typedef std::list<InternalEvent> InternalEventList;
+
+    // Internal timed event list
+    typedef std::vector<InternalTimedEvent> InternalTimedEventVector;
+
+    // State managment
+    std::thread m_thread;
+    volatile bool m_abandon;
+    volatile bool m_running;
+    std::mutex m_stateMutex;
+    WaitableEvent m_quitEvent;
+
+    // Event processing
+    std::mutex m_eventMutex;
+    InternalEventList m_eventList;
+    WaitableEvent m_eventInvoker;
+
+    // Timed events processing
+    std::mutex m_timedEventMutex;
+    InternalTimedEventVector m_timedEventVector;
+    WaitableEvent m_timedEventInvoker;
+
+    // WaitableHandleWatchSupport
+    virtual Thread *GetInvokerThread();
+    virtual void HandleDirectInvoker();
+    bool m_directInvoke;
+
+    // Internals
+    unsigned long GetCurrentTimeMiliseconds() const;
+    void ProcessEvents();
+    void ProcessTimedEvents();
+
+    static void *StaticThreadEntry(void *param);
+
+  public:
+    explicit Thread();
+    virtual ~Thread();
+
+    /**
+     * Run thread. Does nothing if thread is already running
+     */
+    void Run();
+
+    /**
+     * Send quit message to thread and wait for its end
+     * Does nothing is thread is not running
+     */
+    void Quit();
+
+    /**
+     * Checks if current thread is main one
+     * Returns true if it is main program thread, false otherwise
+     */
+    static bool IsMainThread();
+
+    /**
+     * Current thread retrieval
+     * Returns DPL thread handle or NULL if it is main program thread
+     */
+    static Thread *GetCurrentThread();
+
+    /**
+     * Low-level event push, usually used only by EventSupport
+     */
+    void PushEvent(void *event,
+                   EventDispatchProc eventDispatchProc,
+                   EventDeleteProc eventDeleteProc,
+                   void *userParam);
+
+    /**
+     * Low-level timed event push, usually used only by EventSupport
+     */
+    void PushTimedEvent(void *event,
+                        double dueTimeSeconds,
+                        EventDispatchProc eventDispatchProc,
+                        EventDeleteProc eventDeleteProc,
+                        void *userParam);
+
+    /**
+     * Sleep for a number of seconds
+     */
+    static void Sleep(uint64_t seconds);
+
+    /**
+     * Sleep for a number of miliseconds
+     */
+    static void MiliSleep(uint64_t miliseconds);
+
+    /**
+     * Sleep for a number of microseconds
+     */
+    static void MicroSleep(uint64_t microseconds);
+
+    /**
+     * Sleep for a number of nanoseconds
+     */
+    static void NanoSleep(uint64_t nanoseconds);
+};
+
+extern bool g_TLSforMainCreated;
+
+// In case of using TLV in main thread, pthread_exit(NULL) has to be called in
+// this thread explicitly.
+// On the other hand, possibly, because of the kernel bug, there exist
+// a problem, if any other thread than main exist during pthread_exit call
+// (process can become non-responsive)
+// TODO further investigation is required.
+template<typename Type>
+class ThreadLocalVariable :
+    public Noncopyable
+{
+  public:
+    typedef Type ValueType;
+
+    class Exception
+    {
+      public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, NullReference)
+        DECLARE_EXCEPTION_TYPE(Base, KeyCreateFailed)
+    };
+
+  private:
+    pthread_key_t m_key;
+
+    struct ManagedValue
+    {
+        ValueType value;
+        boost::optional<pthread_key_t> guardKey;
+    };
+
+    static void MainThreadExitClean()
+    {
+        // There is a possible bug in kernel. If this function is called
+        // before ALL threads are closed, process will hang!
+        // Because of that, by default this function has to be called in well
+        // known "threads state".
+
+        // pthread_exit(NULL);
+    }
+
+    static void InternalDestroy(void *specific)
+    {
+        // Destroy underlying type
+        ManagedValue *instance = static_cast<ManagedValue *>(specific);
+        if (!instance->guardKey) {
+            delete instance;
+        } else {
+            int result = pthread_setspecific(*(instance->guardKey), instance);
+
+            Assert(result == 0 &&
+                   "Failed to set thread local variable");
+        }
+    }
+
+    Type &Reference(bool allowInstantiate = false)
+    {
+        ManagedValue *instance =
+            static_cast<ManagedValue *>(pthread_getspecific(m_key));
+
+        if (!instance) {
+            // Check if it is allowed to instantiate
+            if (!allowInstantiate) {
+                Throw(typename Exception::NullReference);
+            }
+
+            // checking, if specific data is created for Main thread
+            // If yes, pthread_exit(NULL) is required
+            if (!g_TLSforMainCreated) {
+                if (Thread::IsMainThread()) {
+                    g_TLSforMainCreated = true;
+                    atexit(&MainThreadExitClean);
+                }
+            }
+
+            // Need to instantiate underlying type
+            instance = new ManagedValue();
+
+            int result = pthread_setspecific(m_key, instance);
+
+            Assert(result == 0 &&
+                   "Failed to set thread local variable");
+        }
+
+        return instance->value;
+    }
+
+  public:
+    ThreadLocalVariable()
+    {
+        int result = pthread_key_create(&m_key, &InternalDestroy);
+        if (result != 0) {
+            ThrowMsg(typename Exception::KeyCreateFailed,
+                     "Failed to allocate thread local variable: " << result);
+        }
+    }
+
+    ~ThreadLocalVariable()
+    {
+        pthread_key_delete(m_key);
+    }
+
+    Type &operator=(const Type &other)
+    {
+        Type &reference = Reference(true);
+        reference = other;
+        return reference;
+    }
+
+    bool IsNull() const
+    {
+        return pthread_getspecific(m_key) == NULL;
+    }
+
+    Type& operator*()
+    {
+        return Reference();
+    }
+
+    const Type& operator*() const
+    {
+        return Reference();
+    }
+
+    const Type* operator->() const
+    {
+        return &Reference();
+    }
+
+    Type* operator->()
+    {
+        return &Reference();
+    }
+
+    bool operator!() const
+    {
+        return IsNull();
+    }
+
+    void Reset()
+    {
+        ManagedValue *specific =
+            static_cast<ManagedValue *>(pthread_getspecific(m_key));
+
+        if (!specific) {
+            return;
+        }
+
+        // TODO Should be an assert? is it developers fault to Reset Guarded
+        // value?
+        specific->guardKey = boost::optional<pthread_key_t>();
+
+        InternalDestroy(specific);
+
+        int result = pthread_setspecific(m_key, NULL);
+
+        Assert(result == 0 &&
+               "Failed to reset thread local variable");
+    }
+
+    // GuardValue(true) allows to defer destroy (by pthread internal
+    // functionality) thread specific value until GuardValue(false) will be
+    // called.
+    void GuardValue(bool guard)
+    {
+        ManagedValue *instance =
+            static_cast<ManagedValue *>(pthread_getspecific(m_key));
+
+        Assert(instance && "Failed to get the value");
+
+        instance->guardKey = guard ? m_key : boost::optional<pthread_key_t>();
+    }
+};
+} // namespace DPL
+
+#endif // DPL_THREAD_H
diff --git a/commons/modules/core/include/dpl/type_list.h b/commons/modules/core/include/dpl/type_list.h
new file mode 100644 (file)
index 0000000..88afaf2
--- /dev/null
@@ -0,0 +1,159 @@
+/*
+ * 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        type_list.h
+ * @author      Bartosz Janiak (b.janiak@samsung.com)
+ * @version     1.0
+ * @brief       Generic type list template
+ */
+#ifndef DPL_TYPE_LIST_H
+#define DPL_TYPE_LIST_H
+
+#include <cstddef>
+
+namespace DPL {
+class TypeListGuard
+{
+  public:
+    template<size_t Index>
+    struct Element
+    {
+        struct ERROR_TypeListElementIndexIsOutOfBounds;
+        typedef ERROR_TypeListElementIndexIsOutOfBounds Type;
+    };
+
+    static const size_t Size = 0;
+};
+
+template<typename HeadType, typename TailType>
+class TypeList
+{
+  private:
+    class DummyClass
+    {};
+
+    template<typename List, size_t Enum>
+    struct TypeCounter : public TypeCounter<typename List::Tail, Enum + 1>
+    {};
+
+    template<size_t Enum>
+    struct TypeCounter<TypeListGuard, Enum>
+    {
+        static const size_t Size = Enum;
+    };
+
+  public:
+    typedef TailType Tail;
+    typedef HeadType Head;
+    typedef TypeList<HeadType, TailType> ThisType;
+
+    template<size_t Index, typename DummyType = DummyClass>
+    struct Element
+    {
+        typedef typename TailType::template Element<Index - 1>::Type Type;
+    };
+
+    template<typename DummyType>
+    struct Element<0, DummyType>
+    {
+        typedef HeadType Type;
+    };
+
+    template<typename Type, typename DummyType = DummyClass>
+    struct Contains
+    {
+        typedef typename TailType::template Contains<Type>::Yes Yes;
+    };
+
+    template<typename DummyType>
+    struct Contains<HeadType, DummyType>
+    {
+        typedef int Yes;
+    };
+
+    static const size_t Size = TypeCounter<ThisType, 0>::Size;
+};
+
+template<typename T1 = TypeListGuard, typename T2 = TypeListGuard,
+         typename T3 = TypeListGuard, typename T4 = TypeListGuard,
+         typename T5 = TypeListGuard, typename T6 = TypeListGuard,
+         typename T7 = TypeListGuard, typename T8 = TypeListGuard,
+         typename T9 = TypeListGuard, typename T10 = TypeListGuard,
+         typename T11 = TypeListGuard, typename T12 = TypeListGuard,
+         typename T13 = TypeListGuard, typename T14 = TypeListGuard,
+         typename T15 = TypeListGuard, typename T16 = TypeListGuard,
+         typename T17 = TypeListGuard, typename T18 = TypeListGuard,
+         typename T19 = TypeListGuard, typename T20 = TypeListGuard,
+         typename T21 = TypeListGuard, typename T22 = TypeListGuard,
+         typename T23 = TypeListGuard, typename T24 = TypeListGuard,
+         typename T25 = TypeListGuard, typename T26 = TypeListGuard,
+         typename T27 = TypeListGuard, typename T28 = TypeListGuard,
+         typename T29 = TypeListGuard, typename T30 = TypeListGuard,
+         typename T31 = TypeListGuard, typename T32 = TypeListGuard,
+         typename T33 = TypeListGuard, typename T34 = TypeListGuard,
+         typename T35 = TypeListGuard, typename T36 = TypeListGuard,
+         typename T37 = TypeListGuard, typename T38 = TypeListGuard,
+         typename T39 = TypeListGuard, typename T40 = TypeListGuard,
+         typename T41 = TypeListGuard, typename T42 = TypeListGuard,
+         typename T43 = TypeListGuard, typename T44 = TypeListGuard,
+         typename T45 = TypeListGuard, typename T46 = TypeListGuard,
+         typename T47 = TypeListGuard, typename T48 = TypeListGuard,
+         typename T49 = TypeListGuard, typename T50 = TypeListGuard,
+         typename T51 = TypeListGuard, typename T52 = TypeListGuard,
+         typename T53 = TypeListGuard, typename T54 = TypeListGuard,
+         typename T55 = TypeListGuard, typename T56 = TypeListGuard,
+         typename T57 = TypeListGuard, typename T58 = TypeListGuard,
+         typename T59 = TypeListGuard, typename T60 = TypeListGuard,
+         typename T61 = TypeListGuard, typename T62 = TypeListGuard,
+         typename T63 = TypeListGuard, typename T64 = TypeListGuard>
+struct TypeListDecl
+{
+    typedef TypeList<T1,
+                     typename TypeListDecl<
+                         T2, T3, T4, T5, T6, T7, T8,
+                         T9, T10, T11, T12, T13, T14, T15,
+                         T16, T17, T18, T19, T20, T21, T22,
+                         T23, T24, T25, T26, T27, T28, T29,
+                         T30, T31, T32, T33, T34, T35, T36,
+                         T37, T38, T39, T40, T41, T42, T43,
+                         T44, T45, T46, T47, T48, T49, T50,
+                         T51, T52, T53, T54, T55, T56, T57,
+                         T58, T59, T60, T61, T62, T63, T64>::Type> Type;
+};
+
+template<>
+struct TypeListDecl<TypeListGuard, TypeListGuard, TypeListGuard, TypeListGuard,
+                    TypeListGuard, TypeListGuard, TypeListGuard, TypeListGuard,
+                    TypeListGuard, TypeListGuard, TypeListGuard, TypeListGuard,
+                    TypeListGuard, TypeListGuard, TypeListGuard, TypeListGuard,
+                    TypeListGuard, TypeListGuard, TypeListGuard, TypeListGuard,
+                    TypeListGuard, TypeListGuard, TypeListGuard, TypeListGuard,
+                    TypeListGuard, TypeListGuard, TypeListGuard, TypeListGuard,
+                    TypeListGuard, TypeListGuard, TypeListGuard, TypeListGuard,
+                    TypeListGuard, TypeListGuard, TypeListGuard, TypeListGuard,
+                    TypeListGuard, TypeListGuard, TypeListGuard, TypeListGuard,
+                    TypeListGuard, TypeListGuard, TypeListGuard, TypeListGuard,
+                    TypeListGuard, TypeListGuard, TypeListGuard, TypeListGuard,
+                    TypeListGuard, TypeListGuard, TypeListGuard, TypeListGuard,
+                    TypeListGuard, TypeListGuard, TypeListGuard, TypeListGuard,
+                    TypeListGuard, TypeListGuard, TypeListGuard, TypeListGuard,
+                    TypeListGuard, TypeListGuard, TypeListGuard, TypeListGuard>
+{
+    typedef TypeListGuard Type;
+};
+} // namespace DPL
+
+#endif // DPL_TYPE_LIST_H
diff --git a/commons/modules/core/include/dpl/waitable_event.h b/commons/modules/core/include/dpl/waitable_event.h
new file mode 100644 (file)
index 0000000..364bc5c
--- /dev/null
@@ -0,0 +1,59 @@
+/*
+ * 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        waitable_event.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of waitable event
+ */
+#ifndef DPL_WAITABLE_EVENT_H
+#define DPL_WAITABLE_EVENT_H
+
+#include <dpl/waitable_handle.h>
+#include <dpl/noncopyable.h>
+#include <dpl/exception.h>
+#include <vector>
+
+namespace DPL {
+class WaitableEvent :
+    private Noncopyable
+{
+  public:
+    class Exception
+    {
+      public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, CreateFailed)
+        DECLARE_EXCEPTION_TYPE(Base, DestroyFailed)
+        DECLARE_EXCEPTION_TYPE(Base, SignalFailed)
+        DECLARE_EXCEPTION_TYPE(Base, ResetFailed)
+    };
+
+  private:
+    int m_pipe[2];
+
+  public:
+    WaitableEvent();
+    virtual ~WaitableEvent();
+
+    WaitableHandle GetHandle() const;
+
+    void Signal() const;
+    void Reset() const;
+};
+} // namespace DPL
+
+#endif // DPL_WAITABLE_EVENT_H
diff --git a/commons/modules/core/include/dpl/waitable_handle.h b/commons/modules/core/include/dpl/waitable_handle.h
new file mode 100644 (file)
index 0000000..9864f78
--- /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        waitable_handle.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the header file of waitable handle
+ */
+#ifndef DPL_WAITABLE_HANDLE_H
+#define DPL_WAITABLE_HANDLE_H
+
+#include <dpl/noncopyable.h>
+#include <dpl/exception.h>
+#include <vector>
+
+namespace DPL {
+/**
+ * Waitable unix wait handle definition
+ */
+typedef int WaitableHandle;
+
+/**
+ * Waitable handle list
+ */
+typedef std::vector<WaitableHandle> WaitableHandleList;
+
+/**
+ * Wait mode
+ */
+class WaitMode
+{
+  public:
+    enum Type
+    {
+        Read,  ///< Wait for readability state changes
+        Write  ///< Wait for writability state changes
+    };
+};
+
+/**
+ * Waitable handle list ex
+ */
+typedef std::vector<std::pair<WaitableHandle,
+                              WaitMode::Type> > WaitableHandleListEx;
+
+/**
+ * Waitable handle index list
+ */
+typedef std::vector<size_t> WaitableHandleIndexList;
+
+/**
+ * Wait exceptions
+ */
+DECLARE_EXCEPTION_TYPE(DPL::Exception, WaitFailed)
+
+/**
+ * Wait for single handle readability
+ * Convience function.
+ *
+ * @return Signaled waitable handle index list
+ * @throw WaitFailed Fatal error occurred while waiting for signal
+ */
+WaitableHandleIndexList WaitForSingleHandle(
+    WaitableHandle handle,
+    unsigned long miliseconds =
+        0xFFFFFFFF);
+
+/**
+ * Wait for single handle
+ * Convience function.
+ *
+ * @return Signaled waitable handle index list
+ * @throw WaitFailed Fatal error occurred while waiting for signal
+ */
+WaitableHandleIndexList WaitForSingleHandle(
+    WaitableHandle handle,
+    WaitMode::Type mode,
+    unsigned long miliseconds =
+        0xFFFFFFFF);
+
+/**
+ * Wait for multiple handles readability
+ *
+ * @return Signaled waitable handle index list
+ * @throw WaitFailed Fatal error occurred while waiting for signal
+ */
+WaitableHandleIndexList WaitForMultipleHandles(
+    const WaitableHandleList &handleList,
+    unsigned long miliseconds = 0xFFFFFFFF);
+
+/**
+ * Wait for multiple handles readability
+ *
+ * @return Signaled waitable handle index list
+ * @throw WaitFailed Fatal error occurred while waiting for signal
+ */
+WaitableHandleIndexList WaitForMultipleHandles(
+    const WaitableHandleListEx &handleListEx,
+    unsigned long miliseconds = 0xFFFFFFFF);
+} // namespace DPL
+
+#endif // DPL_WAITABLE_HANDLE_H
diff --git a/commons/modules/core/include/dpl/waitable_handle_watch_support.h b/commons/modules/core/include/dpl/waitable_handle_watch_support.h
new file mode 100644 (file)
index 0000000..18eed6b
--- /dev/null
@@ -0,0 +1,122 @@
+/*
+ * 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        waitable_handle_watch_support.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of waitable handle watch
+ * support
+ */
+#ifndef DPL_WAITABLE_HANDLE_WATCH_SUPPORT_H
+#define DPL_WAITABLE_HANDLE_WATCH_SUPPORT_H
+
+#include <dpl/waitable_event.h>
+#include <dpl/waitable_handle.h>
+#include <dpl/exception.h>
+#include <list>
+#include <map>
+#include <mutex>
+
+namespace DPL {
+class Thread;
+
+class WaitableHandleWatchSupport
+{
+  public:
+    class WaitableHandleListener
+    {
+      public:
+        virtual ~WaitableHandleListener() {}
+
+        virtual void OnWaitableHandleEvent(WaitableHandle waitableHandle,
+                                           WaitMode::Type mode) = 0;
+    };
+
+  protected:
+    // Invoker waitable handle
+    // Signaled by Add/Remove methods
+    // After being signaled one must call Handle invoke to reset invoker
+    WaitableHandle WaitableInvokerHandle() const;
+
+    // Waitable handle ex list
+    WaitableHandleListEx WaitableWatcherHandles() const;
+
+    // Perform actions for signaled waitable handle
+    // Called in execution context, after
+    void HandleWatcher(WaitableHandle waitableHandle, WaitMode::Type mode);
+
+    // Perform actions after invoker was signaled
+    void InvokerFinished();
+
+    // Get invoker context
+    virtual Thread *GetInvokerThread() = 0;
+
+    // Invoke direct invoker
+    virtual void HandleDirectInvoker() = 0;
+
+  private:
+    // Waitable event watchers
+    struct WaitableHandleWatcher
+    {
+        WaitableHandleListener *listener;
+        WaitMode::Type mode;
+
+        WaitableHandleWatcher(WaitableHandleListener *l, WaitMode::Type m) :
+            listener(l),
+            mode(m)
+        {}
+    };
+
+    typedef std::list<WaitableHandleWatcher> WaitableHandleListenerList;
+
+    struct WaitableHandleWatchers
+    {
+        WaitableHandleListenerList listeners;
+        size_t readListenersCount;
+        size_t writeListenersCount;
+
+        WaitableHandleWatchers() :
+            readListenersCount(0),
+            writeListenersCount(0)
+        {}
+    };
+
+    typedef std::map<WaitableHandle,
+                     WaitableHandleWatchers> WaitableHandleWatchersMap;
+
+    // Waitable event watch support
+    mutable std::recursive_mutex m_watchersMutex;
+    WaitableHandleWatchersMap m_watchersMap;
+    WaitableEvent m_watchersInvoker;
+    WaitableEvent m_watchersInvokerCommit;
+
+    // Invoke call
+    void CommitInvoker();
+
+  public:
+    /**
+     * Constructor
+     */
+    explicit WaitableHandleWatchSupport();
+
+    /**
+     * Destructor
+     */
+    virtual ~WaitableHandleWatchSupport();
+};
+} // namespace DPL
+
+#endif // DPL_WAITABLE_HANDLE_WATCH_SUPPORT_H
diff --git a/commons/modules/core/include/dpl/workaround.h b/commons/modules/core/include/dpl/workaround.h
new file mode 100644 (file)
index 0000000..19c26ef
--- /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        workaround.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the header file of workaround
+ */
+#ifndef DPL_WORKAROUND_H
+#define DPL_WORKAROUND_H
+
+/**
+ * Define following macro to track invalid waitable handles
+ * in WaitForSingle/WaitForMultiple functions
+ */
+#define DPL_ENABLE_WAITABLE_HANDLE_BADF_CHECK
+
+/**
+ * Define following macro to enable workaround for problem
+ * with GLIB loop integration and EBADF error handling
+ */
+#define DPL_ENABLE_GLIB_LOOP_INTEGRATION_WORKAROUND
+
+/**
+ * Define following macro to enable workaround for problem
+ * with invalid conversions in htons/ntohs macros
+ */
+#define DPL_ENABLE_HTONS_NTOHS_I386_WORKAROUND
+
+#endif // DPL_WORKAROUND_H
diff --git a/commons/modules/core/src/DESCRIPTION b/commons/modules/core/src/DESCRIPTION
new file mode 100644 (file)
index 0000000..9043c93
--- /dev/null
@@ -0,0 +1 @@
+Source files
diff --git a/commons/modules/core/src/assert.cpp b/commons/modules/core/src/assert.cpp
new file mode 100644 (file)
index 0000000..5a18977
--- /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        assert.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of assert
+ */
+#include <stdio.h>
+#include <stddef.h>
+#include <dpl/assert.h>
+#include <dpl/colors.h>
+#include <dpl/log/log.h>
+#include <cstdlib>
+
+namespace DPL {
+void AssertProc(const char *condition,
+                const char *file,
+                int line,
+                const char *function)
+{
+#define INTERNAL_LOG(message)                                          \
+    do                                                                 \
+    {                                                                  \
+        std::ostringstream platformLog;                                \
+        platformLog << message;                                        \
+        DPL::Log::LogSystemSingleton::Instance().Pedantic(             \
+            platformLog.str().c_str(),                                 \
+            __FILE__, __LINE__, __FUNCTION__);                         \
+    } \
+    while (0)
+
+    // Try to log failed assertion to log system
+    Try
+    {
+        INTERNAL_LOG(
+            "################################################################################");
+        INTERNAL_LOG(
+            "###                          DPL assertion failed!                           ###");
+        INTERNAL_LOG(
+            "################################################################################");
+        INTERNAL_LOG("### Condition: " << condition);
+        INTERNAL_LOG("### File: " << file);
+        INTERNAL_LOG("### Line: " << line);
+        INTERNAL_LOG("### Function: " << function);
+        INTERNAL_LOG(
+            "################################################################################");
+    } catch (Exception) {
+        // Just ignore possible double errors
+    }
+
+    // print assertion message to stderr
+    fprintf(stderr, "Assert!! [%s:%s] %s\n", file, function, condition);
+
+    // Fail with c-library abort
+    abort();
+}
+} // namespace DPL
diff --git a/commons/modules/core/src/colors.cpp b/commons/modules/core/src/colors.cpp
new file mode 100644 (file)
index 0000000..0b2fcd4
--- /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 DPL {
+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 DPL
diff --git a/commons/modules/core/src/errno_string.cpp b/commons/modules/core/src/errno_string.cpp
new file mode 100644 (file)
index 0000000..6c59776
--- /dev/null
@@ -0,0 +1,99 @@
+/*
+ * 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        errno_string.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of errno string
+ */
+#include <stddef.h>
+#include <dpl/errno_string.h>
+#include <dpl/assert.h>
+#include <dpl/exception.h>
+#include <dpl/assert.h>
+#include <dpl/free_deleter.h>
+#include <memory>
+#include <string>
+#include <cstddef>
+#include <cstring>
+#include <malloc.h>
+#include <cerrno>
+#include <stdexcept>
+
+namespace DPL {
+namespace // anonymous
+{
+const size_t DEFAULT_ERRNO_STRING_SIZE = 32;
+} // namespace anonymous
+
+std::string GetErrnoString(int error)
+{
+    size_t size = DEFAULT_ERRNO_STRING_SIZE;
+    char *buffer = NULL;
+
+    for (;;) {
+        // Add one extra characted for end of string null value
+        char *newBuffer = static_cast<char *>(::realloc(buffer, size + 1));
+
+        if (!newBuffer) {
+            // Failed to realloc
+            ::free(buffer);
+            throw std::bad_alloc();
+        }
+
+        // Setup reallocated buffer
+        buffer = newBuffer;
+        ::memset(buffer, 0, size + 1);
+
+        // Try to retrieve error string
+#if (_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && !_GNU_SOURCE
+        // The XSI-compliant version of strerror_r() is provided if:
+        int result = ::strerror_r(error, buffer, size);
+
+        if (result == 0) {
+            std::unique_ptr<char[],free_deleter> scopedBufferFree(buffer);
+            return std::string(buffer);
+        }
+#else
+        errno = 0;
+
+        // Otherwise, the GNU-specific version is provided.
+        char *result = ::strerror_r(error, buffer, size);
+
+        if (result != NULL) {
+            std::unique_ptr<char[],free_deleter> scopedBufferFree(buffer);
+            return std::string(result);
+        }
+#endif
+
+        // Interpret errors
+        switch (errno) {
+        case EINVAL:
+            // We got an invalid errno value
+                ::free(buffer);
+            ThrowMsg(InvalidErrnoValue, "Invalid errno value: " << error);
+
+        case ERANGE:
+            // Incease buffer size and retry
+            size <<= 1;
+            continue;
+
+        default:
+            AssertMsg(0, "Invalid errno value after call to strerror_r!");
+        }
+    }
+}
+} // namespace DPL
diff --git a/commons/modules/core/src/exception.cpp b/commons/modules/core/src/exception.cpp
new file mode 100644 (file)
index 0000000..4d63cc1
--- /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 <stddef.h>
+#include <dpl/exception.h>
+#include <dpl/log/log.h>
+
+namespace DPL {
+Exception* Exception::m_lastException = NULL;
+unsigned int Exception::m_exceptionCount = 0;
+void (*Exception::m_terminateHandler)() = NULL;
+
+void LogUnhandledException(const std::string &str)
+{
+    // Logging to dlog
+    LogPedantic(str);
+}
+
+void LogUnhandledException(const std::string &str,
+                           const char *filename,
+                           int line,
+                           const char *function)
+{
+    // Logging to dlog
+    DPL::Log::LogSystemSingleton::Instance().Error(
+        str.c_str(), filename, line, function);
+}
+} // namespace DPL
diff --git a/commons/modules/core/src/mutex.cpp b/commons/modules/core/src/mutex.cpp
new file mode 100644 (file)
index 0000000..eed1f2e
--- /dev/null
@@ -0,0 +1,92 @@
+/*
+ * 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        mutex.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of mutex
+ */
+#include <stddef.h>
+#include <dpl/mutex.h>
+#include <dpl/assert.h>
+#include <dpl/log/log.h>
+#include <errno.h>
+
+namespace DPL {
+Mutex::Mutex()
+{
+    if (pthread_mutex_init(&m_mutex, NULL) != 0) {
+        int error = errno;
+
+        LogPedantic("Failed to create mutex. Errno: " << error);
+
+        ThrowMsg(Exception::CreateFailed,
+                 "Failed to create mutex. Errno: " << error);
+    }
+}
+
+Mutex::~Mutex()
+{
+    if (pthread_mutex_destroy(&m_mutex) != 0) {
+        int error = errno;
+
+        LogPedantic("Failed to destroy mutex. Errno: " << error);
+    }
+}
+
+void Mutex::Lock() const
+{
+    if (pthread_mutex_lock(&m_mutex) != 0) {
+        int error = errno;
+
+        LogPedantic("Failed to lock mutex. Errno: " << error);
+
+        ThrowMsg(Exception::LockFailed,
+                 "Failed to lock mutex. Errno: " << error);
+    }
+}
+
+void Mutex::Unlock() const
+{
+    if (pthread_mutex_unlock(&m_mutex) != 0) {
+        int error = errno;
+
+        LogPedantic("Failed to unlock mutex. Errno: " << error);
+
+        ThrowMsg(Exception::UnlockFailed,
+                 "Failed to unlock mutex. Errno: " << error);
+    }
+}
+
+Mutex::ScopedLock::ScopedLock(Mutex *mutex) :
+    m_mutex(mutex)
+{
+    Assert(mutex != NULL);
+    m_mutex->Lock();
+}
+
+Mutex::ScopedLock::~ScopedLock()
+{
+    Try
+    {
+        m_mutex->Unlock();
+    }
+    Catch(Mutex::Exception::UnlockFailed)
+    {
+        LogPedantic("Failed to leave mutex scoped lock");
+    }
+}
+} // namespace DPL
diff --git a/commons/modules/core/src/noncopyable.cpp b/commons/modules/core/src/noncopyable.cpp
new file mode 100644 (file)
index 0000000..9453655
--- /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        noncopyable.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of noncopyable
+ */
+#include <stddef.h>
+#include <dpl/noncopyable.h>
+
+namespace DPL {
+Noncopyable::Noncopyable()
+{}
+
+Noncopyable::~Noncopyable()
+{}
+} // namespace DPL
diff --git a/commons/modules/core/src/recursive_mutex.cpp b/commons/modules/core/src/recursive_mutex.cpp
new file mode 100644 (file)
index 0000000..234d25f
--- /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        recursive_mutex.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of recursive mutex
+ */
+#include <stddef.h>
+#include <dpl/recursive_mutex.h>
+#include <dpl/assert.h>
+
+namespace DPL {
+RecursiveMutex::RecursiveMutex()
+{
+    pthread_mutexattr_t attr;
+
+    pthread_mutexattr_init(&attr);
+    pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE);
+
+    if (pthread_mutex_init(&m_mutex, &attr) != 0) {
+        Throw(Exception::CreateFailed);
+    }
+}
+
+RecursiveMutex::~RecursiveMutex()
+{
+    if (pthread_mutex_destroy(&m_mutex) != 0) {
+        Throw(Exception::DestroyFailed);
+    }
+}
+
+void RecursiveMutex::Lock() const
+{
+    if (pthread_mutex_lock(&m_mutex) != 0) {
+        Throw(Exception::LockFailed);
+    }
+}
+
+void RecursiveMutex::Unlock() const
+{
+    if (pthread_mutex_unlock(&m_mutex) != 0) {
+        Throw(Exception::UnlockFailed);
+    }
+}
+
+RecursiveMutex::ScopedLock::ScopedLock(RecursiveMutex *mutex) :
+    m_mutex(mutex)
+{
+    Assert(mutex != NULL);
+    m_mutex->Lock();
+}
+
+RecursiveMutex::ScopedLock::~ScopedLock()
+{
+    m_mutex->Unlock();
+}
+} // namespace DPL
diff --git a/commons/modules/core/src/serialization.cpp b/commons/modules/core/src/serialization.cpp
new file mode 100644 (file)
index 0000000..f8f05ff
--- /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        serialization.cpp
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of data serialization.
+ */
+#include <stddef.h>
+#include <dpl/serialization.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/commons/modules/core/src/single_instance.cpp b/commons/modules/core/src/single_instance.cpp
new file mode 100644 (file)
index 0000000..274b5f8
--- /dev/null
@@ -0,0 +1,125 @@
+/*
+ * 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        single_instance.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of single instance
+ */
+#include <stddef.h>
+#include <dpl/single_instance.h>
+#include <dpl/log/log.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <dpl/assert.h>
+
+namespace DPL {
+namespace // anonumous
+{
+const char *LOCK_PREFIX_PATH = "/tmp/dpl_single_instance_";
+}
+SingleInstance::SingleInstance() :
+    m_locked(false),
+    m_fdLock(-1)
+{}
+
+SingleInstance::~SingleInstance()
+{
+    AssertMsg(!m_locked, "Single instance must be released before exit!");
+}
+
+bool SingleInstance::TryLock(const std::string &lockName)
+{
+    LogPedantic("Locking single instance: " << lockName);
+
+    struct flock lock;
+
+    lock.l_type = F_WRLCK;
+    lock.l_whence = SEEK_SET;
+    lock.l_start = 0;
+    lock.l_len = 1;
+
+    // Open lock file
+    m_fdLock =
+        TEMP_FAILURE_RETRY(open((std::string(LOCK_PREFIX_PATH) +
+                                 lockName).c_str(),
+                                O_WRONLY | O_CREAT, 0666));
+
+    if (m_fdLock == -1) {
+        ThrowMsg(Exception::LockError, "Cannot open single instance lock file!");
+    }
+
+    // Lock file
+    int result = TEMP_FAILURE_RETRY(fcntl(m_fdLock, F_SETLK, &lock));
+
+    // Was the instance successfuly locked ?
+    if (result == 0) {
+        LogPedantic("Instance locked: " << lockName);
+
+        // It is locked now
+        m_locked = true;
+
+        // Done
+        return true;
+    }
+
+    if (errno == EACCES || errno == EAGAIN) {
+        LogPedantic("Instance is already running: " << lockName);
+        return false;
+    }
+
+    // This is lock error
+    ThrowMsg(Exception::LockError, "Cannot lock single instance lock file!");
+}
+
+void SingleInstance::Release()
+{
+    if (!m_locked) {
+        return;
+    }
+
+    LogPedantic("Unlocking single instance");
+
+    // Unlock file
+    struct flock lock;
+
+    lock.l_type = F_UNLCK;
+    lock.l_whence = SEEK_SET;
+    lock.l_start = 0;
+    lock.l_len = 1;
+
+    int result = TEMP_FAILURE_RETRY(fcntl(m_fdLock, F_SETLK, &lock));
+
+    // Was the instance successfuly unlocked ?
+    if (result == -1) {
+        ThrowMsg(Exception::LockError,
+                 "Cannot unlock single instance lock file!");
+    }
+
+    // Close lock file
+    if (TEMP_FAILURE_RETRY(close(m_fdLock)) == -1) {
+        ThrowMsg(Exception::LockError,
+                 "Cannot close single instance lock file!");
+    }
+
+    m_fdLock = -1;
+
+    // Done
+    m_locked = false;
+    LogPedantic("Instance unlocked");
+}
+} // namespace DPL
diff --git a/commons/modules/core/src/singleton.cpp b/commons/modules/core/src/singleton.cpp
new file mode 100644 (file)
index 0000000..a76e8ac
--- /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        generic_event.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/commons/modules/core/src/string.cpp b/commons/modules/core/src/string.cpp
new file mode 100644 (file)
index 0000000..a642eaa
--- /dev/null
@@ -0,0 +1,250 @@
+/*
+ * 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        string.cpp
+ * @author      Piotr Marcinkiewicz (p.marcinkiew@samsung.com)
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ */
+#include <stddef.h>
+#include <memory>
+#include <dpl/string.h>
+#include <dpl/char_traits.h>
+#include <dpl/errno_string.h>
+#include <dpl/exception.h>
+#include <dpl/log/log.h>
+#include <string>
+#include <vector>
+#include <algorithm>
+#include <cstring>
+#include <errno.h>
+#include <iconv.h>
+#include <unicode/ustring.h>
+
+// TODO: Completely move to ICU
+namespace DPL {
+namespace //anonymous
+{
+class ASCIIValidator
+{
+    const std::string& m_TestedString;
+
+  public:
+    ASCIIValidator(const std::string& aTestedString);
+
+    void operator()(char aCharacter) const;
+};
+
+ASCIIValidator::ASCIIValidator(const std::string& aTestedString) :
+    m_TestedString(aTestedString)
+{}
+
+void ASCIIValidator::operator()(char aCharacter) const
+{
+    // Check for ASCII data range
+    if (aCharacter <= 0) {
+        ThrowMsg(
+            StringException::InvalidASCIICharacter,
+            "invalid character code " << static_cast<int>(aCharacter)
+                                      << " from string [" <<
+            m_TestedString
+                                      << "] passed as ASCII");
+    }
+}
+
+const iconv_t gc_IconvOperError = reinterpret_cast<iconv_t>(-1);
+const size_t gc_IconvConvertError = static_cast<size_t>(-1);
+} // namespace anonymous
+
+String FromUTF8String(const std::string& aIn)
+{
+    if (aIn.empty()) {
+        return String();
+    }
+
+    size_t inbytes = aIn.size();
+
+    // Default iconv UTF-32 module adds BOM (4 bytes) in from of string
+    // The worst case is when 8bit UTF-8 char converts to 32bit UTF-32
+    // newsize = oldsize * 4 + end + bom
+    // newsize - bytes for UTF-32 string
+    // oldsize - letters in UTF-8 string
+    // end - end character for UTF-32 (\0)
+    // bom - Unicode header in front of string (0xfeff)
+    size_t outbytes = sizeof(wchar_t) * (inbytes + 2);
+    std::vector<wchar_t> output(inbytes + 2, 0);
+
+    size_t outbytesleft = outbytes;
+    char* inbuf = const_cast<char*>(aIn.c_str());
+
+    // vector is used to provide buffer for iconv which expects char* buffer
+    // but during conversion from UTF32 uses internaly wchar_t
+    char* outbuf = reinterpret_cast<char*>(&output[0]);
+
+    iconv_t iconvHandle = iconv_open("UTF-32", "UTF-8");
+
+    if (gc_IconvOperError == iconvHandle) {
+        int error = errno;
+
+        ThrowMsg(StringException::IconvInitErrorUTF8ToUTF32,
+                 "iconv_open failed for " << "UTF-32 <- UTF-8" <<
+                 "error: " << GetErrnoString(error));
+    }
+
+    size_t iconvRet = iconv(iconvHandle,
+                            &inbuf,
+                            &inbytes,
+                            &outbuf,
+                            &outbytesleft);
+
+    iconv_close(iconvHandle);
+
+    if (gc_IconvConvertError == iconvRet) {
+        ThrowMsg(StringException::IconvConvertErrorUTF8ToUTF32,
+                 "iconv failed for " << "UTF-32 <- UTF-8" << "error: "
+                                     << GetErrnoString());
+    }
+
+    // Ignore BOM in front of UTF-32
+    return &output[1];
+}
+
+std::string ToUTF8String(const DPL::String& aIn)
+{
+    if (aIn.empty()) {
+        return std::string();
+    }
+
+    size_t inbytes = aIn.size() * sizeof(wchar_t);
+    size_t outbytes = inbytes + sizeof(char);
+
+    // wstring returns wchar_t but iconv expects char*
+    // iconv internally is processing input as wchar_t
+    char* inbuf = reinterpret_cast<char*>(const_cast<wchar_t*>(aIn.c_str()));
+    std::vector<char> output(inbytes, 0);
+    char* outbuf = &output[0];
+
+    size_t outbytesleft = outbytes;
+
+    iconv_t iconvHandle = iconv_open("UTF-8", "UTF-32");
+
+    if (gc_IconvOperError == iconvHandle) {
+        ThrowMsg(StringException::IconvInitErrorUTF32ToUTF8,
+                 "iconv_open failed for " << "UTF-8 <- UTF-32"
+                                          << "error: " << GetErrnoString());
+    }
+
+    size_t iconvRet = iconv(iconvHandle,
+                            &inbuf,
+                            &inbytes,
+                            &outbuf,
+                            &outbytesleft);
+
+    iconv_close(iconvHandle);
+
+    if (gc_IconvConvertError == iconvRet) {
+        ThrowMsg(StringException::IconvConvertErrorUTF32ToUTF8,
+                 "iconv failed for " << "UTF-8 <- UTF-32"
+                                     << "error: " << GetErrnoString());
+    }
+
+    return &output[0];
+}
+
+String FromASCIIString(const std::string& aString)
+{
+    String output;
+
+    std::for_each(aString.begin(), aString.end(), ASCIIValidator(aString));
+    std::copy(aString.begin(), aString.end(), std::back_inserter<String>(output));
+
+    return output;
+}
+
+String FromUTF32String(const std::wstring& aString)
+{
+    return String(&aString[0]);
+}
+
+static UChar *ConvertToICU(const String &inputString)
+{
+    std::unique_ptr<UChar[]> outputString;
+    int32_t size = 0;
+    int32_t convertedSize = 0;
+    UErrorCode error = U_ZERO_ERROR;
+
+    // Calculate size of output string
+    ::u_strFromWCS(NULL,
+                   0,
+                   &size,
+                   inputString.c_str(),
+                   -1,
+                   &error);
+
+    if (error == U_ZERO_ERROR ||
+        error == U_BUFFER_OVERFLOW_ERROR)
+    {
+        // What buffer size is ok ?
+        LogPedantic("ICU: Output buffer size: " << size);
+    } else {
+        ThrowMsg(StringException::ICUInvalidCharacterFound,
+                 "ICU: Failed to retrieve output string size. Error: "
+                 << error);
+    }
+
+    // Allocate proper buffer
+    outputString.reset(new UChar[size + 1]);
+    ::memset(outputString.get(), 0, sizeof(UChar) * (size + 1));
+
+    error = U_ZERO_ERROR;
+
+    // Do conversion
+    ::u_strFromWCS(outputString.get(),
+                   size + 1,
+                   &convertedSize,
+                   inputString.c_str(),
+                   -1,
+                   &error);
+
+    if (!U_SUCCESS(error)) {
+        ThrowMsg(StringException::ICUInvalidCharacterFound,
+                 "ICU: Failed to convert string. Error: " << error);
+    }
+
+    // Done
+    return outputString.release();
+}
+
+int StringCompare(const String &left,
+                  const String &right,
+                  bool caseInsensitive)
+{
+    // Convert input strings
+    std::unique_ptr<UChar[]> leftICU(ConvertToICU(left));
+    std::unique_ptr<UChar[]> rightICU(ConvertToICU(right));
+
+    if (caseInsensitive) {
+        return static_cast<int>(u_strcasecmp(leftICU.get(), rightICU.get(), 0));
+    } else {
+        return static_cast<int>(u_strcmp(leftICU.get(), rightICU.get()));
+    }
+}
+} //namespace DPL
+
+std::ostream& operator<<(std::ostream& aStream, const DPL::String& aString)
+{
+    return aStream << DPL::ToUTF8String(aString);
+}
diff --git a/commons/modules/core/src/thread.cpp b/commons/modules/core/src/thread.cpp
new file mode 100644 (file)
index 0000000..6b6790f
--- /dev/null
@@ -0,0 +1,619 @@
+/*
+ * 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        thread.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of thread
+ */
+#include <stddef.h>
+#include <dpl/thread.h>
+#include <dpl/log/log.h>
+#include <sys/time.h>
+#include <algorithm>
+#include <dpl/assert.h>
+#include <errno.h>
+#include <time.h>
+#include <string.h>
+
+namespace // anonymous
+{
+static const size_t NANOSECONDS_PER_SECOND =
+    static_cast<uint64_t>(1000 * 1000 * 1000);
+
+static const size_t NANOSECONDS_PER_MILISECOND =
+    static_cast<uint64_t>(1000 * 1000);
+
+static const size_t NANOSECONDS_PER_MICROSECOND =
+    static_cast<uint64_t>(1000);
+
+static const std::thread::id g_mainThread = std::this_thread::get_id();
+
+class ThreadSpecific
+{
+  public:
+    pthread_key_t threadSpecific;
+
+    ThreadSpecific() :
+        threadSpecific(0)
+    {
+        threadSpecific = 0;
+        pthread_key_create(&threadSpecific, NULL);
+    }
+
+    virtual ~ThreadSpecific()
+    {
+        pthread_key_delete(threadSpecific);
+    }
+};
+
+static ThreadSpecific g_threadSpecific;
+} // namespace anonymous
+
+namespace DPL {
+bool g_TLSforMainCreated = false;
+
+Thread::Thread() :
+    m_thread(),
+    m_abandon(false),
+    m_running(false),
+    m_directInvoke(false)
+{}
+
+Thread::~Thread()
+{
+    // Ensure that we quit thread
+    // Always wait thread by yourself; if thread is still running
+    // this may be sometimes very bad. When derived, some resources
+    // may leak or be doubly freed
+    Quit();
+
+    // Remove any remainig events
+    // Thread proc is surely not running now
+    for (InternalEventList::iterator iterator = m_eventList.begin();
+         iterator != m_eventList.end();
+         ++iterator)
+    {
+        iterator->eventDeleteProc(iterator->event, iterator->userParam);
+    }
+
+    m_eventList.clear();
+}
+
+bool Thread::IsMainThread()
+{
+    return (std::this_thread::get_id() == g_mainThread);
+}
+
+Thread *Thread::GetCurrentThread()
+{
+    if (std::this_thread::get_id() == g_mainThread) {
+        return NULL;
+    }
+
+    void *threadSpecific = pthread_getspecific(g_threadSpecific.threadSpecific);
+
+    // Is this a managed thread ?
+    if (threadSpecific == NULL) {
+        Throw(Exception::UnmanagedThread);
+    }
+
+    return static_cast<Thread *>(threadSpecific);
+}
+
+void *Thread::StaticThreadEntry(void *param)
+{
+    LogPedantic("Entered static thread entry");
+
+    // Retrieve context
+    Thread *This = static_cast<Thread *>(param);
+    Assert(This != NULL);
+
+    // Set thread specific
+    int result = pthread_setspecific(g_threadSpecific.threadSpecific, This);
+
+    if (result != 0) {
+        char *errstr = NULL;
+        char errbuf[512] = {0,};
+#ifdef _GNU_SOURCE
+        errstr = strerror_r(result, errbuf, sizeof(errbuf));
+#else
+        strerror_r(result, errbuf, sizeof(errbuf));
+        errstr = errbuf;
+#endif
+        LogError("Failed to set threadSpecific. Error: " << errstr);
+    }
+
+    This->ThreadEntry();
+
+    // Critical section
+    {
+        // Leave running state
+        std::lock_guard<std::mutex> lock(This->m_stateMutex);
+
+        This->m_running = false;
+
+        // Abandon thread
+        if (This->m_abandon) {
+            LogPedantic("Thread was abandoned");
+            This->m_thread.detach();
+        } else {
+            LogPedantic("Thread is joinable");
+        }
+    }
+
+    return NULL;
+}
+
+int Thread::ThreadEntry()
+{
+    LogPedantic("Entered default thread entry");
+    return Exec();
+}
+
+void Thread::ProcessEvents()
+{
+    LogPedantic("Processing events");
+
+    // Steal current event list
+    InternalEventList stolenEvents;
+
+    // Enter event list critical section
+    {
+        std::lock_guard<std::mutex> lock(m_eventMutex);
+        m_eventList.swap(stolenEvents);
+        m_eventInvoker.Reset();
+    }
+
+    // Process event list
+    LogPedantic("Stolen " << stolenEvents.size() << " internal events");
+
+    for (InternalEventList::iterator iterator = stolenEvents.begin();
+         iterator != stolenEvents.end();
+         ++iterator)
+    {
+        // Dispatch immediate event
+        iterator->eventDispatchProc(iterator->event, iterator->userParam);
+
+        // Delete event
+        iterator->eventDeleteProc(iterator->event, iterator->userParam);
+    }
+}
+
+void Thread::ProcessTimedEvents()
+{
+    // Critical section on timed events mutex
+    {
+        std::lock_guard<std::mutex> lock(m_timedEventMutex);
+
+        // Get current time
+        unsigned long currentTimeMiliseconds = GetCurrentTimeMiliseconds();
+
+        // Info
+        LogPedantic(
+            "Processing timed events. Time now: " << currentTimeMiliseconds <<
+            " ms");
+
+        // All timed events are sorted chronologically
+        // Emit timed out events
+        while (!m_timedEventVector.empty() &&
+               currentTimeMiliseconds >=
+               m_timedEventVector.begin()->registerTimeMiliseconds +
+               m_timedEventVector.begin()->dueTimeMiliseconds)
+        {
+            // Info
+            LogPedantic(
+                "Transforming timed event into immediate event. Absolute due time: "
+                <<
+                (m_timedEventVector.begin()->registerTimeMiliseconds +
+                 m_timedEventVector.begin()->dueTimeMiliseconds) <<
+                " ms");
+
+            // Emit immediate event
+            PushEvent(m_timedEventVector.begin()->event,
+                      m_timedEventVector.begin()->eventDispatchProc,
+                      m_timedEventVector.begin()->eventDeleteProc,
+                      m_timedEventVector.begin()->userParam);
+
+            // Remove timed eventand fix heap
+            std::pop_heap(m_timedEventVector.begin(), m_timedEventVector.end());
+            m_timedEventVector.pop_back();
+        }
+    }
+}
+
+unsigned long Thread::GetCurrentTimeMiliseconds() const
+{
+    timeval tv;
+    gettimeofday(&tv, NULL);
+    return static_cast<unsigned long>(tv.tv_sec) * 1000 +
+           static_cast<unsigned long>(tv.tv_usec) / 1000;
+}
+
+int Thread::Exec()
+{
+    LogPedantic("Executing thread event processing");
+
+    const std::size_t MIN_HANDLE_LIST_SIZE = 4;
+
+    // Start processing of events
+    WaitableHandleListEx handleList;
+
+    // index 0: Quit waitable event handle
+    handleList.push_back(std::make_pair(m_quitEvent.GetHandle(), WaitMode::Read));
+
+    // index 1: Event occurred event handle
+    handleList.push_back(std::make_pair(m_eventInvoker.GetHandle(),
+                                        WaitMode::Read));
+
+    // index 2: Timed event occurred event handle
+    handleList.push_back(std::make_pair(m_timedEventInvoker.GetHandle(),
+                                        WaitMode::Read));
+
+    // index 3: Waitable handle watch support invoker
+    handleList.push_back(std::make_pair(WaitableHandleWatchSupport::
+                                            WaitableInvokerHandle(),
+                                        WaitMode::Read));
+
+    //
+    // Watch list might have been initialized before threaded started
+    // Need to fill waitable event watch list in this case
+    //
+    {
+        WaitableHandleListEx waitableHandleWatchHandles =
+            WaitableHandleWatchSupport::WaitableWatcherHandles();
+        std::copy(
+            waitableHandleWatchHandles.begin(),
+            waitableHandleWatchHandles.end(), std::back_inserter(handleList));
+    }
+
+    // Quit flag
+    bool quit = false;
+
+    while (!quit) {
+        // Retrieve minimum wait time, according to timed events list
+        unsigned long minimumWaitTime;
+
+        // Critical section on timed events mutex
+        {
+            std::lock_guard<std::mutex> lock(m_timedEventMutex);
+
+            if (!m_timedEventVector.empty()) {
+                unsigned long currentTimeMiliseconds =
+                    GetCurrentTimeMiliseconds();
+                unsigned long destinationTimeMiliseconds =
+                    m_timedEventVector.begin()->registerTimeMiliseconds +
+                    m_timedEventVector.begin()->dueTimeMiliseconds;
+
+                // Are we already late with timed event ?
+                if (currentTimeMiliseconds > destinationTimeMiliseconds) {
+                    minimumWaitTime = 0;
+                } else {
+                    minimumWaitTime = destinationTimeMiliseconds -
+                        currentTimeMiliseconds;
+                }
+            } else {
+                minimumWaitTime = 0xFFFFFFFF; // Infinity
+            }
+        }
+
+        // Info
+        LogPedantic(
+            "Thread loop minimum wait time: " << minimumWaitTime << " ms");
+
+        // Do thread waiting
+        WaitableHandleIndexList waitableHandleIndexList =
+            WaitForMultipleHandles(handleList, minimumWaitTime);
+
+        if (waitableHandleIndexList.empty()) {
+            // Timeout occurred. Process timed events.
+            LogPedantic("Timed event list elapsed invoker");
+            ProcessTimedEvents();
+            continue;
+        }
+
+        // Go through each index
+        for (WaitableHandleIndexList::const_iterator
+             waitableHandleIndexIterator = waitableHandleIndexList.begin();
+             waitableHandleIndexIterator != waitableHandleIndexList.end();
+             ++waitableHandleIndexIterator)
+        {
+            size_t index = *waitableHandleIndexIterator;
+
+            LogPedantic("Event loop triggered with index: " << index);
+
+            switch (index) {
+            case 0:
+                // Quit waitable event handle
+                quit = true;
+                break;
+
+            case 1:
+                // Event occurred event handle
+                ProcessEvents();
+
+                // Handle direct invoker
+                if (m_directInvoke) {
+                    m_directInvoke = false;
+
+                    LogPedantic("Handling direct invoker");
+
+                    // Update list
+                    while (handleList.size() > MIN_HANDLE_LIST_SIZE) {
+                        handleList.pop_back();
+                    }
+
+                    // Insert current waitable event handles instead
+                    {
+                        WaitableHandleListEx waitableHandleWatchHandles =
+                            WaitableHandleWatchSupport::WaitableWatcherHandles();
+                        std::copy(
+                            waitableHandleWatchHandles.begin(),
+                            waitableHandleWatchHandles.end(),
+                            std::back_inserter(handleList));
+                    }
+                }
+
+                // Done
+                break;
+
+            case 2:
+                // Timed event list changed
+                LogPedantic("Timed event list changed invoker");
+                ProcessTimedEvents();
+
+                // Reset timed event invoker
+                m_timedEventInvoker.Reset();
+
+                // Done
+                break;
+
+            case 3:
+                // Waitable handle watch support invoker
+                LogPedantic("Waitable handle watch invoker event occurred");
+
+                // First, remove all previous handles
+                while (handleList.size() > MIN_HANDLE_LIST_SIZE) {
+                    handleList.pop_back();
+                }
+
+                // Insert current waitable event handles instead
+                {
+                    WaitableHandleListEx waitableHandleWatchHandles =
+                        WaitableHandleWatchSupport::WaitableWatcherHandles();
+                    std::copy(
+                        waitableHandleWatchHandles.begin(),
+                        waitableHandleWatchHandles.end(),
+                        std::back_inserter(handleList));
+                }
+
+                // Handle invoker in waitable watch support
+                WaitableHandleWatchSupport::InvokerFinished();
+
+                LogPedantic("Waitable handle watch invoker event handled");
+
+                // Done
+                break;
+
+            default:
+                // Waitable event watch list
+                LogPedantic("Waitable handle watch event occurred");
+
+                // Handle event in waitable handle watch
+                {
+                    std::pair<WaitableHandle,
+                              WaitMode::Type> handle = handleList[index];
+                    WaitableHandleWatchSupport::HandleWatcher(handle.first,
+                                                              handle.second);
+                }
+
+                if (m_directInvoke) {
+                    m_directInvoke = false;
+
+                    LogPedantic("Handling direct invoker");
+
+                    // Update list
+                    while (handleList.size() > MIN_HANDLE_LIST_SIZE) {
+                        handleList.pop_back();
+                    }
+
+                    // Insert current waitable event handles instead
+                    {
+                        WaitableHandleListEx waitableHandleWatchHandles =
+                            WaitableHandleWatchSupport::
+                                WaitableWatcherHandles();
+                        std::copy(waitableHandleWatchHandles.begin(),
+                                  waitableHandleWatchHandles.end(),
+                                  std::back_inserter(handleList));
+                    }
+                }
+
+                LogPedantic("Waitable handle watch event handled");
+
+                // Done
+                break;
+            }
+        }
+    }
+
+    LogPedantic("Leaving thread event processing");
+    return 0;
+}
+
+void Thread::Run()
+{
+    LogPedantic("Running thread");
+
+    // Critical section
+    {
+        std::lock_guard<std::mutex> lock(m_stateMutex);
+
+        if (m_running) {
+            return;
+        }
+
+        try{
+            m_thread = std::thread(StaticThreadEntry,this);
+        }catch(std::system_error e){
+            Throw(Exception::RunFailed);
+        }
+
+        // At default, we abandon thread
+        m_abandon = true;
+
+        // Enter running state
+        m_running = true;
+    }
+
+    LogPedantic("Thread run");
+}
+
+void Thread::Quit()
+{
+    // Critical section
+    {
+        std::lock_guard<std::mutex> lock(m_stateMutex);
+
+        // Is thread running ?
+        if (!m_running) {
+            return;
+        }
+
+        LogPedantic("Quitting thread...");
+
+        // Do not abandon thread, we will join
+        m_abandon = false;
+
+        // Singal quit waitable event
+        m_quitEvent.Signal();
+    }
+
+    try{
+        m_thread.join();
+    }catch(std::system_error e){
+        Throw(Exception::QuitFailed);
+    }
+
+    LogPedantic("Thread quit");
+}
+
+void Thread::PushEvent(void *event,
+                       EventDispatchProc eventDispatchProc,
+                       EventDeleteProc eventDeleteProc,
+                       void *userParam)
+{
+    // Enter event list critical section
+    std::lock_guard<std::mutex> lock(m_eventMutex);
+
+    // Push new event
+    m_eventList.push_back(InternalEvent(event, userParam, eventDispatchProc,
+                                        eventDeleteProc));
+
+    // Trigger invoker
+    m_eventInvoker.Signal();
+
+    LogPedantic("Event pushed and invoker signaled");
+}
+
+void Thread::PushTimedEvent(void *event,
+                            double dueTimeSeconds,
+                            EventDispatchProc eventDispatchProc,
+                            EventDeleteProc eventDeleteProc,
+                            void *userParam)
+{
+    // Check for developer errors
+    Assert(dueTimeSeconds >= 0.0);
+
+    // Enter timed event list critical section
+    std::lock_guard<std::mutex> lock(m_timedEventMutex);
+
+    // Get current time
+    unsigned long currentTimeMiliseconds = GetCurrentTimeMiliseconds();
+
+    // Convert to miliseconds
+    unsigned long dueTimeMiliseconds =
+        static_cast<unsigned long>(1000.0 * dueTimeSeconds);
+
+    // Push new timed event
+    m_timedEventVector.push_back(InternalTimedEvent(event, userParam,
+                                                    dueTimeMiliseconds,
+                                                    currentTimeMiliseconds,
+                                                    eventDispatchProc,
+                                                    eventDeleteProc));
+
+    // Heapify timed events
+    std::make_heap(m_timedEventVector.begin(), m_timedEventVector.end());
+
+    // Trigger invoker
+    m_timedEventInvoker.Signal();
+
+    LogPedantic(
+        "Timed event pushed and invoker signaled: due time: " <<
+        dueTimeMiliseconds << " ms, absolute due time: " <<
+        currentTimeMiliseconds + dueTimeMiliseconds << " ms");
+}
+
+Thread *Thread::GetInvokerThread()
+{
+    return this;
+}
+
+void Thread::HandleDirectInvoker()
+{
+    // We must be in ProcessEvents call stack
+    // Mark that situation to handle direct invoker
+    m_directInvoke = true;
+}
+
+void Thread::Sleep(uint64_t seconds)
+{
+    NanoSleep(seconds * NANOSECONDS_PER_SECOND);
+}
+
+void Thread::MiliSleep(uint64_t miliseconds)
+{
+    NanoSleep(miliseconds * NANOSECONDS_PER_MILISECOND);
+}
+
+void Thread::MicroSleep(uint64_t microseconds)
+{
+    NanoSleep(microseconds * NANOSECONDS_PER_MICROSECOND);
+}
+
+void Thread::NanoSleep(uint64_t nanoseconds)
+{
+    timespec requestedTime = {
+        static_cast<time_t>(
+            nanoseconds / NANOSECONDS_PER_SECOND),
+
+        static_cast<long>(
+            nanoseconds % NANOSECONDS_PER_SECOND)
+    };
+
+    timespec remainingTime;
+
+    for (;;) {
+        if (nanosleep(&requestedTime, &remainingTime) == 0) {
+            break;
+        }
+
+        int error = errno;
+        Assert(error == EINTR);
+
+        requestedTime = remainingTime;
+    }
+}
+} // namespace DPL
diff --git a/commons/modules/core/src/waitable_event.cpp b/commons/modules/core/src/waitable_event.cpp
new file mode 100644 (file)
index 0000000..4808896
--- /dev/null
@@ -0,0 +1,77 @@
+/*
+ * 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        waitable_event.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of waitable event
+ */
+#include <stddef.h>
+#include <dpl/waitable_event.h>
+#include <sys/select.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <errno.h>
+
+namespace DPL {
+WaitableEvent::WaitableEvent()
+{
+    if (pipe(m_pipe) == -1) {
+        Throw(Exception::CreateFailed);
+    }
+
+    if (fcntl(m_pipe[0], F_SETFL, O_NONBLOCK |
+              fcntl(m_pipe[0], F_GETFL)) == -1)
+    {
+        Throw(Exception::CreateFailed);
+    }
+}
+
+WaitableEvent::~WaitableEvent()
+{
+    if (TEMP_FAILURE_RETRY(close(m_pipe[0])) == -1) {
+        Throw(Exception::DestroyFailed);
+    }
+
+    if (TEMP_FAILURE_RETRY(close(m_pipe[1])) == -1) {
+        Throw(Exception::DestroyFailed);
+    }
+}
+
+WaitableHandle WaitableEvent::GetHandle() const
+{
+    return m_pipe[0];
+}
+
+void WaitableEvent::Signal() const
+{
+    char data = 0;
+
+    if (TEMP_FAILURE_RETRY(write(m_pipe[1], &data, 1)) != 1) {
+        Throw(Exception::SignalFailed);
+    }
+}
+
+void WaitableEvent::Reset() const
+{
+    char data;
+
+    if (TEMP_FAILURE_RETRY(read(m_pipe[0], &data, 1)) != 1) {
+        Throw(Exception::ResetFailed);
+    }
+}
+} // namespace DPL
diff --git a/commons/modules/core/src/waitable_handle.cpp b/commons/modules/core/src/waitable_handle.cpp
new file mode 100644 (file)
index 0000000..5ea600d
--- /dev/null
@@ -0,0 +1,162 @@
+/*
+ * 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        waitable_handle.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of waitable handle
+ */
+#include <stddef.h>
+#include <dpl/waitable_event.h>
+#include <dpl/workaround.h>
+#include <dpl/log/log.h>
+#include <sys/select.h>
+#include <unistd.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <dpl/assert.h>
+
+namespace DPL {
+namespace // anonymous
+{
+void CheckWaitableHandle(WaitableHandle handle)
+{
+#ifdef DPL_ENABLE_WAITABLE_HANDLE_BADF_CHECK
+    // Try to get descriptor flags
+    int result = fcntl(handle, F_GETFL);
+
+    if (result == -1 && errno == EBADF) {
+        AssertMsg(0, "CheckWaitableHandle: Invalid WaitableHandle! (EBADF)");
+    }
+
+    AssertMsg(result != -1, "CheckWaitableHandle: Invalid WaitableHandle!");
+#endif // DPL_ENABLE_WAITABLE_HANDLE_BADF_CHECK
+}
+} // namespace anonymous
+
+WaitableHandleIndexList WaitForSingleHandle(WaitableHandle handle,
+                                            unsigned long miliseconds)
+{
+    WaitableHandleList waitHandles;
+    waitHandles.push_back(handle);
+    return WaitForMultipleHandles(waitHandles, miliseconds);
+}
+
+WaitableHandleIndexList WaitForSingleHandle(WaitableHandle handle,
+                                            WaitMode::Type mode,
+                                            unsigned long miliseconds)
+{
+    WaitableHandleListEx waitHandles;
+    waitHandles.push_back(std::make_pair(handle, mode));
+    return WaitForMultipleHandles(waitHandles, miliseconds);
+}
+
+WaitableHandleIndexList WaitForMultipleHandles(
+    const WaitableHandleList &waitableHandleList,
+    unsigned long miliseconds)
+{
+    WaitableHandleListEx handleList;
+
+    for (WaitableHandleList::const_iterator iterator = waitableHandleList.begin();
+         iterator != waitableHandleList.end();
+         ++iterator)
+    {
+        // Wait for multiple objects
+        handleList.push_back(std::make_pair(*iterator, WaitMode::Read));
+    }
+
+    // Do waiting
+    return WaitForMultipleHandles(handleList, miliseconds);
+}
+
+WaitableHandleIndexList WaitForMultipleHandles(
+    const WaitableHandleListEx &waitableHandleListEx,
+    unsigned long miliseconds)
+{
+    fd_set readFds, writeFds, errorFds;
+
+    // Fill sets
+    int maxFd = -1;
+
+    FD_ZERO(&readFds);
+    FD_ZERO(&writeFds);
+    FD_ZERO(&errorFds);
+
+    // Add read wait handles
+    for (WaitableHandleListEx::const_iterator iterator =
+             waitableHandleListEx.begin();
+         iterator != waitableHandleListEx.end();
+         ++iterator)
+    {
+        if (iterator->first > maxFd) {
+            maxFd = iterator->first;
+        }
+
+        CheckWaitableHandle(iterator->first);
+
+        // Handle errors along with read and write events
+        FD_SET(iterator->first, &errorFds);
+
+        if (iterator->second == WaitMode::Read) {
+            FD_SET(iterator->first, &readFds);
+        } else if (iterator->second == WaitMode::Write) {
+            FD_SET(iterator->first, &writeFds);
+        }
+    }
+
+    // Do select
+    timeval timeout;
+    timeval *effectiveTimeout = NULL;
+    if (miliseconds != 0xFFFFFFFF) {
+        timeout.tv_sec = miliseconds / 1000;
+        timeout.tv_usec = (miliseconds % 1000) * 1000;
+        effectiveTimeout = &timeout;
+    }
+
+    if (TEMP_FAILURE_RETRY(select(maxFd + 1, &readFds, &writeFds, &errorFds,
+                                  effectiveTimeout)) == -1)
+    {
+        Throw(WaitFailed);
+    }
+
+    // Check results
+    WaitableHandleIndexList indexes;
+    size_t index = 0;
+
+    for (WaitableHandleListEx::const_iterator iterator =
+             waitableHandleListEx.begin();
+         iterator != waitableHandleListEx.end();
+         ++iterator)
+    {
+        // Always return errors, no matter what type of listening is set
+        if (FD_ISSET(iterator->first, &errorFds)) {
+            indexes.push_back(index);
+        } else if (iterator->second == WaitMode::Read) {
+            if (FD_ISSET(iterator->first, &readFds)) {
+                indexes.push_back(index);
+            }
+        } else if (iterator->second == WaitMode::Write) {
+            if (FD_ISSET(iterator->first, &writeFds)) {
+                indexes.push_back(index);
+            }
+        }
+        ++index;
+    }
+
+    // Successfuly awaited some events or timeout occurred
+    return indexes;
+}
+} // namespace DPL
diff --git a/commons/modules/core/src/waitable_handle_watch_support.cpp b/commons/modules/core/src/waitable_handle_watch_support.cpp
new file mode 100644 (file)
index 0000000..c2e76cf
--- /dev/null
@@ -0,0 +1,260 @@
+/*
+ * 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        waitable_handle_watch_support.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of waitable handle watch
+ * support
+ */
+#include <stddef.h>
+#include <dpl/waitable_handle_watch_support.h>
+#include <dpl/thread.h>
+#include <dpl/log/log.h>
+#include <algorithm>
+#include <dpl/assert.h>
+
+namespace DPL {
+WaitableHandleWatchSupport::WaitableHandleWatchSupport()
+{}
+
+WaitableHandleWatchSupport::~WaitableHandleWatchSupport()
+{
+    // Developer assertions
+    if (!m_watchersMap.empty()) {
+        LogWarning("### Leaked watchers map dump ###");
+
+        for (WaitableHandleWatchersMap::const_iterator iterator =
+                 m_watchersMap.begin();
+             iterator != m_watchersMap.end();
+             ++iterator)
+        {
+            LogWarning("###   Waitable handle: " << iterator->first);
+
+            LogWarning(
+                "###     Read listeners: " <<
+                iterator->second.readListenersCount);
+            LogWarning(
+                "###     Write listeners: " <<
+                iterator->second.writeListenersCount);
+
+            for (WaitableHandleListenerList::const_iterator listenersIterator =
+                     iterator->second.listeners.begin();
+                 listenersIterator != iterator->second.listeners.end();
+                 ++listenersIterator)
+            {
+                LogWarning(
+                    "###       Mode: " << listenersIterator->mode <<
+                    ". Listener: 0x" << std::hex << listenersIterator->listener);
+            }
+        }
+    }
+}
+
+WaitableHandle WaitableHandleWatchSupport::WaitableInvokerHandle() const
+{
+    return m_watchersInvoker.GetHandle();
+}
+
+WaitableHandleListEx WaitableHandleWatchSupport::WaitableWatcherHandles() const
+{
+    // Critical section
+    {
+        std::lock_guard<std::recursive_mutex> lock(m_watchersMutex);
+
+        WaitableHandleListEx handleList;
+
+        for (WaitableHandleWatchersMap::const_iterator iterator =
+                 m_watchersMap.begin();
+             iterator != m_watchersMap.end();
+             ++iterator)
+        {
+            // Register waitable event id for wait
+            // Check if there are any read listeners and write listeners
+            // and register for both if applicable
+            if (iterator->second.readListenersCount > 0) {
+                handleList.push_back(std::make_pair(iterator->first,
+                                                    WaitMode::Read));
+            }
+
+            if (iterator->second.writeListenersCount > 0) {
+                handleList.push_back(std::make_pair(iterator->first,
+                                                    WaitMode::Write));
+            }
+        }
+
+        return handleList;
+    }
+}
+
+void WaitableHandleWatchSupport::InvokerFinished()
+{
+    LogPedantic("Invoker finished called");
+
+    // Reset invoker
+    m_watchersInvoker.Reset();
+
+    // Commit invoke
+    m_watchersInvokerCommit.Signal();
+}
+
+void WaitableHandleWatchSupport::HandleWatcher(WaitableHandle waitableHandle,
+                                               WaitMode::Type mode)
+{
+    //
+    // Waitable event occurred
+    // Now call all listeners for that waitable event. It is possible
+    // that some of listeners early disappeared. This is not a problem.
+    // Warning: Listeners and/or watcher may also disappear during dispatching
+    // handlers!
+    //
+    LogPedantic("Waitable event occurred");
+
+    // Critical section for other threads
+    {
+        std::lock_guard<std::recursive_mutex> lock(m_watchersMutex);
+
+        // Notice: We must carefully call watchers here as they may disappear
+        // (zero listeners) or be created during each of handler call
+        //         All removed listeners are handled correctly. Adding
+        // additional listener to the same waitable handle
+        //         during handler dispatch sequence is _not_ supported.
+        WaitableHandleWatchersMap trackedWatchers = m_watchersMap;
+
+        for (WaitableHandleWatchersMap::const_iterator trackedWatchersIterator
+                 = trackedWatchers.begin();
+             trackedWatchersIterator != trackedWatchers.end();
+             ++trackedWatchersIterator)
+        {
+            // Check if this watcher still exists
+            // If not, go to next tracked watcher
+            if (m_watchersMap.find(trackedWatchersIterator->first) ==
+                m_watchersMap.end())
+            {
+                LogPedantic("Watcher disappeared during watcher handler");
+                continue;
+            }
+
+            // Is this is a waitable handle that we are searching for ?
+            if (waitableHandle != trackedWatchersIterator->first) {
+                continue;
+            }
+
+            // Track watcher listeners list
+            WaitableHandleListenerList trackedListeners =
+                trackedWatchersIterator->second.listeners;
+
+            LogPedantic(
+                "Calling waitable event listeners (" <<
+                trackedListeners.size() << ")...");
+
+            // Notice: We must carefully call listeners here as they may
+            // disappear or be created during each of handler call
+            //         All removed listeners are handled correctly. Adding
+            // additional listener to the same waitable handle
+            //         during handler dispatch sequence is should be also
+            // handled, as an extremly case.
+
+            // Call all waitable event listeners who listen for that event
+            for (WaitableHandleListenerList::const_iterator
+                 trackedListenersIterator = trackedListeners.begin();
+                 trackedListenersIterator != trackedListeners.end();
+                 ++trackedListenersIterator)
+            {
+                // Check if this watcher still exists
+                // If not, there cannot be another one. Must exit now (after
+                // break, we actually exit)
+                if (m_watchersMap.find(trackedWatchersIterator->first) ==
+                    m_watchersMap.end())
+                {
+                    LogPedantic("Watcher disappeared during watcher handler");
+                    break;
+                }
+
+                // Check if this watcher listener still exists
+                // If not, go to next tracked watcher listener
+                bool listenerStillExists = false;
+
+                for (WaitableHandleListenerList::const_iterator
+                     searchListenerIterator =
+                         trackedWatchersIterator->second.listeners.begin();
+                     searchListenerIterator !=
+                     trackedWatchersIterator->second.listeners.end();
+                     ++searchListenerIterator)
+                {
+                    if (searchListenerIterator->listener ==
+                        trackedListenersIterator->listener &&
+                        searchListenerIterator->mode ==
+                        trackedListenersIterator->mode)
+                    {
+                        listenerStillExists = true;
+                        break;
+                    }
+                }
+
+                if (!listenerStillExists) {
+                    LogPedantic(
+                        "Watcher listener disappeared during watcher handler");
+                    break;
+                }
+
+                // Is this is a listener mode that we are searching for ?
+                if (mode != trackedListenersIterator->mode) {
+                    continue;
+                }
+
+                // Call waitable event watch listener
+                LogPedantic("Before tracker listener call...");
+                trackedListenersIterator->listener->OnWaitableHandleEvent(
+                    trackedWatchersIterator->first,
+                    trackedListenersIterator->mode);
+                LogPedantic("After tracker listener call...");
+            }
+
+            // Now call all those listeners who registered during listener calls
+            // FIXME: Implement! Notice, that scenario may be recursive!
+
+            LogPedantic("Waitable event listeners called");
+
+            // No more waitable events possible - consistency check
+            break;
+        }
+    }
+}
+
+void WaitableHandleWatchSupport::CommitInvoker()
+{
+    // Check calling context and execute invoker
+    if (Thread::GetCurrentThread() == GetInvokerThread()) {
+        LogPedantic("Calling direct invoker");
+
+        // Direct invoker call
+        HandleDirectInvoker();
+    } else {
+        LogPedantic("Calling indirect invoker");
+
+        // Indirect invoker call
+        m_watchersInvoker.Signal();
+
+        WaitableHandleList waitHandles;
+        waitHandles.push_back(m_watchersInvokerCommit.GetHandle());
+        WaitForMultipleHandles(waitHandles);
+
+        m_watchersInvokerCommit.Reset();
+    }
+}
+
+} // namespace DPL
diff --git a/commons/modules/db/config.cmake b/commons/modules/db/config.cmake
new file mode 100644 (file)
index 0000000..40012ab
--- /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        config.cmake
+# @author      Lukasz Marek (l.marek@samsung.com)
+# @version     1.0
+# @brief
+#
+
+SET(DPL_DB_SOURCES
+    ${PROJECT_SOURCE_DIR}/modules/db/src/naive_synchronization_object.cpp
+    ${PROJECT_SOURCE_DIR}/modules/db/src/orm.cpp
+    ${PROJECT_SOURCE_DIR}/modules/db/src/sql_connection.cpp
+    ${PROJECT_SOURCE_DIR}/modules/db/src/thread_database_support.cpp
+    PARENT_SCOPE
+)
+
+
+SET(DPL_DB_HEADERS
+    ${PROJECT_SOURCE_DIR}/modules/db/include/dpl/db/naive_synchronization_object.h
+    ${PROJECT_SOURCE_DIR}/modules/db/include/dpl/db/orm_generator.h
+    ${PROJECT_SOURCE_DIR}/modules/db/include/dpl/db/orm.h
+    ${PROJECT_SOURCE_DIR}/modules/db/include/dpl/db/orm_interface.h
+    ${PROJECT_SOURCE_DIR}/modules/db/include/dpl/db/orm_macros.h
+    ${PROJECT_SOURCE_DIR}/modules/db/include/dpl/db/sql_connection.h
+    ${PROJECT_SOURCE_DIR}/modules/db/include/dpl/db/thread_database_support.h
+    PARENT_SCOPE
+)
+
+SET(DPL_DB_INCLUDE_DIR
+    ${PROJECT_SOURCE_DIR}/modules/db/include
+    ${PROJECT_SOURCE_DIR}/modules/core/include/
+    PARENT_SCOPE
+)
diff --git a/commons/modules/db/include/dpl/db/naive_synchronization_object.h b/commons/modules/db/include/dpl/db/naive_synchronization_object.h
new file mode 100644 (file)
index 0000000..2f63a0f
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * 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        naive_synchronization_object.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of SQL naive
+ * synchronization object
+ */
+#ifndef DPL_NAIVE_SYNCHRONIZATION_OBJECT_H
+#define DPL_NAIVE_SYNCHRONIZATION_OBJECT_H
+
+#include <dpl/db/sql_connection.h>
+
+namespace DPL {
+namespace DB {
+/**
+ * Naive synchronization object used to synchronize SQL connection
+ * to the same database across different threads and processes
+ */
+class NaiveSynchronizationObject :
+    public SqlConnection::SynchronizationObject
+{
+  public:
+    // [SqlConnection::SynchronizationObject]
+    virtual void Synchronize();
+    virtual void NotifyAll();
+};
+} // namespace DB
+} // namespace DPL
+
+#endif // DPL_NAIVE_SYNCHRONIZATION_OBJECT_H
diff --git a/commons/modules/db/include/dpl/db/orm.h b/commons/modules/db/include/dpl/db/orm.h
new file mode 100644 (file)
index 0000000..0f36516
--- /dev/null
@@ -0,0 +1,1116 @@
+/*
+ * 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        orm.h
+ * @author      Bartosz Janiak (b.janiak@samsung.com)
+ * @version     1.0
+ * @brief       DPL-ORM: Object-relational mapping for sqlite database, written on top of DPL.
+ */
+
+#include <cstdlib>
+#include <cstdio>
+#include <string>
+#include <typeinfo>
+#include <utility>
+#include <set>
+#include <memory>
+#include <boost/optional.hpp>
+
+#include <dpl/db/sql_connection.h>
+#include <dpl/db/orm_interface.h>
+#include <dpl/string.h>
+#include <dpl/type_list.h>
+#include <dpl/assert.h>
+#include <dpl/foreach.h>
+
+#ifndef DPL_ORM_H
+#define DPL_ORM_H
+
+namespace DPL {
+namespace DB {
+namespace ORM {
+
+//TODO move to type utils
+#define DPL_CHECK_TYPE_INSTANTIABILITY(type) \
+    { \
+        type _ignored_; \
+        (void)_ignored_; \
+    }
+
+#define DECLARE_COLUMN_TYPE_LIST() typedef DPL::TypeListDecl<
+#define SELECTED_COLUMN(table_name, column_name) table_name::column_name,
+#define DECLARE_COLUMN_TYPE_LIST_END(name) DPL::TypeListGuard>::Type name;
+
+typedef size_t ColumnIndex;
+typedef size_t ArgumentIndex;
+typedef boost::optional<DPL::String> OptionalString;
+typedef boost::optional<int> OptionalInteger;
+typedef DPL::DB::SqlConnection::DataCommand DataCommand;
+
+namespace RelationTypes {
+    extern const char Equal[];
+    extern const char LessThan[];
+    extern const char And[];
+    extern const char Or[];
+    extern const char Is[];
+    extern const char In[];
+    //TODO define more relation types
+}
+
+namespace DataCommandUtils {
+    //TODO move to DPL::DataCommand?
+    void BindArgument(DataCommand *command, ArgumentIndex index, int argument);
+    void BindArgument(DataCommand *command, ArgumentIndex index, const OptionalInteger& argument);
+    void BindArgument(DataCommand *command, ArgumentIndex index, const DPL::String& argument);
+    void BindArgument(DataCommand *command, ArgumentIndex index, const OptionalString& argument);
+}
+class __attribute__ ((visibility("hidden"))) Expression {
+public:
+    virtual ~Expression() {}
+    virtual std::string GetString() const = 0;
+    virtual ArgumentIndex BindTo(DataCommand *command, ArgumentIndex index) = 0;
+};
+
+typedef std::shared_ptr<Expression> ExpressionPtr;
+
+namespace OrderingUtils {
+
+template<typename CompoundType> inline std::string OrderByInternal()
+{
+    std::string order = OrderByInternal<typename CompoundType::Tail>();
+    if(!order.empty()) return CompoundType::Head::GetString() + ", " + order;
+    else return CompoundType::Head::GetString();
+}
+
+template<> inline std::string OrderByInternal<TypeListGuard>()
+{
+    return std::string();
+}
+
+}
+
+template<typename ColumnType>
+class __attribute__ ((visibility("hidden"))) OrderingExpression {
+protected:
+    static std::string GetSchemaAndName()
+    {
+        std::string statement;
+        statement += ColumnType::GetTableName();
+        statement += ".";
+        statement += ColumnType::GetColumnName();
+        statement += " ";
+        return statement;
+    }
+public:
+    virtual ~OrderingExpression() {}
+};
+
+template<const char* Operator, typename LeftExpression, typename RightExpression>
+class __attribute__ ((visibility("hidden"))) BinaryExpression : public Expression {
+protected:
+    LeftExpression  m_leftExpression;
+    RightExpression m_rightExpression;
+    bool            m_outerParenthesis;
+public:
+    BinaryExpression(const LeftExpression& leftExpression, const RightExpression& rightExpression, bool outerParenthesis = true) :
+        m_leftExpression(leftExpression),
+        m_rightExpression(rightExpression),
+        m_outerParenthesis(outerParenthesis)
+    {}
+
+    virtual std::string GetString() const
+    {
+        return  (m_outerParenthesis ? "( " : " " ) +
+                 m_leftExpression.GetString() + " " + Operator + " " + m_rightExpression.GetString() +
+                (m_outerParenthesis ? " )" : " " ) ;
+    }
+
+    virtual ArgumentIndex BindTo(DataCommand *command, ArgumentIndex index)
+    {
+        index = m_leftExpression.BindTo(command, index);
+        return  m_rightExpression.BindTo(command, index);
+    }
+
+    template<typename TableDefinition>
+    struct ValidForTable {
+        typedef std::pair<typename LeftExpression ::template ValidForTable<TableDefinition>::Yes ,
+                          typename RightExpression::template ValidForTable<TableDefinition>::Yes >
+                Yes;
+    };
+};
+
+template<typename LeftExpression, typename RightExpression>
+BinaryExpression<RelationTypes::And, LeftExpression, RightExpression>
+    And(const LeftExpression& leftExpression, const RightExpression& rightExpression)
+{
+    return BinaryExpression<RelationTypes::And, LeftExpression, RightExpression>
+            (leftExpression, rightExpression);
+}
+
+template<typename LeftExpression, typename RightExpression>
+BinaryExpression<RelationTypes::Or, LeftExpression, RightExpression>
+    Or(const LeftExpression& leftExpression, const RightExpression& rightExpression)
+{
+    return BinaryExpression<RelationTypes::Or, LeftExpression, RightExpression>
+            (leftExpression, rightExpression);
+}
+
+template<typename ArgumentType>
+class __attribute__ ((visibility("hidden"))) ExpressionWithArgument : public Expression {
+protected:
+    ArgumentType argument;
+
+public:
+    explicit ExpressionWithArgument(const ArgumentType& _argument) : argument(_argument) {}
+
+    virtual ArgumentIndex BindTo(DataCommand *command, ArgumentIndex index)
+    {
+        DataCommandUtils::BindArgument(command, index, argument);
+        return index + 1;
+    }
+};
+
+template<typename ColumnData, const char* Relation>
+class __attribute__ ((visibility("hidden"))) Compare : public ExpressionWithArgument<typename ColumnData::ColumnType> {
+public:
+    explicit Compare(typename ColumnData::ColumnType column) :
+        ExpressionWithArgument<typename ColumnData::ColumnType>(column)
+    {}
+
+    virtual std::string GetString() const
+    {
+        std::string statement;
+        statement += ColumnData::GetTableName();
+        statement += ".";
+        statement += ColumnData::GetColumnName();
+        statement += " ";
+        statement += Relation;
+        statement += " ?";
+        return statement;
+    }
+
+    template<typename TableDefinition>
+    struct ValidForTable {
+        typedef typename TableDefinition::ColumnList::template Contains<ColumnData> Yes;
+    };
+};
+#define ORM_DEFINE_COMPARE_EXPRESSION(name, relationType)                      \
+    template<typename ColumnData>                                              \
+    class __attribute__ ((visibility("hidden"))) name : public Compare<ColumnData, RelationTypes::relationType> {     \
+    public:                                                                    \
+        name(typename ColumnData::ColumnType column) :                         \
+            Compare<ColumnData, RelationTypes::relationType>(column)           \
+        {}                                                                     \
+    };
+
+ORM_DEFINE_COMPARE_EXPRESSION(Equals, Equal)
+ORM_DEFINE_COMPARE_EXPRESSION(Is, Is)
+
+#define ORM_DEFINE_ORDERING_EXPRESSION(name, value)                                     \
+    template<typename ColumnType>                                                       \
+    class __attribute__ ((visibility("hidden"))) name                                   \
+        : OrderingExpression<ColumnType> {                                              \
+    public:                                                                             \
+        static std::string GetString()                                                  \
+        {                                                                               \
+            std::string statement = OrderingExpression<ColumnType>::GetSchemaAndName(); \
+            statement += value;                                                         \
+            return statement;                                                           \
+        }                                                                               \
+    };
+
+ORM_DEFINE_ORDERING_EXPRESSION(OrderingAscending, "ASC")
+ORM_DEFINE_ORDERING_EXPRESSION(OrderingDescending, "DESC")
+
+template<typename ColumnData1, typename ColumnData2>
+class __attribute__ ((visibility("hidden"))) CompareBinaryColumn {
+private:
+    std::string m_relation;
+public:
+    CompareBinaryColumn(const char* Relation) :
+      m_relation(Relation)
+    {}
+
+    virtual ~CompareBinaryColumn() {}
+
+    virtual std::string GetString() const
+    {
+        std::string statement;
+        statement += ColumnData1::GetTableName();
+        statement += ".";
+        statement += ColumnData1::GetColumnName();
+        statement += " ";
+        statement += m_relation;
+        statement += " ";
+        statement += ColumnData2::GetTableName();
+        statement += ".";
+        statement += ColumnData2::GetColumnName();
+
+        return statement;
+    }
+};
+
+template<typename ColumnData1, typename ColumnData2>
+CompareBinaryColumn<ColumnData1, ColumnData2>
+    Equal()
+{
+    return CompareBinaryColumn<ColumnData1, ColumnData2>(RelationTypes::Equal);
+}
+
+template<typename ColumnData, const char* Relation>
+class __attribute__ ((visibility("hidden"))) NumerousArguments : public Expression {
+protected:
+    std::set<typename ColumnData::ColumnType> m_argumentList;
+public:
+    NumerousArguments(const std::set<typename ColumnData::ColumnType>& argumentList) : m_argumentList(argumentList) {}
+
+    virtual std::string GetString() const
+    {
+        std::string statement;
+        statement += ColumnData::GetColumnName();
+        statement += " ";
+        statement += Relation;
+        statement += " ( ";
+
+        int argumentCount = m_argumentList.size();
+        while(argumentCount)
+        {
+            statement += "?";
+            argumentCount--;
+            if (argumentCount)
+            {
+                statement += ", ";
+            }
+        }
+
+        statement += " )";
+
+        return statement;
+    }
+
+    virtual ArgumentIndex BindTo(DataCommand *command, ArgumentIndex index)
+    {
+        ArgumentIndex argumentIndex = index;
+        FOREACH(argumentIt, m_argumentList)
+        {
+            DataCommandUtils::BindArgument(command, argumentIndex, *argumentIt);
+            argumentIndex++;
+        }
+        return  argumentIndex + 1;
+    }
+
+    template<typename TableDefinition>
+    struct ValidForTable {
+        typedef typename TableDefinition::ColumnList::template Contains<ColumnData> Yes;
+    };
+};
+
+#define ORM_DEFINE_COMPARE_EXPRESSION_NUMEROUS_ARGUMENTS(name, relationType)                      \
+    template<typename ColumnData>                                              \
+    class __attribute__ ((visibility("hidden"))) name : public NumerousArguments<ColumnData, RelationTypes::relationType> {     \
+    public:                                                                    \
+        name(std::set<typename ColumnData::ColumnType> column) :                         \
+            NumerousArguments<ColumnData, RelationTypes::relationType>(column)           \
+        {}                                                                     \
+    };
+
+ORM_DEFINE_COMPARE_EXPRESSION_NUMEROUS_ARGUMENTS(In, In)
+
+template<typename ColumnType>
+ColumnType GetColumnFromCommand(ColumnIndex columnIndex, DataCommand *command);
+
+class __attribute__ ((visibility("hidden"))) CustomColumnBase {
+public:
+    CustomColumnBase() {}
+    virtual ~CustomColumnBase() {}
+};
+
+template<typename ColumnType>
+class __attribute__ ((visibility("hidden"))) CustomColumn : public CustomColumnBase {
+private:
+    ColumnType m_columnData;
+
+public:
+    CustomColumn() {}
+    CustomColumn(ColumnType data)
+    {
+        m_columnData = data;
+    }
+
+    void SetColumnData(ColumnType data)
+    {
+        m_columnData = data;
+    }
+
+    ColumnType GetColumnData() const
+    {
+        return m_columnData;
+    }
+};
+
+template<typename ColumnList>
+class __attribute__ ((visibility("hidden"))) CustomRowUtil {
+public:
+    static void MakeColumnList(std::vector<CustomColumnBase*>& columnList)
+    {
+        typedef CustomColumn<typename ColumnList::Head::ColumnType> Type;
+        Type* pColumn = new Type();
+        columnList.push_back(pColumn);
+        CustomRowUtil<typename ColumnList::Tail>::MakeColumnList(columnList);
+    }
+
+    static void CopyColumnList(const std::vector<CustomColumnBase*>& srcList, std::vector<CustomColumnBase*>& dstList)
+    {
+        CopyColumnList(srcList, dstList, 0);
+    }
+
+    static ColumnIndex GetColumnIndex(const std::string& columnName)
+    {
+        return GetColumnIndex(columnName, 0);
+    }
+
+private:
+    static void CopyColumnList(const std::vector<CustomColumnBase*>& srcList, std::vector<CustomColumnBase*>& dstList, ColumnIndex index)
+    {
+        typedef CustomColumn<typename ColumnList::Head::ColumnType> Type;
+        Type* pColumn = new Type(((Type*)(srcList.at(index)))->GetColumnData());
+        dstList.push_back(pColumn);
+        CustomRowUtil<typename ColumnList::Tail>::CopyColumnList(srcList, dstList, index + 1);
+    }
+
+    static ColumnIndex GetColumnIndex(const std::string& columnName, ColumnIndex index)
+    {
+        if (ColumnList::Head::GetColumnName() == columnName)
+            return index;
+
+        return CustomRowUtil<typename ColumnList::Tail>::GetColumnIndex(columnName, index + 1);
+    }
+
+template<typename Other>
+friend class CustomRowUtil;
+};
+
+template<>
+class __attribute__ ((visibility("hidden"))) CustomRowUtil<DPL::TypeListGuard> {
+public:
+    static void MakeColumnList(std::vector<CustomColumnBase*>&) {}
+private:
+    static void CopyColumnList(const std::vector<CustomColumnBase*>&, std::vector<CustomColumnBase*>&, ColumnIndex) {}
+    static ColumnIndex GetColumnIndex(const std::string&, ColumnIndex) { return -1; }
+
+template<typename Other>
+friend class CustomRowUtil;
+};
+
+template<typename ColumnList>
+class __attribute__ ((visibility("hidden"))) CustomRow {
+private:
+    std::vector<CustomColumnBase*> m_columns;
+
+public:
+    CustomRow()
+    {
+        CustomRowUtil<ColumnList>::MakeColumnList(m_columns);
+    }
+
+    CustomRow(const CustomRow& r)
+    {
+        CustomRowUtil<ColumnList>::CopyColumnList(r.m_columns, m_columns);
+    }
+
+    virtual ~CustomRow()
+    {
+        while (!m_columns.empty())
+        {
+            CustomColumnBase* pCustomColumn = m_columns.back();
+            m_columns.pop_back();
+            if (pCustomColumn)
+                delete pCustomColumn;
+        }
+    }
+
+    template<typename ColumnType>
+    void SetColumnData(ColumnIndex columnIndex, ColumnType data)
+    {
+        typedef CustomColumn<ColumnType> Type;
+        Assert(columnIndex < m_columns.size());
+        Type* pColumn = dynamic_cast<Type*>(m_columns.at(columnIndex));
+        Assert(pColumn);
+        pColumn->SetColumnData(data);
+    }
+
+    template<typename ColumnData>
+    typename ColumnData::ColumnType GetColumnData()
+    {
+        typedef CustomColumn<typename ColumnData::ColumnType> Type;
+        ColumnIndex index = CustomRowUtil<ColumnList>::GetColumnIndex(ColumnData::GetColumnName());
+        Assert(index < m_columns.size());
+        Type* pColumn = dynamic_cast<Type*>(m_columns.at(index));
+        Assert(pColumn);
+        return pColumn->GetColumnData();
+    }
+};
+
+template<typename CustomRow, typename ColumnType>
+void SetColumnData(CustomRow& row, ColumnType columnData, ColumnIndex columnIndex)
+{
+    row.SetColumnData<ColumnType>(columnIndex, columnData);
+}
+
+template<typename ColumnList, typename CustomRow>
+class  __attribute__ ((visibility("hidden"))) FillCustomRowUtil {
+public:
+    static void FillCustomRow(CustomRow& row, DataCommand* command)
+    {
+        FillCustomRow(row, 0, command);
+    }
+
+private:
+    static void FillCustomRow(CustomRow& row, ColumnIndex columnIndex, DataCommand* command)
+    {
+        typename ColumnList::Head::ColumnType columnData;
+        columnData = GetColumnFromCommand<typename ColumnList::Head::ColumnType>(columnIndex, command);
+        SetColumnData<CustomRow, typename ColumnList::Head::ColumnType>(row, columnData, columnIndex);
+        FillCustomRowUtil<typename ColumnList::Tail, CustomRow>::FillCustomRow(row, columnIndex + 1, command);
+    }
+
+template<typename Other, typename OtherRow>
+friend class FillCustomRowUtil;
+};
+
+template<typename CustomRow>
+class  __attribute__ ((visibility("hidden"))) FillCustomRowUtil<DPL::TypeListGuard, CustomRow> {
+private:
+    static void FillCustomRow(CustomRow&, ColumnIndex, DataCommand *)
+    { /* do nothing, we're past the last element of column list */ }
+
+template<typename Other, typename OtherRow>
+friend class FillCustomRowUtil;
+};
+
+template<typename ColumnList, typename Row>
+class  __attribute__ ((visibility("hidden"))) FillRowUtil {
+public:
+    static void FillRow(Row& row, DataCommand *command)
+    {
+        FillRow(row, 0, command);
+    }
+
+private:
+    static void FillRow(Row& row, ColumnIndex columnIndex, DataCommand *command)
+    {
+        typename ColumnList::Head::ColumnType rowField;
+        rowField = GetColumnFromCommand<typename ColumnList::Head::ColumnType>(columnIndex, command);
+        ColumnList::Head::SetRowField(row, rowField);
+        FillRowUtil<typename ColumnList::Tail, Row>::FillRow(row, columnIndex + 1, command);
+    }
+
+template<typename Other, typename OtherRow>
+friend class FillRowUtil;
+};
+
+template<typename Row>
+class  __attribute__ ((visibility("hidden"))) FillRowUtil<DPL::TypeListGuard, Row> {
+private:
+    static void FillRow(Row&, ColumnIndex, DataCommand *)
+    { /* do nothing, we're past the last element of column list */ }
+
+template<typename Other, typename OtherRow>
+friend class FillRowUtil;
+};
+
+template<typename ColumnList>
+class  __attribute__ ((visibility("hidden"))) JoinUtil {
+public:
+    static std::string GetColumnNames()
+    {
+        std::string result;
+        result = ColumnList::Head::GetTableName();
+        result += ".";
+        result += ColumnList::Head::GetColumnName();
+        if (ColumnList::Tail::Size > 0)
+            result += ", ";
+
+        return result += JoinUtil<typename ColumnList::Tail>::GetColumnNames();
+    }
+
+    static std::string GetJoinTableName(const std::string& tableName)
+    {
+        std::string joinTableName = ColumnList::Head::GetTableName();
+        if (tableName.find(joinTableName) == std::string::npos)
+            return joinTableName;
+
+        return JoinUtil<typename ColumnList::Tail>::GetJoinTableName(tableName);
+    }
+};
+
+template<>
+class  __attribute__ ((visibility("hidden"))) JoinUtil<DPL::TypeListGuard> {
+public:
+    static std::string GetColumnNames() { return ""; }
+    static std::string GetJoinTableName(std::string) { return ""; }
+};
+
+class Exception {
+public:
+    DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+    DECLARE_EXCEPTION_TYPE(Base, SelectReuseWithDifferentQuerySignature)
+    DECLARE_EXCEPTION_TYPE(Base, RowFieldNotInitialized)
+    DECLARE_EXCEPTION_TYPE(Base, EmptyUpdateStatement)
+};
+
+template<typename TableDefinition>
+class  __attribute__ ((visibility("hidden"))) Query
+{
+protected:
+    explicit Query(IOrmInterface* interface) :
+        m_interface(interface),
+        m_command(NULL)
+    {
+    }
+
+    virtual ~Query()
+    {
+        if (m_command == NULL)
+            return;
+
+        TableDefinition::FreeTableDataCommand(m_command, m_interface);
+    }
+
+    IOrmInterface* m_interface;
+    DataCommand *m_command;
+    std::string m_commandString;
+    ArgumentIndex m_bindArgumentIndex;
+};
+
+template<typename TableDefinition>
+class  __attribute__ ((visibility("hidden"))) QueryWithWhereClause : public Query<TableDefinition>
+{
+protected:
+    ExpressionPtr m_whereExpression;
+
+    void Prepare()
+    {
+        if ( !!m_whereExpression )
+        {
+            this->m_commandString += " WHERE ";
+            this->m_commandString += m_whereExpression->GetString();
+        }
+    }
+
+    void Bind()
+    {
+        if ( !!m_whereExpression )
+        {
+            this->m_bindArgumentIndex = m_whereExpression->BindTo(
+                this->m_command, this->m_bindArgumentIndex);
+        }
+    }
+
+public:
+    explicit QueryWithWhereClause(IOrmInterface* interface) :
+        Query<TableDefinition>(interface)
+    {
+    }
+
+    template<typename Expression>
+    void Where(const Expression& expression)
+    {
+        DPL_CHECK_TYPE_INSTANTIABILITY(typename Expression::template ValidForTable<TableDefinition>::Yes);
+        if ( !!m_whereExpression && ( typeid(Expression) != typeid(*m_whereExpression) ) )
+        {
+            std::ostringstream str;
+            str << "Current ORM implementation doesn't allow to reuse Select"
+                    " instance with different query signature (particularly "
+                    "WHERE on different column).\n";
+            str << "Query: ";
+            str << this->m_commandString;
+            ThrowMsg(Exception::SelectReuseWithDifferentQuerySignature,
+                str.str());
+        }
+        //TODO maybe don't make a copy here but just generate the string part of the query.
+        m_whereExpression.reset(new Expression(expression));
+    }
+
+};
+
+template<typename TableDefinition>
+class  __attribute__ ((visibility("hidden"))) Delete : public QueryWithWhereClause<TableDefinition>
+{
+protected:
+    void Prepare()
+    {
+        if ( !this->m_command)
+        {
+            this->m_commandString  = "DELETE FROM ";
+            this->m_commandString += TableDefinition::GetName();
+
+            QueryWithWhereClause<TableDefinition>::Prepare();
+
+            this->m_command = TableDefinition::AllocTableDataCommand(
+                    this->m_commandString.c_str(),
+                    Query<TableDefinition>::m_interface);
+            LogPedantic("Prepared SQL command " << this->m_commandString);
+        }
+    }
+
+    void Bind()
+    {
+        this->m_bindArgumentIndex = 1;
+        QueryWithWhereClause<TableDefinition>::Bind();
+    }
+
+public:
+    explicit Delete(IOrmInterface *interface = NULL) :
+        QueryWithWhereClause<TableDefinition>(interface)
+    {
+    }
+
+    void Execute()
+    {
+        Prepare();
+        Bind();
+        this->m_command->Step();
+        this->m_command->Reset();
+    }
+};
+
+namespace {
+class BindVisitor {
+private:
+    DataCommand *m_command;
+public:
+    ArgumentIndex m_bindArgumentIndex;
+
+    BindVisitor(DataCommand *command) :
+        m_command(command),
+        m_bindArgumentIndex(1)
+    {}
+
+    template<typename ColumnType>
+    void Visit(const char*, const ColumnType& value, bool isSet)
+    {
+        if ( isSet )
+        {
+            DataCommandUtils::BindArgument(m_command, m_bindArgumentIndex, value);
+            m_bindArgumentIndex++;
+        }
+    }
+};
+} //anonymous namespace
+template<typename TableDefinition>
+class __attribute__ ((visibility("hidden"))) Insert : public Query<TableDefinition>
+{
+public:
+    typedef typename TableDefinition::Row Row;
+    typedef DPL::DB::SqlConnection::RowID RowID;
+
+protected:
+    boost::optional<std::string> m_orClause;
+    Row m_row;
+
+    class PrepareVisitor {
+    public:
+        std::string m_columnNames;
+        std::string m_values;
+
+        template<typename ColumnType>
+        void Visit(const char* name, const ColumnType&, bool isSet)
+        {
+            if ( isSet )
+            {
+                if ( !m_columnNames.empty() )
+                {
+                    m_columnNames += ", ";
+                    m_values += ", ";
+                }
+                m_columnNames += name;
+                m_values += "?";
+            }
+        }
+    };
+
+    void Prepare()
+    {
+        if ( !this->m_command )
+        {
+            this->m_commandString = "INSERT ";
+            if ( !!m_orClause )
+            {
+                this->m_commandString += " OR " + *m_orClause + " ";
+            }
+            this->m_commandString += "INTO ";
+            this->m_commandString += TableDefinition::GetName();
+
+            PrepareVisitor visitor;
+            m_row.VisitColumns(visitor);
+
+            this->m_commandString += " ( " + visitor.m_columnNames + " ) ";
+            this->m_commandString += "VALUES ( " + visitor.m_values + " )";
+
+            LogPedantic("Prepared SQL command " << this->m_commandString);
+            this->m_command = TableDefinition::AllocTableDataCommand(
+                this->m_commandString.c_str(),
+                Query<TableDefinition>::m_interface);
+        }
+    }
+
+    void Bind()
+    {
+        BindVisitor visitor(this->m_command);
+        m_row.VisitColumns(visitor);
+    }
+
+public:
+    explicit Insert(
+            IOrmInterface* interface = NULL,
+            const boost::optional<std::string>& orClause = boost::optional<std::string>()) :
+        Query<TableDefinition>(interface),
+        m_orClause(orClause)
+    {
+    }
+
+    void Values(const Row& row)
+    {
+        if ( this->m_command )
+        {
+            if ( !row.IsSignatureMatching(m_row) )
+            {
+                ThrowMsg(Exception::SelectReuseWithDifferentQuerySignature,
+                    "Current ORM implementation doesn't allow to reuse Insert instance "
+                    "with different query signature.");
+            }
+        }
+        m_row = row;
+    }
+
+    RowID Execute()
+    {
+        Prepare();
+        Bind();
+        this->m_command->Step();
+
+        RowID result = TableDefinition::GetLastInsertRowID(
+            Query<TableDefinition>::m_interface);
+
+        this->m_command->Reset();
+        return result;
+    }
+};
+
+template<typename TableDefinition>
+class __attribute__ ((visibility("hidden"))) Select : public QueryWithWhereClause<TableDefinition>
+{
+public:
+    typedef typename TableDefinition::ColumnList       ColumnList;
+    typedef typename TableDefinition::Row              Row;
+
+    typedef std::list<Row>                             RowList;
+protected:
+    boost::optional<std::string> m_orderBy;
+    std::string m_JoinClause;
+    bool                       m_distinctResults;
+
+    void Prepare(const char* selectColumnName)
+    {
+        if ( !this->m_command )
+        {
+            this->m_commandString  = "SELECT ";
+            if (m_distinctResults)
+                this->m_commandString += "DISTINCT ";
+            this->m_commandString += selectColumnName;
+            this->m_commandString += " FROM ";
+            this->m_commandString += TableDefinition::GetName();
+
+            this->m_commandString += m_JoinClause;
+
+            QueryWithWhereClause<TableDefinition>::Prepare();
+
+            if ( !!m_orderBy )
+            {
+                this->m_commandString += " ORDER BY " + *m_orderBy;
+            }
+
+            this->m_command = TableDefinition::AllocTableDataCommand(
+                this->m_commandString.c_str(),
+                Query<TableDefinition>::m_interface);
+
+            LogPedantic("Prepared SQL command " << this->m_commandString);
+        }
+    }
+
+    void Bind()
+    {
+        this->m_bindArgumentIndex = 1;
+        QueryWithWhereClause<TableDefinition>::Bind();
+    }
+
+    template<typename ColumnType>
+    ColumnType GetColumn(ColumnIndex columnIndex)
+    {
+        return GetColumnFromCommand<ColumnType>(columnIndex, this->m_command);
+    }
+
+    Row GetRow()
+    {
+        Row row;
+        FillRowUtil<ColumnList, Row>::FillRow(row, this->m_command);
+        return row;
+    }
+
+    template<typename ColumnList, typename CustomRow>
+    CustomRow GetCustomRow()
+    {
+        CustomRow row;
+        FillCustomRowUtil<ColumnList, CustomRow>::FillCustomRow(row, this->m_command);
+        return row;
+    }
+
+public:
+
+    explicit Select(IOrmInterface *interface = NULL) :
+        QueryWithWhereClause<TableDefinition>(interface),
+        m_distinctResults(false)
+    {
+    }
+
+    void Distinct()
+    {
+        m_distinctResults = true;
+    }
+
+    template<typename CompoundType>
+    void OrderBy(const CompoundType&)
+    {
+        m_orderBy = OrderingUtils::OrderByInternal<typename CompoundType::Type>();
+    }
+
+    void OrderBy(const std::string & orderBy) //backward compatibility
+    {
+        m_orderBy = orderBy;
+    }
+
+    void OrderBy(const char * orderBy) //backward compatibility
+    {
+        m_orderBy = std::string(orderBy);
+    }
+
+    template<typename ColumnList, typename Expression>
+    void Join(const Expression& expression) {
+        std::string usedTableNames = TableDefinition::GetName();
+        if (!m_JoinClause.empty())
+            usedTableNames += m_JoinClause;
+
+        this->m_JoinClause += " JOIN ";
+        this->m_JoinClause += JoinUtil<ColumnList>::GetJoinTableName(usedTableNames);
+        this->m_JoinClause += " ON ";
+        this->m_JoinClause += expression.GetString();
+    }
+
+    template<typename ColumnData>
+    typename ColumnData::ColumnType GetSingleValue()
+    {
+        Prepare(ColumnData::GetColumnName());
+        Bind();
+        this->m_command->Step();
+
+        typename ColumnData::ColumnType result =
+            GetColumn<typename ColumnData::ColumnType>(0);
+
+        this->m_command->Reset();
+        return result;
+    }
+
+    //TODO return range - pair of custom iterators
+    template<typename ColumnData>
+    std::list<typename ColumnData::ColumnType> GetValueList()
+    {
+        Prepare(ColumnData::GetColumnName());
+        Bind();
+
+        std::list<typename ColumnData::ColumnType> resultList;
+
+        while (this->m_command->Step())
+            resultList.push_back(GetColumn<typename ColumnData::ColumnType>(0));
+
+        this->m_command->Reset();
+        return resultList;
+    }
+
+    Row GetSingleRow()
+    {
+        Prepare("*");
+        Bind();
+        this->m_command->Step();
+
+        Row result = GetRow();
+
+        this->m_command->Reset();
+        return result;
+    }
+
+    //TODO return range - pair of custom iterators
+    RowList GetRowList()
+    {
+        Prepare("*");
+        Bind();
+
+        RowList resultList;
+
+        while (this->m_command->Step())
+            resultList.push_back(GetRow());
+
+        this->m_command->Reset();
+        return resultList;
+    }
+
+    template<typename ColumnList, typename CustomRow>
+    CustomRow GetCustomSingleRow()
+    {
+        Prepare(JoinUtil<ColumnList>::GetColumnNames().c_str());
+        Bind();
+        this->m_command->Step();
+
+        CustomRow result = GetCustomRow<ColumnList, CustomRow>();
+
+        this->m_command->Reset();
+        return result;
+    }
+
+    template<typename ColumnList, typename CustomRow>
+    std::list<CustomRow> GetCustomRowList()
+    {
+        Prepare(JoinUtil<ColumnList>::GetColumnNames().c_str());
+        Bind();
+
+        std::list<CustomRow> resultList;
+
+        while (this->m_command->Step())
+            resultList.push_back(GetCustomRow<ColumnList, CustomRow>());
+
+        this->m_command->Reset();
+        return resultList;
+    }
+};
+
+template<typename TableDefinition>
+class __attribute__ ((visibility("hidden"))) Update : public QueryWithWhereClause<TableDefinition> {
+public:
+    typedef typename TableDefinition::Row Row;
+
+protected:
+    boost::optional<std::string> m_orClause;
+    Row m_row;
+
+    class PrepareVisitor {
+    public:
+        std::string m_setExpressions;
+
+        template<typename ColumnType>
+        void Visit(const char* name, const ColumnType&, bool isSet)
+        {
+            if ( isSet )
+            {
+                if ( !m_setExpressions.empty() )
+                {
+                    m_setExpressions += ", ";
+                }
+                m_setExpressions += name;
+                m_setExpressions += " = ";
+                m_setExpressions += "?";
+            }
+        }
+    };
+
+    void Prepare()
+    {
+        if ( !this->m_command )
+        {
+            this->m_commandString = "UPDATE ";
+            if ( !!m_orClause )
+            {
+                this->m_commandString += " OR " + *m_orClause + " ";
+            }
+            this->m_commandString += TableDefinition::GetName();
+            this->m_commandString += " SET ";
+
+            // got through row columns and values
+            PrepareVisitor visitor;
+            m_row.VisitColumns(visitor);
+
+            if(visitor.m_setExpressions.empty())
+            {
+                ThrowMsg(Exception::EmptyUpdateStatement, "No SET expressions in update statement");
+            }
+
+            this->m_commandString += visitor.m_setExpressions;
+
+            // where
+            QueryWithWhereClause<TableDefinition>::Prepare();
+
+            this->m_command = TableDefinition::AllocTableDataCommand(
+                    this->m_commandString.c_str(),
+                    Query<TableDefinition>::m_interface);
+            LogPedantic("Prepared SQL command " << this->m_commandString);
+        }
+    }
+
+    void Bind()
+    {
+        BindVisitor visitor(this->m_command);
+        m_row.VisitColumns(visitor);
+
+        this->m_bindArgumentIndex = visitor.m_bindArgumentIndex;
+        QueryWithWhereClause<TableDefinition>::Bind();
+    }
+
+
+public:
+    explicit Update(IOrmInterface *interface = NULL,
+                    const boost::optional<std::string>& orClause = boost::optional<std::string>()) :
+        QueryWithWhereClause<TableDefinition>(interface),
+        m_orClause(orClause)
+    {
+    }
+
+    void Values(const Row& row)
+    {
+        if ( this->m_command )
+        {
+            if ( !row.IsSignatureMatching(m_row) )
+            {
+                ThrowMsg(Exception::SelectReuseWithDifferentQuerySignature,
+                    "Current ORM implementation doesn't allow to reuse Update instance "
+                    "with different query signature.");
+            }
+        }
+        m_row = row;
+    }
+
+    void Execute()
+    {
+        Prepare();
+        Bind();
+        this->m_command->Step();
+        this->m_command->Reset();
+    }
+};
+
+} //namespace ORM
+} //namespace DB
+} //namespace DPL
+
+#endif // DPL_ORM_H
diff --git a/commons/modules/db/include/dpl/db/orm_generator.h b/commons/modules/db/include/dpl/db/orm_generator.h
new file mode 100644 (file)
index 0000000..ca62410
--- /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        orm_generator.h
+ * @author      Bartosz Janiak (b.janiak@samsung.com)
+ * @version     1.0
+ * @brief       Macro definitions for generating the DPL-ORM table definitions from database definitions.
+ */
+
+#ifndef ORM_GENERATOR_DATABASE_NAME
+#error You need to define database name in ORM_GENERATOR_DATABASE_NAME define before you include orm_generator.h file
+#endif
+
+#include <dpl/db/orm_interface.h>
+
+#define ORM_GENERATOR_DATABASE_NAME_LOCAL <ORM_GENERATOR_DATABASE_NAME>
+
+#ifdef DPL_ORM_GENERATOR_H
+#warning orm_generator.h is included multiply times. Make sure it has different ORM_GENERATOR_DATABASE_NAME set.
+#endif
+
+#define DPL_ORM_GENERATOR_H
+
+
+#include <boost/optional.hpp>
+#include <dpl/string.h>
+#include <dpl/type_list.h>
+#include <dpl/db/sql_connection.h>
+#include <dpl/db/orm.h>
+#include <dpl/assert.h>
+#include <string>
+
+/*
+
+This is true only when exactly one db is available.
+
+#if (defined DECLARE_COLUMN) || (defined INT) || (defined TINYINT) ||               \
+    (defined INTEGER) || (defined BIGINT) || defined(VARCHAR) || defined(TEXT) ||   \
+    (defined SQL) || (defined TABLE_CONSTRAINTS) || (defined OPTIONAL) ||           \
+    (defined DATABASE_START) || (defined DATABASE_END) || (defined CREATE_TABLE) || \
+    (defined COLUMN) || (defined COLUMN_NOT_NULL) || (defined CREATE_TABLE_END)
+
+#error  This file temporarily defines many macros with generic names. To avoid name clash please include \
+        this file as early as possible. If this is not possible please report this problem to DPL developers.
+
+#endif
+*/
+
+namespace DPL {
+namespace DB {
+namespace ORM {
+
+// Global macros
+
+#define STRINGIFY(s) _str(s)
+#define _str(s) #s
+#define DECLARE_COLUMN(FIELD, TYPE) \
+    struct FIELD { \
+        typedef TYPE ColumnType; \
+        static const char* GetTableName() { return GetName(); } \
+        static const char* GetColumnName() { return STRINGIFY(FIELD); } \
+        static void SetRowField(Row& row, const TYPE& _value) { row.Set_##FIELD(_value);} \
+    };
+
+#define INT         int
+#define TINYINT     int
+#define INTEGER     int  //TODO: should be long long?
+#define BIGINT      int  //TODO: should be long long?
+#define VARCHAR(x)  DPL::String
+#define TEXT        DPL::String
+
+#define SQL(...)
+#define TABLE_CONSTRAINTS(...)
+#define OPTIONAL(type) boost::optional< type >
+#define DATABASE_START(db_name)                                 \
+    namespace db_name                                           \
+    {                                                           \
+        class ScopedTransaction                                 \
+        {                                                       \
+            bool m_commited;                                    \
+            IOrmInterface *m_interface;                         \
+                                                                \
+        public:                                                 \
+            ScopedTransaction(IOrmInterface *interface) :       \
+                m_commited(false),                              \
+                m_interface(interface)                          \
+            {                                                   \
+                Assert(interface != NULL);                      \
+                m_interface->TransactionBegin();                \
+            }                                                   \
+                                                                \
+            ~ScopedTransaction()                                \
+            {                                                   \
+                if (!m_commited)                                \
+                    m_interface->TransactionRollback();         \
+            }                                                   \
+                                                                \
+            void Commit()                                       \
+            {                                                   \
+                m_interface->TransactionCommit();               \
+                m_commited = true;                              \
+            }                                                   \
+        };
+
+#define DATABASE_END() }
+
+// RowBase ostream operator<< declaration
+
+#define CREATE_TABLE(name) \
+    namespace name {                                                            \
+        class RowBase;                                                          \
+        inline std::ostream& operator<<(std::ostream& ostr, const RowBase& row); \
+    }
+#define COLUMN_NOT_NULL(name, type, ...)
+#define COLUMN(name, type, ...)
+#define CREATE_TABLE_END()
+
+#include ORM_GENERATOR_DATABASE_NAME_LOCAL
+
+#undef CREATE_TABLE
+#undef COLUMN_NOT_NULL
+#undef COLUMN
+#undef CREATE_TABLE_END
+
+#undef DATABASE_START
+#define DATABASE_START(db_name) namespace db_name {
+
+// RowBase class
+
+#define CREATE_TABLE(name) namespace name { class RowBase {                 \
+   public: friend std::ostream& operator<<(std::ostream&, const RowBase&);
+#define COLUMN_NOT_NULL(name, type, ...)                                \
+        protected: type name; bool m_##name##_set;                          \
+        public:  void Set_##name(const type& _value) {                       \
+                     m_##name##_set = true;                                 \
+                     this->name = _value;                                     \
+        }                                                                   \
+        public:  type Get_##name() const {                                  \
+                     if ( !m_##name##_set ) {                               \
+                        ThrowMsg(Exception::RowFieldNotInitialized,         \
+                        "You tried to read a row field that hasn't been set yet."); \
+                     }                                                      \
+                     return name;                                           \
+        }
+
+#define COLUMN(name, type, ...)                                         \
+        protected: OPTIONAL(type) name; bool m_##name##_set;                \
+        public:  void Set_##name(const OPTIONAL(type)& _value) {             \
+                     m_##name##_set = true;                                 \
+                     this->name = _value;                                     \
+        }                                                                   \
+        public:  OPTIONAL(type) Get_##name() const {                        \
+                     if ( !m_##name##_set ) {                               \
+                        ThrowMsg(Exception::RowFieldNotInitialized,         \
+                        "You tried to read a row field that hasn't been set yet."); \
+                     }                                                      \
+                     return name;                                           \
+        }
+#define CREATE_TABLE_END() }; }
+
+#include ORM_GENERATOR_DATABASE_NAME_LOCAL
+
+#undef CREATE_TABLE
+#undef COLUMN_NOT_NULL
+#undef COLUMN
+#undef CREATE_TABLE_END
+
+// RowBase ostream operator<<
+
+#define CREATE_TABLE(name) std::ostream& name::operator<<(std::ostream& ostr, const RowBase& row) { using ::operator<< ; ostr << STRINGIFY(name) << " (";
+#define COLUMN_NOT_NULL(name, type, ...) ostr << " '" << row.name << "'" ;
+#define COLUMN(name, type, ...)          ostr << " '" << row.name << "'" ;
+#define CREATE_TABLE_END() ostr << " )" ; return ostr; }
+
+#include ORM_GENERATOR_DATABASE_NAME_LOCAL
+
+#undef CREATE_TABLE
+#undef COLUMN_NOT_NULL
+#undef COLUMN
+#undef CREATE_TABLE_END
+
+// RowBase2 class (== RowBase + operator==)
+
+#define CREATE_TABLE(name) namespace name { class RowBase2 : public RowBase { \
+    public: bool operator==(const RowBase2& row) const { return true
+#define COLUMN_NOT_NULL(name, type, ...) && (this->name == row.name)
+#define COLUMN(name, type, ...)          && (this->name == row.name)
+#define CREATE_TABLE_END() ; } }; }
+
+#include ORM_GENERATOR_DATABASE_NAME_LOCAL
+
+#undef CREATE_TABLE
+#undef COLUMN_NOT_NULL
+#undef COLUMN
+#undef CREATE_TABLE_END
+
+// RowBase3 class (== RowBase2 + operator<)
+
+#define CREATE_TABLE(name) namespace name { class RowBase3 : public RowBase2 { \
+    public: bool operator<(const RowBase3& row) const {
+#define COLUMN_NOT_NULL(name, type, ...) if (this->name < row.name) { return true; } if (this->name > row.name) { return false; }
+#define COLUMN(name, type, ...)          if (this->name < row.name) { return true; } if (this->name > row.name) { return false; }
+#define CREATE_TABLE_END() return false; } }; }
+
+#include ORM_GENERATOR_DATABASE_NAME_LOCAL
+
+#undef CREATE_TABLE
+#undef COLUMN_NOT_NULL
+#undef COLUMN
+#undef CREATE_TABLE_END
+
+// RowBase4 class (== RowBase3 + IsSignatureMatching )
+
+#define CREATE_TABLE(name) namespace name { class RowBase4 : public RowBase3 { \
+    public: bool IsSignatureMatching(const RowBase4& row) const { return true
+#define COLUMN_NOT_NULL(name, type, ...) && (this->m_##name##_set == row.m_##name##_set)
+#define COLUMN(name, type, ...)          && (this->m_##name##_set == row.m_##name##_set)
+#define CREATE_TABLE_END() ; } }; }
+
+#include ORM_GENERATOR_DATABASE_NAME_LOCAL
+
+#undef CREATE_TABLE
+#undef COLUMN_NOT_NULL
+#undef COLUMN
+#undef CREATE_TABLE_END
+
+// RowBase5 class (== RowBase4 + default constructor)
+
+#define CREATE_TABLE(name) namespace name { class RowBase5 : public RowBase4 { \
+    public: RowBase5() {
+#define COLUMN_NOT_NULL(name, type, ...) m_##name##_set = false;
+#define COLUMN(name, type, ...)          m_##name##_set = false;
+#define CREATE_TABLE_END() } }; }
+
+#include ORM_GENERATOR_DATABASE_NAME_LOCAL
+
+#undef CREATE_TABLE
+#undef COLUMN_NOT_NULL
+#undef COLUMN
+#undef CREATE_TABLE_END
+
+// Row class (== RowBase5 + ForEachColumn )
+
+#define CREATE_TABLE(name) namespace name { class Row : public RowBase5 { \
+    public: template<typename Visitor>                                    \
+    void VisitColumns(Visitor& visitor) const {
+#define COLUMN_NOT_NULL(name, type, ...) visitor.Visit(STRINGIFY(name), this->name, this->m_##name##_set);
+#define COLUMN(name, type, ...)          visitor.Visit(STRINGIFY(name), this->name, this->m_##name##_set);
+#define CREATE_TABLE_END() } }; }
+
+#include ORM_GENERATOR_DATABASE_NAME_LOCAL
+
+#undef CREATE_TABLE
+#undef COLUMN_NOT_NULL
+#undef COLUMN
+#undef CREATE_TABLE_END
+
+// Field structure declarations
+
+#define CREATE_TABLE(name) namespace name { \
+    static const char* GetName() { return STRINGIFY(name); }
+#define COLUMN_NOT_NULL(name, type, ...) DECLARE_COLUMN(name, type)
+#define COLUMN(name, type, ...) DECLARE_COLUMN(name, OPTIONAL(type))
+#define CREATE_TABLE_END() }
+
+#include ORM_GENERATOR_DATABASE_NAME_LOCAL
+
+#undef CREATE_TABLE
+#undef COLUMN_NOT_NULL
+#undef COLUMN
+#undef CREATE_TABLE_END
+
+// ColumnList typedef
+
+#define CREATE_TABLE(name) namespace name { typedef DPL::TypeListDecl<
+#define COLUMN_NOT_NULL(name, type, ...) name,
+#define COLUMN(name, type, ...) name,
+#define CREATE_TABLE_END() DPL::TypeListGuard>::Type ColumnList; }
+
+#include ORM_GENERATOR_DATABASE_NAME_LOCAL
+
+#undef CREATE_TABLE
+#undef COLUMN_NOT_NULL
+#undef COLUMN
+#undef CREATE_TABLE_END
+
+// TableDefinition struct
+
+#define CREATE_TABLE(table_name)                                            \
+    namespace table_name {                                                  \
+        struct TableDefinition {                                            \
+            typedef table_name::ColumnList ColumnList;                      \
+            typedef table_name::Row Row;                                    \
+            static const char* GetName() { return STRINGIFY(table_name); }  \
+            static DPL::DB::SqlConnection::DataCommand *AllocTableDataCommand( \
+                const std::string &statement,                               \
+                IOrmInterface *interface)                                   \
+            {                                                               \
+                Assert(interface != NULL);                                  \
+                return interface->AllocDataCommand(statement);              \
+            }                                                               \
+            static void FreeTableDataCommand(                               \
+                DPL::DB::SqlConnection::DataCommand *command,               \
+                IOrmInterface *interface)                                   \
+            {                                                               \
+                Assert(interface != NULL);                                  \
+                interface->FreeDataCommand(command);                        \
+            }                                                               \
+            static DPL::DB::SqlConnection::RowID GetLastInsertRowID(        \
+                IOrmInterface *interface)                                   \
+            {                                                               \
+                Assert(interface != NULL);                                  \
+                return interface->GetLastInsertRowID();                     \
+            }                                                               \
+        };                                                                  \
+    }
+
+#define COLUMN_NOT_NULL(name, type, ...)
+#define COLUMN(name, type, ...)
+#define CREATE_TABLE_END()
+
+#include ORM_GENERATOR_DATABASE_NAME_LOCAL
+
+#undef CREATE_TABLE
+#undef COLUMN_NOT_NULL
+#undef COLUMN
+#undef CREATE_TABLE_END
+
+// Query typedefs
+
+#define CREATE_TABLE(name) \
+    namespace name { \
+        typedef Select<TableDefinition> Select; \
+        typedef Insert<TableDefinition> Insert; \
+        typedef Delete<TableDefinition> Delete; \
+        typedef Update<TableDefinition> Update; \
+    }
+#define COLUMN_NOT_NULL(name, type, ...)
+#define COLUMN(name, type, ...)
+#define CREATE_TABLE_END()
+
+#include ORM_GENERATOR_DATABASE_NAME_LOCAL
+
+#undef CREATE_TABLE
+#undef COLUMN_NOT_NULL
+#undef COLUMN
+#undef CREATE_TABLE_END
+
+
+// Global undefs
+#undef INT
+#undef TINYINT
+#undef INTEGER
+#undef BIGINT
+#undef VARCHAR
+#undef TEXT
+
+#undef SQL
+#undef TABLE_CONSTRAINTS
+#undef OPTIONAL
+#undef DATABASE_START
+#undef DATABASE_END
+
+} //namespace ORM
+} //namespace DB
+} //namespace DPL
+
+#undef ORM_GENERATOR_DATABASE_NAME
+#undef ORM_GENERATOR_DATABASE_NAME_LOCAL
diff --git a/commons/modules/db/include/dpl/db/orm_interface.h b/commons/modules/db/include/dpl/db/orm_interface.h
new file mode 100644 (file)
index 0000000..62ec073
--- /dev/null
@@ -0,0 +1,48 @@
+/*
+ * 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    orm_interface.h
+ * @author  Lukasz Marek (l.marek@samsung.com)
+ * @version 1.0
+ */
+
+#include <string>
+#include <dpl/db/sql_connection.h>
+
+#ifndef DPL_ORM_INTERFACE_H
+#define DPL_ORM_INTERFACE_H
+
+namespace DPL {
+namespace DB {
+namespace ORM {
+class IOrmInterface
+{
+  public:
+    virtual ~IOrmInterface() {}
+    virtual DPL::DB::SqlConnection::DataCommand *AllocDataCommand(
+        const std::string &statement) = 0;
+    virtual void FreeDataCommand(DPL::DB::SqlConnection::DataCommand *command)
+        = 0;
+    virtual void TransactionBegin() = 0;
+    virtual void TransactionCommit() = 0;
+    virtual void TransactionRollback() = 0;
+    virtual DPL::DB::SqlConnection::RowID GetLastInsertRowID() = 0;
+};
+}
+}
+}
+
+#endif
diff --git a/commons/modules/db/include/dpl/db/orm_macros.h b/commons/modules/db/include/dpl/db/orm_macros.h
new file mode 100644 (file)
index 0000000..a038523
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+ * 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        orm_macros.h
+ * @author      Bartosz Janiak (b.janiak@samsung.com)
+ * @version     1.0
+ * @brief       Macro definitions for generating the SQL input file from
+ * database definition.
+ */
+
+//Do not include this file directly! It is used only for SQL code generation.
+
+#define CREATE_TABLE(name) CREATE TABLE name(
+#define COLUMN(name, type, ...) name type __VA_ARGS__,
+#define COLUMN_NOT_NULL(name, type, ...) name type __VA_ARGS__ not null,
+#define SQL(...) __VA_ARGS__
+#define TABLE_CONSTRAINTS(...) __VA_ARGS__,
+#define CREATE_TABLE_END() CHECK(1) );
+#define DATABASE_START(db_name)
+#define DATABASE_END()
+
diff --git a/commons/modules/db/include/dpl/db/sql_connection.h b/commons/modules/db/include/dpl/db/sql_connection.h
new file mode 100644 (file)
index 0000000..18a5d3f
--- /dev/null
@@ -0,0 +1,513 @@
+/*
+ * 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        sql_connection.h
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of SQL connection
+ */
+#ifndef DPL_SQL_CONNECTION_H
+#define DPL_SQL_CONNECTION_H
+
+#include <dpl/noncopyable.h>
+#include <dpl/exception.h>
+#include <dpl/availability.h>
+#include <memory>
+#include <boost/optional.hpp>
+#include <dpl/string.h>
+#include <dpl/log/log.h>
+#include <sqlite3.h>
+#include <string>
+#include <dpl/assert.h>
+#include <memory>
+#include <stdint.h>
+
+namespace DPL {
+namespace DB {
+/**
+ * SQL connection class
+ */
+class SqlConnection
+{
+  public:
+    /**
+     * SQL Exception classes
+     */
+    class Exception
+    {
+      public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, SyntaxError)
+        DECLARE_EXCEPTION_TYPE(Base, ConnectionBroken)
+        DECLARE_EXCEPTION_TYPE(Base, InternalError)
+        DECLARE_EXCEPTION_TYPE(Base, InvalidColumn)
+    };
+
+    typedef int ColumnIndex;
+    typedef int ArgumentIndex;
+
+    /*
+     * SQL processed data command
+     */
+    class DataCommand :
+        private Noncopyable
+    {
+      private:
+        SqlConnection *m_masterConnection;
+        sqlite3_stmt *m_stmt;
+
+        void CheckBindResult(int result);
+        void CheckColumnIndex(SqlConnection::ColumnIndex column);
+
+        DataCommand(SqlConnection *connection, const char *buffer);
+
+        friend class SqlConnection;
+
+      public:
+        virtual ~DataCommand();
+
+        /**
+         * Bind null to the prepared statement argument
+         *
+         * @param position Index of argument to bind value to
+         */
+        void BindNull(ArgumentIndex position);
+
+        /**
+         * Bind int to the prepared statement argument
+         *
+         * @param position Index of argument to bind value to
+         * @param value Value to bind
+         */
+        void BindInteger(ArgumentIndex position, int value);
+
+        /**
+         * Bind int8_t to the prepared statement argument
+         *
+         * @param position Index of argument to bind value to
+         * @param value Value to bind
+         */
+        void BindInt8(ArgumentIndex position, int8_t value);
+
+        /**
+         * Bind int16 to the prepared statement argument
+         *
+         * @param position Index of argument to bind value to
+         * @param value Value to bind
+         */
+        void BindInt16(ArgumentIndex position, int16_t value);
+
+        /**
+         * Bind int32 to the prepared statement argument
+         *
+         * @param position Index of argument to bind value to
+         * @param value Value to bind
+         */
+        void BindInt32(ArgumentIndex position, int32_t value);
+
+        /**
+         * Bind int64 to the prepared statement argument
+         *
+         * @param position Index of argument to bind value to
+         * @param value Value to bind
+         */
+        void BindInt64(ArgumentIndex position, int64_t value);
+
+        /**
+         * Bind float to the prepared statement argument
+         *
+         * @param position Index of argument to bind value to
+         * @param value Value to bind
+         */
+        void BindFloat(ArgumentIndex position, float value);
+
+        /**
+         * Bind double to the prepared statement argument
+         *
+         * @param position Index of argument to bind value to
+         * @param value Value to bind
+         */
+        void BindDouble(ArgumentIndex position, double value);
+
+        /**
+         * Bind string to the prepared statement argument
+         *
+         * @param position Index of argument to bind value to
+         * @param value Value to bind
+         */
+        void BindString(ArgumentIndex position, const char *value);
+
+        /**
+         * Bind string to the prepared statement argument
+         *
+         * @param position Index of argument to bind value to
+         * @param value Value to bind
+         */
+        void BindString(ArgumentIndex position, const String& value);
+
+        /**
+         * Bind optional int to the prepared statement argument.
+         * If optional is not set null will be bound
+         *
+         * @param position Index of argument to bind value to
+         * @param value Value to bind
+         */
+        void BindInteger(ArgumentIndex position, const boost::optional<int> &value);
+
+        /**
+         * Bind optional int8 to the prepared statement argument.
+         * If optional is not set null will be bound
+         *
+         * @param position Index of argument to bind value to
+         * @param value Value to bind
+         */
+        void BindInt8(ArgumentIndex position, const boost::optional<int8_t> &value);
+
+        /**
+         * Bind optional int16 to the prepared statement argument.
+         * If optional is not set null will be bound
+         *
+         * @param position Index of argument to bind value to
+         * @param value Value to bind
+         */
+        void BindInt16(ArgumentIndex position, const boost::optional<int16_t> &value);
+
+        /**
+         * Bind optional int32 to the prepared statement argument.
+         * If optional is not set null will be bound
+         *
+         * @param position Index of argument to bind value to
+         * @param value Value to bind
+         */
+        void BindInt32(ArgumentIndex position, const boost::optional<int32_t> &value);
+
+        /**
+         * Bind optional int64 to the prepared statement argument.
+         * If optional is not set null will be bound
+         *
+         * @param position Index of argument to bind value to
+         * @param value Value to bind
+         */
+        void BindInt64(ArgumentIndex position, const boost::optional<int64_t> &value);
+
+        /**
+         * Bind optional float to the prepared statement argument.
+         * If optional is not set null will be bound
+         *
+         * @param position Index of argument to bind value to
+         * @param value Value to bind
+         */
+        void BindFloat(ArgumentIndex position, const boost::optional<float> &value);
+
+        /**
+         * Bind optional double to the prepared statement argument.
+         * If optional is not set null will be bound
+         *
+         * @param position Index of argument to bind value to
+         * @param value Value to bind
+         */
+        void BindDouble(ArgumentIndex position, const boost::optional<double> &value);
+
+        /**
+         * Bind optional string to the prepared statement argument.
+         * If optional is not set null will be bound
+         *
+         * @param position Index of argument to bind value to
+         * @param value Value to bind
+         */
+        void BindString(ArgumentIndex position, const boost::optional<String> &value);
+
+        /**
+         * Execute the prepared statement and/or move
+         * to the next row of the result
+         *
+         * @return True when there was a row returned
+         */
+        bool Step();
+
+        /**
+         * Reset prepared statement's arguments
+         * All parameters will become null
+         */
+        void Reset();
+
+        /**
+         * Checks whether column value is null
+         *
+         * @throw Exception::InvalidColumn
+         */
+        bool IsColumnNull(ColumnIndex column);
+
+        /**
+         * Get integer value from column in current row.
+         *
+         * @throw Exception::InvalidColumn
+         */
+        int GetColumnInteger(ColumnIndex column);
+
+        /**
+         * Get int8 value from column in current row.
+         *
+         * @throw Exception::InvalidColumn
+         */
+        int8_t GetColumnInt8(ColumnIndex column);
+
+        /**
+         * Get int16 value from column in current row.
+         *
+         * @throw Exception::InvalidColumn
+         */
+        int16_t GetColumnInt16(ColumnIndex column);
+        /**
+         * Get int32 value from column in current row.
+         *
+         * @throw Exception::InvalidColumn
+         */
+        int32_t GetColumnInt32(ColumnIndex column);
+
+        /**
+         * Get int64 value from column in current row.
+         *
+         * @throw Exception::InvalidColumn
+         */
+        int64_t GetColumnInt64(ColumnIndex column);
+
+        /**
+         * Get float value from column in current row.
+         *
+         * @throw Exception::InvalidColumn
+         */
+        float GetColumnFloat(ColumnIndex column);
+
+        /**
+         * Get double value from column in current row.
+         *
+         * @throw Exception::InvalidColumn
+         */
+        double GetColumnDouble(ColumnIndex column);
+
+        /**
+         * Get string value from column in current row.
+         *
+         * @throw Exception::InvalidColumn
+         */
+        std::string GetColumnString(ColumnIndex column);
+
+        /**
+         * Get optional integer value from column in current row.
+         *
+         * @throw Exception::InvalidColumn
+         */
+        boost::optional<int> GetColumnOptionalInteger(ColumnIndex column);
+
+        /**
+         * Get optional int8 value from column in current row.
+         *
+         * @throw Exception::InvalidColumn
+         */
+        boost::optional<int8_t> GetColumnOptionalInt8(ColumnIndex column);
+
+        /**
+         * Get optional int16value from column in current row.
+         *
+         * @throw Exception::InvalidColumn
+         */
+        boost::optional<int16_t> GetColumnOptionalInt16(ColumnIndex column);
+
+        /**
+         * Get optional int32 value from column in current row.
+         *
+         * @throw Exception::InvalidColumn
+         */
+        boost::optional<int32_t> GetColumnOptionalInt32(ColumnIndex column);
+
+        /**
+         * Get optional int64 value from column in current row.
+         *
+         * @throw Exception::InvalidColumn
+         */
+        boost::optional<int64_t> GetColumnOptionalInt64(ColumnIndex column);
+
+        /**
+         * Get optional float value from column in current row.
+         *
+         * @throw Exception::InvalidColumn
+         */
+        boost::optional<float> GetColumnOptionalFloat(ColumnIndex column);
+
+        /**
+         * Get optional double value from column in current row.
+         *
+         * @throw Exception::InvalidColumn
+         */
+        boost::optional<double> GetColumnOptionalDouble(ColumnIndex column);
+
+        /**
+         * Get optional string value from column in current row.
+         *
+         * @throw Exception::InvalidColumn
+         */
+        boost::optional<String> GetColumnOptionalString(ColumnIndex column);
+    };
+
+    // Move on copy semantics
+    typedef std::auto_ptr<DataCommand> DataCommandAutoPtr;
+
+    // Open flags
+    class Flag
+    {
+      public:
+        enum Type
+        {
+            None = 1 << 0,
+            UseLucene = 1 << 1
+        };
+
+        enum Option
+        {
+            RO = SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_READONLY,
+            /**
+             * *TODO: please remove CREATE option from RW flag when all places
+             *      that need that switched do CRW
+             */
+            RW = SQLITE_OPEN_NOMUTEX | SQLITE_OPEN_READWRITE |
+                SQLITE_OPEN_CREATE,
+            CRW = RW | SQLITE_OPEN_CREATE
+        };
+    };
+
+    // RowID
+    typedef sqlite3_int64 RowID;
+
+    /**
+     * Synchronization object used to synchronize SQL connection
+     * to the same database across different threads and processes
+     */
+    class SynchronizationObject
+    {
+      public:
+        virtual ~SynchronizationObject() {}
+
+        /**
+         * Synchronizes SQL connection for multiple clients.
+         */
+        virtual void Synchronize() = 0;
+
+        /**
+         * Notify all waiting clients that the connection is no longer locked.
+         */
+        virtual void NotifyAll() = 0;
+    };
+
+  protected:
+    sqlite3 *m_connection;
+
+    // Options
+    bool m_usingLucene;
+
+    // Stored data procedures
+    int m_dataCommandsCount;
+
+    // Synchronization object
+    std::unique_ptr<SynchronizationObject> m_synchronizationObject;
+
+    virtual void Connect(const std::string &address,
+                         Flag::Type = Flag::None, Flag::Option = Flag::RO);
+    virtual void Disconnect();
+
+    void TurnOnForeignKeys();
+
+    static SynchronizationObject *AllocDefaultSynchronizationObject();
+
+  public:
+    /**
+     * Open SQL connection
+     *
+     * Synchronization is archieved by using provided asynchronization object.
+     * If synchronizationObject is set to NULL, so synchronization is performed.
+     * Ownership of the synchronization object is transfered to sql connection
+     * object.
+     *
+     * @param address Database file name
+     * @param flags Open flags
+     * @param synchronizationObject A synchronization object to use.
+     */
+    explicit SqlConnection(const std::string &address = std::string(),
+                           Flag::Type flags = Flag::None,
+                           Flag::Option options = Flag::RO,
+                           SynchronizationObject *synchronizationObject =
+                               AllocDefaultSynchronizationObject());
+
+    /**
+     * Destructor
+     */
+    virtual ~SqlConnection();
+
+    /**
+     * Execute SQL command without result
+     *
+     * @param format
+     * @param ...
+     */
+    void ExecCommand(const char *format, ...) DPL_DEPRECATED_WITH_MESSAGE(
+            "To prevent sql injection do not use this \
+             method for direct sql execution");
+
+    /**
+     * Execute BEGIN; command to start new transaction
+     *
+     */
+    void BeginTransaction();
+
+    /**
+     * Execute ROLLBACK; command to discard changes made
+     *
+     */
+    void RollbackTransaction();
+
+    /**
+     * Execute COMMIT; command to commit changes in database
+     *
+     */
+    void CommitTransaction();
+
+    /**
+     * Prepare stored procedure
+     *
+     * @param format SQL statement
+     * @return Data command representing stored procedure
+     */
+    DataCommandAutoPtr PrepareDataCommand(const char *format, ...);
+
+    /**
+     * Check whether given table exists
+     *
+     * @param tableName Name of the table to check
+     * @return True if given table name exists
+     */
+    bool CheckTableExist(const char *tableName);
+
+    /**
+     * Get last insert operation new row id
+     *
+     * @return Row ID
+     */
+    RowID GetLastInsertRowID() const;
+};
+} // namespace DB
+} // namespace DPL
+
+#endif // DPL_SQL_CONNECTION_H
diff --git a/commons/modules/db/include/dpl/db/thread_database_support.h b/commons/modules/db/include/dpl/db/thread_database_support.h
new file mode 100644 (file)
index 0000000..04ec923
--- /dev/null
@@ -0,0 +1,300 @@
+/*
+ * 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    thread_database_support.h
+ * @author  Przemyslaw Dobrowolski (p.dobrowolsk)
+ * @version 1.0
+ * @brief   This file contains the declaration of thread database support
+ */
+
+#ifndef DPL_THREAD_DATABASE_SUPPORT_H
+#define DPL_THREAD_DATABASE_SUPPORT_H
+
+#include <string>
+#include <dpl/db/sql_connection.h>
+#include <dpl/db/orm_interface.h>
+#include <dpl/thread.h>
+#include <dpl/assert.h>
+#include <stdint.h>
+
+namespace DPL {
+namespace DB {
+/**
+ * Thread database support
+ *
+ * Associate database connection with thread lifecycle
+ *
+ */
+
+class ThreadDatabaseSupport :
+    public DPL::DB::ORM::IOrmInterface
+{
+  private:
+    typedef DPL::DB::SqlConnection *SqlConnectionPtr;
+    typedef DPL::ThreadLocalVariable<SqlConnectionPtr> TLVSqlConnectionPtr;
+    typedef DPL::ThreadLocalVariable<size_t> TLVSizeT;
+    typedef DPL::ThreadLocalVariable<bool> TLVBool;
+
+    TLVSqlConnectionPtr m_connection;
+    TLVBool m_linger;
+    TLVSizeT m_refCounter;
+    TLVSizeT m_transactionDepth;
+    TLVSizeT m_attachCount;
+    TLVBool m_transactionCancel;
+    std::string m_address;
+    DPL::DB::SqlConnection::Flag::Type m_flags;
+
+    TLVSqlConnectionPtr &Connection()
+    {
+        return m_connection;
+    }
+
+    TLVBool &Linger()
+    {
+        return m_linger;
+    }
+
+    TLVSizeT &RefCounter()
+    {
+        return m_refCounter;
+    }
+
+    TLVSizeT &TransactionDepth()
+    {
+        return m_transactionDepth;
+    }
+
+    TLVSizeT &AttachCount()
+    {
+        return m_attachCount;
+    }
+
+    TLVBool &TransactionCancel()
+    {
+        return m_transactionCancel;
+    }
+
+    void CheckedConnectionDelete()
+    {
+        Assert(!Connection().IsNull());
+        Assert(*Linger() == true);
+
+        if (*RefCounter() > 0 || *AttachCount() > 0) {
+            return;
+        }
+
+        // Destroy connection
+        LogDebug("Destroying thread database connection: " << m_address);
+
+        delete *Connection();
+
+        // Blocking destroy
+        Connection().GuardValue(false);
+        Linger().GuardValue(false);
+        RefCounter().GuardValue(false);
+        TransactionCancel().GuardValue(false);
+        TransactionDepth().GuardValue(false);
+        AttachCount().GuardValue(false);
+
+        Connection().Reset();
+        Linger().Reset();
+        RefCounter().Reset();
+        TransactionCancel().Reset();
+        TransactionDepth().Reset();
+        AttachCount().Reset();
+    }
+
+    void TransactionUnref()
+    {
+        LogPedantic("Unref transaction");
+
+        if (--(*TransactionDepth()) == 0) {
+            LogPedantic("Transaction is finalized");
+
+            if (*TransactionCancel()) {
+                LogPedantic("Transaction will be rolled back");
+                (*Connection())->RollbackTransaction();
+            } else {
+                LogPedantic("Transaction will be commited");
+                (*Connection())->CommitTransaction();
+            }
+        }
+    }
+
+  public:
+    ThreadDatabaseSupport(const std::string &address,
+                          DPL::DB::SqlConnection::Flag::Type flags) :
+        m_address(address),
+        m_flags(flags)
+    {}
+
+    virtual ~ThreadDatabaseSupport()
+    {}
+
+    void AttachToThread(
+        DPL::DB::SqlConnection::Flag::Option options =
+            DPL::DB::SqlConnection::Flag::RO)
+    {
+        Linger() = false;
+
+        if (!Connection().IsNull()) {
+            // Add reference
+            ++*AttachCount();
+            return;
+        }
+
+        // Initialize SQL connection described in traits
+        LogDebug("Attaching thread database connection: " << m_address);
+
+        Connection() = new DPL::DB::SqlConnection(
+                m_address.c_str(), m_flags, options);
+
+        RefCounter() = 0;
+
+        AttachCount() = 1;
+
+        //Init Transaction related variables
+        TransactionDepth() = 0;
+        TransactionCancel() = false;
+
+        // Blocking destroy
+        Connection().GuardValue(true);
+        Linger().GuardValue(true);
+        RefCounter().GuardValue(true);
+        TransactionDepth().GuardValue(true);
+        AttachCount().GuardValue(true);
+        TransactionCancel().GuardValue(true);
+    }
+
+    void DetachFromThread()
+    {
+        // Calling thread must support thread database connections
+        Assert(!Connection().IsNull());
+
+        // Remove reference
+        --*AttachCount();
+
+        if (*AttachCount() > 0) {
+            return;
+        }
+
+        // It must not be in linger state yet
+        Assert(*Linger() == false);
+
+        LogDebug("Detaching thread database connection: " << m_address);
+
+        // Enter linger state
+        *Linger() = true;
+
+        // Checked delete
+        CheckedConnectionDelete();
+    }
+
+    bool IsAttached()
+    {
+        return !AttachCount().IsNull() && *AttachCount() > 0;
+    }
+
+    DPL::DB::SqlConnection::DataCommand *AllocDataCommand(
+        const std::string &statement)
+    {
+        // Calling thread must support thread database connections
+        Assert(!Connection().IsNull());
+
+        // Calling thread must not be in linger state
+        Assert(*Linger() == false);
+
+        // Add reference
+        ++*RefCounter();
+
+        // Create new unmanaged data command
+        return (*Connection())->PrepareDataCommand(statement.c_str()).release();
+    }
+
+    void FreeDataCommand(DPL::DB::SqlConnection::DataCommand *command)
+    {
+        // Calling thread must support thread database connections
+        Assert(!Connection().IsNull());
+
+        // Delete data command
+        delete command;
+
+        // Unreference SQL connection
+        --*RefCounter();
+
+        // If it is linger state, connection may be destroyed
+        if (*Linger() == true) {
+            CheckedConnectionDelete();
+        }
+    }
+
+    void TransactionBegin()
+    {
+        // Calling thread must support thread database connections
+        Assert(!Connection().IsNull());
+
+        LogPedantic("Begin transaction");
+
+        // Addref transaction
+        if (++(*TransactionDepth()) == 1) {
+            LogPedantic("Transaction is initialized");
+
+            TransactionCancel() = false;
+            (*Connection())->BeginTransaction();
+        }
+    }
+
+    void TransactionCommit()
+    {
+        // Calling thread must support thread database connections
+        Assert(!Connection().IsNull());
+
+        LogPedantic("Commit transaction");
+
+        // Unref transation
+        TransactionUnref();
+    }
+
+    void TransactionRollback()
+    {
+        // Calling thread must support thread database connections
+        Assert(!Connection().IsNull());
+
+        // Cancel and unref transaction
+        TransactionCancel() = true;
+        TransactionUnref();
+    }
+
+    DPL::DB::SqlConnection::RowID GetLastInsertRowID()
+    {
+        // Calling thread must support thread database connections
+        Assert(!Connection().IsNull());
+
+        return (*Connection())->GetLastInsertRowID();
+    }
+
+    bool CheckTableExist(const char *name)
+    {
+        // Calling thread must support thread database connections
+        Assert(!Connection().IsNull());
+
+        return (*Connection())->CheckTableExist(name);
+    }
+};
+}
+}
+
+#endif // DPL_THREAD_DATABASE_SUPPORT_H
diff --git a/commons/modules/db/src/naive_synchronization_object.cpp b/commons/modules/db/src/naive_synchronization_object.cpp
new file mode 100644 (file)
index 0000000..1ac71ca
--- /dev/null
@@ -0,0 +1,44 @@
+/*
+ * 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        naive_synchronization_object.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of SQL naive
+ * synchronization object
+ */
+#include <stddef.h>
+#include <dpl/db/naive_synchronization_object.h>
+#include <dpl/thread.h>
+
+namespace {
+    unsigned int seed = time(NULL);
+}
+
+namespace DPL {
+namespace DB {
+void NaiveSynchronizationObject::Synchronize()
+{
+    // Sleep for about 10ms - 30ms
+    Thread::MiliSleep(10 + rand_r(&seed) % 20);
+}
+
+void NaiveSynchronizationObject::NotifyAll()
+{
+    // No need to inform about anything
+}
+} // namespace DB
+} // namespace DPL
diff --git a/commons/modules/db/src/orm.cpp b/commons/modules/db/src/orm.cpp
new file mode 100644 (file)
index 0000000..c69415d
--- /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        orm.cpp
+ * @author      Bartosz Janiak (b.janiak@samsung.com)
+ * @version     1.0
+ * @brief       Static definitions and function template specialziations of
+ * DPL-ORM.
+ */
+#include <stddef.h>
+#include <dpl/db/orm.h>
+
+namespace DPL {
+namespace DB {
+namespace ORM {
+namespace RelationTypes {
+const char Equal[] = "=";
+const char LessThan[] = "<";
+const char And[] = "AND";
+const char Or[] = "OR";
+const char Is[] = "IS";
+const char In[] = "IN";
+}
+
+template<>
+int GetColumnFromCommand<int>(ColumnIndex columnIndex,
+                              DataCommand *command)
+{
+    return command->GetColumnInteger(columnIndex);
+}
+
+template<>
+DPL::String GetColumnFromCommand<DPL::String>(ColumnIndex columnIndex,
+                                              DataCommand *command)
+{
+    return DPL::FromUTF8String(command->GetColumnString(columnIndex));
+}
+
+template<>
+OptionalInteger GetColumnFromCommand<OptionalInteger>(ColumnIndex columnIndex,
+                                                      DataCommand *command)
+{
+    return command->GetColumnOptionalInteger(columnIndex);
+}
+
+template<>
+OptionalString GetColumnFromCommand<OptionalString>(ColumnIndex columnIndex,
+                                                    DataCommand *command)
+{
+    return command->GetColumnOptionalString(columnIndex);
+}
+
+template<>
+double GetColumnFromCommand<double>(ColumnIndex columnIndex,
+                                    DataCommand *command)
+{
+    return command->GetColumnDouble(columnIndex);
+}
+
+void DataCommandUtils::BindArgument(DataCommand *command,
+                                    ArgumentIndex index,
+                                    int argument)
+{
+    command->BindInteger(index, argument);
+}
+
+void DataCommandUtils::BindArgument(DataCommand *command,
+                                    ArgumentIndex index,
+                                    const OptionalInteger& argument)
+{
+    command->BindInteger(index, argument);
+}
+
+void DataCommandUtils::BindArgument(DataCommand *command,
+                                    ArgumentIndex index,
+                                    const DPL::String& argument)
+{
+    command->BindString(index, argument);
+}
+
+void DataCommandUtils::BindArgument(DataCommand *command,
+                                    ArgumentIndex index,
+                                    const OptionalString& argument)
+{
+    command->BindString(index, argument);
+}
+}
+}
+}
diff --git a/commons/modules/db/src/sql_connection.cpp b/commons/modules/db/src/sql_connection.cpp
new file mode 100644 (file)
index 0000000..a98a364
--- /dev/null
@@ -0,0 +1,874 @@
+/*
+ * 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        sql_connection.cpp
+ * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version     1.0
+ * @brief       This file is the implementation file of SQL connection
+ */
+#include <stddef.h>
+#include <dpl/db/sql_connection.h>
+#include <dpl/db/naive_synchronization_object.h>
+#include <dpl/free_deleter.h>
+#include <memory>
+#include <dpl/noncopyable.h>
+#include <dpl/assert.h>
+#include <db-util.h>
+#include <unistd.h>
+#include <cstdio>
+#include <cstdarg>
+
+namespace DPL {
+namespace DB {
+namespace // anonymous
+{
+class ScopedNotifyAll :
+    public Noncopyable
+{
+  private:
+    SqlConnection::SynchronizationObject *m_synchronizationObject;
+
+  public:
+    explicit ScopedNotifyAll(
+        SqlConnection::SynchronizationObject *synchronizationObject) :
+        m_synchronizationObject(synchronizationObject)
+    {}
+
+    ~ScopedNotifyAll()
+    {
+        if (!m_synchronizationObject) {
+            return;
+        }
+
+        LogPedantic("Notifying after successful synchronize");
+        m_synchronizationObject->NotifyAll();
+    }
+};
+} // namespace anonymous
+
+SqlConnection::DataCommand::DataCommand(SqlConnection *connection,
+                                        const char *buffer) :
+    m_masterConnection(connection),
+    m_stmt(NULL)
+{
+    Assert(connection != NULL);
+
+    // Notify all after potentially synchronized database connection access
+    ScopedNotifyAll notifyAll(connection->m_synchronizationObject.get());
+
+    for (;;) {
+        int ret = sqlite3_prepare_v2(connection->m_connection,
+                                     buffer, strlen(buffer),
+                                     &m_stmt, NULL);
+
+        if (ret == SQLITE_OK) {
+            LogPedantic("Data command prepared successfuly");
+            break;
+        } else if (ret == SQLITE_BUSY) {
+            LogPedantic("Collision occurred while preparing SQL command");
+
+            // Synchronize if synchronization object is available
+            if (connection->m_synchronizationObject) {
+                LogPedantic("Performing synchronization");
+                connection->m_synchronizationObject->Synchronize();
+                continue;
+            }
+
+            // No synchronization object defined. Fail.
+        }
+
+        // Fatal error
+        const char *error = sqlite3_errmsg(m_masterConnection->m_connection);
+
+        LogPedantic("SQL prepare data command failed");
+        LogPedantic("    Statement: " << buffer);
+        LogPedantic("    Error: " << error);
+
+        ThrowMsg(Exception::SyntaxError, error);
+    }
+
+    LogPedantic("Prepared data command: " << buffer);
+
+    // Increment stored data command count
+    ++m_masterConnection->m_dataCommandsCount;
+}
+
+SqlConnection::DataCommand::~DataCommand()
+{
+    LogPedantic("SQL data command finalizing");
+
+    if (sqlite3_finalize(m_stmt) != SQLITE_OK) {
+        LogPedantic("Failed to finalize data command");
+    }
+
+    // Decrement stored data command count
+    --m_masterConnection->m_dataCommandsCount;
+}
+
+void SqlConnection::DataCommand::CheckBindResult(int result)
+{
+    if (result != SQLITE_OK) {
+        const char *error = sqlite3_errmsg(
+                m_masterConnection->m_connection);
+
+        LogPedantic("Failed to bind SQL statement parameter");
+        LogPedantic("    Error: " << error);
+
+        ThrowMsg(Exception::SyntaxError, error);
+    }
+}
+
+void SqlConnection::DataCommand::BindNull(
+    SqlConnection::ArgumentIndex position)
+{
+    CheckBindResult(sqlite3_bind_null(m_stmt, position));
+    LogPedantic("SQL data command bind null: ["
+                << position << "]");
+}
+
+void SqlConnection::DataCommand::BindInteger(
+    SqlConnection::ArgumentIndex position,
+    int value)
+{
+    CheckBindResult(sqlite3_bind_int(m_stmt, position, value));
+    LogPedantic("SQL data command bind integer: ["
+                << position << "] -> " << value);
+}
+
+void SqlConnection::DataCommand::BindInt8(
+    SqlConnection::ArgumentIndex position,
+    int8_t value)
+{
+    CheckBindResult(sqlite3_bind_int(m_stmt, position,
+                                     static_cast<int>(value)));
+    LogPedantic("SQL data command bind int8: ["
+                << position << "] -> " << value);
+}
+
+void SqlConnection::DataCommand::BindInt16(
+    SqlConnection::ArgumentIndex position,
+    int16_t value)
+{
+    CheckBindResult(sqlite3_bind_int(m_stmt, position,
+                                     static_cast<int>(value)));
+    LogPedantic("SQL data command bind int16: ["
+                << position << "] -> " << value);
+}
+
+void SqlConnection::DataCommand::BindInt32(
+    SqlConnection::ArgumentIndex position,
+    int32_t value)
+{
+    CheckBindResult(sqlite3_bind_int(m_stmt, position,
+                                     static_cast<int>(value)));
+    LogPedantic("SQL data command bind int32: ["
+                << position << "] -> " << value);
+}
+
+void SqlConnection::DataCommand::BindInt64(
+    SqlConnection::ArgumentIndex position,
+    int64_t value)
+{
+    CheckBindResult(sqlite3_bind_int64(m_stmt, position,
+                                       static_cast<sqlite3_int64>(value)));
+    LogPedantic("SQL data command bind int64: ["
+                << position << "] -> " << value);
+}
+
+void SqlConnection::DataCommand::BindFloat(
+    SqlConnection::ArgumentIndex position,
+    float value)
+{
+    CheckBindResult(sqlite3_bind_double(m_stmt, position,
+                                        static_cast<double>(value)));
+    LogPedantic("SQL data command bind float: ["
+                << position << "] -> " << value);
+}
+
+void SqlConnection::DataCommand::BindDouble(
+    SqlConnection::ArgumentIndex position,
+    double value)
+{
+    CheckBindResult(sqlite3_bind_double(m_stmt, position, value));
+    LogPedantic("SQL data command bind double: ["
+                << position << "] -> " << value);
+}
+
+void SqlConnection::DataCommand::BindString(
+    SqlConnection::ArgumentIndex position,
+    const char *value)
+{
+    if (!value) {
+        BindNull(position);
+        return;
+    }
+
+    // Assume that text may disappear
+    CheckBindResult(sqlite3_bind_text(m_stmt, position,
+                                      value, strlen(value),
+                                      SQLITE_TRANSIENT));
+
+    LogPedantic("SQL data command bind string: ["
+                << position << "] -> " << value);
+}
+
+void SqlConnection::DataCommand::BindString(
+    SqlConnection::ArgumentIndex position,
+    const String &value)
+{
+    BindString(position, ToUTF8String(value).c_str());
+}
+
+void SqlConnection::DataCommand::BindInteger(
+    SqlConnection::ArgumentIndex position,
+    const boost::optional<int> &value)
+{
+    if (!value) {
+        BindNull(position);
+    } else {
+        BindInteger(position, *value);
+    }
+}
+
+void SqlConnection::DataCommand::BindInt8(
+    SqlConnection::ArgumentIndex position,
+    const boost::optional<int8_t> &value)
+{
+    if (!value) {
+        BindNull(position);
+    } else {
+        BindInt8(position, *value);
+    }
+}
+
+void SqlConnection::DataCommand::BindInt16(
+    SqlConnection::ArgumentIndex position,
+    const boost::optional<int16_t> &value)
+{
+    if (!value) {
+        BindNull(position);
+    } else {
+        BindInt16(position, *value);
+    }
+}
+
+void SqlConnection::DataCommand::BindInt32(
+    SqlConnection::ArgumentIndex position,
+    const boost::optional<int32_t> &value)
+{
+    if (!value) {
+        BindNull(position);
+    } else {
+        BindInt32(position, *value);
+    }
+}
+
+void SqlConnection::DataCommand::BindInt64(
+    SqlConnection::ArgumentIndex position,
+    const boost::optional<int64_t> &value)
+{
+    if (!value) {
+        BindNull(position);
+    } else {
+        BindInt64(position, *value);
+    }
+}
+
+void SqlConnection::DataCommand::BindFloat(
+    SqlConnection::ArgumentIndex position,
+    const boost::optional<float> &value)
+{
+    if (!value) {
+        BindNull(position);
+    } else {
+        BindFloat(position, *value);
+    }
+}
+
+void SqlConnection::DataCommand::BindDouble(
+    SqlConnection::ArgumentIndex position,
+    const boost::optional<double> &value)
+{
+    if (!value) {
+        BindNull(position);
+    } else {
+        BindDouble(position, *value);
+    }
+}
+
+void SqlConnection::DataCommand::BindString(
+    SqlConnection::ArgumentIndex position,
+    const boost::optional<String> &value)
+{
+    if (!!value) {
+        BindString(position, ToUTF8String(*value).c_str());
+    } else {
+        BindNull(position);
+    }
+}
+
+bool SqlConnection::DataCommand::Step()
+{
+    // Notify all after potentially synchronized database connection access
+    ScopedNotifyAll notifyAll(
+        m_masterConnection->m_synchronizationObject.get());
+
+    for (;;) {
+        int ret = sqlite3_step(m_stmt);
+
+        if (ret == SQLITE_ROW) {
+            LogPedantic("SQL data command step ROW");
+            return true;
+        } else if (ret == SQLITE_DONE) {
+            LogPedantic("SQL data command step DONE");
+            return false;
+        } else if (ret == SQLITE_BUSY) {
+            LogPedantic("Collision occurred while executing SQL command");
+
+            // Synchronize if synchronization object is available
+            if (m_masterConnection->m_synchronizationObject) {
+                LogPedantic("Performing synchronization");
+
+                m_masterConnection->
+                    m_synchronizationObject->Synchronize();
+
+                continue;
+            }
+
+            // No synchronization object defined. Fail.
+        }
+
+        // Fatal error
+        const char *error = sqlite3_errmsg(m_masterConnection->m_connection);
+
+        LogPedantic("SQL step data command failed");
+        LogPedantic("    Error: " << error);
+
+        ThrowMsg(Exception::InternalError, error);
+    }
+}
+
+void SqlConnection::DataCommand::Reset()
+{
+    /*
+     * According to:
+     * http://www.sqlite.org/c3ref/stmt.html
+     *
+     * if last sqlite3_step command on this stmt returned an error,
+     * then sqlite3_reset will return that error, althought it is not an error.
+     * So sqlite3_reset allways succedes.
+     */
+    sqlite3_reset(m_stmt);
+
+    LogPedantic("SQL data command reset");
+}
+
+void SqlConnection::DataCommand::CheckColumnIndex(
+    SqlConnection::ColumnIndex column)
+{
+    if (column < 0 || column >= sqlite3_column_count(m_stmt)) {
+        ThrowMsg(Exception::InvalidColumn, "Column index is out of bounds");
+    }
+}
+
+bool SqlConnection::DataCommand::IsColumnNull(
+    SqlConnection::ColumnIndex column)
+{
+    LogPedantic("SQL data command get column type: [" << column << "]");
+    CheckColumnIndex(column);
+    return sqlite3_column_type(m_stmt, column) == SQLITE_NULL;
+}
+
+int SqlConnection::DataCommand::GetColumnInteger(
+    SqlConnection::ColumnIndex column)
+{
+    LogPedantic("SQL data command get column integer: [" << column << "]");
+    CheckColumnIndex(column);
+    int value = sqlite3_column_int(m_stmt, column);
+    LogPedantic("    Value: " << value);
+    return value;
+}
+
+int8_t SqlConnection::DataCommand::GetColumnInt8(
+    SqlConnection::ColumnIndex column)
+{
+    LogPedantic("SQL data command get column int8: [" << column << "]");
+    CheckColumnIndex(column);
+    int8_t value = static_cast<int8_t>(sqlite3_column_int(m_stmt, column));
+    LogPedantic("    Value: " << value);
+    return value;
+}
+
+int16_t SqlConnection::DataCommand::GetColumnInt16(
+    SqlConnection::ColumnIndex column)
+{
+    LogPedantic("SQL data command get column int16: [" << column << "]");
+    CheckColumnIndex(column);
+    int16_t value = static_cast<int16_t>(sqlite3_column_int(m_stmt, column));
+    LogPedantic("    Value: " << value);
+    return value;
+}
+
+int32_t SqlConnection::DataCommand::GetColumnInt32(
+    SqlConnection::ColumnIndex column)
+{
+    LogPedantic("SQL data command get column int32: [" << column << "]");
+    CheckColumnIndex(column);
+    int32_t value = static_cast<int32_t>(sqlite3_column_int(m_stmt, column));
+    LogPedantic("    Value: " << value);
+    return value;
+}
+
+int64_t SqlConnection::DataCommand::GetColumnInt64(
+    SqlConnection::ColumnIndex column)
+{
+    LogPedantic("SQL data command get column int64: [" << column << "]");
+    CheckColumnIndex(column);
+    int64_t value = static_cast<int64_t>(sqlite3_column_int64(m_stmt, column));
+    LogPedantic("    Value: " << value);
+    return value;
+}
+
+float SqlConnection::DataCommand::GetColumnFloat(
+    SqlConnection::ColumnIndex column)
+{
+    LogPedantic("SQL data command get column float: [" << column << "]");
+    CheckColumnIndex(column);
+    float value = static_cast<float>(sqlite3_column_double(m_stmt, column));
+    LogPedantic("    Value: " << value);
+    return value;
+}
+
+double SqlConnection::DataCommand::GetColumnDouble(
+    SqlConnection::ColumnIndex column)
+{
+    LogPedantic("SQL data command get column double: [" << column << "]");
+    CheckColumnIndex(column);
+    double value = sqlite3_column_double(m_stmt, column);
+    LogPedantic("    Value: " << value);
+    return value;
+}
+
+std::string SqlConnection::DataCommand::GetColumnString(
+    SqlConnection::ColumnIndex column)
+{
+    LogPedantic("SQL data command get column string: [" << column << "]");
+    CheckColumnIndex(column);
+
+    const char *value = reinterpret_cast<const char *>(
+            sqlite3_column_text(m_stmt, column));
+
+    LogPedantic("Value: " << (value ? value : "NULL"));
+
+    if (value == NULL) {
+        return std::string();
+    }
+
+    return std::string(value);
+}
+
+boost::optional<int> SqlConnection::DataCommand::GetColumnOptionalInteger(
+    SqlConnection::ColumnIndex column)
+{
+    LogPedantic("SQL data command get column optional integer: ["
+                << column << "]");
+    CheckColumnIndex(column);
+    if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) {
+        return boost::optional<int>();
+    }
+    int value = sqlite3_column_int(m_stmt, column);
+    LogPedantic("    Value: " << value);
+    return boost::optional<int>(value);
+}
+
+boost::optional<int8_t> SqlConnection::DataCommand::GetColumnOptionalInt8(
+    SqlConnection::ColumnIndex column)
+{
+    LogPedantic("SQL data command get column optional int8: ["
+                << column << "]");
+    CheckColumnIndex(column);
+    if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) {
+        return boost::optional<int8_t>();
+    }
+    int8_t value = static_cast<int8_t>(sqlite3_column_int(m_stmt, column));
+    LogPedantic("    Value: " << value);
+    return boost::optional<int8_t>(value);
+}
+
+boost::optional<int16_t> SqlConnection::DataCommand::GetColumnOptionalInt16(
+    SqlConnection::ColumnIndex column)
+{
+    LogPedantic("SQL data command get column optional int16: ["
+                << column << "]");
+    CheckColumnIndex(column);
+    if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) {
+        return boost::optional<int16_t>();
+    }
+    int16_t value = static_cast<int16_t>(sqlite3_column_int(m_stmt, column));
+    LogPedantic("    Value: " << value);
+    return boost::optional<int16_t>(value);
+}
+
+boost::optional<int32_t> SqlConnection::DataCommand::GetColumnOptionalInt32(
+    SqlConnection::ColumnIndex column)
+{
+    LogPedantic("SQL data command get column optional int32: ["
+                << column << "]");
+    CheckColumnIndex(column);
+    if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) {
+        return boost::optional<int32_t>();
+    }
+    int32_t value = static_cast<int32_t>(sqlite3_column_int(m_stmt, column));
+    LogPedantic("    Value: " << value);
+    return boost::optional<int32_t>(value);
+}
+
+boost::optional<int64_t> SqlConnection::DataCommand::GetColumnOptionalInt64(
+    SqlConnection::ColumnIndex column)
+{
+    LogPedantic("SQL data command get column optional int64: ["
+                << column << "]");
+    CheckColumnIndex(column);
+    if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) {
+        return boost::optional<int64_t>();
+    }
+    int64_t value = static_cast<int64_t>(sqlite3_column_int64(m_stmt, column));
+    LogPedantic("    Value: " << value);
+    return boost::optional<int64_t>(value);
+}
+
+boost::optional<float> SqlConnection::DataCommand::GetColumnOptionalFloat(
+    SqlConnection::ColumnIndex column)
+{
+    LogPedantic("SQL data command get column optional float: ["
+                << column << "]");
+    CheckColumnIndex(column);
+    if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) {
+        return boost::optional<float>();
+    }
+    float value = static_cast<float>(sqlite3_column_double(m_stmt, column));
+    LogPedantic("    Value: " << value);
+    return boost::optional<float>(value);
+}
+
+boost::optional<double> SqlConnection::DataCommand::GetColumnOptionalDouble(
+    SqlConnection::ColumnIndex column)
+{
+    LogPedantic("SQL data command get column optional double: ["
+                << column << "]");
+    CheckColumnIndex(column);
+    if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) {
+        return boost::optional<double>();
+    }
+    double value = sqlite3_column_double(m_stmt, column);
+    LogPedantic("    Value: " << value);
+    return boost::optional<double>(value);
+}
+
+boost::optional<String> SqlConnection::DataCommand::GetColumnOptionalString(
+    SqlConnection::ColumnIndex column)
+{
+    LogPedantic("SQL data command get column optional string: ["
+                << column << "]");
+    CheckColumnIndex(column);
+    if (sqlite3_column_type(m_stmt, column) == SQLITE_NULL) {
+        return boost::optional<String>();
+    }
+    const char *value = reinterpret_cast<const char *>(
+            sqlite3_column_text(m_stmt, column));
+
+    if (value == NULL)
+        return boost::optional<String>();
+
+    LogPedantic("Value: " << value);
+    String s = FromUTF8String(value);
+    return boost::optional<String>(s);
+}
+
+void SqlConnection::Connect(const std::string &address,
+                            Flag::Type type,
+                            Flag::Option flag)
+{
+    if (m_connection != NULL) {
+        LogPedantic("Already connected.");
+        return;
+    }
+    LogPedantic("Connecting to DB: " << address << "...");
+
+    // Connect to database
+    int result = -1;
+    int retry = 5;
+    while( result != SQLITE_OK){
+        if (type & Flag::UseLucene) {
+            result = db_util_open_with_options(
+                    address.c_str(),
+                    &m_connection,
+                    flag,
+                    NULL);
+
+            m_usingLucene = true;
+            LogPedantic("Lucene index enabled");
+        } else {
+            result = sqlite3_open_v2(
+                    address.c_str(),
+                    &m_connection,
+                    flag,
+                    NULL);
+
+            m_usingLucene = false;
+            LogPedantic("Lucene index disabled");
+        }
+
+        if (result == SQLITE_OK) {
+            LogPedantic("Connected to DB");
+        } else {
+            LogPedantic("Failed to connect to DB! ret="<<result);
+            if( retry-- <= 0 )
+                ThrowMsg(Exception::ConnectionBroken, address);
+        }
+    }
+
+    // Enable foreign keys
+    TurnOnForeignKeys();
+}
+
+void SqlConnection::Disconnect()
+{
+    if (m_connection == NULL) {
+        LogPedantic("Already disconnected.");
+        return;
+    }
+
+    LogPedantic("Disconnecting from DB...");
+
+    // All stored data commands must be deleted before disconnect
+    AssertMsg(m_dataCommandsCount == 0,
+           "All stored procedures must be deleted"
+           " before disconnecting SqlConnection");
+
+    int result;
+
+    if (m_usingLucene) {
+        result = db_util_close(m_connection);
+    } else {
+        result = sqlite3_close(m_connection);
+    }
+
+    if (result != SQLITE_OK) {
+        const char *error = sqlite3_errmsg(m_connection);
+        LogPedantic("SQL close failed");
+        LogPedantic("    Error: " << error);
+        Throw(Exception::InternalError);
+    }
+
+    m_connection = NULL;
+
+    LogPedantic("Disconnected from DB");
+}
+
+bool SqlConnection::CheckTableExist(const char *tableName)
+{
+    if (m_connection == NULL) {
+        LogPedantic("Cannot execute command. Not connected to DB!");
+        return false;
+    }
+
+    DataCommandAutoPtr command =
+        PrepareDataCommand("select tbl_name from sqlite_master where name=?;");
+
+    command->BindString(1, tableName);
+
+    if (!command->Step()) {
+        LogPedantic("No matching records in table");
+        return false;
+    }
+
+    return command->GetColumnString(0) == tableName;
+}
+
+SqlConnection::SqlConnection(const std::string &address,
+                             Flag::Type flag,
+                             Flag::Option option,
+                             SynchronizationObject *synchronizationObject) :
+    m_connection(NULL),
+    m_usingLucene(false),
+    m_dataCommandsCount(0),
+    m_synchronizationObject(synchronizationObject)
+{
+    LogPedantic("Opening database connection to: " << address);
+
+    // Connect to DB
+    SqlConnection::Connect(address, flag, option);
+
+    if (!m_synchronizationObject) {
+        LogPedantic("No synchronization object defined");
+    }
+}
+
+SqlConnection::~SqlConnection()
+{
+    LogPedantic("Closing database connection");
+
+    // Disconnect from DB
+    Try
+    {
+        SqlConnection::Disconnect();
+    }
+    Catch(Exception::Base)
+    {
+        LogPedantic("Failed to disconnect from database");
+    }
+}
+
+void SqlConnection::ExecCommand(const char *format, ...)
+{
+    if (m_connection == NULL) {
+        LogPedantic("Cannot execute command. Not connected to DB!");
+        return;
+    }
+
+    if (format == NULL) {
+        LogPedantic("Null query!");
+        ThrowMsg(Exception::SyntaxError, "Null statement");
+    }
+
+    char *rawBuffer;
+
+    va_list args;
+    va_start(args, format);
+
+    if (vasprintf(&rawBuffer, format, args) == -1) {
+        rawBuffer = NULL;
+    }
+
+    va_end(args);
+
+    std::unique_ptr<char[],free_deleter> buffer(rawBuffer);
+
+    if (!buffer) {
+        LogPedantic("Failed to allocate statement string");
+        return;
+    }
+
+    LogPedantic("Executing SQL command: " << buffer.get());
+
+    // Notify all after potentially synchronized database connection access
+    ScopedNotifyAll notifyAll(m_synchronizationObject.get());
+
+    for (;;) {
+        char *errorBuffer;
+
+        int ret = sqlite3_exec(m_connection,
+                               buffer.get(),
+                               NULL,
+                               NULL,
+                               &errorBuffer);
+
+        std::string errorMsg;
+
+        // Take allocated error buffer
+        if (errorBuffer != NULL) {
+            errorMsg = errorBuffer;
+            sqlite3_free(errorBuffer);
+        }
+
+        if (ret == SQLITE_OK) {
+            return;
+        }
+
+        if (ret == SQLITE_BUSY) {
+            LogPedantic("Collision occurred while executing SQL command");
+
+            // Synchronize if synchronization object is available
+            if (m_synchronizationObject) {
+                LogPedantic("Performing synchronization");
+                m_synchronizationObject->Synchronize();
+                continue;
+            }
+
+            // No synchronization object defined. Fail.
+        }
+
+        // Fatal error
+        LogPedantic("Failed to execute SQL command. Error: " << errorMsg);
+        ThrowMsg(Exception::SyntaxError, errorMsg);
+    }
+}
+
+SqlConnection::DataCommandAutoPtr SqlConnection::PrepareDataCommand(
+    const char *format,
+    ...)
+{
+    if (m_connection == NULL) {
+        LogPedantic("Cannot execute data command. Not connected to DB!");
+        return DataCommandAutoPtr();
+    }
+
+    char *rawBuffer;
+
+    va_list args;
+    va_start(args, format);
+
+    if (vasprintf(&rawBuffer, format, args) == -1) {
+        rawBuffer = NULL;
+    }
+
+    va_end(args);
+
+    std::unique_ptr<char[],free_deleter> buffer(rawBuffer);
+
+    if (!buffer) {
+        LogPedantic("Failed to allocate statement string");
+        return DataCommandAutoPtr();
+    }
+
+    LogPedantic("Executing SQL data command: " << buffer.get());
+
+    return DataCommandAutoPtr(new DataCommand(this, buffer.get()));
+}
+
+SqlConnection::RowID SqlConnection::GetLastInsertRowID() const
+{
+    return static_cast<RowID>(sqlite3_last_insert_rowid(m_connection));
+}
+
+void SqlConnection::TurnOnForeignKeys()
+{
+    ExecCommand("PRAGMA foreign_keys = ON;");
+}
+
+void SqlConnection::BeginTransaction()
+{
+    ExecCommand("BEGIN;");
+}
+
+void SqlConnection::RollbackTransaction()
+{
+    ExecCommand("ROLLBACK;");
+}
+
+void SqlConnection::CommitTransaction()
+{
+    ExecCommand("COMMIT;");
+}
+
+SqlConnection::SynchronizationObject *
+SqlConnection::AllocDefaultSynchronizationObject()
+{
+    return new NaiveSynchronizationObject();
+}
+} // namespace DB
+} // namespace DPL
diff --git a/commons/modules/db/src/thread_database_support.cpp b/commons/modules/db/src/thread_database_support.cpp
new file mode 100644 (file)
index 0000000..101640f
--- /dev/null
@@ -0,0 +1,23 @@
+/*
+ * 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    thread_database_support.cpp
+ * @author  Przemyslaw Dobrowolski (p.dobrowolsk)
+ * @version 1.0
+ * @brief   This file contains the definition of thread database support
+ */
+#include <stddef.h>
+#include <dpl/db/thread_database_support.h>
\ No newline at end of file
diff --git a/commons/modules/log/config.cmake b/commons/modules/log/config.cmake
new file mode 100644 (file)
index 0000000..1d27163
--- /dev/null
@@ -0,0 +1,41 @@
+# 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        config.cmake
+# @author      Lukasz Marek (l.marek@samsung.com)
+# @version     1.0
+# @brief
+#
+
+SET(DPL_LOG_SOURCES
+    ${PROJECT_SOURCE_DIR}/modules/log/src/abstract_log_provider.cpp
+    ${PROJECT_SOURCE_DIR}/modules/log/src/dlog_log_provider.cpp
+    ${PROJECT_SOURCE_DIR}/modules/log/src/log.cpp
+    PARENT_SCOPE
+)
+
+SET(DPL_LOG_HEADERS
+    ${PROJECT_SOURCE_DIR}/modules/log/include/dpl/log/abstract_log_provider.h
+    ${PROJECT_SOURCE_DIR}/modules/log/include/dpl/log/dlog_log_provider.h
+    ${PROJECT_SOURCE_DIR}/modules/log/include/dpl/log/log.h
+    ${PROJECT_SOURCE_DIR}/modules/log/include/dpl/log/secure_log.h
+    PARENT_SCOPE
+)
+
+SET(DPL_LOG_INCLUDE_DIR
+    ${PROJECT_SOURCE_DIR}/modules/log/include/
+    ${PROJECT_SOURCE_DIR}/modules/core/include/
+    PARENT_SCOPE
+)
diff --git a/commons/modules/log/include/dpl/log/abstract_log_provider.h b/commons/modules/log/include/dpl/log/abstract_log_provider.h
new file mode 100644 (file)
index 0000000..62fa050
--- /dev/null
@@ -0,0 +1,59 @@
+/*
+ * 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 DPL {
+namespace Log {
+class AbstractLogProvider
+{
+  public:
+    virtual ~AbstractLogProvider() {}
+
+    virtual void Debug(const char *message,
+                       const char *fileName,
+                       int line,
+                       const char *function) = 0;
+    virtual void Info(const char *message,
+                      const char *fileName,
+                      int line,
+                      const char *function) = 0;
+    virtual void Warning(const char *message,
+                         const char *fileName,
+                         int line,
+                         const char *function) = 0;
+    virtual void Error(const char *message,
+                       const char *fileName,
+                       int line,
+                       const char *function) = 0;
+    virtual void Pedantic(const char *message,
+                          const char *fileName,
+                          int line,
+                          const char *function) = 0;
+
+  protected:
+    static const char *LocateSourceFileName(const char *filename);
+};
+}
+} // namespace DPL
+
+#endif // DPL_ABSTRACT_LOG_PROVIDER_H
diff --git a/commons/modules/log/include/dpl/log/dlog_log_provider.h b/commons/modules/log/include/dpl/log/dlog_log_provider.h
new file mode 100644 (file)
index 0000000..f23399a
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ * 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 <dpl/free_deleter.h>
+#include <memory>
+#include <string>
+
+namespace DPL {
+namespace Log {
+class DLOGLogProvider :
+    public AbstractLogProvider
+{
+  private:
+    std::unique_ptr<char[],free_deleter> m_tag;
+
+    static std::string FormatMessage(const char *message,
+                                     const char *filename,
+                                     int line,
+                                     const char *function);
+
+  public:
+    DLOGLogProvider();
+    virtual ~DLOGLogProvider();
+
+    virtual void Debug(const char *message,
+                       const char *fileName,
+                       int line,
+                       const char *function);
+    virtual void Info(const char *message,
+                      const char *fileName,
+                      int line,
+                      const char *function);
+    virtual void Warning(const char *message,
+                         const char *fileName,
+                         int line,
+                         const char *function);
+    virtual void Error(const char *message,
+                       const char *fileName,
+                       int line,
+                       const char *function);
+    virtual void Pedantic(const char *message,
+                          const char *fileName,
+                          int line,
+                          const char *function);
+
+    // Set global Tag according to DLOG
+    void SetTag(const char *tag);
+};
+}
+} // namespace DPL
+
+#endif // DPL_DLOG_LOG_PROVIDER_H
diff --git a/commons/modules/log/include/dpl/log/log.h b/commons/modules/log/include/dpl/log/log.h
new file mode 100644 (file)
index 0000000..ebe678c
--- /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 <dpl/singleton.h>
+#include <dpl/noncopyable.h>
+#include <dpl/log/abstract_log_provider.h>
+#include <dpl/log/dlog_log_provider.h>
+#include <sstream>
+#include <list>
+
+namespace DPL {
+namespace Log {
+/**
+ * DPL log system
+ */
+class LogSystem :
+    private Noncopyable
+{
+  private:
+    typedef std::list<AbstractLogProvider *> AbstractLogProviderPtrList;
+    AbstractLogProviderPtrList m_providers;
+
+    DLOGLogProvider *m_dlogProvider;
+
+    bool m_isLoggingEnabled;
+
+  public:
+    bool IsLoggingEnabled() const;
+    LogSystem();
+    virtual ~LogSystem();
+
+    /**
+     * Log debug message
+     */
+    void Debug(const char *message,
+               const char *filename,
+               int line,
+               const char *function);
+
+    /**
+     * Log info message
+     */
+    void Info(const char *message,
+              const char *filename,
+              int line,
+              const char *function);
+
+    /**
+     * Log warning message
+     */
+    void Warning(const char *message,
+                 const char *filename,
+                 int line,
+                 const char *function);
+
+    /**
+     * Log error message
+     */
+    void Error(const char *message,
+               const char *filename,
+               int line,
+               const char *function);
+
+    /**
+     * Log pedantic message
+     */
+    void Pedantic(const char *message,
+                  const char *filename,
+                  int line,
+                  const char *function);
+
+    /**
+     * 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);
+};
+
+/*
+ * 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 DPL
+
+//
+// Log support
+//
+//
+
+#ifdef DPL_LOGS_ENABLED
+    #define DPL_MACRO_FOR_LOGGING(message, function)                           \
+    do                                                                     \
+    {                                                                      \
+        if (DPL::Log::LogSystemSingleton::Instance().IsLoggingEnabled())   \
+        {                                                                  \
+            std::ostringstream platformLog;                                \
+            platformLog << message;                                        \
+            DPL::Log::LogSystemSingleton::Instance().function(             \
+                platformLog.str().c_str(),                                 \
+                __FILE__, __LINE__, __FUNCTION__);                         \
+        }                                                                  \
+    } while (0)
+#else
+/* avoid warnings about unused variables */
+    #define DPL_MACRO_FOR_LOGGING(message, function)                           \
+    do {                                                                   \
+        DPL::Log::NullStream ns;                                           \
+        ns << message;                                                     \
+    } while (0)
+#endif
+
+#define  LogDebug(message) DPL_MACRO_FOR_LOGGING(message, Debug)
+#define  LogInfo(message) DPL_MACRO_FOR_LOGGING(message, Info)
+#define  LogWarning(message) DPL_MACRO_FOR_LOGGING(message, Warning)
+#define  LogError(message) DPL_MACRO_FOR_LOGGING(message, Error)
+#define  LogPedantic(message) DPL_MACRO_FOR_LOGGING(message, Pedantic)
+
+#endif // DPL_LOG_H
diff --git a/commons/modules/log/include/dpl/log/secure_log.h b/commons/modules/log/include/dpl/log/secure_log.h
new file mode 100644 (file)
index 0000000..6402c4f
--- /dev/null
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) 2013 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       secure_log.h
+ * @author     Jihoon Chung(jihoon.chung@samsung.com)
+ * @version    0.1
+ * @brief
+ */
+
+#ifndef DPL_SECURE_LOG_H
+#define DPL_SECURE_LOG_H
+
+#include <dlog.h>
+
+#define COLOR_ERROR   "\e[1;31m"
+#define COLOR_WARNING "\e[2;31m"
+#define COLOR_END     "\e[0m"
+#define COLOR_TAG     "\e[0m"
+
+// default TAG
+#undef LOG_TAG
+#define LOG_TAG "WRT_UNDEFINED"
+
+#ifdef WRT_LOG
+#undef LOG_TAG
+#define LOG_TAG "WRT"
+#undef COLOR_TAG
+#define COLOR_TAG "\e[1;32m"
+#endif
+
+#ifdef WRT_BUNDLE_LOG
+#undef LOG_TAG
+#define LOG_TAG "WRT_BUNDLE"
+#undef COLOR_TAG
+#define COLOR_TAG "\e[1;34m"
+#endif
+
+#ifdef WRT_PLUGINS_COMMON_LOG
+#undef LOG_TAG
+#define LOG_TAG "WRT_PLUGINS/COMMON"
+#undef COLOR_TAG
+#define COLOR_TAG "\e[1;36m"
+#endif
+
+#ifdef WRT_PLUGINS_WIDGET_LOG
+#undef LOG_TAG
+#define LOG_TAG "WRT_PLUGINS/WIDGET"
+#undef COLOR_TAG
+#define COLOR_TAG "\e[1;35m"
+#endif
+
+#ifdef WRT_INSTALLER_LOG
+#undef LOG_TAG
+#define LOG_TAG "WRT_INSTALLER"
+#undef COLOR_TAG
+#define COLOR_TAG "\e[1;32m"
+#endif
+
+#ifndef SECURE_SLOGD
+#define SECURE_SLOGD(fmt, arg...) SLOGD(fmt,##arg)
+#endif
+
+#ifndef SECURE_SLOGW
+#define SECURE_SLOGW(fmt, arg...) SLOGW(fmt,##arg)
+#endif
+
+#ifndef SECURE_SLOGE
+#define SECURE_SLOGE(fmt, arg...) SLOGE(fmt,##arg)
+#endif
+
+#undef _D
+#define _D(fmt, arg ...) SECURE_SLOGD(COLOR_TAG fmt COLOR_END,##arg)
+#undef _W
+#define _W(fmt, arg ...) SECURE_SLOGW(COLOR_WARNING fmt COLOR_END,##arg)
+#undef _E
+#define _E(fmt, arg ...) SECURE_SLOGE(COLOR_ERROR fmt COLOR_END,##arg)
+
+#endif // DPL_SECURE_LOG_H
+
diff --git a/commons/modules/log/src/abstract_log_provider.cpp b/commons/modules/log/src/abstract_log_provider.cpp
new file mode 100644 (file)
index 0000000..a03f8a0
--- /dev/null
@@ -0,0 +1,34 @@
+/*
+ * 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 DPL {
+namespace Log {
+const char *AbstractLogProvider::LocateSourceFileName(const char *filename)
+{
+    const char *ptr = strrchr(filename, '/');
+    return ptr != NULL ? ptr + 1 : filename;
+}
+}
+}
diff --git a/commons/modules/log/src/dlog_log_provider.cpp b/commons/modules/log/src/dlog_log_provider.cpp
new file mode 100644 (file)
index 0000000..f4fa0c9
--- /dev/null
@@ -0,0 +1,117 @@
+/*
+ * 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 <dpl/log/dlog_log_provider.h>
+#include <cstring>
+#include <sstream>
+#include <dlog.h>
+
+#ifdef SECURE_LOG
+    #define INTERNAL_DLP_LOG_ SECURE_LOG
+#else
+    #define INTERNAL_DLP_LOG_ LOG
+#endif
+
+/*
+ * The __extension__ keyword in the following define is required because
+ * macros used here from dlog.h use non-standard extension that cause
+ * gcc to show unwanted warnings when compiling with -pedantic switch.
+ */
+#define INTERNAL_DLP_LOG __extension__ INTERNAL_DLP_LOG_
+
+namespace DPL {
+namespace Log {
+std::string DLOGLogProvider::FormatMessage(const char *message,
+                                           const char *filename,
+                                           int line,
+                                           const char *function)
+{
+    std::ostringstream val;
+
+    val << std::string("[") <<
+    LocateSourceFileName(filename) << std::string(":") << line <<
+    std::string("] ") << function << std::string("(): ") << message;
+
+    return val.str();
+}
+
+DLOGLogProvider::DLOGLogProvider()
+{}
+
+DLOGLogProvider::~DLOGLogProvider()
+{}
+
+void DLOGLogProvider::SetTag(const char *tag)
+{
+    m_tag.reset(strdup(tag));
+}
+
+void DLOGLogProvider::Debug(const char *message,
+                            const char *filename,
+                            int line,
+                            const char *function)
+{
+    INTERNAL_DLP_LOG(LOG_DEBUG, m_tag.get(), "%s",
+        FormatMessage(message, filename, line, function).c_str());
+}
+
+void DLOGLogProvider::Info(const char *message,
+                           const char *filename,
+                           int line,
+                           const char *function)
+{
+    INTERNAL_DLP_LOG(LOG_INFO, m_tag.get(), "%s",
+        FormatMessage(message, filename, line, function).c_str());
+}
+
+void DLOGLogProvider::Warning(const char *message,
+                              const char *filename,
+                              int line,
+                              const char *function)
+{
+    INTERNAL_DLP_LOG(LOG_WARN, m_tag.get(), "%s",
+        FormatMessage(message, filename, line, function).c_str());
+}
+
+void DLOGLogProvider::Error(const char *message,
+                            const char *filename,
+                            int line,
+                            const char *function)
+{
+    INTERNAL_DLP_LOG(LOG_ERROR, m_tag.get(), "%s",
+        FormatMessage(message, filename, line, function).c_str());
+}
+
+void DLOGLogProvider::Pedantic(const char *message,
+                               const char *filename,
+                               int line,
+                               const char *function)
+{
+    INTERNAL_DLP_LOG(LOG_DEBUG, "DPL", "%s",
+        FormatMessage(message, filename, line, function).c_str());
+}
+}
+} // namespace DPL
+
+#undef INTERNAL_DLP_LOG
+#undef INTERNAL_DLP_LOG_
+
diff --git a/commons/modules/log/src/log.cpp b/commons/modules/log/src/log.cpp
new file mode 100644 (file)
index 0000000..fcc2d43
--- /dev/null
@@ -0,0 +1,143 @@
+/*
+ * 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 <dpl/log/log.h>
+#include <dpl/singleton_impl.h>
+
+IMPLEMENT_SINGLETON(DPL::Log::LogSystem)
+
+namespace DPL {
+namespace Log {
+
+bool LogSystem::IsLoggingEnabled() const
+{
+    return m_isLoggingEnabled;
+}
+
+LogSystem::LogSystem() :
+    m_dlogProvider(NULL),
+    m_isLoggingEnabled(true)
+{
+    // DLOG
+    m_dlogProvider = new DLOGLogProvider();
+    AddProvider(m_dlogProvider);
+}
+
+LogSystem::~LogSystem()
+{
+    // Delete all providers
+    for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
+         iterator != m_providers.end();
+         ++iterator)
+    {
+        delete *iterator;
+    }
+
+    m_providers.clear();
+
+    // And even default providers
+    m_dlogProvider = NULL;
+}
+
+void LogSystem::SetTag(const char* tag)
+{
+    if (m_dlogProvider != NULL) {
+        m_dlogProvider->SetTag(tag);
+    }
+}
+
+void LogSystem::AddProvider(AbstractLogProvider *provider)
+{
+    m_providers.push_back(provider);
+}
+
+void LogSystem::RemoveProvider(AbstractLogProvider *provider)
+{
+    m_providers.remove(provider);
+}
+
+void LogSystem::Debug(const char *message,
+                      const char *filename,
+                      int line,
+                      const char *function)
+{
+    for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
+         iterator != m_providers.end();
+         ++iterator)
+    {
+        (*iterator)->Debug(message, filename, line, function);
+    }
+}
+
+void LogSystem::Info(const char *message,
+                     const char *filename,
+                     int line,
+                     const char *function)
+{
+    for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
+         iterator != m_providers.end();
+         ++iterator)
+    {
+        (*iterator)->Info(message, filename, line, function);
+    }
+}
+
+void LogSystem::Warning(const char *message,
+                        const char *filename,
+                        int line,
+                        const char *function)
+{
+    for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
+         iterator != m_providers.end();
+         ++iterator)
+    {
+        (*iterator)->Warning(message, filename, line, function);
+    }
+}
+
+void LogSystem::Error(const char *message,
+                      const char *filename,
+                      int line,
+                      const char *function)
+{
+    for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
+         iterator != m_providers.end();
+         ++iterator)
+    {
+        (*iterator)->Error(message, filename, line, function);
+    }
+}
+
+void LogSystem::Pedantic(const char *message,
+                         const char *filename,
+                         int line,
+                         const char *function)
+{
+    for (AbstractLogProviderPtrList::iterator iterator = m_providers.begin();
+         iterator != m_providers.end();
+         ++iterator)
+    {
+        (*iterator)->Pedantic(message, filename, line, function);
+    }
+}
+}
+} // namespace DPL
diff --git a/commons/wrt-commons b/commons/wrt-commons
new file mode 100644 (file)
index 0000000..a285a63
--- /dev/null
@@ -0,0 +1,204 @@
+wrt-commons:
+Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   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.
diff --git a/communication_client/include/SecurityCommunicationClient.h b/communication_client/include/SecurityCommunicationClient.h
new file mode 100644 (file)
index 0000000..1c4b4da
--- /dev/null
@@ -0,0 +1,109 @@
+/*
+ * Copyright (c) 2012 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        SecurityCommunicationClient.h
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       This is header of class used by IPC client with implemented templates
+ *
+ */
+
+/*
+ * This class hides implementation of specific communication types
+ * and enables switching between them by #defined macros.
+ *
+ * supported types : DBUS_CONNECTION
+ *
+ * IMPORTANT : Exactly ONE type MUST be defined.
+ *
+ */
+
+#ifndef SECURITYCOMMUNICATIONCLIENT_H_
+#define SECURITYCOMMUNICATIONCLIENT_H_
+
+#ifdef DBUS_CONNECTION
+#include <dpl/dbus/dbus_client.h>
+#endif
+#include <dpl/log/log.h>
+#include "SecuritySocketClient.h"
+#include <string>
+#include <memory>
+
+
+namespace WrtSecurity {
+namespace Communication {
+class Client
+{
+public:
+    class Exception
+    {
+    public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, SecurityCommunicationClientException)
+    };
+
+    explicit Client(const std::string &intefaceName);
+
+
+
+    template<typename ... Args>
+    void call(const char* methodName, const Args& ... args)
+    {
+
+        connect();
+        Try{
+        #ifdef DBUS_CONNECTION
+            m_dbusClient->call(methodName, args...);
+        } Catch (DPL::DBus::Client::Exception::DBusClientException){
+        #endif //DBUS_CONNECTION
+        #ifdef SOCKET_CONNECTION
+            m_socketClient->call(methodName, args...);
+        } Catch (SecuritySocketClient::Exception::SecuritySocketClientException){
+        #endif //SOCKET_CONNECTION
+            LogError("Error getting response");
+            disconnect();
+            ReThrowMsg(Exception::SecurityCommunicationClientException,
+                       "Error getting response");
+        }
+        LogInfo("Call served");
+        disconnect();
+  }
+
+    template<typename ...Args>
+    void call(std::string methodName, const Args&... args)
+    {
+        call(methodName.c_str(), args...);
+    }
+
+
+private:
+
+    void connect();
+    void disconnect();
+
+    std::string m_interfaceName;
+    #ifdef DBUS_CONNECTION
+    std::unique_ptr<DPL::DBus::Client> m_dbusClient;
+    #endif
+
+    #ifdef SOCKET_CONNECTION
+    std::unique_ptr<SecuritySocketClient> m_socketClient;
+    #endif
+};
+} // namespace Communication
+} // namespace WrtSecurity
+
+#endif /* SECURITYCOMMUNICATIONCLIENT_H_ */
diff --git a/communication_client/src/SecurityCommunicationClient.cpp b/communication_client/src/SecurityCommunicationClient.cpp
new file mode 100644 (file)
index 0000000..9bc155f
--- /dev/null
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) 2012 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        SecurityCommunicationClient.h
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       This is implementation of class used IPC client
+ */
+
+
+#include "SecurityCommunicationClient.h"
+
+#ifdef DBUS_CONNECTION
+#include "security_daemon_dbus_config.h"
+#endif
+
+#include <dpl/log/log.h>
+
+namespace WrtSecurity{
+namespace Communication{
+
+  Client::Client(const std::string& interfaceName){
+    #if DBUS_CONNECTION
+      LogInfo("DBus create");
+    Try {
+      m_dbusClient.reset(new DPL::DBus::Client(WrtSecurity::SecurityDaemonConfig::OBJECT_PATH(),
+                         WrtSecurity::SecurityDaemonConfig::SERVICE_NAME(),
+                         interfaceName));
+    } Catch (DPL::DBus::Client::Exception::DBusClientException) {
+      LogError("Error getting connection");
+      ReThrowMsg(Exception::SecurityCommunicationClientException,
+               "Error getting connection");
+    }
+    if(NULL == m_dbusClient.get()){
+      LogError("Couldn't get client");
+      ThrowMsg(Exception::SecurityCommunicationClientException,
+               "Error getting client");
+    }
+    #endif //DBUS_CONNECTION
+
+    #ifdef SOCKET_CONNECTION
+    m_socketClient.reset(new SecuritySocketClient(interfaceName));
+    if(NULL == m_socketClient.get()){
+        LogError("Couldn't get client");
+        ThrowMsg(Exception::SecurityCommunicationClientException,
+                 "Error getting client");
+    }
+    #endif //SOCKET_CONNECTION
+    LogDebug("Created wrt-security communication client");
+  }
+
+  void Client::connect(){
+    #ifdef SOCKET_CONNECTION
+      Try {
+          m_socketClient->connect();
+      } Catch(SecuritySocketClient::Exception::SecuritySocketClientException){
+          LogError("Couldn't connect");
+          ReThrowMsg(Exception::SecurityCommunicationClientException,
+                     "Error connecting");
+      }
+
+    #endif //SOCKET_CONNECTION
+      LogDebug("Wrt-security client Connected");
+  }
+
+  void Client::disconnect(){
+
+    #ifdef SOCKET_CONNECTION
+      m_socketClient->disconnect();
+    #endif //SOCKET_CONNECTION
+      LogDebug("Wrt-security client Disconnected");
+  }
+
+
+} // namespace Communication
+
+} // namespace WrtSecurity
+
diff --git a/etc/CMakeLists.txt b/etc/CMakeLists.txt
new file mode 100644 (file)
index 0000000..ba76f68
--- /dev/null
@@ -0,0 +1,13 @@
+
+SET(ETC_DIR ${PROJECT_SOURCE_DIR}/etc)
+
+  INSTALL(FILES
+    ${ETC_DIR}/wrt_security_create_clean_db.sh
+    ${ETC_DIR}/wrt_security_change_policy.sh
+    DESTINATION /usr/bin
+    )
+
+INSTALL(FILES
+    ${ETC_DIR}/schema.xsd
+    DESTINATION share/wrt-engine
+    )
diff --git a/etc/schema.xsd b/etc/schema.xsd
new file mode 100644 (file)
index 0000000..8028f3e
--- /dev/null
@@ -0,0 +1,415 @@
+<?xml version="1.0" encoding="utf-8"?>
+<!DOCTYPE schema
+  PUBLIC "-//W3C//DTD XMLSchema 200102//EN" "http://www.w3.org/2001/XMLSchema.dtd"
+ [
+   <!ATTLIST schema
+     xmlns:ds CDATA #FIXED "http://www.w3.org/2000/09/xmldsig#">
+   <!ENTITY dsig 'http://www.w3.org/2000/09/xmldsig#'>
+   <!ENTITY % p ''>
+   <!ENTITY % s ''>
+  ]>
+
+<!-- Schema for XML Signatures
+    http://www.w3.org/2000/09/xmldsig#
+    $Revision: 1.1 $ on $Date: 2002/02/08 20:32:26 $ by $Author: reagle $
+
+    Copyright 2001 The Internet Society and W3C (Massachusetts Institute
+    of Technology, Institut National de Recherche en Informatique et en
+    Automatique, Keio University). All Rights Reserved.
+    http://www.w3.org/Consortium/Legal/
+
+    This document is governed by the W3C Software License [1] as described
+    in the FAQ [2].
+
+    [1] http://www.w3.org/Consortium/Legal/copyright-software-19980720
+    [2] http://www.w3.org/Consortium/Legal/IPR-FAQ-20000620.html#DTD
+-->
+
+
+<schema xmlns="http://www.w3.org/2001/XMLSchema"
+        xmlns:ds="http://www.w3.org/2000/09/xmldsig#"
+        targetNamespace="http://www.w3.org/2000/09/xmldsig#"
+        version="0.1" elementFormDefault="qualified">
+
+<!-- Basic Types Defined for Signatures -->
+
+<simpleType name="CryptoBinary">
+  <restriction base="base64Binary">
+  </restriction>
+</simpleType>
+
+<!-- Start Signature -->
+
+<element name="Signature" type="ds:SignatureType"/>
+<complexType name="SignatureType">
+  <sequence>
+    <element ref="ds:SignedInfo"/>
+    <element ref="ds:SignatureValue"/>
+    <element ref="ds:KeyInfo" minOccurs="0"/>
+    <element ref="ds:Object" minOccurs="0" maxOccurs="unbounded"/>
+  </sequence>
+  <attribute name="Id" type="ID" use="optional"/>
+</complexType>
+
+  <element name="SignatureValue" type="ds:SignatureValueType"/>
+  <complexType name="SignatureValueType">
+    <simpleContent>
+      <extension base="base64Binary">
+        <attribute name="Id" type="ID" use="optional"/>
+      </extension>
+    </simpleContent>
+  </complexType>
+
+<!-- Start SignedInfo -->
+
+<element name="SignedInfo" type="ds:SignedInfoType"/>
+<complexType name="SignedInfoType">
+  <sequence>
+    <element ref="ds:CanonicalizationMethod"/>
+    <element ref="ds:SignatureMethod"/>
+    <element ref="ds:Reference" maxOccurs="unbounded"/>
+  </sequence>
+  <attribute name="Id" type="ID" use="optional"/>
+</complexType>
+
+  <element name="CanonicalizationMethod" type="ds:CanonicalizationMethodType"/>
+  <complexType name="CanonicalizationMethodType" mixed="true">
+    <sequence>
+      <any namespace="##any" minOccurs="0" maxOccurs="unbounded"/>
+      <!-- (0,unbounded) elements from (1,1) namespace -->
+    </sequence>
+    <attribute name="Algorithm" type="anyURI" use="required"/>
+  </complexType>
+
+  <element name="SignatureMethod" type="ds:SignatureMethodType"/>
+  <complexType name="SignatureMethodType" mixed="true">
+    <sequence>
+      <element name="HMACOutputLength" minOccurs="0" type="ds:HMACOutputLengthType"/>
+      <any namespace="##other" minOccurs="0" maxOccurs="unbounded"/>
+      <!-- (0,unbounded) elements from (1,1) external namespace -->
+    </sequence>
+    <attribute name="Algorithm" type="anyURI" use="required"/>
+  </complexType>
+
+<!-- Start Reference -->
+
+<element name="Reference" type="ds:ReferenceType"/>
+<complexType name="ReferenceType">
+  <sequence>
+    <element ref="ds:Transforms" minOccurs="0"/>
+    <element ref="ds:DigestMethod"/>
+    <element ref="ds:DigestValue"/>
+  </sequence>
+  <attribute name="Id" type="ID" use="optional"/>
+  <attribute name="URI" type="anyURI" use="optional"/>
+  <attribute name="Type" type="anyURI" use="optional"/>
+</complexType>
+
+  <element name="Transforms" type="ds:TransformsType"/>
+  <complexType name="TransformsType">
+    <sequence>
+      <element ref="ds:Transform" maxOccurs="unbounded"/>
+    </sequence>
+  </complexType>
+
+  <element name="Transform" type="ds:TransformType"/>
+  <complexType name="TransformType" mixed="true">
+    <choice minOccurs="0" maxOccurs="unbounded">
+      <any namespace="##other" processContents="lax"/>
+      <!-- (1,1) elements from (0,unbounded) namespaces -->
+      <element name="XPath" type="string"/>
+    </choice>
+    <attribute name="Algorithm" type="anyURI" use="required"/>
+  </complexType>
+
+<!-- End Reference -->
+
+<element name="DigestMethod" type="ds:DigestMethodType"/>
+<complexType name="DigestMethodType" mixed="true">
+  <sequence>
+    <any namespace="##other" processContents="lax" minOccurs="0" maxOccurs="unbounded"/>
+  </sequence>
+  <attribute name="Algorithm" type="anyURI" use="required"/>
+</complexType>
+
+<element name="DigestValue" type="ds:DigestValueType"/>
+<simpleType name="DigestValueType">
+  <restriction base="base64Binary"/>
+</simpleType>
+
+<!-- End SignedInfo -->
+
+<!-- Start KeyInfo -->
+
+<element name="KeyInfo" type="ds:KeyInfoType"/>
+<complexType name="KeyInfoType" mixed="true">
+  <choice maxOccurs="unbounded">
+    <element ref="ds:KeyName"/>
+    <element ref="ds:KeyValue"/>
+    <element ref="ds:RetrievalMethod"/>
+    <element ref="ds:X509Data"/>
+    <element ref="ds:PGPData"/>
+    <element ref="ds:SPKIData"/>
+    <element ref="ds:MgmtData"/>
+    <any processContents="lax" namespace="##other"/>
+    <!-- (1,1) elements from (0,unbounded) namespaces -->
+  </choice>
+  <attribute name="Id" type="ID" use="optional"/>
+</complexType>
+
+  <element name="KeyName" type="string"/>
+  <element name="MgmtData" type="string"/>
+
+  <element name="KeyValue" type="ds:KeyValueType"/>
+  <complexType name="KeyValueType" mixed="true">
+   <choice>
+     <element ref="ds:DSAKeyValue"/>
+     <element ref="ds:RSAKeyValue"/>
+     <element ref="ds:ECKeyValue"/>
+     <any namespace="##other" processContents="lax"/>
+   </choice>
+  </complexType>
+
+<!-- ECDSA KEY DEFINITIONS -->
+
+  <element name="ECKeyValue" type="ds:ECKeyValueType"/>
+  <complexType name="ECKeyValueType">
+    <sequence>
+      <choice>
+        <element name="ECParameters" type="ds:ECParametersType"/>
+        <element name="NamedCurve" type="ds:NamedCurveType"/>
+      </choice>
+      <element name="PublicKey" type="ds:ECPointType"/>
+    </sequence>
+    <attribute name="Id" type="ID" use="optional"/>
+  </complexType>
+
+  <complexType name="NamedCurveType">
+    <attribute name="URI" type="anyURI" use="required"/>
+  </complexType>
+
+  <simpleType name="ECPointType">
+    <restriction base="ds:CryptoBinary"/>
+  </simpleType>
+
+  <element name="RetrievalMethod" type="ds:RetrievalMethodType"/>
+  <complexType name="RetrievalMethodType">
+    <sequence>
+      <element ref="ds:Transforms" minOccurs="0"/>
+    </sequence>
+    <attribute name="URI" type="anyURI"/>
+    <attribute name="Type" type="anyURI" use="optional"/>
+  </complexType>
+
+    <complexType name="ECParametersType">
+      <sequence>
+        <element name="FieldID" type="ds:FieldIDType"/>
+        <element name="Curve" type="ds:CurveType"/>
+        <element name="Base" type="ds:ECPointType"/>
+        <element name="Order" type="ds:CryptoBinary"/>
+        <element name="CoFactor" type="integer" minOccurs="0"/>
+        <element name="ValidationData" type="ds:ECValidationDataType" minOccurs="0"/>
+      </sequence>
+    </complexType>
+
+    <complexType name="FieldIDType">
+      <choice>
+        <element ref="ds:Prime"/>
+        <element ref="ds:TnB"/>
+        <element ref="ds:PnB"/>
+        <element ref="ds:GnB"/>
+        <any namespace="##other" processContents="lax"/>
+      </choice>
+    </complexType>
+
+    <element name="Prime" type="ds:PrimeFieldParamsType"/>
+    <complexType name="PrimeFieldParamsType">
+      <sequence>
+        <element name="P" type="ds:CryptoBinary"/>
+      </sequence>
+    </complexType>
+
+    <element name="GnB" type="ds:CharTwoFieldParamsType"/>
+    <complexType name="CharTwoFieldParamsType">
+      <sequence>
+        <element name="M" type="positiveInteger"/>
+      </sequence>
+    </complexType>
+
+    <element name="TnB" type="ds:TnBFieldParamsType"/>
+    <complexType name="TnBFieldParamsType">
+      <complexContent>
+        <extension base="ds:CharTwoFieldParamsType">
+          <sequence>
+            <element name="K" type="positiveInteger"/>
+          </sequence>
+        </extension>
+      </complexContent>
+    </complexType>
+
+    <element name="PnB" type="ds:PnBFieldParamsType"/>
+    <complexType name="PnBFieldParamsType">
+      <complexContent>
+        <extension base="ds:CharTwoFieldParamsType">
+          <sequence>
+            <element name="K1" type="positiveInteger"/>
+            <element name="K2" type="positiveInteger"/>
+            <element name="K3" type="positiveInteger"/>
+          </sequence>
+        </extension>
+      </complexContent>
+    </complexType>
+
+    <complexType name="CurveType">
+      <sequence>
+        <element name="A" type="ds:CryptoBinary"/>
+        <element name="B" type="ds:CryptoBinary"/>
+      </sequence>
+    </complexType>
+
+  <complexType name="ECValidationDataType">
+    <sequence>
+      <element name="seed" type="ds:CryptoBinary"/>
+    </sequence>
+    <attribute name="hashAlgorithm" type="anyURI" use="required"/>
+  </complexType>
+
+
+<!-- Start X509Data -->
+
+<element name="X509Data" type="ds:X509DataType"/>
+<complexType name="X509DataType">
+  <sequence maxOccurs="unbounded">
+    <choice>
+      <element name="X509IssuerSerial" type="ds:X509IssuerSerialType"/>
+      <element name="X509SKI" type="base64Binary"/>
+      <element name="X509SubjectName" type="string"/>
+      <element name="X509Certificate" type="base64Binary"/>
+      <element name="X509CRL" type="base64Binary"/>
+      <any namespace="##other" processContents="lax"/>
+    </choice>
+  </sequence>
+</complexType>
+
+<complexType name="X509IssuerSerialType">
+  <sequence>
+    <element name="X509IssuerName" type="string"/>
+    <element name="X509SerialNumber" type="integer"/>
+  </sequence>
+</complexType>
+
+<!-- End X509Data -->
+
+<!-- Begin PGPData -->
+
+<element name="PGPData" type="ds:PGPDataType"/>
+<complexType name="PGPDataType">
+  <choice>
+    <sequence>
+      <element name="PGPKeyID" type="base64Binary"/>
+      <element name="PGPKeyPacket" type="base64Binary" minOccurs="0"/>
+      <any namespace="##other" processContents="lax" minOccurs="0"
+       maxOccurs="unbounded"/>
+    </sequence>
+    <sequence>
+      <element name="PGPKeyPacket" type="base64Binary"/>
+      <any namespace="##other" processContents="lax" minOccurs="0"
+       maxOccurs="unbounded"/>
+    </sequence>
+  </choice>
+</complexType>
+
+<!-- End PGPData -->
+
+<!-- Begin SPKIData -->
+
+<element name="SPKIData" type="ds:SPKIDataType"/>
+<complexType name="SPKIDataType">
+  <sequence maxOccurs="unbounded">
+    <element name="SPKISexp" type="base64Binary"/>
+    <any namespace="##other" processContents="lax" minOccurs="0"/>
+  </sequence>
+</complexType>
+
+<!-- End SPKIData -->
+
+<!-- End KeyInfo -->
+
+<!-- Start Object (Manifest, SignatureProperty) -->
+
+<element name="Object" type="ds:ObjectType"/>
+<complexType name="ObjectType" mixed="true">
+  <sequence minOccurs="0" maxOccurs="unbounded">
+    <any namespace="##any" processContents="lax"/>
+  </sequence>
+  <attribute name="Id" type="ID" use="optional"/>
+  <attribute name="MimeType" type="string" use="optional"/> <!-- add a grep facet -->
+  <attribute name="Encoding" type="anyURI" use="optional"/>
+</complexType>
+
+<element name="Manifest" type="ds:ManifestType"/>
+<complexType name="ManifestType">
+  <sequence>
+    <element ref="ds:Reference" maxOccurs="unbounded"/>
+  </sequence>
+  <attribute name="Id" type="ID" use="optional"/>
+</complexType>
+
+<element name="SignatureProperties" type="ds:SignaturePropertiesType"/>
+<complexType name="SignaturePropertiesType">
+  <sequence>
+    <element ref="ds:SignatureProperty" maxOccurs="unbounded"/>
+  </sequence>
+  <attribute name="Id" type="ID" use="optional"/>
+</complexType>
+
+   <element name="SignatureProperty" type="ds:SignaturePropertyType"/>
+   <complexType name="SignaturePropertyType" mixed="true">
+     <choice maxOccurs="unbounded">
+       <any namespace="##other" processContents="lax"/>
+       <!-- (1,1) elements from (1,unbounded) namespaces -->
+     </choice>
+     <attribute name="Target" type="anyURI" use="required"/>
+     <attribute name="Id" type="ID" use="optional"/>
+   </complexType>
+
+<!-- End Object (Manifest, SignatureProperty) -->
+
+<!-- Start Algorithm Parameters -->
+
+<simpleType name="HMACOutputLengthType">
+  <restriction base="integer"/>
+</simpleType>
+
+<!-- Start KeyValue Element-types -->
+
+<element name="DSAKeyValue" type="ds:DSAKeyValueType"/>
+<complexType name="DSAKeyValueType">
+  <sequence>
+    <sequence minOccurs="0">
+      <element name="P" type="ds:CryptoBinary"/>
+      <element name="Q" type="ds:CryptoBinary"/>
+    </sequence>
+    <element name="G" type="ds:CryptoBinary" minOccurs="0"/>
+    <element name="Y" type="ds:CryptoBinary"/>
+    <element name="J" type="ds:CryptoBinary" minOccurs="0"/>
+    <sequence minOccurs="0">
+      <element name="Seed" type="ds:CryptoBinary"/>
+      <element name="PgenCounter" type="ds:CryptoBinary"/>
+    </sequence>
+  </sequence>
+</complexType>
+
+<element name="RSAKeyValue" type="ds:RSAKeyValueType"/>
+<complexType name="RSAKeyValueType">
+  <sequence>
+    <element name="Modulus" type="ds:CryptoBinary"/>
+    <element name="Exponent" type="ds:CryptoBinary"/>
+  </sequence>
+</complexType>
+
+<!-- End KeyValue Element-types -->
+
+<!-- End Signature -->
+
+</schema>
diff --git a/etc/wrt_security_change_policy.sh b/etc/wrt_security_change_policy.sh
new file mode 100644 (file)
index 0000000..8a65b7e
--- /dev/null
@@ -0,0 +1,26 @@
+#!/bin/sh
+# 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.
+#
+
+#Uncomment this when IPC is set to DBus
+#dbus-send --system --print-reply --dest=org.tizen.SecurityDaemon /org/tizen/SecurityDaemon org.tizen.AceCheckAccessInterface.update_policy
+
+#Uncomment this when IPC is set to sockets
+echo "delete from AcePolicyResult where 1==1;" | /usr/bin/sqlite3 /opt/dbspace/.ace.db
+echo "delete from AceAttribute where 1==1;" | /usr/bin/sqlite3 /opt/dbspace/.ace.db
+echo "delete from AcePromptDecision where 1==1;" | /usr/bin/sqlite3 /opt/dbspace/.ace.db
+/usr/bin/pkill -9 wrt-security
+/bin/sleep 3
+
diff --git a/etc/wrt_security_create_clean_db.sh b/etc/wrt_security_create_clean_db.sh
new file mode 100644 (file)
index 0000000..08d7a3f
--- /dev/null
@@ -0,0 +1,36 @@
+#!/bin/sh
+# 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.
+#
+for name in ace
+do
+    rm -f /opt/dbspace/.$name.db
+    rm -f /opt/dbspace/.$name.db-journal
+    SQL="PRAGMA journal_mode = PERSIST;"
+    sqlite3 /opt/dbspace/.$name.db "$SQL"
+    SQL=".read /usr/share/wrt-engine/"$name"_db.sql"
+    sqlite3 /opt/dbspace/.$name.db "$SQL"
+    touch /opt/dbspace/.$name.db-journal
+    chown 0:6026 /opt/dbspace/.$name.db
+    chown 0:6026 /opt/dbspace/.$name.db-journal
+    chmod 660 /opt/dbspace/.$name.db
+    chmod 660 /opt/dbspace/.$name.db-journal
+    if [ -f /usr/lib/rpm-plugins/msm.so ]
+    then
+        chsmack -a "wrt-security-daemon::db" /opt/dbspace/.$name.db
+        chsmack -a "wrt-security-daemon::db" /opt/dbspace/.$name.db-journal
+    fi
+done
+
+
diff --git a/mockups/AceDAOReadOnly_mock.cpp b/mockups/AceDAOReadOnly_mock.cpp
new file mode 100644 (file)
index 0000000..9a463d8
--- /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.
+ */
+/**
+ * @author     Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version    0.1
+ * @brief      ACE DAO read only mockup class
+ */
+#include "AceDAOReadOnly_mock.h"
+
+namespace AceDB {
+OptionalExtendedPolicyResult AceDAOReadOnly::m_policyResult = ExtendedPolicyResult();
+OptionalCachedPromptDecision AceDAOReadOnly::m_promptDecision =
+        OptionalCachedPromptDecision();
+PreferenceTypes AceDAOReadOnly::m_devCapSetting =
+        PreferenceTypes::PREFERENCE_DEFAULT;
+PreferenceTypes AceDAOReadOnly::m_widgetDevCapSetting =
+        PreferenceTypes::PREFERENCE_DEFAULT;
+PreferenceTypesMap AceDAOReadOnly::m_devCapSettings = PreferenceTypesMap();
+BaseAttributeSet AceDAOReadOnly::m_attributeSet = BaseAttributeSet();
+BasePermissionList AceDAOReadOnly::m_widgetDevCapSettings = BasePermissionList();
+RequestedDevCapsMap AceDAOReadOnly::m_devCapPermissions =
+        RequestedDevCapsMap();
+FeatureNameVector AceDAOReadOnly::m_featureName;
+std::string AceDAOReadOnly::m_guid = std::string();
+};
diff --git a/mockups/AceDAOReadOnly_mock.h b/mockups/AceDAOReadOnly_mock.h
new file mode 100644 (file)
index 0000000..b28b304
--- /dev/null
@@ -0,0 +1,187 @@
+/*
+ * 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     Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version    0.1
+ * @brief      ACE DAO read only mockup class
+ */
+
+#ifndef WRT_MOCKUPS_ACE_DAO_READ_ONLY_MOCK_H_
+#define WRT_MOCKUPS_ACE_DAO_READ_ONLY_MOCK_H_
+
+#include <set>
+#include <utility>
+#include <string>
+
+#include <openssl/md5.h>
+#include <dpl/exception.h>
+#include <dpl/string.h>
+
+#include <PreferenceTypes.h>
+#include <BaseAttribute.h>
+#include <BasePermission.h>
+#include <IRequest.h>
+#include <PolicyEffect.h>
+#include <PolicyResult.h>
+#include <PromptDecision.h>
+#include <dpl/foreach.h>
+
+namespace AceDB {
+
+typedef std::map<DPL::String, bool> RequestedDevCapsMap;
+typedef DPL::String FeatureName;
+typedef std::vector<FeatureName> FeatureNameVector;
+
+class AceDAOReadOnly
+{
+  public:
+    class Exception
+    {
+      public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, DatabaseError)
+    };
+
+    AceDAOReadOnly() {}
+
+    static void attachToThreadRO(){};
+    static void attachToThreadRW(){};
+    static void detachFromThread(){};
+
+    // policy effect/decision
+    static OptionalExtendedPolicyResult getPolicyResult(
+            const BaseAttributeSet &/*attributes*/)
+    {
+        return m_policyResult;
+    }
+
+    // prompt decision
+    static OptionalCachedPromptDecision getPromptDecision(
+            WidgetHandle /*widgetHandle*/,
+            int /*hash*/)
+    {
+        return m_promptDecision;
+    }
+
+    // resource settings
+    static PreferenceTypes getDevCapSetting(const std::string &/*resource*/)
+    {
+        return m_devCapSetting;
+    }
+    static void getDevCapSettings(PreferenceTypesMap *preferences)
+    {
+        *preferences = m_devCapSettings;
+    }
+
+    // user settings
+    static void getWidgetDevCapSettings(BasePermissionList *permissions)
+    {
+        *permissions = m_widgetDevCapSettings;
+    }
+
+    static PreferenceTypes getWidgetDevCapSetting(
+            const std::string &/*resource*/,
+            WidgetHandle /*handler*/)
+    {
+        return m_widgetDevCapSetting;
+    }
+
+    static void getAttributes(BaseAttributeSet *attributes)
+    {
+        *attributes = m_attributeSet;
+    }
+
+    static void getRequestedDevCaps(
+        int /*widgetHandle*/,
+        RequestedDevCapsMap *permissions)
+    {
+        *permissions = m_devCapPermissions;
+    }
+
+    // Setting return values for mockups
+    static void setPolicyResult(OptionalExtendedPolicyResult value)
+    {
+        m_policyResult = value;
+    }
+
+    static void setPromptDecision(OptionalCachedPromptDecision value)
+    {
+        m_promptDecision = value;
+    }
+
+    static void setDevCapSetting(PreferenceTypes value)
+    {
+        m_devCapSetting = value;
+    }
+
+    static void setWidgetDevCapSetting(PreferenceTypes value)
+    {
+        m_widgetDevCapSetting = value;
+    }
+
+    static void setWidgetDevCapSettings(BasePermissionList value)
+    {
+        m_widgetDevCapSettings = value;
+    }
+
+    static void setDevCapSettings(PreferenceTypesMap value)
+    {
+        m_devCapSettings = value;
+    }
+
+    static void setAttributeSet(BaseAttributeSet value)
+    {
+        m_attributeSet = value;
+    }
+
+    static void setDevCapPermissions(RequestedDevCapsMap value)
+    {
+        m_devCapPermissions = value;
+    }
+
+    static void getAcceptedFeature(
+        WidgetHandle /* widgetHandle */,
+        FeatureNameVector *featureVector)
+    {
+        *featureVector = m_featureName;
+    }
+
+    static void setAcceptedFeature(const FeatureNameVector &fvector)
+    {
+        m_featureName = fvector;
+    }
+
+    static std::string getGUID(const WidgetHandle& handle)
+    {
+        return m_guid;
+    }
+
+  protected:
+    static OptionalExtendedPolicyResult m_policyResult;
+    static OptionalCachedPromptDecision m_promptDecision;
+    static PreferenceTypes m_devCapSetting;
+    static PreferenceTypes m_widgetDevCapSetting;
+    static PreferenceTypesMap m_devCapSettings;
+    static BaseAttributeSet m_attributeSet;
+    static BasePermissionList m_widgetDevCapSettings;
+    static RequestedDevCapsMap m_devCapPermissions;
+    static FeatureNameVector m_featureName;
+    static std::string m_guid;
+};
+
+}
+
+#endif // WRT_MOCKUPS_ACE_DAO_READ_ONLY_MOCK_H_
diff --git a/mockups/PolicyInformationPoint_mock.h b/mockups/PolicyInformationPoint_mock.h
new file mode 100644 (file)
index 0000000..07ced18
--- /dev/null
@@ -0,0 +1,32 @@
+/*
+ * 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  Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version 1.0
+ * @brief   PolicyInformationPoint mockup class
+ */
+#ifndef WRT_MOCKUPS_POLICY_INFORMATION_POINT_MOCK_H_
+#define WRT_MOCKUPS_POLICY_INFORMATION_POINT_MOCK_H_
+
+class PolicyInformationPoint {
+  public:
+    PolicyInformationPoint(void*, void*, void*){};
+    virtual ~PolicyInformationPoint(){};
+    void getAttributesValues(void*, void*){};
+
+};
+
+#endif // WRT_MOCKUPS_POLICY_INFORMATION_POINT_MOCK_H_
diff --git a/mockups/communication_client_mock.cpp b/mockups/communication_client_mock.cpp
new file mode 100644 (file)
index 0000000..bb75880
--- /dev/null
@@ -0,0 +1,28 @@
+/*
+ * 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      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       DBus client mockup class.
+ */
+#include "communication_client_mock.h"
+
+namespace WrtSecurity {
+namespace Communication {
+    int Client::m_checkAccessResult = 0;
+    bool Client::m_validationResult = true;
+}
+};
diff --git a/mockups/communication_client_mock.h b/mockups/communication_client_mock.h
new file mode 100644 (file)
index 0000000..457fd0e
--- /dev/null
@@ -0,0 +1,114 @@
+/*
+ * 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      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       DBus client mockup class.
+ */
+
+#ifndef WRT_MOCKUPS_DBUS_CLIENT_MOCK_H_
+#define WRT_MOCKUPS_DBUS_CLIENT_MOCK_H_
+
+#include <dpl/exception.h>
+#include <dpl/assert.h>
+
+#include <string>
+#include <vector>
+#include "ace_server_api.h"
+#include "popup_response_server_api.h"
+
+namespace WrtSecurity {
+namespace Communication {
+
+/*
+ * This class is a mockup implementation for some methods called
+ * with DBus::Client.
+ */
+
+class Client
+{
+
+  public:
+    class Exception
+    {
+      public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, SecurityCommunicationClientException)
+    };
+
+    Client(std::string /*interfaceName*/)
+    {
+    }
+
+    // ACE server api check access method
+    void call(const std::string &methodName,
+              int,
+              const std::string&,
+              const std::string&,
+              const std::vector<std::string>&,
+              const std::vector<std::string>&,
+              const std::string&,
+              int* outArg)
+    {
+        if (methodName == WrtSecurity::AceServerApi::CHECK_ACCESS_METHOD()) {
+            Assert(NULL != outArg);
+            *outArg = m_checkAccessResult;
+            return;
+        }
+    }
+
+    void call(const std::string &methodName,
+                  bool,
+                  int,
+                  int,
+                  const std::string&,
+                  const std::string&,
+                  const std::vector<std::string>&,
+                  const std::vector<std::string>&,
+                  const std::string&,
+                  bool* outArg)
+    {
+        if (methodName == WrtSecurity::PopupServerApi::VALIDATION_METHOD()) {
+            Assert(NULL != outArg);
+            *outArg = m_validationResult;
+            return;
+        }
+    }
+
+
+    ~Client()
+    {
+    }
+
+    static void setCheckAccessResult(int value)
+    {
+        m_checkAccessResult = value;
+    }
+
+    static void setValidationResult(bool value)
+    {
+        m_validationResult = value;
+    }
+
+  private:
+    static int m_checkAccessResult;
+    static bool m_validationResult;
+};
+
+} // namespace DBus
+}
+
+#endif // WRT_MOCKUPS_DBUS_CLIENT_MOCK_H_
diff --git a/packaging/wrt-security.changes b/packaging/wrt-security.changes
new file mode 100644 (file)
index 0000000..893d2eb
--- /dev/null
@@ -0,0 +1,12 @@
+* Thu Sep 12 2013 Hyunwoo Kim <hwlove.kim@samsung.com>
+- Use GDbus instead of dbus-glib
+- Start ecore main loop in main()
+- Add API for removing requested device capabilities of widget
+
+* Tue Aug 20 2013 Hyunwoo Kim <hwlove.kim@samsung.com>
+- Remove ace_check_access and Add ace_check_access_ex.
+- Remove roaming attribute.
+* Mon Aug 5 2013 Hyunwoo Kim <hwlove.kim@samsung.com>
+- Add ace checking API that can return reason of access denial(Privilge or Privacy)
+* Thu Jul 25 2013 Hyunwoo Kim <hwlove.kim@samsung.com>
+- Remove unused logs
diff --git a/packaging/wrt-security.manifest b/packaging/wrt-security.manifest
new file mode 100644 (file)
index 0000000..a61f2e7
--- /dev/null
@@ -0,0 +1,20 @@
+<manifest>
+       <define>
+               <domain name="wrt-security-daemon" />
+               <provide>
+                       <label name="wrt-security-daemon::daemon" />
+                       <label name="wrt-security-daemon::db" />
+               </provide>
+       </define>
+       <request>
+               <domain name="_" />
+       </request>
+       <assign>
+               <filesystem path="/usr/bin/wrt_security_change_policy.sh" exec_label="none"/>
+               <filesystem path="/usr/bin/wrt-security-daemon" label="wrt-security-daemon" exec_label="wrt-security-daemon"/>
+               <filesystem path="/usr/lib/systemd/system/wrt-security-daemon.service" label="_" exec_label="none" />
+               <filesystem path="/usr/lib/systemd/system/wrt-security-daemon.socket" label="_" exec_label="none" />
+               <filesystem path="/usr/lib/systemd/system/multi-user.target.wants/wrt-security-daemon.service" label="_" exec_label="none" />
+               <filesystem path="/usr/lib/systemd/system/sockets.target.wants/wrt-security-daemon.socket" label="_" exec_label="none" />
+       </assign>
+</manifest>
diff --git a/packaging/wrt-security.spec b/packaging/wrt-security.spec
new file mode 100644 (file)
index 0000000..0dc4512
--- /dev/null
@@ -0,0 +1,170 @@
+Name:       wrt-security
+Summary:    Wrt security daemon.
+Version:    0.0.67
+Release:    0
+Group:      Security/Access Control
+License:    Apache-2.0
+URL:        N/A
+Source0:    %{name}-%{version}.tar.gz
+Source1001: %{name}.manifest
+BuildRequires: cmake
+BuildRequires: zip
+BuildRequires: pkgconfig(dlog)
+BuildRequires: pkgconfig(openssl)
+BuildRequires: libattr-devel
+BuildRequires: pkgconfig(libsmack)
+BuildRequires: pkgconfig(dbus-1)
+BuildRequires: pkgconfig(libpcrecpp)
+BuildRequires: pkgconfig(icu-i18n)
+BuildRequires: pkgconfig(libsoup-2.4)
+BuildRequires: pkgconfig(xmlsec1)
+BuildRequires: pkgconfig(capi-appfw-app-manager)
+BuildRequires: pkgconfig(capi-appfw-package-manager)
+BuildRequires: pkgconfig(privacy-manager-client)
+BuildRequires: pkgconfig(privacy-manager-server)
+BuildRequires: pkgconfig(dpl-wrt-dao-ro)
+BuildRequires: pkgconfig(libsystemd-daemon)
+BuildRequires: pkgconfig(sqlite3)
+BuildRequires: pkgconfig(db-util)
+
+BuildRequires: tizen-security-policy
+Requires: tizen-security-policy
+%{?systemd_requires}
+
+%description
+Wrt security daemon and utilities.
+
+%package -n wrt-security-devel
+Summary:    Header files for client libraries.
+Group:      Development/Libraries
+Requires:   wrt-security = %{version}-%{release}
+
+%description -n wrt-security-devel
+Developer files for client libraries.
+
+%define enable_privacy_manager 1
+%define enable_wrt_ocsp 0
+
+%prep
+%setup -q
+cp %{SOURCE1001} .
+
+%build
+export LDFLAGS+="-Wl,--rpath=%{_libdir}"
+
+%cmake . -DDPL_LOG="ON" \
+        -DVERSION=%{version} \
+        -DCMAKE_BUILD_TYPE=%{?build_type:%build_type} \
+%if 0%{?enable_wrt_ocsp}
+        -DENABLE_WRT_OCSP=1 \
+%else
+        -DENABLE_WRT_OCSP=0 \
+%endif
+%if 0%{?enable_privacy_manager}
+       -DENABLE_PRIVACY_MANAGER=1 
+%endif
+
+
+make %{?jobs:-j%jobs}
+
+
+%install
+rm -rf %{buildroot}
+mkdir -p %{buildroot}/usr/share/license
+cp LICENSE %{buildroot}/usr/share/license/%{name}
+
+%make_install
+mkdir -p %{buildroot}%{_libdir}/systemd/system/multi-user.target.wants
+mkdir -p %{buildroot}%{_libdir}/systemd/system/sockets.target.wants
+ln -sf /usr/lib/systemd/system/wrt-security-daemon.service %{buildroot}%{_libdir}/systemd/system/multi-user.target.wants/wrt-security-daemon.service
+ln -sf /usr/lib/systemd/system/wrt-security-daemon.socket  %{buildroot}%{_libdir}/systemd/system/sockets.target.wants/wrt-security-daemon.socket
+
+%clean
+rm -rf %{buildroot}
+
+%post
+if [ ! -e "/opt/dbspace/.ace.db" ]; then
+    echo "This is new install of wrt-security"
+    echo "Calling /usr/bin/wrt_security_create_clean_db.sh"
+    /usr/bin/wrt_security_create_clean_db.sh
+else
+    # Find out old and new version of databases
+    ACE_OLD_DB_VERSION=`sqlite3 /opt/dbspace/.ace.db ".tables" | grep "DB_VERSION_"`
+    ACE_NEW_DB_VERSION=`cat /usr/share/wrt-engine/ace_db.sql | tr '[:blank:]' '\n' | grep DB_VERSION_`
+    echo "OLD ace database version ${ACE_OLD_DB_VERSION}"
+    echo "NEW ace database version ${ACE_NEW_DB_VERSION}"
+
+    if [ ${ACE_OLD_DB_VERSION} -a ${ACE_NEW_DB_VERSION} ]
+    then
+        if [ ${ACE_NEW_DB_VERSION} = ${ACE_OLD_DB_VERSION} ]
+        then
+            echo "Equal database detected so db installation ignored"
+        else
+            echo "Calling /usr/bin/wrt_security_create_clean_db.sh"
+            /usr/bin/wrt_security_create_clean_db.sh
+        fi
+    else
+        echo "Calling /usr/bin/wrt_security_create_clean_db.sh"
+        /usr/bin/wrt_security_create_clean_db.sh
+    fi
+fi
+
+/sbin/ldconfig
+echo "[WRT] wrt-security postinst done ..."
+
+%postun
+/sbin/ldconfig
+
+%files -n wrt-security
+%manifest %{name}.manifest
+%defattr(-,root,root,-)
+%attr(755,root,root) /usr/bin/wrt-security-daemon
+%{_libdir}/libace*.so
+%{_libdir}/libace*.so.*
+%{_libdir}/libwrt-security-commons.so
+%{_libdir}/libwrt-security-commons.so.*
+%{_libdir}/libwrt-security-commons-log.so
+%{_libdir}/libwrt-security-commons-log.so.*
+%{_libdir}/libwrt-security-commons-db.so
+%{_libdir}/libwrt-security-commons-db.so.*
+%if 0%{?enable_wrt_ocsp}
+%{_libdir}/libwrt-ocsp.so
+%{_libdir}/libwrt-ocsp.so.*
+%endif
+
+/usr/share/wrt-engine/*
+%attr(755,root,root) %{_bindir}/wrt_security_create_clean_db.sh
+%attr(755,root,root) %{_bindir}/wrt_security_change_policy.sh
+%attr(664,root,root) %{_datadir}/dbus-1/services/*
+%attr(664,root,root) /usr/etc/ace/bondixml*
+%attr(664,root,root) /usr/etc/ace/UnrestrictedPolicy.xml
+%attr(664,root,root) /usr/etc/ace/WAC2.0Policy.xml
+%{_datadir}/license/%{name}
+%{_libdir}/systemd/*
+
+%files -n wrt-security-devel
+%manifest %{name}.manifest
+%defattr(-,root,root,-)
+%{_includedir}/wrt-security/*
+%{_includedir}/ace/*
+%{_includedir}/ace-client/*
+%{_includedir}/ace-settings/*
+%{_includedir}/ace-install/*
+%{_includedir}/ace-common/*
+%{_includedir}/ace-popup-validation/*
+%{_libdir}/pkgconfig/security-client.pc
+%{_libdir}/pkgconfig/security-communication-client.pc
+%{_libdir}/pkgconfig/security-core.pc
+%{_libdir}/pkgconfig/security-dao-ro.pc
+%{_libdir}/pkgconfig/security-dao-rw.pc
+%{_libdir}/pkgconfig/security-install.pc
+%{_libdir}/pkgconfig/security-popup-validation.pc
+%{_libdir}/pkgconfig/security-settings.pc
+%{_libdir}/pkgconfig/security.pc
+%{_libdir}/pkgconfig/wrt-security-commons.pc
+%{_libdir}/pkgconfig/wrt-security-commons-log.pc
+%{_libdir}/pkgconfig/wrt-security-commons-db.pc
+%if 0%{?enable_wrt_ocsp}
+%{_includedir}/wrt-ocsp/*
+%{_libdir}/pkgconfig/security-wrt-ocsp.pc
+%endif
diff --git a/socket_connection/client/SecuritySocketClient.cpp b/socket_connection/client/SecuritySocketClient.cpp
new file mode 100644 (file)
index 0000000..d5d9aa1
--- /dev/null
@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) 2012 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        SecuritySocketClient.cpp
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       Implemtation of socket client class.
+ */
+
+#include <sys/socket.h>
+#include <string.h>
+#include <fcntl.h>
+#include <sys/types.h>
+#include <sys/un.h>
+#include <errno.h>
+#include <unistd.h>
+
+#include "SecuritySocketClient.h"
+#include "security_daemon_socket_config.h"
+
+void SecuritySocketClient::throwWithErrnoMessage(const std::string& specificInfo){
+    char *errstr = NULL;
+    char errbuf[512] = {0,};
+    #ifdef _GNU_SOURCE
+        errstr = strerror_r(errno, errbuf, sizeof(errbuf));
+    #else
+        strerror_r(errno, errbuf, sizeof(errbuf));
+        errstr = errbuf;
+    #endif
+    LogError(specificInfo << " : " << errstr);
+    ThrowMsg(Exception::SecuritySocketClientException, specificInfo << " : " << errstr);
+}
+
+SecuritySocketClient::SecuritySocketClient(const std::string& interfaceName) {
+    m_interfaceName = interfaceName;
+    m_serverAddress = WrtSecurity::SecurityDaemonSocketConfig::SERVER_ADDRESS();
+#ifdef ALL_LOGS
+    LogDebug("Client created");
+#endif
+}
+
+void SecuritySocketClient::connect(){
+    struct sockaddr_un remote;
+    if(-1 == (m_socketFd = socket(AF_UNIX, SOCK_STREAM,0))){
+       LogError("SecuritySocketClient: socket creation of wrt-security client socket failed." << errno);
+        throwWithErrnoMessage("socket()");
+    }
+
+    //socket needs to be nonblocking, because read can block after select
+    int flags;
+    if (-1 == (flags = fcntl(m_socketFd, F_GETFL, 0)))
+        flags = 0;
+    if(-1 == (fcntl(m_socketFd, F_SETFL, flags | O_NONBLOCK))){
+       LogError("SecuritySocketClient: fcntl on wrt-security client socket failed." << errno);
+        throwWithErrnoMessage("fcntl");
+    }
+
+    bzero(&remote, sizeof(remote));
+    remote.sun_family = AF_UNIX;
+    strncpy(remote.sun_path, m_serverAddress.c_str(), sizeof(remote.sun_path) - 1);
+    if(-1 == ::connect(m_socketFd, (struct sockaddr *)&remote, SUN_LEN(&remote))){
+       LogError("SecuritySocketClient: Connection with wrt-security failed." << errno);
+        throwWithErrnoMessage("connect()");
+    }
+
+    m_socketConnector.reset(new SocketConnection(m_socketFd));
+
+    LogDebug("Client connected");
+}
+
+void SecuritySocketClient::disconnect(){
+    //Socket should be already closed by server side, 
+    //even though we should close it in case of any errors
+    close(m_socketFd);
+    LogDebug("Client disconnected");
+}
diff --git a/socket_connection/client/SecuritySocketClient.h b/socket_connection/client/SecuritySocketClient.h
new file mode 100644 (file)
index 0000000..7d4bc95
--- /dev/null
@@ -0,0 +1,142 @@
+/*
+ * Copyright (c) 2012 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        SecuritySocketClient.h
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       Header of socket client class.
+ */
+
+#ifndef SECURITYSOCKETCLIENT_H_
+#define SECURITYSOCKETCLIENT_H_
+
+#include <memory>
+#include <string>
+#include <dpl/log/log.h>
+#include "SocketConnection.h"
+
+/* IMPORTANT:
+ * Methods connect(), call() and disconnected() should be called one by one.
+ * Between connect() and disconnect() you can use call() only once.
+ * It is because of timeout on call, e.g. to avoid waiting for corrupted data.
+ */
+
+/* USAGE:
+ * Class should be used according to this scheme:
+ * SecuritySocketClient client("Interface Name");
+ * (...)
+ * client.connect();
+ * client.call("Method name", in_arg1, in_arg2, ..., in_argN,
+ *             out_arg1, out_arg2, ..., out_argM);
+ * client.disconnect();
+ * (...)
+ *
+ * input parameters of the call are passed with reference,
+ * output ones are passed as pointers - parameters MUST be passed this way.
+ *
+ * Currently client supports serialization and deserialization of simple types
+ * (int, char, float, unsigned), strings (std::string and char*) and
+ * some STL containers (std::vector, std::list, std::map, std::pair).
+ * Structures and classes are not (yet) supported.
+ */
+
+class SecuritySocketClient {
+public:
+    class Exception
+    {
+    public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, SecuritySocketClientException)
+    };
+
+    SecuritySocketClient(const std::string &interfaceName);
+    void connect();
+    void disconnect();
+
+    void call(std::string methodName){
+        make_call(m_interfaceName);
+        make_call(methodName);
+    }
+
+    template<typename ...Args>
+    void call(std::string methodName, const Args&... args){
+        make_call(m_interfaceName);
+        make_call(methodName);
+        make_call(args...);
+    }
+
+private:
+    template<typename T, typename ...Args>
+    void make_call(const T& invalue, const Args&... args){
+        make_call(invalue);
+        make_call(args...);
+    }
+
+    template<typename T>
+    void make_call(const T& invalue){
+        Try {
+            m_socketConnector->write(invalue);
+        }
+        Catch (SocketConnection::Exception::SocketConnectionException){
+            LogError("Socket connection write error");
+            ReThrowMsg(Exception::SecuritySocketClientException,"Socket connection write error");
+        }
+    }
+
+    template<typename T, typename ...Args>
+    void make_call(const T* invalue, const Args&... args){
+        make_call(invalue);
+        make_call(args...);
+    }
+
+    template<typename T>
+    void make_call(const T* invalue){
+        Try {
+            m_socketConnector->write(invalue);
+        }
+        Catch (SocketConnection::Exception::SocketConnectionException){
+            LogError("Socket connection write error");
+            ReThrowMsg(Exception::SecuritySocketClientException,"Socket connection write error");
+        }
+    }
+
+    template<typename T, typename ...Args>
+    void make_call(T * outvalue, const Args&... args){
+        make_call(outvalue);
+        make_call(args...);
+    }
+
+    template<typename T>
+    void make_call(T* outvalue){
+        Try {
+            m_socketConnector->read(outvalue);
+        }
+        Catch (SocketConnection::Exception::SocketConnectionException){
+            LogError("Socket connection read error");
+            ReThrowMsg(Exception::SecuritySocketClientException,"Socket connection read error");
+        }
+    }
+
+
+private:
+    void throwWithErrnoMessage(const std::string& specificInfo);
+    std::string m_serverAddress;
+    std::string m_interfaceName;
+    std::unique_ptr<SocketConnection> m_socketConnector;
+    int m_socketFd;
+};
+
+#endif /* SECURITYSOCKETCLIENT_H_ */
diff --git a/socket_connection/connection/SocketConnection.cpp b/socket_connection/connection/SocketConnection.cpp
new file mode 100644 (file)
index 0000000..f504bae
--- /dev/null
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2012 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        SocketConnection.cpp
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ */
+
+#include "SocketConnection.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/socket_connection/connection/SocketConnection.h b/socket_connection/connection/SocketConnection.h
new file mode 100644 (file)
index 0000000..a11b588
--- /dev/null
@@ -0,0 +1,116 @@
+/*
+ * Copyright (c) 2012 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        SocketConnection.h
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       This file is a header of Socket Connection class with implemented templates
+ */
+
+#ifndef SOCKETCONNECTION_H_
+#define SOCKETCONNECTION_H_
+
+#include <dpl/serialization.h>
+#include <dpl/log/log.h>
+#include <new>
+#include "SocketStream.h"
+
+/*
+ * This class implements interface for generic read and write from given socket.
+ * It does not maintain socket descriptor, so any connecting and disconnecting should be
+ * done above calls to this class.
+ */
+
+/*
+ * Throws SocketConnectionException when read/write will not succeed or if any bad allocation
+ * exception occurs during read.
+ */
+
+class SocketConnection {
+
+public:
+
+    class Exception
+    {
+    public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, SocketConnectionException)
+    };
+
+    explicit SocketConnection(int socket_fd) : m_socketStream(socket_fd){
+        LogInfo("Created");
+    }
+
+    template<typename T, typename ...Args>
+    void read(T* out, const Args&... args ){
+        read(out);
+        read(args...);
+    }
+
+    template<typename T>
+    void read(T* out){
+        Try {
+            DPL::Deserialization::Deserialize(m_socketStream, *out);
+        }
+
+        Catch (std::bad_alloc){
+            LogError("Bad allocation error");
+            ThrowMsg(Exception::SocketConnectionException, "Bad allocation error");
+        }
+
+        Catch (SocketStream::Exception::SocketStreamException) {
+            LogError("Socket stream error");
+            ReThrowMsg(Exception::SocketConnectionException, "Socket stream error");
+        }
+    }
+
+    template<typename T, typename ...Args>
+    void write(const T& in, const Args&... args){
+        write(in);
+        write(args...);
+    }
+
+    template<typename T>
+    void write(const T& in){
+        Try {
+            DPL::Serialization::Serialize(m_socketStream, in);
+        } Catch (SocketStream::Exception::SocketStreamException) {
+            LogError("Socket stream error");
+            ReThrowMsg(Exception::SocketConnectionException, "Socket stream error");
+        }
+    }
+
+    template<typename T, typename ...Args>
+    void write(const T* in, const Args&... args){
+        write(in);
+        write(args...);
+    }
+
+    template<typename T>
+        void write(const T* in){
+            Try {
+                DPL::Serialization::Serialize(m_socketStream, in);
+            } Catch (SocketStream::Exception::SocketStreamException) {
+                LogError("Socket stream error");
+                ReThrowMsg(Exception::SocketConnectionException, "Socket stream error");
+            }
+        }
+
+private:
+    SocketStream m_socketStream;
+};
+
+#endif /* SOCKETCONNECTION_H_ */
diff --git a/socket_connection/connection/SocketStream.cpp b/socket_connection/connection/SocketStream.cpp
new file mode 100644 (file)
index 0000000..36f6d2c
--- /dev/null
@@ -0,0 +1,191 @@
+/*
+ * Copyright (c) 2012 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        SocketStream.cpp
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       Implementation of socket stream class
+ */
+
+
+#include <sys/socket.h>
+#include <sys/select.h>
+#include <errno.h>
+#include <cstring>
+#include <unistd.h>
+#include <dpl/log/log.h>
+#include "SocketStream.h"
+
+#define READ_TIEMOUT_SEC 1
+#define READ_TIMEUOT_NSEC 0
+#define WRITE_TIMEOUT_SEC 0
+#define WRITE_TIMEOUT_NSEC 100000000
+#define MAX_BUFFER 10240
+
+void SocketStream::throwWithErrnoMessage(std::string function_name){
+    char *errstr = NULL;
+    char errbuf[512] = {0,};
+    #ifdef _GNU_SOURCE
+        errstr = strerror_r(errno, errbuf, sizeof(errbuf));
+    #else
+        strerror_r(errno, errbuf, sizeof(errbuf));
+        errstr = errbuf;
+    #endif
+    LogError(function_name << " : " << errstr);
+    ThrowMsg(Exception::SocketStreamException, function_name << " : " << errstr);
+}
+
+void SocketStream::Read(size_t num, void * bytes){
+
+    if(NULL == bytes){
+        LogError("Null pointer to buffer");
+        ThrowMsg(Exception::SocketStreamException, "Null pointer to buffer");
+    }
+    
+    m_bytesRead += num;
+    
+    if(m_bytesRead > MAX_BUFFER){
+        LogError("Too big buffer requested!");
+        ThrowMsg(Exception::SocketStreamException, "Too big buffer requested!");
+    }
+
+    char part_buffer[MAX_BUFFER];
+    std::string whole_buffer;
+
+    fd_set rset, allset;
+    int max_fd;
+    ssize_t bytes_read = 0, bytes_to_read = (ssize_t) num;
+
+    timespec timeout;
+
+    max_fd = m_socketFd;
+    ++max_fd;
+
+    FD_ZERO(&allset);
+    FD_SET(m_socketFd, &allset);
+
+    int returned_value;
+       
+    char *errstr = NULL;
+    char errbuf[512] = {0,};
+
+    while(bytes_to_read != 0){
+        timeout.tv_sec = READ_TIEMOUT_SEC;
+        timeout.tv_nsec = READ_TIMEUOT_NSEC;
+        rset = allset;
+
+        if(-1 == (returned_value = pselect(max_fd, &rset, NULL, NULL, &timeout, NULL))){
+            if(errno == EINTR) continue;
+            throwWithErrnoMessage("pselect()");
+        }
+        if(0 == returned_value){
+            //This means pselect got timedout
+            //This is not a proper behavior in reading data from UDS
+            //And could mean we got corrupted connection
+            LogError("Couldn't read whole data. continue..");
+            continue;
+        }
+        if(FD_ISSET(m_socketFd, &rset)){
+            bytes_read = read(m_socketFd, part_buffer, num);
+            if(bytes_read <= 0){
+                if(errno == ECONNRESET || errno == ENOTCONN || errno == ETIMEDOUT){
+                    #ifdef _GNU_SOURCE
+                        errstr = strerror_r(errno, errbuf, sizeof(errbuf));
+                    #else
+                        strerror_r(errno, errbuf, sizeof(errbuf));
+                        errstr = errbuf;
+                    #endif
+                    ThrowMsg(Exception::SocketStreamException,
+                            "Connection closed : " << errstr << ". Couldn't read whole data");
+                }else if (errno != EAGAIN && errno != EWOULDBLOCK){
+                    throwWithErrnoMessage("read()");
+                }
+            }
+
+            whole_buffer.append(part_buffer, bytes_read);
+            bytes_to_read-=bytes_read;
+            bytes_read = 0;
+            continue;
+        }
+
+    }
+    memcpy(bytes, whole_buffer.c_str(), num);
+}
+
+void SocketStream::Write(size_t num, const void * bytes){
+
+    if(NULL == bytes){
+        LogError("Null pointer to buffer");
+        ThrowMsg(Exception::SocketStreamException, "Null pointer to buffer");
+    }
+    
+    m_bytesWrote += num;
+    
+    if(m_bytesWrote > MAX_BUFFER){
+        LogError("Too big buffer requested!");
+        ThrowMsg(Exception::SocketStreamException, "Too big buffer requested!");
+    }
+
+    fd_set wset, allset;
+    int max_fd;
+
+    timespec timeout;
+
+    max_fd = m_socketFd;
+    ++max_fd;
+
+    FD_ZERO(&allset);
+    FD_SET(m_socketFd, &allset);
+
+    int returned_value;
+
+    int write_res, bytes_to_write = num;
+    unsigned int current_offset = 0;
+
+    char *errstr = NULL;
+    char errbuf[512] = {0,};
+
+    while(current_offset != num){
+        timeout.tv_sec = WRITE_TIMEOUT_SEC;
+        timeout.tv_nsec = WRITE_TIMEOUT_NSEC;
+        wset = allset;
+
+        if(-1 == (returned_value = pselect(max_fd, NULL, &wset, NULL, &timeout, NULL))){
+            if(errno == EINTR) continue;
+            throwWithErrnoMessage("pselect()");
+        }
+
+        if(FD_ISSET(m_socketFd, &wset)){
+            if(-1 == (write_res = write(m_socketFd, reinterpret_cast<const char *>(bytes) + current_offset, bytes_to_write))){
+                if(errno == ECONNRESET || errno == EPIPE){
+                    #ifdef _GNU_SOURCE
+                        errstr = strerror_r(errno, errbuf, sizeof(errbuf));
+                    #else
+                        strerror_r(errno, errbuf, sizeof(errbuf));
+                        errstr = errbuf;
+                    #endif
+                    ThrowMsg(Exception::SocketStreamException,
+                            "Connection closed : " << errstr << ". Couldn't write whole data");
+
+                }else if(errno != EAGAIN && errno != EWOULDBLOCK){
+                    throwWithErrnoMessage("write()");
+                }
+            }
+            current_offset += write_res;
+            bytes_to_write -= write_res;
+        }
+    }
+}
diff --git a/socket_connection/connection/SocketStream.h b/socket_connection/connection/SocketStream.h
new file mode 100644 (file)
index 0000000..dc1db61
--- /dev/null
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2012 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        SocketStream.h
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       Header of socket stream class.
+ */
+
+#ifndef SOCKETSTREAM_H_
+#define SOCKETSTREAM_H_
+
+#include <string>
+#include <sys/socket.h>
+#include <sys/select.h>
+#include <dpl/serialization.h>
+#include <dpl/log/log.h>
+
+/*
+ * This class implements binary read/write from socket used for DPL serialization and deserialization
+ * It can read or write buffers of max *total* size 10kB.
+ * I does not maintain socket descriptor.
+ */
+
+/*
+ * Throws SocketStreamException when buffer is null or its size exceeds max size or when
+ * there is an error during read or write.
+ */
+
+
+
+class SocketStream : public DPL::IStream {
+public:
+    class Exception
+    {
+      public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, SocketStreamException)
+    };
+
+    explicit SocketStream(int socket_fd) : m_socketFd(socket_fd), 
+                                           m_bytesRead(0),
+                                           m_bytesWrote(0)
+    {
+        LogInfo("Created");
+    }
+    void Read(size_t num, void * bytes);
+    void Write(size_t num, const void * bytes);
+private:
+    void throwWithErrnoMessage(std::string specificInfo);
+    int m_socketFd;
+    int m_bytesRead;
+    int m_bytesWrote;
+};
+
+#endif /* SOCKETSTREAM_H_ */
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
new file mode 100644 (file)
index 0000000..03bf125
--- /dev/null
@@ -0,0 +1,171 @@
+# 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     CMakeLists.txt
+# @author   Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+#
+
+SET(DAEMON_BASIC_DEP
+    dpl-efl
+    dpl-dbus-efl
+    dpl-utils-efl
+    libsoup-2.4
+    openssl
+    libsmack
+    privacy-manager-server
+  )
+
+IF(SMACK_ENABLE)
+    LIST(APPEND DAEMON_BASIC_DEP libprivilege-control)
+ENDIF(SMACK_ENABLE)
+
+IF(NOT DEFINED ENABLE_PRIVACY_MANAGER)
+PKG_CHECK_MODULES(DAEMON_DEP
+    ${DAEMON_BASIC_DEP}
+    REQUIRED
+    libsystemd-daemon)
+ELSE()
+PKG_CHECK_MODULES(DAEMON_DEP
+    ${DAEMON_BASIC_DEP}
+    ${PRIVILEGE_MANAGER_DEP}
+    REQUIRED
+    libsystemd-daemon)
+ENDIF()
+
+SET(DAEMON_SOURCES_PATH ${PROJECT_SOURCE_DIR}/src)
+
+SET(DAEMON_SOURCES
+    #socket connection
+    ${PROJECT_SOURCE_DIR}/socket_connection/connection/SocketConnection.cpp
+    ${PROJECT_SOURCE_DIR}/socket_connection/connection/SocketStream.cpp
+    #caller
+    ${DAEMON_SOURCES_PATH}/services/caller/security_caller.cpp
+    #daemon
+    ${DAEMON_SOURCES_PATH}/daemon/dbus/security_dbus_service.cpp
+    ${DAEMON_SOURCES_PATH}/daemon/sockets/security_socket_service.cpp
+    ${DAEMON_SOURCES_PATH}/daemon/security_daemon.cpp
+    ${DAEMON_SOURCES_PATH}/main.cpp
+    #ocsp
+    ${DAEMON_SOURCES_PATH}/services/ocsp/dbus/ocsp_server_dbus_interface.cpp
+    ${DAEMON_SOURCES_PATH}/services/ocsp/socket/ocsp_service_callbacks.cpp
+    ${DAEMON_SOURCES_PATH}/services/ocsp/ocsp_service.cpp
+    #ace
+    ${DAEMON_SOURCES_PATH}/services/ace/dbus/ace_server_dbus_interface.cpp
+    ${DAEMON_SOURCES_PATH}/services/ace/socket/ace_service_callbacks.cpp
+    ${DAEMON_SOURCES_PATH}/services/ace/ace_service.cpp
+    ${DAEMON_SOURCES_PATH}/services/ace/logic/security_controller.cpp
+    ${DAEMON_SOURCES_PATH}/services/ace/logic/attribute_facade.cpp
+    ${DAEMON_SOURCES_PATH}/services/ace/logic/security_logic.cpp
+    ${DAEMON_SOURCES_PATH}/services/ace/logic/simple_roaming_agent.cpp
+    #popup
+    ${DAEMON_SOURCES_PATH}/services/popup/dbus/popup_response_dbus_interface.cpp
+    ${DAEMON_SOURCES_PATH}/services/popup/socket/popup_service_callbacks.cpp
+  )
+
+SET_SOURCE_FILES_PROPERTIES(
+    ${DAEMON_SOURCES}
+    PROPERTIES
+        COMPILE_FLAGS "-std=c++0x -fPIE")
+
+############################# Lets start compilation process ##################
+
+IF(DEFINED DBUS_CONNECTION)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/daemon/dbus)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/caller)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ace/dbus)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ocsp/dbus)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/popup/dbus)
+ENDIF()
+
+#ace library
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/ace/include)
+#socket connection library
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/socket_connection/connection)
+#daemon
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/daemon)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/daemon/dbus)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/daemon/sockets/api)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/daemon/sockets)
+#caller
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/caller)
+#ace
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ace)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ace/dbus)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ace/socket)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ace/socket/api)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ace/logic)
+#ocsp
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ocsp)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ocsp/dbus)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ocsp/socket)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ocsp/socket/api)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ocsp/logic)
+#popup
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/popup)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/popup/dbus)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/popup/socket)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/popup/socket/api)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/popup/logic)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/ace/include)
+INCLUDE_DIRECTORIES(${DAEMON_DEP_INCLUDE_DIRS})
+
+IF(NOT DEFINED DBUS_CONNECTION)
+#commons
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/commons/modules/log/include)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/commons/modules/core/include)
+LINK_DIRECTORIES(
+    ${PROJECT_SOURCE_DIR}/commons/build/core
+    ${PROJECT_SOURCE_DIR}/commons/build/log
+    )
+ENDIF()
+
+ADD_EXECUTABLE(${TARGET_DAEMON}
+    ${DAEMON_SOURCES})
+
+IF(DEFINED DBUS_CONNECTION)
+TARGET_LINK_LIBRARIES(${TARGET_DAEMON}
+    ${DAEMON_DEP_LIBRARIES}
+    ${TARGET_ACE_LIB}
+    ${TARGET_ACE_DAO_RW_LIB}
+    -pie
+    )
+ELSE()
+TARGET_LINK_LIBRARIES(${TARGET_DAEMON}
+    ${DAEMON_DEP_LIBRARIES}
+    ${TARGET_ACE_LIB}
+    ${TARGET_ACE_DAO_RW_LIB}
+    libwrt-security-commons
+    libwrt-security-commons-log
+    -pie
+    )
+ENDIF()
+
+INSTALL(TARGETS ${TARGET_DAEMON}
+    DESTINATION bin)
+
+INSTALL(FILES
+    ${PROJECT_SOURCE_DIR}/src/daemon/dbus/org.tizen.SecurityDaemon.service
+    DESTINATION /usr/share/dbus-1/services
+    )
+
+INSTALL(FILES
+    ${PROJECT_SOURCE_DIR}/src/services/ace/ace_server_api.h
+    ${PROJECT_SOURCE_DIR}/src/services/ocsp/ocsp_server_api.h
+    ${PROJECT_SOURCE_DIR}/src/services/popup/popup_response_server_api.h
+    ${PROJECT_SOURCE_DIR}/src/services/popup/popup_ace_data_types.h
+    ${PROJECT_SOURCE_DIR}/src/daemon/dbus/security_daemon_dbus_config.h
+    DESTINATION /usr/include/wrt-security
+    )
diff --git a/src/TODO.txt b/src/TODO.txt
new file mode 100644 (file)
index 0000000..48755fd
--- /dev/null
@@ -0,0 +1,11 @@
+Security Daemon todos:
+
+* One runtime instance should be allowed (DONE)
+* Hide application symbols that should not be exported.
+* Add support for service/module dependencies.
+* Signals blocking/handlers should be added.
+* Connections to other databases should be set.
+* Make it a real daemon (demonize ? auto restarting support ?)
+* Same of the files needs to be separated from the rest of WebRuntime sources:
+    - global_config.cpp
+
diff --git a/src/daemon/dbus/org.tizen.SecurityDaemon.service b/src/daemon/dbus/org.tizen.SecurityDaemon.service
new file mode 100644 (file)
index 0000000..fc51772
--- /dev/null
@@ -0,0 +1,3 @@
+[D-BUS Service]
+Name=org.tizen.SecurityDaemon
+Exec=/usr/bin/wrt-security-daemon
diff --git a/src/daemon/dbus/security_daemon_dbus_config.h b/src/daemon/dbus/security_daemon_dbus_config.h
new file mode 100644 (file)
index 0000000..30b8d90
--- /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        security_daemon_dbus_config.h
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This file contains security daemon DBus configuration.
+ */
+#ifndef WRT_SRC_RPC_SECURITY_DAEMON_DBUS_CONFIG_H_
+#define WRT_SRC_RPC_SECURITY_DAEMON_DBUS_CONFIG_H_
+
+#include <string>
+
+namespace WrtSecurity {
+
+struct SecurityDaemonConfig {
+    static const std::string OBJECT_PATH()
+    {
+        return "/org/tizen/SecurityDaemon";
+    }
+
+    static const std::string SERVICE_NAME()
+    {
+        return "org.tizen.SecurityDaemon";
+    }
+};
+
+} // namespace WrtSecurity
+
+#endif // WRT_SRC_RPC_SECURITY_DAEMON_DBUS_CONFIG_H_
diff --git a/src/daemon/dbus/security_dbus_service.cpp b/src/daemon/dbus/security_dbus_service.cpp
new file mode 100644 (file)
index 0000000..303aa19
--- /dev/null
@@ -0,0 +1,95 @@
+/*
+ * 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        security_dbus_service.cpp
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @author      Zbigniew Kostrzewa (z.kostrzewa@samsung.com)
+ * @version     1.0
+ * @brief       This file contains implementation of security DBus service.
+ */
+#include <dpl/log/log.h>
+#include <algorithm>
+#include <gio/gio.h>
+#include <dpl/exception.h>
+#include <dpl/dbus/interface.h>
+#include <dpl/dbus/connection.h>
+#include "security_dbus_service.h"
+#include "security_daemon_dbus_config.h"
+#include <ace_server_dbus_interface.h>
+#include <ocsp_server_dbus_interface.h>
+#include <popup_response_dbus_interface.h>
+
+
+void SecurityDBusService::start()
+{
+    LogDebug("SecurityDBusService starting");
+    m_connection = DPL::DBus::Connection::systemBus();
+    std::for_each(m_objects.begin(),
+                  m_objects.end(),
+                  [this] (const DPL::DBus::ObjectPtr& object)
+                  {
+                      m_connection->registerObject(object);
+                  });
+    m_connection->registerService(
+            WrtSecurity::SecurityDaemonConfig::SERVICE_NAME());
+}
+
+void SecurityDBusService::stop()
+{
+    LogDebug("SecurityDBusService stopping");
+    m_connection.reset();
+}
+
+void SecurityDBusService::initialize()
+{
+    LogDebug("SecurityDBusService initializing");
+    g_type_init();
+
+    addInterface(WrtSecurity::SecurityDaemonConfig::OBJECT_PATH(),
+                 std::make_shared<RPC::AceServerDBusInterface>());
+    addInterface(WrtSecurity::SecurityDaemonConfig::OBJECT_PATH(),
+                 std::make_shared<RPC::OcspServerDBusInterface>());
+    addInterface(WrtSecurity::SecurityDaemonConfig::OBJECT_PATH(),
+                 std::make_shared<RPC::PopupResponseDBusInterface>());
+}
+
+void SecurityDBusService::addInterface(const std::string& objectPath,
+                                       const InterfaceDispatcherPtr& dispatcher)
+{
+    auto ifaces =
+        DPL::DBus::Interface::fromXMLString(dispatcher->getXmlSignature());
+    if (ifaces.empty())
+    {
+        ThrowMsg(DPL::Exception, "No interface description.");
+    }
+
+    auto iface = ifaces.at(0);
+    iface->setDispatcher(dispatcher.get());
+
+    m_dispatchers.push_back(dispatcher);
+    m_objects.push_back(DPL::DBus::Object::create(objectPath, iface));
+}
+
+void SecurityDBusService::deinitialize()
+{
+    LogDebug("SecurityDBusService deinitializing");
+    m_objects.clear();
+    m_dispatchers.clear();
+}
+
+#ifdef DBUS_CONNECTION
+DAEMON_REGISTER_SERVICE_MODULE(SecurityDBusService)
+#endif //DBUS_CONNECTION
diff --git a/src/daemon/dbus/security_dbus_service.h b/src/daemon/dbus/security_dbus_service.h
new file mode 100644 (file)
index 0000000..82fd627
--- /dev/null
@@ -0,0 +1,53 @@
+/*
+ * 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        security_dbus_service.h
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @author      Zbigniew Kostrzewa (z.kostrzewa@samsung.com)
+ * @version     1.0
+ * @brief       This file contains definitions of security DBus service.
+ */
+#ifndef WRT_SRC_RPC_SECURITY_DBUS_SERVICE_H_
+#define WRT_SRC_RPC_SECURITY_DBUS_SERVICE_H_
+
+#include <memory>
+#include <vector>
+#include <dpl/dbus/connection.h>
+#include <dpl/dbus/object.h>
+#include <dpl/dbus/dispatcher.h>
+#include <dpl/dbus/dbus_interface_dispatcher.h>
+#include <security_daemon.h>
+
+class SecurityDBusService : public SecurityDaemon::DaemonService {
+private:
+    virtual void initialize();
+    virtual void start();
+    virtual void stop();
+    virtual void deinitialize();
+
+private:
+    typedef std::shared_ptr<DPL::DBus::InterfaceDispatcher> InterfaceDispatcherPtr;
+    typedef std::shared_ptr<DPL::DBus::Dispatcher> DispatcherPtr;
+
+    void addInterface(const std::string& objectPath,
+                      const InterfaceDispatcherPtr& dispatcher);
+
+    DPL::DBus::ConnectionPtr m_connection;
+    std::vector<DPL::DBus::ObjectPtr> m_objects;
+    std::vector<DispatcherPtr> m_dispatchers;
+};
+
+#endif // WRT_SRC_RPC_SECURITY_DBUS_SERVICE_H_
diff --git a/src/daemon/security_daemon.cpp b/src/daemon/security_daemon.cpp
new file mode 100644 (file)
index 0000000..f24f176
--- /dev/null
@@ -0,0 +1,114 @@
+/*
+ * 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        security_daemon.cpp
+ * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
+ * @version     1.0
+ * @brief       This is implementation file of Security Daemon
+ */
+
+#include "security_daemon.h"
+
+#include <dpl/assert.h>
+#include <dpl/foreach.h>
+#include <dpl/log/log.h>
+#ifdef DBUS_CONNECTION
+#include <dpl/framework_efl.h>
+#endif
+
+#include <dpl/singleton_impl.h>
+IMPLEMENT_SINGLETON(SecurityDaemon::SecurityDaemon)
+
+#include <ace-dao-rw/AceDAO.h>
+
+namespace SecurityDaemon {
+
+SecurityDaemon::SecurityDaemon() :
+    m_initialized(false),
+    m_terminating(false),
+    m_returnValue(0)
+{
+}
+
+void SecurityDaemon::initialize(int& /*argc*/, char** /*argv*/)
+{
+    DPL::Log::LogSystemSingleton::Instance().SetTag("SECURITY_DAEMON");
+    LogDebug("Initializing");
+    Assert(!m_initialized && "Already Initialized");
+
+    DatabaseService::initialize();
+    FOREACH (service, m_servicesList) {
+        (*service)->initialize();
+    }
+    m_initialized = true;
+    LogDebug("Initialized");
+}
+
+int SecurityDaemon::execute()
+{
+    Assert(m_initialized && "Not Initialized");
+    LogDebug("Starting execute");
+    FOREACH (service, m_servicesList) {
+        (*service)->start();
+    }
+
+    return m_returnValue;
+}
+
+void SecurityDaemon::terminate(int returnValue)
+{
+    Assert(m_initialized && "Not Initialized");
+    Assert(!m_terminating && "Already terminating");
+    LogDebug("Terminating");
+
+    m_returnValue = returnValue;
+    m_terminating = true;
+
+    FOREACH (service, m_servicesList) {
+        (*service)->stop();
+    }
+}
+
+void SecurityDaemon::shutdown()
+{
+    LogDebug("Shutdown");
+    Assert(m_initialized && "Not Initialized");
+
+    DatabaseService::deinitialize();
+    FOREACH (service, m_servicesList) {
+        (*service)->deinitialize();
+    }
+
+    m_initialized = false;
+}
+
+namespace DatabaseService {
+
+void initialize(void)
+{
+    LogDebug("Ace/Wrt database services initializing...");
+    AceDB::AceDAO::attachToThreadRW();
+}
+
+void deinitialize(void)
+{
+    LogDebug("Ace/Wrt database services deinitializing...");
+    AceDB::AceDAO::detachFromThread();
+}
+
+} //namespace DatabaseService
+
+} //namespace SecurityDaemon
diff --git a/src/daemon/security_daemon.h b/src/daemon/security_daemon.h
new file mode 100644 (file)
index 0000000..a98f309
--- /dev/null
@@ -0,0 +1,94 @@
+/*
+ * 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        security_daemon.h
+ * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
+ * @version     1.0
+ * @brief       This is header file of Security Daemon
+ */
+
+#ifndef WRT_SRC_SECURITY_DAEMON_SECURITY_DAEMON_H
+#define WRT_SRC_SECURITY_DAEMON_SECURITY_DAEMON_H
+
+#include <utility>
+#include <memory>
+#include <list>
+#include <dpl/noncopyable.h>
+#include <dpl/singleton.h>
+#include <dpl/assert.h>
+
+
+namespace SecurityDaemon {
+
+class DaemonService : DPL::Noncopyable {
+  public:
+    virtual void initialize() = 0;
+    virtual void start() = 0;
+    virtual void stop() = 0;
+    virtual void deinitialize() = 0;
+};
+
+class SecurityDaemon : DPL::Noncopyable
+{
+  public:
+    SecurityDaemon();
+
+    void initialize(int& argc, char** argv);
+    int execute();
+    void terminate(int returnValue = 0);
+
+    template<typename ServiceType, typename ...Args>
+    void registerService(Args&&... args)
+    {
+        Assert(!m_initialized && "Too late for registration");
+
+        m_servicesList.push_back(
+                std::make_shared<ServiceType>(std::forward<Args>(args)...));
+    }
+
+    void shutdown();
+
+  private:
+    bool m_initialized;
+    bool m_terminating;
+    int m_returnValue;
+    typedef std::list<std::shared_ptr<DaemonService>> DaemonServiceList;
+    DaemonServiceList m_servicesList;
+};
+
+namespace DatabaseService {
+    void initialize();
+    void deinitialize();
+};
+
+} //namespace SecurityDaemon
+
+typedef DPL::Singleton<SecurityDaemon::SecurityDaemon> SecurityDaemonSingleton;
+
+#define DAEMON_REGISTER_SERVICE_MODULE(Type)                                \
+    namespace {                                                             \
+        static int initializeModule();                                      \
+        static int initializeModuleHelper = initializeModule();             \
+        int initializeModule()                                              \
+        {                                                                   \
+            (void)initializeModuleHelper;                                   \
+            SecurityDaemonSingleton::Instance().registerService<Type>();    \
+            return 0;                                                       \
+        }                                                                   \
+    }
+
+
+#endif /* WRT_SRC_SECURITY_DAEMON_SECURITY_DAEMON_H */
diff --git a/src/daemon/sockets/api/callback_api.h b/src/daemon/sockets/api/callback_api.h
new file mode 100644 (file)
index 0000000..ddda4d4
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2012 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        callback_api.h
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       This header provides types and exceptions required for security service callbacks
+ */
+
+#ifndef CALLBACK_API_H_
+#define CALLBACK_API_H_
+
+#include <dpl/exception.h>
+
+typedef void (*socketServerCallback) (SocketConnection * connector);
+
+typedef bool (*securityCheck) (int socketfd);
+
+namespace ServiceCallbackApi{
+
+    class Exception{
+    public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, ServiceCallbackException)
+    };
+
+}
+
+#endif /* CALLBACK_API_H_ */
diff --git a/src/daemon/sockets/security_daemon_socket_config.h b/src/daemon/sockets/security_daemon_socket_config.h
new file mode 100644 (file)
index 0000000..3d8b6f8
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2012 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        security_daemon_socket_config.h
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief
+ */
+
+#ifndef SECURITY_DAEMON_SOCKET_CONFIG_H_
+#define SECURITY_DAEMON_SOCKET_CONFIG_H_
+
+#include <string>
+#include <signal.h>
+
+namespace WrtSecurity {
+
+struct SecurityDaemonSocketConfig {
+    static const std::string SERVER_ADDRESS()
+    {
+        return "/tmp/server";
+    }
+};
+
+} // namespace WrtSecurity
+#endif /* SECURITY_DAEMON_SOCKET_CONFIG_H_ */
diff --git a/src/daemon/sockets/security_socket_service.cpp b/src/daemon/sockets/security_socket_service.cpp
new file mode 100644 (file)
index 0000000..fc7e730
--- /dev/null
@@ -0,0 +1,440 @@
+/*
+ * Copyright (c) 2012 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        security_socket_service.cpp
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       Implementation of socket server
+ */
+#include <systemd/sd-daemon.h>
+#include <errno.h>
+#include <sys/types.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <sys/signalfd.h>
+#include <sys/select.h>
+#include <sys/stat.h>
+#include <signal.h>
+#include <fcntl.h>
+#include <cstring>
+#include <unistd.h>
+#include <dpl/log/log.h>
+#include "ace_service_callbacks_api.h"
+#include "ocsp_service_callbacks_api.h"
+#include "popup_service_callbacks_api.h"
+#include "security_daemon_socket_config.h"
+#include "security_socket_service.h"
+
+#define MAX_LISTEN 5
+#define SIGNAL_TO_CLOSE SIGUSR1
+
+void SecuritySocketService::throwWithErrnoMessage(const std::string& specificInfo){
+    LogError(specificInfo << " : " << strerror(errno));
+    ThrowMsg(DPL::Exception, specificInfo << " : " << strerror(errno));
+}
+
+void SecuritySocketService::registerServiceCallback(const std::string &interfaceName,
+                                                    const std::string &methodName,
+                                                    socketServerCallback callbackMethod,
+                                                    securityCheck securityMethod){
+    if(NULL == callbackMethod){
+        LogError("Null callback");
+        ThrowMsg(DPL::Exception, "Null callback");
+    }
+    if(interfaceName.empty() || methodName.empty()){
+        LogError("Interface and method name cannot be empty");
+        ThrowMsg(DPL::Exception, "Empty interface or method name");
+    }
+
+    auto serviceCallbackPtr = std::make_shared<ServiceCallback>(ServiceCallback(callbackMethod, securityMethod));
+    m_callbackMap[interfaceName][methodName] = serviceCallbackPtr;
+}
+
+void SecuritySocketService::addClientSocket(int clientSocket){
+    std::lock_guard<std::mutex> guard(m_clientSocketListMutex);
+    m_clientSocketList.push_back(clientSocket);
+}
+
+void SecuritySocketService::removeClientSocket(int clientSocket){
+    std::lock_guard<std::mutex> guard(m_clientSocketListMutex);
+    m_clientSocketList.remove(clientSocket);
+}
+
+bool SecuritySocketService::popClientSocket(int * clientSocket){
+    std::lock_guard<std::mutex> guard(m_clientSocketListMutex);
+    if(m_clientSocketList.empty())
+        return false;
+    *clientSocket = m_clientSocketList.front();
+    m_clientSocketList.pop_front();
+    return true;
+}
+
+int SecuritySocketService::get_systemd_socket(std::string &path) {
+
+       int type = SOCK_STREAM;
+       int listening = 1;
+       size_t length = 0;
+       int fd = -1;
+       int n;
+
+       // Gets number of created by systemd file descriptors that represent open sockets.
+       n = sd_listen_fds(1);
+
+       // Check open sockets count (must be 1)
+       if (n != 1)
+               return -1;
+
+       // File descriptor calculation
+       fd = SD_LISTEN_FDS_START  + 0;
+
+       // File descriptor veryfication.
+       if (sd_is_socket_unix(fd, type, listening, path.c_str(), length) > 0) {
+               activatedBySystemd = true;
+               return fd;
+       }
+
+       // No proper socket or error
+       return -1;
+}
+
+void SecuritySocketService::initialize(){
+
+    LogInfo("Initializing...");
+    m_serverAddress = WrtSecurity::SecurityDaemonSocketConfig::SERVER_ADDRESS();
+    m_signalToClose = SIGNAL_TO_CLOSE;
+
+    //registering Ace callbacks
+    registerServiceCallback(WrtSecurity::AceServerApi::INTERFACE_NAME(),
+                            WrtSecurity::AceServiceCallbacksApi::CHECK_ACCESS_METHOD_CALLBACK().first,
+                            WrtSecurity::AceServiceCallbacksApi::CHECK_ACCESS_METHOD_CALLBACK().second);
+
+    registerServiceCallback(WrtSecurity::AceServerApi::INTERFACE_NAME(),
+                            WrtSecurity::AceServiceCallbacksApi::CHECK_ACCESS_INSTALL_METHOD_CALLBACK().first,
+                            WrtSecurity::AceServiceCallbacksApi::CHECK_ACCESS_INSTALL_METHOD_CALLBACK().second);
+
+    registerServiceCallback(WrtSecurity::AceServerApi::INTERFACE_NAME(),
+                            WrtSecurity::AceServiceCallbacksApi::UPDATE_POLICY_METHOD_CALLBACK().first,
+                            WrtSecurity::AceServiceCallbacksApi::UPDATE_POLICY_METHOD_CALLBACK().second);
+    LogInfo("Registered Ace callbacks");
+
+    //registering Ocsp callbacks
+    registerServiceCallback(WrtSecurity::OcspServerApi::INTERFACE_NAME(),
+                            WrtSecurity::OcspServiceCallbacksApi::CHECK_ACCESS_METHOD_CALLBACK().first,
+                            WrtSecurity::OcspServiceCallbacksApi::CHECK_ACCESS_METHOD_CALLBACK().second);
+    LogInfo("Registered Ocsp callbacks");
+
+    //registering Popup callbacks
+    registerServiceCallback(WrtSecurity::PopupServerApi::INTERFACE_NAME(),
+                            WrtSecurity::PopupServiceCallbacksApi::VALIDATION_METHOD_CALLBACK().first,
+                            WrtSecurity::PopupServiceCallbacksApi::VALIDATION_METHOD_CALLBACK().second);
+    LogInfo("Registered Popup callbacks");
+
+    // Get systemd socket
+    activatedBySystemd = false;
+    m_listenFd = get_systemd_socket(m_serverAddress);
+    if (m_listenFd >= 0) {
+       LogInfo("Initialized");
+       return;
+    }
+
+    // Default socket initialization
+    if(-1 == (m_listenFd = socket(AF_UNIX, SOCK_STREAM, 0))){
+        throwWithErrnoMessage("socket()");
+    }
+    LogInfo("Server socket created");
+
+    //socket needs to be nonblocking, because read can block after select
+    int flags;
+    if (-1 == (flags = fcntl(m_listenFd, F_GETFL, 0)))
+        flags = 0;
+    if(-1 == (fcntl(m_listenFd, F_SETFL, flags | O_NONBLOCK))){
+        throwWithErrnoMessage("fcntl");
+    }
+
+    sockaddr_un server_address;
+    bzero(&server_address, sizeof(server_address));
+    server_address.sun_family = AF_UNIX;
+    strncpy(server_address.sun_path, m_serverAddress.c_str(), sizeof(server_address.sun_path) - 1);
+    unlink(server_address.sun_path);
+
+    mode_t socket_umask, original_umask;
+    socket_umask = 0;
+    original_umask = umask(socket_umask);
+
+    if(-1 == bind(m_listenFd, (struct sockaddr *)&server_address, SUN_LEN(&server_address))){
+        throwWithErrnoMessage("bind()");
+    }
+
+    umask(original_umask);
+
+    LogInfo("Initialized");
+}
+
+void SecuritySocketService::start(){
+
+    LogInfo("Starting...");
+    if(m_serverAddress.empty()){
+        LogError("Server not initialized");
+        ThrowMsg(DPL::Exception, "Server not initialized");
+    }
+
+    sigset_t sigset;
+    sigemptyset(&sigset);
+    if(-1 == sigaddset(&sigset, m_signalToClose)){
+        throwWithErrnoMessage("sigaddset()");
+    }
+    int returned_value;
+    if ((returned_value = pthread_sigmask(SIG_BLOCK, &sigset, NULL)) < 0) {
+        errno = returned_value;
+        throwWithErrnoMessage("pthread_sigmask()");
+    }
+
+    pthread_t mainThread;
+    if((returned_value = pthread_create(&mainThread, NULL, &serverThread, this)) < 0){
+        errno = returned_value;
+        throwWithErrnoMessage("pthread_create()");
+    }
+    m_mainThread = mainThread;
+
+    LogInfo("Started");
+}
+
+void * SecuritySocketService::serverThread(void * data){
+    pthread_detach(pthread_self());
+    SecuritySocketService &t = *static_cast<SecuritySocketService *>(data);
+    LogInfo("Running server main thread");
+    Try {
+        t.mainLoop();
+    } Catch (DPL::Exception) {
+        LogError("Socket server error. Exiting...");
+        return (void *)1;
+    }
+
+    return (void *)0;
+}
+
+
+void SecuritySocketService::mainLoop(){
+
+#ifdef ALL_LOGS
+       LogInfo("Server thread Main Loop : Started");
+#endif
+
+    if(!activatedBySystemd && listen(m_listenFd, MAX_LISTEN) == -1){
+        throwWithErrnoMessage("listen()");
+    }
+#ifdef ALL_LOGS
+       LogInfo("Server thread Main Loop : Listened something");
+#endif
+    //Settings to catch closing signal in select
+    int signal_fd;
+    sigset_t sigset;
+    if(-1 == (sigemptyset(&sigset))){
+        throwWithErrnoMessage("sigemptyset()");
+    }
+    if(-1 == (sigaddset(&sigset, m_signalToClose))) {
+        throwWithErrnoMessage("sigaddset()");
+    }
+    if((signal_fd = signalfd(-1, &sigset, 0)) < 0){
+        throwWithErrnoMessage("signalfd()");
+    }
+
+    //Setting descriptors for pselect
+    fd_set allset, rset;
+    int maxfd;
+    FD_ZERO(&allset);
+    FD_SET(m_listenFd, &allset);
+    FD_SET(signal_fd, &allset);
+    maxfd = (m_listenFd > signal_fd) ? (m_listenFd) : (signal_fd);
+    ++maxfd;
+    //this will block SIGPIPE for this thread and every thread created in it
+    //reason : from here on we don't won't to receive SIGPIPE on writing to closed socket
+    //instead of signal we want to receive error from write - hence blocking SIGPIPE
+    sigset_t set;
+    sigemptyset(&set);
+    sigaddset(&set, SIGPIPE);
+    pthread_sigmask(SIG_BLOCK, &set, NULL);
+#ifdef ALL_LOGS
+       LogInfo("Server thread Main Loop : Entering while loop.");
+#endif
+    while(1){
+        rset = allset;
+        if(-1 == pselect(maxfd, &rset, NULL, NULL, NULL, NULL)){
+            closeConnections();
+            throwWithErrnoMessage("pselect()");
+        }
+#ifdef ALL_LOGS
+               LogInfo("Server thread Main Loop : PSelected something.");
+#endif
+        if(FD_ISSET(signal_fd, &rset)){
+            LogInfo("Got signal to close");
+            signalfd_siginfo siginfo;
+            ssize_t res;
+            res = read(signal_fd, &siginfo, sizeof(siginfo));
+            if(res <= 0){
+                closeConnections();
+                throwWithErrnoMessage("read()");
+            }
+            if((size_t)res != sizeof(siginfo)){
+                closeConnections();
+                LogError("couldn't read whole siginfo");
+                ThrowMsg(DPL::Exception, "couldn't read whole siginfo");
+            }
+            if((int)siginfo.ssi_signo == m_signalToClose){
+                LogInfo("Server thread got signal to close");
+                closeConnections();
+                return;
+            } else {
+                LogInfo("Got not handled signal");
+            }
+        }
+        if(FD_ISSET(m_listenFd, &rset)){
+            int client_fd;
+#ifdef ALL_LOGS
+                       LogInfo("Server thread Main Loop : Client is there.");
+#endif
+            if(-1 == (client_fd = accept(m_listenFd, NULL, NULL))){
+                closeConnections();
+                throwWithErrnoMessage("accept()");
+            }
+            LogInfo("Got incoming connection");
+            Connection_Info * connection = new Connection_Info(client_fd, (void *)this);
+            int res;
+            pthread_t client_thread;
+            if((res = pthread_create(&client_thread, NULL, &connectionThread, connection)) < 0){
+                delete connection;
+                errno = res;
+                closeConnections();
+                throwWithErrnoMessage("pthread_create()");
+            }
+#ifdef ALL_LOGS
+                       LogInfo("Added incoming connection");
+#endif
+            addClientSocket(client_fd);
+        }
+    }
+}
+
+void * SecuritySocketService::connectionThread(void * data){
+    pthread_detach(pthread_self());
+    std::auto_ptr<Connection_Info> c (static_cast<Connection_Info *>(data));
+    SecuritySocketService &t = *static_cast<SecuritySocketService *>(c->data);
+#ifdef ALL_LOGS
+    LogInfo("Starting connection thread");
+#endif
+    Try {
+        t.connectionService(c->connfd);
+    } Catch (DPL::Exception){
+        LogError("Connection thread error : " << _rethrown_exception.DumpToString());
+        t.removeClientSocket(c->connfd);
+        close(c->connfd);
+        return (void*)1;
+    }
+#ifdef ALL_LOGS
+    LogInfo("Client serviced");
+#endif
+    return (void*)0;
+}
+
+void SecuritySocketService::connectionService(int fd){
+
+    SocketConnection connector = SocketConnection(fd);
+    std::string interfaceName, methodName;
+
+    Try {
+        connector.read(&interfaceName, &methodName);
+    } Catch (SocketConnection::Exception::SocketConnectionException){
+        LogError("Socket Connection read error");
+        ReThrowMsg(DPL::Exception, "Socket Connection read error");
+    }
+#ifdef ALL_LOGS
+    LogDebug("Got interface : " << interfaceName);
+    LogDebug("Got method : " << methodName);
+#endif
+    if( m_callbackMap.find(interfaceName) == m_callbackMap.end()){
+        LogError("Unknown interface : " << interfaceName);
+        ThrowMsg(DPL::Exception, "Unknown interface : " << interfaceName);
+    }
+
+    if(m_callbackMap[interfaceName].find(methodName) == m_callbackMap[interfaceName].end()){
+        LogError("Unknown method : " << methodName);
+        ThrowMsg(DPL::Exception, "Unknown method");
+    }
+
+    if(m_callbackMap[interfaceName][methodName]->securityCallback != NULL){
+        if(!m_callbackMap[interfaceName][methodName]->securityCallback(fd)){
+            LogError("Security check returned false");
+            ThrowMsg(DPL::Exception, "Security check returned false");
+        }
+    }
+#ifdef ALL_LOGS
+    LogInfo("Calling service");
+#endif
+    Try{
+        m_callbackMap[interfaceName][methodName]->serviceCallback(&connector);
+    } Catch (ServiceCallbackApi::Exception::ServiceCallbackException){
+        LogError("Service callback error");
+        ReThrowMsg(DPL::Exception, "Service callback error");
+    }
+#ifdef ALL_LOGS
+    LogInfo("Removing client");
+#endif
+    removeClientSocket(fd);
+    close(fd);
+#ifdef ALL_LOGS
+    LogInfo("Call served");
+#endif
+
+}
+
+void SecuritySocketService::stop(){
+    LogInfo("Stopping");
+    if(-1 == close(m_listenFd))
+        if(errno != ENOTCONN)
+            throwWithErrnoMessage("close()");
+    int returned_value;
+    if((returned_value = pthread_kill(m_mainThread, m_signalToClose)) < 0){
+        errno = returned_value;
+        throwWithErrnoMessage("pthread_kill()");
+    }
+    pthread_join(m_mainThread, NULL);
+
+    LogInfo("Stopped");
+}
+
+void SecuritySocketService::closeConnections(){
+
+    int clientSocket;
+    LogInfo("Closing client sockets");
+    while(popClientSocket(&clientSocket)){
+        if(-1 == close(clientSocket)){
+            LogError("close() : " << strerror(errno));
+        }
+    }
+
+    LogInfo("Connections closed");
+}
+
+void SecuritySocketService::deinitialize(){
+    m_serverAddress.clear();
+
+    LogInfo("Deinitialized");
+
+}
+
+#ifdef SOCKET_CONNECTION
+DAEMON_REGISTER_SERVICE_MODULE(SecuritySocketService)
+#endif
diff --git a/src/daemon/sockets/security_socket_service.h b/src/daemon/sockets/security_socket_service.h
new file mode 100644 (file)
index 0000000..852838d
--- /dev/null
@@ -0,0 +1,112 @@
+/*
+ * Copyright (c) 2012 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        security_socket_service.h
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       Header of socket server class
+ */
+
+#ifndef SECURITY_SOCKET_SERVICE_H_
+#define SECURITY_SOCKET_SERVICE_H_
+
+#include <map>
+#include <list>
+#include <memory>
+#include <mutex>
+#include <pthread.h>
+#include <security_daemon.h>
+#include <SocketConnection.h>
+#include <callback_api.h>
+
+class SecuritySocketService : public SecurityDaemon::DaemonService {
+
+private:
+  bool activatedBySystemd;
+  int get_systemd_socket(std::string &path);
+
+private:
+  virtual void initialize();
+  virtual void start();
+  virtual void stop();
+  virtual void deinitialize();
+
+
+private:
+
+    //Function for registering callback with given interface and method name and possibly security check callback
+    void registerServiceCallback(const std::string& interfaceName,
+                                 const std::string& methodName,
+                                 socketServerCallback serviceCallback,
+                                 securityCheck securityCallback = NULL);
+    //Thread function for server
+    static void * serverThread(void *);
+    //Main function for server
+    void mainLoop();
+    //Thread function for connection serving
+    static void * connectionThread(void *);
+    //Main function for connection serving
+    void connectionService(int fd);
+    //closing all connections
+    void closeConnections();
+    //logs an error and throws an exception with message containing errno message
+    void throwWithErrnoMessage(const std::string &specificInfo);
+
+    //concurrency safe methods for client socket list - add, remove and pop (with returned value)
+    void addClientSocket(int clientThread);
+    void removeClientSocket(int clientThread);
+    bool popClientSocket(int* clientThread);
+
+    //Address of socket server
+    std::string m_serverAddress;
+    //Signal used for informing threads to stop
+    int m_signalToClose;
+    //Socket for listening
+    int m_listenFd;
+    //Number of main thread
+    pthread_t m_mainThread;
+    //Numbers of all created threads for connections
+    std::list<int> m_clientSocketList;
+
+    //Thread list mutex
+    std::mutex m_clientSocketListMutex;
+
+    //Structure for callback maps
+    class ServiceCallback
+    {
+    public:
+        ServiceCallback(socketServerCallback ser, securityCheck sec) : serviceCallback(ser), securityCallback(sec){}
+        socketServerCallback serviceCallback;
+        securityCheck securityCallback;
+    };
+
+    typedef std::shared_ptr<ServiceCallback> ServiceCallbackPtr;
+    //Map for callback methods, key is a method name and value is a callback to method
+    typedef std::map<std::string, ServiceCallbackPtr> ServiceMethodCallbackMap;
+    //Map for interface methods, key is an interface name and value is a map of available methods with callbacks
+    std::map<std::string, ServiceMethodCallbackMap> m_callbackMap;
+
+    //Structure passed to connection thread
+    struct Connection_Info{
+        Connection_Info(int fd, void * data) : connfd(fd), data(data)
+        {}
+        int connfd;
+        void * data;
+    };
+
+};
+
+#endif /* SECURITY_SOCKET_SERVICE_H_ */
diff --git a/src/main.cpp b/src/main.cpp
new file mode 100644 (file)
index 0000000..608f939
--- /dev/null
@@ -0,0 +1,114 @@
+/*
+ * 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        main.cpp
+ * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
+ * @version     1.0
+ * @brief       This is main routing for Security Daemon
+ */
+
+#include <systemd/sd-daemon.h>
+#include <dpl/log/log.h>
+#include <dpl/single_instance.h>
+#include <privacy_manager_daemon.h>
+
+#include "security_daemon.h"
+
+#include <pthread.h>
+#include <glib.h>
+#include <Ecore.h>
+
+static const std::string DAEMON_INSTANCE_UUID =
+    "5ebf3f24-dad6-4a27-88b4-df7970efe7a9";
+
+static Ecore_Event_Handler *g_exitHandler;
+static Eina_Bool exitHandler(void */*data*/, int /*type*/, void */*event*/)
+{
+    privacy_manager_daemon_stop();
+    privacy_manager_daemon_shutdown();
+
+    auto& daemon = SecurityDaemonSingleton::Instance();
+    daemon.shutdown();                   
+
+    ecore_event_handler_del(g_exitHandler);
+
+    ecore_main_loop_quit();
+
+    return ECORE_CALLBACK_CANCEL;
+}      
+
+static Eina_Bool startHandler(void */*data*/)
+{
+    int retVal;
+       auto& daemon = SecurityDaemonSingleton::Instance();
+       
+       privacy_manager_daemon_initialize();
+
+       privacy_manager_daemon_start();
+       
+       int argc = 0;
+       char* argv = NULL;
+
+       daemon.initialize(argc, &argv);
+    retVal = daemon.execute();
+    if (retVal != 0)
+    {
+        LogError("Failed to execute daemon.");
+        ecore_main_loop_quit();
+        
+        return ECORE_CALLBACK_CANCEL;
+    }
+
+       // Notification to systemd
+       sd_notify(0, "READY=1");
+
+    return ECORE_CALLBACK_CANCEL;
+}
+
+int main(int argc, char* argv[])
+{
+       DPL::SingleInstance instance;
+       
+       Try {
+               if (!instance.TryLock(DAEMON_INSTANCE_UUID)) {
+                       LogError("Security Daemon is already running");
+                       return -1;
+               }
+    } Catch (DPL::SingleInstance::Exception::LockError) {
+        LogError("Failed to lock/unlock Security Daemon instance.");
+        return -1;
+    }
+       
+    if (!ecore_init())
+    {
+        LogError("Ecore cannot be initialized");
+        return -1;
+    }
+       
+    ecore_timer_add(0.1, &startHandler, NULL);
+    g_exitHandler = ecore_event_handler_add(ECORE_EVENT_SIGNAL_EXIT, &exitHandler, NULL);
+    ecore_main_loop_begin();
+    ecore_shutdown();
+
+       Try {
+           instance.Release();
+    } Catch (DPL::SingleInstance::Exception::LockError) {
+        LogError("Failed to release Security Daemon instance.");
+        return -1;
+    }
+
+    return 0;
+}
diff --git a/src/services/ace/ace_server_api.h b/src/services/ace/ace_server_api.h
new file mode 100644 (file)
index 0000000..e327e31
--- /dev/null
@@ -0,0 +1,65 @@
+/*
+ * 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        ace_server_api.h
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       This file contains definitions of ACE server interface name & methods.
+ */
+
+#ifndef WRT_SRC_RPC_SECURITY_DAEMON_ACE_SERVER_API_H_
+#define WRT_SRC_RPC_SECURITY_DAEMON_ACE_SERVER_API_H_
+
+#include<string>
+
+
+namespace WrtSecurity{
+namespace AceServerApi{
+
+    // DBus interface names
+    inline const std::string INTERFACE_NAME()
+    {
+        return "org.tizen.AceCheckAccessInterface";
+    }
+
+    // IN string subject
+    // IN string resource
+    // IN vector<string> function param names
+    // IN vector<string> function param values
+    // OUT int allow, deny, popup type
+    inline const std::string CHECK_ACCESS_METHOD()
+    {
+        return "check_access";
+    }
+
+    // IN string subject
+    // IN string resource
+    // OUT int allow, deny, popup type
+    inline const std::string CHECK_ACCESS_INSTALL_METHOD()
+    {
+        return "check_access_install";
+    }
+
+    // Policy update trigger
+    inline const std::string UPDATE_POLICY_METHOD()
+    {
+        return "update_policy";
+    }
+};
+};
+
+
+#endif // WRT_SRC_RPC_SECURITY_DAEMON_ACE_SERVER_API_H_
diff --git a/src/services/ace/ace_service.cpp b/src/services/ace/ace_service.cpp
new file mode 100644 (file)
index 0000000..15227f4
--- /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        ace_service.cpp
+ * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
+ * @version     1.0
+ * @brief       This is implementation file of AceService service
+ */
+
+#include <dpl/log/log.h>
+#include <security_controller.h>
+
+#include "security_daemon.h"
+
+namespace AceService
+{
+
+class AceService : public SecurityDaemon::DaemonService
+{
+  private:
+    virtual void initialize()
+    {
+        LogDebug("AceService initializing");
+
+        SecurityControllerSingleton::Instance().Touch();
+        SecurityControllerSingleton::Instance().SwitchToThread(NULL);
+
+        CONTROLLER_POST_SYNC_EVENT(
+            SecurityController,
+            SecurityControllerEvents::InitializeSyncEvent());
+    }
+
+    virtual void start()
+    {
+        LogDebug("Starting AceService");
+    }
+
+    virtual void stop()
+    {
+        LogDebug("Stopping AceService");
+    }
+
+    virtual void deinitialize()
+    {
+        LogDebug("AceService deinitializing");
+        SecurityControllerSingleton::Instance().SwitchToThread(NULL);
+        //this is direct call inside
+        CONTROLLER_POST_SYNC_EVENT(
+            SecurityController,
+            SecurityControllerEvents::TerminateSyncEvent());
+    }
+
+};
+
+DAEMON_REGISTER_SERVICE_MODULE(AceService)
+
+}//namespace AceService
diff --git a/src/services/ace/dbus/ace_server_dbus_interface.cpp b/src/services/ace/dbus/ace_server_dbus_interface.cpp
new file mode 100644 (file)
index 0000000..e77b9f9
--- /dev/null
@@ -0,0 +1,144 @@
+/*
+ * 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        ace_service_dbus_interface.cpp
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       Implementation of ACE server API.
+ */
+#include <dpl/foreach.h>
+#include <vector>
+#include <string>
+#include "ace_server_dbus_interface.h"
+#include <dpl/dbus/dbus_server_deserialization.h>
+#include <dpl/dbus/dbus_server_serialization.h>
+
+#include <ace/Request.h>
+#include <ace/PolicyResult.h>
+#include <security_controller.h>
+#include <attribute_facade.h>
+
+
+namespace RPC {
+
+void AceServerDBusInterface::onMethodCall(const gchar* methodName,
+                          GVariant* parameters,
+                          GDBusMethodInvocation* invocation)
+{
+    using namespace WrtSecurity;
+
+    if (0 == g_strcmp0(methodName, AceServerApi::ECHO_METHOD().c_str()))
+    {
+        std::string str;
+        DPL::DBus::ServerDeserialization::deserialize(parameters, &str);
+        g_dbus_method_invocation_return_value(invocation,
+                DPL::DBus::ServerSerialization::serialize(str));
+    } else if (0 == g_strcmp0(methodName,
+                              AceServerApi::CHECK_ACCESS_METHOD().c_str()))
+    {
+        int widgetHandle;
+        std::string subject, resource, sessionId;
+        std::vector<std::string> paramNames, paramValues;
+        if (!DPL::DBus::ServerDeserialization::deserialize(parameters,
+                                                      &widgetHandle,
+                                                      &subject,
+                                                      &resource,
+                                                      &paramNames,
+                                                      &paramValues,
+                                                      &sessionId)) {
+            g_dbus_method_invocation_return_dbus_error(
+                          invocation,
+                          "org.tizen.AceCheckAccessInterface.UnknownError",
+                          "Error in deserializing input parameters");
+            return;
+        }
+        if (paramNames.size() != paramValues.size()) {
+            g_dbus_method_invocation_return_dbus_error(
+                      invocation,
+                      "org.tizen.AceCheckAccessInterface.UnknownError",
+                      "Varying sizes of parameter names and parameter values");
+            return;
+        }
+        LogDebug("We got subject: " << subject);
+        LogDebug("We got resource: " << resource);
+
+        FunctionParamImpl params;
+        for (size_t i = 0; i < paramNames.size(); ++i) {
+            params.addAttribute(paramNames[i], paramValues[i]);
+        }
+
+        Request request(widgetHandle,
+                        WidgetExecutionPhase_Invoke,
+                        &params);
+        request.addDeviceCapability(resource);
+
+        PolicyResult result(PolicyEffect::DENY);
+        CONTROLLER_POST_SYNC_EVENT(
+            SecurityController,
+            SecurityControllerEvents::CheckRuntimeCallSyncEvent(
+                &result,
+                &request,
+                sessionId));
+
+        int response = PolicyResult::serialize(result);
+        g_dbus_method_invocation_return_value(invocation,
+                DPL::DBus::ServerSerialization::serialize(response));
+    } else if (0 == g_strcmp0(methodName,
+            AceServerApi::CHECK_ACCESS_INSTALL_METHOD().c_str()))
+    {
+        int widgetHandle;
+        std::string resource;
+        if (!DPL::DBus::ServerDeserialization::deserialize(parameters,
+                                            &widgetHandle,
+                                            &resource)) {
+            g_dbus_method_invocation_return_dbus_error(
+                    invocation,
+                    "org.tizen.AceCheckAccessInterface.UnknownError",
+                    "Error in deserializing input parameters");
+            return;
+        }
+        LogDebug("We got handle: " << widgetHandle);
+        LogDebug("We got resource: " << resource);
+
+        Request request(widgetHandle,
+              WidgetExecutionPhase_WidgetInstall);
+        request.addDeviceCapability(resource);
+
+        PolicyResult result(PolicyEffect::DENY);
+        CONTROLLER_POST_SYNC_EVENT(
+        SecurityController,
+        SecurityControllerEvents::CheckFunctionCallSyncEvent(
+             &result,
+             &request));
+
+        int response = PolicyResult::serialize(result);
+        g_dbus_method_invocation_return_value(invocation,
+                DPL::DBus::ServerSerialization::serialize(response));
+    } else if (0 == g_strcmp0(methodName,
+            AceServerApi::UPDATE_POLICY_METHOD().c_str()))
+    {
+        LogDebug("Policy update DBus message received");
+        CONTROLLER_POST_SYNC_EVENT(
+                    SecurityController,
+                    SecurityControllerEvents::UpdatePolicySyncEvent());
+        g_dbus_method_invocation_return_value(invocation, NULL);
+    } else {
+        // invalid method name
+        g_dbus_method_invocation_return_value(invocation, NULL);
+    }
+}
+
+} // namespace RPC
diff --git a/src/services/ace/dbus/ace_server_dbus_interface.h b/src/services/ace/dbus/ace_server_dbus_interface.h
new file mode 100644 (file)
index 0000000..d5957cb
--- /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        ace_service_dbus_interface.h
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       Class that handles ACE server API.
+ */
+#ifndef WRT_SRC_RPC_SECURITY_DAEMON_ACE_SERVER_DBUS_INTERFACE_H_
+#define WRT_SRC_RPC_SECURITY_DAEMON_ACE_SERVER_DBUS_INTERFACE_H_
+
+#include <dpl/dbus/dbus_interface_dispatcher.h>
+#include "api/ace_server_dbus_api.h"
+
+namespace RPC {
+
+class AceServerDBusInterface : public DPL::DBus::InterfaceDispatcher {
+  public:
+    AceServerDBusInterface():
+        DPL::DBus::InterfaceDispatcher(WrtSecurity::AceServerApi::INTERFACE_NAME())
+    {
+        using namespace WrtSecurity;
+
+        setXmlSignature("<node>"
+            "  <interface name='" + AceServerApi::INTERFACE_NAME() + "'>"
+            "    <method name='" + AceServerApi::ECHO_METHOD() + "'>"
+            "      <arg type='s' name='input' direction='in'/>"
+            "      <arg type='s' name='output' direction='out'/>"
+            "    </method>"
+            "    <method name='" + AceServerApi::CHECK_ACCESS_METHOD() + "'>"
+            "      <arg type='i' name='handle' direction='in'/>"
+            "      <arg type='s' name='subject' direction='in'/>"
+            "      <arg type='s' name='resource' direction='in'/>"
+            "      <arg type='as' name='parameter names' direction='in'/>"
+            "      <arg type='as' name='parameter values' direction='in'/>"
+            "      <arg type='s' name='session' direction='in'/>"
+            "      <arg type='i' name='output' direction='out'/>"
+            "    </method>"
+            "    <method name='" + AceServerApi::CHECK_ACCESS_INSTALL_METHOD() + "'>"
+            "      <arg type='i' name='handle' direction='in'/>"
+            "      <arg type='s' name='resource' direction='in'/>"
+            "      <arg type='i' name='output' direction='out'/>"
+            "    </method>"
+            "    <method name='" + AceServerApi::UPDATE_POLICY_METHOD() + "'>"
+            "    </method>"
+            "  </interface>"
+            "</node>");
+    }
+
+    virtual ~AceServerDBusInterface()
+    {}
+
+    virtual void onMethodCall(const gchar* methodName,
+                              GVariant* parameters,
+                              GDBusMethodInvocation* invocation);
+};
+
+} // namespace RPC
+
+#endif // WRT_SRC_RPC_SECURITY_DAEMON_ACE_SERVER_DBUS_INTERFACE_H_
diff --git a/src/services/ace/dbus/api/ace_server_dbus_api.h b/src/services/ace/dbus/api/ace_server_dbus_api.h
new file mode 100644 (file)
index 0000000..9db4f05
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ * 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        ace_server_api.h
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This file contains definitions ACE server interface & methods specifically needed by DBUS.
+ */
+#ifndef WRT_SRC_RPC_SECURITY_DAEMON_ACE_SERVER_DBUS_API_H_
+#define WRT_SRC_RPC_SECURITY_DAEMON_ACE_SERVER_DBUS_API_H_
+
+#include "ace_server_api.h"
+#include<string>
+
+namespace WrtSecurity{
+namespace AceServerApi{
+
+    // RPC test function
+    // IN std::string
+    // OUT std::string
+    inline const std::string ECHO_METHOD()
+    {
+        return "echo";
+    }
+};
+};
+
+
+#endif // WRT_SRC_RPC_SECURITY_DAEMON_ACE_SERVER_DBUS_API_H_
diff --git a/src/services/ace/logic/acf_consts.h b/src/services/ace/logic/acf_consts.h
new file mode 100644 (file)
index 0000000..93ecfae
--- /dev/null
@@ -0,0 +1,41 @@
+/*
+ * 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.
+ */
+/*
+ * This file contain consts for Signing Template and Policy Manager
+ * This values will be used to specified and identified algorithms in xml policy documents.
+ * Its consistent with BONDI 1.0 released requirements
+ *
+ * NOTE: This values should be verified when ACF will be updated to the latest version of BONDI requirements
+ * This values comes from widget digital signature 1.0 - required version of this doc is very important
+ *
+ **/
+
+#ifndef ACF_CONSTS_TYPES_H
+#define ACF_CONSTS_TYPES_H
+
+//Digest Algorithms
+extern const char* DIGEST_ALG_SHA256;
+
+//Canonicalization Algorithms
+extern const char* CANONICAL_ALG_C14N;
+
+//Signature Algorithms
+extern const char* SIGNATURE_ALG_RSA_with_SHA256;
+extern const char* SIGNATURE_ALG_DSA_with_SHA1;
+extern const char* SIGNATURE_ALG_ECDSA_with_SHA256;
+
+#endif
+
diff --git a/src/services/ace/logic/attribute_facade.cpp b/src/services/ace/logic/attribute_facade.cpp
new file mode 100644 (file)
index 0000000..3b1aeac
--- /dev/null
@@ -0,0 +1,701 @@
+/*
+ * 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.
+ */
+/**
+ *
+ * This file contains classes that implement WRT_INTERFACE.h interfaces,
+ * so that ACE could access  WRT specific and other information during
+ * the decision making.
+ *
+ * @file    attribute_.cpp
+ * @author  Jaroslaw Osmanski (j.osmanski@samsung.com)
+ * @author  Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @author  Ming Jin(ming79.jin@samsung.com)
+ * @version 1.0
+ * @brief   Implementation file for attributes obtaining.
+ */
+
+#include <dpl/exception.h>
+#include <sstream>
+#include <algorithm>
+#include <list>
+#include <string>
+#include <sstream>
+#include <stdexcept>
+#include <map>
+#include <cstdlib>
+#include <ace-dao-ro/AceDAOReadOnly.h>
+#include <ace/WRT_INTERFACE.h>
+#include <map>
+#include <dpl/log/log.h>
+#include <dpl/foreach.h>
+#include <attribute_facade.h>
+#include <ace/Request.h>
+#include <simple_roaming_agent.h>
+
+namespace // anonymous
+{
+typedef std::list<std::string> AttributeHandlerResponse;
+
+typedef AttributeHandlerResponse (*AttributeHandler)(
+    const WidgetExecutionPhase &phase,
+    const WidgetHandle &widgetHandle);
+typedef AttributeHandlerResponse (*ResourceAttributeHandler)(
+    const WidgetExecutionPhase &phase,
+    const WidgetHandle &widgetHandle,
+    const Request &request);
+
+AttributeHandlerResponse AttributeClassHandler(const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle & /*widgetHandle*/)
+{
+    AttributeHandlerResponse response;
+    response.push_back("widget");
+    return response;
+}
+
+AttributeHandlerResponse AttributeInstallUriHandler(
+        const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle &widgetHandle)
+{
+    AttributeHandlerResponse response;
+    std::string value = AceDB::AceDAOReadOnly::getShareHref(widgetHandle);
+    if(!value.empty())
+        response.push_back(value);
+    return response;
+}
+
+AttributeHandlerResponse AttributeVersionHandler(const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle &widgetHandle)
+{
+    AttributeHandlerResponse response;
+
+    std::string value = AceDB::AceDAOReadOnly::getVersion(widgetHandle);
+
+    if (!value.empty()) {
+        response.push_back(value);
+    }
+
+    return response;
+}
+
+AttributeHandlerResponse AttributeDistributorKeyCnHandler(
+        const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle &widgetHandle)
+{
+    AttributeHandlerResponse response;
+    response = AceDB::AceDAOReadOnly::getKeyCommonNameList(widgetHandle,
+        AceDB::WidgetCertificateData::DISTRIBUTOR, AceDB::WidgetCertificateData::ENDENTITY);
+    return response;
+}
+
+AttributeHandlerResponse AttributeDistributorKeyFingerprintHandler(
+        const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle &widgetHandle)
+{
+    AttributeHandlerResponse response;
+    response = AceDB::AceDAOReadOnly::getKeyFingerprints(widgetHandle,
+        AceDB::WidgetCertificateData::DISTRIBUTOR, AceDB::WidgetCertificateData::ENDENTITY);
+    return response;
+}
+
+AttributeHandlerResponse AttributeDistributorKeyRootCnHandler(
+        const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle &widgetHandle)
+{
+    AttributeHandlerResponse response;
+    response = AceDB::AceDAOReadOnly::getKeyCommonNameList(widgetHandle,
+        AceDB::WidgetCertificateData::DISTRIBUTOR, AceDB::WidgetCertificateData::ROOT);
+    return response;
+}
+
+AttributeHandlerResponse AttributeDistributorKeyRootFingerprintHandler(
+        const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle &widgetHandle)
+{
+    AttributeHandlerResponse response;
+    response = AceDB::AceDAOReadOnly::getKeyFingerprints(widgetHandle,
+        AceDB::WidgetCertificateData::DISTRIBUTOR, AceDB::WidgetCertificateData::ROOT);
+    return response;
+}
+
+AttributeHandlerResponse AttributeAuthorKeyCnHandler(
+        const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle &widgetHandle)
+{
+    AttributeHandlerResponse response;
+    response = AceDB::AceDAOReadOnly::getKeyCommonNameList(widgetHandle,
+        AceDB::WidgetCertificateData::AUTHOR, AceDB::WidgetCertificateData::ENDENTITY);
+    return response;
+}
+
+AttributeHandlerResponse AttributeAuthorKeyFingerprintHandler(
+        const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle &widgetHandle)
+{
+    AttributeHandlerResponse response;
+    response = AceDB::AceDAOReadOnly::getKeyFingerprints(widgetHandle,
+        AceDB::WidgetCertificateData::AUTHOR, AceDB::WidgetCertificateData::ENDENTITY);
+    return response;
+}
+
+AttributeHandlerResponse AttributeAuthorKeyRootCnHandler(
+        const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle &widgetHandle)
+{
+    AttributeHandlerResponse response;
+    response = AceDB::AceDAOReadOnly::getKeyCommonNameList(widgetHandle,
+        AceDB::WidgetCertificateData::AUTHOR, AceDB::WidgetCertificateData::ROOT);
+    return response;
+}
+
+AttributeHandlerResponse AttributeAuthorKeyRootFingerprintHandler(
+        const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle &widgetHandle)
+{
+    AttributeHandlerResponse response;
+    response = AceDB::AceDAOReadOnly::getKeyFingerprints(widgetHandle,
+        AceDB::WidgetCertificateData::AUTHOR, AceDB::WidgetCertificateData::ROOT);
+    return response;
+}
+
+AttributeHandlerResponse AttributeNetworkAccessUriHandler(
+        const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle & /*widgetHandle*/)
+{
+    AttributeHandlerResponse response;
+    return response;
+}
+
+AttributeHandlerResponse AttributeIdHandler(const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle &widgetHandle)
+{
+    AttributeHandlerResponse response;
+
+    std::string wGUID = AceDB::AceDAOReadOnly::getGUID(widgetHandle);
+
+    if (!wGUID.empty()) {
+        response.push_back(wGUID);
+    }
+    return response;
+}
+
+AttributeHandlerResponse AttributeAuthorNameHandler(
+        const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle &widgetHandle)
+{
+    AttributeHandlerResponse response;
+
+    std::string value = AceDB::AceDAOReadOnly::getAuthorName(widgetHandle);
+
+    if (!value.empty()) {
+        response.push_back(value);
+    }
+
+    return response;
+}
+
+AttributeHandlerResponse AttributeRoamingHandler(
+        const WidgetExecutionPhase &phase,
+        const WidgetHandle & /*widgetHandle*/)
+{
+    AttributeHandlerResponse response;
+
+    if (WidgetExecutionPhase_WidgetInstall == phase) {
+        // TODO undetermind value
+        response.push_back(std::string(""));
+    } else if (SimpleRoamingAgentSingleton::Instance().IsRoamingOn()) {
+        response.push_back(std::string("true"));
+    } else {
+        response.push_back(std::string("false"));
+    }
+
+    return response;
+}
+
+AttributeHandlerResponse AttributeBearerTypeHandler(
+        const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle & /*widgetHandle*/)
+{
+    AttributeHandlerResponse response;
+
+    std::string bearerName = "undefined-bearer-name";
+
+    if (bearerName.empty()) {
+        LogWarning("Bearer-type is NOT SET or empty");
+    } else {
+        response.push_back(bearerName);
+    }
+
+    return response;
+}
+
+struct AttributeHandlerContext
+{
+    std::string name;
+    WidgetExecutionPhase allowedPhaseMask;
+    AttributeHandler handler;
+};
+
+// Private masks
+const WidgetExecutionPhase WidgetExecutionPhase_All =
+    static_cast<WidgetExecutionPhase>(
+        WidgetExecutionPhase_WidgetInstall |
+        WidgetExecutionPhase_WidgetInstantiate |
+        WidgetExecutionPhase_WebkitBind |
+        WidgetExecutionPhase_Invoke);
+const WidgetExecutionPhase WidgetExecutionPhase_NoWidgetInstall =
+    static_cast<WidgetExecutionPhase>(
+        WidgetExecutionPhase_WidgetInstantiate |
+        WidgetExecutionPhase_WebkitBind |
+        WidgetExecutionPhase_Invoke);
+
+#define ALL_PHASE(name, handler) \
+    { # name, WidgetExecutionPhase_All, handler },
+
+#define NO_INSTALL(name, handler) \
+    { # name, WidgetExecutionPhase_NoWidgetInstall, handler },
+
+AttributeHandlerContext HANDLED_ATTRIBUTES_LIST[] = {
+    ALL_PHASE(Class, &AttributeClassHandler)
+    ALL_PHASE(install-uri, &AttributeInstallUriHandler)
+    ALL_PHASE(version, &AttributeVersionHandler)
+    ALL_PHASE(distributor-key-cn, &AttributeDistributorKeyCnHandler)
+    ALL_PHASE(distributor-key-fingerprint,
+              &AttributeDistributorKeyFingerprintHandler)
+    ALL_PHASE(distributor-key-root-cn,
+              &AttributeDistributorKeyRootCnHandler)
+    ALL_PHASE(distributor-key-root-fingerprint,
+              &AttributeDistributorKeyRootFingerprintHandler)
+    ALL_PHASE(author-key-cn, &AttributeAuthorKeyCnHandler)
+    ALL_PHASE(author-key-fingerprint, &AttributeAuthorKeyFingerprintHandler)
+    ALL_PHASE(author-key-root-cn, &AttributeAuthorKeyRootCnHandler)
+    ALL_PHASE(author-key-root-fingerprint,
+              &AttributeAuthorKeyRootFingerprintHandler)
+    ALL_PHASE(network-access-uri, &AttributeNetworkAccessUriHandler)
+    ALL_PHASE(id, &AttributeIdHandler)
+//    ALL_PHASE(name, &AttributeNameHandler)
+//    ALL_PHASE(widget-attr:name, &AttributeWidgetAttrNameHandler)
+    ALL_PHASE(author-name, &AttributeAuthorNameHandler)
+    /* Enviroment  attributes*/
+//    NO_INSTALL(roaming, &AttributeRoamingHandler)
+//    NO_INSTALL(bearer-type, &AttributeBearerTypeHandler)
+};
+
+#undef ALL_PHASE
+#undef NO_INSTALL
+
+const size_t HANDLED_ATTRIBUTES_LIST_COUNT =
+    sizeof(HANDLED_ATTRIBUTES_LIST) / sizeof(HANDLED_ATTRIBUTES_LIST[0]);
+
+template<class T>
+class lambdaCollectionPusher
+{
+  public:
+    std::list<T>& m_collection;
+    lambdaCollectionPusher(std::list<T>& collection) : m_collection(collection)
+    {
+    }
+    void operator()(const T& element) const
+    {
+        m_collection.push_back(element);
+    }
+};
+
+AttributeHandlerResponse AttributeDeviceCapHandler(const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle & /*widgetHandle*/,
+        const Request &request)
+{
+    AttributeHandlerResponse response;
+
+    Request::DeviceCapabilitySet capSet = request.getDeviceCapabilitySet();
+    LogDebug("device caps set contains");
+    FOREACH(dc, capSet)
+    {
+        LogDebug("-> " << *dc);
+    }
+
+    std::for_each(
+        capSet.begin(),
+        capSet.end(),
+        lambdaCollectionPusher<std::string>(response));
+
+    return response;
+}
+
+//class lambdaFeatureEquality :
+//    public std::binary_function<FeatureHandle, int, bool>
+//{
+//  public:
+//    bool operator()(const FeatureHandle& wFeature,
+//            const int& resurceId) const
+//    {
+//        return wFeature == resurceId;
+//    }
+//};
+//
+//class lambdaPushFeatureName :
+//    public std::binary_function<WidgetFeature, AttributeHandlerResponse, void>
+//{
+//    void operator()(const WidgetFeature& wFeature,
+//            AttributeHandlerResponse& response) const
+//    {
+//        response.push_back(DPL::ToUTF8String(wFeature.name));
+//    }
+//};
+
+AttributeHandlerResponse AttributeApiFeatureHandler(
+        const WidgetExecutionPhase & /* phase */,
+        const WidgetHandle & /* widgetHandle */,
+        const Request & /* request */)
+{
+    LogDebug("WAC 2.0 does not support api-feature and resource-id in policy.");
+    AttributeHandlerResponse response;
+    return response;
+}
+
+AttributeHandlerResponse AttributeFeatureInstallUriHandler(
+        const WidgetExecutionPhase & /* phase */,
+        const WidgetHandle & /* widgetHandle */,
+        const Request & /* request */)
+{
+    LogDebug("WAC 2.0 does not support feature-install-uri is policy!");
+    AttributeHandlerResponse response;
+    return response;
+}
+
+AttributeHandlerResponse AttributeFeatureFeatureKeyCnHandler(
+        const WidgetExecutionPhase & /* phase */,
+        const WidgetHandle & /* widgetHandle */,
+        const Request & /* request */)
+{
+    LogDebug("WAC 2.0 does not support feature-key-cn is policy!");
+    AttributeHandlerResponse response;
+    return response;
+}
+
+AttributeHandlerResponse AttributeFeatureKeyRootCnHandler(
+        const WidgetExecutionPhase & /* phase */,
+        const WidgetHandle & /* widgetHandle */,
+        const Request & /* request */)
+{
+    LogDebug("WAC 2.0 does not support feature-key-root-cn is policy!");
+    AttributeHandlerResponse response;
+    return response;
+}
+
+AttributeHandlerResponse AttributeFeatureKeyRootFingerprintHandler(
+        const WidgetExecutionPhase & /* phase */,
+        const WidgetHandle & /* widgetHandle */,
+        const Request & /* request */)
+{
+    LogDebug("WAC 2.0 does not support"
+        " feature-key-root-fingerprint is policy!");
+    AttributeHandlerResponse response;
+    return response;
+}
+
+struct ResourceAttributeHandlerContext
+{
+    std::string name;
+    WidgetExecutionPhase allowedPhaseMask;
+    ResourceAttributeHandler handler;
+};
+
+#define ALL_PHASE(name, handler) \
+    { # name, WidgetExecutionPhase_All, handler },
+
+ResourceAttributeHandlerContext HANDLED_RESOURCE_ATTRIBUTES_LIST[] = {
+    ALL_PHASE(device-cap, &AttributeDeviceCapHandler)
+    ALL_PHASE(api-feature, &AttributeApiFeatureHandler)
+    // For compatiblity with older policies we tread resource-id
+    // identically as api-feature
+    ALL_PHASE(resource-id, &AttributeApiFeatureHandler)
+
+    ALL_PHASE(feature-install-uri, &AttributeFeatureInstallUriHandler)
+    ALL_PHASE(feature-key-cn, &AttributeFeatureFeatureKeyCnHandler)
+    ALL_PHASE(feature-key-root-cn, &AttributeFeatureKeyRootCnHandler)
+    ALL_PHASE(feature-key-root-fingerprint,
+              &AttributeFeatureKeyRootFingerprintHandler)
+};
+
+#undef ALL_PHASE
+
+const size_t HANDLED_RESOURCE_ATTRIBUTES_LIST_COUNT =
+    sizeof(HANDLED_RESOURCE_ATTRIBUTES_LIST) /
+    sizeof(HANDLED_RESOURCE_ATTRIBUTES_LIST[0]);
+} // namespace anonymous
+
+/*
+ * class WebRuntimeImpl
+ */
+int WebRuntimeImpl::getAttributesValuesLoop(const Request &request,
+        std::list<ATTRIBUTE>* attributes,
+        WidgetExecutionPhase executionPhase)
+{
+    WidgetHandle widgetHandle = request.getWidgetHandle();
+
+    FOREACH(itr, *attributes)
+    {
+        // Get attribute name
+        std::string attribute = *itr->first;
+
+        // Search for attribute handler
+        bool attributeFound = false;
+
+        for (size_t i = 0; i < HANDLED_ATTRIBUTES_LIST_COUNT; ++i) {
+            if (HANDLED_ATTRIBUTES_LIST[i].name == attribute) {
+                // Check if execution phase is valid
+                if ((executionPhase &
+                     HANDLED_ATTRIBUTES_LIST[i].allowedPhaseMask) == 0) {
+                    // Attribute found, but execution state
+                    // forbids to execute handler
+                    LogWarning(
+                        "Request for attribute: '" <<
+                        attribute << "' which is supported " <<
+                        "but forbidden at widget execution phase: "
+                        <<
+                        executionPhase);
+            } else {
+                // Execution phase allows handler
+                AttributeHandlerResponse attributeResponse =
+                    (*HANDLED_ATTRIBUTES_LIST[i].handler)(
+                        executionPhase,
+                            widgetHandle);
+                    std::copy(attributeResponse.begin(),
+                              attributeResponse.end(),
+                              std::back_inserter(*itr->second));
+                }
+
+                attributeFound = true;
+                break;
+            }
+        }
+
+        if (!attributeFound) {
+            LogWarning("Request for attribute: '" <<
+                       attribute << "' which is not supported");
+        }
+    }
+
+    return 0;
+}
+
+int WebRuntimeImpl::getAttributesValues(const Request &request,
+        std::list<ATTRIBUTE>* attributes)
+{
+    // Get current execution state
+    WidgetExecutionPhase executionPhase =
+        request.getExecutionPhase();
+
+    return getAttributesValuesLoop(request, attributes, executionPhase);
+}
+
+std::string WebRuntimeImpl::getSessionId(const Request & /* request */)
+{
+    std::string result;
+    LogError("Not implemented!");
+    return result;
+}
+
+WebRuntimeImpl::WebRuntimeImpl()
+{
+}
+
+/*
+ * class ResourceInformationImpl
+ */
+
+int ResourceInformationImpl::getAttributesValuesLoop(const Request &request,
+        std::list<ATTRIBUTE>* attributes,
+        WidgetExecutionPhase executionPhase)
+{
+    // Currently, we assume widgets have internal representation of integer IDs
+    WidgetHandle widgetHandle = request.getWidgetHandle();
+    //TODO add resource id string analyzys
+    FOREACH(itr, *attributes)
+    {
+        // Get attribute name
+        std::string attribute = *itr->first;
+        LogDebug("getting attribute value for: " << attribute);
+        FOREACH(aaa, *itr->second)
+        {
+            LogDebug("its value is: " << *aaa);
+        }
+
+        // Search for attribute handler
+        bool attributeFound = false;
+
+        for (size_t i = 0; i < HANDLED_RESOURCE_ATTRIBUTES_LIST_COUNT; ++i) {
+            if (HANDLED_RESOURCE_ATTRIBUTES_LIST[i].name == attribute) {
+                // Check if execution phase is valid
+                if ((executionPhase &
+                     HANDLED_RESOURCE_ATTRIBUTES_LIST[i].allowedPhaseMask) ==
+                    0) {
+                    // Attribute found, but execution state
+                    // forbids to execute handler
+                    LogDebug(
+                        "Request for attribute: '" <<
+                        attribute <<
+                        "' which is supported but forbidden " <<
+                        "at widget execution phase: " << executionPhase);
+                    itr->second = NULL;
+                } else {
+                    // Execution phase allows handler
+                    AttributeHandlerResponse attributeResponse =
+                        (*HANDLED_RESOURCE_ATTRIBUTES_LIST[i].handler)(
+                            executionPhase,
+                            widgetHandle,
+                            request);
+                        std::copy(attributeResponse.begin(),
+                            attributeResponse.end(),
+                            std::back_inserter(*itr->second));
+
+                    std::ostringstream attributeResponseFull;
+
+                    for (AttributeHandlerResponse::const_iterator
+                         it = attributeResponse.begin();
+                         it != attributeResponse.end(); ++it) {
+                        attributeResponseFull <<
+                        (it == attributeResponse.begin() ? "" : ", ") <<
+                        *it;
+                    }
+
+                    LogDebug("Attribute(" << attribute << ") = " <<
+                             attributeResponseFull.str());
+                }
+
+                attributeFound = true;
+                break;
+            }
+        }
+
+        if (!attributeFound) {
+            LogWarning("Request for attribute: '" << attribute <<
+                       "' which is not supported");
+        }
+    }
+    return 0;
+}
+
+int ResourceInformationImpl::getAttributesValues(const Request &request,
+        std::list<ATTRIBUTE>* attributes)
+{
+    // Get current execution state
+    WidgetExecutionPhase executionPhase =
+        request.getExecutionPhase();
+    return getAttributesValuesLoop(request, attributes, executionPhase);
+}
+
+ResourceInformationImpl::ResourceInformationImpl()
+{
+}
+
+/*
+ * class OperationSystemImpl
+ */
+
+int OperationSystemImpl::getAttributesValues(const Request &request,
+        std::list<ATTRIBUTE>* attributes)
+{
+    //FIXME:
+    //GetExecution name without widget name
+    WidgetExecutionPhase executionPhase =
+        request.getExecutionPhase();
+
+    FOREACH(itr, *attributes)
+    {
+        // Get attribute name
+        std::string attribute = *itr->first;
+
+        // Search for attribute handler
+        bool attributeFound = false;
+
+        for (size_t i = 0; i < HANDLED_ATTRIBUTES_LIST_COUNT; ++i) {
+            if (HANDLED_ATTRIBUTES_LIST[i].name == attribute) {
+                // Check if execution phase is valid
+                if ((executionPhase &
+                     HANDLED_ATTRIBUTES_LIST[i].allowedPhaseMask) == 0) {
+                    // Attribute found, but execution state forbids
+                    // to execute handler
+                    LogDebug("Request for attribute: '" << attribute <<
+                             "' which is supported but forbidden at " <<
+                             "widget execution phase: " << executionPhase);
+                    itr->second = NULL;
+                } else {
+                    // Execution phase allows handler
+                    AttributeHandlerResponse attributeResponse =
+                        (*HANDLED_ATTRIBUTES_LIST[i].handler)(
+                            executionPhase,
+                            0);
+                    std::copy(attributeResponse.begin(),
+                              attributeResponse.end(),
+                              std::back_inserter(*itr->second));
+
+                    std::ostringstream attributeResponseFull;
+
+                    for (AttributeHandlerResponse::const_iterator
+                        it = attributeResponse.begin();
+                        it != attributeResponse.end();
+                        ++it) {
+                        attributeResponseFull <<
+                        (it == attributeResponse.begin()
+                         ? "" : ", ") << *it;
+                    }
+
+                    LogDebug("Attribute(" << attribute <<
+                             ") = " << attributeResponseFull.str());
+                }
+
+                attributeFound = true;
+                break;
+            }
+        }
+
+        if (!attributeFound) {
+            LogWarning("Request for attribute: '" << attribute <<
+                       "' which is not supported");
+        }
+    }
+
+    return 0;
+}
+
+OperationSystemImpl::OperationSystemImpl()
+{
+}
+
+/*
+ * end of class OperationSystemImpl
+ */
+
+int FunctionParamImpl::getAttributesValues(const Request & /*request*/,
+        std::list<ATTRIBUTE> *attributes)
+{
+    FOREACH(iter, *attributes)
+    {
+        std::string attributeName = *(iter->first);
+
+        ParamMap::const_iterator i;
+        std::pair<ParamMap::const_iterator, ParamMap::const_iterator> jj =
+            paramMap.equal_range(attributeName);
+
+        for (i = jj.first; i != jj.second; ++i) {
+            iter->second->push_back(i->second);
+            LogDebug("Attribute: " << attributeName << " Value: " <<
+                     i->second);
+        }
+    }
+    return 0;
+}
diff --git a/src/services/ace/logic/attribute_facade.h b/src/services/ace/logic/attribute_facade.h
new file mode 100644 (file)
index 0000000..7b6898c
--- /dev/null
@@ -0,0 +1,98 @@
+/*
+ * 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    attribute_facade.h
+ * @author  Jaroslaw Osmanski (j.osmanski@samsung.com)
+ * @author  Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @version 1.0
+ * @brief   This file contains the declaration of WebRuntimeImpl,
+ *          ResourceInformationImpl, OperationSystemImpl
+ */
+
+#ifndef ATTRIBUTE_FACADE_H
+#define ATTRIBUTE_FACADE_H
+
+#include <string>
+#include <map>
+#include <vector>
+
+#include <ace/WRT_INTERFACE.h>
+
+class Request;
+
+class WebRuntimeImpl : public IWebRuntime
+{
+  public:
+    // Return current sessionId
+    int getAttributesValuesLoop(const Request &request,
+            std::list<ATTRIBUTE>* attributes,
+            WidgetExecutionPhase executionPhase);
+
+    int getAttributesValues(const Request &request,
+            std::list<ATTRIBUTE>* attributes);
+    virtual std::string getSessionId(const Request &request);
+    WebRuntimeImpl();
+};
+
+class ResourceInformationImpl : public IResourceInformation
+{
+  public:
+    int getAttributesValuesLoop(const Request &request,
+            std::list<ATTRIBUTE>* attributes,
+            WidgetExecutionPhase executionPhase);
+    int getAttributesValues(const Request &request,
+            std::list<ATTRIBUTE>* attributes);
+    ResourceInformationImpl();
+};
+
+class OperationSystemImpl : public IOperationSystem
+{
+  public:
+    /**
+     * gather and set attributes values for specified attribute name
+     * @param attributes is a list of pairs(
+     *   first:   pointer to attribute name
+     *   second: list of values for attribute (std::string)  -
+     *   its a list of string (BONDI requirement), but usually there
+     *   will be only one string
+     */
+    int getAttributesValues(const Request &request,
+            std::list<ATTRIBUTE>* attributes);
+    OperationSystemImpl();
+};
+
+class FunctionParamImpl : public IFunctionParam
+{
+  public:
+    virtual int getAttributesValues(const Request & /*request*/,
+            std::list<ATTRIBUTE> *attributes);
+    void addAttribute(const std::string &key,
+            const std::string &value)
+    {
+        paramMap.insert(make_pair(key, value));
+    }
+    virtual ~FunctionParamImpl()
+    {
+    }
+
+  private:
+    typedef std::multimap<std::string, std::string> ParamMap;
+    ParamMap paramMap;
+};
+
+typedef std::vector <FunctionParamImpl> FunctionParams;
+
+#endif //ATTRIBUTE_FACADE_H
diff --git a/src/services/ace/logic/security_controller.cpp b/src/services/ace/logic/security_controller.cpp
new file mode 100644 (file)
index 0000000..a0fe874
--- /dev/null
@@ -0,0 +1,94 @@
+/*
+ * 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.
+ */
+/**
+ * This class simply redirects the access requests to access control engine.
+ * The aim is to hide access control engine specific details from WRT modules.
+ * It also implements WRT_INTERFACE.h interfaces, so that ACE could access
+ * WRT specific and other information during the decision making.
+ *
+ * @file    security_controller.cpp
+ * @author  Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @author  Ming Jin(ming79.jin@samsung.com)
+ * @version 1.0
+ * @brief   Implementation file for security controller
+ */
+#include <security_controller.h>
+#include <ace/PolicyEnforcementPoint.h>
+#include <ace/WRT_INTERFACE.h>
+//#include <engine/PolicyEvaluatorFactory.h>
+//#include <logic/attribute_facade.h>
+#include <dpl/singleton_impl.h>
+#include <dpl/log/log.h>
+#include <security_logic.h>
+#include <security_caller.h>
+
+IMPLEMENT_SINGLETON(SecurityController)
+
+struct SecurityController::Impl
+{
+    SecurityLogic logic;
+};
+
+SecurityController::SecurityController()
+{
+    m_impl.reset(new Impl);
+}
+
+SecurityController::~SecurityController()
+{
+}
+
+void SecurityController::OnEventReceived(
+    const SecurityControllerEvents::InitializeSyncEvent & /* event */)
+{
+    SecurityCallerSingleton::Instance().Run();
+    m_impl->logic.initialize();
+}
+
+void SecurityController::OnEventReceived(
+        const SecurityControllerEvents::UpdatePolicySyncEvent& /* event */)
+{
+    m_impl->logic.updatePolicy();
+}
+
+void SecurityController::OnEventReceived(
+    const SecurityControllerEvents::TerminateSyncEvent & /*event*/)
+{
+    SecurityCallerSingleton::Instance().Quit();
+    m_impl->logic.terminate();
+}
+
+void SecurityController::OnEventReceived(
+    const SecurityControllerEvents::CheckFunctionCallSyncEvent &ev)
+{
+    *ev.GetArg0() = m_impl->logic.checkFunctionCall(ev.GetArg1());
+}
+
+void SecurityController::OnEventReceived(
+    const SecurityControllerEvents::CheckRuntimeCallSyncEvent &ev)
+{
+    *ev.GetArg0() = m_impl->logic.checkFunctionCall(ev.GetArg1(), ev.GetArg2());
+}
+
+void SecurityController::OnEventReceived(
+           const SecurityControllerEvents::ValidatePopupResponseEvent &ev)
+{
+    m_impl->logic.validatePopupResponse(ev.GetArg0(),
+                                        ev.GetArg1(),
+                                        ev.GetArg2(),
+                                        ev.GetArg3(),
+                                        ev.GetArg4());
+}
diff --git a/src/services/ace/logic/security_controller.h b/src/services/ace/logic/security_controller.h
new file mode 100644 (file)
index 0000000..d122420
--- /dev/null
@@ -0,0 +1,111 @@
+/*
+ * 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.
+ */
+/**
+ * This class simply redirects the access requests to access control engine.
+ * The aim is to hide access control engine specific details from WRT modules.
+ * It also implements WRT_INTERFACE.h interfaces, so that ACE could access
+ * WRT specific and other information during the decision making.
+ *
+ * @file    security_controller.h
+ * @author  Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @author  Ming Jin(ming79.jin@samsung.com)
+ * @version 1.0
+ * @brief   Header file for security controller
+ */
+#ifndef SECURITY_CONTROLLER_H
+#define SECURITY_CONTROLLER_H
+
+#include <dpl/singleton.h>
+#include <dpl/event/controller.h>
+#include <dpl/generic_event.h>
+#include <dpl/type_list.h>
+#include <string>
+#include <ace-dao-ro/PreferenceTypes.h>
+#include <ace/AbstractPolicyEnforcementPoint.h>
+#include <ace-dao-ro/PromptModel.h>
+#include <string>
+#include <dpl/event/inter_context_delegate.h>
+
+namespace Jobs {
+class Job;
+}
+
+namespace SecurityControllerEvents {
+DECLARE_GENERIC_EVENT_0(InitializeSyncEvent)
+DECLARE_GENERIC_EVENT_0(TerminateSyncEvent)
+DECLARE_GENERIC_EVENT_0(UpdatePolicySyncEvent)
+
+DECLARE_GENERIC_EVENT_2(CheckFunctionCallSyncEvent,
+                        PolicyResult *,
+                        Request *
+                       )
+
+DECLARE_GENERIC_EVENT_3(CheckRuntimeCallSyncEvent,
+                        PolicyResult *,
+                        Request *,
+                        std::string //sessionId
+                       )
+
+DECLARE_GENERIC_EVENT_5(ValidatePopupResponseEvent,
+                        Request *,
+                        bool, //is allowed
+                        Prompt::Validity,
+                        std::string, //sessionId
+                        bool* //check return value
+                       )
+
+} // namespace SecurityControllerEvents
+
+typedef DPL::TypeListDecl<
+    SecurityControllerEvents::InitializeSyncEvent,
+    SecurityControllerEvents::TerminateSyncEvent,
+    SecurityControllerEvents::UpdatePolicySyncEvent,
+    SecurityControllerEvents::ValidatePopupResponseEvent,
+    SecurityControllerEvents::CheckRuntimeCallSyncEvent,
+    SecurityControllerEvents::CheckFunctionCallSyncEvent>::Type
+SecurityControllerEventsTypeList;
+
+class SecurityController :
+        public DPL::Event::Controller<SecurityControllerEventsTypeList>
+{
+  protected:
+    virtual void OnEventReceived(
+            const SecurityControllerEvents::InitializeSyncEvent &event);
+    virtual void OnEventReceived(
+            const SecurityControllerEvents::UpdatePolicySyncEvent &event);
+    virtual void OnEventReceived(
+            const SecurityControllerEvents::ValidatePopupResponseEvent &e);
+    virtual void OnEventReceived(
+            const SecurityControllerEvents::TerminateSyncEvent &event);
+    virtual void OnEventReceived(
+            const SecurityControllerEvents::CheckFunctionCallSyncEvent &e);
+    virtual void OnEventReceived(
+            const SecurityControllerEvents::CheckRuntimeCallSyncEvent &e);
+
+  private:
+    class Impl;
+    std::unique_ptr<Impl> m_impl;
+
+    SecurityController();
+    //This desctructor must be in implementation file (cannot be autogenerated)
+    ~SecurityController();
+
+    friend class DPL::Singleton<SecurityController>;
+};
+
+typedef DPL::Singleton<SecurityController> SecurityControllerSingleton;
+
+#endif // SECURITY_CONTROLLER_H
diff --git a/src/services/ace/logic/security_logic.cpp b/src/services/ace/logic/security_logic.cpp
new file mode 100644 (file)
index 0000000..5448fc0
--- /dev/null
@@ -0,0 +1,386 @@
+/*
+ * 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.
+ */
+/**
+ * This class simply redirects the access requests to access control engine.
+ * The aim is to hide access control engine specific details from WRT modules.
+ * It also implements WRT_INTERFACE.h interfaces, so that ACE could access
+ * WRT specific and other information during the decision making.
+ *
+ * @file    security_controller.h
+ # @author  Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @author  Ming Jin(ming79.jin@samsung.com)
+ * @author  Piotr Kozbial (p.kozbial@samsung.com)
+ * @version 1.0
+ * @brief   Header file for security logic
+ */
+
+#include <security_logic.h>
+#include <attribute_facade.h>
+#ifdef WRT_SMACK_ENABLED
+#include <privilege-control.h>
+#endif
+#include <ace-dao-rw/AceDAO.h>
+#include <ace-dao-ro/AceDAOConversions.h>
+#include <ace/PolicyInformationPoint.h>
+#include <ace/PromptDecision.h>
+#include <dpl/log/log.h>
+#include <dpl/foreach.h>
+
+namespace {
+
+Request::ApplicationType getAppType(const Request *request) {
+    AceDB::AppTypes appType =
+        AceDB::AceDAOReadOnly::getWidgetType(request->getWidgetHandle());
+    switch (appType) {
+    case AceDB::AppTypes::Tizen:
+        LogDebug("==== Found Tizen application. ====");
+        return Request::APP_TYPE_TIZEN;
+    case AceDB::AppTypes::WAC20:
+        LogDebug("==== Found Wac20 application. ====");
+        return Request::APP_TYPE_WAC20;
+    default:
+        LogDebug("==== Unknown application type. ====");
+    }
+    return Request::APP_TYPE_UNKNOWN;
+}
+
+} // anonymous namespace
+
+void SecurityLogic::initialize() {
+    AceDB::AceDAO::attachToThreadRW();
+    m_policyEnforcementPoint.initialize(new WebRuntimeImpl(),
+                                        new ResourceInformationImpl(),
+                                        new OperationSystemImpl());
+}
+
+void SecurityLogic::terminate() {
+    m_policyEnforcementPoint.terminate();
+    AceDB::AceDAO::detachFromThread();
+}
+
+
+void SecurityLogic::grantPlatformAccess(const Request& request)
+{
+    (void)request;
+#ifdef WRT_SMACK_ENABLED
+    try {
+        unsigned long long id =
+            static_cast<unsigned long long>(request.getWidgetHandle());
+        Request::DeviceCapabilitySet dc = request.getDeviceCapabilitySet();
+
+        size_t i,size = dc.size();
+        std::unique_ptr<const char*[]> array(new const char*[size+1]);
+
+        array[size] = NULL;
+        auto it = dc.begin();
+
+        for(i=0; (i<size) && (it!=dc.end()); ++i,++it) {
+            array[i] = it->c_str();
+        }
+        int ret = wrt_permissions_add(id, array.get());
+        if (PC_OPERATION_SUCCESS != ret) {
+            LogError("smack rules couldn't be granted");
+        }
+    } catch (std::bad_alloc&) {
+        LogError("smack rules couldn't be granted: memory allocation failed");
+    }
+#endif
+}
+
+PolicyResult SecurityLogic::checkFunctionCall(Request* request)
+{
+    Assert(NULL != request);
+
+    LogDebug("=== Check widget existance ===");
+    Try {
+        request->setAppType(getAppType(request));
+    } Catch (AceDB::AceDAOReadOnly::Exception::DatabaseError) {
+        LogError("==== Couldn't find widget for handle: " <<
+            request->getWidgetHandle() << ". Access denied. ====");
+        return PolicyEffect::DENY;
+    }
+
+    PolicyResult aceResult = m_policyEnforcementPoint.check(*request).policyResult;
+
+    if (aceResult == PolicyEffect::PERMIT) {
+        grantPlatformAccess(*request);
+        return PolicyEffect::PERMIT;
+    } else if (aceResult == PolicyEffect::PROMPT_ONESHOT ||
+               aceResult == PolicyEffect::PROMPT_SESSION ||
+               aceResult == PolicyEffect::PROMPT_BLANKET ||
+               aceResult == PolicyDecision::NOT_APPLICABLE ||
+               aceResult == PolicyResult::UNDETERMINED)
+    {
+        // TODO: check stored user answers!!!
+        // if necessary, grant SMACK rules
+        // return appropriately - the following is a dummy:
+        return aceResult;
+    } else {
+        return PolicyEffect::DENY;
+    }
+}
+
+PolicyResult SecurityLogic::checkFunctionCall(Request* request, const std::string &sessionId)
+{
+    Assert(NULL != request);
+    LogDebug("=== Check existance of widget === ");
+    Try {
+        request->setAppType(getAppType(request));
+    } Catch (AceDB::AceDAOReadOnly::Exception::DatabaseError) {
+        LogError("==== Couldn't find widget for handle: " <<
+            request->getWidgetHandle() << ". Access denied. ====");
+        return PolicyEffect::DENY;
+    }
+
+    ExtendedPolicyResult exAceResult = m_policyEnforcementPoint.check(*request);
+    PolicyResult aceResult = exAceResult.policyResult;
+
+    LogDebug("Result returned by policy " << aceResult << ". RuleID: " << exAceResult.ruleId);
+
+    if (aceResult == PolicyEffect::PERMIT) {
+        LogDebug("Grant access.");
+        grantPlatformAccess(*request);
+        return PolicyEffect::PERMIT;
+    }
+
+    if (aceResult == PolicyEffect::PROMPT_ONESHOT ||
+        aceResult == PolicyEffect::DENY)
+    {
+        return aceResult;
+    }
+
+    OptionalCachedPromptDecision decision = AceDB::AceDAOReadOnly::getPromptDecision(
+        request->getWidgetHandle(),
+        exAceResult.ruleId);
+
+    if (!decision) {
+        LogDebug("No CachedPromptDecision found.");
+        return aceResult;
+    }
+
+    if (aceResult == PolicyEffect::PROMPT_BLANKET) {
+        if (decision->decision == PromptDecision::ALLOW_ALWAYS) {
+            LogDebug("Found user decision. Result changed to PERMIT. Access granted");
+            grantPlatformAccess(*request);
+            return PolicyEffect::PERMIT;
+        }
+        if (decision->decision == PromptDecision::DENY_ALWAYS) {
+            LogDebug("Found user decision. Result changed to DENY.");
+            return PolicyEffect::DENY;
+        }
+        if (decision->decision == PromptDecision::ALLOW_FOR_SESSION
+            && !!(decision->session)
+            && sessionId == DPL::ToUTF8String(*(decision->session)))
+        {
+            LogDebug("Result changed to PERMIT. Access granted.");
+            grantPlatformAccess(*request);
+            return PolicyEffect::PERMIT;
+        }
+        if (decision->decision == PromptDecision::DENY_FOR_SESSION
+            && !!(decision->session)
+            && sessionId == DPL::ToUTF8String(*(decision->session)))
+        {
+            LogDebug("Found user decision. Result changed to DENY.");
+            return PolicyEffect::DENY;
+        }
+        return aceResult;
+    }
+
+    if (aceResult == PolicyEffect::PROMPT_SESSION) {
+        if (decision->decision == PromptDecision::ALLOW_FOR_SESSION
+            && !!(decision->session)
+            && sessionId == DPL::ToUTF8String(*(decision->session)))
+        {
+            LogDebug("Found user decision. Result changed to PERMIT. Access granted.");
+            grantPlatformAccess(*request);
+            return PolicyEffect::PERMIT;
+        }
+        if (decision->decision == PromptDecision::DENY_FOR_SESSION
+            && !!(decision->session)
+            && sessionId == DPL::ToUTF8String(*(decision->session)))
+        {
+            LogDebug("Found user decision. Result changed to DENY.");
+            return PolicyEffect::DENY;
+        }
+        return aceResult;
+    }
+
+    // This should not happend - all PolicyEffect values were supported before.
+    // This mean that someone has modyfied PolicyEffect enum. SPANK SPANK SPANK
+    LogError("Unsupported PolicyEffect!");
+    return PolicyEffect::DENY;
+}
+
+void SecurityLogic::validatePopupResponse(Request* request,
+                                          bool allowed,
+                                          Prompt::Validity validity,
+                                          const std::string& sessionId,
+                                          bool* retValue)
+{
+    Assert(NULL != retValue);
+    Assert(NULL != request);
+
+    LogDebug("Start");
+    LogDebug("User answered: " << allowed << " with validity: " << validity);
+    LogDebug("Check widget existance");
+    Try {
+        request->setAppType(getAppType(request));
+    } Catch (AceDB::AceDAOReadOnly::Exception::DatabaseError) {
+        LogError("==== Couldn't find widget for handle: " <<
+            request->getWidgetHandle() << ". Access denied. ====");
+        retValue = false;
+        return;
+    }
+
+    *retValue = false;
+    OptionalExtendedPolicyResult extendedAceResult =
+        m_policyEnforcementPoint.checkFromCache(*request);
+    if (!extendedAceResult) {
+        LogDebug("No cached policy result - but it should be here");
+        LogDebug("returning " << *retValue);
+        return;
+    }
+
+    PolicyResult aceResult = extendedAceResult->policyResult;
+    if (aceResult == PolicyEffect::DENY) {
+        LogDebug("returning " << *retValue);
+        return;
+    }
+    if (aceResult == PolicyEffect::PERMIT) {
+        // TODO  we were asked for prompt validation
+        // but we got that no prompt should be opened - is this OK?
+        // (this is on the diagram in wiki)
+        *retValue = true;
+    } else if (aceResult == PolicyEffect::PROMPT_ONESHOT ||
+               aceResult == PolicyEffect::PROMPT_SESSION ||
+               aceResult == PolicyEffect::PROMPT_BLANKET)
+    {
+        Request::DeviceCapabilitySet devCaps =
+                request->getDeviceCapabilitySet();
+
+        FOREACH (it, devCaps) {
+            Request::DeviceCapability resourceId = *it;
+            LogDebug("Recheck: " << *it);
+            // 1) check if per-widget settings permit
+            AceDB::PreferenceTypes wgtPref =
+                AceDB::AceDAOReadOnly::getWidgetDevCapSetting(
+                    resourceId,
+                    request->getWidgetHandle());
+            if (AceDB::PreferenceTypes::PREFERENCE_DENY == wgtPref) {
+                LogDebug("returning " << *retValue);
+                return;
+            }
+            // 2) check if per-dev-cap settings permit
+            AceDB::PreferenceTypes resPerf =
+                AceDB::AceDAOReadOnly::getDevCapSetting(resourceId);
+            if (AceDB::PreferenceTypes::PREFERENCE_DENY == resPerf) {
+                LogDebug("returning " << *retValue);
+                return;
+            }
+
+            // 3) check for stored propmt answer - should not be there
+            // TODO  - is this check necessary?
+            AceDB::BaseAttributeSet attributes;
+            AceDB::AceDAOReadOnly::getAttributes(&attributes);
+            Request req(request->getWidgetHandle(),
+                        request->getExecutionPhase());
+            req.addDeviceCapability(resourceId);
+            PolicyInformationPoint *pip =
+                m_policyEnforcementPoint.getPip();
+
+            Assert(NULL != pip);
+
+            pip->getAttributesValues(&req, &attributes);
+            auto attrHash = AceDB::AceDaoConversions::convertToHash(attributes);
+
+            // 4) validate consistency of answer with policy result
+            Prompt::Validity clampedValidity =
+                    clampPromptValidity(validity, *(aceResult.getEffect()));
+
+            // 5) store answer in database if appropriate
+            // TODO  how about userParam? sessionId?
+            DPL::String userParam = DPL::FromUTF8String(sessionId);
+            boost::optional<DPL::String> sessionOptional = DPL::FromUTF8String(sessionId);
+
+            switch (clampedValidity) {
+            case Prompt::Validity::ALWAYS: {
+                AceDB::AceDAO::setPromptDecision(
+                    request->getWidgetHandle(),
+                    extendedAceResult->ruleId,
+                    sessionOptional,
+                    allowed ?
+                    PromptDecision::ALLOW_ALWAYS :
+                    PromptDecision::DENY_ALWAYS);
+                break; }
+            case Prompt::Validity::SESSION: {
+                AceDB::AceDAO::setPromptDecision(
+                    request->getWidgetHandle(),
+                    extendedAceResult->ruleId,
+                    sessionOptional,
+                    allowed ?
+                    PromptDecision::ALLOW_FOR_SESSION :
+                    PromptDecision::DENY_FOR_SESSION);
+                break; }
+
+            case Prompt::Validity::ONCE: {
+                LogInfo("Validity ONCE, not saving prompt decision to cache");
+                break; }
+            }
+
+        }
+        // access granted!
+        *retValue = allowed;
+    }
+    if (*retValue) {
+        // 6) grant smack label if not granted yet
+        grantPlatformAccess(*request);
+    }
+    LogDebug("Finish");
+    LogDebug("returning " << *retValue);
+}
+
+void SecurityLogic::updatePolicy()
+{
+    LogDebug("SecurityLogic::updatePolicy");
+    m_policyEnforcementPoint.updatePolicy();
+}
+
+Prompt::Validity SecurityLogic::clampPromptValidity(
+        Prompt::Validity validity,
+        PolicyEffect effect)
+{
+    switch (effect) {
+    case PolicyEffect::PROMPT_BLANKET: {
+        return validity; }
+    case PolicyEffect::PROMPT_SESSION: {
+        if (Prompt::Validity::ALWAYS == validity) {
+            LogInfo("ALWAYS returned from prompt in PROMPT_SESSION");
+            return Prompt::Validity::SESSION;
+        }
+        return validity; }
+    case PolicyEffect::PROMPT_ONESHOT: {
+        if (Prompt::Validity::ONCE != validity) {
+            LogInfo("Not ONCE returned from prompt in PROMPT_ONESHOT");
+        }
+        return Prompt::Validity::ONCE; }
+    case PolicyEffect::DENY:
+    case PolicyEffect::PERMIT:
+    default: {// other options - should not happen
+        LogError("This kind of policy effect does not deal with prompts");
+        return Prompt::Validity::ONCE;  }
+    }
+}
+
diff --git a/src/services/ace/logic/security_logic.h b/src/services/ace/logic/security_logic.h
new file mode 100644 (file)
index 0000000..71f8bae
--- /dev/null
@@ -0,0 +1,76 @@
+/*
+ * 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.
+ */
+/**
+ * This class simply redirects the access requests to access control engine.
+ * The aim is to hide access control engine specific details from WRT modules.
+ * It also implements WRT_INTERFACE.h interfaces, so that ACE could access
+ * WRT specific and other information during the decision making.
+ *
+ * @file    security_controller.h
+ * @author  Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @author  Ming Jin(ming79.jin@samsung.com)
+ * @author  Piotr Kozbial (p.kozbial@samsung.com)
+ * @version 1.0
+ * @brief   Header file for security logic
+ */
+#ifndef SECURITY_LOGIC_H
+#define SECURITY_LOGIC_H
+
+#include <ace/Request.h>
+#include <ace/PolicyResult.h>
+#include <ace/AbstractPolicyEnforcementPoint.h>
+#include <ace/Preference.h>
+#include <ace/PolicyEnforcementPoint.h>
+#include <ace-dao-ro/PromptModel.h>
+
+/* SecurityLogic
+ * May only be created and used by SecurityController.
+ * There may be only one instance.
+ */
+class SecurityLogic {
+  public:
+    SecurityLogic() {}
+    ~SecurityLogic() {}
+    // initialize/terminate
+    /** */
+    void initialize();
+    /** */
+    void terminate();
+
+    /** */
+    PolicyResult checkFunctionCall(Request*);
+    PolicyResult checkFunctionCall(Request*, const std::string &session);
+
+    void validatePopupResponse(Request* request,
+                               bool allowed,
+                               Prompt::Validity validity,
+                               const std::string& sessionId,
+                               bool* retValue);
+
+    /**
+     * Updates policy and clears policy cache
+     */
+    void updatePolicy();
+
+  private:
+    PolicyEnforcementPoint m_policyEnforcementPoint;
+
+    Prompt::Validity clampPromptValidity(Prompt::Validity validity,
+                                         PolicyEffect effect);
+    void grantPlatformAccess(const Request& request);
+};
+
+#endif // SECURITY_CONTROLLER_H
diff --git a/src/services/ace/logic/simple_roaming_agent.cpp b/src/services/ace/logic/simple_roaming_agent.cpp
new file mode 100644 (file)
index 0000000..cb78c97
--- /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    simple_roaming_agent.cpp
+ * @author  Pawel Sikorski (p.sikorski@samsung.com)
+ * @author  Lukasz Marek (l.marek@samsung.com)
+ * @author  Lukasz Wrzosek (l.wrzosek@samsung.com)
+ * @version 1.0
+ * @brief   roaming agent
+ */
+
+#include "simple_roaming_agent.h"
+#include <vconf.h>
+#include <dpl/log/log.h>
+#include <dpl/singleton_impl.h>
+IMPLEMENT_SINGLETON(SimpleRoamingAgent)
+
+SimpleRoamingAgent::SimpleRoamingAgent()
+{
+    if (vconf_notify_key_changed(
+            VCONFKEY_TELEPHONY_SVC_ROAM,
+            vConfChagedCallback, this) < 0)
+    {
+        LogError("Cannot add vconf callback [" <<
+                 VCONFKEY_TELEPHONY_SVC_ROAM << "]");
+        Assert(false && "Cannot add vconf callback");
+    }
+
+    int result = 0;
+    if (vconf_get_int(VCONFKEY_TELEPHONY_SVC_ROAM, &result) != 0) {
+        LogError("Cannot get current roaming status");
+        Assert(false && "Cannot get current roaming status");
+    } else {
+        bool type = (result == VCONFKEY_TELEPHONY_SVC_ROAM_ON);
+        m_networkType = type ? ROAMING : HOME;
+        LogInfo("Network type is " << (type ? "ROAMING" : "HOME"));
+    }
+
+}
+
+SimpleRoamingAgent::~SimpleRoamingAgent()
+{
+    if (vconf_ignore_key_changed(
+            VCONFKEY_TELEPHONY_SVC_ROAM,
+            vConfChagedCallback) < 0)
+    {
+        LogError("Cannot rm vconf callback [" <<
+                 VCONFKEY_TELEPHONY_SVC_ROAM << "]");
+        //Assert(false && "Cannot remove vconf callback");
+    }
+
+}
+
+void SimpleRoamingAgent::vConfChagedCallback(keynode_t *keyNode, void *data)
+{
+    LogInfo("SimpleRoamingAgent::vConfChagedCallback ");
+    char *key = vconf_keynode_get_name(keyNode);
+
+    if (NULL == key) {
+        LogWarning("vconf key is null.");
+        return;
+    }
+    std::string keyString = key;
+    if (VCONFKEY_TELEPHONY_SVC_ROAM != keyString) {
+        LogError("Wrong key found");
+        Assert(false && "Wrong key found in vconf callback");
+        return;
+    }
+    SimpleRoamingAgent *agent = static_cast<SimpleRoamingAgent *>(data);
+    if (NULL == agent) {
+        LogError("Bad user arg from vconf lib");
+        Assert(false && "Bad user arg from vconf lib");
+        return;
+    }
+    int result = 0;
+    if (vconf_get_int(VCONFKEY_TELEPHONY_SVC_ROAM, &result) != 0) {
+        LogError("Cannot get current roaming status");
+        Assert(false && "Cannot get current roaming status");
+    } else {
+        bool type = (result == VCONFKEY_TELEPHONY_SVC_ROAM_ON);
+        agent->m_networkType = type ? ROAMING : HOME;
+        LogInfo("Network type is " << (type ? "ROAMING" : "HOME"));
+    }
+}
diff --git a/src/services/ace/logic/simple_roaming_agent.h b/src/services/ace/logic/simple_roaming_agent.h
new file mode 100755 (executable)
index 0000000..65b0bbe
--- /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    simple_roaming_agent.h
+ * @author  Pawel Sikorski (p.sikorski@samsung.com)
+ * @author  Lukasz Wrzosek (l.wrzosek@samsung.com)
+ * @version 1.0
+ * @brief   simple roaming agent
+ */
+
+#ifndef WRT_SRC_ACCESS_CONTROL_COMMON_SIMPLE_ROAMING_AGENT_H_
+#define WRT_SRC_ACCESS_CONTROL_COMMON_SIMPLE_ROAMING_AGENT_H_
+
+#include <string>
+#include <dpl/singleton.h>
+#include <dpl/noncopyable.h>
+#include <vconf.h>
+
+class SimpleRoamingAgent : DPL::Noncopyable
+{
+  public:
+    bool IsRoamingOn() const
+    {
+        return ROAMING == m_networkType;
+    }
+
+  private:
+    enum NetworkType {ROAMING, HOME};
+
+    NetworkType m_networkType;
+
+    SimpleRoamingAgent();
+    virtual ~SimpleRoamingAgent();
+
+    static void vConfChagedCallback(keynode_t *keyNode, void *userParam);
+
+    friend class DPL::Singleton<SimpleRoamingAgent>;
+};
+
+typedef DPL::Singleton<SimpleRoamingAgent> SimpleRoamingAgentSingleton;
+
+#endif//WRT_SRC_ACCESS_CONTROL_COMMON_SIMPLE_ROAMING_AGENT_H_
diff --git a/src/services/ace/socket/ace_service_callbacks.cpp b/src/services/ace/socket/ace_service_callbacks.cpp
new file mode 100644 (file)
index 0000000..ac3f6cf
--- /dev/null
@@ -0,0 +1,133 @@
+/*
+ * Copyright (c) 2012 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        ace_service_callbacks.cpp
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       Implementation of Ace Service callbacks
+ */
+#include <string>
+#include <vector>
+#include <dpl/log/log.h>
+#include "ace_service_callbacks.h"
+#include <callback_api.h>
+#include <ace/Request.h>
+#include <ace/PolicyResult.h>
+#include <security_controller.h>
+#include <security_caller.h>
+#include <attribute_facade.h>
+
+namespace RPC {
+
+void AceServiceCallbacks::checkAccess(SocketConnection * connector){
+
+    int widgetHandle = 0;
+    std::string subject, resource, sessionId;
+    std::vector<std::string> paramNames, paramValues;
+    Try {
+        connector->read(&widgetHandle,
+                        &subject,
+                        &resource,
+                        &paramNames,
+                        &paramValues,
+                        &sessionId);
+    } Catch (SocketConnection::Exception::SocketConnectionException){
+        LogError("Socket Connection read error");
+        ReThrowMsg(ServiceCallbackApi::Exception::ServiceCallbackException,
+                   "Socket Connection read error");
+    }
+
+    if (paramNames.size() != paramValues.size()) {
+        ThrowMsg(ServiceCallbackApi::Exception::ServiceCallbackException, "Varying sizes of parameter names and parameter values");
+    }
+    LogDebug("We got subject: " << subject);
+    LogDebug("We got resource: " << resource);
+
+    FunctionParamImpl params;
+    for (size_t i = 0; i < paramNames.size(); ++i) {
+        params.addAttribute(paramNames[i], paramValues[i]);
+    }
+
+    Request request(widgetHandle,
+                    WidgetExecutionPhase_Invoke,
+                    &params);
+    request.addDeviceCapability(resource);
+
+    PolicyResult result(PolicyEffect::DENY);
+    SecurityCallerSingleton::Instance().SendSyncEvent(
+        SecurityControllerEvents::CheckRuntimeCallSyncEvent(
+            &result,
+            &request,
+            sessionId));
+
+    int response = PolicyResult::serialize(result);
+
+    Try{
+        connector->write(response);
+    } Catch (SocketConnection::Exception::SocketConnectionException){
+        LogError("Socket Connection write error");
+        ReThrowMsg(ServiceCallbackApi::Exception::ServiceCallbackException,
+                   "Socket Connection write error");
+    }
+}
+
+void AceServiceCallbacks::checkAccessInstall(SocketConnection * connector){
+
+    int widgetHandle;
+    std::string resource;
+
+    Try {
+        connector->read(&widgetHandle,
+                        &resource);
+    } Catch (SocketConnection::Exception::SocketConnectionException){
+        LogError("Socket Connection read error");
+        ReThrowMsg(ServiceCallbackApi::Exception::ServiceCallbackException,
+                   "Socket Connection read error");
+    }
+
+    LogDebug("We got handle: " << widgetHandle);
+    LogDebug("We got resource: " << resource);
+
+    Request request(widgetHandle,
+          WidgetExecutionPhase_WidgetInstall);
+    request.addDeviceCapability(resource);
+
+    PolicyResult result(PolicyEffect::DENY);
+    SecurityCallerSingleton::Instance().SendSyncEvent(
+            SecurityControllerEvents::CheckFunctionCallSyncEvent(
+                    &result,
+                    &request));
+
+    int response = PolicyResult::serialize(result);
+
+    Try{
+        connector->write(response);
+    }  Catch (SocketConnection::Exception::SocketConnectionException){
+        LogError("Socket Connection write error");
+        ReThrowMsg(ServiceCallbackApi::Exception::ServiceCallbackException,
+                   "Socket Connection write error");
+    }
+}
+
+void AceServiceCallbacks::updatePolicy(SocketConnection * /*connector*/){
+
+
+    LogDebug("Policy update socket message received");
+    SecurityCallerSingleton::Instance().SendSyncEvent(
+            SecurityControllerEvents::UpdatePolicySyncEvent());
+}
+
+} //namespace RPC
diff --git a/src/services/ace/socket/ace_service_callbacks.h b/src/services/ace/socket/ace_service_callbacks.h
new file mode 100644 (file)
index 0000000..e5ebc18
--- /dev/null
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2012 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        ace_service_callbacks.h
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       Header of Ace Service callbacks
+ */
+
+#ifndef ACE_SERVICE_CALLBACKS_H_
+#define ACE_SERVICE_CALLBACKS_H_
+
+#include <memory>
+#include <SocketConnection.h>
+#include <dpl/log/log.h>
+
+namespace RPC {
+
+namespace AceServiceCallbacks {
+
+    // IN string subject
+    // IN string resource
+    // IN vector<string> function param names
+    // IN vector<string> function param values
+    // OUT int allow, deny, popup type
+    void checkAccess(SocketConnection * connector);
+
+    // IN string subject
+    // IN string resource
+    // OUT int allow, deny, popup type
+    void checkAccessInstall(SocketConnection * connector);
+
+    // Policy update trigger
+    void updatePolicy(SocketConnection * connector);
+
+};
+
+} //namespace RPC
+
+#endif /* ACE_SERVICE_CALLBACKS_H_ */
diff --git a/src/services/ace/socket/api/ace_service_callbacks_api.h b/src/services/ace/socket/api/ace_service_callbacks_api.h
new file mode 100644 (file)
index 0000000..dfd136b
--- /dev/null
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2012 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        ace_service_callbacks_api.h
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       Header with api of implemented Ace Service callbacks
+ */
+#ifndef ACE_SERVICE_CALLBACKS_API_H_
+#define ACE_SERVICE_CALLBACKS_API_H_
+
+#include <string>
+#include <utility>
+#include "ace_server_api.h"
+#include "ace_service_callbacks.h"
+#include "callback_api.h"
+
+namespace WrtSecurity{
+namespace AceServiceCallbacksApi{
+
+inline const std::pair<std::string, socketServerCallback> CHECK_ACCESS_METHOD_CALLBACK() {
+    return std::make_pair(WrtSecurity::AceServerApi::CHECK_ACCESS_METHOD(),
+                          RPC::AceServiceCallbacks::checkAccess);
+}
+
+inline const std::pair<std::string, socketServerCallback> CHECK_ACCESS_INSTALL_METHOD_CALLBACK() {
+    return std::make_pair(WrtSecurity::AceServerApi::CHECK_ACCESS_INSTALL_METHOD(),
+                          RPC::AceServiceCallbacks::checkAccessInstall);
+}
+
+inline const std::pair<std::string, socketServerCallback> UPDATE_POLICY_METHOD_CALLBACK() {
+    return std::make_pair(WrtSecurity::AceServerApi::UPDATE_POLICY_METHOD(),
+                          RPC::AceServiceCallbacks::updatePolicy);
+}
+
+} // namespace AceServiceCallbacksApi
+} // namespace WrtSecurity
+
+
+#endif // ACE_SERVICE_CALLBACKS_API_H_
diff --git a/src/services/caller/security_caller.cpp b/src/services/caller/security_caller.cpp
new file mode 100644 (file)
index 0000000..8fab788
--- /dev/null
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2012 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        popup_service_callbacks.cpp
+ * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
+ * @version     1.0
+ * @brief       Implementation of Security Caller Thread singleton
+ */
+
+#include <security_caller.h>
+#include <dpl/singleton_impl.h>
+
+IMPLEMENT_SINGLETON(SecurityCallerThread)
diff --git a/src/services/caller/security_caller.h b/src/services/caller/security_caller.h
new file mode 100644 (file)
index 0000000..e1b68d0
--- /dev/null
@@ -0,0 +1,189 @@
+/*
+ * Copyright (c) 2012 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        popup_service_callbacks.cpp
+ * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
+ * @version     1.0
+ * @brief       Header of Security Caller class used by services socket callbacks
+ */
+
+#ifndef SECURITY_CALLER_H__
+#define SECURITY_CALLER_H__
+
+#include <dpl/thread.h>
+#include <dpl/assert.h>
+#include <dpl/singleton.h>
+
+#include <security_controller.h>
+
+#include <pthread.h>
+
+class IEventHolder
+{
+ public:
+  virtual void FinalizeSending() = 0;
+  virtual ~IEventHolder() {};
+};
+
+template<class EventType>
+class EventHolderImpl : public IEventHolder
+{
+  EventType event;
+
+ public:
+  EventHolderImpl(const EventType& e) : event(e) {}
+  virtual void FinalizeSending()
+  {
+    LogDebug("sending real sync event");
+    CONTROLLER_POST_SYNC_EVENT(SecurityController, event);
+  }
+};
+
+/*
+ * Because Security Controller is a DPL::Controler class, its events
+ * can be send only from a DPL managed thread. SecurityCallerTread class
+ * has been implemented as a workaround of that constraint.
+ * This class is a DPL managed thread that waits for requests
+ * from non DPL managed threads and when receives one it posts event
+ * to the Security Controler in charge of the calling thread.
+ */
+
+
+class SecurityCallerThread : public DPL::Thread
+{
+ private:
+  pthread_mutex_t m_mutex2;
+  pthread_mutex_t m_mutex;
+  pthread_cond_t m_cond;
+  pthread_cond_t m_cond2;
+  bool m_continue;
+  bool m_finished;
+  IEventHolder* m_eventHolder;
+  pthread_mutex_t m_syncMutex;
+
+
+  SecurityCallerThread() :
+    Thread(),
+    m_mutex2(PTHREAD_MUTEX_INITIALIZER),
+    m_mutex(PTHREAD_MUTEX_INITIALIZER),
+    m_cond(PTHREAD_COND_INITIALIZER),
+    m_cond2(PTHREAD_COND_INITIALIZER),
+    m_continue(true),
+    m_finished(false),
+    m_eventHolder(NULL),
+    m_syncMutex(PTHREAD_MUTEX_INITIALIZER)
+  {
+    LogDebug("constructor");
+  }
+
+  virtual ~SecurityCallerThread()
+  {
+    pthread_mutex_unlock(&m_syncMutex);
+    pthread_cond_destroy(&m_cond);
+    pthread_cond_destroy(&m_cond2);
+    pthread_mutex_destroy(&m_mutex2);
+    pthread_mutex_destroy(&m_mutex);
+    pthread_mutex_destroy(&m_syncMutex);
+  }
+
+ protected:
+  /* main routine of the SecurityCallerThread */
+  virtual int ThreadEntry()
+  {
+    LogDebug("SecurityCallerThread start");
+    pthread_mutex_lock(&m_mutex); // lock shared data
+
+    while (m_continue) // main loop
+    {
+      if (m_eventHolder) // if m_eventHolder is set, the request has been received
+      {
+        m_eventHolder->FinalizeSending(); // send actual event in charge of calling thread
+        delete m_eventHolder;
+        m_eventHolder = NULL;
+        LogDebug("setting finished state");
+        pthread_mutex_lock(&m_syncMutex); // lock m_finished
+        m_finished = true;
+        pthread_mutex_unlock(&m_syncMutex); // unlock m_finished
+        LogDebug("finished");
+        pthread_cond_signal(&m_cond2); // signal a calling thread that event has been posted.
+      }
+      LogDebug("waiting for event");
+      // atomically:
+      // unlock m_mutex, wait on m_cond until signal received, lock m_mutex
+      pthread_cond_wait(&m_cond, &m_mutex);
+      LogDebug("found an event");
+    }
+
+    pthread_mutex_unlock(&m_mutex);
+
+    return 0;
+  }
+
+ public:
+  void Quit()
+  {
+    LogDebug("Quit called");
+    pthread_mutex_lock(&m_mutex);    // lock shared data
+    m_continue = false;              // main loop condition set to false
+    pthread_mutex_unlock(&m_mutex);  // unlock shard data
+    pthread_cond_signal(&m_cond);
+  }
+
+  template <class EventType>
+  void SendSyncEvent(const EventType& event)
+  {
+    // prevent SendSyncEvent being called by multiple threads at the same time.
+    pthread_mutex_lock(&m_mutex2);
+    LogDebug("sending sync event");
+    bool correct_thread = false;
+    Try {
+      LogDebug("Checking if this is unmanaged thread");
+      DPL::Thread::GetCurrentThread();
+    } Catch (DPL::Thread::Exception::UnmanagedThread) {
+      correct_thread = true;
+    }
+    Assert(correct_thread &&
+           "This method may not be called from DPL managed thread or main thread");
+    LogDebug("putting an event to be posted");
+    pthread_mutex_lock(&m_mutex);  // lock shared data
+    Assert(m_eventHolder == NULL && "Whooops");
+    m_eventHolder = new EventHolderImpl<EventType>(event); // put an event to be posted
+    pthread_mutex_unlock(&m_mutex); // unlock shared data
+    LogDebug("Signal caller thread that new event has been created");
+    pthread_cond_signal(&m_cond);   // signal SecurityCallerThread to wake up because new
+                                    // event is waiting to be posted
+
+    LogDebug("waiting untill send completes");
+    pthread_mutex_lock(&m_syncMutex); /* wait until send completes */
+    while (!m_finished)
+    {
+        pthread_cond_wait(&m_cond2, &m_syncMutex); // wait until event is posted
+    }
+    LogDebug("done");
+    m_finished = false;
+    pthread_mutex_unlock(&m_syncMutex);
+    pthread_mutex_unlock(&m_mutex2);
+  }
+
+ private:
+  friend class DPL::Singleton<SecurityCallerThread>;
+};
+
+typedef DPL::Singleton<SecurityCallerThread> SecurityCallerSingleton;
+
+
+
+#endif //SECURITY_CALLER_H__
diff --git a/src/services/ocsp/dbus/api/ocsp_server_dbus_api.h b/src/services/ocsp/dbus/api/ocsp_server_dbus_api.h
new file mode 100644 (file)
index 0000000..df9817b
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * 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        ocsp_server_api.h
+ * @author
+ * @version     1.0
+ * @brief       This file contains definitions OCSP server interface & methods specifically needed by DBus.
+ */
+#ifndef WRT_SRC_RPC_SECURITY_DAEMON_OCSP_SERVER_DBUS_API_H_
+#define WRT_SRC_RPC_SECURITY_DAEMON_OCSP_SERVER_DBUS_API_H_
+
+#include "ocsp_server_api.h"
+#include<string>
+
+namespace WrtSecurity{
+namespace OcspServerApi{
+
+
+// RPC test function
+// IN std::string
+// OUT std::string
+inline const std::string ECHO_METHOD()
+{
+    return "echo";
+}
+
+
+
+}
+};
+
+#endif // WRT_SRC_RPC_SECURITY_DAEMON_OCSP_SERVER_DBUS_API_H_
diff --git a/src/services/ocsp/dbus/ocsp_server_dbus_interface.cpp b/src/services/ocsp/dbus/ocsp_server_dbus_interface.cpp
new file mode 100644 (file)
index 0000000..2acc5d8
--- /dev/null
@@ -0,0 +1,77 @@
+/*
+ * 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        ocsp_service_dbus_interface.cpp
+ * @author      Piotr Marcinkiewicz (p.marcinkiew@samsung.com)
+ * @version     1.0
+ * @brief       Implementation of OCSP server API.
+ */
+#include "ocsp_server_dbus_interface.h"
+
+namespace RPC {
+
+using namespace WrtSecurity;
+
+OcspServerDBusInterface::OcspServerDBusInterface():
+    DPL::DBus::InterfaceDispatcher(OcspServerApi::INTERFACE_NAME())
+{
+    setXmlSignature("<node>"
+        "  <interface name='" + OcspServerApi::INTERFACE_NAME() + "'>"
+        "    <method name='" + OcspServerApi::ECHO_METHOD() + "'>"
+        "      <arg type='s' name='input' direction='in'/>"
+        "      <arg type='s' name='output' direction='out'/>"
+        "    </method>"
+        "    <method name='" + OcspServerApi::CHECK_ACCESS_METHOD() + "'>"
+        "      <arg type='i' name='input' direction='in'/>"
+        "      <arg type='i' name='output' direction='out'/>"
+        "    </method>"
+        "  </interface>"
+        "</node>");
+}
+
+
+void OcspServerDBusInterface::onMethodCall(
+        const gchar* argMethodName,
+        GVariant* argParameters,
+        GDBusMethodInvocation* argInvocation)
+{
+    if (OcspServerApi::ECHO_METHOD() == argMethodName){
+        // TODO: Deserialization should use
+        // DBus::SErverDeserialization::deserialize()
+        const gchar* arg = NULL;
+        g_variant_get(argParameters, "(&s)", &arg);
+        // TODO: Serialization should use
+        // DBus::SErverDeserialization::serialize()
+        gchar* response = g_strdup_printf(arg);
+        g_dbus_method_invocation_return_value(argInvocation,
+                                              g_variant_new ("(s)", response));
+        g_free (response);
+    } else if (OcspServerApi::CHECK_ACCESS_METHOD() == argMethodName) {
+        gint32 value;
+        g_variant_get(argParameters, "(i)", &value);
+
+        // TODO: this is making OCSP service a stub! this HAS to be moved
+        // with proper implementation to cert-svc daemon
+        gint32 response = 0; // Certificates are valid for now
+
+        GVariant* varResponse = g_variant_new ("(i)", response);
+                //This function will unref invocation and it will be freed
+        LogDebug("OCSP dbus interface tries to send result");
+        g_dbus_method_invocation_return_value(argInvocation, varResponse);
+    }
+}
+
+} // namespace RPC
diff --git a/src/services/ocsp/dbus/ocsp_server_dbus_interface.h b/src/services/ocsp/dbus/ocsp_server_dbus_interface.h
new file mode 100644 (file)
index 0000000..748c0bd
--- /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        ocsp_service_dbus_interface.h
+ * @author      Piotr Marcinkiewicz (p.marcinkiew@samsung.com)
+ * @version     1.0
+ * @brief       Class that handles OCSP server API.
+ */
+#ifndef WRT_SRC_RPC_SECURITY_DAEMON_OCSP_SERVER_DBUS_INTERFACE_H_
+#define WRT_SRC_RPC_SECURITY_DAEMON_OCSP_SERVER_DBUS_INTERFACE_H_
+
+#include <list>
+#include <dpl/dbus/dbus_interface_dispatcher.h>
+#include "api/ocsp_server_dbus_api.h"
+
+namespace RPC {
+
+class OcspServerDBusInterface :
+    public DPL::DBus::InterfaceDispatcher
+{
+  public:
+    OcspServerDBusInterface();
+
+    virtual ~OcspServerDBusInterface()
+    {}
+
+    virtual void onMethodCall(const gchar* method_name,
+                              GVariant* parameters,
+                              GDBusMethodInvocation* invocation);
+};
+
+} // namespace RPC
+
+#endif // WRT_SRC_RPC_SECURITY_DAEMON_OCSP_SERVER_DBUS_INTERFACE_H_
diff --git a/src/services/ocsp/ocsp_server_api.h b/src/services/ocsp/ocsp_server_api.h
new file mode 100644 (file)
index 0000000..61be515
--- /dev/null
@@ -0,0 +1,49 @@
+/*
+ * 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        ocsp_server_api.h
+ * @author
+ * @version     1.0
+ * @brief       This file contains definitions OCSP server interface & methods.
+ */
+#ifndef WRT_SRC_RPC_SECURITY_DAEMON_OCSP_SERVER_API_H_
+#define WRT_SRC_RPC_SECURITY_DAEMON_OCSP_SERVER_API_H_
+
+#include "ocsp_server_api.h"
+#include<string>
+
+namespace WrtSecurity{
+namespace OcspServerApi{
+
+// DBus interface name
+inline const std::string INTERFACE_NAME()
+{
+    return "org.tizen.OcspCheck";
+}
+
+// Function checks WidgetStatus for installed widget.
+// https://106.116.37.24/wiki/WebRuntime/Security/Widget_Signatures
+// IN WidgetHandle Widget ID in Database
+// OUT WidgetStatus GOOD/REVOKED
+inline const std::string CHECK_ACCESS_METHOD()
+{
+    return "OcspCheck";
+}
+
+}
+};
+
+#endif // WRT_SRC_RPC_SECURITY_DAEMON_OCSP_SERVER_API_H_
diff --git a/src/services/ocsp/ocsp_service.cpp b/src/services/ocsp/ocsp_service.cpp
new file mode 100644 (file)
index 0000000..34d3499
--- /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        ocsp_service.cpp
+ * @author      Piotr Marcinkiewicz (p.marcinkiew@samsung.com)
+ * @version     1.0
+ * @brief       This is implementation file of Ocsp service
+ */
+
+#include "security_daemon.h"
+
+namespace OcspService {
+
+class OcspService : public SecurityDaemon::DaemonService
+{
+  private:
+    virtual void initialize()
+    {
+    }
+
+    virtual void start()
+    {
+    }
+
+    virtual void stop()
+    {
+    }
+
+    virtual void deinitialize()
+    {
+    }
+
+};
+
+DAEMON_REGISTER_SERVICE_MODULE(OcspService)
+
+}//namespace OcspService
+
diff --git a/src/services/ocsp/socket/api/ocsp_service_callbacks_api.h b/src/services/ocsp/socket/api/ocsp_service_callbacks_api.h
new file mode 100644 (file)
index 0000000..fd9bf3e
--- /dev/null
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2012 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        ocsp_service_callbacks_api.h
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       Header with api of implemented Ocsp Service callbacks
+ */
+
+#ifndef OCSP_SERVICE_CALLBACKS_API_H_
+#define OCSP_SERVICE_CALLBACKS_API_H_
+
+#include <string>
+#include <utility>
+#include "SocketConnection.h"
+#include "ocsp_server_api.h"
+#include "ocsp_service_callbacks.h"
+#include "callback_api.h"
+
+namespace WrtSecurity{
+namespace OcspServiceCallbacksApi{
+
+inline const std::pair<std::string, socketServerCallback> CHECK_ACCESS_METHOD_CALLBACK(){
+    return std::make_pair(WrtSecurity::OcspServerApi::CHECK_ACCESS_METHOD(),
+                          RPC::OcspServiceCallbacks::checkAccess);
+}
+
+} // namespace OcspServiceCallbacksApi
+} // namespace WrtSecurity
+
+#endif // OCSP_SERVICE_CALLBACKS_API_H_
diff --git a/src/services/ocsp/socket/ocsp_service_callbacks.cpp b/src/services/ocsp/socket/ocsp_service_callbacks.cpp
new file mode 100644 (file)
index 0000000..53811b5
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2012 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        ocsp_service_callbacks.cpp
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       Implementation of Ocsp Service callbacks
+ */
+
+#include "ocsp_service_callbacks.h"
+#include <callback_api.h>
+#include <dpl/log/log.h>
+
+namespace RPC {
+
+void OcspServiceCallbacks::checkAccess(SocketConnection * connector){
+    int response = 0;
+    Try {
+        int handle;
+        connector->read(&handle);
+        LogDebug("handle : " << handle);
+        connector->write(response);
+    } Catch (SocketConnection::Exception::SocketConnectionException){
+        LogError("Socket Connection write error");
+        ReThrowMsg(ServiceCallbackApi::Exception::ServiceCallbackException,
+                   "Socket Connection write error");
+    }
+}
+
+} // namespace RPC
diff --git a/src/services/ocsp/socket/ocsp_service_callbacks.h b/src/services/ocsp/socket/ocsp_service_callbacks.h
new file mode 100644 (file)
index 0000000..df77a80
--- /dev/null
@@ -0,0 +1,35 @@
+/*
+ * Copyright (c) 2012 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        ocsp_service_callbacks.h
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       Header of Ocsp Service callbacks class
+ */
+
+#ifndef OCSP_SERVICE_CALLBACKS_H_
+#define OCSP_SERVICE_CALLBACKS_H_
+
+#include <SocketConnection.h>
+
+namespace RPC {
+
+namespace OcspServiceCallbacks {
+    void checkAccess(SocketConnection * connector);
+};
+
+} // namespace RPC
+#endif /* OCSP_SERVICE_CALLBACKS_H_ */
diff --git a/src/services/popup/dbus/popup_response_dbus_interface.cpp b/src/services/popup/dbus/popup_response_dbus_interface.cpp
new file mode 100644 (file)
index 0000000..f897eeb
--- /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    popup_response_dispatcher.cpp
+ * @author  Zbigniew Kostrzewa (z.kostrzewa@samsung.com)
+ * @version 1.0
+ * @brief
+ */
+
+#include "popup_response_dbus_interface.h"
+#include <vector>
+#include <string>
+#include <dpl/dbus/dbus_server_deserialization.h>
+#include <dpl/dbus/dbus_server_serialization.h>
+#include <ace/Request.h>
+#include <ace-dao-ro/PromptModel.h>
+#include "popup_ace_data_types.h"
+//#include "access-control/engine/PromptModel.h"
+#include "attribute_facade.h"
+//#include "Request.h"
+#include "security_controller.h"
+
+namespace RPC
+{
+
+void PopupResponseDBusInterface::onMethodCall(const gchar* methodName,
+                                           GVariant* parameters,
+                                           GDBusMethodInvocation* invocation)
+{
+    using namespace WrtSecurity;
+#if 1
+    if (0 == g_strcmp0(methodName,
+            PopupServerApi::VALIDATION_METHOD().c_str()))
+    {
+        // popup answer data
+        bool allowed = false;
+        int serializedValidity = 0;
+
+        // ACE data
+        AceUserdata acedata;
+
+        if (!DPL::DBus::ServerDeserialization::deserialize(
+                parameters,
+                &allowed,
+                &serializedValidity,
+                &(acedata.handle),
+                &(acedata.subject),
+                &(acedata.resource),
+                &(acedata.paramKeys),
+                &(acedata.paramValues),
+                &(acedata.sessionId)))
+        {
+            g_dbus_method_invocation_return_dbus_error(
+                          invocation,
+                          "org.tizen.PopupResponse.UnknownError",
+                          "Error in deserializing input parameters");
+            return;
+        }
+
+        if (acedata.paramKeys.size() != acedata.paramValues.size()) {
+            g_dbus_method_invocation_return_dbus_error(
+                      invocation,
+                      "org.tizen.PopupResponse.UnknownError",
+                      "Varying sizes of parameter names and parameter values");
+            return;
+        }
+
+        FunctionParamImpl params;
+        for (size_t i = 0; i < acedata.paramKeys.size(); ++i) {
+            params.addAttribute(acedata.paramKeys[i], acedata.paramValues[i]);
+        }
+        Request request(acedata.handle,
+                        WidgetExecutionPhase_Invoke,
+                        &params);
+        request.addDeviceCapability(acedata.resource);
+
+        Prompt::Validity validity = static_cast<Prompt::Validity>(serializedValidity);
+
+        bool response = false;
+        SecurityControllerEvents::ValidatePopupResponseEvent ev(
+            &request,
+            allowed,
+            validity,
+            acedata.sessionId,
+            &response);
+        CONTROLLER_POST_SYNC_EVENT(SecurityController, ev);
+
+        g_dbus_method_invocation_return_value(
+            invocation,
+            DPL::DBus::ServerSerialization::serialize(response));
+    }
+#endif
+}
+
+}
diff --git a/src/services/popup/dbus/popup_response_dbus_interface.h b/src/services/popup/dbus/popup_response_dbus_interface.h
new file mode 100644 (file)
index 0000000..19e9494
--- /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    popup_response_dbus_interface.h
+ * @author  Zbigniew Kostrzewa (z.kostrzewa@samsung.com)
+ * @author  Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version 1.0
+ * @brief
+ */
+
+#ifndef WRT_SRC_RPC_DAEMON_POPUP_RESPONSE_DBUS_INTERFACE_H
+#define WRT_SRC_RPC_DAEMON_POPUP_RESPONSE_DBUS_INTERFACE_H
+
+#include <dpl/dbus/dbus_interface_dispatcher.h>
+#include "popup_response_server_api.h"
+
+namespace RPC {
+
+class PopupResponseDBusInterface : public DPL::DBus::InterfaceDispatcher
+{
+public:
+    PopupResponseDBusInterface():
+            DPL::DBus::InterfaceDispatcher(
+                    WrtSecurity::PopupServerApi::INTERFACE_NAME())
+    {
+        using namespace WrtSecurity;
+
+        setXmlSignature("<node>"
+                 "  <interface name='" +
+                         PopupServerApi::INTERFACE_NAME() + "'>"
+                 "    <method name='" +
+                         PopupServerApi::VALIDATION_METHOD() + "'>"
+                         // popup answer data
+                 "      <arg type='b' name='allowed' direction='in'/>"
+                 "      <arg type='i' name='valid' direction='in'/>"
+                         // this is copied from ace_server_dbus_interface
+                 "      <arg type='i' name='handle' direction='in'/>"
+                 "      <arg type='s' name='subject' direction='in'/>"
+                 "      <arg type='s' name='resource' direction='in'/>"
+                 "      <arg type='as' name='parameter names' direction='in'/>"
+                 "      <arg type='as' name='parameter values' direction='in'/>"
+                 "      <arg type='s' name='sessionId' direction='in'/>"
+                 "      <arg type='b' name='response' direction='out'/>"
+                 "    </method>"
+                 "  </interface>"
+                 "</node>");
+
+    }
+
+    virtual ~PopupResponseDBusInterface()
+    {}
+
+    virtual void onMethodCall(const gchar* methodName,
+                              GVariant* parameters,
+                              GDBusMethodInvocation* invocation);
+};
+
+}
+
+#endif // WRT_SRC_RPC_DAEMON_POPUP_RESPONSE_DBUS_INTERFACE_H
diff --git a/src/services/popup/popup_ace_data_types.h b/src/services/popup/popup_ace_data_types.h
new file mode 100644 (file)
index 0000000..1b5f734
--- /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    popup_ace_data_types.h
+ * @author  Pawel Sikorski (p.sikorski@samsung.com)
+ * @version 1.0
+ * @brief
+ */
+
+#ifndef POPUP_ACE_DATA_TYPES_H_
+#define POPUP_ACE_DATA_TYPES_H_
+
+#include <vector>
+#include <string>
+
+// additional data needed by PolicyEvaluaor to recognize Popup Response
+struct AceUserdata
+{
+    //TODO INVALID_WIDGET_HANDLE is defined in wrt_plugin_export.h.
+    // I do not want to include that file here...
+    AceUserdata(): handle(-1) {}
+
+    int handle;
+    std::string subject;
+    std::string resource;
+    std::vector<std::string> paramKeys;
+    std::vector<std::string> paramValues;
+    std::string sessionId;
+};
+
+typedef bool SecurityStatus;
+
+#endif /* POPUP_ACE_DATA_TYPES_H_ */
diff --git a/src/services/popup/popup_response_server_api.h b/src/services/popup/popup_response_server_api.h
new file mode 100644 (file)
index 0000000..47dd4d3
--- /dev/null
@@ -0,0 +1,45 @@
+/*
+ * 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    popup_response_server_api.h
+ * @author  Zbigniew Kostrzewa (z.kostrzewa@samsung.com)
+ * @version 1.0
+ * @brief
+ */
+
+#ifndef WRT_SRC_RPC_SECURITY_DAEMON_API_POPUP_RESPONSE_SERVER_API_H
+#define WRT_SRC_RPC_SECURITY_DAEMON_API_POPUP_RESPONSE_SERVER_API_H
+
+#include <string>
+
+namespace WrtSecurity{
+namespace PopupServerApi{
+
+inline const std::string INTERFACE_NAME()
+{
+    return "org.tizen.PopupResponse";
+}
+
+inline const std::string VALIDATION_METHOD()
+{
+    return "validate";
+}
+
+}
+}
+
+#endif // WRT_SRC_RPC_SECURITY_DAEMON_API_POPUP_RESPONSE_SERVER_API_H
+
diff --git a/src/services/popup/socket/api/popup_service_callbacks_api.h b/src/services/popup/socket/api/popup_service_callbacks_api.h
new file mode 100644 (file)
index 0000000..d22b9c7
--- /dev/null
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2012 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        popup_service_callbacks_api.h
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       Header with api of Popup Service callbacks
+ */
+
+#ifndef POPUP_SERVICE_CALLBACKS_API_H_
+#define POPUP_SERVICE_CALLBACKS_API_H_
+
+#include <string>
+#include <utility>
+#include "SocketConnection.h"
+#include "popup_response_server_api.h"
+#include "popup_service_callbacks.h"
+#include <callback_api.h>
+
+namespace WrtSecurity{
+namespace PopupServiceCallbacksApi{
+
+inline std::pair<std::string, socketServerCallback> VALIDATION_METHOD_CALLBACK(){
+    return std::make_pair(WrtSecurity::PopupServerApi::VALIDATION_METHOD(), RPC::PopupServiceCallbacks::validate);
+}
+
+} // namespace PopupServiceCallbacksApi
+} // namespace WrtSecurity
+
+#endif /* POPUP_SERVICE_CALLBACKS_API_H_ */
diff --git a/src/services/popup/socket/popup_service_callbacks.cpp b/src/services/popup/socket/popup_service_callbacks.cpp
new file mode 100644 (file)
index 0000000..d3e88e0
--- /dev/null
@@ -0,0 +1,90 @@
+/*
+ * Copyright (c) 2012 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        popup_service_callbacks.cpp
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       Implementation of Popup Service callbacks
+ */
+
+#include "popup_service_callbacks.h"
+#include <callback_api.h>
+#include <ace/Request.h>
+#include <ace-dao-ro/PromptModel.h>
+#include <dpl/log/log.h>
+#include "attribute_facade.h"
+#include "popup_ace_data_types.h"
+#include "security_controller.h"
+#include <security_caller.h>
+
+namespace RPC {
+
+void PopupServiceCallbacks::validate(SocketConnection * connector){
+
+    bool allowed = false;
+    int serializedValidity = 0;
+
+    AceUserdata acedata;
+
+    Try {
+        connector->read(&allowed,
+                        &serializedValidity,
+                        &(acedata.handle),
+                        &(acedata.subject),
+                        &(acedata.resource),
+                        &(acedata.paramKeys),
+                        &(acedata.paramValues),
+                        &(acedata.sessionId));
+    } Catch (SocketConnection::Exception::SocketConnectionException){
+        LogError("Socket connection read error");
+        ReThrowMsg(ServiceCallbackApi::Exception::ServiceCallbackException,
+                   "Socket connection read error");
+    }
+
+    if (acedata.paramKeys.size() != acedata.paramValues.size()) {
+        ThrowMsg(ServiceCallbackApi::Exception::ServiceCallbackException,
+                 "Varying sizes of parameter names vector and parameter values vector");
+    }
+    FunctionParamImpl params;
+    for (size_t i = 0; i < acedata.paramKeys.size(); ++i) {
+        params.addAttribute(acedata.paramKeys[i], acedata.paramValues[i]);
+    }
+    Request request(acedata.handle,
+                    WidgetExecutionPhase_Invoke,
+                    &params);
+    request.addDeviceCapability(acedata.resource);
+
+    Prompt::Validity validity = static_cast<Prompt::Validity>(serializedValidity);
+
+    bool response = false;
+    SecurityControllerEvents::ValidatePopupResponseEvent ev(
+        &request,
+        allowed,
+        validity,
+        acedata.sessionId,
+        &response);
+    SecurityCallerSingleton::Instance().SendSyncEvent(ev);
+
+    Try {
+        connector->write(response);
+    } Catch (SocketConnection::Exception::SocketConnectionException){
+        LogError("Socket connection write error");
+        ReThrowMsg(ServiceCallbackApi::Exception::ServiceCallbackException,
+                   "Socket connection write error");
+    }
+}
+
+} // namespace RPC
diff --git a/src/services/popup/socket/popup_service_callbacks.h b/src/services/popup/socket/popup_service_callbacks.h
new file mode 100644 (file)
index 0000000..e7d30f2
--- /dev/null
@@ -0,0 +1,36 @@
+/*
+ * Copyright (c) 2012 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        popup_service_callbacks.h
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       Header of Popup Service callbacks
+ */
+
+#ifndef POPUP_SERVICE_CALLBACKS_H_
+#define POPUP_SERVICE_CALLBACKS_H_
+
+#include <memory>
+#include <SocketConnection.h>
+
+namespace RPC {
+
+namespace PopupServiceCallbacks {
+    void validate(SocketConnection * connector);
+};
+
+} // namespace RPC
+#endif /* POPUP_SERVICE_CALLBACKS_H_ */
diff --git a/systemd/wrt-security-daemon.service b/systemd/wrt-security-daemon.service
new file mode 100644 (file)
index 0000000..96e140d
--- /dev/null
@@ -0,0 +1,13 @@
+
+[Unit]
+Description=Wrt security daemon
+Requires=wrt-security-daemon.socket
+
+[Service]
+Type=notify
+ExecStart=/usr/bin/wrt-security-daemon
+Restart=always
+RestartSec=0
+
+[Install]
+WantedBy=multi-user.target
diff --git a/systemd/wrt-security-daemon.socket b/systemd/wrt-security-daemon.socket
new file mode 100644 (file)
index 0000000..d5aa41f
--- /dev/null
@@ -0,0 +1,10 @@
+[Unit]
+Description=Wrt Security socket
+
+[Socket]
+ListenStream=/tmp/server
+SocketMode=0777
+PassCredentials=yes
+Accept=false
+SmackLabelIPIn=wrt-security-daemon
+SmackLabelIPOut=wrt-security-daemon
diff --git a/wrt_ocsp/CMakeLists.txt b/wrt_ocsp/CMakeLists.txt
new file mode 100644 (file)
index 0000000..e03d379
--- /dev/null
@@ -0,0 +1 @@
+ADD_SUBDIRECTORY(src)
\ No newline at end of file
diff --git a/wrt_ocsp/include/wrt_ocsp_api.h b/wrt_ocsp/include/wrt_ocsp_api.h
new file mode 100644 (file)
index 0000000..856d97b
--- /dev/null
@@ -0,0 +1,74 @@
+/*
+ *    Copyright (c) 2012 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        wrt_oscp_api.h
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       This is C api for WRT OCSP
+ */
+#ifndef WRT_OCSP_API_H
+#define WRT_OCSP_API_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef enum{
+  WRT_OCSP_OK,
+  WRT_OCSP_INVALID_ARGUMENTS,
+  WRT_OCSP_INTERNAL_ERROR
+}wrt_ocsp_return_t;
+
+typedef int wrt_ocsp_widget_handle_t;
+typedef enum {
+  //The certificate has not been revoked.
+  WRT_OCSP_WIDGET_VERIFICATION_STATUS_GOOD,
+
+  //The certificate has been revoked.
+  WRT_OCSP_WIDGET_VERIFICATION_STATUS_REVOKED
+
+
+}wrt_ocsp_widget_verification_status_t;
+
+//-------------Initialization and shutdown-------------------
+/*
+ * Establishes connection to security server. Must be called only once.
+ * Returns WRT_OCSP_OK or error
+ */
+wrt_ocsp_return_t wrt_ocsp_initialize(void);
+
+/*
+ * Deinitializes internal structures. Must be called only once.
+ * Returns WRT_OCSP_OK or error
+ */
+
+wrt_ocsp_return_t wrt_ocsp_shutdown(void);
+
+//-------------Widget verification------------------------------
+/*
+ * Requests verification for widget identified with 'handle'.
+ * 'status holds server response.
+ * Returns WRT_OCSP_OK or error
+ */
+
+wrt_ocsp_return_t wrt_ocsp_verify_widget(wrt_ocsp_widget_handle_t handle,
+                                         wrt_ocsp_widget_verification_status_t* status);
+
+
+#ifdef __cplusplus
+}
+#endif
+#endif //WRT_OCSP_API_H
diff --git a/wrt_ocsp/src/CMakeLists.txt b/wrt_ocsp/src/CMakeLists.txt
new file mode 100644 (file)
index 0000000..35bc91b
--- /dev/null
@@ -0,0 +1,60 @@
+include(FindPkgConfig)
+
+PKG_CHECK_MODULES(WRT_OCSP_DEPS
+    dpl-efl
+    dpl-dbus-efl
+    REQUIRED
+    )
+
+SET(WRT_OCSP_DIR
+    ${PROJECT_SOURCE_DIR}/wrt_ocsp
+    )
+
+SET(WRT_OCSP_SRC_DIR
+    ${WRT_OCSP_DIR}/src
+    )
+
+SET(WRT_OCSP_INCLUDE_DIR
+    ${WRT_OCSP_DIR}/include
+    )
+
+SET(WRT_OCSP_SOURCES
+    ${COMMUNICATION_CLIENT_SOURCES}
+    ${WRT_OCSP_SRC_DIR}/wrt_ocsp_api.cpp
+    )
+
+SET(WRT_OCSP_INCLUDES
+    ${WRT_OCSP_DEPS_INCLUDE_DIRS}
+    ${WRT_OCSP_INCLUDE_DIR}
+    ${COMMUNICATION_CLIENT_INCLUDES}
+    ${PROJECT_SOURCE_DIR}/src/services/ocsp
+    ${PROJECT_SOURCE_DIR}/src/services/ocsp/dbus/api
+    ${PROJECT_SOURCE_DIR}/src/daemon/dbus
+    )
+
+ADD_DEFINITIONS(${WRT_OCSP_DEPS_CFLAGS})
+ADD_DEFINITIONS(${WRT__CFLAGS_OTHER})
+
+INCLUDE_DIRECTORIES(${WRT_OCSP_INCLUDES})
+
+ADD_LIBRARY(${TARGET_WRT_OCSP_LIB} SHARED ${WRT_OCSP_SOURCES})
+
+SET_TARGET_PROPERTIES(${TARGET_WRT_OCSP_LIB} PROPERTIES
+    SOVERSION ${API_VERSION}
+    VERSION ${VERSION})
+
+SET_TARGET_PROPERTIES(${TARGET_WRT_OCSP_LIB} PROPERTIES
+    COMPILE_FLAGS -fPIC)
+
+TARGET_LINK_LIBRARIES(${TARGET_WRT_OCSP_LIB}
+    ${WRT_OCSP_DEPS_LIBRARIES}
+    ${WRT_OCSP_DEPS_LDFLAGS}
+    )
+
+INSTALL(TARGETS ${TARGET_WRT_OCSP_LIB}
+    DESTINATION ${LIB_INSTALL_DIR})
+
+INSTALL(FILES
+    ${WRT_OCSP_INCLUDE_DIR}/wrt_ocsp_api.h
+    DESTINATION include/wrt-ocsp
+    )
diff --git a/wrt_ocsp/src/wrt_ocsp_api.cpp b/wrt_ocsp/src/wrt_ocsp_api.cpp
new file mode 100644 (file)
index 0000000..8c1dd1a
--- /dev/null
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 2012 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        wrt_ocsp_api.cpp
+ * @author      Zofia Abramowska (z.abramowska@samsung.com)
+ * @version     1.0
+ * @brief       This file contains implementation of WRT OCSP api
+ */
+
+#include <dpl/log/log.h>
+#include <dpl/dbus/dbus_client.h>
+#include "ocsp_server_api.h"
+#include "SecurityCommunicationClient.h"
+
+#include "wrt_ocsp_api.h"
+
+static WrtSecurity::Communication::Client *communicationClient = NULL;
+
+wrt_ocsp_return_t wrt_ocsp_initialize(void){
+#ifdef __SUPPORT_OCSP__
+    if (NULL != communicationClient) {
+        LogError("wrt_ocsp_api already initialized");
+        return WRT_OCSP_INTERNAL_ERROR;
+    }
+
+    Try {
+        communicationClient = new WrtSecurity::Communication::Client(WrtSecurity::OcspServerApi::INTERFACE_NAME());
+    } Catch (WrtSecurity::Communication::Client::Exception::SecurityCommunicationClientException) {
+        LogError("Can't connect to daemon");
+        return WRT_OCSP_INTERNAL_ERROR;
+    }
+#endif
+    LogInfo("Initialized");
+    return WRT_OCSP_OK;
+}
+
+wrt_ocsp_return_t wrt_ocsp_shutdown(void){
+#ifdef __SUPPORT_OCSP__    
+    if (NULL == communicationClient) {
+        LogError("wrt_ocsp_api not initialized");
+        return WRT_OCSP_INTERNAL_ERROR;
+    }
+    delete communicationClient;
+    communicationClient = NULL;
+#endif
+    LogInfo("Shutdown");
+    return WRT_OCSP_OK;
+}
+
+wrt_ocsp_return_t wrt_ocsp_verify_widget(wrt_ocsp_widget_handle_t handle,
+                                         wrt_ocsp_widget_verification_status_t* status){
+
+    LogInfo("Verifying");
+    if (NULL == status) {
+        LogError("Invalid arguments");
+        return WRT_OCSP_INVALID_ARGUMENTS;
+    }
+    int intResponse;
+
+#ifdef __SUPPORT_OCSP__ 
+    Try {
+        communicationClient->call(WrtSecurity::OcspServerApi::CHECK_ACCESS_METHOD(),
+                                  handle,
+                                  &intResponse);
+    } Catch (WrtSecurity::Communication::Client::Exception::SecurityCommunicationClientException) {
+        LogError("Problem with connection to daemon");
+        return WRT_OCSP_INTERNAL_ERROR;
+    }
+#endif
+    intResponse = 0;
+    (*status) = static_cast<wrt_ocsp_widget_verification_status_t>(intResponse);
+    LogInfo("Widget verified with response " << intResponse);
+    return WRT_OCSP_OK;
+}