Tizen 2.0 Release
authorHyungKyu Song <hk76.song@samsung.com>
Fri, 15 Feb 2013 15:16:15 +0000 (00:16 +0900)
committerHyungKyu Song <hk76.song@samsung.com>
Fri, 15 Feb 2013 15:16:15 +0000 (00:16 +0900)
226 files changed:
AUTHORS [new file with mode: 0644]
CMakeLists.txt [new file with mode: 0644]
LICENSE.APLv2.0 [new file with mode: 0644]
NOTICE [new file with mode: 0755]
ace/CMakeLists.txt [new file with mode: 0644]
ace/DESCRIPTION [new file with mode: 0644]
ace/configuration/TizenPolicy.xml [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/security-server/CMakeLists.txt [new file with mode: 0644]
build/security-server/security-server.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]
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/certificates/CMakeLists.txt [new file with mode: 0644]
etc/certificates/orange.production.pem [new file with mode: 0644]
etc/certificates/tizen-developer-root-ca.pem [new file with mode: 0644]
etc/certificates/tizen-distributor-root-ca-partner.pem [new file with mode: 0644]
etc/certificates/tizen-distributor-root-ca-public.pem [new file with mode: 0644]
etc/certificates/tizen.root.preproduction.cert.pem [new file with mode: 0644]
etc/certificates/wac.publisherid.pem [new file with mode: 0644]
etc/certificates/wac.root.preproduction.pem [new file with mode: 0644]
etc/certificates/wac.root.production.pem [new file with mode: 0644]
etc/fingerprint_list.xml [new file with mode: 0644]
etc/fingerprint_list.xsd [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]
packaging/libsecurity-server-client.manifest [new file with mode: 0644]
packaging/security-server.manifest [new file with mode: 0644]
packaging/security-server.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/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/security-srv/CMakeLists.txt--original [new file with mode: 0644]
src/security-srv/client/security-server-client.c [new file with mode: 0644]
src/security-srv/communication/security-server-comm.c [new file with mode: 0644]
src/security-srv/include/SLP_security-model_PG.h [new file with mode: 0644]
src/security-srv/include/SLP_security-server_PG.h [new file with mode: 0644]
src/security-srv/include/security-server-comm.h [new file with mode: 0644]
src/security-srv/include/security-server-common.h [new file with mode: 0644]
src/security-srv/include/security-server-cookie.h [new file with mode: 0644]
src/security-srv/include/security-server-password.h [new file with mode: 0644]
src/security-srv/include/security-server-util.h [new file with mode: 0644]
src/security-srv/include/security-server.h [new file with mode: 0644]
src/security-srv/mw-list [new file with mode: 0644]
src/security-srv/security-serverd [new file with mode: 0644]
src/security-srv/server/security-server-cookie.c [new file with mode: 0644]
src/security-srv/server/security-server-main.c [new file with mode: 0644]
src/security-srv/server/security-server-password.c [new file with mode: 0644]
src/security-srv/util/security-server-util-common.c [new file with mode: 0644]
src/security-srv/util/security-server-util.c [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: 0644]
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]
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..402ac47
--- /dev/null
@@ -0,0 +1,142 @@
+# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES 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("security-server")
+
+############################# 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
+
+ADD_DEFINITIONS("-DSOCKET_CONNECTION")      #defines sockets as used IPC
+#ADD_DEFINITIONS("-DDBUS_CONNECTION")        #defines DBus as used IPC
+
+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 "security-server")
+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")
+SET(security-server-client "security-server-client")
+
+############################# 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(ace)
+ADD_SUBDIRECTORY(ace_client)
+ADD_SUBDIRECTORY(ace_common)
+ADD_SUBDIRECTORY(ace_install)
+ADD_SUBDIRECTORY(ace_settings)
+ADD_SUBDIRECTORY(ace_popup_validation)
+ADD_SUBDIRECTORY(communication_client)
+ADD_SUBDIRECTORY(wrt_ocsp)
+ADD_SUBDIRECTORY(src)
+ADD_SUBDIRECTORY(build)
+ADD_SUBDIRECTORY(etc)
+
diff --git a/LICENSE.APLv2.0 b/LICENSE.APLv2.0
new file mode 100644 (file)
index 0000000..467a417
--- /dev/null
@@ -0,0 +1,203 @@
+Copyright (c) 2010 - 2013 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 (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.
diff --git a/NOTICE b/NOTICE
new file mode 100755 (executable)
index 0000000..5719d03
--- /dev/null
+++ b/NOTICE
@@ -0,0 +1,3 @@
+Copyright (c) 2010 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
+Except as noted, this software is licensed under Apache License, Version 2.
+Please, see the LICENSE.APLv2.0 file for Apache License, Version 2 terms and conditions.
diff --git a/ace/CMakeLists.txt b/ace/CMakeLists.txt
new file mode 100644 (file)
index 0000000..4fbfcdf
--- /dev/null
@@ -0,0 +1,140 @@
+# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+######################################################################
+
+#DB vcore
+PKG_CHECK_MODULES(ACE_DB_DEP
+    dpl-efl
+    REQUIRED)
+
+#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"
+    )
+
+STRING(REPLACE ";" ":" DEPENDENCIES "${ACE_DB_DEP_INCLUDE_DIRS}")
+
+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 ${CMAKE_BINARY_DIR}/ace/database_checksum_ace.h ${PROJECT_SOURCE_DIR}/ace/orm/ace_db_sql_generator.h ${PROJECT_SOURCE_DIR}/ace/orm/ace_db
+  )
+
+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
+    ${CMAKE_CURRENT_SOURCE_DIR}/configuration/TizenPolicy.xml
+    DESTINATION /usr/etc/ace
+    PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ GROUP_WRITE)
+
+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
+    )
+
+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)
+
+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)
+
+TARGET_LINK_LIBRARIES(${TARGET_ACE_LIB}
+    ${TARGET_ACE_DAO_RW_LIB}
+    ${ACE_LIB_DEPS_LIBRARIES}
+)
+
+INSTALL(TARGETS ${TARGET_ACE_LIB}
+    DESTINATION lib)
+
+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/TizenPolicy.xml b/ace/configuration/TizenPolicy.xml
new file mode 100644 (file)
index 0000000..1f21ab3
--- /dev/null
@@ -0,0 +1,547 @@
+<policy-set id="Tizen-Policy" combine="first-matching-target">
+    <policy id="Tizen-Policy-Partner-API" description="Partner API" combine="permit-overrides">
+        <!-- Partner API. This is finger-print of tizen-distributor-root-ca-partner.pem -->
+        <target>
+            <subject>
+                <subject-match attr="distributor-key-root-fingerprint" func="equal">
+                    sha-1 67:37:DE:B7:B9:9D:D2:DB:A5:2C:42:DE:CB:2F:2C:3E:33:97:E1:85
+                </subject-match>
+            </subject>
+        </target>
+
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="tizen" />
+            </condition>
+        </rule>
+
+        <!-- access to application -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="application.kill" />
+                <resource-match attr="device-cap" func="equal" match="application.launch" />
+                <resource-match attr="device-cap" func="equal" match="application.read" />
+            </condition>
+        </rule>
+
+        <!-- access to bluetooth -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="bluetooth.admin" />
+                <resource-match attr="device-cap" func="equal" match="bluetooth.gap" />
+                <resource-match attr="device-cap" func="equal" match="bluetooth.spp" />
+            </condition>
+        </rule>
+
+        <!-- access to calendar -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="calendar.read" />
+                <resource-match attr="device-cap" func="equal" match="calendar.write" />
+            </condition>
+        </rule>
+
+        <!-- access to call history -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="callhistory.read" />
+                <resource-match attr="device-cap" func="equal" match="callhistory.write" />
+            </condition>
+        </rule>
+
+        <!-- access to contact -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="contact.read" />
+                <resource-match attr="device-cap" func="equal" match="contact.write" />
+            </condition>
+        </rule>
+
+        <!-- access to content -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="content.read" />
+                <resource-match attr="device-cap" func="equal" match="content.write" />
+            </condition>
+        </rule>
+
+        <!-- access to NFC -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="nfc.admin" />
+                <resource-match attr="device-cap" func="equal" match="nfc.tag" />
+                <resource-match attr="device-cap" func="equal" match="nfc.p2p" />
+                <resource-match attr="device-cap" func="equal" match="nfc.cardemulation" />
+                <resource-match attr="device-cap" func="equal" match="nfc.common" />
+            </condition>
+        </rule>
+
+        <!-- access to systeminfo -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="systeminfo" />
+            </condition>
+        </rule>
+
+        <!-- access to system setting -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="setting" />
+            </condition>
+        </rule>
+
+        <!-- access to download feature -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="download" />
+            </condition>
+        </rule>
+
+        <!-- access to power feature -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="power" />
+            </condition>
+        </rule>
+
+        <!-- access to push feature -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="push" />
+            </condition>
+        </rule>
+
+        <!-- access to timeutil -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="time" />
+            </condition>
+        </rule>
+
+        <!-- access to external network -->
+        <!-- XMLHttpRequestTizen and externalNetworkAccessTizen defined for Tizen Webapp -->
+        <!-- Function of two capabilities are same to XMLHttpRequest and externalNetworkAccess of WAC -->
+        <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>
+
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="alarm" />
+            </condition>
+        </rule>
+
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="log" />
+            </condition>
+        </rule>
+
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="messaging.read" />
+                <resource-match attr="device-cap" func="equal" match="messaging.write" />
+                <resource-match attr="device-cap" func="equal" match="messaging.send" />
+            </condition>
+        </rule>
+
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="filesystem.read" />
+                <resource-match attr="device-cap" func="equal" match="filesystem.write" />
+            </condition>
+        </rule>
+
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="notification.read" />
+                <resource-match attr="device-cap" func="equal" match="notification.write" />
+            </condition>
+        </rule>
+
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="networkbearerselection" />
+            </condition>
+        </rule>
+
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="datacontrol.consumer" />
+            </condition>
+        </rule>
+
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="se" />
+            </condition>
+        </rule>
+
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="account.read" />
+                               <resource-match attr="device-cap" func="equal" match="account.write" />
+            </condition>
+        </rule>
+
+        <rule effect="deny" />
+    </policy>
+    <policy id="Tizen-Policy-Trusted" description="Tizen's policy for trusted domain" combine="permit-overrides">
+        <!-- This is finger-print of certificate for TIZEN SDK (tizen.root.preproduction.cert.pem) --> 
+        <target>
+            <subject>
+                <subject-match attr="distributor-key-root-fingerprint" func="equal">
+                    sha-1 AD:A1:44:89:6A:35:6D:17:01:E9:6F:46:C6:00:7B:78:BE:2E:D9:4E
+                </subject-match>
+            </subject>
+        </target> 
+
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="tizen" />
+            </condition>
+        </rule>
+
+        <!-- access to application -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="application.launch" />
+                <resource-match attr="device-cap" func="equal" match="application.read" />
+            </condition>
+        </rule>
+
+        <!-- access to bluetooth -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="bluetooth.admin" />
+                <resource-match attr="device-cap" func="equal" match="bluetooth.gap" />
+                <resource-match attr="device-cap" func="equal" match="bluetooth.spp" />
+            </condition>
+        </rule>
+
+        <!-- access to calendar -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="calendar.read" />
+                <resource-match attr="device-cap" func="equal" match="calendar.write" />
+            </condition>
+        </rule>
+
+        <!-- access to call history -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="callhistory.read" />
+                <resource-match attr="device-cap" func="equal" match="callhistory.write" />
+            </condition>
+        </rule>
+
+        <!-- access to contact -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="contact.read" />
+                <resource-match attr="device-cap" func="equal" match="contact.write" />
+            </condition>
+        </rule>
+
+        <!-- access to content -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="content.read" />
+                <resource-match attr="device-cap" func="equal" match="content.write" />
+            </condition>
+        </rule>
+
+        <!-- access to NFC -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="nfc.admin" />
+                <resource-match attr="device-cap" func="equal" match="nfc.tag" />
+                <resource-match attr="device-cap" func="equal" match="nfc.p2p" />
+                <resource-match attr="device-cap" func="equal" match="nfc.cardemulation" />
+                <resource-match attr="device-cap" func="equal" match="nfc.common" />
+            </condition>
+        </rule>
+
+        <!-- access to systeminfo -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="systeminfo" />
+            </condition>
+        </rule>
+
+        <!-- access to system setting -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="setting" />
+            </condition>
+        </rule>
+
+        <!-- access to download feature -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="download" />
+            </condition>
+        </rule>
+
+        <!-- access to power feature -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="power" />
+            </condition>
+        </rule>
+
+        <!-- access to push feature -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="push" />
+            </condition>
+        </rule>
+
+        <!-- access to timeutil -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="time" />
+            </condition>
+        </rule>
+
+        <!-- access to external network -->
+        <!-- XMLHttpRequestTizen and externalNetworkAccessTizen defined for Tizen Webapp -->
+        <!-- Function of two capabilities are same to XMLHttpRequest and externalNetworkAccess of WAC -->
+        <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>
+
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="alarm" />
+            </condition>
+        </rule>
+
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="log" />
+            </condition>
+        </rule>
+
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="messaging.read" />
+                <resource-match attr="device-cap" func="equal" match="messaging.write" />
+                <resource-match attr="device-cap" func="equal" match="messaging.send" />
+            </condition>
+        </rule>
+
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="filesystem.read" />
+                <resource-match attr="device-cap" func="equal" match="filesystem.write" />
+            </condition>
+        </rule>
+
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="notification.read" />
+                <resource-match attr="device-cap" func="equal" match="notification.write" />
+            </condition>
+        </rule>
+
+        <rule effect="deny" />
+    </policy>
+
+    <policy id="Tizen-Policy-Untrusted" description="Tizen's policy for untrusted domain" combine="permit-overrides">
+        <!-- Specific Untrusted Policy for Tizen -->
+
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="tizen" />
+            </condition>
+        </rule>
+
+        <!-- access to application -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="application.launch" />
+                <resource-match attr="device-cap" func="equal" match="application.read" />
+            </condition>
+        </rule>
+
+        <!-- access to bluetooth -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="bluetooth.admin" />
+                <resource-match attr="device-cap" func="equal" match="bluetooth.gap" />
+                <resource-match attr="device-cap" func="equal" match="bluetooth.spp" />
+            </condition>
+        </rule>
+
+        <!-- access to calendar -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="calendar.read" />
+                <resource-match attr="device-cap" func="equal" match="calendar.write" />
+            </condition>
+        </rule>
+
+        <!-- access to call history -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="callhistory.read" />
+                <resource-match attr="device-cap" func="equal" match="callhistory.write" />
+            </condition>
+        </rule>
+
+        <!-- access to contact -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="contact.read" />
+                <resource-match attr="device-cap" func="equal" match="contact.write" />
+            </condition>
+        </rule>
+
+        <!-- access to content -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="content.read" />
+                <resource-match attr="device-cap" func="equal" match="content.write" />
+            </condition>
+        </rule>
+
+        <!-- access to NFC -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="nfc.admin" />
+                <resource-match attr="device-cap" func="equal" match="nfc.tag" />
+                <resource-match attr="device-cap" func="equal" match="nfc.p2p" />
+                <resource-match attr="device-cap" func="equal" match="nfc.cardemulation" />
+                <resource-match attr="device-cap" func="equal" match="nfc.common" />
+            </condition>
+        </rule>
+
+        <!-- access to systeminfo -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="systeminfo" />
+            </condition>
+        </rule>
+
+        <!-- access to system setting -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="setting" />
+            </condition>
+        </rule>
+
+        <!-- access to download feature -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="download" />
+            </condition>
+        </rule>
+
+        <!-- access to power feature -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="power" />
+            </condition>
+        </rule>
+
+        <!-- access to push feature -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="push" />
+            </condition>
+        </rule>
+
+        <!-- access to timeutil -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="time" />
+            </condition>
+        </rule>
+
+        <!-- access to external network -->
+        <!-- XMLHttpRequestTizen and externalNetworkAccessTizen defined for Tizen Webapp -->
+        <!-- Function of two capabilities are same to XMLHttpRequest and externalNetworkAccess of WAC -->
+        <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>
+
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="alarm" />
+            </condition>
+        </rule>
+
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="log" />
+            </condition>
+        </rule>
+
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="messaging.read" />
+                <resource-match attr="device-cap" func="equal" match="messaging.write" />
+                <resource-match attr="device-cap" func="equal" match="messaging.send" />
+            </condition>
+        </rule>
+
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="filesystem.read" />
+                <resource-match attr="device-cap" func="equal" match="filesystem.write" />
+            </condition>
+        </rule>
+
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="notification.read" />
+                <resource-match attr="device-cap" func="equal" match="notification.write" />
+            </condition>
+        </rule>
+
+        <rule effect="deny" />
+    </policy>
+</policy-set>
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..1a6e0ed
--- /dev/null
@@ -0,0 +1,169 @@
+<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..4d4ce06
--- /dev/null
@@ -0,0 +1,461 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES 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 DPL::OptionalString &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::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..61e5a86
--- /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) {
+        sprintf(&attrHashCoded[i << 1],
+                "%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..48e2c2b
--- /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 <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.IsNull() ? 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.IsNull() ? "" : 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.IsNull() ? "" : 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.IsNull() ? "" : 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::Optional<DPL::String> cn = it->Get_common_name();
+            out.push_back(cn.IsNull() ? "" : 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::Optional<DPL::String> sha1 = it->Get_sha1_fingerprint();
+            if (!sha1.IsNull())
+                keys.push_back(DPL::ToUTF8String(*sha1));
+            DPL::Optional<DPL::String> md5 = it->Get_md5_fingerprint();
+            if (!md5.IsNull())
+                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::Optional<DPL::String> value = rows.front().Get_share_href();
+        std::string ret = "";
+        if(!value.IsNull())
+            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..013608f
--- /dev/null
@@ -0,0 +1,82 @@
+
+SET(ACE_DAO_DEPS_LIST
+    dpl-efl
+    dpl-db-efl
+    ecore
+    appcore-efl
+    openssl
+    vconf
+    db-util
+    libpcrecpp
+    icu-uc
+    libxml-2.0
+    )
+
+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})
+
+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")
+target_link_libraries(${TARGET_ACE_DAO_RO_LIB}
+    ${TARGET_DPL_EFL}
+    ${TARGET_DPL_DB_EFL}
+    ${ACE_DAO_DEPS_LIBRARY}
+    ${ACE_DAO_DEPS_LDFLAGS}
+)
+
+ADD_LIBRARY(${TARGET_ACE_DAO_RW_LIB} SHARED
+    ${ACE_DAO_RW_SOURCES}
+)
+
+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(TARGETS ${TARGET_ACE_DAO_RW_LIB}
+    DESTINATION lib)
+
diff --git a/ace/dao/PromptModel.cpp b/ace/dao/PromptModel.cpp
new file mode 100644 (file)
index 0000000..ece84c6
--- /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::Null;
+}
+
+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..56cfc44
--- /dev/null
@@ -0,0 +1,886 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT 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");
+    } else if (result == MatchResult::MRFalse) {
+        LogDebug("Returning FALSE");
+    } else if (result == MatchResult::MRUndetermined) {
+        LogDebug("Returning UNDETERMINED");
+    }
+    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();
+    }
+
+    LogDebug("Comparing attribute: " << this->m_name << "(" <<
+        myVal << ") with: " << tempNam <<
+        "(" << tempVal << ")");
+
+    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);
+    re.FullMatch(input->c_str(), &val[0], &val[1],
+                 &val[2], &val[3], &val[4],
+                 &val[5], &val[6], &val[7], &val[8]);
+
+#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..bbd179c
--- /dev/null
@@ -0,0 +1,333 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT 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)
+{
+    LogDebug("Effects to be combined with algorithm: " << ::toString(algorithm));
+    showEffectList(effects);
+
+    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..e6121a4
--- /dev/null
@@ -0,0 +1,236 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES 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;
+
+    LogDebug("Attributes to be matched");
+    printAttributes(*attrSet);
+    LogDebug("Condition attributes values");
+    printAttributes(attributes);
+
+    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..f1edffb
--- /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.
+ */
+#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>
+
+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 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 ""; }
+    }
+
+    return storagePath + fileName;
+}
+
+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;
+}
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..73d2f6e
--- /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.IsNull()) {
+        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.IsNull()
+                    && "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.IsNull()) {
+            if (!fromCacheOnly) {
+                LogError("Policy evaluated to NULL value");
+                Assert(false && "Policy evaluated to NULL value");
+            }
+            return OptionalExtendedPolicyResult::Null;
+        }
+        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..039ada6
--- /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.
+ */
+#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()
+{
+}
+
+//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..fa9ae36
--- /dev/null
@@ -0,0 +1,744 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT 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!");
+        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);
+
+    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);
+
+    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);
+
+    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;
+    //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*
+    std::string temp(reinterpret_cast<const char *>(attrName));
+    Attribute * 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;
+    }
+
+    std::string temp(reinterpret_cast<const char*>(attrName));
+    Attribute * 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); //unreachable statement
+}
+
+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;
+    }
+}
+
+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..6fb9a83
--- /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 <dpl/shared_ptr.h>
+#include <dpl/assert.h>
+
+namespace AceDB {
+
+class BaseAttribute;
+typedef DPL::SharedPtr<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..5a01cfe
--- /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       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 DPL::OptionalString &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 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..ede3792
--- /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.
+ */
+
+#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>
+#include <dpl/event/inter_context_delegate.h>
+
+class AbstractPolicyEnforcementPoint
+{
+  public:
+    typedef DPL::Event::ICDelegate<PolicyResult> ResponseReceiver;
+    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..e15d343
--- /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.
+ */
+#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 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..ec9d9f0
--- /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        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_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..902587a
--- /dev/null
@@ -0,0 +1,96 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT 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>
+
+//#include <dpl/optional.h>
+#include <dpl/event/inter_context_delegate.h>
+#include <dpl/event/property.h>
+
+#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..e9c9285
--- /dev/null
@@ -0,0 +1,153 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT 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>
+
+#include <dpl/event/event_listener.h>
+#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..f59fe80
--- /dev/null
@@ -0,0 +1,259 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT 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.h>
+#include <dpl/optional_typedefs.h>
+
+#include <ace/PolicyEffect.h>
+
+typedef DPL::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)
+    {}
+
+    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
+    {}
+
+    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 DPL::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..bfe425b
--- /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 <dpl/optional.h>
+#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 DPL::Optional<PromptDecision> OptionalPromptDecision;
+
+struct CachedPromptDecision {
+    PromptDecision decision;
+    DPL::OptionalString session;
+};
+
+typedef DPL::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..09d15f8
--- /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.
+ */
+//
+//  @ Project : Access Control Engine
+//  @ File Name : UserDecision.h
+//  @ Date : 2009-05-22
+//  @ Author : Samsung
+//
+//
+
+#ifndef _WIDGET_USAGE_H
+#define _WIDGET_USAGE_H
+
+#include <dpl/event/event_support.h>
+
+#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..4b4081b
--- /dev/null
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES 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;
+    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..817a988
--- /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(const ace_request_t* request, ace_bool_t* access);
+
+#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..72a7f56
--- /dev/null
@@ -0,0 +1,71 @@
+include(FindPkgConfig)
+
+PKG_CHECK_MODULES(ACE_CLIENT_DEPS
+    dpl-efl
+    dpl-event-efl
+    dpl-dbus-efl
+    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(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..16d9f36
--- /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        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 <dpl/dbus/dbus_client.h>
+#include "popup_response_server_api.h"
+#include "security_daemon_dbus_config.h"
+//#include "PromptModel.h"
+
+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(const ace_request_t* request, ace_bool_t* access)
+{
+    if (NULL == request || NULL == access) {
+        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);
+        *access = ret ? ACE_TRUE : ACE_FALSE;
+    } 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..3c4d086
--- /dev/null
@@ -0,0 +1,665 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES 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/optional.h>
+#include <dpl/string.h>
+#include <dpl/optional_typedefs.h>
+#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>
+
+// 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;
+    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;
+    DPL::Optional<std::set<DPL::String>> m_grantedDevCaps;
+    std::set<std::string> m_acceptedFeatures;
+};
+
+AceThinClientImpl::AceThinClientImpl()
+  : m_communicationClient(NULL),
+    m_popupValidationClient(NULL),
+    m_wrt(new WebRuntimeImpl()),
+    m_res(new ResourceInformationImpl()),
+    m_sys(new OperationSystemImpl()),
+    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::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.IsNull()) {
+        m_grantedDevCaps = std::set<DPL::String>();
+        m_acceptedFeatures.clear();
+
+        AceDB::FeatureNameVector fvector;
+        AceDB::AceDAOReadOnly::getAcceptedFeature(ace_request.widgetHandle, &fvector);
+        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.IsNull()) {
+                // 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.IsNull()) {
+                    // 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.IsNull()) {
+                // 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.IsNull()) {
+        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.IsNull()) {
+            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);
+}
+
+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..30fee60
--- /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        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_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..598b96d
--- /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.
+ */
+/*
+ * @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);
+
+// ---------------- 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..d0757e1
--- /dev/null
@@ -0,0 +1,62 @@
+include(FindPkgConfig)
+
+PKG_CHECK_MODULES(ACE_INSTALL_DEPS
+    dpl-efl
+    dpl-dbus-efl
+    REQUIRED
+    )
+
+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})
+
+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)
+
+TARGET_LINK_LIBRARIES(${TARGET_ACE_INSTALL_LIB}
+    ${ACE_INSTALL_DEPS_LIBRARIES}
+    ${TARGET_ACE_DAO_RW_LIB}
+    )
+
+INSTALL(TARGETS ${TARGET_ACE_INSTALL_LIB}
+    DESTINATION lib)
+
+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..eca3305
--- /dev/null
@@ -0,0 +1,345 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES 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);
+        caps->items[i].device_capability =
+                new char[strlen(devCapRequested.c_str())+1];
+        strcpy(caps->items[i].device_capability, devCapRequested.c_str());
+        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_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.IsNull()) {
+       *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..69fe495
--- /dev/null
@@ -0,0 +1,62 @@
+include(FindPkgConfig)
+
+PKG_CHECK_MODULES(ACE_POPUP_VALIDATION_DEPS
+    dpl-efl
+    dpl-dbus-efl
+    REQUIRED
+    )
+
+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})
+
+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)
+
+TARGET_LINK_LIBRARIES(${TARGET_ACE_POPUP_VALIDATION_LIB}
+    ${ACE_POPUP_VALIDATION_DEPS_LIBRARIES} ${ACE_POPUP_VALIDATION_DEPS_LDFLAGS}
+    )
+
+INSTALL(TARGETS ${TARGET_ACE_POPUP_VALIDATION_LIB}
+    DESTINATION lib)
+
+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..8277c2f
--- /dev/null
@@ -0,0 +1,135 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES 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"
+#include "security_daemon_dbus_config.h"
+#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..8cd835e
--- /dev/null
@@ -0,0 +1,56 @@
+include(FindPkgConfig)
+
+PKG_CHECK_MODULES(ACE_SETTINGS_DEPS
+    dpl-efl
+    REQUIRED
+    )
+
+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})
+
+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)
+
+TARGET_LINK_LIBRARIES(${TARGET_ACE_SETTINGS_LIB}
+    ${ACE_SETTINGS_DEPS_LIBRARIES}
+    ${TARGET_ACE_DAO_RW_LIB}
+    )
+
+INSTALL(TARGETS ${TARGET_ACE_SETTINGS_LIB}
+    DESTINATION lib)
+
+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..c51d065
--- /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)
+#
+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)
+ADD_SUBDIRECTORY(security-server)
+ADD_SUBDIRECTORY(wrt_ocsp)
diff --git a/build/ace/CMakeLists.txt b/build/ace/CMakeLists.txt
new file mode 100644 (file)
index 0000000..b42ab2e
--- /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/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..820a4b3
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=@CMAKE_INSTALL_PREFIX@
+exec_prefix=${prefix}
+libdir=${prefix}/lib
+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..4268970
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=@CMAKE_INSTALL_PREFIX@
+exec_prefix=${prefix}
+libdir=${prefix}/lib
+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..9f5bd4a
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=@CMAKE_INSTALL_PREFIX@
+exec_prefix=${prefix}
+libdir=${prefix}/lib
+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..b7bdaa0
--- /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/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..ea166b3
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=@CMAKE_INSTALL_PREFIX@
+exec_prefix=${prefix}
+libdir=${prefix}/lib
+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..8c0a70b
--- /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/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..9ddcefa
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=@CMAKE_INSTALL_PREFIX@
+exec_prefix=${prefix}
+libdir=${prefix}/lib
+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..b79c6f5
--- /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/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..385b47b
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=@CMAKE_INSTALL_PREFIX@
+exec_prefix=${prefix}
+libdir=${prefix}/lib
+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..b768f2f
--- /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/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..1abc082
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=@CMAKE_INSTALL_PREFIX@
+exec_prefix=${prefix}
+libdir=${prefix}/lib
+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..4f11913
--- /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/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..1b01b5f
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=@CMAKE_INSTALL_PREFIX@
+exec_prefix=${prefix}
+libdir=${prefix}/lib
+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/security-server/CMakeLists.txt b/build/security-server/CMakeLists.txt
new file mode 100644 (file)
index 0000000..d65dd3a
--- /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      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+# @brief
+#
+
+CONFIGURE_FILE(security-server.pc.in security-server.pc @ONLY)
+
+INSTALL(FILES
+    ${CMAKE_BINARY_DIR}/build/security-server/security-server.pc
+    DESTINATION
+    lib/pkgconfig
+    )
diff --git a/build/security-server/security-server.pc.in b/build/security-server/security-server.pc.in
new file mode 100644 (file)
index 0000000..df49caf
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=@CMAKE_INSTALL_PREFIX@
+exec_prefix=${prefix}
+libdir=${prefix}/lib
+includedir=${prefix}/include
+
+Name: security-server
+Description: Security Server Package
+Version: 1.0.1
+Requires: openssl libsmack
+Libs: -L${libdir} -lsecurity-server-client -lsmack
+Cflags: -I${includedir}/security-server
diff --git a/build/wrt-security/CMakeLists.txt b/build/wrt-security/CMakeLists.txt
new file mode 100644 (file)
index 0000000..9995265
--- /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/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..7f63cc5
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=@CMAKE_INSTALL_PREFIX@
+exec_prefix=${prefix}
+libdir=${prefix}/lib
+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..7b1bf5f
--- /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/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..2fb4258
--- /dev/null
@@ -0,0 +1,11 @@
+prefix=@CMAKE_INSTALL_PREFIX@
+exec_prefix=${prefix}
+libdir=${prefix}/lib
+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/communication_client/include/SecurityCommunicationClient.h b/communication_client/include/SecurityCommunicationClient.h
new file mode 100644 (file)
index 0000000..8244c60
--- /dev/null
@@ -0,0 +1,108 @@
+/*
+ * 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_
+
+#include <dpl/dbus/dbus_client.h>
+#include <dpl/log/log.h>
+#include <dpl/scoped_ptr.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..13b137e
--- /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        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
+
+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
+    LogInfo("Created 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
+      LogInfo("Connected");
+  }
+
+  void Client::disconnect(){
+
+    #ifdef SOCKET_CONNECTION
+      m_socketClient->disconnect();
+    #endif //SOCKET_CONNECTION
+    LogInfo("Disconnected");
+  }
+
+
+} // namespace Communication
+
+} // namespace WrtSecurity
+
diff --git a/etc/CMakeLists.txt b/etc/CMakeLists.txt
new file mode 100644 (file)
index 0000000..93fc6b3
--- /dev/null
@@ -0,0 +1,25 @@
+
+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
+    )
+
+INSTALL(FILES
+    ${ETC_DIR}/fingerprint_list.xsd
+    DESTINATION share/wrt-engine/
+    )
+
+INSTALL(FILES
+    ${ETC_DIR}/fingerprint_list.xml
+    DESTINATION share/wrt-engine/
+    )
+
+ADD_SUBDIRECTORY(certificates)
diff --git a/etc/certificates/CMakeLists.txt b/etc/certificates/CMakeLists.txt
new file mode 100644 (file)
index 0000000..27774cd
--- /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        CMakeLists.txt
+# @author      Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+# @author      Yunchan Cho (yunchan.cho@samsung.com)
+# @version     1.0
+# @brief
+#
+
+SET(CERT_DIR ${PROJECT_SOURCE_DIR}/etc/certificates)
+
+INSTALL(FILES
+    ${CERT_DIR}/wac.root.preproduction.pem
+    ${CERT_DIR}/wac.root.production.pem
+    ${CERT_DIR}/wac.publisherid.pem
+    ${CERT_DIR}/tizen.root.preproduction.cert.pem
+    ${CERT_DIR}/tizen-developer-root-ca.pem
+    ${CERT_DIR}/tizen-distributor-root-ca-partner.pem
+    ${CERT_DIR}/tizen-distributor-root-ca-public.pem
+    DESTINATION /opt/share/cert-svc/certs/code-signing/wac/
+    )
diff --git a/etc/certificates/orange.production.pem b/etc/certificates/orange.production.pem
new file mode 100644 (file)
index 0000000..888967d
--- /dev/null
@@ -0,0 +1,13 @@
+-----BEGIN CERTIFICATE-----
+MIICVTCCAb6gAwIBAgIETdzAMDANBgkqhkiG9w0BAQUFADBvMQswCQYDVQQGEwJHQjERMA8GA1UE
+CBMITm9ybWFuZHkxDTALBgNVBAcTBENBRU4xDzANBgNVBAoTBk9yYW5nZTETMBEGA1UECxMKT3Jh
+bmdlTGFiczEYMBYGA1UEAxMPT3JhbmdlTGFicyBDQUVOMB4XDTExMDUyNTA4MzkxMloXDTM2MDUx
+ODA4MzkxMlowbzELMAkGA1UEBhMCR0IxETAPBgNVBAgTCE5vcm1hbmR5MQ0wCwYDVQQHEwRDQUVO
+MQ8wDQYDVQQKEwZPcmFuZ2UxEzARBgNVBAsTCk9yYW5nZUxhYnMxGDAWBgNVBAMTD09yYW5nZUxh
+YnMgQ0FFTjCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAj9130ZtpXp/679/2pmFldFgjz5tN
+CjLT6CEWC9yketyKgyV1c0DBMcy4PNLdOb0VxhfcNXNYoBylCp6mPj3mWRM5VSet03XA8k6/L0T4
+dYicYGaIojowhzBBfaIXnBDvMQD5kanC5CDd6HtFzQbBkN73NIdGrR/aFqNtC/wopFECAwEAATAN
+BgkqhkiG9w0BAQUFAAOBgQCIjZYXTdsMCpIYENX6UyD/EM+SZBkVvoB2R8ghRZbKHOcr58ZyGvdH
+i/Y0hp5zNN7bUQurEMWtIxF+s3oaYH0x9xwXCd5UEV9Y+dmD1/qlK7lfSlC7mwynHs3bhMEGOJF2
+TlDzZyVYBIT3LQjfq6G18bGHkwU3uTsxZMSgtz5LgQ==
+-----END CERTIFICATE-----
diff --git a/etc/certificates/tizen-developer-root-ca.pem b/etc/certificates/tizen-developer-root-ca.pem
new file mode 100644 (file)
index 0000000..76c003c
--- /dev/null
@@ -0,0 +1,17 @@
+-----BEGIN CERTIFICATE-----
+MIICnzCCAggCCQCn+GGT4zh+BjANBgkqhkiG9w0BAQUFADCBkzELMAkGA1UEBhMC
+S1IxDjAMBgNVBAgMBVN1d29uMQ4wDAYDVQQHDAVTdXdvbjEWMBQGA1UECgwNVGl6
+ZW4gVGVzdCBDQTElMCMGA1UECwwcVGl6ZW4gVGVzdCBEZXZlbG9wZXIgUm9vdCBD
+QTElMCMGA1UEAwwcVGl6ZW4gVGVzdCBEZXZlbG9wZXIgUm9vdCBDQTAeFw0xMjEw
+MjYwOTUwMTNaFw0yMjEwMjQwOTUwMTNaMIGTMQswCQYDVQQGEwJLUjEOMAwGA1UE
+CAwFU3V3b24xDjAMBgNVBAcMBVN1d29uMRYwFAYDVQQKDA1UaXplbiBUZXN0IENB
+MSUwIwYDVQQLDBxUaXplbiBUZXN0IERldmVsb3BlciBSb290IENBMSUwIwYDVQQD
+DBxUaXplbiBUZXN0IERldmVsb3BlciBSb290IENBMIGfMA0GCSqGSIb3DQEBAQUA
+A4GNADCBiQKBgQDWT6ZH5JyGadTUK1QmNwU8j+py4WtuElJE+4/wPFP8/KBmvvmI
+rGVjhUbKXToKIo8N6C/0SLxGEWuRAIoZHhg5JVbw1Ay7smgJJHizDUAqMTmV6LI9
+yTFbBV+OlO2Dir4LVdQ/XDBiqqslr7pqXgsg1V2g7x+tOI/f3dn2kWoVZQIDAQAB
+MA0GCSqGSIb3DQEBBQUAA4GBADGJYMtzUBDK+KKLZQ6zYmrKb+OWLlmEr/t/c2af
+KjTKUtommcz8VeTPqrDBOwxlVPdxlbhisCYzzvwnWeZk1aeptxxU3kdW9N3/wocN
+5nBzgqkkHJnj/ptqjrH2v/m0Z3hBuI4/akHIIfCBF8mUHwqcxYsRdcCIrkgp2Aiv
+bSaM
+-----END CERTIFICATE-----
diff --git a/etc/certificates/tizen-distributor-root-ca-partner.pem b/etc/certificates/tizen-distributor-root-ca-partner.pem
new file mode 100644 (file)
index 0000000..2be6916
--- /dev/null
@@ -0,0 +1,17 @@
+-----BEGIN CERTIFICATE-----
+MIICozCCAgwCCQD9IBoOxzq2hjANBgkqhkiG9w0BAQUFADCBlTELMAkGA1UEBhMC
+S1IxDjAMBgNVBAgMBVN1d29uMQ4wDAYDVQQHDAVTdXdvbjEWMBQGA1UECgwNVGl6
+ZW4gVGVzdCBDQTEiMCAGA1UECwwZVGl6ZW4gRGlzdHJpYnV0b3IgVGVzdCBDQTEq
+MCgGA1UEAwwhVGl6ZW4gUGFydG5lciBEaXN0cmlidXRvciBSb290IENBMB4XDTEy
+MTAyNjA4MTIzMVoXDTIyMTAyNDA4MTIzMVowgZUxCzAJBgNVBAYTAktSMQ4wDAYD
+VQQIDAVTdXdvbjEOMAwGA1UEBwwFU3V3b24xFjAUBgNVBAoMDVRpemVuIFRlc3Qg
+Q0ExIjAgBgNVBAsMGVRpemVuIERpc3RyaWJ1dG9yIFRlc3QgQ0ExKjAoBgNVBAMM
+IVRpemVuIFBhcnRuZXIgRGlzdHJpYnV0b3IgUm9vdCBDQTCBnzANBgkqhkiG9w0B
+AQEFAAOBjQAwgYkCgYEAnIBA2qQEaMzGalP0kzvwUxdCC6ybSC/fb+M9iGvt8QXp
+ic2yARQB+bIhfbEu1XHwE1jCAGxKd6uT91b4FWr04YwnBPoRX4rBGIYlqo/dg+pS
+rGyFjy7vfr0BOdWp2+WPlTe7SOS6bVauncrSoHxX0spiLaU5LU686BKr7YaABV0C
+AwEAATANBgkqhkiG9w0BAQUFAAOBgQAX0Tcfmxcs1TUPBdr1U1dx/W/6Y4PcAF7n
+DnMrR0ZNRPgeSCiVLax1bkHxcvW74WchdKIb24ZtAsFwyrsmUCRV842YHdfddjo6
+xgUu7B8n7hQeV3EADh6ft/lE8nalzAl9tALTxAmLtYvEYA7thvDoKi1k7bN48izL
+gS9G4WEAUg==
+-----END CERTIFICATE-----
diff --git a/etc/certificates/tizen-distributor-root-ca-public.pem b/etc/certificates/tizen-distributor-root-ca-public.pem
new file mode 100644 (file)
index 0000000..9b16176
--- /dev/null
@@ -0,0 +1,17 @@
+-----BEGIN CERTIFICATE-----
+MIICozCCAgwCCQD9XW6kNg4bbjANBgkqhkiG9w0BAQUFADCBlTELMAkGA1UEBhMC
+S1IxDjAMBgNVBAgMBVN1d29uMQ4wDAYDVQQHDAVTdXdvbjEWMBQGA1UECgwNVGl6
+ZW4gVGVzdCBDQTEjMCEGA1UECwwaVFRpemVuIERpc3RyaWJ1dG9yIFRlc3QgQ0Ex
+KTAnBgNVBAMMIFRpemVuIFB1YmxpYyBEaXN0cmlidXRvciBSb290IENBMB4XDTEy
+MTAyNjA4MDAyN1oXDTIyMTAyNDA4MDAyN1owgZUxCzAJBgNVBAYTAktSMQ4wDAYD
+VQQIDAVTdXdvbjEOMAwGA1UEBwwFU3V3b24xFjAUBgNVBAoMDVRpemVuIFRlc3Qg
+Q0ExIzAhBgNVBAsMGlRUaXplbiBEaXN0cmlidXRvciBUZXN0IENBMSkwJwYDVQQD
+DCBUaXplbiBQdWJsaWMgRGlzdHJpYnV0b3IgUm9vdCBDQTCBnzANBgkqhkiG9w0B
+AQEFAAOBjQAwgYkCgYEA8o0kPY1U9El1BbBUF1k4jCq6mH8a6MmDJdjgsz+hILAY
+sPWimRTXUcW8GAUWhZWgm1Fbb49xWcasA8b4bIJabC/6hLb8uWiozzpRXyQJbe7k
+//RocskRqDmFOky8ANFsCCww72/Xbq8BFK1sxlGdmOWQiGwDWBDlS2Lw1XOMqb0C
+AwEAATANBgkqhkiG9w0BAQUFAAOBgQBUotZqTNFr+SNyqeZqhOToRsg3ojN1VJUa
+07qdlVo5I1UObSE+UTJPJ0NtSj7OyTY7fF3E4xzUv/w8aUoabQP1erEmztY/AVD+
+phHaPytkZ/Dx+zDZ1u5e9bKm5zfY4dQs/A53zDQta5a/NkZOEF97Dj3+bzAh2bP7
+KOszlocFYw==
+-----END CERTIFICATE-----
diff --git a/etc/certificates/tizen.root.preproduction.cert.pem b/etc/certificates/tizen.root.preproduction.cert.pem
new file mode 100644 (file)
index 0000000..bbf523b
--- /dev/null
@@ -0,0 +1,60 @@
+Certificate:
+    Data:
+        Version: 3 (0x2)
+        Serial Number:
+            b3:cb:d1:5b:de:6e:66:95
+        Signature Algorithm: sha1WithRSAEncryption
+        Issuer: C=KR, ST=Suwon, O=Samsung Electronics, OU=SLP, CN=SLP WebApp Temporary CA/emailAddress=yunchan.cho@samsung.com
+        Validity
+            Not Before: Dec  8 10:27:32 2011 GMT
+            Not After : Nov 30 10:27:32 2021 GMT
+        Subject: C=KR, ST=Suwon, O=Samsung Electronics, OU=SLP, CN=SLP WebApp Temporary CA/emailAddress=yunchan.cho@samsung.com
+        Subject Public Key Info:
+            Public Key Algorithm: rsaEncryption
+                Public-Key: (1024 bit)
+                Modulus:
+                    00:cb:46:b8:94:81:b1:83:d7:29:05:2a:33:01:9e:
+                    66:15:f8:be:bb:95:17:dd:7a:c4:c2:f5:d9:e4:aa:
+                    fd:c8:8d:a9:48:65:fc:3d:dc:47:d7:2a:2f:5e:c7:
+                    1f:22:ed:e0:98:e6:43:6d:74:82:ca:7d:22:9c:60:
+                    44:18:cd:ca:d6:6b:16:ca:ed:63:c9:7a:f1:00:df:
+                    e4:6b:33:47:2f:78:75:61:d7:c9:29:3e:a9:ee:76:
+                    dd:2e:fe:9d:e7:3c:0d:02:f4:e9:2d:46:74:49:52:
+                    ef:a0:d6:9d:4d:08:65:ea:6b:35:72:a5:08:d8:46:
+                    46:03:99:7c:66:8c:60:c4:91
+                Exponent: 65537 (0x10001)
+        X509v3 extensions:
+            X509v3 Subject Key Identifier: 
+                47:A8:8F:CD:1F:22:BA:69:85:13:55:21:2D:C2:19:2D:5F:FF:DC:03
+            X509v3 Authority Key Identifier: 
+                keyid:47:A8:8F:CD:1F:22:BA:69:85:13:55:21:2D:C2:19:2D:5F:FF:DC:03
+
+            X509v3 Basic Constraints: 
+                CA:TRUE
+    Signature Algorithm: sha1WithRSAEncryption
+        c2:c4:62:f2:ec:6f:2b:05:9c:09:cc:ae:e9:77:a9:1d:66:6b:
+        03:7b:01:3a:e6:29:bb:2a:b8:15:d8:a1:7d:9b:05:b4:8c:cb:
+        ae:c7:eb:68:c0:e3:29:c7:e7:5a:ca:1a:0c:3a:ab:91:80:4f:
+        9b:36:d4:45:b4:7b:2c:ef:f3:fd:cb:84:84:85:42:3d:ec:18:
+        3f:5f:9e:b1:1f:8d:0a:57:89:51:e4:eb:7e:da:e9:79:82:61:
+        38:ad:ca:94:43:71:00:73:13:b9:e9:ef:bc:68:c5:ff:5e:0a:
+        f6:b9:2a:3d:1d:21:77:22:d0:4e:e7:ad:da:31:0b:51:fa:44:
+        cd:fa
+-----BEGIN CERTIFICATE-----
+MIIC9jCCAl+gAwIBAgIJALPL0VvebmaVMA0GCSqGSIb3DQEBBQUAMIGTMQswCQYD
+VQQGEwJLUjEOMAwGA1UECAwFU3V3b24xHDAaBgNVBAoME1NhbXN1bmcgRWxlY3Ry
+b25pY3MxDDAKBgNVBAsMA1NMUDEgMB4GA1UEAwwXU0xQIFdlYkFwcCBUZW1wb3Jh
+cnkgQ0ExJjAkBgkqhkiG9w0BCQEWF3l1bmNoYW4uY2hvQHNhbXN1bmcuY29tMB4X
+DTExMTIwODEwMjczMloXDTIxMTEzMDEwMjczMlowgZMxCzAJBgNVBAYTAktSMQ4w
+DAYDVQQIDAVTdXdvbjEcMBoGA1UECgwTU2Ftc3VuZyBFbGVjdHJvbmljczEMMAoG
+A1UECwwDU0xQMSAwHgYDVQQDDBdTTFAgV2ViQXBwIFRlbXBvcmFyeSBDQTEmMCQG
+CSqGSIb3DQEJARYXeXVuY2hhbi5jaG9Ac2Ftc3VuZy5jb20wgZ8wDQYJKoZIhvcN
+AQEBBQADgY0AMIGJAoGBAMtGuJSBsYPXKQUqMwGeZhX4vruVF916xML12eSq/ciN
+qUhl/D3cR9cqL17HHyLt4JjmQ210gsp9IpxgRBjNytZrFsrtY8l68QDf5GszRy94
+dWHXySk+qe523S7+nec8DQL06S1GdElS76DWnU0IZeprNXKlCNhGRgOZfGaMYMSR
+AgMBAAGjUDBOMB0GA1UdDgQWBBRHqI/NHyK6aYUTVSEtwhktX//cAzAfBgNVHSME
+GDAWgBRHqI/NHyK6aYUTVSEtwhktX//cAzAMBgNVHRMEBTADAQH/MA0GCSqGSIb3
+DQEBBQUAA4GBAMLEYvLsbysFnAnMrul3qR1mawN7ATrmKbsquBXYoX2bBbSMy67H
+62jA4ynH51rKGgw6q5GAT5s21EW0eyzv8/3LhISFQj3sGD9fnrEfjQpXiVHk637a
+6XmCYTitypRDcQBzE7np77xoxf9eCva5Kj0dIXci0E7nrdoxC1H6RM36
+-----END CERTIFICATE-----
diff --git a/etc/certificates/wac.publisherid.pem b/etc/certificates/wac.publisherid.pem
new file mode 100644 (file)
index 0000000..758fe66
--- /dev/null
@@ -0,0 +1,24 @@
+-----BEGIN CERTIFICATE-----
+MIID9DCCAtygAwIBAgIOZscBAQACO65mNg72468wDQYJKoZIhvcNAQEFBQAwgZQx
+CzAJBgNVBAYTAkRFMRwwGgYDVQQKExNUQyBUcnVzdENlbnRlciBHbWJIMTEwLwYD
+VQQLEyhQcmUtUHJvZHVjdGlvbiBUQyBUcnVzdENlbnRlciBDbGFzcyAyIENBMTQw
+MgYDVQQDEytQcmUtUHJvZHVjdGlvbiBUQyBUcnVzdENlbnRlciBDbGFzcyAyIENB
+IElJMB4XDTA2MDYwODE0MTYwMVoXDTI1MTIzMTIyNTk1OVowgZQxCzAJBgNVBAYT
+AkRFMRwwGgYDVQQKExNUQyBUcnVzdENlbnRlciBHbWJIMTEwLwYDVQQLEyhQcmUt
+UHJvZHVjdGlvbiBUQyBUcnVzdENlbnRlciBDbGFzcyAyIENBMTQwMgYDVQQDEytQ
+cmUtUHJvZHVjdGlvbiBUQyBUcnVzdENlbnRlciBDbGFzcyAyIENBIElJMIIBIjAN
+BgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3Ewnr8E24AqXnf1Lu7w/g79Hht+W
+lvWQg7cPC7685oj0htT0SmDy94uQaC3qRzBJktLKCyuniABykhdTr04rGWgzqD8n
+EzcFCt5k0gF39l3ND/JL+S2YJK/f/xc884hjcLsHUU7cAd6mDlVkOszFK86DNbu0
+noz0y1y462RIOvPCjkYl/GJ5zL62bdDbgFqrWMPZ54JFG0Rj1v575ygfOd2LwOXe
+xjzqfYI4JOx9frKWakPTehW+0UY5UdF0cMvHuLJie9H0vOobR4vtkenbS283b6j7
+0WCoU/BeAr4qskvMs9WwkwDquO4XnzYQDsEVgjBu4H2W0ihNUYJbRo8wtQIDAQAB
+o0IwQDAPBgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBhjAdBgNVHQ4EFgQU
+DTX6+fYyziPR1HZxViaGOj66QOYwDQYJKoZIhvcNAQEFBQADggEBALZ0pfjOfePn
+D/6QDCt+cjQ5+U4eKcOlJMXrpEAlnC6oAnN1hqbOQaj44aIAbNap36E/Hl9s0Uga
+c4nz73o5uPvdDmbWzNnMz6ey5NU0XXNzHxQWFdb0+Z7Cho5txoZjjynYXmyQc3RJ
+rrPI+6Uej6sEv15ZGirjABza6pNJ+2NLojLyUb+8et3OCLS+wJ4qrX/5uwgL50Lt
+0M2iPdZv+gjZwNmNWYIflYrSXa3ujclH+EAkkk/G1JxPzhVI3cII3y2DUZQAPCcX
+XQDXIX2zJo7bYaUYJhlEeiGX17cdXMXDT1tbXKKg2mRIga1K4lknn9U/vzkjMJXL
+GA38dUZRZ2Y=
+-----END CERTIFICATE-----
diff --git a/etc/certificates/wac.root.preproduction.pem b/etc/certificates/wac.root.preproduction.pem
new file mode 100644 (file)
index 0000000..7c46a6a
--- /dev/null
@@ -0,0 +1,22 @@
+-----BEGIN CERTIFICATE-----
+MIIDijCCAnKgAwIBAgIOMwoBAQAuBBKsIqIni7QwDQYJKoZIhvcNAQELBQAwYDEL
+MAkGA1UEBhMCR0IxJTAjBgNVBAoMHFdBQyBBcHBsaWNhdGlvbiBTZXJ2aWNlcyBM
+dGQxKjAoBgNVBAMMIVdBQyBBcHBsaWNhdGlvbiBTZXJ2aWNlcyBMdGQgVEVTVDAe
+Fw0xMTAzMDMxNTA3MTlaFw0zNjAzMDMxNTA3MTlaMGAxCzAJBgNVBAYTAkdCMSUw
+IwYDVQQKDBxXQUMgQXBwbGljYXRpb24gU2VydmljZXMgTHRkMSowKAYDVQQDDCFX
+QUMgQXBwbGljYXRpb24gU2VydmljZXMgTHRkIFRFU1QwggEiMA0GCSqGSIb3DQEB
+AQUAA4IBDwAwggEKAoIBAQC1PB3UrpAQgLSVqHRPhHqdDJsjKQe/CT9oS4lA+mI/
+vkhAvam/EvcNrNHcLVvSph+Mj0d2Y2J9wkcNW7fS3qZJXtpMNU36r7XdBk9kiYhc
+PwJbckCo9Pp8YFxkuR6xV6Cc4o54mO2mumxDQ1hbwCsc5CT7yQz0FVVhCE01X6JJ
+D61DvqmAzCUpehmEXthNV/s/o8fL+I2mD75p8vNDyIZHSJX59czO3PriT3tH2h+0
+tQx7NEWG70fQEU2CzcH9UngPYU7xXqNOhT9GmI/yL3HTeYGNH3i5VHrBjxeTF11t
+IWSUDWQX1W0Y7TbN06XcGcuqPgjZ9xMcV7S4OiCBJz5nAgMBAAGjQjBAMA8GA1Ud
+EwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBQp5dzy2tJEArpT
+qcQWNXG6J7y5WTANBgkqhkiG9w0BAQsFAAOCAQEAoXuyi8AjMx2yKVpss7xpVi5v
+aUjcHU3AlptjNCFrXI6Bw+KJGNo8ydYlEASRd5dL/pJ6/V+UuUt9EngjUSdYOZGB
+OgCeB2sJI8EZSay2LLhOCmkAxltC94Y/KRzkKqsYvNc6yvF85d+d4gbokf4APjmR
+1TSlZLZsVhwfR0k0mer2rHQGE5Ljezdk7ZGeEMLdn6WFScwjo980EI0OqEoJU3on
++1TTBYudZ4o3qMgHiFwJafUJ6i3zuYbi9x86zMqeI4dJTbsTKLM0QV8vIdzI9fkV
+t1tO/uBBAsNFUv8PAYwP4AFyGvyJbR4uxwxuQZKrltgjSTkPGYR14JtrGk7Y9g==
+-----END CERTIFICATE-----
+
diff --git a/etc/certificates/wac.root.production.pem b/etc/certificates/wac.root.production.pem
new file mode 100644 (file)
index 0000000..efccefd
--- /dev/null
@@ -0,0 +1,22 @@
+-----BEGIN CERTIFICATE-----
+MIIDgTCCAmmgAwIBAgIPAKTxAAEALtiV8/+rhB6+MA0GCSqGSIb3DQEBCwUAMFsx
+CzAJBgNVBAYTAkdCMSUwIwYDVQQKDBxXQUMgQXBwbGljYXRpb24gU2VydmljZXMg
+THRkMSUwIwYDVQQDDBxXQUMgQXBwbGljYXRpb24gU2VydmljZXMgTHRkMB4XDTEx
+MDMxNDE0MDEwNFoXDTM2MDMxNDE0MDEwNFowWzELMAkGA1UEBhMCR0IxJTAjBgNV
+BAoMHFdBQyBBcHBsaWNhdGlvbiBTZXJ2aWNlcyBMdGQxJTAjBgNVBAMMHFdBQyBB
+cHBsaWNhdGlvbiBTZXJ2aWNlcyBMdGQwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw
+ggEKAoIBAQDCf6RHUPVBUY4YXYMdrmt5yO95eRCOG6vJtI9w0UM2w/2fihD5SMYa
+3cCVam4j6F8FSspMIx+4CTCwdDSUixBGENwGEhD4qxqqV3KTObmxmYbELa97S1IP
+qwoFelzUX6e+qHmYHi+eu/hONeiZaPBLtUtCd6ppCd5ACrD/kf/Ug/tfUtngozjG
+sJ1UB10Ezi3fKs3OkkZMuecJvjWmDpRAyvIeeV8xfzeyn+DMpvhnI9RrSY0j4huE
+ud6Lzzg0jV8+m54v0j7hv9klyNcGiZ+bmHr0LIyAtT+uktcms/4p3V9j01SI9Tmw
+HcHKDXnM6kuThWpr6DR9KFSZ8zD2Nx5nAgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMB
+Af8wDgYDVR0PAQH/BAQDAgEGMB0GA1UdDgQWBBT5bKdU2+CGE17R+o/rMCZHHMn+
+WzANBgkqhkiG9w0BAQsFAAOCAQEAXmO+J5suIGuzbfYBoTdr8gahFfWEbhm1y6mJ
+eZAc+Mf5L+In20p+Oj5uy6LsTmJsE9VE/+gi1eALKl9EhgYhET2ZlAzRFCN5dTWv
+NTAFxJfGMkn2U5iW+luJ+lejyYBqEEFRpzwhXZbVDZQLim4CU75H75KzFkUgTulG
+5M6U/Plt6S1rKgMkeYiR27W4C2NZMFXYqctt0m+eKEa3ueZE9pYUxqVcvQKSI017
+Nbc1kSkcuSKFV2Bk2T5dh5jQvywykdWLubAe6XiiC5CIT31kcSX6AlVhgNxWRRKP
+QFO7lWqxnQMR2Or38ve7oSg1oL5Sx80fcbp3ovaYSKt5jnVWfg==
+-----END CERTIFICATE-----
+
diff --git a/etc/fingerprint_list.xml b/etc/fingerprint_list.xml
new file mode 100644 (file)
index 0000000..640c75a
--- /dev/null
@@ -0,0 +1,29 @@
+<CertificateSet>
+    <CertificateDomain name="wacpublisher">                                                           <!-- this domain is used to verify author-signatures -->
+        <FingerprintSHA1>AF:90:29:D2:B2:E1:6F:D6:7E:7E:EC:8E:BE:74:FA:4C:00:9C:49:FE</FingerprintSHA1><!-- root.cert.pem w3c signature tests -->
+        <FingerprintSHA1>A6:00:BC:53:AC:37:5B:6A:03:C3:7A:8A:E0:1B:87:8B:82:94:9B:C2</FingerprintSHA1><!-- wac.publisher.pem -->
+        <FingerprintSHA1>C2:C4:B5:72:9A:CF:D9:72:C5:DE:C1:E1:30:FF:74:7F:7A:AF:27:12</FingerprintSHA1><!-- root_cacert.pem certificate for internal tests -->
+        <FingerprintSHA1>2B:A0:20:7D:40:90:1D:00:04:89:60:00:3B:DE:34:89:21:BE:D4:4F</FingerprintSHA1><!-- tizen-developer-root-ca.pem -->
+    </CertificateDomain>
+    <CertificateDomain name="wacroot">
+        <FingerprintSHA1>AF:90:29:D2:B2:E1:6F:D6:7E:7E:EC:8E:BE:74:FA:4C:00:9C:49:FE</FingerprintSHA1><!-- root.cert.pem w3c signature tests -->
+        <FingerprintSHA1>C2:C4:B5:72:9A:CF:D9:72:C5:DE:C1:E1:30:FF:74:7F:7A:AF:27:12</FingerprintSHA1><!-- root_cacert.pem certificate for internal tests -->
+        <FingerprintSHA1>A0:59:D3:37:E8:C8:2E:7F:38:84:7D:21:A9:9E:19:A9:8E:EC:EB:E1</FingerprintSHA1><!-- wac.root.production.pem -->
+        <FingerprintSHA1>8D:1F:CB:31:68:11:DA:22:59:26:58:13:6C:C6:72:C9:F0:DE:84:2A</FingerprintSHA1><!-- wac.root.preproduction.pem -->
+        <FingerprintSHA1>84:A8:85:67:1C:D9:A9:C9:8C:7C:C3:BC:7F:EB:A6:7D:44:94:D9:8F</FingerprintSHA1><!-- tizen-distributor-root-ca-public.pem -->
+    </CertificateDomain>
+    <CertificateDomain name="developer">
+        <FingerprintSHA1>4A:9D:7A:4B:3B:29:D4:69:0A:70:B3:80:EC:A9:44:6B:03:7C:9A:38</FingerprintSHA1><!-- operator.root.cert.pem internal tests-->
+    </CertificateDomain>
+    <CertificateDomain name="wacmember">
+    </CertificateDomain>
+    <CertificateDomain name="tizenmember">                                                            <!-- used to verify tizen widgets -->
+        <FingerprintSHA1>67:37:DE:B7:B9:9D:D2:DB:A5:2C:42:DE:CB:2F:2C:3E:33:97:E1:85</FingerprintSHA1><!-- tizen-distributor-root-ca-partner.pem -->
+        <FingerprintSHA1>04:C5:A6:1D:75:BB:F5:5C:0F:A2:66:F6:09:4D:9B:2B:5F:3B:44:AE</FingerprintSHA1><!-- tizen-distributor-root-ca-public.pem -->
+        <FingerprintSHA1>AD:A1:44:89:6A:35:6D:17:01:E9:6F:46:C6:00:7B:78:BE:2E:D9:4E</FingerprintSHA1><!-- tizen.root.preproduction.cert.pem for internal test of SDK -->
+        <FingerprintSHA1>FE:11:C7:FB:38:2E:90:3A:F4:41:80:EE:28:40:61:C2:56:7D:0B:BD</FingerprintSHA1><!-- orange.production.pem - hash from it is encoded on sim cards -->
+    </CertificateDomain>
+    <CertificateDomain name="orangelegacy">
+        <FingerprintSHA1>FE:11:C7:FB:38:2E:90:3A:F4:41:80:EE:28:40:61:C2:56:7D:0B:BD</FingerprintSHA1><!-- orange.production.pem - This certificate requires special treatment during verification process -->
+    </CertificateDomain>
+</CertificateSet>
diff --git a/etc/fingerprint_list.xsd b/etc/fingerprint_list.xsd
new file mode 100644 (file)
index 0000000..b0fab23
--- /dev/null
@@ -0,0 +1,21 @@
+<?xml version="1.0" encoding="utf-8"?>
+<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema">
+
+<xs:element name="CertificateSet" type="CertificateSetType" />
+<xs:complexType name="CertificateSetType">
+  <xs:sequence>
+    <xs:element ref="CertificateDomain" minOccurs="0" maxOccurs="unbounded" />
+  </xs:sequence>
+</xs:complexType>
+
+<xs:element name="CertificateDomain" type="CertificateDomainType" />
+<xs:complexType name="CertificateDomainType">
+  <xs:sequence>
+    <xs:element ref="FingerprintSHA1" minOccurs="0" maxOccurs="unbounded" />
+  </xs:sequence>
+  <xs:attribute name="name" type="xs:string" use="required" />
+</xs:complexType>
+
+<xs:element name="FingerprintSHA1" type="xs:string"/>
+
+</xs:schema>
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..dce9880
--- /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;" | sqlite3 /opt/dbspace/.ace.db
+echo "delete from AceAttribute where 1==1;" | sqlite3 /opt/dbspace/.ace.db
+echo "delete from AcePromptDecision where 1==1;" | sqlite3 /opt/dbspace/.ace.db
+pkill -9 security-ser
+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..ead4467
--- /dev/null
@@ -0,0 +1,31 @@
+#!/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
+done
+
+
diff --git a/packaging/libsecurity-server-client.manifest b/packaging/libsecurity-server-client.manifest
new file mode 100644 (file)
index 0000000..a76fdba
--- /dev/null
@@ -0,0 +1,5 @@
+<manifest>
+       <request>
+               <domain name="_" />
+       </request>
+</manifest>
diff --git a/packaging/security-server.manifest b/packaging/security-server.manifest
new file mode 100644 (file)
index 0000000..4117683
--- /dev/null
@@ -0,0 +1,12 @@
+<manifest>
+       <define>
+               <domain name="security-server" />
+               <provide>
+                       <label name="security-server::daemon" />
+                       <label name="security-server::db" />
+               </provide>
+       </define>
+       <request>
+               <domain name="_" />
+       </request>
+</manifest>
diff --git a/packaging/security-server.spec b/packaging/security-server.spec
new file mode 100644 (file)
index 0000000..8fe40a0
--- /dev/null
@@ -0,0 +1,185 @@
+#sbs-git:slp/pkgs/s/security-server security-server 0.0.37
+Name:       security-server
+Summary:    Security server and utilities
+Version:    0.0.61
+Release:    1
+Group:      TO_BE/FILLED_IN
+License:    Apache License, Version 2.0
+URL:        N/A
+Source0:    %{name}-%{version}.tar.gz
+Source1:    security-server.manifest
+Source2:    libsecurity-server-client.manifest
+BuildRequires: cmake
+BuildRequires: zip
+BuildRequires: pkgconfig(dlog)
+BuildRequires: pkgconfig(openssl)
+BuildRequires: libattr-devel
+BuildRequires: pkgconfig(libsmack)
+BuildRequires: pkgconfig(dbus-1)
+BuildRequires: pkgconfig(dpl-efl)
+BuildRequires: pkgconfig(dpl-utils-efl)
+BuildRequires: pkgconfig(dpl-dbus-efl)
+BuildRequires: pkgconfig(libpcrecpp)
+BuildRequires: pkgconfig(icu-i18n)
+BuildRequires: pkgconfig(libsoup-2.4)
+BuildRequires: pkgconfig(xmlsec1)
+
+%description
+Security server and utilities
+
+%package -n libsecurity-server-client
+Summary:    Security server (client)
+Group:      Development/Libraries
+Requires:   security-server = %{version}-%{release}
+Requires(post): /sbin/ldconfig
+Requires(postun): /sbin/ldconfig
+
+%description -n libsecurity-server-client
+Security server package (client)
+
+
+%package -n libsecurity-server-client-devel
+Summary:    Security server (client-devel)
+Group:      Development/Libraries
+Requires:   libsecurity-server-client = %{version}-%{release}
+
+%description -n libsecurity-server-client-devel
+Security server package (client-devel)
+
+%package -n security-server-devel
+Summary:    for web applications (Development)
+Group:      Development/Libraries
+Requires:   security-server = %{version}-%{release}
+
+%description -n security-server-devel
+Security daemon for web applications (Development)
+
+%package -n security-server-certs
+Summary:    Certificates for web applications.
+Group:      Development/Libraries
+Requires:   security-server
+
+%description -n security-server-certs
+Certificates for wrt.
+
+%prep
+%setup -q
+
+%build
+export LDFLAGS+="-Wl,--rpath=%{_prefix}/lib"
+
+cmake . -DCMAKE_INSTALL_PREFIX=%{_prefix} \
+        -DDPL_LOG="ON"                    \
+        -DVERSION=%{version}              \
+        -DCMAKE_BUILD_TYPE=%{?build_type:%build_type}
+make %{?jobs:-j%jobs}
+
+
+%install
+rm -rf %{buildroot}
+mkdir -p %{buildroot}/usr/share/license
+cp LICENSE.APLv2.0 %{buildroot}/usr/share/license/%{name}
+cp LICENSE.APLv2.0 %{buildroot}/usr/share/license/libsecurity-server-client
+%make_install
+install -D %{SOURCE1} %{buildroot}%{_datadir}/security-server.manifest
+install -D %{SOURCE2} %{buildroot}%{_datadir}/libsecurity-server-client.manifest
+
+%clean
+rm -rf %{buildroot}
+
+
+%post
+mkdir -p /etc/rc.d/rc3.d
+mkdir -p /etc/rc.d/rc5.d
+ln -s /etc/rc.d/init.d/security-serverd /etc/rc.d/rc3.d/S10security-server
+ln -s /etc/rc.d/init.d/security-serverd /etc/rc.d/rc5.d/S10security-server
+
+if [ -z ${2} ]; 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
+
+echo "[WRT] wrt-security postinst done ..."
+
+%postun
+rm -f /etc/rc.d/rc3.d/S10security-server
+rm -f /etc/rc.d/rc5.d/S10security-server
+
+%post -n libsecurity-server-client -p /sbin/ldconfig
+
+%postun -n libsecurity-server-client -p /sbin/ldconfig
+
+
+%files -n security-server
+%manifest %{_datadir}/security-server.manifest
+%defattr(-,root,root,-)
+/usr/share/security-server/mw-list
+%attr(755,root,root) /etc/rc.d/init.d/security-serverd
+#/etc/rc.d/rc3.d/S10security-server
+#/etc/rc.d/rc5.d/S10security-server
+%attr(755,root,root) /usr/bin/security-server
+#/usr/bin/sec-svr-util
+%{_libdir}/libace*.so
+%{_libdir}/libace*.so.*
+%{_libdir}/libwrt-ocsp.so
+%{_libdir}/libwrt-ocsp.so.*
+/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
+%attr(664,root,root) /usr/etc/ace/TizenPolicy.xml
+%{_datadir}/license/%{name}
+
+#%files -n security-server-certs
+%attr(664,root,root) /opt/share/cert-svc/certs/code-signing/wac/wac.publisherid.pem
+%attr(664,root,root) /opt/share/cert-svc/certs/code-signing/wac/tizen.root.preproduction.cert.pem
+%attr(664,root,root) /opt/share/cert-svc/certs/code-signing/wac/wac.root.production.pem
+%attr(664,root,root) /opt/share/cert-svc/certs/code-signing/wac/wac.root.preproduction.pem
+%attr(664,root,root) /opt/share/cert-svc/certs/code-signing/wac/tizen-developer-root-ca.pem
+%attr(664,root,root) /opt/share/cert-svc/certs/code-signing/wac/tizen-distributor-root-ca-partner.pem
+%attr(664,root,root) /opt/share/cert-svc/certs/code-signing/wac/tizen-distributor-root-ca-public.pem
+
+%files -n libsecurity-server-client
+%manifest %{_datadir}/libsecurity-server-client.manifest
+%defattr(-,root,root,-)
+/usr/lib/libsecurity-server-client.so.*
+%{_datadir}/license/libsecurity-server-client
+
+%files -n libsecurity-server-client-devel
+%defattr(-,root,root,-)
+/usr/lib/libsecurity-server-client.so
+/usr/include/security-server/security-server.h
+/usr/lib/pkgconfig/security-server.pc
+%{_includedir}/wrt-security/*
+%{_includedir}/ace/*
+%{_includedir}/ace-client/*
+%{_includedir}/ace-settings/*
+%{_includedir}/ace-install/*
+%{_includedir}/ace-common/*
+%{_includedir}/ace-popup-validation/*
+%{_includedir}/wrt-ocsp/*
+%{_libdir}/pkgconfig/*.pc
diff --git a/socket_connection/client/SecuritySocketClient.cpp b/socket_connection/client/SecuritySocketClient.cpp
new file mode 100644 (file)
index 0000000..4c33102
--- /dev/null
@@ -0,0 +1,75 @@
+/*
+ * 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 "SecuritySocketClient.h"
+#include "security_daemon_socket_config.h"
+
+void SecuritySocketClient::throwWithErrnoMessage(const std::string& specificInfo){
+    LogError(specificInfo << " : " << strerror(errno));
+    ThrowMsg(Exception::SecuritySocketClientException, specificInfo << " : " << strerror(errno));
+}
+
+SecuritySocketClient::SecuritySocketClient(const std::string& interfaceName) {
+    m_interfaceName = interfaceName;
+    m_serverAddress = WrtSecurity::SecurityDaemonSocketConfig::SERVER_ADDRESS();
+    LogInfo("Client created");
+}
+
+void SecuritySocketClient::connect(){
+    struct sockaddr_un remote;
+    if(-1 == (m_socketFd = socket(AF_UNIX, SOCK_STREAM,0))){
+        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))){
+        throwWithErrnoMessage("fcntl");
+    }
+
+    bzero(&remote, sizeof(remote));
+    remote.sun_family = AF_UNIX;
+    strcpy(remote.sun_path, m_serverAddress.c_str());
+    if(-1 == ::connect(m_socketFd, (struct sockaddr *)&remote, SUN_LEN(&remote))){
+        throwWithErrnoMessage("connect()");
+    }
+
+    m_socketConnector.reset(new SocketConnection(m_socketFd));
+
+    LogInfo("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);
+    LogInfo("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..4ef8bca
--- /dev/null
@@ -0,0 +1,166 @@
+/*
+ * 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 <dpl/log/log.h>
+#include "SocketStream.h"
+
+#define READ_TIEMOUT_SEC 60
+#define READ_TIMEUOT_NSEC 0
+#define WRITE_TIMEOUT_SEC 60
+#define WRITE_TIMEOUT_NSEC 0
+#define MAX_BUFFER 10240
+
+void SocketStream::throwWithErrnoMessage(std::string function_name){
+    LogError(function_name << " : " << strerror(errno));
+    ThrowMsg(Exception::SocketStreamException, function_name << " : " << strerror(errno));
+}
+
+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;
+
+    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");
+            ThrowMsg(Exception::SocketStreamException, "Couldn't read whole data");
+        }
+        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){
+                    LogInfo("Connection closed : " << strerror(errno));
+                    ThrowMsg(Exception::SocketStreamException,
+                            "Connection closed : " << strerror(errno) << ". 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;
+
+    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){
+                    LogInfo("Connection closed : " << strerror(errno));
+                    ThrowMsg(Exception::SocketStreamException,
+                            "Connection closed : " << strerror(errno) << ". 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..17d1d28
--- /dev/null
@@ -0,0 +1,190 @@
+# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES 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
+    dlog
+    openssl
+    libsmack
+  )
+
+IF(SMACK_ENABLE)
+    LIST(APPEND DAEMON_BASIC_DEP libprivilege-control)
+ENDIF(SMACK_ENABLE)
+
+PKG_CHECK_MODULES(DAEMON_DEP
+    ${DAEMON_BASIC_DEP}
+    REQUIRED)
+
+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")
+
+SET(LEGACY_DAEMON_SOURCES
+    #security-server
+    ${DAEMON_SOURCES_PATH}/security-srv/communication/security-server-comm.c
+    ${DAEMON_SOURCES_PATH}/security-srv/server/security-server-cookie.c
+    ${DAEMON_SOURCES_PATH}/security-srv/server/security-server-main.c
+    ${DAEMON_SOURCES_PATH}/security-srv/server/security-server-password.c
+    ${DAEMON_SOURCES_PATH}/security-srv/util/security-server-util-common.c)
+
+SET_SOURCE_FILES_PROPERTIES(${LEGACY_DAEMON_SOURCES}
+    PROPERTIES COMPILE_FLAGS "-DSECURITY_SERVER_DEBUG_DLOG")
+
+SET(DAEMON_SOURCES
+    ${DAEMON_SOURCES}
+    #security-server
+    ${LEGACY_DAEMON_SOURCES})
+
+SET_SOURCE_FILES_PROPERTIES(
+    ${DAEMON_SOURCES_PATH}/security-srv/communication/security-server-comm.c
+    PROPERTIES COMPILE_FLAGS "-D_GNU_SOURCE")
+
+
+############################# Lets start compilation process ##################
+#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})
+#security-server
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/security-srv/include)
+
+
+
+ADD_EXECUTABLE(${TARGET_DAEMON}
+    ${DAEMON_SOURCES})
+
+TARGET_LINK_LIBRARIES(${TARGET_DAEMON}
+    ${DAEMON_DEP_LIBRARIES}
+    ${TARGET_ACE_LIB}
+    ${TARGET_ACE_DAO_RW_LIB})
+
+
+
+###################################################################################################
+## for libsecurity-server-client.so (library)
+pkg_check_modules(pkgs REQUIRED dlog openssl libsmack)
+
+SET(VERSION_MAJOR 1)
+SET(VERSION ${VERSION_MAJOR}.0.1)
+
+SET(libsecurity-server-client_SOURCES
+    ${DAEMON_SOURCES_PATH}/security-srv/client/security-server-client.c
+    ${DAEMON_SOURCES_PATH}/security-srv/communication/security-server-comm.c)
+SET(libsecurity-server-client_LDFLAGS " -module -avoid-version")
+SET(libsecurity-server-client_CFLAGS  " ${CFLAGS} -fPIC -I${sec_svr_include_dir} ${debug_type} -D_GNU_SOURCE ")
+#SET(libsecurity-server-client_LIBADD "")
+
+ADD_LIBRARY(security-server-client SHARED ${libsecurity-server-client_SOURCES})
+TARGET_LINK_LIBRARIES(security-server-client ${pkgs_LDFLAGS})
+SET_TARGET_PROPERTIES(security-server-client PROPERTIES SOVERSION ${VERSION_MAJOR})
+SET_TARGET_PROPERTIES(security-server-client PROPERTIES VERSION ${VERSION})
+SET_TARGET_PROPERTIES(security-server-client PROPERTIES COMPILE_FLAGS "${libsecurity-server-client_CFLAGS}")
+###################################################################################################
+
+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
+    )
+
+INSTALL(FILES
+    ${PROJECT_SOURCE_DIR}/src/security-srv/include/security-server.h
+    DESTINATION /usr/include/security-server
+    )
+
+INSTALL(FILES
+    ${PROJECT_SOURCE_DIR}/src/security-srv/mw-list
+    DESTINATION /usr/share/security-server/)
+
+INSTALL(FILES
+    ${PROJECT_SOURCE_DIR}/src/security-srv/security-serverd
+    DESTINATION /etc/rc.d/init.d)
+
+INSTALL(TARGETS security-server-client DESTINATION lib)
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..891bde6
--- /dev/null
@@ -0,0 +1,3 @@
+[D-BUS Service]
+Name=org.tizen.SecurityDaemon
+Exec=/usr/bin/security-server
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..7beba55
--- /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(),
+                  [&m_connection] (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..7f93e4f
--- /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        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>
+
+#include <dpl/framework_efl.h>
+
+#include <dpl/singleton_impl.h>
+IMPLEMENT_SINGLETON(SecurityDaemon::SecurityDaemon)
+
+#include <ace-dao-rw/AceDAO.h>
+
+namespace SecurityDaemon {
+
+//This is declared not in SecurityDaemon class, so no Ecore.h is needed there.
+static Ecore_Event_Handler *g_exitHandler;
+static Eina_Bool exitHandler(void */*data*/, int /*type*/, void */*event*/)
+{
+    auto& daemon = SecurityDaemonSingleton::Instance();
+    daemon.terminate(0);
+
+    return ECORE_CALLBACK_CANCEL;
+}
+
+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");
+
+    g_exitHandler = ecore_event_handler_add(ECORE_EVENT_SIGNAL_EXIT,
+                                            &exitHandler,
+                                            NULL);
+
+    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();
+    }
+    ecore_main_loop_begin();
+    return m_returnValue;
+}
+
+void SecurityDaemon::terminate(int returnValue)
+{
+    Assert(m_initialized && "Not Initialized");
+    Assert(!m_terminating && "Already terminating");
+    LogDebug("Terminating");
+
+    ecore_event_handler_del(g_exitHandler);
+
+    m_returnValue = returnValue;
+    m_terminating = true;
+
+    FOREACH (service, m_servicesList) {
+        (*service)->stop();
+    }
+
+    ecore_main_loop_quit();
+}
+
+void SecurityDaemon::shutdown()
+{
+    LogDebug("Shutdown");
+    Assert(m_initialized && "Not Initialized");
+    Assert(m_terminating && "Not terminated");
+
+    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..689de1c
--- /dev/null
@@ -0,0 +1,384 @@
+/*
+ * 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 <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 <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 TIMEOUT_SEC 0
+#define TIMEOUT_NSEC 100000000
+#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;
+}
+
+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");
+
+    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;
+    strcpy(server_address.sun_path, m_serverAddress.c_str());
+    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(){
+
+    if(listen(m_listenFd, MAX_LISTEN) == -1){
+        throwWithErrnoMessage("listen()");
+    }
+
+    //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);
+    timespec timeout;
+    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);
+
+    while(1){
+        timeout.tv_sec = TIMEOUT_SEC;
+        timeout.tv_nsec = TIMEOUT_NSEC;
+        rset = allset;
+        if(-1 == pselect(maxfd, &rset, NULL, NULL, &timeout, NULL)){
+            closeConnections();
+            throwWithErrnoMessage("pselect()");
+        }
+
+        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;
+            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()");
+            }
+            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);
+    LogInfo("Starting connection thread");
+    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;
+    }
+    LogInfo("Client serviced");
+    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");
+    }
+
+    LogDebug("Got interface : " << interfaceName);
+    LogDebug("Got method : " << methodName);
+
+    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");
+        }
+    }
+
+    LogInfo("Calling service");
+    Try{
+        m_callbackMap[interfaceName][methodName]->serviceCallback(&connector);
+    } Catch (ServiceCallbackApi::Exception::ServiceCallbackException){
+        LogError("Service callback error");
+        ReThrowMsg(DPL::Exception, "Service callback error");
+    }
+
+    LogInfo("Removing client");
+    removeClientSocket(fd);
+    close(fd);
+
+    LogInfo("Call served");
+
+}
+
+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..882d0e5
--- /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        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:
+
+  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..4b16270
--- /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        main.cpp
+ * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
+ * @version     1.0
+ * @brief       This is main routing for Security Daemon
+ */
+
+#include <dpl/log/log.h>
+#include <dpl/single_instance.h>
+
+#include "security_daemon.h"
+
+#include <pthread.h>
+
+static const std::string DAEMON_INSTANCE_UUID =
+    "5ebf3f24-dad6-4a27-88b4-df7970efe7a9";
+
+extern "C" void *security_server_main_thread(void *data);
+
+int main(int argc, char* argv[])
+{
+
+    pthread_t main_thread;
+
+    if (0 != pthread_create(&main_thread, NULL, security_server_main_thread, NULL)) {
+        LogError("Cannot create security server thread");
+        return -1;
+    }
+
+    DPL::SingleInstance instance;
+    try {
+        if (!instance.TryLock(DAEMON_INSTANCE_UUID)) {
+            LogError("Security Daemon is already running");
+            return -1;
+        }
+    } catch (const DPL::SingleInstance::Exception::LockError &e) {
+        LogError(e.DumpToString());
+        return -1;
+    }
+
+    auto& daemon = SecurityDaemonSingleton::Instance();
+
+    daemon.initialize(argc, argv);
+
+    //Run daemon
+    auto retVal = daemon.execute();
+
+    daemon.shutdown();
+    try {
+        instance.Release();
+    } catch (const DPL::SingleInstance::Exception::LockError &e) {
+        LogError(e.DumpToString());
+    }
+
+    return retVal;
+}
diff --git a/src/security-srv/CMakeLists.txt--original b/src/security-srv/CMakeLists.txt--original
new file mode 100644 (file)
index 0000000..4b8d9e0
--- /dev/null
@@ -0,0 +1,78 @@
+SET(PREFIX ${CMAKE_INSTALL_PREFIX})
+SET(EXEC_PREFIX "\${prefix}")
+SET(LIBDIR "\${prefix}/lib")
+SET(INCLUDEDIR "\${prefix}/include")
+SET(VERSION_MAJOR 1)
+SET(VERSION ${VERSION_MAJOR}.0.1)
+
+#Verbose
+#SET(CMAKE_VERBOSE_MAKEFILE ON)
+
+INCLUDE_DIRECTORIES(${CMAKE_SOURCE_DIR}/include)
+
+INCLUDE(FindPkgConfig)
+pkg_check_modules(pkgs REQUIRED dlog openssl libsmack)
+
+FOREACH(flag ${pkgs_CFLAGS})
+       SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}")
+ENDFOREACH(flag)
+
+SET(sec_svr_dir "./")
+SET(sec_svr_include_dir "./include")
+SET(sec_svr_src_dir "./src")
+SET(sec_svr_test_dir "./testcases")
+
+## Additional flag
+#SET(debug_type "-DSECURITY_SERVER_DEBUG_TO_CONSOLE")
+SET(debug_type "-DSECURITY_SERVER_DEBUG_DLOG")
+#SET(debug_type "")
+
+SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} -fvisibility=hidden")
+SET(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${EXTRA_CFLAGS}")
+
+###################################################################################################
+## for libsecurity-server-client.so (library)
+SET(libsecurity-server-client_SOURCES ${sec_svr_src_dir}/client/security-server-client.c ${sec_svr_src_dir}/communication/security-server-comm.c)
+SET(libsecurity-server-client_LDFLAGS " -module -avoid-version")
+SET(libsecurity-server-client_CFLAGS  " ${CFLAGS} -fPIC -I${sec_svr_include_dir} ${debug_type} -D_GNU_SOURCE ")
+#SET(libsecurity-server-client_LIBADD "")
+
+ADD_LIBRARY(security-server-client SHARED ${libsecurity-server-client_SOURCES})
+TARGET_LINK_LIBRARIES(security-server-client ${pkgs_LDFLAGS})
+SET_TARGET_PROPERTIES(security-server-client PROPERTIES SOVERSION ${VERSION_MAJOR})
+SET_TARGET_PROPERTIES(security-server-client PROPERTIES VERSION ${VERSION})
+SET_TARGET_PROPERTIES(security-server-client PROPERTIES COMPILE_FLAGS "${libsecurity-server-client_CFLAGS}")
+###################################################################################################
+
+###################################################################################################
+## for security-server (binary)
+SET(security-server_SOURCES ${sec_svr_src_dir}/server/security-server-main.c ${sec_svr_src_dir}/communication/security-server-comm.c ${sec_svr_src_dir}/server/security-server-cookie.c ${sec_svr_src_dir}/server/security-server-password.c ${sec_svr_src_dir}/util/security-server-util-common.c )
+SET(security-server_CFLAGS " -I/usr/include -I. -I${sec_svr_include_dir} ${debug_type} -D_GNU_SOURCE ")
+SET(security-server_LDFLAGS ${pkgs_LDFLAGS} -lpthread)
+
+ADD_EXECUTABLE(security-server ${security-server_SOURCES})
+TARGET_LINK_LIBRARIES(security-server ${pkgs_LDFLAGS})
+SET_TARGET_PROPERTIES(security-server PROPERTIES COMPILE_FLAGS "${security-server_CFLAGS}")
+####################################################################################################
+
+##FOR TEST METHOD ONLY. MUST BE DELETED ON RELEASE ############################################################
+## for security-server util (binary)
+SET(sec-svr-util_SOURCES ${sec_svr_src_dir}/util/security-server-util.c ${sec_svr_src_dir}/communication/security-server-comm.c ${sec_svr_src_dir}/util/security-server-util-common.c ${sec_svr_src_dir}/server/security-server-cookie.c)
+SET(sec-svr-util_CFLAGS " -I/usr/include -I. -I${sec_svr_include_dir} ${debug_type} -D_GNU_SOURCE ")
+SET(sec-svr-util_LDFLAGS ${pkgs_LDFLAGS})
+
+ADD_EXECUTABLE(sec-svr-util ${sec-svr-util_SOURCES})
+TARGET_LINK_LIBRARIES(sec-svr-util ${pkgs_LDFLAGS})
+SET_TARGET_PROPERTIES(sec-svr-util PROPERTIES COMPILE_FLAGS "${sec-svr-util_CFLAGS}")
+####################################################################################################
+
+CONFIGURE_FILE(security-server.pc.in security-server.pc @ONLY)
+
+INSTALL(TARGETS security-server-client DESTINATION lib)
+
+INSTALL(PROGRAMS ${CMAKE_BINARY_DIR}/security-server DESTINATION bin)
+INSTALL(PROGRAMS ${CMAKE_BINARY_DIR}/sec-svr-util DESTINATION bin)
+INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/security-server.pc DESTINATION lib/pkgconfig)
+INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/include/security-server.h DESTINATION include/security-server)
+INSTALL(FILES ${CMAKE_CURRENT_SOURCE_DIR}/mw-list DESTINATION share/security-server)
+INSTALL(PROGRAMS ${CMAKE_CURRENT_SOURCE_DIR}/security-serverd DESTINATION /etc/rc.d/init.d)
diff --git a/src/security-srv/client/security-server-client.c b/src/security-srv/client/security-server-client.c
new file mode 100644 (file)
index 0000000..e934df1
--- /dev/null
@@ -0,0 +1,1020 @@
+/*
+ * security-server
+ *
+ *  Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ *
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <errno.h>
+#include <unistd.h>
+#include <string.h>
+#include <sys/smack.h>
+
+#include "security-server.h"
+#include "security-server-common.h"
+#include "security-server-comm.h"
+
+#if 0
+void printhex(unsigned char *data, int size)
+{
+       int i;
+       for(i=0;i<size;i++)
+       {
+               if(data[i] < 0xF)
+                       printf("0");
+
+               printf("%X ", data[i]);
+               if(((i+1) % 16) == 0 && i != 0)
+                       printf("\n");
+       }
+       printf("\n");
+}
+
+
+char *read_cmdline_from_proc(pid_t pid)
+{
+       int memsize = 32;
+       char path[32];
+       char *cmdline = NULL;
+
+       snprintf(path, sizeof(path), "/proc/%d/exe", pid);
+
+       cmdline = malloc(32);
+       if(cmdline == NULL)
+       {
+               SEC_SVR_DBG("%s", "Out of memory");
+               goto error;
+       }
+
+       while(1)
+       {
+               bzero(cmdline, memsize);
+               /* readlink() may have security hole in normal symbolic link. *
+                * But this link is located at proc fs that only kernel can change */
+               readlink(path, cmdline, memsize);       /* FlawFinder: ignore */
+SEC_SVR_DBG("pid: %d, cmdline: %s", pid, cmdline);
+
+               /* Check it's truncated */
+               if(cmdline[memsize -1] != 0)
+               {
+                       cmdline = (char *)realloc(cmdline, sizeof(char) * (memsize + 32));
+                       memsize += 32;
+                       if(cmdline == NULL)
+                       {
+                               SEC_SVR_DBG("%s", "Out of memory");
+                               goto error;
+                       }
+               }
+               else
+                       break;
+       }
+
+error:
+       return cmdline;
+}
+#endif
+
+
+/* We may need to filter error code */
+int convert_to_public_error_code(int err_code)
+{
+       /* Do we need this? */
+       return err_code;
+}
+
+
+
+       SECURITY_SERVER_API
+int security_server_get_gid(const char *object)
+{
+       int sockfd = -1, retval, gid;
+       response_header hdr;
+
+       if(object == NULL)
+       {
+               SEC_SVR_DBG("%s", "Client: object is null or object is too big");
+               retval = SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+               goto error;
+       }
+       if( strlen(object) > SECURITY_SERVER_MAX_OBJ_NAME )
+       {
+               SEC_SVR_DBG("%s", "object is null or object is too big");
+               retval = SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+               goto error;
+       }
+
+       if(strlen(object) == 0)
+       {
+               SEC_SVR_DBG("Client: object is is empty");
+               retval = SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+               goto error;
+       }
+
+       SEC_SVR_DBG("%s", "Client: security_server_get_gid() is called");
+       retval = connect_to_server(&sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Connection failed: %d", retval);
+               goto error;
+       }
+       SEC_SVR_DBG("%s", "Client: Security server has been connected");
+
+       /* make request packet and send to server*/
+       retval = send_gid_request(sockfd, object);
+       SEC_SVR_DBG("%s", "Client: gid request has been sent");
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Send gid request failed: %d", retval);
+               goto error;
+       }
+
+       /* Receive response */
+       retval = recv_get_gid_response(sockfd, &hdr, &gid);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("Client: Receive response failed: %d", retval);
+               goto error;
+       }
+       SEC_SVR_DBG("%s", "Client: get gid response has been received");
+
+       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_GID_RESPONSE)       /* Wrong response */
+       {
+               if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
+               {
+                       /* There must be some error */
+                       SEC_SVR_DBG("Client: It'll be an error. return code:%d", hdr.return_code);
+                       retval = return_code_to_error_code(hdr.return_code);
+                       goto error;
+               }
+               else
+               {
+                       /* Something wrong with response */
+                       SEC_SVR_DBG("Client: Something wrong with response:%d", hdr.basic_hdr.msg_id);
+                       retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
+                       goto error;
+               }
+       }
+
+       SEC_SVR_DBG("received gid is %d", gid);
+       retval = gid;
+
+error:
+       if(sockfd > 0)
+               close(sockfd);
+       /* If error happened */
+       if(retval < 0)
+               retval = convert_to_public_error_code(retval);
+
+       return retval;
+}
+
+
+
+
+       SECURITY_SERVER_API
+int security_server_get_object_name(gid_t gid, char *object, size_t max_object_size)
+{
+       int sockfd = -1, retval;
+       response_header hdr;
+
+       if(object == NULL)
+       {
+               retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
+               goto error;
+       }
+
+       retval = connect_to_server(&sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Client: connect to server failed: %d", retval);
+               goto error;
+       }
+
+       /* make request packet */
+       retval = send_object_name_request(sockfd, gid);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Client: cannot send request: %d", retval);
+               goto error;
+       }
+
+       retval = recv_get_object_name(sockfd, &hdr, object, max_object_size);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("Client: Receive response failed: %d", retval);
+               goto error;
+       }
+
+       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_OBJECT_NAME_RESPONSE)       /* Wrong response */
+       {
+               if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
+               {
+                       /* There must be some error */
+                       SEC_SVR_DBG("Client: There is error on response: return code:%d", hdr.basic_hdr.msg_id);
+                       retval = return_code_to_error_code(hdr.return_code);
+               }
+               else
+               {
+                       /* Something wrong with response */
+                       SEC_SVR_DBG("Client: Some unexpected error happene: return code:%d", hdr.basic_hdr.msg_id);
+                       retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
+               }
+               goto error;
+       }
+
+error:
+       if(sockfd > 0)
+               close(sockfd);
+
+       retval = convert_to_public_error_code(retval);
+       return retval;
+}
+
+
+
+       SECURITY_SERVER_API
+int security_server_request_cookie(char *cookie, size_t max_cookie)
+{
+       int sockfd = -1, retval;
+       response_header hdr;
+
+       if(cookie == NULL)
+       {
+               retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
+               goto error;
+       }
+       if(max_cookie < SECURITY_SERVER_COOKIE_LEN)
+       {
+               retval = SECURITY_SERVER_ERROR_BUFFER_TOO_SMALL;
+               goto error;
+       }
+
+       SEC_SVR_DBG("%s", "Client: security_server_request_cookie() is called");
+       retval = connect_to_server(&sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("%s", "Client: connection failed");
+               goto error;
+       }
+
+       /* make request packet */
+       retval = send_cookie_request(sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Client: send cookie failed: %d", retval);
+               goto error;
+       }
+       SEC_SVR_DBG("%s", "Client: cookie request sent");
+       retval = recv_cookie(sockfd, &hdr, cookie);
+
+       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_COOKIE_RESPONSE)    /* Wrong response */
+       {
+               if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
+               {
+                       /* There must be some error */
+                       SEC_SVR_DBG("Client ERROR: There is an error on response. return code:%d", hdr.return_code);
+                       retval = return_code_to_error_code(hdr.return_code);
+               }
+               else
+               {
+                       /* Something wrong with response */
+                       SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
+                       retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
+               }
+               goto error;
+       }
+       SEC_SVR_DBG("%s", "Client: cookie received");
+
+error:
+       if(sockfd > 0)
+               close(sockfd);
+
+       retval = convert_to_public_error_code(retval);
+       return retval;
+}
+
+
+
+
+
+       SECURITY_SERVER_API
+int security_server_check_privilege(const char *cookie, gid_t privilege)
+{
+       int sockfd = -1, retval;
+       response_header hdr;
+
+       if(cookie == NULL)
+       {
+               retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
+               goto error;
+       }
+
+       retval = connect_to_server(&sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               goto error;
+       }
+
+       /* make request packet */
+       retval = send_privilege_check_request(sockfd, cookie, privilege);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Send failed: %d", retval);
+               goto error;
+       }
+
+       retval = recv_privilege_check_response(sockfd, &hdr);
+
+       retval = return_code_to_error_code(hdr.return_code);
+       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_RESPONSE)   /* Wrong response */
+       {
+               if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
+               {
+                       /* There must be some error */
+                       SEC_SVR_DBG("Client: Error has been received. return code:%d", hdr.return_code);
+               }
+               else
+               {
+                       /* Something wrong with response */
+                       SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
+                       retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
+               }
+               goto error;
+       }
+
+error:
+       if(sockfd > 0)
+               close(sockfd);
+
+       retval = convert_to_public_error_code(retval);
+       return retval;
+}
+
+
+       SECURITY_SERVER_API
+int security_server_check_privilege_by_cookie(const char *cookie,
+                                              const char *object,
+                                              const char *access_rights)
+{
+       int sockfd = -1, retval;
+        int olen, alen;
+       response_header hdr;
+
+       if(cookie == NULL || object == NULL || access_rights == NULL)
+       {
+               retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
+               goto error;
+       }
+
+        olen = strlen(object);
+        alen = strlen(access_rights);
+
+        if (olen > MAX_OBJECT_LABEL_LEN || alen > MAX_MODE_STR_LEN)
+       {
+               retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
+               goto error;
+       }
+
+       retval = connect_to_server(&sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               goto error;
+       }
+
+       /* make request packet */
+        retval = send_privilege_check_new_request(
+                     sockfd, cookie, object, access_rights);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Send failed: %d", retval);
+               goto error;
+       }
+
+       retval = recv_privilege_check_new_response(sockfd, &hdr);
+
+       retval = return_code_to_error_code(hdr.return_code);
+       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_NEW_RESPONSE)
+        /* Wrong response */
+       {
+               if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
+               {
+                       /* There must be some error */
+                       SEC_SVR_DBG("Client: Error has been received. return code:%d",
+                                    hdr.return_code);
+               }
+               else
+               {
+                       /* Something wrong with response */
+                       SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
+                       retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
+               }
+               goto error;
+       }
+
+error:
+       if(sockfd >= 0)
+               close(sockfd);
+
+       retval = convert_to_public_error_code(retval);
+       return retval;
+}
+
+       SECURITY_SERVER_API
+int security_server_check_privilege_by_sockfd(int sockfd,
+                                              const char *object,
+                                              const char *access_rights)
+{
+    char *subject;
+    int ret;
+    ret = smack_new_label_from_socket(sockfd, &subject);
+    if (ret != 0)
+    {
+        return SECURITY_SERVER_API_ERROR_SERVER_ERROR;
+    }
+    ret = smack_have_access(subject, object, access_rights);
+    SEC_SVR_DBG("check by sockfd, subject >%s< object >%s< rights >%s< ====> %d",
+                subject, object, access_rights, ret);
+    free(subject);
+    if (ret == 1)
+    {
+        return SECURITY_SERVER_API_SUCCESS;
+    }
+    else
+    {
+        return SECURITY_SERVER_API_ERROR_ACCESS_DENIED;
+    }
+}
+
+
+       SECURITY_SERVER_API
+int security_server_get_cookie_size(void)
+{
+       return SECURITY_SERVER_COOKIE_LEN;
+}
+
+
+
+       SECURITY_SERVER_API
+int security_server_get_cookie_pid(const char *cookie)
+{
+       int sockfd = -1, retval, pid = -1;
+       response_header hdr;
+
+       if(cookie == NULL)
+       {
+               retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
+               goto error;
+       }
+
+       retval = connect_to_server(&sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               goto error;
+       }
+
+       /* make request packet */
+       retval = send_pid_request(sockfd, cookie);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Client: Send failed: %d", retval);
+               goto error;
+       }
+
+       retval = recv_pid_response(sockfd, &hdr, &pid);
+
+       retval = return_code_to_error_code(hdr.return_code);
+       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_PID_RESPONSE)       /* Wrong response */
+       {
+               if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
+               {
+                       /* There must be some error */
+                       SEC_SVR_DBG("Client: Error has been received. return code:%d", hdr.return_code);
+               }
+               else
+               {
+                       /* Something wrong with response */
+                       SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
+                       retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
+               }
+               goto error;
+       }
+       if(hdr.return_code == SECURITY_SERVER_RETURN_CODE_NO_SUCH_COOKIE)
+       {
+               SEC_SVR_DBG("%s"," Client: There is no such cookie exist");
+       }
+
+error:
+       if(sockfd > 0)
+               close(sockfd);
+
+       retval = convert_to_public_error_code(retval);
+       if(retval == 0)
+               return pid;
+
+       return retval;
+}
+
+
+
+       SECURITY_SERVER_API
+int security_server_launch_debug_tool(int argc, const char **argv)
+{
+       int sockfd = -1, retval;
+       response_header hdr;
+
+       if(argc < 1 || argv == NULL || argv[0] == NULL)
+       {
+               retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
+               goto error;
+       }
+
+       if(argc == 1)
+       {
+               if(strcmp(argv[0], SECURITY_SERVER_KILL_APP_PATH) != 0)
+               {
+                       retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
+                       goto error;
+               }
+       }
+
+       /* Check the caller is developer shell */
+       retval = getuid();
+       if(retval != SECURITY_SERVER_DEVELOPER_UID)
+       {
+               SEC_SVR_DBG("Client: It's not allowed to call this API by uid %d", retval);
+               retval = SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED;
+               goto error;
+       }
+
+       retval = connect_to_server(&sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               goto error;
+       }
+
+       /* make request packet */
+       retval = send_launch_tool_request(sockfd, argc, argv);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Client: Send failed: %d", retval);
+               goto error;
+       }
+
+       retval = recv_generic_response(sockfd, &hdr);
+
+       retval = return_code_to_error_code(hdr.return_code);
+       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE)      /* Wrong response */
+       {
+               if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
+               {
+                       /* There must be some error */
+                       SEC_SVR_DBG("Client: Error has been received. return code:%d", hdr.return_code);
+               }
+               else
+               {
+                       /* Something wrong with response */
+                       SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
+                       retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
+               }
+               goto error;
+       }
+
+error:
+       if(sockfd > 0)
+               close(sockfd);
+
+       retval = convert_to_public_error_code(retval);
+       return retval;
+}
+
+
+
+       SECURITY_SERVER_API
+int security_server_is_pwd_valid(unsigned int *current_attempts,
+       unsigned int *max_attempts,
+       unsigned int *valid_secs)
+{
+       int sockfd = -1, retval = SECURITY_SERVER_ERROR_UNKNOWN;
+       response_header hdr;
+
+       if(current_attempts == NULL || max_attempts == NULL ||valid_secs == NULL)
+       {
+               retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
+               goto error;
+       }
+
+       /* Authenticate self that is setting app  goes here */
+       /* 1st, check cmdline which is setting app */
+       /* 2nd, check /proc/self/attr/current for the SMACK label */
+
+       retval = connect_to_server(&sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               goto error;
+       }
+
+       /* make request packet */
+       retval = send_valid_pwd_request(sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Client: Send failed: %d", retval);
+               goto error;
+       }
+
+       retval = recv_pwd_response(sockfd, &hdr, current_attempts, max_attempts, valid_secs);
+
+       retval = return_code_to_error_code(hdr.return_code);
+       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_VALID_PWD_RESPONSE) /* Wrong response */
+       {
+               if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_VALID_PWD_RESPONSE)
+               {
+                       /* There must be some error */
+                       SEC_SVR_DBG("Client: Error has been received. return code:%d", hdr.return_code);
+               }
+               else
+               {
+                       /* Something wrong with response */
+                       SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
+                       retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
+               }
+               goto error;
+       }
+error:
+       if(sockfd > 0)
+               close(sockfd);
+
+       retval = convert_to_public_error_code(retval);
+       return retval;
+}
+
+
+
+       SECURITY_SERVER_API
+int security_server_set_pwd(const char *cur_pwd,
+                       const char *new_pwd,
+                       const unsigned int max_challenge,
+                       const unsigned int valid_period_in_days)
+{
+       int sockfd = -1, retval;
+       response_header hdr;
+
+       if(new_pwd == NULL || strlen(new_pwd) > SECURITY_SERVER_MAX_PASSWORD_LEN)
+       {
+               retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
+               goto error;
+       }
+
+       /* Authenticate self that is setting app  goes here */
+       /* 1st, check cmdline which is setting app */
+       /* 2nd, check /proc/self/attr/current for the SMACK label */
+
+       retval = connect_to_server(&sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               goto error;
+       }
+
+       /* make request packet */
+       retval = send_set_pwd_request(sockfd, cur_pwd, new_pwd, max_challenge, valid_period_in_days);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Client: Send failed: %d", retval);
+               goto error;
+       }
+
+       retval = recv_generic_response(sockfd, &hdr);
+
+       retval = return_code_to_error_code(hdr.return_code);
+       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE)   /* Wrong response */
+       {
+               if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
+               {
+                       /* There must be some error */
+                       SEC_SVR_DBG("Client: Error has been received. return code:%d", hdr.return_code);
+               }
+               else
+               {
+                       /* Something wrong with response */
+                       SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
+                       retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
+               }
+               goto error;
+       }
+error:
+       if(sockfd > 0)
+               close(sockfd);
+
+       retval = convert_to_public_error_code(retval);
+       return retval;
+}
+
+
+       SECURITY_SERVER_API
+int security_server_set_pwd_validity(const unsigned int valid_period_in_days)
+{
+    int sockfd = -1, retval;
+    response_header hdr;
+
+    retval = connect_to_server(&sockfd);
+    if(retval != SECURITY_SERVER_SUCCESS)
+    {
+        /* Error on socket */
+        goto error;
+    }
+
+    /* make request packet */
+    retval = send_set_pwd_validity_request(sockfd, valid_period_in_days);
+    if(retval != SECURITY_SERVER_SUCCESS)
+    {
+        /* Error on socket */
+        SEC_SVR_DBG("Client: Send failed: %d", retval);
+        goto error;
+    }
+
+    retval = recv_generic_response(sockfd, &hdr);
+
+    retval = return_code_to_error_code(hdr.return_code);
+    if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_SET_PWD_VALIDITY_RESPONSE)   /* Wrong response */
+    {
+        if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
+        {
+            /* There must be some error */
+            SEC_SVR_DBG("Client: Error has been received. return code:%d", hdr.return_code);
+        }
+        else
+        {
+            /* Something wrong with response */
+            SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
+            retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
+        }
+        goto error;
+    }
+error:
+    if(sockfd > 0)
+        close(sockfd);
+
+    retval = convert_to_public_error_code(retval);
+    return retval;
+}
+
+       SECURITY_SERVER_API
+int security_server_set_pwd_max_challenge(const unsigned int max_challenge)
+{
+    int sockfd = -1, retval;
+    response_header hdr;
+
+    retval = connect_to_server(&sockfd);
+    if(retval != SECURITY_SERVER_SUCCESS)
+    {
+        /* Error on socket */
+        goto error;
+    }
+
+    /* make request packet */
+    retval = send_set_pwd_max_challenge_request(sockfd, max_challenge);
+    if(retval != SECURITY_SERVER_SUCCESS)
+    {
+        /* Error on socket */
+        SEC_SVR_DBG("Client: Send failed: %d", retval);
+        goto error;
+    }
+
+    retval = recv_generic_response(sockfd, &hdr);
+
+    retval = return_code_to_error_code(hdr.return_code);
+    if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_SET_PWD_MAX_CHALLENGE_RESPONSE)   /* Wrong response */
+    {
+        if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
+        {
+            /* There must be some error */
+            SEC_SVR_DBG("Client: Error has been received. return code:%d", hdr.return_code);
+        }
+        else
+        {
+            /* Something wrong with response */
+            SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
+            retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
+        }
+        goto error;
+    }
+error:
+    if(sockfd > 0)
+        close(sockfd);
+
+    retval = convert_to_public_error_code(retval);
+    return retval;
+}
+
+
+
+       SECURITY_SERVER_API
+int security_server_reset_pwd(const char *new_pwd,
+                       const unsigned int max_challenge,
+                       const unsigned int valid_period_in_days)
+{
+       int sockfd = -1, retval;
+       response_header hdr;
+
+       if(new_pwd == NULL || strlen(new_pwd) > SECURITY_SERVER_MAX_PASSWORD_LEN)
+       {
+               retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
+               goto error;
+       }
+
+       /* Authenticate self that is setting app  goes here */
+       /* 1st, check cmdline which is setting app */
+       /* 2nd, check /proc/self/attr/current for the SMACK label */
+
+       retval = connect_to_server(&sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               goto error;
+       }
+
+       /* make request packet */
+       retval = send_reset_pwd_request(sockfd, new_pwd, max_challenge, valid_period_in_days);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Client: Send failed: %d", retval);
+               goto error;
+       }
+
+       retval = recv_generic_response(sockfd, &hdr);
+
+       retval = return_code_to_error_code(hdr.return_code);
+       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_RESET_PWD_RESPONSE) /* Wrong response */
+       {
+               if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
+               {
+                       /* There must be some error */
+                       SEC_SVR_DBG("Client: Error has been received. return code:%d", hdr.return_code);
+               }
+               else
+               {
+                       /* Something wrong with response */
+                       SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
+                       retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
+               }
+               goto error;
+       }
+error:
+       if(sockfd > 0)
+               close(sockfd);
+
+       retval = convert_to_public_error_code(retval);
+       return retval;
+}
+
+
+
+       SECURITY_SERVER_API
+int security_server_chk_pwd(const char *challenge,
+       unsigned int *current_attempt,
+       unsigned int *max_attempts,
+       unsigned int *valid_secs)
+{
+       int sockfd = -1, retval;
+       response_header hdr;
+
+       if(challenge == NULL || strlen(challenge) > SECURITY_SERVER_MAX_PASSWORD_LEN
+               || current_attempt == NULL || max_attempts == NULL || valid_secs == NULL)
+       {
+               retval = SECURITY_SERVER_ERROR_INPUT_PARAM;
+               goto error;
+       }
+
+       /* Authenticate self goes here */
+
+       retval = connect_to_server(&sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               goto error;
+       }
+
+       /* make request packet */
+       retval = send_chk_pwd_request(sockfd, challenge);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Client: Send failed: %d", retval);
+               goto error;
+       }
+
+       retval = recv_pwd_response(sockfd, &hdr, current_attempt, max_attempts, valid_secs);
+
+       retval = return_code_to_error_code(hdr.return_code);
+       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE)   /* Wrong response */
+       {
+               if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
+               {
+                       /* There must be some error */
+                       SEC_SVR_DBG("Client: Error has been received. return code:%d", hdr.return_code);
+               }
+               else
+               {
+                       /* Something wrong with response */
+                       SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
+                       retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
+               }
+               goto error;
+       }
+error:
+       if(sockfd > 0)
+               close(sockfd);
+
+       retval = convert_to_public_error_code(retval);
+       return retval;
+}
+
+       SECURITY_SERVER_API
+int security_server_set_pwd_history(int number_of_history)
+{
+       int sockfd = -1, retval;
+       response_header hdr;
+
+       if(number_of_history > SECURITY_SERVER_MAX_PASSWORD_HISTORY || number_of_history < 0)
+               return SECURITY_SERVER_API_ERROR_INPUT_PARAM;
+
+       /* Authenticate self that is setting app  goes here */
+       /* 1st, check cmdline which is setting app */
+       /* 2nd, check /proc/self/attr/current for the SMACK label */
+
+       retval = connect_to_server(&sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               goto error;
+       }
+
+       /* make request packet */
+       retval = send_set_pwd_history_request(sockfd, number_of_history);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Client: Send failed: %d", retval);
+               goto error;
+       }
+       retval = recv_generic_response(sockfd, &hdr);
+
+       retval = return_code_to_error_code(hdr.return_code);
+       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_SET_PWD_HISTORY_RESPONSE)   /* Wrong response */
+       {
+               if(hdr.basic_hdr.msg_id == SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE)
+               {
+                       /* There must be some error */
+                       SEC_SVR_DBG("Client: Error has been received. return code:%d", hdr.return_code);
+               }
+               else
+               {
+                       /* Something wrong with response */
+                       SEC_SVR_DBG("Client ERROR: Unexpected error occurred:%d", retval);
+                       retval = SECURITY_SERVER_ERROR_BAD_RESPONSE;
+               }
+               goto error;
+       }
+error:
+       if(sockfd > 0)
+               close(sockfd);
+
+       retval = convert_to_public_error_code(retval);
+       return retval;
+}
diff --git a/src/security-srv/communication/security-server-comm.c b/src/security-srv/communication/security-server-comm.c
new file mode 100644 (file)
index 0000000..7b3b1aa
--- /dev/null
@@ -0,0 +1,2325 @@
+/*
+ * security-server
+ *
+ *  Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ *
+ */
+
+#include <sys/poll.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/socket.h>
+#include <sys/types.h>
+#include <sys/smack.h>
+#include <fcntl.h>
+#include <sys/un.h>
+#include <errno.h>
+#include <unistd.h>
+#include <sys/stat.h>
+
+#include "security-server-common.h"
+#include "security-server-comm.h"
+
+void printhex(const unsigned char *data, int size)
+{
+       int i;
+       for(i=0;i<size;i++)
+       {
+               if(data[i] < 0xF)
+                       printf("0");
+
+               printf("%X ", data[i]);
+               if(((i+1) % 16) == 0 && i != 0)
+                       printf("\n");
+       }
+       printf("\n");
+}
+
+char *read_cmdline_from_proc(pid_t pid)
+{
+       int memsize = 32;
+       char path[32];
+       char *cmdline = NULL, *tempptr = NULL;
+       FILE *fp = NULL;
+
+       snprintf(path, sizeof(path), "/proc/%d/cmdline", pid);
+
+       fp = fopen(path, "r");
+       if(fp == NULL)
+       {
+               SEC_SVR_DBG("Cannot open cmdline on pid[%d]", pid);
+               return NULL;
+       }
+
+       cmdline = malloc(32);
+       if(cmdline == NULL)
+       {
+               SEC_SVR_DBG("%s", "Out of memory");
+               fclose(fp);
+               return NULL;
+       }
+
+       bzero(cmdline, memsize);
+       if(fgets(cmdline, 32, fp) == NULL)
+       {
+               SEC_SVR_DBG("%s", "Cannot read cmdline");
+               free(cmdline);
+               fclose(fp);
+               return NULL;
+       }
+
+       while(cmdline[memsize -2] != 0)
+       {
+               cmdline[memsize -1] = (char) fgetc(fp);
+               tempptr = realloc(cmdline, memsize + 32);
+               if(tempptr == NULL)
+               {
+                       fclose(fp);
+                       SEC_SVR_DBG("%s", "Out of memory");
+                       return NULL;
+               }
+               cmdline = tempptr;
+               bzero(cmdline + memsize, 32);
+               fgets(cmdline + memsize, 32, fp);
+               memsize += 32;
+       }
+
+       if(fp != NULL)
+               fclose(fp);
+       return cmdline;
+}
+
+/* Return code in packet is positive integer *
+ * We need to convert them to error code which are negative integer */
+int return_code_to_error_code(int ret_code)
+{
+       int ret;
+       switch(ret_code)
+       {
+               case SECURITY_SERVER_RETURN_CODE_SUCCESS:
+               case SECURITY_SERVER_RETURN_CODE_ACCESS_GRANTED:
+                       ret = SECURITY_SERVER_SUCCESS;
+                       break;
+               case SECURITY_SERVER_RETURN_CODE_BAD_REQUEST:
+                       ret = SECURITY_SERVER_ERROR_BAD_REQUEST;
+                       break;
+               case SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED:
+                       ret = SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED;
+                       break;
+               case SECURITY_SERVER_RETURN_CODE_ACCESS_DENIED:
+                       ret = SECURITY_SERVER_ERROR_ACCESS_DENIED;
+                       break;
+               case SECURITY_SERVER_RETURN_CODE_NO_SUCH_OBJECT:
+                       ret = SECURITY_SERVER_ERROR_NO_SUCH_OBJECT;
+                       break;
+               case SECURITY_SERVER_RETURN_CODE_SERVER_ERROR:
+                       ret = SECURITY_SERVER_ERROR_SERVER_ERROR;
+                       break;
+               case SECURITY_SERVER_RETURN_CODE_NO_SUCH_COOKIE:
+                       ret = SECURITY_SERVER_ERROR_NO_SUCH_COOKIE;
+                       break;
+               case SECURITY_SERVER_RETURN_CODE_NO_PASSWORD:
+                       ret = SECURITY_SERVER_ERROR_NO_PASSWORD;
+                       break;
+               case SECURITY_SERVER_RETURN_CODE_PASSWORD_EXIST:
+                       ret = SECURITY_SERVER_ERROR_PASSWORD_EXIST;
+                       break;
+               case SECURITY_SERVER_RETURN_CODE_PASSWORD_MISMATCH:
+                       ret = SECURITY_SERVER_ERROR_PASSWORD_MISMATCH;
+                       break;
+               case SECURITY_SERVER_RETURN_CODE_PASSWORD_RETRY_TIMER:
+                       ret = SECURITY_SERVER_ERROR_PASSWORD_RETRY_TIMER;
+                       break;
+               case SECURITY_SERVER_RETURN_CODE_PASSWORD_EXPIRED:
+                       ret = SECURITY_SERVER_ERROR_PASSWORD_EXPIRED;
+                       break;
+               case SECURITY_SERVER_RETURN_CODE_PASSWORD_MAX_ATTEMPTS_EXCEEDED:
+                       ret = SECURITY_SERVER_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED;
+                       break;
+               case SECURITY_SERVER_RETURN_CODE_PASSWORD_REUSED:
+                       ret = SECURITY_SERVER_ERROR_PASSWORD_REUSED;
+                       break;
+               default:
+                       ret = SECURITY_SERVER_ERROR_UNKNOWN;
+                       break;
+       }
+       return ret;
+}
+
+int check_socket_poll(int sockfd, int event, int timeout)
+{
+       struct pollfd poll_fd[1];
+       int retval = SECURITY_SERVER_ERROR_POLL;
+
+       poll_fd[0].fd = sockfd;
+       poll_fd[0].events = event;
+       retval = poll(poll_fd, 1, timeout);
+       if(retval < 0)
+       {
+               SEC_SVR_DBG("poll() error. errno=%d", errno);
+               if(errno != EINTR)
+                       return SECURITY_SERVER_ERROR_POLL;
+               else
+               {
+                       /* Chile process has been closed. Not poll() problem. Call it once again */
+                       return check_socket_poll(sockfd, event, timeout);
+               }
+       }
+
+       /* Timed out */
+       if(retval == 0)
+       {
+               return SECURITY_SERVER_ERROR_TIMEOUT;
+       }
+
+       if(poll_fd[0].revents != event)
+       {
+               SEC_SVR_DBG("Something wrong on the peer socket. event=0x%x", poll_fd[0].revents);
+               return SECURITY_SERVER_ERROR_POLL;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+int safe_server_sock_close(int client_sockfd)
+{
+       struct pollfd poll_fd[1];
+       int retval;
+       retval = SECURITY_SERVER_ERROR_POLL;
+       poll_fd[0].fd = client_sockfd;
+       poll_fd[0].events = POLLRDHUP;
+       retval = poll(poll_fd, 1, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       SEC_SVR_DBG("%s", "Server: Closing server socket");
+       close(client_sockfd);
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Create a Unix domain socket and bind */
+int create_new_socket(int *sockfd)
+{
+       int retval = 0, localsockfd = 0, flags;
+       struct sockaddr_un serveraddr;
+       mode_t sock_mode;
+
+       /* Deleted garbage Unix domain socket file */
+       retval = remove(SECURITY_SERVER_SOCK_PATH);
+
+    if (retval == -1 && errno != ENOENT) {
+        retval = SECURITY_SERVER_ERROR_UNKNOWN;
+        localsockfd = -1;
+        SEC_SVR_DBG("%s", "Unable to remove /tmp/.security_server.sock");
+        goto error;
+    }
+
+       /* Create Unix domain socket */
+       if((localsockfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0 )
+       {
+               retval = SECURITY_SERVER_ERROR_SOCKET;
+               localsockfd = -1;
+               SEC_SVR_DBG("%s", "Socket creation failed");
+               goto error;
+       }
+
+       if(smack_fsetlabel(localsockfd, "@", SMACK_LABEL_IPOUT) != 0)
+       {
+               SEC_SVR_DBG("%s", "SMACK labeling failed");
+               if(errno != EOPNOTSUPP)
+               {
+                       retval = SECURITY_SERVER_ERROR_SOCKET;
+            close(localsockfd);
+                       localsockfd = -1;
+                       goto error;
+               }
+       }
+       if(smack_fsetlabel(localsockfd, "*", SMACK_LABEL_IPIN) != 0)
+       {       SEC_SVR_DBG("%s", "SMACK labeling failed");
+               if(errno != EOPNOTSUPP)
+               {
+                       retval = SECURITY_SERVER_ERROR_SOCKET;
+            close(localsockfd);
+                       localsockfd = -1;
+                       goto error;
+               }
+       }
+
+       /* Make socket as non blocking */
+       if((flags = fcntl(localsockfd, F_GETFL, 0)) < 0 ||
+                       fcntl(localsockfd, F_SETFL, flags | O_NONBLOCK) < 0)
+       {
+               retval = SECURITY_SERVER_ERROR_SOCKET;
+               close(localsockfd);
+               localsockfd = -1;
+               SEC_SVR_DBG("%s", "Cannot go to nonblocking mode");
+               goto error;
+       }
+
+       bzero (&serveraddr, sizeof(serveraddr));
+       serveraddr.sun_family = AF_UNIX;
+       strncpy(serveraddr.sun_path, SECURITY_SERVER_SOCK_PATH,
+                       strlen(SECURITY_SERVER_SOCK_PATH));
+       serveraddr.sun_path[strlen(SECURITY_SERVER_SOCK_PATH)] = 0;
+
+       /* Bind the socket */
+       if((bind(localsockfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr))) < 0)
+       {
+               retval = SECURITY_SERVER_ERROR_SOCKET_BIND;
+               SEC_SVR_DBG("%s", "Cannot bind");
+               close(localsockfd);
+               localsockfd = -1;
+               goto error;
+       }
+
+
+       /* Change permission to accept all processes that has different uID/gID */
+       sock_mode = (S_IRWXU | S_IRWXG | S_IRWXO);
+       /* Flawfinder hits this chmod function as level 5 CRITICAL as race condition flaw *
+        * Flawfinder recommends to user fchmod insted of chmod
+        * But, fchmod doesn't work on socket file so there is no other choice at this point */
+       if(chmod(SECURITY_SERVER_SOCK_PATH, sock_mode) < 0)             /* Flawfinder: ignore */
+       {
+               SEC_SVR_DBG("%s", "chmod() error");
+               retval = SECURITY_SERVER_ERROR_SOCKET;
+               close(localsockfd);
+               localsockfd = -1;
+               goto error;
+       }
+
+       retval = SECURITY_SERVER_SUCCESS;
+
+error:
+       *sockfd = localsockfd;
+       return retval;
+}
+
+/* Authenticate peer that it's really security server.
+ * Check UID that is root
+ */
+int authenticate_server(int sockfd)
+{
+       int retval;
+       struct ucred cr;
+       unsigned int cl = sizeof(cr);
+/*     char *cmdline = NULL;*/
+
+       /* get socket peer credential */
+       if(getsockopt(sockfd, SOL_SOCKET, SO_PEERCRED, &cr, &cl) != 0)
+       {
+               retval = SECURITY_SERVER_ERROR_SOCKET;
+               SEC_SVR_DBG("%s", "getsockopt() failed");
+               goto error;
+       }
+
+       /* Security server must run as root */
+       if(cr.uid != 0)
+       {
+               retval = SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED;
+               SEC_SVR_DBG("Peer is not root: uid=%d", cr.uid);
+               goto error;
+       }
+       else
+               retval = SECURITY_SERVER_SUCCESS;
+
+       /* Read command line of the PID from proc fs */
+       /* This is commented out because non root process cannot read link of /proc/pid/exe */
+/*     cmdline = read_cmdline_from_proc(cr.pid);
+
+       if(strcmp(cmdline, SECURITY_SERVER_DAEMON_PATH) != 0)
+       {
+               retval = SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED;
+               SEC_SVR_DBG("Cmdline is different. auth failed. cmdline=%s", cmdline);
+       }
+       else
+       {
+               retval = SECURITY_SERVER_SUCCESS;
+               SEC_SVR_DBG("Server authenticatd. %s, sockfd=%d", cmdline, sockfd);
+       }
+*/
+error:
+/*     if(cmdline != NULL)
+               free(cmdline);
+*/
+       return retval;
+}
+
+/* Create a socket and connect to Security Server */
+int connect_to_server(int *fd)
+{
+       struct sockaddr_un clientaddr;
+       int client_len = 0, localsockfd, ret, flags;
+       *fd = -1;
+
+       /* Create a socket */
+       localsockfd = socket(AF_UNIX, SOCK_STREAM, 0);
+       if(localsockfd < 0)
+       {
+               SEC_SVR_DBG("%s", "Error on socket()");
+               return SECURITY_SERVER_ERROR_SOCKET;
+       }
+
+       /* Make socket as non blocking */
+       if((flags = fcntl(localsockfd, F_GETFL, 0)) < 0 ||
+                       fcntl(localsockfd, F_SETFL, flags | O_NONBLOCK) < 0)
+       {
+               close(localsockfd);
+               SEC_SVR_DBG("%s", "Cannot go to nonblocking mode");
+               return SECURITY_SERVER_ERROR_SOCKET;
+       }
+
+       bzero(&clientaddr, sizeof(clientaddr));
+       clientaddr.sun_family = AF_UNIX;
+       strncpy(clientaddr.sun_path, SECURITY_SERVER_SOCK_PATH, strlen(SECURITY_SERVER_SOCK_PATH));
+       clientaddr.sun_path[strlen(SECURITY_SERVER_SOCK_PATH)] = 0;
+       client_len = sizeof(clientaddr);
+
+       ret = connect(localsockfd, (struct sockaddr*)&clientaddr, client_len);
+       if( ret < 0)
+       {
+               if(errno == EINPROGRESS)
+               {
+                       SEC_SVR_DBG("%s", "Connection is in progress");
+                       ret = check_socket_poll(localsockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+                       if(ret == SECURITY_SERVER_ERROR_POLL)
+                       {
+                               SEC_SVR_DBG("%s", "poll() error");
+                               close(localsockfd);
+                               return SECURITY_SERVER_ERROR_SOCKET;
+                       }
+                       if(ret == SECURITY_SERVER_ERROR_TIMEOUT)
+                       {
+                               SEC_SVR_DBG("%s", "poll() timeout");
+                               close(localsockfd);
+                               return SECURITY_SERVER_ERROR_SOCKET;
+                       }
+                       ret = connect(localsockfd, (struct sockaddr*)&clientaddr, client_len);
+                       if(ret < 0)
+                       {
+                               SEC_SVR_DBG("%s", "connection failed");
+                               close(localsockfd);
+                               return SECURITY_SERVER_ERROR_SOCKET;
+                       }
+               }
+               else
+               {
+                       SEC_SVR_DBG("%s", "Connection failed");
+                       close(localsockfd);
+                       return SECURITY_SERVER_ERROR_SOCKET;
+               }
+       }
+
+       /* Authenticate the peer is actually security server */
+       ret = authenticate_server(localsockfd);
+       if(ret  != SECURITY_SERVER_SUCCESS)
+       {
+               close(localsockfd);
+               SEC_SVR_DBG("Authentication failed. %d", ret);
+               return ret;
+       }
+       *fd = localsockfd;
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Accept a new client connection */
+int accept_client(int server_sockfd)
+{
+       /* Call poll() to wait for socket connection */
+       int retval, localsockfd;
+       struct sockaddr_un clientaddr;
+       unsigned int client_len;
+
+       client_len = sizeof(clientaddr);
+
+       /* Check poll */
+       retval = check_socket_poll(server_sockfd, POLLIN, SECURITY_SERVER_ACCEPT_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "Error on polling");
+               return SECURITY_SERVER_ERROR_SOCKET;
+       }
+
+       /* Timed out */
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               /*SEC_SVR_DBG("%s", "accept() timeout");*/
+               return SECURITY_SERVER_ERROR_TIMEOUT;
+       }
+
+       localsockfd = accept(server_sockfd,
+                       (struct sockaddr *)&clientaddr,
+                       &client_len);
+
+       if(localsockfd < 0)
+       {
+               SEC_SVR_DBG("Cannot accept client. errno=%d", errno);
+               return SECURITY_SERVER_ERROR_SOCKET;
+       }
+       return localsockfd;
+}
+
+/* Minimal check of request packet */
+int validate_header(basic_header hdr)
+{
+       if(hdr.version != SECURITY_SERVER_MSG_VERSION)
+               return SECURITY_SERVER_ERROR_BAD_REQUEST;
+
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Send generic response packet to client
+ *
+ * Generic Response Packet Format
+ 0                   1                   2                   3
+ 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+|---------------------------------------------------------------|
+| version=0x01  |  Message ID   |Message Length (without header)|
+|---------------------------------------------------------------|
+|  return code  |
+-----------------
+*/
+int send_generic_response (int sockfd, unsigned char msgid, unsigned char return_code)
+{
+       response_header hdr;
+       int size;
+
+       /* Assemble header */
+       hdr.basic_hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.basic_hdr.msg_id = msgid;
+       hdr.basic_hdr.msg_len = 0;
+       hdr.return_code = return_code;
+
+       /* Check poll */
+       size = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(size == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       if(size == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+
+       /* Send to client */
+       size = write(sockfd, &hdr, sizeof(hdr));
+
+       if(size < sizeof(hdr))
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Send cookie response to client
+ *
+ * Get Cookie response packet format
+ *  0                   1                   2                   3
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ *  |---------------------------------------------------------------|
+ *  | version=0x01  |MessageID=0x02 |       Message Length =20      |
+ *  |---------------------------------------------------------------|
+ *  |  return code  |                                               |
+ *  -----------------                                               |
+ *  |                 cookie (20 bytes)                             |
+ *  |---------------------------------------------------------------|
+*/
+int send_cookie(int sockfd, unsigned char *cookie)
+{
+       response_header hdr;
+       unsigned char msg[SECURITY_SERVER_COOKIE_LEN + sizeof(hdr)];
+       int ret;
+
+       /* Assemble header */
+       hdr.basic_hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.basic_hdr.msg_id = SECURITY_SERVER_MSG_TYPE_COOKIE_RESPONSE;
+       hdr.basic_hdr.msg_len = SECURITY_SERVER_COOKIE_LEN;
+       hdr.return_code = SECURITY_SERVER_RETURN_CODE_SUCCESS;
+
+       memcpy(msg, &hdr, sizeof(hdr));
+       memcpy(msg + sizeof(hdr), cookie, SECURITY_SERVER_COOKIE_LEN);
+
+       /* Check poll */
+       ret = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(ret == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       if(ret == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+
+       ret = write(sockfd, msg, sizeof(hdr) + SECURITY_SERVER_COOKIE_LEN);
+       if(ret <  sizeof(hdr) + SECURITY_SERVER_COOKIE_LEN)
+       {
+               /* Error on writing */
+               SEC_SVR_DBG("Error on write: %d", ret);
+               ret = SECURITY_SERVER_ERROR_SEND_FAILED;
+               return ret;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Send Object name response *
+ * Get Object name response packet format
+ *  0                   1                   2                   3
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x06 |       Message Length          |
+ * |---------------------------------------------------------------|
+ * |  return code  |                                               |
+ * -----------------                                               |
+ * |                 object name                                   |
+ * |---------------------------------------------------------------|
+*/
+int send_object_name(int sockfd, char *obj)
+{
+       response_header hdr;
+       unsigned char msg[strlen(obj) + sizeof(hdr)];
+       int ret;
+
+       hdr.basic_hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.basic_hdr.msg_id = 0x06;
+       hdr.basic_hdr.msg_len = strlen(obj);
+       hdr.return_code = SECURITY_SERVER_RETURN_CODE_SUCCESS;
+
+       memcpy(msg, &hdr, sizeof(hdr));
+       memcpy(msg + sizeof(hdr), obj, strlen(obj));
+
+       /* Check poll */
+       ret = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(ret == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       if(ret == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+
+       ret = write(sockfd, msg, sizeof(hdr) + strlen(obj));
+       if(ret <  sizeof(hdr) + strlen(obj))
+       {
+               /* Error on writing */
+               SEC_SVR_DBG("Error on write: %d", ret);
+               ret = SECURITY_SERVER_ERROR_SEND_FAILED;
+               return ret;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Send GID response to client
+ *
+ * Get GID response packet format
+ *  0                   1                   2                   3
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x08 |       Message Length = 4      |
+ * |---------------------------------------------------------------|
+ * |  return code  |           gid (first 3 words)                 |
+ * |---------------------------------------------------------------|
+ * |gid(last word) |
+ * |---------------|
+*/
+int send_gid(int sockfd, int gid)
+{
+       response_header hdr;
+       unsigned char msg[sizeof(gid) + sizeof(hdr)];
+       int ret;
+
+       /* Assemble header */
+       hdr.basic_hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.basic_hdr.msg_id = SECURITY_SERVER_MSG_TYPE_GID_RESPONSE;
+       hdr.basic_hdr.msg_len = sizeof(gid);
+       hdr.return_code = SECURITY_SERVER_RETURN_CODE_SUCCESS;
+
+       /* Perpare packet */
+       memcpy(msg, &hdr, sizeof(hdr));
+       memcpy(msg + sizeof(hdr), &gid, sizeof(gid));
+
+       /* Check poll */
+       ret = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(ret == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       if(ret == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+
+       /* Send it */
+       ret = write(sockfd, msg, sizeof(hdr) + sizeof(gid));
+       if(ret <  sizeof(hdr) + sizeof(gid))
+       {
+               /* Error on writing */
+               SEC_SVR_DBG("Error on write(): %d", ret);
+               ret = SECURITY_SERVER_ERROR_SEND_FAILED;
+               return ret;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Send PID response to client
+ *
+ * Get PID response packet format
+ *  0                   1                   2                   3
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x0a |       Message Length = 4      |
+ * |---------------------------------------------------------------|
+ * |  return code  |           pid (first 3 words)                 |
+ * |---------------------------------------------------------------|
+ * |pid(last word) |
+ * |---------------|
+*/
+int send_pid(int sockfd, int pid)
+{
+       response_header hdr;
+       unsigned char msg[sizeof(pid) + sizeof(hdr)];
+       int ret;
+
+       /* Assemble header */
+       hdr.basic_hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.basic_hdr.msg_id = SECURITY_SERVER_MSG_TYPE_PID_RESPONSE;
+       hdr.basic_hdr.msg_len = sizeof(pid);
+       hdr.return_code = SECURITY_SERVER_RETURN_CODE_SUCCESS;
+
+       /* Perpare packet */
+       memcpy(msg, &hdr, sizeof(hdr));
+       memcpy(msg + sizeof(hdr), &pid, sizeof(pid));
+
+       /* Check poll */
+       ret = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(ret == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       if(ret == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+
+       /* Send it */
+       ret = write(sockfd, msg, sizeof(hdr) + sizeof(pid));
+       if(ret <  sizeof(hdr) + sizeof(pid))
+       {
+               /* Error on writing */
+               SEC_SVR_DBG("Error on write(): %d", ret);
+               ret = SECURITY_SERVER_ERROR_SEND_FAILED;
+               return ret;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Send Check password response to client
+ *
+ * Check password response packet format
+ *  0                   1                   2                   3
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |   MessageID   |       Message Length = 12     |
+ * |---------------------------------------------------------------|
+ * |  return code  |           attempts (first 3 words)            |
+ * |---------------------------------------------------------------|
+ * |attempts(rest) |          max_attempts (first 3 words)         |
+ * |---------------|-----------------------------------------------|
+ * | max_attempts  |          expire_in_days (first 3 words)       |
+ * |---------------------------------------------------------------|
+ * |expire_in_days |
+ * |----------------
+ */
+int send_pwd_response(const int sockfd,
+       const unsigned char msg_id,
+       const unsigned char return_code,
+       const unsigned int current_attempts,
+       const unsigned int max_attempts,
+       const unsigned int expire_time)
+{
+       response_header hdr;
+       unsigned int expire_secs;
+       unsigned char msg[sizeof(hdr) + sizeof(current_attempts) + sizeof(max_attempts) + sizeof(expire_secs)];
+       int ret, ptr = 0;
+
+
+       /* Assemble header */
+       hdr.basic_hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.basic_hdr.msg_id = msg_id;
+       hdr.basic_hdr.msg_len = sizeof(unsigned int) * 3;
+       hdr.return_code = return_code;
+
+       /* Perpare packet */
+       memcpy(msg, &hdr, sizeof(hdr));
+       ptr += sizeof(hdr);
+       memcpy(msg + ptr, &current_attempts, sizeof(current_attempts));
+       ptr += sizeof(current_attempts);
+       memcpy(msg + ptr, &max_attempts, sizeof(max_attempts));
+       ptr += sizeof(max_attempts);
+       memcpy(msg + ptr, &expire_time, sizeof(expire_time));
+       ptr += sizeof(expire_time);
+
+       /* Check poll */
+       ret = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(ret == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "Server: poll() error");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       if(ret == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "Server: poll() timeout");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+
+       /* Send it */
+       ret = write(sockfd, msg, ptr);
+       if(ret <  ptr)
+       {
+               /* Error on writing */
+               SEC_SVR_DBG("Server: ERROR on write(): %d", ret);
+               ret = SECURITY_SERVER_ERROR_SEND_FAILED;
+               return ret;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Send cookie request packet to security server *
+ *
+ * Message format
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x01 |       Message Length = 0      |
+ * |---------------------------------------------------------------|
+ */
+int send_cookie_request(int sock_fd)
+{
+       basic_header hdr;
+       int retval;
+
+       /* Assemble header */
+       hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_COOKIE_REQUEST;
+       hdr.msg_len = 0;
+
+       /* Check poll */
+       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+
+       /* Send to server */
+       retval = write(sock_fd, &hdr, sizeof(hdr));
+       if(retval < sizeof(hdr))
+       {
+               /* Write error */
+               SEC_SVR_DBG("Error on write(): %d", retval);
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Send GID request message to security server
+ *
+ * Message format
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x07 |   Message Length = variable   |
+ * |---------------------------------------------------------------|
+ * |                                                               |
+ * |                   Object name (variable)                      |
+ * |                                                               |
+ * |---------------------------------------------------------------|
+ */
+int send_gid_request(int sock_fd, const char* object)
+{
+       basic_header hdr;
+       int retval = 0, send_len = 0;
+       unsigned char *buf = NULL;
+
+       if(strlen(object) > SECURITY_SERVER_MAX_OBJ_NAME)
+       {
+               /* Object name is too big*/
+               SEC_SVR_DBG("Object name is too big %dbytes", strlen(object));
+               return SECURITY_SERVER_ERROR_INPUT_PARAM;
+       }
+
+       hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_GID_REQUEST;
+       hdr.msg_len = strlen(object);
+
+       send_len = sizeof(hdr) + strlen(object);
+
+       buf = malloc(send_len);
+       if(buf == NULL)
+       {
+               SEC_SVR_DBG("%s", "out of memory");
+               return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
+       }
+
+       memcpy(buf, &hdr, sizeof(hdr));
+       memcpy(buf + sizeof(hdr), object, strlen(object));
+
+       /* Check poll */
+       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               retval = SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+       }
+
+       retval = write(sock_fd, buf, send_len);
+       if(retval < send_len)
+       {
+               /* Write error */
+               SEC_SVR_DBG("Error on write(): %d. errno=%d, sockfd=%d", retval, errno, sock_fd);
+               retval = SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       else
+               retval = SECURITY_SERVER_SUCCESS;
+
+error:
+       if(buf != NULL)
+               free(buf);
+
+       return retval;
+}
+
+/* Send object name request message to security server *
+ *
+ * Message format
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x05 |       Message Length = 4      |
+ * |---------------------------------------------------------------|
+ * |                               gid                             |
+ * |---------------------------------------------------------------|
+ */
+int send_object_name_request(int sock_fd, int gid)
+{
+       basic_header hdr;
+       int retval;
+       unsigned char buf[sizeof(hdr) + sizeof(gid)];
+
+       /* Assemble header */
+       hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_OBJECT_NAME_REQUEST;
+       hdr.msg_len = sizeof(gid);
+
+       memcpy(buf, &hdr, sizeof(hdr));
+       memcpy(buf + sizeof(hdr), &gid, sizeof(gid));
+
+       /* Check poll */
+       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+
+       /* Send to server */
+       retval = write(sock_fd, buf, sizeof(buf));
+       if(retval < sizeof(buf))
+       {
+               /* Write error */
+               SEC_SVR_DBG("Error on write(): %d", retval);
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Send privilege check request message to security server *
+ *
+ * Message format
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x03 |      Message Length = 24      |
+ * |---------------------------------------------------------------|
+ * |                                                               |
+ * |                                                               |
+ * |                      Cookie (20bytes)                         |
+ * |                                                               |
+ * |                                                               |
+ * |---------------------------------------------------------------|
+ * |                            GID                                |
+ * |---------------------------------------------------------------|
+ */
+int send_privilege_check_request(int sock_fd, const char*cookie, int gid)
+{
+       basic_header hdr;
+       int retval;
+       unsigned char buf[sizeof(hdr) + sizeof(gid) + SECURITY_SERVER_COOKIE_LEN];
+
+       /* Assemble header */
+       hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_REQUEST;
+       hdr.msg_len = sizeof(gid) + SECURITY_SERVER_COOKIE_LEN;
+
+       memcpy(buf, &hdr, sizeof(hdr));
+       memcpy(buf + sizeof(hdr), cookie, SECURITY_SERVER_COOKIE_LEN);
+       memcpy(buf + sizeof(hdr) + SECURITY_SERVER_COOKIE_LEN, &gid, sizeof(gid));
+
+       /* Check poll */
+       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+
+       /* Send to server */
+       retval = write(sock_fd, buf, sizeof(buf));
+       if(retval < sizeof(buf))
+       {
+               /* Write error */
+               SEC_SVR_DBG("Error on write(): %d", retval);
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+int send_privilege_check_new_request(int sock_fd,
+                                     const char *cookie,
+                                     const char *object,
+                                     const char *access_rights)
+{
+       basic_header hdr;
+       int retval;
+        int olen, alen;
+        int size;
+
+        olen = strlen(object);
+        alen = strlen(access_rights);
+        if (olen > MAX_OBJECT_LABEL_LEN || alen > MAX_MODE_STR_LEN)
+        {
+                return SECURITY_SERVER_ERROR_INPUT_PARAM;
+        }
+
+       unsigned char buf[sizeof(hdr) + SECURITY_SERVER_COOKIE_LEN +
+                          2*sizeof(int) + MAX_OBJECT_LABEL_LEN + MAX_MODE_STR_LEN];
+
+       /* Assemble header */
+       hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_NEW_REQUEST;
+       hdr.msg_len = SECURITY_SERVER_COOKIE_LEN + 2*sizeof(int) + olen + alen;
+
+       memcpy(buf, &hdr, sizeof(hdr));
+       memcpy(buf + sizeof(hdr), cookie, SECURITY_SERVER_COOKIE_LEN);
+        memcpy(buf + sizeof(hdr) + SECURITY_SERVER_COOKIE_LEN, &olen, sizeof(int));
+        memcpy(buf + sizeof(hdr) + SECURITY_SERVER_COOKIE_LEN + sizeof(int),
+               &alen, sizeof(int));
+       memcpy(buf + sizeof(hdr) + SECURITY_SERVER_COOKIE_LEN + 2*sizeof(int), object, olen);
+       memcpy(buf + sizeof(hdr) + SECURITY_SERVER_COOKIE_LEN + 2*sizeof(int) + olen,
+               access_rights, alen);
+
+       /* Check poll */
+       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+
+        size = sizeof(hdr) + SECURITY_SERVER_COOKIE_LEN + 2*sizeof(int) + olen + alen;
+       /* Send to server */
+       retval = write(sock_fd, buf, size);
+       if(retval < size)
+       {
+               /* Write error */
+               SEC_SVR_DBG("Error on write(): %d", retval);
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Send PID check request message to security server *
+ *
+ * Message format
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x09 |      Message Length = 20      |
+ * |---------------------------------------------------------------|
+ * |                                                               |
+ * |                                                               |
+ * |                      Cookie (20bytes)                         |
+ * |                                                               |
+ * |                                                               |
+ * |---------------------------------------------------------------|
+ */
+int send_pid_request(int sock_fd, const char*cookie)
+{
+       basic_header hdr;
+       int retval;
+       unsigned char buf[sizeof(hdr) + SECURITY_SERVER_COOKIE_LEN];
+
+       /* Assemble header */
+       hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_PID_REQUEST;
+       hdr.msg_len = SECURITY_SERVER_COOKIE_LEN;
+
+       memcpy(buf, &hdr, sizeof(hdr));
+       memcpy(buf + sizeof(hdr), cookie, SECURITY_SERVER_COOKIE_LEN);
+
+       /* Check poll */
+       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+
+       /* Send to server */
+       retval = write(sock_fd, buf, sizeof(buf));
+       if(retval < sizeof(buf))
+       {
+               /* Write error */
+               SEC_SVR_DBG("Error on write(): %d", retval);
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+
+/* Send debug tool launch request message to security server *
+ *
+ * Message format
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x0b |       Message Length          |
+ * |---------------------------------------------------------------|
+ * |                        total # of args                        |
+ * |---------------------------------------------------------------|
+ * |                        1st argv length                        |
+ * |---------------------------------------------------------------|
+ * |                                                               |
+ * |                            1st argv                           |
+ * |                                                               |
+ * |---------------------------------------------------------------|
+ * |                        2nd argv length                        |
+ * |---------------------------------------------------------------|
+ * |                                                               |
+ * |                            2nd argv                           |
+ * |                                                               |
+ * |---------------------------------------------------------------|
+ * |                                ...                            |
+ * |---------------------------------------------------------------|
+ * |                        nth argv length                        |
+ * |---------------------------------------------------------------|
+ * |                                                               |
+ * |                            nth argv                           |
+ * |                                                               |
+ * |---------------------------------------------------------------|
+ */
+int send_launch_tool_request(int sock_fd, int argc, const char **argv)
+{
+       basic_header hdr;
+       int retval, total_length = 0, ptr, i, tempnum;
+       unsigned char *buf = NULL;
+
+       for (i=0;i<argc;i++)
+       {
+               if(argv[i] == NULL)
+               {
+                       SEC_SVR_DBG("Error: %dth argv is NULL", i);
+                       return SECURITY_SERVER_ERROR_INPUT_PARAM;
+               }
+               total_length += strlen(argv[i]);
+       }
+
+       if(total_length < 1)
+       {
+               SEC_SVR_DBG("Error: There is a problem in argv. [%d]", total_length);
+               return SECURITY_SERVER_ERROR_INPUT_PARAM;
+       }
+       total_length += sizeof(hdr) + sizeof(int) +(argc * sizeof(int));
+
+       if(total_length > 0xffff)
+       {
+               SEC_SVR_DBG("Buffer overflow. too big payload. [%d]", total_length);
+               return SECURITY_SERVER_ERROR_INPUT_PARAM;
+       }
+
+       buf = malloc(total_length);
+       if(buf == NULL)
+       {
+               SEC_SVR_DBG("%s", "Error: failed to malloc()");
+               return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
+       }
+
+       /* Assemble header */
+       hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_TOOL_REQUEST;
+       hdr.msg_len = (unsigned short)total_length;
+       memcpy(buf, &hdr, sizeof(hdr));
+       ptr = sizeof(hdr);
+       memcpy(buf + ptr, &argc, sizeof(int));
+       ptr += sizeof(hdr);
+
+       /* Assemple each argv length and value */
+       for(i=0;i<argc;i++)
+       {
+               tempnum = strlen(argv[i]);
+               memcpy(buf + ptr, &tempnum, sizeof(int));
+               ptr += sizeof(int);
+               memcpy(buf + ptr, argv[i], tempnum);
+               ptr += tempnum;
+       }
+
+       /* Check poll */
+       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+       }
+
+       /* Send to server */
+       retval = write(sock_fd, buf, total_length);
+       if(retval < sizeof(buf))
+       {
+               /* Write error */
+               SEC_SVR_DBG("Error on write(): %d", retval);
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+       }
+       retval = SECURITY_SERVER_SUCCESS;
+
+error:
+       if(buf != NULL)
+               free(buf);
+       return retval;
+}
+
+/* Send validate password request message to security server *
+ *
+ * Message format
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x0d |       Message Length          |
+ * |---------------------------------------------------------------|
+ */
+int send_valid_pwd_request(int sock_fd)
+{
+       basic_header hdr;
+       int retval;
+
+       hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_VALID_PWD_REQUEST;
+       hdr.msg_len = 0;
+
+       /* Check poll */
+       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+       }
+
+       /* Send to server */
+       retval = write(sock_fd, &hdr, sizeof(hdr));
+       if(retval < sizeof(hdr))
+       {
+               /* Write error */
+               SEC_SVR_DBG("Error on write(): %d", retval);
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+       }
+       retval = SECURITY_SERVER_SUCCESS;
+
+error:
+       return retval;
+}
+
+/* Send password set request message to security server *
+ *
+ * Message format
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x0f |       Message Length          |
+ * |---------------------------------------------------------------|
+ * |  cur_pwd_len  |  new_pwd_len  |                               |
+ * |--------------------------------                               |
+ * |                            cur pwd                            |
+ * |---------------------------------------------------------------|
+ * |                                                               |
+ * |                            new pwd                            |
+ * |                                                               |
+ * |---------------------------------------------------------------|
+ * |                         max attempts                          |
+ * |---------------------------------------------------------------|
+ * |                         valid days                            |
+ * |---------------------------------------------------------------|
+ */
+int send_set_pwd_request(int sock_fd,
+                       const char*cur_pwd,
+                       const char*new_pwd,
+                       const unsigned int max_challenge,
+                       const unsigned int valid_period_in_days)
+{
+       basic_header hdr;
+       int retval, total_length = 0, ptr;
+       unsigned char *buf = NULL, cur_pwd_len, new_pwd_len;
+
+       if(cur_pwd == NULL)
+               cur_pwd_len = 0;
+       else
+               cur_pwd_len = strlen(cur_pwd);
+       new_pwd_len = strlen(new_pwd);
+
+       total_length += sizeof(hdr) + sizeof(char) + sizeof(char) + cur_pwd_len
+               + new_pwd_len + sizeof(unsigned int) + sizeof(unsigned int);
+
+       buf = malloc(total_length);
+       if(buf == NULL)
+       {
+               SEC_SVR_DBG("%s", "Error: failed to malloc()");
+               return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
+       }
+
+       /* Assemble header */
+       hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_SET_PWD_REQUEST;
+       hdr.msg_len = (unsigned short)total_length;
+       memcpy(buf, &hdr, sizeof(hdr));
+       ptr = sizeof(hdr);
+       memcpy(buf + ptr, &cur_pwd_len, sizeof(char));
+       ptr += sizeof(char);
+       memcpy(buf + ptr, &new_pwd_len, sizeof(char));
+       ptr += sizeof(char);
+       if(cur_pwd != NULL)
+       {
+               memcpy(buf + ptr, cur_pwd, cur_pwd_len);
+               ptr += cur_pwd_len;
+       }
+       memcpy(buf + ptr, new_pwd, new_pwd_len);
+       ptr += new_pwd_len;
+       memcpy(buf + ptr, &max_challenge, sizeof(unsigned int));
+       ptr += sizeof(unsigned int);
+       memcpy(buf + ptr, &valid_period_in_days, sizeof(unsigned int));
+
+       /* Check poll */
+       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+       }
+
+       /* Send to server */
+       retval = write(sock_fd, buf, total_length);
+       if(retval < sizeof(buf))
+       {
+               /* Write error */
+               SEC_SVR_DBG("Error on write(): %d", retval);
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+       }
+       retval = SECURITY_SERVER_SUCCESS;
+
+error:
+       if(buf != NULL)
+               free(buf);
+       return retval;
+}
+
+/* Send password validity change request message to security server *
+ *
+ * Message format
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x0f |       Message Length          |
+ * |---------------------------------------------------------------|
+ * |                         valid days                            |
+ * |---------------------------------------------------------------|
+ */
+int send_set_pwd_validity_request(int sock_fd, const unsigned int valid_period_in_days)
+{
+    basic_header hdr;
+    int retval, total_length = 0, ptr;
+    unsigned char *buf = NULL;
+
+    total_length = sizeof(hdr) + sizeof(unsigned int);
+
+    buf = malloc(total_length);
+    if(buf == NULL)
+    {
+        SEC_SVR_DBG("%s", "Error: failed to malloc()");
+        return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
+    }
+
+    /* Assemble header */
+    hdr.version = SECURITY_SERVER_MSG_VERSION;
+    hdr.msg_id = SECURITY_SERVER_MSG_TYPE_SET_PWD_VALIDITY_REQUEST;
+    hdr.msg_len = (unsigned short)total_length;
+    memcpy(buf, &hdr, sizeof(hdr));
+    ptr = sizeof(hdr);
+    memcpy(buf + ptr, &valid_period_in_days, sizeof(unsigned int));
+
+    /* Check poll */
+    retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+    if(retval == SECURITY_SERVER_ERROR_POLL)
+    {
+        SEC_SVR_DBG("%s", "poll() error");
+        retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+        goto error;
+
+    }
+    if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+    {
+        SEC_SVR_DBG("%s", "poll() timeout");
+        retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+        goto error;
+    }
+
+    /* Send to server */
+    retval = write(sock_fd, buf, total_length);
+    if(retval < sizeof(buf))
+    {
+        /* Write error */
+        SEC_SVR_DBG("Error on write(): %d", retval);
+        retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+        goto error;
+    }
+    retval = SECURITY_SERVER_SUCCESS;
+
+error:
+    if(buf != NULL)
+        free(buf);
+    return retval;
+}
+
+/* Send password max challenge request message to security server *
+ *
+ * Message format
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x0f |       Message Length          |
+ * |---------------------------------------------------------------|
+ * |                         max challenge                         |
+ * |---------------------------------------------------------------|
+ */
+int send_set_pwd_max_challenge_request(int sock_fd, const unsigned int max_challenge)
+{
+    basic_header hdr;
+    int retval, total_length = 0, ptr;
+    unsigned char *buf = NULL;
+
+    total_length = sizeof(hdr) + sizeof(unsigned int);
+
+    buf = malloc(total_length);
+    if(buf == NULL)
+    {
+        SEC_SVR_DBG("%s", "Error: failed to malloc()");
+        return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
+    }
+
+    /* Assemble header */
+    hdr.version = SECURITY_SERVER_MSG_VERSION;
+    hdr.msg_id = SECURITY_SERVER_MSG_TYPE_SET_PWD_MAX_CHALLENGE_REQUEST;
+    hdr.msg_len = (unsigned short)total_length;
+    memcpy(buf, &hdr, sizeof(hdr));
+    ptr = sizeof(hdr);
+    memcpy(buf + ptr, &max_challenge, sizeof(unsigned int));
+
+    /* Check poll */
+    retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+    if(retval == SECURITY_SERVER_ERROR_POLL)
+    {
+        SEC_SVR_DBG("%s", "poll() error");
+        retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+        goto error;
+
+    }
+    if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+    {
+        SEC_SVR_DBG("%s", "poll() timeout");
+        retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+        goto error;
+    }
+
+    /* Send to server */
+    retval = write(sock_fd, buf, total_length);
+    if(retval < sizeof(buf))
+    {
+        /* Write error */
+        SEC_SVR_DBG("Error on write(): %d", retval);
+        retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+        goto error;
+    }
+    retval = SECURITY_SERVER_SUCCESS;
+
+error:
+    if(buf != NULL)
+        free(buf);
+    return retval;
+}
+
+/* Send password reset request message to security server *
+ *
+ * Message format
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x11 |       Message Length          |
+ * |---------------------------------------------------------------|
+ * |  new_pwd_len  |                                               |
+ * |---------------------------------------------------------------|
+ * |                                                               |
+ * |                            new pwd                            |
+ * |                                                               |
+ * |---------------------------------------------------------------|
+ * |                         max attempts                          |
+ * |---------------------------------------------------------------|
+ * |                         valid days                            |
+ * |---------------------------------------------------------------|
+ */
+int send_reset_pwd_request(int sock_fd,
+                       const char*new_pwd,
+                       const unsigned int max_challenge,
+                       const unsigned int valid_period_in_days)
+{
+       basic_header hdr;
+       int retval, total_length = 0, ptr;
+       unsigned char *buf = NULL, new_pwd_len;
+
+       new_pwd_len = strlen(new_pwd);
+
+       total_length += sizeof(hdr) + sizeof(char) + new_pwd_len + sizeof(unsigned int) +
+               sizeof(unsigned int);
+
+       buf = malloc(total_length);
+       if(buf == NULL)
+       {
+               SEC_SVR_DBG("%s", "Error: failed to malloc()");
+               return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
+       }
+
+       /* Assemble header */
+       hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_RESET_PWD_REQUEST;
+       hdr.msg_len = (unsigned short)total_length;
+       memcpy(buf, &hdr, sizeof(hdr));
+       ptr = sizeof(hdr);
+       memcpy(buf + ptr, &new_pwd_len, sizeof(char));
+       ptr += sizeof(char);
+       memcpy(buf + ptr, new_pwd, new_pwd_len);
+       ptr += new_pwd_len;
+       memcpy(buf + ptr, &max_challenge, sizeof(unsigned int));
+       ptr += sizeof(unsigned int);
+       memcpy(buf + ptr, &valid_period_in_days, sizeof(unsigned int));
+
+       /* Check poll */
+       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+       }
+
+       /* Send to server */
+       retval = write(sock_fd, buf, total_length);
+       if(retval < sizeof(buf))
+       {
+               /* Write error */
+               SEC_SVR_DBG("Error on write(): %d", retval);
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+       }
+       retval = SECURITY_SERVER_SUCCESS;
+
+error:
+       if(buf != NULL)
+               free(buf);
+       return retval;
+}
+
+/* Send password check request message to security server *
+ *
+ * Message format
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x13 |       Message Length          |
+ * |---------------------------------------------------------------|
+ * | challenge_len |                                               |
+ * |---------------                                                |
+ * |                          challenge                            |
+ * |---------------------------------------------------------------|
+ */
+int send_chk_pwd_request(int sock_fd, const char*challenge)
+{
+       basic_header hdr;
+       int retval, total_length = 0, ptr;
+       unsigned char *buf = NULL, challenge_len;
+
+       challenge_len = strlen(challenge);
+
+       total_length += sizeof(hdr) + sizeof(char) + challenge_len;
+
+       buf = malloc(total_length);
+       if(buf == NULL)
+       {
+               SEC_SVR_DBG("%s", "Error: failed to malloc()");
+               return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
+       }
+
+       /* Assemble header */
+       hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_CHK_PWD_REQUEST;
+       hdr.msg_len = (unsigned short)total_length;
+       memcpy(buf, &hdr, sizeof(hdr));
+       ptr = sizeof(hdr);
+       memcpy(buf + ptr, &challenge_len, sizeof(char));
+       ptr += sizeof(char);
+       memcpy(buf + ptr, challenge, challenge_len);
+       ptr += sizeof(char);
+
+       /* Check poll */
+       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+       }
+
+       /* Send to server */
+       retval = write(sock_fd, buf, total_length);
+       if(retval < sizeof(buf))
+       {
+               /* Write error */
+               SEC_SVR_DBG("Error on write(): %d", retval);
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+       }
+       retval = SECURITY_SERVER_SUCCESS;
+
+error:
+       if(buf != NULL)
+               free(buf);
+       return retval;
+}
+
+/* Send password history set request message to security server *
+ *
+ * Message format
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x15 |       Message Length          |
+ * |---------------------------------------------------------------|
+ * | challenge_len |
+ * |----------------
+ */
+int send_set_pwd_history_request(int sock_fd, int num)
+{
+       basic_header hdr;
+       int retval, total_length = 0, ptr;
+       unsigned char history;
+       unsigned char buf[sizeof(hdr) + sizeof(history)];
+
+       total_length = sizeof(hdr) + sizeof(char);
+       history = (unsigned char) num;
+
+       /* Assemble header */
+       hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_SET_PWD_HISTORY_REQUEST;
+       hdr.msg_len = (unsigned short)total_length;
+       memcpy(buf, &hdr, sizeof(hdr));
+       ptr = sizeof(hdr);
+       memcpy(buf + ptr, &history, sizeof(char));
+       ptr += sizeof(char);
+
+       /* Check poll */
+       retval = check_socket_poll(sock_fd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+       }
+
+       /* Send to server */
+       retval = write(sock_fd, buf, ptr);
+       if(retval < sizeof(buf))
+       {
+               /* Write error */
+               SEC_SVR_DBG("Error on write(): %d", retval);
+               retval =  SECURITY_SERVER_ERROR_SEND_FAILED;
+               goto error;
+       }
+       retval = SECURITY_SERVER_SUCCESS;
+
+error:
+       return retval;
+}
+
+/* Receive request header */
+int recv_hdr(int client_sockfd, basic_header *basic_hdr)
+{
+       int retval;
+
+       /* Check poll */
+       retval = check_socket_poll(client_sockfd, POLLIN, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               return SECURITY_SERVER_ERROR_SOCKET;
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               return SECURITY_SERVER_ERROR_TIMEOUT;
+       }
+
+       /* Receive request header first */
+       retval = read(client_sockfd, basic_hdr, sizeof(basic_header));
+       if(retval < sizeof(basic_header))
+       {
+               SEC_SVR_DBG("read failed. closing socket %d", retval);
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+
+       /* Validate header */
+       retval = validate_header(*basic_hdr);
+       return retval;
+}
+
+
+/* Receive check privilege request packet body */
+int recv_check_privilege_request(int sockfd, unsigned char *requested_cookie, int *requested_privilege)
+{
+       int retval;
+       retval = read(sockfd, requested_cookie, SECURITY_SERVER_COOKIE_LEN);
+       if(retval < SECURITY_SERVER_COOKIE_LEN)
+       {
+               SEC_SVR_DBG("Received cookie size is too small: %d", retval);
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+
+       retval = read(sockfd, requested_privilege, sizeof(int));
+       if(retval < sizeof(int))
+       {
+               SEC_SVR_DBG("privilege size is too small: %d", retval);
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Receive check privilege request packet body (new mode)*/
+int recv_check_privilege_new_request(int sockfd,
+                                     unsigned char *requested_cookie,
+                                     char *object_label,
+                                     char *access_rights)
+{
+       int retval;
+        int olen, alen;
+
+       retval = read(sockfd, requested_cookie, SECURITY_SERVER_COOKIE_LEN);
+       if(retval < SECURITY_SERVER_COOKIE_LEN)
+       {
+               SEC_SVR_DBG("Received cookie size is too small: %d", retval);
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+
+       retval = read(sockfd, &olen, sizeof(int));
+       if(retval < sizeof(int) || olen < 0 || olen > MAX_OBJECT_LABEL_LEN)
+       {
+               SEC_SVR_DBG("error reading object_label len: %d", retval);
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+
+       retval = read(sockfd, &alen, sizeof(int));
+       if(retval < sizeof(int) || alen < 0 || olen > MAX_MODE_STR_LEN)
+       {
+               SEC_SVR_DBG("error reading access_rights len: %d", retval);
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+
+       retval = read(sockfd, object_label, olen);
+       if(retval < olen)
+       {
+               SEC_SVR_DBG("error reading object_label: %d", retval);
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+        object_label[olen] = '\0';
+
+       retval = read(sockfd, access_rights, olen);
+       if(retval < alen)
+       {
+               SEC_SVR_DBG("error reading access_rights: %d", retval);
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+        access_rights[alen] = '\0';
+
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Receive pid request packet body */
+int recv_pid_request(int sockfd, unsigned char *requested_cookie)
+{
+       int retval;
+       retval = read(sockfd, requested_cookie, SECURITY_SERVER_COOKIE_LEN);
+       if(retval < SECURITY_SERVER_COOKIE_LEN)
+       {
+               SEC_SVR_DBG("Received cookie size is too small: %d", retval);
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Receive pid request packet body */
+int recv_launch_tool_request(int sockfd, int argc, char *argv[])
+{
+       int retval, i, argv_len;
+
+       argv[0] = malloc(strlen(SECURITY_SERVER_DEBUG_TOOL_PATH) + 1);
+       strncpy(argv[0], SECURITY_SERVER_DEBUG_TOOL_PATH, (strlen(SECURITY_SERVER_DEBUG_TOOL_PATH) + 1));
+
+       for(i=1;i<argc;i++)
+       {
+               retval = read(sockfd, &argv_len, sizeof(int));
+               if(retval < sizeof(int))
+               {
+                       SEC_SVR_DBG("Error: argv length recieve failed: %d", retval);
+                       free_argv(argv, argc);
+                       return SECURITY_SERVER_ERROR_RECV_FAILED;
+               }
+
+               argv[i] = malloc(argv_len + 1);
+               if(argv[i] == NULL)
+               {
+                       SEC_SVR_DBG("Error: malloc() failed: %d", retval);
+                       free_argv(argv, argc);
+                       return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
+               }
+
+               memset(argv[i], 0x00, argv_len + 1);
+               retval = read(sockfd, argv[i], argv_len);
+               if(retval < argv_len)
+               {
+                       SEC_SVR_DBG("Error: argv recieve failed: %d", retval);
+                       free_argv(argv, argc);
+                       return SECURITY_SERVER_ERROR_RECV_FAILED;
+               }
+       }
+
+       return SECURITY_SERVER_SUCCESS;
+}
+
+int recv_generic_response(int sockfd, response_header *hdr)
+{
+       int retval;
+
+       /* Check poll */
+       retval = check_socket_poll(sockfd, POLLIN, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "Client: poll() error");
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "Client: poll() timeout");
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+
+       /* Receive response */
+       retval = read(sockfd, hdr, sizeof(response_header));
+       if(retval < sizeof(response_header) )
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Client: Receive failed %d", retval);
+               return  SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+
+       if(hdr->return_code != SECURITY_SERVER_RETURN_CODE_SUCCESS)
+       {
+               SEC_SVR_DBG("Client: return code is not success: %d", hdr->return_code);
+               return return_code_to_error_code(hdr->return_code);
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+int recv_get_gid_response(int sockfd, response_header *hdr, int *gid)
+{
+       int retval;
+
+       retval = recv_generic_response(sockfd, hdr);
+       if(retval != SECURITY_SERVER_SUCCESS)
+               return return_code_to_error_code(hdr->return_code);
+
+       retval = read(sockfd, gid, sizeof(int));
+       if(retval < sizeof(int))
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Receive failed %d", retval);
+               return  SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+int recv_get_object_name(int sockfd, response_header *hdr, char *object, int max_object_size)
+{
+       int retval;
+       char *local_obj_name = NULL;
+
+       /* Check poll */
+       retval = check_socket_poll(sockfd, POLLIN, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+
+       /* Read response */
+       retval = read(sockfd, hdr, sizeof(response_header));
+       if(retval < sizeof(hdr) )
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("cannot recv respons: %d", retval);
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+
+       if(hdr->return_code == SECURITY_SERVER_RETURN_CODE_SUCCESS)
+       {
+               if(max_object_size < hdr->basic_hdr.msg_len)
+               {
+                       SEC_SVR_DBG("Object name is too small need %d bytes, but %d bytes", hdr->basic_hdr.msg_len, max_object_size);
+                       return SECURITY_SERVER_ERROR_BUFFER_TOO_SMALL;
+               }
+               if(hdr->basic_hdr.msg_len > SECURITY_SERVER_MAX_OBJ_NAME)
+               {
+                       SEC_SVR_DBG("Received object name is too big. %d", hdr->basic_hdr.msg_len);
+                       return SECURITY_SERVER_ERROR_BAD_RESPONSE;
+               }
+
+               local_obj_name = malloc(hdr->basic_hdr.msg_len + 1);
+               if(local_obj_name == NULL)
+               {
+                       SEC_SVR_DBG("%s", "Out of memory error");
+                       return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
+               }
+
+               retval = read(sockfd, local_obj_name, hdr->basic_hdr.msg_len);
+               if(retval < (hdr->basic_hdr.msg_len))
+               {
+                       /* Error on socket */
+                       SEC_SVR_DBG("read() failed: %d", retval);
+                       if(local_obj_name != NULL)
+                               free(local_obj_name);
+                       return SECURITY_SERVER_ERROR_RECV_FAILED;
+               }
+               memcpy(object, local_obj_name, hdr->basic_hdr.msg_len);
+               object[hdr->basic_hdr.msg_len] = 0;
+               retval = SECURITY_SERVER_SUCCESS;
+       }
+       else
+       {
+               SEC_SVR_DBG("Error received. return code: %d", hdr->return_code);
+               retval = return_code_to_error_code(hdr->return_code);
+               return retval;
+       }
+
+       if(local_obj_name != NULL)
+               free(local_obj_name);
+       return SECURITY_SERVER_SUCCESS;
+}
+
+int recv_cookie(int sockfd, response_header *hdr, char *cookie)
+{
+       int retval;
+
+       retval = recv_generic_response(sockfd, hdr);
+       if(retval != SECURITY_SERVER_SUCCESS)
+               return return_code_to_error_code(hdr->return_code);
+
+       retval = read(sockfd, cookie, SECURITY_SERVER_COOKIE_LEN);
+       if(retval < SECURITY_SERVER_COOKIE_LEN)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("read() failed: %d", retval);
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+int recv_privilege_check_response(int sockfd, response_header *hdr)
+{
+       int retval;
+
+       retval = recv_generic_response(sockfd, hdr);
+       if(hdr->return_code != SECURITY_SERVER_RETURN_CODE_ACCESS_GRANTED &&
+                       hdr->return_code != SECURITY_SERVER_RETURN_CODE_ACCESS_DENIED)
+       {
+               SEC_SVR_DBG("response error: %d", hdr->return_code);
+               return return_code_to_error_code(hdr->return_code);
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+int recv_privilege_check_new_response(int sockfd, response_header *hdr)
+{
+       int retval;
+
+       retval = recv_generic_response(sockfd, hdr);
+       if(hdr->return_code != SECURITY_SERVER_RETURN_CODE_ACCESS_GRANTED &&
+                       hdr->return_code != SECURITY_SERVER_RETURN_CODE_ACCESS_DENIED)
+       {
+               SEC_SVR_DBG("response error: %d", hdr->return_code);
+               return return_code_to_error_code(hdr->return_code);
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+int recv_pid_response(int sockfd, response_header *hdr, int *pid)
+{
+       int retval;
+
+       retval = recv_generic_response(sockfd, hdr);
+       if(retval != SECURITY_SERVER_SUCCESS)
+               return return_code_to_error_code(hdr->return_code);
+
+       retval = read(sockfd, pid, sizeof(int));
+       if(retval < sizeof(int))
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Client: Receive failed %d", retval);
+               return  SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+int recv_pwd_response(int sockfd, response_header *hdr,
+       unsigned int *current_attempts,
+       unsigned int *max_attempts,
+       unsigned int *valid_secs)
+{
+       int retval;
+       *current_attempts = 0;
+       *max_attempts = 0;
+       *valid_secs = 0;
+
+       retval = recv_generic_response(sockfd, hdr);
+
+       switch(retval)
+       {
+               case SECURITY_SERVER_ERROR_PASSWORD_EXIST:
+               case SECURITY_SERVER_ERROR_NO_PASSWORD:
+               case SECURITY_SERVER_ERROR_PASSWORD_MISMATCH:
+               case SECURITY_SERVER_ERROR_PASSWORD_RETRY_TIMER:
+               case SECURITY_SERVER_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED:
+               case SECURITY_SERVER_ERROR_PASSWORD_EXPIRED:
+               case SECURITY_SERVER_ERROR_PASSWORD_REUSED:
+               case SECURITY_SERVER_SUCCESS:
+                       break;
+               default:
+                       return return_code_to_error_code(hdr->return_code);
+       }
+
+       retval = read(sockfd, current_attempts, sizeof(unsigned int));
+       if(retval < sizeof(unsigned int))
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Client: Receive failed %d", retval);
+               return  SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+       retval = read(sockfd, max_attempts, sizeof(unsigned int));
+       if(retval < sizeof(unsigned int))
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Client: Receive failed %d", retval);
+               return  SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+       retval = read(sockfd, valid_secs, sizeof(unsigned int));
+       if(retval < sizeof(unsigned int))
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Client: Receive failed %d", retval);
+               return  SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+
+    //if come here there were no errors
+    return SECURITY_SERVER_SUCCESS;
+}
+
+/* Authenticate client application *
+ * Currently it only gets peer's credential information only *
+ * If we need, we can extend in the futer */
+int authenticate_client_application(int sockfd, int *pid, int *uid)
+{
+       int retval = 0;
+       struct ucred cr;
+       unsigned int cl = sizeof(cr);
+
+       /* get PID of socket peer */
+       if(getsockopt(sockfd, SOL_SOCKET, SO_PEERCRED, &cr, &cl) != 0)
+       {
+               retval = SECURITY_SERVER_ERROR_SOCKET;
+               SEC_SVR_DBG("%s", "getsockopt failed");
+               *pid = 0;
+               goto error;
+       }
+       *pid = cr.pid;
+       *uid = cr.uid;
+
+       /* Authenticate client that it's real client application */
+       /* TBA */
+
+error:
+       return retval;
+}
+
+/* Checking client is pre-defined middleware daemons *
+ * Check privilege API is only allowed to middleware daemons *
+ * cmd line list of middleware daemons are listed in
+ * /usr/share/security-server/mw-list */
+int search_middleware_cmdline(char *cmdline)
+{
+       FILE *fp = NULL;
+       int ret;
+       char middleware[SECURITY_SERVER_MAX_PATH_LEN];
+
+       /* Open the list file */
+       fp = fopen(SECURITY_SERVER_MIDDLEWARE_LIST_PATH, "r");
+       if(fp == NULL)
+       {
+               /* error on file */
+               SEC_SVR_DBG("%s", "Error oening mw-list file");
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+
+       /* Search each line */
+       ret = SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED;
+       while(fgets(middleware, SECURITY_SERVER_MAX_PATH_LEN, fp) != NULL)
+       {
+               if(strncmp(middleware, cmdline, strlen(middleware)-1) == 0)
+               {
+                       /* found */
+                       SEC_SVR_DBG("%s", "found matching cmd line");
+                       ret = SECURITY_SERVER_SUCCESS;
+                       break;
+               }
+
+       }
+       if(fp != NULL)
+               fclose(fp);
+       return ret;
+}
+
+/* Authenticate the application is middleware daemon
+ * The middleware must run as root and the cmd line must be pre listed */
+int authenticate_client_middleware(int sockfd, int *pid)
+{
+       int retval = SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED;
+       struct ucred cr;
+       unsigned int cl = sizeof(cr);
+       char *cmdline = NULL;
+
+       *pid = 0;
+
+       /* get PID of socket peer */
+       if(getsockopt(sockfd, SOL_SOCKET, SO_PEERCRED, &cr, &cl) != 0)
+       {
+               retval = SECURITY_SERVER_ERROR_SOCKET;
+               SEC_SVR_DBG("%s", "Error on getsockopt");
+               goto error;
+       }
+
+       /* All middlewares will run as root */
+       if(cr.uid != 0)
+       {
+               retval = SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED;
+               SEC_SVR_DBG("Non root process has called API: %d", cr.uid);
+               goto error;
+       }
+
+       /* Read command line of the PID from proc fs */
+       cmdline = read_cmdline_from_proc(cr.pid);
+       if(cmdline  == NULL)
+       {
+               /* It's weired. no file in proc file system, */
+               retval = SECURITY_SERVER_ERROR_FILE_OPERATION;
+               SEC_SVR_DBG("Error on opening /proc/%d/cmdline", cr.pid);
+               goto error;
+       }
+
+       /* Search cmdline of the peer that is really middleware executable */
+       retval = search_middleware_cmdline(cmdline);
+       *pid = cr.pid;
+
+error:
+       if(cmdline != NULL)
+               free(cmdline);
+
+       return retval;
+}
+
+/* Authenticate the application is middleware daemon
+ * The middleware must run as root and the cmd line must be pre listed */
+int authenticate_developer_shell(int sockfd)
+{
+       int retval = SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED;
+       struct ucred cr;
+       unsigned int cl = sizeof(cr);
+       char *cmdline = NULL;
+
+       /* get PID of socket peer */
+       if(getsockopt(sockfd, SOL_SOCKET, SO_PEERCRED, &cr, &cl) != 0)
+       {
+               retval = SECURITY_SERVER_ERROR_SOCKET;
+               SEC_SVR_DBG("%s", "Error on getsockopt");
+               goto error;
+       }
+
+       /* All middlewares will run as root */
+       if(cr.uid != SECURITY_SERVER_DEVELOPER_UID)
+       {
+               retval = SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED;
+               SEC_SVR_DBG("Non root process has called API: %d", cr.uid);
+               goto error;
+       }
+
+       /* Read command line of the PID from proc fs */
+       cmdline = read_cmdline_from_proc(cr.pid);
+       if(cmdline  == NULL)
+       {
+               /* It's weired. no file in proc file system, */
+               retval = SECURITY_SERVER_ERROR_FILE_OPERATION;
+               SEC_SVR_DBG("Error on opening /proc/%d/cmdline", cr.pid);
+               goto error;
+       }
+
+       /* Search cmdline of the peer that is really debug tool */
+       if(strncmp(cmdline, SECURITY_SERVER_DEBUG_TOOL_PATH, strlen(SECURITY_SERVER_DEBUG_TOOL_PATH)) != 0)
+       {
+               SEC_SVR_DBG("Error: Wrong cmdline [%s]", cmdline);
+               retval = SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED;
+               goto error;
+       }
+       retval = SECURITY_SERVER_SUCCESS;
+       SEC_SVR_DBG("%s", "Client Authenticated");
+
+error:
+       if(cmdline != NULL)
+               free(cmdline);
+
+       return retval;
+}
+
+int free_argv(char **argv, int argc)
+{
+       int i;
+       if(argv == NULL)
+       {
+               SEC_SVR_DBG("%s", "Cannot free NULL pointer");
+               return SECURITY_SERVER_ERROR_INPUT_PARAM;
+       }
+       for (i=0;i<argc;i++)
+       {
+               if(argv[i] != NULL)
+                       free(argv[i]);
+       }
+       free(argv);
+       return SECURITY_SERVER_SUCCESS;
+}
+
diff --git a/src/security-srv/include/SLP_security-model_PG.h b/src/security-srv/include/SLP_security-model_PG.h
new file mode 100644 (file)
index 0000000..0f2dc07
--- /dev/null
@@ -0,0 +1,73 @@
+/**
+ * @defgroup SLP_PG_SECURITY Security and Permissions
+ * @ingroup SLP_PG
+ * @{
+ *     @brief  <em class="ref">Also see </em>  [ @ref SecurityFW ]
+ *     @defgroup CertificateManager_PG
+ *     @defgroup Security_Server_PG
+ *     @defgroup SecureStorage_PG
+ *     @}
+ *     @defgroup SLP_PG_SECURITY
+ *     @ingroup SLP_PG
+ *     @{
+
+<h1 class="pg">Security Requirements</h1>
+<h2>Privileges </h2>
+<p>All processes MUST have least privilege to operate their own purpose. middleware daemons might run as root to satisfy their functional requirements, but there MUST BE NO application process which is running as root. In this document application represents all processes which has user interface to the end user.</p>
+<p>Each application process should have different privileges to satisfy least privilege, therefore there should be an entity to take care of process privileges.</p>
+<p>If an application process requires higher (system or root) privilege to provide some function, the function must be implemented in a middleware daemon and the function must be provided as an API to application</p>
+<h2>Application Sandboxing</h2>
+<p>All applications MUST NOT interfere each other. Interference covers killing other processes, modify or delete other application's files, overwrite or read other application process' memory area, masquerading other applications, and reading other application's sensitive files.</p>
+<h2>Middleware Resource Protection</h2>
+<p>All middleware resources MUST be protected by unauthorized access from applications. If the middleware is a daemon process, the process must not be interfered by applications, if the middleware is a library and the resources of the middleware are files, then the files must not be modified by unauthorized process.</p>
+<p>The resources must be protected at the resource level, not API level because API could be easily detoured</p>
+<h2>Privilege Escalation</h2>
+<p>There should be no privilege escalation, but by some management and/or manufacturing reason, unpredicted privilege escalation might be necessary. In this situation the modules which require privilege escalation MUST be highly reviewed and managed by developers and security manager.</p>
+<h1 class="pg">Security Model</h1>
+<h2>Background Information</h2>
+<h3>Discretionary Access Control</h3>
+<p>Linux kernel have supported discretionary access control (DAC) from the very beginning which controls access based on user ID, group ID of a process and owner of file that the process tries to access. This access control mechanism has been evolved with the Linux system evolution, additionally, SLP is not an embedded Linux platform but a normal Linux platform, therefore SLP has full support on DAC.</p>
+<p>In Linux all process is executed with user ID and groups, normally inherited by parent process. The processes which are executed in booting script will be executed as root user because the parent process "init" is root process. Any other user processes including user shell will be executed as an user that is logged in by the console login process. The groups that the process belongs to are also inherited by parent process, the list of group ID is assigned when the user is logged in based on "/etc/group" file. A process can be belonged more than thousand of groups (max 65,536 but I think too many groups might occur some problem).</p>
+<p>Only root process can change user ID and groups of the process by calling setuid() and setgroups() function, so if a root process is changed user to non root, then it can never change its user ID and groups again.</p>
+<p>There is a special feature to change user ID even the process is not owned by root user. If the executable file has setuid sticky bit, then the process will be executed as the owner of executable files. This is very important for access control because it can produce "privilege escalation" which can harm the platform security. In Linux PC, utilities such as "sudo" and "su" has this feature because these command need to change user to root or other user ID. These utilities first executed as root user and then changes to other user ID if needed.</p>
+<p>In Linux file system, all files are labeled with security context which describes owner user ID and group ID of the file and the permission of each accessible entity which are owner, group, and others. Permissions are consisting of read, write, and execute for each entity. If accessing process's user ID is same to owner of the file to be accessed, then the owner's permission is applied, if the process has the group that is labeled on the file, then the group's permission is applied, if not, then the other's permission is applied. All these functions are implemented in Linux kernel, so you don't need anything more for the feature. By the way, root process bypasses all the permission checking, that is root process can access all files. You can refer to Linux fundamental documents for this feature.</p>
+<p>The owner of a file can change permission of the file but, cannot change owner of the file. Only root process can change owner of the file, so if you want to change owner of a file, you have to be root.</p>
+<h3>Mandatory Access Control</h3>
+<p>DAC is great security feature of Linux, but sometime DAC is not sufficient to protect platform. DAC is based on user ID, group and file’s permissions, the granularity is limited to user ID level, in some way platform may need more precise access control than DAC. Mandatory Access Control (MAC) provides this security feature to give better and precise access control based on labeling and policy.</p>
+<p>MAC was not a part of standard Linux in the beginning, but since there were several requirements, so from kernel 2.6 version, some of the MAC mechanisms have been added to main line kernel source as optional features.</p>
+<p>MAC needs security context labeling and policy to control. Usually, all files have its security context described in extended attribute(xattr) of file system or some other places if xattr is not supported. Policy describes which subject (process) has permission to do something (operation) to some object. It doesn’t refer to owner and permission of the DAC field, just refer to security context of subject and object, and then searches allowed operations. Object can be files, directories, system calls, sockets and so on, each MAC mechanism has different set of objects.</p>
+<p>Using MAC, even root process can be denied to access some important object and some chosen root process can be allowed. Currently there are many MAC mechanisms such as SELinux, App-Armor, SMACK, RBAC, grsecurity and so on, and each of them has different objectives and approach.</p>
+<h2>Security Model</h2>
+<p>Since SLP is a Linux platform, its security model is similar to other Linux platform’s security model. In SLP, DAC and MAC are used, but biggest difference is that we need user space access control such as telephony, system management and so on.</p>
+<h3>Discretionary Access Control</h3>
+<p>- <b><i>User ID policy for processes</i></b></p>
+<p>All middleware daemons are running as root user ID, it's natural because daemons are executed by init process which is root process. There are a few exceptions that are not running as root even though the process is executed by init process. They are menu-screen, voice-call-daemon, and indicator. The reason is that the exceptional processes are executed by init process but they are not middleware, but applications. These special processes maybe increased at any time.</p>
+<p>Normal applications are executed as non root user ID. To achieve application sandboxing, all applications should run as all different user IDs, but it might occur complexity to the platform, so all the inhouse applications are executed as same user, and each 3rd party application will be executed as each different user ID.</p>
+<p><b><i>- Group ID for fine grained access control</i></b></p>
+<p>In Linux, a single process can be owned by a single user ID, but it can be belonged to multiple group IDs (max 65,536). In current desktop Linux such as Ubuntu, they use group ID to enforce access control for shared objects, such as CD-ROM, printer, audio, and so on. In SLP, we will use group ID as same usage, but the object will be different than normal desktop Linux, such as telephony, contact, and so on.</p>
+<p>As a result, each application will be given different group IDs based on its required privilege.</p>
+<p><i><b>- Security context on files</b></i></p>
+<p>For security and safety reason, basically all files in SLP owned by root as other Linux platform does, and then, non root user process cannot modify any files. The permission of normal files will be "rw-r--r--" which means only owner can modify or delete and the group member and others only can read, this is also same as other Linux platform. Lastly permission of executive files will be "rwxr-xr-x", so anybody can execute them, and also same as others.</p>
+<p>But there are many special files to be shared and modified by non root processes for example database files and device files in dev file system. In these cases, group ID of file is used. A shared file is owned by root but belonged to proper group ID which describes the file's content or object. The permission of the file could be "rw-rw-r--" to allow the processes belonged to the group can modify the file.</p>
+<p>There are some secret files to be protected by unauthorized read operation, then we can use same method as above but only difference will be no read permission to others, such as "rw-------", or "rw-rw----".</p>
+<p>Finally, there will be newly created files from middleware daemons and applications. There is default umask "022" , so if the created file is from middleware daemon, then the context of the file will be "root:root rw-r--r--", which means only root can modify and other users can read the file, if an application creates a file, then context wiil be "app_user:app_user rw-r--r--", so only the application can modify the file. This is normal usage but there must be some special cases which the file should be shared within applications. But, chown command and function only works under root privilege so applications cannot change owner of created files, so only thing possible is to change permission by chmod function. But there is only one option, share to none or share to all.</p>
+<h3>Mandatory Access Control</h3>
+<p>Mandatory access control(MAC) is currently out of scope of the SLP because there is almost no concrete threat which could be protected by MAC. Only one possible threat is that the network access by unauthorized process when there is a connected interface is already created. The adversary can monitor network interface status and if there is a new interface created, then it can use socket directly and it's possible to send some data by the socket. It's not possible to protect only by DAC.</p>
+<h2>User Space</h2>
+<p>There are many objects in user space such as making a phone call, sending a SMS message, which are not recognizable by kernel because thses objects are implemented in a daemon process, applications will request access by IPC and the kernel cannot manage inside of IPC messages. In these cases we must have a user space trusted entity which judges and controls access to such objects, which sits between applications and middleware daemons.</p>
+<p>To enable this, the entity must get identity of the subject application and object to be accessed, but it's not easy because some of the IPC mechanisms don't support peer's identity acquisition. For example all the dbus messages are routed by dbus daemon, so the receiver only guarantees dbus daemon sent the message, not the original sender of the message. Therefore, we have to support such mechanism to guarantee the original sender's identity to the final receiver along with reliable and secure access decision mechanism.</p>
+<p>To enforce access control, there must be an access policy which should be stored securely and it must be reliable. In SLP we utilized group ID for this policy. All processes have their user ID and groups which are controlled by kernel, each user space object is described as a group ID and the subject process will have the group ID if the application process has corresponding group ID then the access to be allowed, if not, the access will be denied.</p>
+<p>One more function required is that the enforcing entity needs to know other processes groups information. proc file system can be used. In proc file system, there is a file named "status", which describes various information about a process including all groups that the process belong to.</p>
+<h1 class="pg">Implementation</h1>
+<h2>User ID and Group ID Administration for Processes</h2>
+<p>As described above, all the daemons will be run by root, this is natural because all the booting scripts are executed by init process which is a root process, so all the processes executed by booting scripts will be run as root automatically. But there are some exceptions. There are some processes which are executed by booting scripts but not actually daemons such as menu screen and indicator. These processes must drop their privilege to a normal user, so in the beginning of their code, they change their user ID and groups to a normal user.</p>
+<p>All other applications will be executed by AUL (application utility library). When a new application process is requested to be executed, AUL daemon (launchpad) which is a root process receives the request, fork() and execute requested application in the child process. During this process, after forking a process, the launchpad child process changes its user ID to a corresponding user ID, changes matching groups, changes home directory, and execute the application. This is similar to su command in Linux environment.</p>
+<p>When a new application is installed, package manager adds a new user which has same user name with package name but substituting dot '.' to underscore '_'. But this feature is currently out of scope of the SLP.</p>
+<p>The group ID will be described as manifest permission item which described in control file of the debian package. Manifest permission items and group IDs will not correspond 1 to 1, basically one permission item will mean a set of group IDs to enable the permission, the sets might consist of 1 group ID or many group IDs. When a new application is installed, these groups will be assigned to the user ID, this could be implemented by adduser command. But this feature is currently out of scope of the SLP.</p>
+<h2>Changing Owner, Group and Permissions for Files</h2>
+<p>Since SLP uses debian package for the internal build system, all files which are installed by debian are automatically owned by root and their permissions set to 0644 (rw-r--r--), which means only root can modify and other processes only can read. But in the platform there are various files which should be modified by applications also, so we need to modify the ownership and permission intentionally.</p>
+<p>The only way to do this is by using postinst script of each of the debian package. On each package if there are some files should be shared, the package developer should add a few line to postinst file to change owner ship and permission to the files. To change owner, of a file, you have to be a root, if you are using fakeroot, the chown will not be affected.</p>
+*/
+/**
+*@}
+*/
diff --git a/src/security-srv/include/SLP_security-server_PG.h b/src/security-srv/include/SLP_security-server_PG.h
new file mode 100644 (file)
index 0000000..c1016ab
--- /dev/null
@@ -0,0 +1,350 @@
+/**
+ *
+ * @ingroup   SLP_PG
+ * @defgroup  Security_Server_PG Security Server
+@{
+
+<h1 class="pg">Introduction</h1>
+<p>In Linux system, access control is enforced in the kernel space objects such as file, socket, directory, and device which are all described as files. In SLP, many objects are defined in user space which cannot be described as file, for example, make a phone call, send a SMS message, connect to the Internet, and modify SIM password. Some of the objects in user space are very sensitive to the platform and the phone business as well as user's property. Therefore the user space objects needed to be protected.</p>
+<p>To protect such user space objects, there must be a kind of credential to decide access result, and the credential must be trusted. Since process has privileges and the objects only has label, so some trusted entity should check the process has right privilege to access objects, and the security hooks to check this privilege should be located in the each middleware service daemons which provide the objects to the applications.</p>
+<p>Security Server uses group IDs of Linux system that are assigned to each process. In detail, if a process requests to get some user-space service to a middleware daemon, the middleware daemon requests to check privilege of some process, then the security server checks given gid is assigned to the process or not. If yes, then return yes, if no, then return no.</p>
+<p>If an application and middleware daemon uses Linux standard IPC such as Unix domain socket, there is no need to introduce 3rd party process to check gid that the process has. But some of service uses non Linux standard IPC such as telephony - using dbus - which the peer's credential is not propagated to the other peer. As a result to meet all the system's environment, we introduce Security Server.</p>
+<p>
+Security Server uses a random token named "cookie" to identify a process, the cookie needed not to be abled to guess easily, so it's quite long (currently 20 bytes), and only kept by Security Server process memory</p>
+
+<h1 class="pg">Security Server Architecture</h1>
+@image html SLP_Security-Server_PG_image001.png
+<p>Above fiture explains software architecture of Security Server. It is client-server structure, and communicates by IPC. The IPC must be point-2-point mechanism such as UNIX domain socket, not server related IPC such as dbus, because it's not easy to guarantee the other peer's security.</p>
+<p>Application or middleware process can call Security Server API to assign a new cookie or checking privilege of the given cookie. In this case, client library authenticates IPC peer and check the peer is Security Server process. In the same sense, Security Server authenticates client also.</p>
+<p>Application requests cookie to Security Server before requesting the service to the middleware daemon. Security Server authenticates the client, generates a random cookie, stores the cookie into local memory, and responds to the client with the cookie value. Client loads the cookie in the request message and sends to the middleware server, then the receiver middleware daemon check the privilege of the given cookie by calling Security Server API. Security Server compares received cookie value with stored cookie, checks and responds to the middleware daemon. Finally middleware daemon knows the client's privilege and it decides continue or block the request.</p>
+
+<h2>Sub components</h2>
+
+<h3>Client library</h3>
+@image html SLP_Security-Server_PG_image002.png
+<p>Client library is linked to application or middleware daemon. Therefore it belongs to the caller process, so uid, pid, and groups are also same. If the application calls cookie request API, the client compose cookie request message and sends to the Security Server and wait for the response. After receiving the response, first checks the response is from Security Server, and if it's true, it stores cookie into cookie container.</p>
+<p>Middleware daemon also links same client library, but by the difference of the calling APIs, the functions are different. Middleware daemon first receives cookie value loaded in service request from the client, and then the middleware calls Security Server API to check the cookie has the privilege to the service and waits for the response. After receiving the response, it authenticates the response is really from Security Server, and continue service by the result of the API.</p>
+
+<h3>Security Server Daemon</h3>
+@image html SLP_Security-Server_PG_image003.png
+<p>Security Server daemon is a Unix domain socket server, but it only has single thread and single process to get rid of race condition for the proc file system and cookie list to be shared. It’s easy to manage, more secure and the Security Server itself doesn't need to maintain a session for a long time.</p>
+<p>When request API is received from the client, Security Server first parses, and authenticates the message, and creates cookie or checks privilege. Cookie is a 20 bytes random string too hard to be guessed. So it's hard to be spoofed.</p>
+<p>Cookie generator generates a cookie based on proc file system information of the client process with group IDs the client belongs to, and privilege checker searches received cookie value with stored cookie list and checks the privilege.</p>
+<p>Cookie list is a linked list implemented in memory and it stores and manages generated cookie.</p>
+
+<h1 class="pg">Dependency</h1>
+<p>The Security Server has high dependency on Linux kernel, precisely the proc file system. Since Security Server refers to proc file system with processes group ID, so the kernel must support group ID representation on the proc file system.</p>
+<p>In kernel version 2.6, there is a file in proc file system "/proc/[pid]/status" which describes various information about the process as text, it has a line named "Groups:" and it lists the group IDs that the process is belonged to. But there is a drawback in this file, it only shows at most 32 group IDs, if number of groups of the process is bigger than 32, it ignores them.</p>
+<p>To enable to show all the groups you have to patch the kernel source code to show more groups than 32, but there is another drawback. All files in the proc file system has size limit to 4k bytes because the file buffer size is 4k bytes, so it's not possible to show all possible groups of the process (64k), but currently number of all groups in the LiMo platform is much lower than the size, so it's not a big problem. But near future we need to apply this patch into kernel mainline source code by any form.</p>
+
+<h1 class="pg">Scenarios</h1>
+@image html SLP_Security-Server_PG_image004.png
+<p>Security Server process view is described in figure above. It's explained in above, so it's not necessary to explain again. But one possible question may arise, that why do we need Security Server, that the service daemon can authenticates application process by the IPC, and the daemon can check proc file system by itself, so it seems that we may not need to have Security Server at all<p>
+@image html SLP_Security-Server_PG_image005.png
+<p>But there is exceptional process view described in figure above. If the middleware's IPC mechanism is dbus, then the daemon cannot guarantee the identity of the requesting application. In this case, there is no possible way to check and authenticate application from the middleware daemon directly. We need a trusted 3rd party to guarantee such identity and privilege, therefore Security Server is required.</p>
+<p>As described above, the cookie value is the key of the security of Security Server. The cookie value must not to be exposed into the platform, the cookie value must be stored securely that only Security Server and the application process knows the value. Even the middleware daemon should not cache the cookie for the security reason</p>
+
+<h1 class="pg">APIs</h1>
+
+<h3 class="pg">security_server_get_gid</h3>
+<table>
+       <tr>
+               <td>
+                       API Name:
+               </td>
+               <td>
+                       gid_t security_server_get_gid(const char *object)
+               </td>
+       </tr>
+       <tr>
+               <td>
+                       Input Parameter:
+               </td>
+               <td>
+                       object name as Null terminated string
+               </td>
+       </tr>
+       <tr>
+               <td>
+                       Output Parameter:
+               </td>
+               <td>
+                       N/A
+               </td>
+       </tr>
+       <tr>
+               <td>
+                       Return value:
+               </td>
+               <td>
+                       On success, returns the integer gid of requested object.<br>
+                       On fail, returns negative integer
+               </td>
+       </tr>
+</table>
+This API returns the gid from given object name. This API is only allowed to be called from middleware service daemon which is running under root privilege
+
+<h3 class="pg">security_server_get_object_name</h3>
+<table>
+       <tr>
+               <td>
+                       API Name:
+               </td>
+               <td>
+                       int security_server_get_object_name(gid_t gid, char *object, size_t max_object_size)
+               </td>
+       </tr>
+       <tr>
+               <td>
+                       Input Parameter:
+               </td>
+               <td>
+                       gid, max_object_size
+               </td>
+       </tr>
+       <tr>
+               <td>
+                       Output Parameter:
+               </td>
+               <td>
+                       object as null terminated string
+               </td>
+       </tr>
+       <tr>
+               <td>
+                       Return value:
+               </td>
+               <td>
+                       On success, returns 0<br>
+                       On fail, returns negative integer
+               </td>
+       </tr>
+</table>
+This API is opposite with security_server_get_gid(). It converts given gid to object name which buffer size is max_object_size. If object name is bigger then max_object_size then it returns SECURITY_SERVER_API_ERROR_BUFFER_TOO_SMAL error.
+
+<h3 class="pg">security_server_request_cookie</h3>
+<table>
+       <tr>
+               <td>
+                       API Name:
+               </td>
+               <td>
+                       gid_t security_server_request_cookie(char *cookie, size_t max_cookie)
+               </td>
+       </tr>
+       <tr>
+               <td>
+                       Input Parameter:
+               </td>
+               <td>
+                       max_cookie
+               </td>
+       </tr>
+       <tr>
+               <td>
+                       Output Parameter:
+               </td>
+               <td>
+                       cookie
+               </td>
+       </tr>
+       <tr>
+               <td>
+                       Return value:
+               </td>
+               <td>
+                       On success, returns 0<br>
+                       On fail, returns negative integer
+               </td>
+       </tr>
+</table>
+This API requests a cookie to Security Server. max_cookie is the size of buffer cookie to be filled with cookie value, if max_cookie smaller then cookie size, then this API returns SECURITY_SERVER_API_ERROR_BUFFER_TOO_SMAL error.
+
+<h3 class="pg">security_server_get_cookie_size</h3>
+<table>
+       <tr>
+               <td>
+                       API Name:
+               </td>
+               <td>
+                       int security_server_get_cookie_size(void)
+               </td>
+       </tr>
+       <tr>
+               <td>
+                       Input Parameter:
+               </td>
+               <td>
+                       N/A
+               </td>
+       </tr>
+       <tr>
+               <td>
+                       Output Parameter:
+               </td>
+               <td>
+                       N/A
+               </td>
+       </tr>
+       <tr>
+               <td>
+                       Return value:
+               </td>
+               <td>
+                       size of cookie value
+               </td>
+       </tr>
+</table>
+This API simply returns the size of cookie.
+
+<h3 class="pg">security_server_check_privilege</h3>
+<table>
+       <tr>
+               <td>
+                       API Name:
+               </td>
+               <td>
+                       int security_server_check_privilege(const char *cookie, gid_t privilege)
+               </td>
+       </tr>
+       <tr>
+               <td>
+                       Input Parameter:
+               </td>
+               <td>
+                       cookie, privilege
+               </td>
+       </tr>
+       <tr>
+               <td>
+                       Output Parameter:
+               </td>
+               <td>
+                       N/A
+               </td>
+       </tr>
+       <tr>
+               <td>
+                       Return value:
+               </td>
+               <td>
+                       On success, returns 0<br>
+                       On fail, returns negative integer
+               </td>
+       </tr>
+</table>
+This API checks the cookie value has privilege for given gid. This API should be called by middleware server only after application embed cookie into the request message and sent to the middleware server. The middleware server should aware with the privilege parameter because it knows the object which the client application tries to access.
+
+
+<h1 class="pg">Implementation Guide</h1>
+
+<h2>Middleware server side</h2>
+<p>
+In middleware, implementation is focused on checking privilege of the requested client application. To call security_server_check_privilege() API, you have to get the gid value first, and this can be achieved by calling security_server_get_gid() API. The pre-condition of this scenario is that the middleware server knows the name of the object. Once you get the gid values, you can cache them for better performance. </p>
+<p>
+Once a client application requests to access the middleware’s object, the client should embed cookie into the request message. If not, the security is not guaranteed. After getting request and embedded cookie, the middleware server call security_server_check_privilege() API to check the client is allowed to access the object, the security server will respond the result. Finally the server need to decide continue the service or not.</p>
+
+@code
+static gid_t g_gid;
+
+int get_gid()
+{
+       int ret;
+       // Get gid of telephony call - example object
+       ret = security_server_get_gid("telephony_call");
+       if(ret < 0)
+       {
+               return -1;
+       }
+       g_gid = ret;
+       return 0;
+}
+
+int main(int argc, char * argv[])
+{
+       char *cookie = NULL;
+       int ret, cookie_size;
+
+
+       ...
+
+
+               // Initially get gid about the object which is interested in
+               if(get_gid() < 0)
+                       exit(-1);
+
+       // get cookie size and malloc it if you want
+       cookie_size = security_server_get_cookie_size();
+       cookie = malloc(cookie_size);
+
+       ...
+
+       // If a request has been received
+       // First parse the request and get the cookie value
+       // Let's assume that the buffer cookie is filled with received cookie value
+       ret = security_server_check_privilege(cookie, cookie_size);
+       if(ret == SECURITY_SERVER_API_ERROR_ACCESS_DENIED)
+       {
+               // Access denied
+               // Send error message to client application
+       }
+       else if( ret != SECURITY_SERVER_SUCCESS)
+       {
+               // Error occurred
+               // Check error condition 
+       }
+       else
+       {
+               // Access granted
+               // Continue service
+               ...
+       }
+
+
+       ...
+
+
+       free(cookie);
+       ...
+}
+@endcode
+
+<h2>Client application side</h2>
+<p>
+In client application, what you need is just request a cookie and embed it into request message</p>
+
+@code
+int some_platform_api()
+{
+       char *cookie = NULL;
+       int cookie_size, ret;
+
+       ...
+
+
+       // malloc the cookie
+       cookie_size = security_server_get_cookie_size();
+       cookie = malloc(cookie_size);
+
+       ...
+
+
+               // Request cookie from the security server
+               ret = security_server_request_cookie(cookie, cookie_size);
+       if(ret < 0)
+       {
+               // Some error occurred
+               return -1;
+       }
+
+       // embed cookie into the message and send to the server
+
+       ...
+       free(cookie);
+}
+@endcode
+
+*/
+/**
+*@}
+*/
diff --git a/src/security-srv/include/security-server-comm.h b/src/security-srv/include/security-server-comm.h
new file mode 100644 (file)
index 0000000..3a3de6f
--- /dev/null
@@ -0,0 +1,136 @@
+/*
+ *  security-server
+ *
+ *  Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ *
+ */
+
+#ifndef SECURITY_SERVER_COMM_H
+#define SECURITY_SERVER_COMM_H
+
+/* Message */
+typedef struct
+{
+       unsigned char version;
+       unsigned char msg_id;
+       unsigned short msg_len;
+} basic_header;
+
+typedef struct
+{
+       basic_header basic_hdr;
+       unsigned char return_code;
+} response_header;
+
+/* Message Types */
+#define SECURITY_SERVER_MSG_TYPE_COOKIE_REQUEST                0x01
+#define SECURITY_SERVER_MSG_TYPE_COOKIE_RESPONSE       0x02
+#define SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_REQUEST       0x03
+#define SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_RESPONSE      0x04
+#define SECURITY_SERVER_MSG_TYPE_OBJECT_NAME_REQUEST   0x05
+#define SECURITY_SERVER_MSG_TYPE_OBJECT_NAME_RESPONSE  0x06
+#define SECURITY_SERVER_MSG_TYPE_GID_REQUEST           0x07
+#define SECURITY_SERVER_MSG_TYPE_GID_RESPONSE          0x08
+#define SECURITY_SERVER_MSG_TYPE_PID_REQUEST           0x09
+#define SECURITY_SERVER_MSG_TYPE_PID_RESPONSE          0x0a
+#define SECURITY_SERVER_MSG_TYPE_TOOL_REQUEST          0x0b
+#define SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE         0x0c
+#define SECURITY_SERVER_MSG_TYPE_VALID_PWD_REQUEST     0x0d
+#define SECURITY_SERVER_MSG_TYPE_VALID_PWD_RESPONSE    0x0e
+#define SECURITY_SERVER_MSG_TYPE_SET_PWD_REQUEST       0x0f
+#define SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE      0x10
+#define SECURITY_SERVER_MSG_TYPE_RESET_PWD_REQUEST     0x11
+#define SECURITY_SERVER_MSG_TYPE_RESET_PWD_RESPONSE    0x12
+#define SECURITY_SERVER_MSG_TYPE_CHK_PWD_REQUEST       0x13
+#define SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE      0x14
+#define SECURITY_SERVER_MSG_TYPE_SET_PWD_HISTORY_REQUEST       0x15
+#define SECURITY_SERVER_MSG_TYPE_SET_PWD_HISTORY_RESPONSE      0x16
+#define SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_NEW_REQUEST   0x17
+#define SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_NEW_RESPONSE  0x18
+#define SECURITY_SERVER_MSG_TYPE_SET_PWD_MAX_CHALLENGE_REQUEST   0x19
+#define SECURITY_SERVER_MSG_TYPE_SET_PWD_MAX_CHALLENGE_RESPONSE  0x1a
+#define SECURITY_SERVER_MSG_TYPE_SET_PWD_VALIDITY_REQUEST    0x1b
+#define SECURITY_SERVER_MSG_TYPE_SET_PWD_VALIDITY_RESPONSE   0x1c
+#define SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE      0xff
+
+/* Return code */
+#define SECURITY_SERVER_RETURN_CODE_SUCCESS            0x00
+#define SECURITY_SERVER_RETURN_CODE_BAD_REQUEST                0x01
+#define SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED      0x02
+#define SECURITY_SERVER_RETURN_CODE_ACCESS_GRANTED     0x03
+#define SECURITY_SERVER_RETURN_CODE_ACCESS_DENIED      0x04
+#define SECURITY_SERVER_RETURN_CODE_NO_SUCH_OBJECT     0x05
+#define SECURITY_SERVER_RETURN_CODE_NO_SUCH_COOKIE     0x06
+#define SECURITY_SERVER_RETURN_CODE_NO_PASSWORD                0x07
+#define SECURITY_SERVER_RETURN_CODE_PASSWORD_EXIST             0x08
+#define SECURITY_SERVER_RETURN_CODE_PASSWORD_MISMATCH  0x09
+#define SECURITY_SERVER_RETURN_CODE_PASSWORD_MAX_ATTEMPTS_EXCEEDED     0x0a
+#define SECURITY_SERVER_RETURN_CODE_PASSWORD_EXPIRED   0x0b
+#define SECURITY_SERVER_RETURN_CODE_PASSWORD_REUSED    0x0c
+#define SECURITY_SERVER_RETURN_CODE_PASSWORD_RETRY_TIMER       0x0d
+#define SECURITY_SERVER_RETURN_CODE_SERVER_ERROR       0x0e
+
+int return_code_to_error_code(int ret_code);
+int create_new_socket(int *sockfd);
+int safe_server_sock_close(int client_sockfd);
+int connect_to_server(int *fd);
+int accept_client(int server_sockfd);
+int authenticate_client_application(int sockfd, int *pid, int *uid);
+int authenticate_client_middleware(int sockfd, int *pid);
+int authenticate_developer_shell(int sockfd);
+char *read_cmdline_from_proc(pid_t pid);
+int send_generic_response (int sockfd, unsigned char msgid, unsigned char return_code);
+int send_cookie(int sockfd, unsigned char *cookie);
+int send_object_name(int sockfd, char *obj);
+int send_gid(int sockfd, int gid);
+int send_cookie_request(int sock_fd);
+int send_gid_request(int sock_fd, const char* object);
+int send_object_name_request(int sock_fd, int gid);
+int send_privilege_check_request(int sock_fd, const char*cookie, int gid);
+int send_privilege_check_new_request(int sock_fd,
+                                     const char *cookie,
+                                     const char *object,
+                                     const char *access_rights);
+int recv_get_gid_response(int sockfd, response_header *hdr, int *gid);
+int recv_get_object_name(int sockfd, response_header *hdr, char *object, int max_object_size);
+int recv_cookie(int sockfd, response_header *hdr, char *cookie);
+int recv_privilege_check_response(int sockfd, response_header *hdr);
+int recv_privilege_check_new_response(int sockfd, response_header *hdr);
+int recv_hdr(int client_sockfd, basic_header *basic_hdr);
+int recv_check_privilege_request(int sockfd, unsigned char *requested_cookie, int *requested_privilege);
+int recv_check_privilege_new_request(int sockfd,
+                                     unsigned char *requested_cookie,
+                                     char *object_label,
+                                     char *access_rights);
+int send_pid_request(int sock_fd, const char*cookie);
+int recv_pid_response(int sockfd, response_header *hdr, int *pid);
+int recv_pid_request(int sockfd, unsigned char *requested_cookie);
+int send_pid(int sockfd, int pid);
+int send_launch_tool_request(int sock_fd, int argc, const char **argv);
+int recv_generic_response(int sockfd, response_header *hdr);
+int recv_launch_tool_request(int sockfd, int argc, char *argv[]);
+int recv_pwd_response(int sockfd, response_header *hdr, unsigned int *current_attempts,
+       unsigned int *max_attempts, unsigned int *valid_days);
+int send_set_pwd_request(int sock_fd, const char*cur_pwd, const char*new_pwd,
+       const unsigned int max_challenge, const unsigned int valid_period_in_days);
+int send_set_pwd_validity_request(int sock_fd, const unsigned int valid_period_in_days);
+int send_set_pwd_max_challenge_request(int sock_fd, const unsigned int max_challenge);
+int send_chk_pwd_request(int sock_fd, const char*challenge);
+int check_socket_poll(int sockfd, int event, int timeout);
+int free_argv(char **argv, int argc);
+
+#endif
diff --git a/src/security-srv/include/security-server-common.h b/src/security-srv/include/security-server-common.h
new file mode 100644 (file)
index 0000000..355892d
--- /dev/null
@@ -0,0 +1,122 @@
+/*
+ *  security-server
+ *
+ *  Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ *
+ */
+
+#ifndef SECURITY_SERVER_COMMON_H
+#define SECURITY_SERVER_COMMON_H
+
+#include <sys/types.h>
+
+/* Definitions *********************************************************/
+/* Return value. Continuing from return value of the client header file */
+#define SECURITY_SERVER_SUCCESS                                0
+#define SECURITY_SERVER_ERROR_SOCKET                   -1
+#define SECURITY_SERVER_ERROR_BAD_REQUEST              -2
+#define SECURITY_SERVER_ERROR_BAD_RESPONSE             -3
+#define SECURITY_SERVER_ERROR_SEND_FAILED              -4
+#define SECURITY_SERVER_ERROR_RECV_FAILED              -5
+#define SECURITY_SERVER_ERROR_NO_SUCH_OBJECT           -6
+#define SECURITY_SERVER_ERROR_AUTHENTICATION_FAILED    -7
+#define SECURITY_SERVER_ERROR_INPUT_PARAM              -8
+#define SECURITY_SERVER_ERROR_BUFFER_TOO_SMALL         -9
+#define SECURITY_SERVER_ERROR_OUT_OF_MEMORY            -10
+#define SECURITY_SERVER_ERROR_ACCESS_DENIED            -11
+#define SECURITY_SERVER_ERROR_SERVER_ERROR             -12
+#define SECURITY_SERVER_ERROR_NO_SUCH_COOKIE           -13
+#define SECURITY_SERVER_ERROR_NO_PASSWORD              -14
+#define SECURITY_SERVER_ERROR_PASSWORD_EXIST           -15
+#define SECURITY_SERVER_ERROR_PASSWORD_MISMATCH                -16
+#define SECURITY_SERVER_ERROR_PASSWORD_RETRY_TIMER     -17
+#define SECURITY_SERVER_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED   -18
+#define SECURITY_SERVER_ERROR_PASSWORD_EXPIRED -19
+#define SECURITY_SERVER_ERROR_PASSWORD_REUSED  -20
+#define SECURITY_SERVER_ERROR_SOCKET_BIND              -21
+#define SECURITY_SERVER_ERROR_FILE_OPERATION           -22
+#define SECURITY_SERVER_ERROR_TIMEOUT                  -23
+#define SECURITY_SERVER_ERROR_POLL                     -24
+#define SECURITY_SERVER_ERROR_UNKNOWN                  -255
+
+/* Miscellaneous Definitions */
+#define SECURITY_SERVER_SOCK_PATH                      "/tmp/.security_server.sock"
+#define SECURITY_SERVER_DEFAULT_COOKIE_PATH            "/tmp/.security_server.coo"
+#define SECURITY_SERVER_DAEMON_PATH                    "/usr/bin/security-server"
+#define SECURITY_SERVER_COOKIE_LEN                     20
+#define MAX_OBJECT_LABEL_LEN                            32
+#define MAX_MODE_STR_LEN                                16
+#define SECURITY_SERVER_MIDDLEWARE_LIST_PATH           "/usr/share/security-server/mw-list"
+#define SECURITY_SERVER_MAX_OBJ_NAME                   30
+#define SECURITY_SERVER_MAX_PATH_LEN                   50
+#define SECURITY_SERVER_MSG_VERSION                    0x01
+#define SECURITY_SERVER_ACCEPT_TIMEOUT_MILISECOND      10000
+#define SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND      3000
+#define SECURITY_SERVER_DEVELOPER_UID                  5100
+#define SECURITY_SERVER_DEBUG_TOOL_PATH                        "/usr/bin/debug-util"
+#define SECURITY_SERVER_KILL_APP_PATH                  "/usr/bin/kill_app"
+#define SECURITY_SERVER_DATA_DIRECTORY_PATH            "/opt/data/security-server"
+#define SECURITY_SERVER_ATTEMPT_FILE_NAME      "attempts"
+#define SECURITY_SERVER_HISTORY_FILE_NAME      "history"
+#define SECURITY_SERVER_MAX_PASSWORD_LEN               32
+#define SECURITY_SERVER_HASHED_PWD_LEN                 32  /* SHA256 */
+#define SECURITY_SERVER_PASSWORD_RETRY_TIMEOUT_SECOND          1
+#define SECURITY_SERVER_MAX_PASSWORD_HISTORY   50
+#define SECURITY_SERVER_NUM_THREADS                    10
+
+/* API prefix */
+#ifndef SECURITY_SERVER_API
+#define SECURITY_SERVER_API    __attribute__((visibility("default")))
+#endif
+
+
+
+/* Data types *****************************************************************/
+/* Cookie List data type */
+typedef struct _cookie_list
+{
+       unsigned char   cookie[SECURITY_SERVER_COOKIE_LEN];     /* 20 bytes random Cookie */
+       int             path_len;                               /* Client process cmd line length */
+       int             permission_len;                         /* Client process permissions (aka group IDs) */
+       pid_t           pid;                                    /* Client process's PID */
+       char            *path;                                  /* Client process's cmd line string */
+       int             *permissions;                           /* Array of GID that the client process has */
+        char            *smack_label;                           /* SMACK label of the client process */
+       struct _cookie_list     *prev;                          /* Next cookie list */
+       struct _cookie_list     *next;                          /* Previous cookie list */
+} cookie_list;
+
+
+/* Function prototypes ******************************************************/
+/* IPC */
+
+void printhex(const unsigned char *data, int size);
+
+/* Debug */
+#ifdef SECURITY_SERVER_DEBUG_TO_CONSOLE /* debug msg will be printed in console */
+#define SEC_SVR_DBG(FMT, ARG ...) fprintf(stderr, "[%s:%d] "FMT"\n", \
+               __FILE__, __LINE__, ##ARG)
+
+#elif SECURITY_SERVER_DEBUG_DLOG       /* debug msg will be printed by dlog daemon */
+#define LOG_TAG "SECURITY_SERVER"
+#include <dlog.h>
+#define SEC_SVR_DBG    SLOGD
+#else /* No debug output */
+#define SEC_SVR_DBG(FMT, ARG ...) {}
+#endif
+
+#endif
diff --git a/src/security-srv/include/security-server-cookie.h b/src/security-srv/include/security-server-cookie.h
new file mode 100644 (file)
index 0000000..3acc720
--- /dev/null
@@ -0,0 +1,42 @@
+/*
+ *  security-server
+ *
+ *  Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved\r
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ *
+ */
+
+#ifndef SECURITY_SERVER_COOKIE_H\r
+#define SECURITY_SERVER_COOKIE_H\r
+\r
+#include "security-server-common.h"\r
+\r
+int free_cookie_item(cookie_list *cookie);
+cookie_list *delete_cookie_item(cookie_list *cookie);
+cookie_list *search_existing_cookie(int pid, const cookie_list *c_list);
+cookie_list *search_cookie(const cookie_list *c_list, const unsigned char *cookie, int privilege);
+cookie_list *search_cookie_new(const cookie_list *c_list,
+                               const unsigned char *cookie,
+                               const char *object,
+                               const char *access_rights);
+int generate_random_cookie(unsigned char *cookie, int size);
+cookie_list *create_cookie_item(int pid, int sockfd, cookie_list *c_list);
+cookie_list *create_default_cookie(void);
+cookie_list * garbage_collection(cookie_list *cookie);
+cookie_list *search_cookie_from_pid(cookie_list *c_list, int pid);
+void printhex(const unsigned char *data, int size);\r
+\r
+#endif\r
diff --git a/src/security-srv/include/security-server-password.h b/src/security-srv/include/security-server-password.h
new file mode 100644 (file)
index 0000000..7fa9377
--- /dev/null
@@ -0,0 +1,37 @@
+/*
+ *  security-server
+ *
+ *  Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ *
+ */
+
+#ifndef SECURITY_SERVER_PASSWORD_H
+#define SECURITY_SERVER_PASSWORD_H
+
+#include "security-server-common.h"
+#include "security-server-comm.h"
+
+int process_valid_pwd_request(int sockfd);
+int process_set_pwd_request(int sockfd);
+int process_reset_pwd_request(int sockfd);
+int process_reset_pwd_request(int sockfd);
+int process_chk_pwd_request(int sockfd);
+int process_set_pwd_max_challenge_request(int sockfd);
+int process_set_pwd_validity_request(int sockfd);
+int init_try(void);
+
+#endif
diff --git a/src/security-srv/include/security-server-util.h b/src/security-srv/include/security-server-util.h
new file mode 100644 (file)
index 0000000..32c9f72
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ *  security-server
+ *
+ *  Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ *
+ */
+
+#ifndef SECURITY_SERVER_UTIL_H
+#define SECURITY_SERVER_UTIL_H
+
+/* Only for test */
+/* These msg type MUST BE REMOVED before release **************************/
+#define SECURITY_SERVER_MSG_TYPE_GET_ALL_COOKIES_REQUEST       0x51
+#define SECURITY_SERVER_MSG_TYPE_GET_ALL_COOKIES_RESPONSE      0x52
+#define SECURITY_SERVER_MSG_TYPE_GET_COOKIEINFO_FROM_PID_REQUEST       0x53
+#define SECURITY_SERVER_MSG_TYPE_GET_COOKIEINFO_RESPONSE       0x54
+#define SECURITY_SERVER_MSG_TYPE_GET_COOKIEINFO_FROM_COOKIE_REQUEST    0x55
+/**********************************************************************/
+
+int util_process_all_cookie(int sockfd, cookie_list* list);
+int util_process_cookie_from_pid(int sockfd, cookie_list* list);
+int util_process_cookie_from_cookie(int sockfd, cookie_list* list);
+
+
+#endif
diff --git a/src/security-srv/include/security-server.h b/src/security-srv/include/security-server.h
new file mode 100644 (file)
index 0000000..bf2201b
--- /dev/null
@@ -0,0 +1,999 @@
+/*
+ *  security-server
+ *
+ *  Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ *
+ */
+
+#ifndef SECURITY_SERVER_H
+#define SECURITY_SERVER_H
+
+#include <sys/types.h>
+
+/**
+ * @file    security-server.h
+ * @version 1.0
+ * @brief   This file contains APIs of the Security Server
+*/
+
+/**
+ * @defgroup SecurityFW
+ * @{
+ *
+ * @defgroup SECURITY_SERVER Security Server
+ * @version  1.0
+ * @brief    Security Server client library functions
+ *
+*/
+
+/**
+ * @addtogroup SECURITY_SERVER
+ * @{
+*/
+
+/*
+ * ====================================================================================================
+ * <tt>
+ *
+ * Revision History:
+ *
+ *  -- Company Name -- | Modification Date | Description of Changes
+ *  -----------------------------------------------------------------------
+ *   --- Samsung ------ | --- 2010-07-25 -- | First created
+ *
+ *    </tt>
+ */
+
+/**
+ * \name Return Codes
+ * exported by the foundation API.
+ * result codes begin with the start error code and extend into negative direction.
+ * @{
+*/
+#define SECURITY_SERVER_API_SUCCESS                    0
+/*! \brief   indicating the result of the one specific API is successful */
+#define SECURITY_SERVER_API_ERROR_SOCKET               -1
+
+/*! \brief   indicating the socket between client and Security Server has been failed  */
+#define SECURITY_SERVER_API_ERROR_BAD_REQUEST          -2
+
+/*! \brief   indicating the response from Security Server is malformed */
+#define SECURITY_SERVER_API_ERROR_BAD_RESPONSE         -3
+
+/*! \brief   indicating the transmitting request has been failed */
+#define SECURITY_SERVER_API_ERROR_SEND_FAILED          -4
+
+/*! \brief   indicating the receiving response has been failed */
+#define SECURITY_SERVER_API_ERROR_RECV_FAILED          -5
+
+/*! \brief   indicating requesting object is not exist */
+#define SECURITY_SERVER_API_ERROR_NO_SUCH_OBJECT       -6
+
+/*! \brief   indicating the authentication between client and server has been failed */
+#define SECURITY_SERVER_API_ERROR_AUTHENTICATION_FAILED        -7
+
+/*! \brief   indicating the API's input parameter is malformed */
+#define SECURITY_SERVER_API_ERROR_INPUT_PARAM          -8
+
+/*! \brief   indicating the output buffer size which is passed as parameter is too small */
+#define SECURITY_SERVER_API_ERROR_BUFFER_TOO_SMALL     -9
+
+/*! \brief   indicating system  is running out of memory state */
+#define SECURITY_SERVER_API_ERROR_OUT_OF_MEMORY                -10
+
+/*! \brief   indicating the access has been denied by Security Server */
+#define SECURITY_SERVER_API_ERROR_ACCESS_DENIED                -11
+
+/*! \brief   indicating Security Server has been failed for some reason */
+#define SECURITY_SERVER_API_ERROR_SERVER_ERROR         -12
+
+/*! \brief   indicating given cookie is not exist in the database  */
+#define SECURITY_SERVER_API_ERROR_NO_SUCH_COOKIE       -13
+
+/*! \brief   indicating there is no phone password set  */
+#define SECURITY_SERVER_API_ERROR_NO_PASSWORD          -14
+
+/*! \brief   indicating password exists in system  */
+#define SECURITY_SERVER_API_ERROR_PASSWORD_EXIST               -15
+
+/*! \brief   indicating password mismatch  */
+#define SECURITY_SERVER_API_ERROR_PASSWORD_MISMATCH    -16
+
+/*! \brief   indicating password retry timeout is not occurred yet  */
+#define SECURITY_SERVER_API_ERROR_PASSWORD_RETRY_TIMER -17
+
+/*! \brief   indicating password retry timeout is not occurred yet  */
+#define SECURITY_SERVER_API_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED       -18
+
+/*! \brief   indicating password retry timeout is not occurred yet  */
+#define SECURITY_SERVER_API_ERROR_PASSWORD_EXPIRED     -19
+
+/*! \brief   indicating password retry timeout is not occurred yet  */
+#define SECURITY_SERVER_API_ERROR_PASSWORD_REUSED      -20
+
+/*! \brief   indicating the error with unknown reason */
+#define SECURITY_SERVER_API_ERROR_UNKNOWN              -255
+/** @}*/
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+
+/**
+ * \par Description:
+ * Retreives Linux group ID from object name which is passed by parameter
+ *
+ * \par Purpose:
+ * This API may be used before security_server_check_privilege() API by middleware daemon to get group ID of a specific object.
+ *
+ * \par Typical use case:
+ * In middleware daemon, before checking privilege of a service the daemon need to know the GID of the service. This API support the functionality.
+ *
+ * \par Method of function operation:
+ * Opens /etc/group file and searches the object name as group name. If there is matching result, returns GID as integer
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ * - This API is only allowed to be called by pre-defined middleware daemon
+ *
+ * \param[in] object Name of the object which is kwnown by the caller.
+ *
+ * \return matching gid (positive integer) on success, or negative error code on error.
+ *
+ * \par Prospective clients:
+ * Inhouse middleware
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ * \pre None
+ *
+ * \post None
+ *
+ * \see /etc/group,
+ * security_server_get_object_name(), security_server_check_privilege()
+ *
+ * \remarks None
+ *
+ * \par Sample code:
+ * \code
+ * #include <security-server.h>
+ * ...
+ * int retval;
+ *
+ * // You have to make sure that  the input param '*object' is defined in the platform
+ * retval = security_server_get_gid("telephony_makecall");
+ * if(retval < 0)
+ * {
+ *     printf("%s", "Error has occurred\n");
+ *     exit(0);
+ * }
+ * ...
+ * \endcode
+*/
+int security_server_get_gid(const char *object);
+
+
+
+/**
+ * \par Description:
+ * Retreives object name as mull terminated string from Linux group ID which is passed by parameter
+ *
+ * \par Purpose:
+ * This API may be used to get object name if the caller process only knows GID of the object.
+ *
+ * \par Typical use case:
+ * In middleware daemon, by some reason, need to know object name from the Linux group ID, then call this API to retrieve object name as string
+ *
+ * \par Method of function operation:
+ * Opens /etc/group file and searches matching gid. If there is matching result, returns name of the group as null terminated string
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ * - This API is only allowed to be called by pre-defined middleware daemon
+ *
+ * \param[in] gid Linux group ID which needed to be retrieved as object name.
+ * \param[out] object Place holder for matching object name for gid.
+ * \param[in] max_object_size Allocated byte size of parameter "object".
+ *
+ * \return 0 on success, or negative error code on error.
+ *
+ * \par Prospective clients:
+ * Inhouse middleware.
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ * \pre output parameter object must be malloced before calling this API not to make memory curruption
+ *
+ * \post None
+ *
+ * \see /etc/group,
+ * security_server_get_gid()
+ *
+ * \remarks None
+ *
+ * \par Sample code:
+ * \code
+ * #include <security-server.h>
+ * ...
+ * int retval;
+ * char objectname[20];
+ *
+ * // Call the API
+ * retval = security_server_get_object_name(6005, objectname, sizeof(objectname));
+ * if(retval < 0)
+ * {
+ *     printf("%s", "Error has occurred\n");
+ *     exit(0);
+ * }
+ * ...
+ * \endcode
+*/
+int security_server_get_object_name(gid_t gid, char *object, size_t max_object_size);
+
+
+
+/**
+ * \par Description:
+ * Request cookie to the Security Server. Cookie is a random bit stream which is used as ticket for user space object.
+ *
+ * \par Purpose:
+ * This API may be used by application and client middleware process to get access to middleware daemons.
+ *
+ * \par Typical use case:
+ * When an application process wants to get access to some middleware object, first call this API to get cookie value. Then it calls the service API to get service with the cookie value.
+ *
+ * \par Method of function operation:
+ * Caller process just send request message. Security Server checks proc file system to get list of gIDs the caller belongs, then create a random cookie and responds to caller.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ * Cookie needs to be stored relatively secure.
+ *
+ * \param[out] cookie Place holder for cookie value.
+ * \param[in] max_cookie Allocated byte size of parameter "cookie".
+ *
+ * \return 0 on success, or negative error code on error.
+ *
+ * \par Prospective clients:
+ * Any process
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ * \pre output parameter cookie must be malloced before calling this API not to make memory curruption
+ * Size of the cookie can be retrieved by security_server_get_cookie_size() API.
+ *
+ * \post None
+ *
+ * \see security_server_check_privilege(), security_server_get_cookie_size()
+ *
+ * \remarks None
+ *
+ * \par Sample code:
+ * \code
+ * #include <security-server.h>
+ * ...
+ * int retval;
+ * size_t cookie_size;
+ * cookie_size = security_server_get_cookie_size();
+ * unsigned char cookie[cookie_size];
+ *
+ * // Call the API
+ * retval = security_server_request_cookie(cookie, cookie_size);
+ * if(retval < 0)
+ * {
+ *     printf("%s", "Error has occurred\n");
+ *     exit(0);
+ * }
+ * ...
+ * \endcode
+*/
+int security_server_request_cookie(char *cookie, size_t max_cookie);
+
+
+
+/**
+ * \par Description:
+ * This API gets the cookie's byte size which is issued by Security Server.
+ *
+ * \par Purpose:
+ * This API may be used by application and middleware process to get size of cookie before getting and storing cookie value.
+ *
+ * \par Typical use case:
+ * When an application process wants to get access to some middleware object, first call this API to get cookie value. Then it calls the service API to get service with the cookie value.
+ *
+ * \par Method of function operation:
+ * This API just returns pre-defined integer value as cookie size.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ * None
+ *
+ * \return Always returns byte size of the cookie.
+ *
+ * \par Prospective clients:
+ * Any process
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ * \pre None
+ *
+ * \post None
+ *
+ * \see security_server_request_cookie()
+
+ * \remarks None
+ *
+ * \par Sample code:
+ * \code
+ * #include <security-server.h>
+ * ...
+ * int retval;
+ * size_t cookie_size;
+ *
+ * // API calling
+ * cookie_size = security_server_get_cookie_size();
+ * unsigned char cookie[cookie_size];
+ *
+ * char objectname[20];
+ * retval = security_server_request_cookie(cookie, cookie_size);
+ * if(retval < 0)
+ * {
+ *     printf("%s", "Error has occurred\n");
+ *     exit(0);
+ * }
+ * ...
+ * \endcode
+*/
+int security_server_get_cookie_size(void);
+
+
+
+/**
+ * \par Description:
+ * This API checks the cookie is allowed to access to given object.
+ *
+ * \par Purpose:
+ * This API may be used by middleware process to ask the client application has privilege for the given object.
+ *
+ * \par Typical use case:
+ * When middleware server receives request message from client application process with cookie value, it calls this API to ask to Security Server that the client application has privilege to access the service. If yes, then the middleware daemon can continue service, if not, it can return error to client application.
+ *
+ * \par Method of function operation:
+ * When Security Server receives this request, it searches cookie database and check the cookie is there, if there is matching cookie, then it checks the cookie has the privilege. It returns success if there is match, if not, it returns error.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ * Cookie value needs to be stored relatively secure\n
+ * Privilege should be pre-defined by Platform design.
+ *
+ * \param[in] cookie Received cookie value from client application
+ * \param[in] privilege Object group ID which the client application wants to access
+ *
+ * \return 0 on success, or negative error code on error.
+ *
+ * \par Prospective clients:
+ * Only pre-defiend middleware daemons
+ *
+ * \par Known issues/bugs:
+ * None
+ * \pre None
+ *
+ * \post None
+ *
+ * \see security_server_request_cookie(), security_server_get_gid(), security_server_get_cookie_size()
+ *
+ * \remarks None
+ *
+ * \par Sample code:
+ * \code
+ * #include <security-server.h>
+ * ...
+ * int retval;
+ * size_t cookie_size;
+ * int call_gid;
+ * cookie_size = security_server_get_cookie_size();
+ * unsigned char recved_cookie[cookie_size];
+ *
+ * ... // Receiving request with cookie
+ *
+ * call_gid = security_server_get_gid("telephony_makecall");
+ * retval = security_server_check_privilege(recved_cookie, (gid_t)call_gid);
+ * if(retval < 0)
+ * {
+ *     if(retval == SECURITY_SERVER_API_ERROR_ACCESS_DENIED)
+ *     {
+ *             printf("%s", "access has been denied\n");
+ *             return;
+ *     }
+ *     printf("%s", "Error has occurred\n");
+ * }
+ * ...
+ *
+ * \endcode
+*/
+int security_server_check_privilege(const char *cookie, gid_t privilege);
+
+int security_server_check_privilege_by_cookie(const char *cookie,
+                                              const char *object,
+                                              const char *access_rights);
+
+int security_server_check_privilege_by_sockfd(int sockfd,
+                                              const char *object,
+                                              const char *access_rights);
+
+/**
+ * \par Description:
+ * This API searchs a cookie value and returns PID of the given cookie.
+ *
+ * \par Purpose:
+ * This API may be used by middleware process to ask the client application has privilege for the given object.
+ *
+ * \par Typical use case:
+ * In some cases, a middleware server wants to know PID of the application process. But if the middleware server uses non-direct IPC such as dbus, it's nearly impossible to know and guarantee peer PID. By using this API, the middleware server can retrieve a PID of the requesting process.
+ *
+ * \par Method of function operation:
+ * When Security Server receives this request, it searches cookie database and check the cookie is there, if there is matching cookie, then it returns corresponding PID for the cookie.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ * Cookie value needs to be stored relatively secure\n
+ * This API is abled to be called only by pre-defined middleware servers.
+ *
+ * \param[in] cookie Received cookie value from client application. Cookie is not a null terminated human readable string. Make sure you're code doesn't have any string related process on the cookie.
+ *
+ * \return positive integer on success meaning the PID, 0 means the cookie is for root process, negative integer error code on error.
+ *
+ * \par Prospective clients:
+ * Only pre-defiend middleware daemons
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ * \pre None
+ *
+ * \post None
+ *
+ * \see security_server_request_cookie(), security_server_get_cookie_size()
+ *
+ * \remarks the cookie is not a null terminated string. Cookie is a BINARY byte stream of such length which can be retrieved by security_server_get_cookie_size() API.
+ * Therefore, please do not use strcpy() family to process cookie value. You MUST use memcpy() function to process cookie value.
+ * You also have to know that the cookie value doesn't carry any null terminator. So you don't need to allocate 1 more byte of the cookie size.
+ *
+ * \par Sample code:
+ * \code
+ * #include <security-server.h>
+ * ...
+ * int peerpid;
+ * size_t cookie_size;
+ * gid_t call_gid;
+ * cookie_size = security_server_get_cookie_size();
+ * unsigned char recved_cookie[cookie_size];
+ *
+ * ... // Receiving request with cookie
+ *
+ * peerpid = security_server_get_cookie_pid(recved_cookie);
+ * if(peerpid < 0)
+ * {
+ *     printf("%s", "Error has occurred\n");
+ * }
+ * ...
+ *
+ * \endcode
+*/
+int security_server_get_cookie_pid(const char *cookie);
+
+
+
+/**
+ * \par Description:
+ * This API checks phone validity of password, to check existance, expiration, remaining attempts.
+ *
+ * \par Purpose:
+ * This API should be used by applications which needs phone password check. Caller application should behave properly after this API call.
+ *
+ * \par Typical use case:
+ * Lock screen can call this API before it shows unlock screen, if there is password, lock screen can show password input UI, if not, lock screen can show just unlock screen
+ *
+ * \par Method of function operation:
+ * Sends a validate request to security server and security server replies with password information.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ * Password file should be stored safely. The password file will be stored by security server and only allowed itself to read/write, and data is will be securely hashed\n
+ *
+ * \param[out] current_attempts Number of password check missed attempts.
+ * \param[out] max_attempts Number of maximum attempts that the password locks. 0 means infinite
+ * \param[out] valid_secs Remaining time in second which represents this password will be expired. 0xFFFFFFFF means infinite
+ *
+ * \return 0 if there is no password set, other negative integer error code on error.
+ *
+ * \par Prospective clients:
+ * Applications which can unlock UI
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ * \pre None
+ *
+ * \post None
+ *
+ * \see security_server_set_pwd(), security_server_chk_pwd()
+ *
+ * \remarks If password file is currupted or accitentally deleted, this API may not synchronized with security-server, but security-server will check file status on next request.
+ *
+ * \par Sample code:
+ * \code
+ * #include <security-server.h>
+ * ...
+ * int ret;
+ * unsigned int attempt, max_attempt, expire_sec;
+ *
+ * ret = security_server_is_pwd_valid(&attempt, &max_attempt, &expire_sec);
+ * if(is_pwd_set == SECURITY_SERVER_API_ERROR_NO_PASSWORD)
+ * {
+ *     printf("%s", "There is no password exists\n");
+ * }
+ * else if(is_pwd_set == SECURITY_SERVER_SUCCESS && expire_sec > 0 && attempt < max_attempts)
+ * {
+ *     printf("%s", "Password is valid by now\n");
+ * }
+ * else
+ * {
+ *     printf("%s", "Something wrong\n");
+ * }
+ * ...
+ *
+ * \endcode
+*/
+int security_server_is_pwd_valid(unsigned int *current_attempts,
+                       unsigned int *max_attempts,
+                       unsigned int *valid_secs);
+
+
+
+/**
+ * \par Description:
+ * This API sets phone password only if current password matches.
+ *
+ * \par Purpose:
+ * This API should be used by setting application when the user changes his/her phone password.
+ *
+ * \par Typical use case:
+ * Setting application calls this API to change phone password. Caller needs current password to grant the change.
+ *
+ * \par Method of function operation:
+ * Sends current password with new password to security-server, security-server checks current password and set new password to current only when current password is correct. Caller application can determine maximum number of attempts and expiration time in days
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ * There is retry timer on this API to limit replay attack. You will get error if you called this API too often.\n
+ *
+ * \param[in] cur_pwd Null terminated current password string. It can be NULL pointer if there is no password set yet - by calling security_server_is_pwd_empty()
+ * \param[in] new_pwd Null terminated new password string. It must not a NULL pointer.
+ * \param[in] max_challenge Maximum number of attempts that user can try to check the password without success in serial. 0 means infinity.
+ * \param[in] valid_period_in_days. Number of days that this password is valid. 0 means infinity
+ *
+ * \return 0 on seccuess, negative integer error code on error.
+ *
+ * \par Prospective clients:
+ * Platform's THE ONLY setting application and some dedicated privileged processes
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ * \pre None
+ *
+ * \post None
+ *
+ * \see security_server_is_pwd_valid(), security_server_chk_pwd(), security_server_reset_pwd()
+ *
+ * \remarks Only setting application can call this API. The password file will be acces controlled and securely hashed. Security-server will remain previous password file to recover unexpected password file curruption.
+ * \remarks If current password exists and it's expired, or max attempts reached, you cannot call this API. You have to call security_server_reset_pwd() API.
+ *
+ * \par Sample code:
+ * \code
+ * #include <security-server.h>
+ * ...
+ * int ret;
+ * unsigned int attempt, max_attempt, expire_sec;
+ *
+ * ret = security_server_is_pwd_valid(&attempt, &max_attempt, &expire_sec);
+ * if(is_pwd_set == SECURITY_SERVER_API_ERROR_NO_PASSWORD)
+ * {
+ *     printf("%s", "There is no password exists\n");
+ *     ret = security_server_set_pwd(NULL, "this_is_new_pwd", 20, 365);
+ *     if(ret != SECURITY_SERVER_API_SUCCESS)
+ *     {
+ *             printf("%s", "we have error\n");
+ *             ...
+ *     }
+ * }
+ * else if(is_pwd_set == SECURITY_SERVER_SUCCESS && expire_sec > 0 && attempt < max_attempts)
+ * {
+ *     printf("%s", "Password is valid by now\n");
+ *     ret = security_server_set_pwd("this_is_current_pwd", "this_is_new_pwd", 20, 365);
+ *     if(ret != SECURITY_SERVER_API_SUCCESS)
+ *     {
+ *             printf("%s", "we have error\n");
+ *             ...
+ *     }
+ * }
+ * else
+ * {
+ *     printf("%s", "Something wrong\n");
+ * }
+ * ...
+ *
+ * \endcode
+*/
+int security_server_set_pwd(const char *cur_pwd,
+                       const char *new_pwd,
+                       const unsigned int max_challenge,
+                       const unsigned int valid_period_in_days);
+
+
+/**
+ * \par Description:
+ * This API sets validity period for currently setup password.
+ *
+ * \par Purpose:
+ * This API should be used by Enterprise authorities to modify password policy. To be used only with valid password setup.
+ *
+ * \par Typical use case:
+ * Authorized application calls this API to change current passwords validity when password policy needs to be changed.
+ *
+ * \par Method of function operation:
+ * Function attempts to find currently set password and changes its current validity to passed number of days. Retry counter for the password is reset to zero.
+ * If there is no password set, function returns proper error code.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ * \param[in] valid_period_in_days. Number of days that this password is valid. 0 means infinity
+ *
+ * \return 0 on success, negative integer error code on error.
+ *
+ * \par Prospective clients:
+ * Platform's THE ONLY setting application and some dedicated privileged processes
+ *
+ * \par Known issues/bugs:
+ * Identifying calling peer is not ready yet, should be based on SMACK somehow.
+ *
+ * \see security_server_is_pwd_valid(), security_server_chk_pwd(), security_server_reset_pwd()
+ */
+int security_server_set_pwd_validity(const unsigned int valid_period_in_days);
+
+
+/**
+ * \par Description:
+ * This API sets maximum number of attempts for currently setup password.
+ *
+ * \par Purpose:
+ * This API should be used by Enterprise authorities to modify password policy. To be used only with valid password setup.
+ *
+ * \par Typical use case:
+ * Authorized application calls this API to change current passwords max attempt number when password policy needs to be changed.
+ *
+ * \par Method of function operation:
+ * Function attempts to find currently set password and changes its max attempt number to passed one. Retry counter for the password is reset to zero.
+ * If there is no password set, function returns proper error code.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ * \param[in] max_challenge Maximum number of attempts that user can try to check the password without success in serial. 0 means infinity.
+ *
+ * \return 0 on success, negative integer error code on error.
+ *
+ * \par Prospective clients:
+ * Platform's THE ONLY setting application and some dedicated privileged processes
+ *
+ * \par Known issues/bugs:
+ * Identifying calling peer is not ready yet, should be based on SMACK somehow.
+ *
+ * \see security_server_is_pwd_valid(), security_server_chk_pwd(), security_server_reset_pwd()
+ */
+int security_server_set_pwd_max_challenge(const unsigned int max_challenge);
+
+/**
+ * \par Description:
+ * This API sets phone password only if current password is invalid or user forgot the password.
+ *
+ * \par Purpose:
+ * This API should be used by setting application or dedicated processes when the user changes his/her phone password.
+ *
+ * \par Typical use case:
+ * User forgots the password. He calls emergency manager(auto or manual)  for reset password. Emergency manager calls this API and reset phone password.
+ *
+ * \par Method of function operation:
+ * Resetting phone password with input string without any matching current password.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ * There is retry timer on this API to limit replay attack. You will get error if you called this API too often.\n
+ *
+ * \param[in] new_pwd Null terminated new password string. It must not a NULL pointer.
+ * \param[in] max_challenge Maximum number of attempts that user can try to check the password without success in serial. 0 means infinity.
+ * \param[in] valid_period_in_days. Number of days that this password is valid. 0 means infinity
+ *
+ * \return 0 on seccuess, negative integer error code on error.
+ *
+ * \par Prospective clients:
+ * Platform's THE ONLY setting application and some dedicated privileged processes
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ * \pre None
+ *
+ * \post None
+ *
+ * \see security_server_is_pwd_valid(), security_server_chk_pwd(), security_server_set_pwd()
+ *
+ * \remarks Only dedicated applications can call this API. The password file will be acces controlled and securely hashed. Security-server will remain previous password file to recover unexpected password file curruption.
+ *
+ * \par Sample code:
+ * \code
+ * #include <security-server.h>
+ * ...
+ * int ret;
+ * unsigned int attempt, max_attempt, expire_sec;
+ *
+ *     ret = security_server_set_pwd("this_is_new_pwd", 20, 365);
+ *     if(retval != SECURITY_SERVER_API_SUCCESS)
+ *     {
+ *             printf("%s", "we have error\n");
+ *             ...
+ *     }
+ * ...
+ *
+ * \endcode
+*/
+int security_server_reset_pwd(const char *new_pwd,
+                       const unsigned int max_challenge,
+                       const unsigned int valid_period_in_days);
+
+/**
+ * \par Description:
+ * This API compares stored phone password with challenged input value.
+ *
+ * \par Purpose:
+ * This API should be used by applications which has phone UI lock capability.
+ *
+ * \par Typical use case:
+ * Lock screen calls this API after user typed phone password and pressed okay.
+ *
+ * \par Method of function operation:
+ * Sends challenged password to security-server, security-server compares hashed current password and hashed challenged password.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ * There is retry timer on this API to limit replay attack. You will get error if you called this API too often.\n
+ *
+ * \param[in] challenge Null terminated challenged password string. It must not a NULL pointer.
+ * \param[out] current_attempts Number of password check missed attempts.
+ * \param[out] max_attempts Number of maximum attempts that the password locks. 0 means infinite
+ * \param[out] valid_secs Remaining time in second which represents this password will be expired. 0xFFFFFFFF means infinite
+ *
+ * \return 0 on seccuess, negative integer error code on error.
+ *
+ * \par Prospective clients:
+ * Applications which has phone UI lock feature.
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ * \pre None
+ *
+ * \post None
+ *
+ * \see security_server_is_pwd_valid(), security_server_set_pwd()
+ *
+ * \remarks The password file will be acces controlled and securely hashed. Security-server will remain previous password file to recover unexpected password file curruption.
+ *
+ * \par Sample code:
+ * \code
+ * #include <security-server.h>
+ * ...
+ * int retval;
+ * unsigned int attempt, max_attempt, expire_sec;
+ *
+ * retval = security_server_chk_pwd("is_this_password", &attmpt, &max_attempt, &expire_sec);
+ * if(retval == SECURITY_SERVER_API_ERROR_PASSWORD_MISMATCH)
+ * {
+ *     printf("%s", "Oh you typed wrong password\n");
+ *     ...
+ * }
+ * else if(retval == SECURITY_SERVER_API_SUCCESS)
+ * {
+ *     printf("%s", "You remember your password.\n");
+ *     ...
+ * }
+ * ...
+ *
+ * \endcode
+*/
+int security_server_chk_pwd(const char *challenge,
+                       unsigned int *current_attempt,
+                       unsigned int *max_attempt,
+                       unsigned int *valid_secs);
+
+
+/**
+ * \par Description:
+ * This API set the number of password history which should be maintained. Once this number set, user cannot reuse recent number of passwords which is described in this history value
+ *
+ * \par Purpose:
+ * This API should be used only by dedicated process in the platform.
+ *
+ * \par Typical use case:
+ * Enterprise manager calls this API when the enterprise wants to enforce harder password policy.
+ *
+ * \par Method of function operation:
+ * When enterprise manager (MDM) is trying to change the security policy for phone password, it calls this API background to change the history policy.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ * There is retry timer on this API to limit replay attack. You will get error if you called this API too often.\n
+ *
+ * \param[in] number_of_history Number of history to be checked when user tries to change password. Maximum is currently 50
+ *
+ * \return 0 on seccuess, negative integer error code on error.
+ *
+ * \par Prospective clients:
+ * MDM client, Enterprise manager.
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ * \pre None
+ *
+ * \post None
+ *
+ * \see security_server_set_pwd()
+ *
+ * \remarks The password file will be acces controlled and securely hashed. Security-server will remain previous password file to recover unexpected password file curruption.
+ *
+ * \par Sample code:
+ * \code
+ * #include <security-server.h>
+ * ...
+ * int retval;
+ *
+ * ret = security_server_set_pwd_history(100);
+ *     if(ret != SECURITY_SERVER_API_SUCCESS)
+ *     {
+ *             printf("%s", "You have error\n");
+ *             ...
+ *     }
+ * ...
+ *
+ * \endcode
+*/
+int security_server_set_pwd_history(int number_of_history);
+
+
+
+/**
+ * \par Description:
+ * This API launches /usr/bin/debug-util as root privilege.
+ *
+ * \par Purpose:
+ * This API will be used only by SDK with developer privilege to launch debugging tool to debug as the developing applicaion's privilege.
+ *
+ * \par Typical use case:
+ * During appliation development, SDK opens a shell to install, launch, and debug the developing application. But the shell will not have any privilege to control platform. Therefore we need a special utility to manage debugging environement as same privilege level of the application. If this API is called, security server will launch the debug utility as root privilege and the utility will drop its privilege same as developing application
+ *
+ *
+ * \par Method of function operation:
+ * When Security Server receives this request, it checks uid of the client, and launches /usr/bin/debug-util with given arguements.
+ *
+ * \par Sync (or) Async:
+ * This is a Synchronous API.
+ *
+ * \par Important notes:
+ * Caller process of this API must be owned by developer user.\n
+ * The caller process will be pre-defined.
+ * /usr/bin/debug-util itself must be omitted in the argv. Security server will put this as first argv in the execution procedure
+ *
+ * \param[in] argc Number of arguements.
+ *
+ * \param[in] argv Arguements
+ *
+ * \return 0 on success, negative integer error code on error.
+ *
+ * \par Prospective clients:
+ * Only pre-defiend debugging utility.
+ *
+ * \par Known issues/bugs:
+ * None
+ *
+ * \pre None
+ *
+ * \post None
+ *
+ * \see None
+ *
+ * \remarks Calling this API, you have to put argv[1] of the debug-util as argv[0] of this API. Security server will put argv[0] automatically
+ *
+ * \par Sample code:
+ * \code
+ * #include <security-server.h>
+ * #define DEVELOPER_UID 5500
+ *
+ * int main(int argc, char **argv)
+ * {
+ *     int my_uid, ret;
+ *     uid = getuid();
+ *     if(uid != DEVELOPER_UID)
+ *     {
+ *             // You must be developer user
+ *             exit(1);
+ *     }
+ *
+ *     ret = security_server_launch_debug_tool(argc -1, argv++)
+ *     if(ret != SECURITY_SERVER_SUCCESS)
+ *     {
+ *             // Some error occurred
+ *             exit(1);
+ *     }
+ *     ...
+ * }
+ *
+ * \endcode
+*/
+int security_server_launch_debug_tool(int argc, const char **argv);
+
+#ifdef __cplusplus
+}
+#endif
+
+/**
+ * @}
+*/
+
+/**
+ * @}
+*/
+
+#endif
diff --git a/src/security-srv/mw-list b/src/security-srv/mw-list
new file mode 100644 (file)
index 0000000..9bfa0b0
--- /dev/null
@@ -0,0 +1,13 @@
+/usr/bin/telephony-server
+/usr/bin/ss-server
+/usr/bin/dnet
+/usr/bin/msg-server
+/usr/bin/alarm-server
+/usr/bin/dnet
+/usr/bin/audio-session-mgr-server
+/usr/bin/lbs_server
+/usr/bin/power_manager
+/usr/bin/system_server
+/opt/home/root/security_server_tc_server
+/usr/bin/sec-svr-util
+
diff --git a/src/security-srv/security-serverd b/src/security-srv/security-serverd
new file mode 100644 (file)
index 0000000..48fbefc
--- /dev/null
@@ -0,0 +1,4 @@
+#!/bin/sh
+
+# start secure-storage server
+/usr/bin/security-server &
diff --git a/src/security-srv/server/security-server-cookie.c b/src/security-srv/server/security-server-cookie.c
new file mode 100644 (file)
index 0000000..518134b
--- /dev/null
@@ -0,0 +1,606 @@
+/*
+ *  security-server
+ *  Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ *
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/stat.h>
+#include <errno.h>
+#include <unistd.h>
+#include <string.h>
+#include <sys/types.h>
+#include <fcntl.h>
+#include <sys/smack.h>
+
+#include "security-server-cookie.h"
+
+/* Delete useless cookie item *
+ * then connect prev and next */
+int free_cookie_item(cookie_list *cookie)
+{
+       if(cookie->path != NULL)
+               free(cookie->path);
+       if(cookie->permissions != NULL)
+               free(cookie->permissions);
+        if(cookie->smack_label != NULL)
+                free(cookie->smack_label);
+       if(cookie->prev != NULL)
+               cookie->prev->next = cookie->next;
+       if(cookie->next != NULL)
+               cookie->next->prev = cookie->prev;
+       free(cookie);
+       cookie = NULL;
+       return 0;
+}
+
+/* Cut the link of the current cookie item and connect previous link and next line *
+ * That is remove a cookie item *
+ * Returns next cookie item  if exist, NULL for no more cookie item */
+cookie_list *delete_cookie_item(cookie_list *cookie)
+{
+       cookie_list *retval = NULL;
+       if(cookie == NULL)
+       {
+               SEC_SVR_DBG("%s", "Cannot delete null cookie");
+               return retval;
+       }
+
+       /* Reconnect cookie item */
+       if(cookie->next != NULL)
+       {
+               cookie->prev->next = cookie->next;
+               cookie->next->prev = cookie->prev;
+               retval = cookie->next;
+       }
+       else
+       {
+               cookie->prev->next = NULL;
+       }
+       
+       free_cookie_item(cookie);
+       return retval;
+}
+
+cookie_list * garbage_collection(cookie_list *cookie)
+{
+       char path[17];
+       cookie_list *retval = NULL;
+       struct stat statbuf;
+       int ret;
+
+       while(cookie != NULL)
+       {
+               /* Skip default cookie */
+               if(cookie->pid ==0)
+                       return cookie;
+
+               /* Try to find the PID directory from proc fs */
+               snprintf(path, sizeof(path), "/proc/%d", cookie->pid);
+               path[16] = 0;
+               ret = stat(path, &statbuf);
+               if(ret != 0)
+               {
+                       /* If it's not exist, delete the cookie */
+                       if(errno == ENOENT)
+                       {
+                               SEC_SVR_DBG("Garbage found. PID:%d, deleting...", cookie->pid);
+                               cookie = delete_cookie_item(cookie);
+                               continue;
+                       }
+                       else
+                       {
+                               /* Some error occurred */
+                               SEC_SVR_DBG("Error occurred on stat: errno = %d", errno);
+                               return cookie;
+                       }
+               }
+               else
+               {
+                       /* This is not a garbage. returning */
+                       return cookie;
+               }
+       }
+       return retval;
+}
+
+/* Search existing cookie from the cookie list for the client process *
+ * At the same time, it collects garbage cookie which PID is no longer exist and delete them */
+cookie_list *search_existing_cookie(int pid, const cookie_list *c_list)
+{
+       cookie_list *current =(cookie_list *)c_list, *cookie = NULL;
+       char *cmdline = NULL, *debug_cmdline = NULL;
+
+       /* Search from the list */
+       while(current != NULL)
+       {
+               /* print_cookie(current);*/
+               current = garbage_collection(current);
+               if(current == NULL)
+                       break;
+
+               /* PID must be same */
+               if(current->pid == pid)
+               {
+                       /* Found cookie for the pid. Check the cookie is reused by dirrent executable */
+                       /* Check the path of the process */
+                       cmdline = (char*)read_cmdline_from_proc(pid);
+                       if(cmdline == NULL)
+                       {
+                               SEC_SVR_DBG("%s", "cannot read cmdline");
+                               return NULL;
+                       }
+                       /* Check the path is different */
+                       if(strncmp(cmdline, current->path, current->path_len) != 0 || strlen(cmdline) != current->path_len)
+                       {
+                               SEC_SVR_DBG("pid [%d] has been reused by %s. deleting the old cookie.", pid, cmdline);
+                               debug_cmdline = malloc(current->path_len + 1);
+                               if(debug_cmdline == NULL)
+                               {
+                                       SEC_SVR_DBG("%s", "out of memory error");
+                                       free(cmdline);
+                                       return NULL;
+                               }
+                               strncpy(debug_cmdline, current->path, current->path_len);
+                               debug_cmdline[current->path_len] = 0;
+                               SEC_SVR_DBG("[%s] --> [%s]", cmdline, debug_cmdline);
+                               if(debug_cmdline != NULL)
+                               {
+                                       free(debug_cmdline);
+                                       debug_cmdline = NULL;
+                               }
+                               /* Okay. delete current cookie */
+                               current = delete_cookie_item(current);
+                               if(cmdline != NULL)
+                               {
+                                       free(cmdline);
+                                       cmdline = NULL;
+                               }
+                               continue;
+                       }
+                       else
+                       {
+                               SEC_SVR_DBG("%s", "cookie found");
+                               cookie = current;
+                       }
+
+                       if(cmdline != NULL)
+                       {
+                               free(cmdline);
+                               cmdline = NULL;
+                       }
+               }
+               current = current->next;
+       }
+       return cookie;
+}
+
+/* Search existing cookie from the cookie list for matching pid *
+ * Default cookie (meaning PID 0) is not allowed in here */
+cookie_list *search_cookie_from_pid(cookie_list *c_list, int pid)
+{
+       cookie_list *current = (cookie_list *)c_list, *retval = NULL;
+
+       /* Search from the list */
+       while(current != NULL)
+       {
+               /* print_cookie(current);*/
+               /* PID must be same */
+               current = garbage_collection(current);
+               if(current == NULL)
+                       break;
+
+               if(current->pid == pid)
+               {
+                       SEC_SVR_DBG("%s", "cookie has been found");
+                       retval = current;
+                       goto finish;
+               }
+               current = current->next;
+       }
+finish:
+       return retval;
+}
+
+/* Search existing cookie from the cookie list for matching cookie and privilege */
+/* If privilege is 0, just search cookie exists or not */
+cookie_list *search_cookie(const cookie_list *c_list, const unsigned char *cookie, int privilege)
+{
+       cookie_list *current = (cookie_list *)c_list, *retval = NULL;
+       int i;
+
+       /* Search from the list */
+       while(current != NULL)
+       {
+               /* print_cookie(current);*/
+               /* PID must be same */
+               current = garbage_collection(current);
+               if(current == NULL)
+                       break;
+
+               if(memcmp(current->cookie, cookie, SECURITY_SERVER_COOKIE_LEN) == 0)
+               {
+                       SEC_SVR_DBG("%s", "cookie has been found");
+
+                       /* default cookie is for root process which is pid is set to 0 */
+                       if(current->pid == 0 || privilege == 0)
+                       {
+                               retval = current;
+                               goto finish;
+                       }
+                       else
+                       {
+                               for(i=0 ; i < current->permission_len ; i++)
+                               {
+                                       if(privilege == current->permissions[i])
+                                       {
+                                               SEC_SVR_DBG("Found privilege %d", privilege);
+                                               retval = current;
+                                               goto finish;
+                                       }
+                               }
+                       }
+               }
+               current = current->next;
+       }
+finish:
+       return retval;
+}
+
+
+cookie_list *search_cookie_new(const cookie_list *c_list,
+                               const unsigned char *cookie,
+                               const char *object,
+                               const char *access_rights)
+{
+       cookie_list *current = (cookie_list *)c_list, *retval = NULL;
+        int ret;
+       int i;
+
+       /* Search from the list */
+       while(current != NULL)
+       {
+               /* print_cookie(current);*/
+               /* PID must be same */
+               current = garbage_collection(current);
+               if(current == NULL)
+                       break;
+
+               if(memcmp(current->cookie, cookie, SECURITY_SERVER_COOKIE_LEN) == 0)
+               {
+                       SEC_SVR_DBG("%s", "cookie has been found");
+
+                                ret = smack_have_access(current->smack_label, object, access_rights);
+          SEC_SVR_DBG("smack_have_access, subject >%s< object >%s< access >%s< ===> %d",
+                    current->smack_label, object, access_rights, ret);
+                                if (ret == 1)
+                                {
+                                        retval = current;
+                                        goto finish;
+                                }
+               }
+               current = current->next;
+       }
+finish:
+       return retval;
+}
+
+
+/* Generage a random stream value of size to cookie *
+ * by reading /dev/uranddom file */
+int generate_random_cookie(unsigned char *cookie, int size)
+{
+       int fd, ret;
+
+    if (cookie == NULL) {
+        SEC_SVR_DBG("%s", "Null pointer passed to function");
+        return SECURITY_SERVER_ERROR_UNKNOWN;
+    }
+       fd = open("/dev/urandom", O_RDONLY);
+       if(fd < 0)
+       {
+               SEC_SVR_DBG("%s", "Cannot open /dev/urandom");
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+       ret = read(fd, cookie, size);
+       if(ret < size)
+       {
+               SEC_SVR_DBG("Cannot read /dev/urandom: %d", ret);
+               ret = SECURITY_SERVER_ERROR_FILE_OPERATION;
+               goto error;
+       }
+       close(fd);
+       ret = SECURITY_SERVER_SUCCESS;
+error:
+       if(fd >= 0)
+               close(fd);
+       return ret;
+}
+
+/* Create a cookie item from PID */
+cookie_list *create_cookie_item(int pid, int sockfd, cookie_list *c_list)
+{
+       int ret, tempint;
+       cookie_list *added = NULL, *current = NULL;
+       char path[24], *cmdline = NULL;
+       char *buf = NULL, inputed, *tempptr = NULL;
+       char delim[] = ": ", *token = NULL;
+       int *permissions = NULL, perm_num = 1, cnt, i, *tempperm = NULL;
+        char *smack_label = NULL;
+       FILE *fp = NULL;
+
+       current = search_existing_cookie(pid, c_list);
+       if(current != NULL)
+       {
+               /* There is a cookie for this process already */
+               added = current;
+               SEC_SVR_DBG("%s", "Existing cookie found");
+               goto error;
+       }
+
+       /* Read command line of the PID from proc fs */
+       cmdline = (char *)read_cmdline_from_proc(pid);
+       if(cmdline == NULL)
+       {
+               SEC_SVR_DBG("Error on reading /proc/%d/cmdline", pid);
+               goto error;
+       }
+
+       /*
+        * modified by security part
+        *  - get gid from /etc/group
+        */
+       /* Read group info of the PID from proc fs - /proc/[PID]/status */
+       snprintf(path, sizeof(path), "/proc/%d/status", pid);
+       fp = fopen(path, "r");
+
+       /* Find the line which starts with 'Groups:' */
+       i = 0;
+       
+       while(1)
+       {
+               buf = (char*)malloc(sizeof(char) * 128);
+               if(buf == NULL)
+               {
+                       SEC_SVR_DBG("%s", "Error on malloc()");
+                       goto error;
+               }
+               memset(buf, 0x00, 128);
+               cnt = 128;
+
+               /* get one line from /proc/[PID]/status */
+               while(1)
+               {
+                       tempint = fgetc(fp);
+                       inputed = (char)tempint;
+                       if(tempint == EOF)
+                               goto out_of_while;
+                       else if(inputed == '\n')
+                       {
+                               buf[i] = '\0';
+                               break;
+                       }
+                       else if((i == cnt) && (inputed != '\n'))
+                       {
+                               tempptr = (char*)realloc(buf, sizeof(char) * (i + 128));
+                               if(tempptr == NULL)
+                               {
+                                       SEC_SVR_DBG("%s", "Error on realloc()");
+                                       goto error;
+                               }
+                               buf = tempptr;
+                               buf[i++] = inputed;
+                               cnt = i + 128;
+                       }
+                       else
+                               buf[i++] = inputed;
+               }
+               i = 0;
+
+               /* find 'Groups:' */
+               if(strncmp(buf, "Groups:", 7) == 0)
+               {
+                       /* get gid from the line and insert to 'permissions' array */
+                       token = strtok(buf, delim); // first string is "Groups"
+                       while((token = strtok(NULL, delim)))
+                       {
+                               tempperm = realloc(permissions, sizeof(int) * perm_num);
+                               if(tempperm == NULL)
+                               {
+                                       SEC_SVR_DBG("%s", "Error on realloc()");
+                                       goto error;
+                               }
+                               permissions = tempperm;
+                               errno = 0;
+                               permissions[perm_num - 1] = strtoul(token, 0, 10);
+                               if (errno != 0)
+                               {
+                                       SEC_SVR_DBG("cannot change string to integer [%s]", token);
+                                       ret = SECURITY_SERVER_ERROR_SERVER_ERROR;
+                                       goto error;
+                               }
+                               perm_num++;
+                       }
+                       perm_num--;
+
+                       /* goto out of while loop */
+                       break;
+               }
+               if(buf != NULL)
+               {
+                       free(buf);
+                       buf = NULL;
+               }
+       }
+out_of_while:
+               
+       /* Each group ID is stored in each line of the file */
+//     while(fgets(permline, sizeof(permline), fp) != NULL)
+//     {
+//             permissions = realloc(permissions, sizeof(int) * perm_num);
+//             if(permissions == NULL)
+//             {
+//                     SEC_SVR_DBG("%s", "Error on realloc()");
+//                     goto error;
+//             }
+//             permissions[perm_num -1] = strtoul(permline, 0, 10);
+//             perm_num++;
+//     }
+//     perm_num--;
+       /*
+        * modifying end
+        */
+
+       /* Go to last cookie from the list */
+       current = c_list;
+       while(current->next != NULL)
+       {
+               current = current->next;
+       }
+
+       /* Create a new one and assign values */
+       added = malloc(sizeof(cookie_list));
+       if(added == NULL)
+               goto error;
+
+       ret = generate_random_cookie(added->cookie, SECURITY_SERVER_COOKIE_LEN);
+       if(ret != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("Error on making random cookie: %d", ret);
+               free(added);
+               added = NULL;
+               goto error;
+       }
+
+        /* Check SMACK label */
+        ret = smack_new_label_from_socket(sockfd, &smack_label);
+        if (ret != 0)
+       {
+               SEC_SVR_DBG("Error checking peer label: %d", ret);
+               free(added);
+               added = NULL;
+               goto error;
+       }
+
+       added->path_len = strlen(cmdline);
+       added->path = calloc(1, strlen(cmdline));
+       memcpy(added->path, cmdline, strlen(cmdline));
+
+       added->permission_len = perm_num;
+       added->pid = pid;
+       added->permissions = permissions;
+       added->smack_label = smack_label;
+       added->prev = current;
+       current->next = added;
+       added->next = NULL;
+
+error:
+       if(cmdline != NULL)
+               free(cmdline);
+       if(fp != NULL)
+               fclose(fp);
+       if(buf != NULL)
+               free(buf);
+
+       if(added == NULL && permissions != NULL)
+               free(permissions);
+
+       return added;
+}
+
+/* Check stored default cookie, if it's not exist make a new one and store it */
+int check_stored_cookie(unsigned char *cookie, int size)
+{
+       int fd, ret;
+
+       /* First, check the default cookie is stored */
+       fd = open(SECURITY_SERVER_DEFAULT_COOKIE_PATH, O_RDONLY);
+       if(fd < 0)
+       {
+               if(errno != ENOENT)
+               {
+                       SEC_SVR_DBG("Cannot open default cookie. errno=%d", errno);
+                       ret = SECURITY_SERVER_ERROR_FILE_OPERATION;
+                       unlink(SECURITY_SERVER_DEFAULT_COOKIE_PATH);
+               }
+
+               ret = generate_random_cookie(cookie, size);
+
+               /* Save cookie to disk */
+               fd = open(SECURITY_SERVER_DEFAULT_COOKIE_PATH, O_WRONLY | O_CREAT, 0600);
+               if (fd < 0)
+               {
+                       SEC_SVR_DBG("Cannot open default cookie errno=%d", errno);
+                       ret = SECURITY_SERVER_ERROR_FILE_OPERATION;
+                       goto error;
+               }
+               ret = write(fd, cookie, size);
+               if(ret < size)
+               {
+                       SEC_SVR_DBG("%s", "Cannot save default cookie");
+                       ret = SECURITY_SERVER_ERROR_FILE_OPERATION;
+                       goto error;
+               }
+
+               close(fd);
+               return SECURITY_SERVER_SUCCESS;
+       }
+
+       ret = read (fd, cookie, size);
+       if(ret < size)
+       {
+               SEC_SVR_DBG("Cannot read default cookie errno=%d", errno);
+               ret = SECURITY_SERVER_ERROR_FILE_OPERATION;
+               goto error;
+       }
+       ret = SECURITY_SERVER_SUCCESS;
+
+error:
+       if(fd >= 0)
+               close(fd);
+       return ret;
+}
+/* Create a cookie item from PID */
+
+/* Create a default cookie when security server is executed *
+ * Default cookie is for root processes that needs cookie */
+cookie_list *create_default_cookie(void)
+{
+       cookie_list *first = NULL;
+       int ret;
+
+       first = malloc(sizeof(cookie_list));
+
+       ret = check_stored_cookie(first->cookie, SECURITY_SERVER_COOKIE_LEN);
+       if(ret != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("Error on making random cookie: %d", ret);
+               free(first);
+               return NULL;
+       }
+
+       first->path_len = 0;
+       first->permission_len = 0;
+       first->pid = 0;
+       first->path = NULL;
+       first->permissions = NULL;
+        first->smack_label = NULL;
+       first->prev = NULL;
+       first->next = NULL;
+       return first;
+}
diff --git a/src/security-srv/server/security-server-main.c b/src/security-srv/server/security-server-main.c
new file mode 100644 (file)
index 0000000..1cd5cfb
--- /dev/null
@@ -0,0 +1,1196 @@
+/*
+ * security-server
+ *
+ *  Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ *
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include <string.h>
+#include <sys/types.h>
+#include <errno.h>
+#include <signal.h>
+#include <pthread.h>
+#include <limits.h>
+
+#include "security-server-cookie.h"
+#include "security-server-common.h"
+#include "security-server-password.h"
+#include "security-server-comm.h"
+
+/* Set cookie as a global variable */
+cookie_list *c_list;
+pthread_mutex_t cookie_mutex;
+int thread_status[SECURITY_SERVER_NUM_THREADS];
+struct security_server_thread_param {
+       int client_sockfd;
+       int server_sockfd;
+       int thread_status;
+};
+
+/************************************************************************************************/
+/* Just for test. This code must be removed on release */
+#include "security-server-util.h"
+/************************************************************************************************/
+
+#if 0
+void printhex(unsigned char *data, int size)
+{
+       int i;
+       for(i=0;i<size;i++)
+       {
+               if(data[i] < 0xF)
+                       printf("0");
+
+               printf("%X ", data[i]);
+               if(((i+1) % 16) == 0 && i != 0)
+                       printf("\n");
+       }
+       printf("\n");
+}
+
+void print_cookie(cookie_list *list)
+{
+       int i;
+       printf("%s", "cookie:\n");
+       printhex(list->cookie, SECURITY_SERVER_COOKIE_LEN);
+       printf("path_len: %d\n", list->path_len);
+       printf("permission_len: %d\n", list->permission_len);
+       printf("PID: %d\n", list->pid);
+       printf("path: %s\n", list->path);
+       printf("%s", "permissions: ");
+       for(i=0;i<list->permission_len;i++)
+       {
+               printf("%d ", list->permissions[i]);
+       }
+       printf("%s", "\n");
+       printf("prev: %p\n", list->prev);
+       printf("next: %p\n", list->next);
+}
+#endif
+
+/* Object name is actually name of a Group ID *
+ * This function opens /etc/group file and search group ID and
+ * returns the string */
+int search_object_name(int gid, char *obj, int obj_size)
+{
+       FILE *fp = NULL;
+       char *linebuf = NULL, *token = NULL, *token2, *tempstr = NULL;
+       int ret = 0, tmp_gid, bufsize;
+       fp = fopen("/etc/group", "r");
+       if(fp == NULL)
+       {
+               /* cannot open /etc/group */
+               SEC_SVR_DBG("%s", "Cannot open /etc/group");
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+
+       linebuf = malloc(128);
+       bufsize = 128;
+       if(linebuf == NULL)
+       {
+               ret = SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
+               SEC_SVR_DBG("%s", "cannot malloc()");
+               goto error;
+       }
+
+       bzero(linebuf, bufsize);
+       ret = SECURITY_SERVER_ERROR_NO_SUCH_OBJECT;
+       while(fgets(linebuf, bufsize, fp) != NULL)
+       {
+               while(linebuf[bufsize -2] != 0)
+               {
+                       linebuf[bufsize -1] = (char) fgetc(fp);
+                       tempstr = realloc(linebuf, bufsize + 128);
+                       if(tempstr == NULL)
+                       {
+                               ret = SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
+                               goto error;
+                       }
+                       linebuf = tempstr;
+                       bzero(linebuf + bufsize, 128);
+                       fgets(linebuf + bufsize, 128, fp);
+                       bufsize += 128;
+               }
+
+               token = strtok(linebuf, ":");   /* group name */
+               if(token == NULL)
+               {
+                       SEC_SVR_DBG("/etc/group is not valid. cannot find gid: [%s]", linebuf);
+                       ret = SECURITY_SERVER_ERROR_SERVER_ERROR;
+                       goto error;
+               }
+               token2 = strtok(NULL, ":");     /* group password */
+               if(token2== NULL)
+               {
+                       SEC_SVR_DBG("/etc/group is not valid. cannot find gid: [%s]", linebuf);
+                       ret = SECURITY_SERVER_ERROR_SERVER_ERROR;
+                       goto error;
+               }
+               token2 = strtok(NULL, ":");     /* gid */
+               if(token2 == NULL)
+               {
+                       SEC_SVR_DBG("/etc/group is not valid. cannot find gid: [%s]", linebuf);
+                       ret = SECURITY_SERVER_ERROR_SERVER_ERROR;
+                       goto error;
+               }
+
+               errno = 0;
+               tmp_gid = strtoul(token2, 0, 10);
+               if (errno != 0)
+               {
+                       SEC_SVR_DBG("cannot change string to integer [%s]", token2);
+                       ret = SECURITY_SERVER_ERROR_SERVER_ERROR;
+                       goto error;
+               }
+
+               if(tmp_gid == gid)
+               {
+                       /* We found it */
+                       if(strlen(token) > obj_size)
+                       {
+                               ret = SECURITY_SERVER_ERROR_BUFFER_TOO_SMALL;
+                               SEC_SVR_DBG("buffer is too small. %d --> %d", obj_size, strlen(token));
+                               goto error;
+                       }
+                       strncpy(obj, token, strlen(token));
+                       obj[strlen(token)] = 0;
+                       ret = SECURITY_SERVER_SUCCESS;
+                       break;
+               }
+               bzero(linebuf, bufsize);
+       }
+
+error:
+       if(linebuf != NULL)
+               free(linebuf);
+       if(fp != NULL)
+               fclose(fp);
+       return ret;
+}
+
+/* Search GID from group name *
+ * This function opens /etc/group and search group name by given gid */
+int search_gid(const char *obj)
+{
+       FILE *fp = NULL;
+       char *linebuf = NULL, *token = NULL, *token2, *tempstr = NULL;
+       int ret = SECURITY_SERVER_ERROR_NO_SUCH_OBJECT, tmp_gid, bufsize;
+
+       SEC_SVR_DBG("Searching for object %s", obj);
+
+       fp = fopen("/etc/group", "r");
+       if(fp == NULL)
+       {
+               /* cannot open /etc/group */
+               SEC_SVR_DBG("%s", "cannot open /etc/group");
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+
+       linebuf = malloc(128);
+       bufsize = 128;
+       if(linebuf == NULL)
+       {
+               ret = SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
+               SEC_SVR_DBG("%s", "Out Of Memory");
+               goto error;
+       }
+
+       bzero(linebuf, bufsize);
+       while(fgets(linebuf, bufsize, fp) != NULL)
+       {
+               while(linebuf[bufsize -2] != 0 )
+               {
+                       linebuf[bufsize -1] = (char) fgetc(fp);
+                       tempstr = realloc(linebuf, bufsize + 128);
+                       if(tempstr == NULL)
+                       {
+                               ret = SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
+                               goto error;
+                       }
+                       linebuf = tempstr;
+                       bzero(linebuf + bufsize, 128);
+                       fgets(linebuf + bufsize, 128, fp);
+                       bufsize += 128;
+               }
+
+               token = strtok(linebuf, ":");   /* group name */
+               token2 = strtok(NULL, ":");     /* group password */
+               token2 = strtok(NULL, ":");     /* gid */
+               if(token2 == NULL)
+               {
+                       SEC_SVR_DBG("/etc/group is not valid. cannot find gid: [%s]", linebuf);
+                       ret = SECURITY_SERVER_ERROR_SERVER_ERROR;
+                       goto error;
+               }
+               errno = 0;
+               tmp_gid = strtoul(token2, 0, 10);
+               if ( errno != 0 )
+               {
+                       SEC_SVR_DBG("cannot change string to integer [%s]", token2);
+                       ret = SECURITY_SERVER_ERROR_SERVER_ERROR;
+                       goto error;
+               }
+
+               if(strcmp(obj, token) == 0)
+               {
+                       /* We found it */
+                       ret = tmp_gid;
+                       SEC_SVR_DBG("GID of %s is found: %d", obj, ret);
+                       break;
+               }
+               bzero(linebuf, bufsize);
+       }
+
+error:
+       if(linebuf != NULL)
+               free(linebuf);
+       if(fp != NULL)
+               fclose(fp);
+       return ret;
+}
+
+/* Signal handler for processes */
+static void security_server_sig_child(int signo, siginfo_t *info, void *data)
+{
+       int status;
+       pid_t child_pid;
+       pid_t child_pgid;
+
+       child_pgid = getpgid(info->si_pid);
+       SEC_SVR_DBG("Signal handler: dead_pid=%d, pgid=%d",info->si_pid,child_pgid);
+
+       while ((child_pid = waitpid(-1, &status, WNOHANG)) > 0) {
+               if(child_pid == child_pgid)
+                       killpg(child_pgid,SIGKILL);
+       }
+
+       return;
+}
+
+/* Execute a debugging tool by fork() and execve() */
+int execute_debug_tool(int argc, char *const *argv, int server_sockfd, int client_sockfd)
+{
+       int ret, i;
+       SEC_SVR_DBG("%s", "Executing tool");
+
+       ret = fork();
+       if(ret == 0)
+       {
+               close(client_sockfd);
+               close(server_sockfd);
+               setsid();
+
+               for(i=0;i<_NSIG;i++)
+                       signal(i, SIG_DFL);
+
+               ret = execv(argv[0], argv);
+               if(ret == -1)
+               {
+                       SEC_SVR_DBG("Error:Failed to execute [%d]", errno);
+                       exit(-1);
+               }
+       }
+       if(ret < 0)
+       {
+               SEC_SVR_DBG("Error: Failed to fork [%d]", errno);
+               return SECURITY_SERVER_ERROR_SERVER_ERROR;
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+int process_cookie_request(int sockfd)
+{
+       int retval, client_pid, client_uid;
+       cookie_list *created_cookie = NULL;
+
+       /* Authenticate client */
+       retval = authenticate_client_application(sockfd, &client_pid, &client_uid);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "Client Authentication Failed");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+       /* If client application is root process, just respond default cookie */
+       if( client_uid == 0)
+       {
+               SEC_SVR_DBG("%s", "Requested application is a root process");
+               created_cookie = c_list;
+               if(c_list == NULL)
+               {
+                       SEC_SVR_DBG("%s", "Cannot read default cookie");
+                       goto error;
+               }
+       }
+       else
+       {
+               /* Create a new cookie. or find existing one */
+               pthread_mutex_lock(&cookie_mutex);
+               created_cookie = create_cookie_item(client_pid, sockfd, c_list);
+               pthread_mutex_unlock(&cookie_mutex);
+               if(created_cookie == NULL)
+               {
+                       SEC_SVR_DBG("%s","Cannot create a cookie");
+                       goto error;
+               }
+       }
+       /* send cookie as response */
+       retval = send_cookie(sockfd, created_cookie->cookie);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+       }
+        SEC_SVR_DBG("Server: Cookie created for client PID %d LABEL >%s<",
+                    created_cookie->pid,
+                    (created_cookie->smack_label)?(created_cookie->smack_label):"NULL");
+
+       SEC_SVR_DBG("%s", "Server: Cookie has been sent to client");
+
+error:
+       return retval;
+}
+
+int process_check_privilege_request(int sockfd)
+{
+       /* Authenticate client */
+       int retval, client_pid, requested_privilege;
+       unsigned char requested_cookie[SECURITY_SERVER_COOKIE_LEN];
+       cookie_list *search_result = NULL;
+
+       retval = authenticate_client_middleware(sockfd, &client_pid);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "Client Authentication Failed");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;;
+       }
+
+       retval = recv_check_privilege_request(sockfd,
+                               requested_cookie, &requested_privilege);
+       if(retval == SECURITY_SERVER_ERROR_RECV_FAILED)
+       {
+               SEC_SVR_DBG("%s", "Receiving request failed");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;;
+       }
+
+       if(requested_privilege < 1)
+       {
+               SEC_SVR_DBG("Requiring bad privilege [%d]", requested_privilege);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Search cookie list */
+       pthread_mutex_lock(&cookie_mutex);
+       search_result = search_cookie(c_list, requested_cookie, requested_privilege);
+       pthread_mutex_unlock(&cookie_mutex);
+       if(search_result != NULL)
+       {
+               /* We found */
+               SEC_SVR_DBG("We found the cookie with %d privilege and pid:%d", requested_privilege, client_pid);
+               SEC_SVR_DBG("%s", "Cookie comparison succeeded. Access granted.");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_ACCESS_GRANTED);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+       }
+       else
+       {
+               /* It's not exist */
+               SEC_SVR_DBG("Could not find the cookie with %d privilege", requested_privilege);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_ACCESS_DENIED);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+       }
+error:
+       return retval;
+}
+
+int process_check_privilege_new_request(int sockfd)
+{
+       /* Authenticate client */
+       int retval, client_pid, requested_privilege;
+       unsigned char requested_cookie[SECURITY_SERVER_COOKIE_LEN];
+       cookie_list *search_result = NULL;
+        char object_label[MAX_OBJECT_LABEL_LEN+1];
+        char access_rights[MAX_MODE_STR_LEN+1];
+
+       retval = authenticate_client_middleware(sockfd, &client_pid);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "Client Authentication Failed");
+               retval = send_generic_response(sockfd, 
+                               SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_NEW_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;;
+       }
+
+        retval = recv_check_privilege_new_request(
+                     sockfd, requested_cookie, object_label, access_rights);
+       if(retval == SECURITY_SERVER_ERROR_RECV_FAILED)
+       {
+               SEC_SVR_DBG("%s", "Receiving request failed");
+               retval = send_generic_response(sockfd, 
+                               SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_NEW_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;;
+       }
+
+       /* Search cookie list */
+       pthread_mutex_lock(&cookie_mutex);
+       search_result = search_cookie_new(c_list, requested_cookie, object_label, access_rights);
+       pthread_mutex_unlock(&cookie_mutex);
+
+       if(search_result != NULL)
+    {
+               /* We found */
+               SEC_SVR_DBG("We found the cookie with %s rights and pid:%d", access_rights, client_pid);
+               SEC_SVR_DBG("%s", "Cookie comparison succeeded. Access granted.");
+               retval = send_generic_response(sockfd, 
+                               SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_NEW_RESPONSE, 
+                               SECURITY_SERVER_RETURN_CODE_ACCESS_GRANTED);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+       }
+       else
+       {
+               /* It's not exist */
+               SEC_SVR_DBG("Could not find the cookie with %s rights", access_rights);
+               retval = send_generic_response(sockfd, 
+                               SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_NEW_RESPONSE, 
+                               SECURITY_SERVER_RETURN_CODE_ACCESS_DENIED);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+       }
+error:
+       return retval;
+
+
+}
+
+int process_object_name_request(int sockfd)
+{
+       int retval, client_pid, requested_privilege;
+       char object_name[SECURITY_SERVER_MAX_OBJ_NAME];
+
+       /* Authenticate client */
+       retval = authenticate_client_middleware(sockfd, &client_pid);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "Client Authentication Failed");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_OBJECT_NAME_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Receive GID */
+       retval = read(sockfd, &requested_privilege, sizeof(requested_privilege));
+       if (retval < sizeof(requested_privilege))
+       {
+               SEC_SVR_DBG("%s", "Receiving request failed");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_OBJECT_NAME_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Search from /etc/group */
+       retval = search_object_name(requested_privilege,
+                       object_name,
+                       SECURITY_SERVER_MAX_OBJ_NAME);
+       if (retval == SECURITY_SERVER_ERROR_NO_SUCH_OBJECT)
+       {
+               /* It's not exist */
+               SEC_SVR_DBG("There is no such object for gid [%d]", requested_privilege);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_OBJECT_NAME_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_NO_SUCH_OBJECT);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error occurred */
+               SEC_SVR_DBG("Error on searching object name [%d]", retval);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_OBJECT_NAME_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* We found */
+       SEC_SVR_DBG("We found object: %s", object_name);
+       retval = send_object_name(sockfd, object_name);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+       }
+
+error:
+       return retval;
+}
+
+int process_gid_request(int sockfd, int msg_len)
+{
+       int retval, client_pid;
+       char object_name[SECURITY_SERVER_MAX_OBJ_NAME];
+       /* Authenticate client as middleware daemon */
+       retval = authenticate_client_middleware(sockfd, &client_pid);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "Client authentication failed");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_GID_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       if(msg_len >= SECURITY_SERVER_MAX_OBJ_NAME)
+       {
+               /* Too big ojbect name */
+               SEC_SVR_DBG("%s", "Object name is too big");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_GID_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Receive group name */
+       retval = read(sockfd, object_name, msg_len);
+       if (retval < msg_len )
+       {
+               SEC_SVR_DBG("%s", "Failed to read object name");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_GID_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+       object_name[msg_len] = 0;
+
+       /* Search /etc/group for the given group name */
+       retval = search_gid(object_name);
+       if (retval == SECURITY_SERVER_ERROR_NO_SUCH_OBJECT)
+       {
+               /* Not exist */
+               SEC_SVR_DBG("The object [%s] is not exist", object_name);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_GID_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_NO_SUCH_OBJECT);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       if(retval < 0)
+       {
+               /* Error occurred */
+               SEC_SVR_DBG("Cannot send the response. %d", retval);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_GID_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+
+               goto error;
+       }
+       /* We found */
+       retval = send_gid(sockfd, retval);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("ERROR: Cannot gid response: %d", retval);
+       }
+error:
+       return retval;
+}
+
+int process_pid_request(int sockfd)
+{
+       int retval, client_pid;
+       unsigned char requested_cookie[SECURITY_SERVER_COOKIE_LEN];
+       cookie_list *search_result = NULL;
+
+       /* Authenticate client */
+       retval = authenticate_client_middleware(sockfd, &client_pid);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "Client Authentication Failed");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_PID_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       retval = recv_pid_request(sockfd, requested_cookie);
+       if(retval == SECURITY_SERVER_ERROR_RECV_FAILED)
+       {
+               SEC_SVR_DBG("%s", "Receiving request failed");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_PID_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Search cookie list */
+       pthread_mutex_lock(&cookie_mutex);
+       search_result = search_cookie(c_list, requested_cookie, 0);
+       pthread_mutex_unlock(&cookie_mutex);
+       if(search_result != NULL)
+       {
+               /* We found */
+               SEC_SVR_DBG("We found the cookie and pid:%d", search_result->pid);
+               SEC_SVR_DBG("%s", "Cookie comparison succeeded. Access granted.");
+               retval = send_pid(sockfd, search_result->pid);
+
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+       }
+       else
+       {
+               /* It's not exist */
+               SEC_SVR_DBG("%s", "Could not find the cookie");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_PID_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_NO_SUCH_COOKIE);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send pid response: %d", retval);
+               }
+       }
+error:
+       return retval;
+}
+
+int process_tool_request(int client_sockfd, int server_sockfd)
+{
+       int retval, argcnum;
+       char **recved_argv = NULL;
+
+       /* Authenticate client */
+       retval = authenticate_developer_shell(client_sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "Client Authentication Failed");
+               retval = send_generic_response(client_sockfd,
+                               SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Receive Total number of argv */
+       argcnum = 0;
+       retval = read(client_sockfd, &argcnum, sizeof(int));
+       if((retval < sizeof(int)) || argcnum > (UINT_MAX/sizeof(char *))-2 || argcnum < 0)
+       {
+               SEC_SVR_DBG("Error: argc recieve failed: %d", retval);
+               retval = send_generic_response(client_sockfd,
+                               SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+       argcnum += 2;
+       recved_argv = (char **)malloc(sizeof(char *) * argcnum);
+       if(recved_argv == NULL)
+       {
+               SEC_SVR_DBG("Error: malloc() failed: %d", retval);
+               retval = send_generic_response(client_sockfd,
+                               SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+       memset(recved_argv, 0, sizeof(char *) * argcnum);
+
+       retval = recv_launch_tool_request(client_sockfd, argcnum -1, recved_argv);
+       if(retval == SECURITY_SERVER_ERROR_RECV_FAILED)
+       {
+               SEC_SVR_DBG("%s", "Receiving request failed");
+               recved_argv = NULL;
+               retval = send_generic_response(client_sockfd,
+                               SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+       if(argcnum < 2)
+       {
+               SEC_SVR_DBG("Error: Too small number of argv [%d]", argcnum);
+               retval = send_generic_response(client_sockfd,
+                               SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+       /* Execute the command */
+       retval = execute_debug_tool(argcnum, recved_argv, server_sockfd, client_sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("Error: Cannot execute debug tool [%d]", retval);
+               retval = send_generic_response(client_sockfd,
+                               SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+       }
+       else
+       {
+               SEC_SVR_DBG("%s", "Tool has been executed");
+               retval = send_generic_response(client_sockfd,
+                               SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_SUCCESS);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+       }
+error:
+       if(recved_argv != NULL)
+       {
+               /* Free */
+               free_argv(recved_argv, argcnum);
+               recved_argv = NULL;
+               argcnum =0;;
+       }
+       return retval;
+}
+
+void *security_server_thread(void *param)
+{
+       int client_sockfd = -1, client_uid, client_pid;
+       int server_sockfd, retval, argcnum;
+       basic_header basic_hdr;
+       struct security_server_thread_param *my_param;
+
+       my_param = (struct security_server_thread_param *) param;
+       client_sockfd = my_param->client_sockfd;
+       server_sockfd = my_param->server_sockfd;
+
+       /* Receive request header */
+       retval = recv_hdr(client_sockfd, &basic_hdr);
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT || retval == SECURITY_SERVER_ERROR_RECV_FAILED
+               || retval == SECURITY_SERVER_ERROR_SOCKET)
+       {
+               SEC_SVR_DBG("Receiving header error [%d]",retval);
+               close(client_sockfd);
+               client_sockfd = -1;
+               goto error;;
+       }
+
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Response */
+               SEC_SVR_DBG("Receiving header error [%d]",retval);
+               retval = send_generic_response(client_sockfd,
+                               SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+                       goto error;
+               }
+               safe_server_sock_close(client_sockfd);
+               client_sockfd = -1;
+               goto error;
+       }
+
+       /* Act different for request message ID */
+       switch(basic_hdr.msg_id)
+       {
+               case SECURITY_SERVER_MSG_TYPE_COOKIE_REQUEST:
+                       SEC_SVR_DBG("%s", "Cookie request received");
+                       process_cookie_request(client_sockfd);
+                       break;
+
+               case SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_REQUEST:
+                       SEC_SVR_DBG("%s", "Privilege check received");
+                       process_check_privilege_request(client_sockfd);
+                       break;
+
+               case SECURITY_SERVER_MSG_TYPE_CHECK_PRIVILEGE_NEW_REQUEST:
+                       SEC_SVR_DBG("%s", "Privilege check (new mode) received");
+                       process_check_privilege_new_request(client_sockfd);
+                       break;
+
+               case SECURITY_SERVER_MSG_TYPE_OBJECT_NAME_REQUEST:
+                       SEC_SVR_DBG("%s", "Get object name request received");
+                       process_object_name_request(client_sockfd);
+                       break;
+
+               case SECURITY_SERVER_MSG_TYPE_GID_REQUEST:
+                       SEC_SVR_DBG("%s", "Get GID received");
+                       process_gid_request(client_sockfd, (int)basic_hdr.msg_len);
+                       break;
+
+               case SECURITY_SERVER_MSG_TYPE_PID_REQUEST:
+                       SEC_SVR_DBG("%s", "pid request received");
+                       process_pid_request(client_sockfd);
+                       break;
+
+               case SECURITY_SERVER_MSG_TYPE_TOOL_REQUEST:
+                       SEC_SVR_DBG("%s", "launch tool request received");
+                       process_tool_request(client_sockfd, server_sockfd);
+                       break;
+
+               case SECURITY_SERVER_MSG_TYPE_VALID_PWD_REQUEST:
+                       SEC_SVR_DBG("%s", "Server: validate password request received");
+                       process_valid_pwd_request(client_sockfd);
+                       break;
+
+               case SECURITY_SERVER_MSG_TYPE_SET_PWD_REQUEST:
+                       SEC_SVR_DBG("%s", "Server: set password request received");
+                       process_set_pwd_request(client_sockfd);
+                       break;
+
+               case SECURITY_SERVER_MSG_TYPE_RESET_PWD_REQUEST:
+                       SEC_SVR_DBG("%s", "Server: reset password request received");
+                       process_reset_pwd_request(client_sockfd);
+                       break;
+
+               case SECURITY_SERVER_MSG_TYPE_CHK_PWD_REQUEST:
+                       SEC_SVR_DBG("%s", "Server: check password request received");
+                       process_chk_pwd_request(client_sockfd);
+                       break;
+
+               case SECURITY_SERVER_MSG_TYPE_SET_PWD_HISTORY_REQUEST:
+                       SEC_SVR_DBG("%s", "Server: set password histroy request received");
+                       process_set_pwd_history_request(client_sockfd);
+                       break;
+
+               case SECURITY_SERVER_MSG_TYPE_SET_PWD_MAX_CHALLENGE_REQUEST:
+                   SEC_SVR_DBG("%s", "Server: set password max challenge request received");
+                   process_set_pwd_max_challenge_request(client_sockfd);
+                   break;
+
+        case SECURITY_SERVER_MSG_TYPE_SET_PWD_VALIDITY_REQUEST:
+            SEC_SVR_DBG("%s", "Server: set password validity request received");
+            process_set_pwd_validity_request(client_sockfd);
+            break;
+
+/************************************************************************************************/
+/* Just for test. This code must be removed on release */
+               case SECURITY_SERVER_MSG_TYPE_GET_ALL_COOKIES_REQUEST:
+                       SEC_SVR_DBG("%s", "all cookie info request received -- NEED TO BE DELETED ON RELEASE");
+                       retval = authenticate_client_application(client_sockfd, &client_pid, &client_uid);
+                       if(retval != SECURITY_SERVER_SUCCESS)
+                       {
+                               SEC_SVR_DBG("%s", "Client Authentication Failed");
+                               retval = send_generic_response(client_sockfd,
+                                               SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE,
+                                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
+                               if(retval != SECURITY_SERVER_SUCCESS)
+                               {
+                                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+                               }
+                               break;
+                       }
+                       retval = util_process_all_cookie(client_sockfd, c_list);
+                       if(retval != SECURITY_SERVER_SUCCESS)
+                       {
+                               SEC_SVR_DBG("ERROR: Cannot send all cookie info: %d", retval);
+                       }
+                       break;
+
+               case SECURITY_SERVER_MSG_TYPE_GET_COOKIEINFO_FROM_PID_REQUEST:
+                       SEC_SVR_DBG("%s", "cookie info from pid request received -- NEED TO BE DELETED ON RELEASE");
+                       if(retval != SECURITY_SERVER_SUCCESS)
+                       {
+                               SEC_SVR_DBG("%s", "Client Authentication Failed");
+                               retval = send_generic_response(client_sockfd,
+                                               SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE,
+                                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
+                               if(retval != SECURITY_SERVER_SUCCESS)
+                               {
+                                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+                               }
+                               break;
+                       }
+                       util_process_cookie_from_pid(client_sockfd, c_list);
+                       break;
+
+               case SECURITY_SERVER_MSG_TYPE_GET_COOKIEINFO_FROM_COOKIE_REQUEST:
+                       SEC_SVR_DBG("%s", "cookie info from cookie request received -- NEED TO BE DELETED ON RELEASE");
+                       if(retval != SECURITY_SERVER_SUCCESS)
+                       {
+                               SEC_SVR_DBG("%s", "Client Authentication Failed");
+                               retval = send_generic_response(client_sockfd,
+                                               SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE,
+                                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
+                               if(retval != SECURITY_SERVER_SUCCESS)
+                               {
+                                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+                               }
+                               break;
+                       }
+                       util_process_cookie_from_cookie(client_sockfd, c_list);
+                       break;
+/************************************************************************************************/
+
+
+               default:
+                       SEC_SVR_DBG("Unknown msg ID :%d", basic_hdr.msg_id);
+                       /* Unknown message ID */
+                       retval = send_generic_response(client_sockfd,
+                       SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE,
+                       SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+                       if(retval != SECURITY_SERVER_SUCCESS)
+                       {
+                               SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+                       }
+                       break;
+       }
+
+       if(client_sockfd > 0)
+       {
+               safe_server_sock_close(client_sockfd);
+               client_sockfd = -1;
+       }
+
+error:
+       if(client_sockfd > 0)
+               close(client_sockfd);
+       thread_status[my_param->thread_status] = 0;
+       pthread_detach(pthread_self());
+       pthread_exit(NULL);
+}
+
+void *security_server_main_thread(void *data)
+{
+       int server_sockfd = 0, retval, client_sockfd = -1, args[2], rc;
+       struct sigaction act, dummy;
+       pthread_t threads[SECURITY_SERVER_NUM_THREADS];
+       struct security_server_thread_param param[SECURITY_SERVER_NUM_THREADS];
+
+       SEC_SVR_DBG("%s", "Starting Security Server main thread");
+
+       /* security server must be executed by root */
+       if(getuid() != 0)
+       {
+               fprintf(stderr, "%s\n", "You are not root. exiting...");
+               goto error;
+       }
+
+       for(retval = 0 ; retval < SECURITY_SERVER_NUM_THREADS; retval++)
+               thread_status[retval] = 0;
+
+       initiate_try();
+
+       /* Create and bind a Unix domain socket */
+       retval = create_new_socket(&server_sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "cannot create socket. exiting...");
+               goto error;
+       }
+
+       if(listen(server_sockfd, 5) < 0)
+       {
+               SEC_SVR_DBG("%s", "listen() failed. exiting...");
+               goto error;
+       }
+
+       /* Create a default cookie --> Cookie for root process */
+       c_list = create_default_cookie();
+       if(c_list == NULL)
+       {
+               SEC_SVR_DBG("%s", "cannot make a default cookie. exiting...");
+               goto error;
+       }
+
+       /* Init signal handler */
+       act.sa_handler = NULL;
+       act.sa_sigaction = security_server_sig_child;
+       sigemptyset(&act.sa_mask);
+       act.sa_flags = SA_NOCLDSTOP | SA_SIGINFO;
+
+       if (sigaction(SIGCHLD, &act, &dummy) < 0)
+       {
+               SEC_SVR_DBG("%s", "cannot change session");
+       }
+
+       pthread_mutex_init(&cookie_mutex, NULL);
+
+       while(1)
+       {
+               /* Accept a new client */
+               if(client_sockfd < 0)
+                       client_sockfd = accept_client(server_sockfd);
+
+               if(client_sockfd == SECURITY_SERVER_ERROR_TIMEOUT)
+                       continue;
+               if(client_sockfd < 0)
+                       goto error;
+               SEC_SVR_DBG("Server: new connection has been accepted: %d", client_sockfd);
+               retval = 0;
+               while(1)
+               {
+                       if(thread_status[retval] == 0)
+                       {
+                               thread_status[retval] = 1;
+                               param[retval].client_sockfd = client_sockfd;
+                               param[retval].server_sockfd = server_sockfd;
+                               param[retval].thread_status= retval;
+                               SEC_SVR_DBG("Server: Creating a new thread: %d", retval);
+                               rc =pthread_create(&threads[retval], NULL, security_server_thread, (void *)&param[retval]);
+                               if (rc)
+                               {
+                                       SEC_SVR_DBG("Error: Server: Cannot create thread:%d", rc);
+                                       goto error;
+                               }
+                               break;
+                       }
+                       retval++;
+                       if(retval >= SECURITY_SERVER_NUM_THREADS)
+                               retval = 0;
+               }
+               client_sockfd = -1;
+       }
+error:
+       if(server_sockfd > 0)
+               close(server_sockfd);
+
+       pthread_detach(pthread_self());
+       pthread_exit(NULL);
+}
+
+/*
+int main(int argc, char* argv[])
+{
+       int res;
+       pthread_t main_thread;
+
+       res = pthread_create(&main_thread, NULL, security_server_main_thread, NULL);
+       if (res == 0)
+       {
+               while (1)
+                       sleep(60);
+       }
+       else
+       {
+               SEC_SVR_DBG("Error: Server: Cannot create main security server thread: %d", res);
+       }
+       pthread_exit(NULL);
+       return 0;
+}
+*/
diff --git a/src/security-srv/server/security-server-password.c b/src/security-srv/server/security-server-password.c
new file mode 100644 (file)
index 0000000..a86c219
--- /dev/null
@@ -0,0 +1,1579 @@
+/*
+ *  security-server
+ *
+ *  Copyright (c) 2000 - 2012 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ *
+ */
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <dirent.h>
+#include <errno.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <openssl/sha.h>
+
+#include "security-server-password.h"
+
+struct timeval prev_try;
+
+int initiate_try()
+{
+       gettimeofday(&prev_try, NULL);
+}
+
+int validate_pwd_file(char *filename)
+{
+       int i;
+
+       if((strncmp(filename + (strlen(filename) -4), ".pwd" , 4)) != 0)
+       {
+               SEC_SVR_DBG("The passwor filename [%s] is invalid", filename);
+               return SECURITY_SERVER_ERROR_NO_PASSWORD;
+       }
+
+       for(i=0;i<(strlen(filename) -4);i++)
+       {
+               if(filename[i] > '9' || filename[i] < '0')
+               {
+                       SEC_SVR_DBG("The passwor filename [%s] is invalid", filename);
+                       return SECURITY_SERVER_ERROR_NO_PASSWORD;
+               }
+       }
+       return SECURITY_SERVER_SUCCESS;
+}
+
+int dir_filter(const struct dirent *entry)
+{
+       if ((strcmp(entry->d_name, ".") == 0) ||
+               (strcmp(entry->d_name, "..") == 0) ||
+               (strcmp(entry->d_name, "attempts") ==0) ||
+               (strcmp(entry->d_name, "history") ==0) )
+               return (0);
+       else
+               return (1);
+}
+
+int get_pwd_path(char *path)
+{
+       int retval;
+       struct dirent **mydirent;
+       int num;
+       num = scandir(SECURITY_SERVER_DATA_DIRECTORY_PATH, &mydirent, &dir_filter, alphasort);
+       if(num < 0)
+       {
+               SEC_SVR_DBG("Server: [Error] Cannot scan password directory. errno: %d", errno);
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+       if(num == 0)
+       {
+               SEC_SVR_DBG("%s", "Server: There is no password file");
+               return SECURITY_SERVER_ERROR_NO_PASSWORD;
+       }
+
+       snprintf(path, 255, "%s/%s", SECURITY_SERVER_DATA_DIRECTORY_PATH, mydirent[num-1]->d_name);
+       retval = validate_pwd_file(mydirent[num-1]->d_name);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("Removing invalid password file: %s", path);
+               unlink(path);
+               get_pwd_path(path);
+       }
+       SEC_SVR_DBG("Password file path: %s", path);
+       while (num--)
+               free(mydirent[num]);
+       free(mydirent);
+       return SECURITY_SERVER_SUCCESS;
+}
+
+int load_password(unsigned char *cur_pwd, unsigned int *max_attempt, unsigned int *expire_time)
+{
+       int retval, fd;
+       char pwd_path[255];
+
+       /* Create directory */
+       retval = mkdir(SECURITY_SERVER_DATA_DIRECTORY_PATH, 0700);
+       if(retval != 0)
+       {
+               if(errno != EEXIST)
+               {
+                       SEC_SVR_DBG("Cannot create directory. errno: %d", errno);
+                       return SECURITY_SERVER_ERROR_FILE_OPERATION;
+               }
+       }
+
+       /* Check password files */
+       while(1)
+       {
+               /* Get password file path */
+               retval = get_pwd_path(pwd_path);
+               if(retval == SECURITY_SERVER_ERROR_NO_PASSWORD)
+               {
+                       SEC_SVR_DBG("%s", "Current password doesn't exist");
+                       return SECURITY_SERVER_ERROR_NO_PASSWORD;
+               }
+
+               /* Load password file */
+               fd = open(pwd_path, O_RDONLY | O_NONBLOCK );
+               if(fd < 0)
+               {
+                       if(errno == ENOENT)
+                       {
+                               SEC_SVR_DBG("%s", "Server: Current password doesn't exist");
+                               return SECURITY_SERVER_ERROR_NO_PASSWORD;
+                       }
+                       SEC_SVR_DBG("Server: Current password cannot be opened. errno: %d", errno);
+                       return SECURITY_SERVER_ERROR_FILE_OPERATION;
+               }
+
+               /* Read and store into memory */
+               retval = read(fd, cur_pwd, SECURITY_SERVER_HASHED_PWD_LEN);
+               if(retval < SECURITY_SERVER_HASHED_PWD_LEN)
+               {
+                       SEC_SVR_DBG("%s", "Server: Current password corrupted. resetting to previous one. 0");
+                       close(fd);
+                       fd = 0;
+                       unlink(pwd_path);
+                       continue;
+               }
+
+               retval = read(fd, max_attempt, sizeof(unsigned int));
+               if(retval < sizeof(unsigned int))
+               {
+                       SEC_SVR_DBG("%s", "Server: Current password corrupted. resetting to previous one. 1");
+                       close(fd);
+                       fd = 0;
+                       unlink(pwd_path);
+                       continue;
+               }
+
+               retval = read(fd, expire_time, sizeof(unsigned int));
+               if(retval < sizeof(unsigned int))
+               {
+                       SEC_SVR_DBG("%s", "Server: Current password corrupted. resetting to previous one. 2");
+                       close(fd);
+                       fd = 0;
+                       unlink(pwd_path);
+                       continue;
+               }
+               close(fd);
+
+               /* Check expiration time. */
+               if(*expire_time == 0)  /* No valid period */
+                       *expire_time = 0xffffffff;
+               else if(*expire_time <= time(NULL)) /* expired */
+                       *expire_time =0;
+               else            /* valid yet */
+                       *expire_time -= time(NULL);
+               break;
+       }
+       SEC_SVR_DBG("%s", "Server: Current password file successfully loaded");
+       return SECURITY_SERVER_SUCCESS;
+}
+
+int get_current_attempt(int increase)
+{
+       int retval, fd, attempt;
+       char path[255];
+
+       snprintf(path, 255, "%s/%s", SECURITY_SERVER_DATA_DIRECTORY_PATH,
+               SECURITY_SERVER_ATTEMPT_FILE_NAME);
+
+       /* Open current attempt file as read mode */
+       fd = open(path, O_RDONLY | O_NONBLOCK );
+       if(fd < 0)
+       {
+               if(errno == ENOENT)
+               {
+                       SEC_SVR_DBG("%s", "Server: attempt doesn't exist. Creating one:");
+                       /* Create one if it doesn't exist */
+                       fd = open(path, O_WRONLY | O_NONBLOCK | O_CREAT, 0600);
+                       if(fd < 0)
+                       {
+                               SEC_SVR_DBG("Server ERROR: Cannot open attempt file. errno: %d", errno);
+                               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+                       }
+                       retval = fchmod(fd, 0600);
+                       if(retval != 0)
+                       {
+                               SEC_SVR_DBG("Server ERROR: Cannot chmod attempt file. errno: %d", errno);
+                               close(fd);
+                               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+                       }
+                       attempt = increase;
+                       retval = write(fd, &attempt, sizeof(int));
+                       close(fd);
+                       if(retval < sizeof(int))
+                       {
+                               SEC_SVR_DBG("%s", "Server ERROR: Cannot write attempt");
+                               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+                       }
+                       return attempt;
+               }
+               SEC_SVR_DBG("Current password cannot be opened. errno: %d", errno);
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+       retval = read(fd, &attempt, sizeof(int));
+       close(fd);
+       if(retval < sizeof(int))
+       {
+               SEC_SVR_DBG("%s", "Server ERROR: Cannot read attempt");
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+
+       if(increase > 0)
+       {
+               /* Open the file again with write mode */
+               fd = open(path, O_WRONLY | O_NONBLOCK, 0600);
+               if(fd < 0)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot open attempt file. errno: %d", errno);
+                       return SECURITY_SERVER_ERROR_FILE_OPERATION;
+               }
+               retval = fchmod(fd, 0600);
+               if(retval != 0)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot chmod attempt file. errno: %d", errno);
+                       close(fd);
+                       return SECURITY_SERVER_ERROR_FILE_OPERATION;
+               }
+               attempt += increase;
+               retval = write(fd, &attempt, sizeof(int));
+               close(fd);
+               if(retval < sizeof(int))
+               {
+                       SEC_SVR_DBG("%s", "Server ERROR: Cannot write attempt");
+                       return SECURITY_SERVER_ERROR_FILE_OPERATION;
+               }
+       }
+       return attempt;
+}
+
+int reset_attempt(void)
+{
+       int fd, retval;
+       char path[255];
+       unsigned int attempt = 0;
+
+       snprintf(path, 255, "%s/%s", SECURITY_SERVER_DATA_DIRECTORY_PATH,
+               SECURITY_SERVER_ATTEMPT_FILE_NAME);
+
+       /* Open the file again with write mode */
+       fd = open(path, O_WRONLY | O_NONBLOCK, 0600);
+       if(fd < 0)
+       {
+               SEC_SVR_DBG("Server ERROR: Cannot open attempt file. errno: %d", errno);
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+       retval = fchmod(fd, 0600);
+       if(retval != 0)
+       {
+               SEC_SVR_DBG("Server ERROR: Cannot chmod attempt file. errno: %d", errno);
+               close(fd);
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+       retval = write(fd, &attempt, sizeof(int));
+       close(fd);
+       if(retval < sizeof(int))
+       {
+               SEC_SVR_DBG("%s", "Server ERROR: Cannot write attempt");
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+       SEC_SVR_DBG("%s", "Server: Attempt reset");
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Compare current password Stored password is hashed by SHA-256 Algorithm */
+int check_password(const unsigned char *cur_pwd, const unsigned char *requested_pwd,
+                       const unsigned int max_attempts, const unsigned int expire_time,
+                       int *current_attempt)
+{
+       unsigned int current_time = time(NULL);
+
+       if(max_attempts != 0)
+       {
+               *current_attempt = get_current_attempt(1);
+
+               if(*current_attempt > max_attempts)
+               {
+                       SEC_SVR_DBG("Server: Max attempt exceeded: %d, %d", *current_attempt, max_attempts);
+                       return SECURITY_SERVER_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED;
+               }
+               if(*current_attempt < 0)
+               {
+                       SEC_SVR_DBG("Server: Attempt file operation failed. Ignoring... : %d", *current_attempt);
+               }
+       }
+
+       /* Compare */
+       if(memcmp(cur_pwd, requested_pwd, SECURITY_SERVER_HASHED_PWD_LEN) != 0)
+       {
+           SEC_SVR_DBG("%s", "Password mismatched");
+           return SECURITY_SERVER_ERROR_PASSWORD_MISMATCH;
+       }
+
+    if(expire_time == 0)
+    {
+        SEC_SVR_DBG("Server: Password has been expired: %d, %d", current_time, expire_time);
+        return SECURITY_SERVER_ERROR_PASSWORD_EXPIRED;
+    }
+
+    SEC_SVR_DBG("%s", "Password matched");
+    return SECURITY_SERVER_SUCCESS;
+}
+
+int set_history(int num)
+{
+       int fd, retval;
+       char path[255];
+
+       snprintf(path, 255, "%s/%s", SECURITY_SERVER_DATA_DIRECTORY_PATH,
+               SECURITY_SERVER_HISTORY_FILE_NAME);
+
+       /* Open the file again with write mode */
+       fd = open(path, O_WRONLY | O_NONBLOCK, 0600);
+       if(fd < 0)
+       {
+               if (errno == ENOENT)
+               {
+                       fd = open(path, O_WRONLY | O_NONBLOCK | O_CREAT, 0600);
+                       if(fd < 0)
+                       {
+                               SEC_SVR_DBG("Server ERROR: Cannot create history file. errno: %d", errno);
+                               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+                       }
+               }
+               else
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot open history file. errno: %d", errno);
+                       return SECURITY_SERVER_ERROR_FILE_OPERATION;
+               }
+       }
+       retval = fchmod(fd, 0600);
+       if(retval != 0)
+       {
+               SEC_SVR_DBG("Server ERROR: Cannot chmod history file. errno: %d", errno);
+               close(fd);
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+       retval = write(fd, &num, sizeof(int));
+       close(fd);
+       if(retval < sizeof(int))
+       {
+               SEC_SVR_DBG("%s", "Server ERROR: Cannot write history");
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+       SEC_SVR_DBG("%s", "Server: history set finished");
+       return SECURITY_SERVER_SUCCESS;
+}
+
+
+int get_history_num(void)
+{
+       /* Placeholder for password history check count getting function */
+       int fd, retval, history;
+       char path[255];
+
+       snprintf(path, 255, "%s/%s", SECURITY_SERVER_DATA_DIRECTORY_PATH,
+               SECURITY_SERVER_HISTORY_FILE_NAME);
+
+       /* Load password file */
+       fd = open(path, O_RDONLY | O_NONBLOCK );
+       if(fd < 0)
+       {
+               if(errno == ENOENT)
+               {
+                       SEC_SVR_DBG("%s", "Server: history file doesn't exist");
+                       retval = set_history(0);
+                       return retval;
+               }
+               SEC_SVR_DBG("Server ERROR: history file cannot be opened. errno: %d", errno);
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+       retval = read(fd, &history, sizeof(history));
+       close(fd);
+       if(retval < sizeof(history))
+       {
+               SEC_SVR_DBG("%s", "History file corrupted. Creating new one");
+               unlink(path);
+               retval = set_history(0);
+               return retval;
+       }
+       SEC_SVR_DBG("History file read: %d", history);
+       return history;
+}
+
+
+
+int check_history(const unsigned char *requested_pwd)
+{
+       unsigned char history_pwd[SECURITY_SERVER_HASHED_PWD_LEN];
+       char path[255];
+       unsigned int max_history;
+       int num, history_count, fd, file_count, retval;
+       int retval2 = SECURITY_SERVER_SUCCESS;
+       struct dirent **mydirent;
+
+       history_count = get_history_num();
+       if(history_count <= 0)
+               return SECURITY_SERVER_SUCCESS;
+
+       num = scandir(SECURITY_SERVER_DATA_DIRECTORY_PATH, &mydirent, &dir_filter, alphasort);
+       if(num < 0)
+       {
+               SEC_SVR_DBG("Server: [Error] Cannot scan password directory. errno: %d", errno);
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+
+       if(num == 0)
+       {
+               SEC_SVR_DBG("%s", "Server: There is no password file");
+               return SECURITY_SERVER_ERROR_NO_PASSWORD;
+       }
+
+       file_count = 2;
+       while((num--))
+       {
+               snprintf(path, 255, "%s/%s", SECURITY_SERVER_DATA_DIRECTORY_PATH, mydirent[num]->d_name);
+               SEC_SVR_DBG("Password file path: %s", path);
+               if(history_count > 0)
+               {
+                       /* Load password file */
+                       fd = open(path, O_RDONLY | O_NONBLOCK );
+                       if(fd < 0)
+                       {
+                               if(errno == ENOENT)
+                               {
+                                       SEC_SVR_DBG("%s", "Current password doesn't exist");
+                                       return SECURITY_SERVER_SUCCESS;
+                               }
+                               SEC_SVR_DBG("Current password cannot be opened. errno: %d", errno);
+                               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+                       }
+                       /* Read and store into memory */
+                       retval = read(fd, history_pwd, SECURITY_SERVER_HASHED_PWD_LEN);
+                       if(retval < SECURITY_SERVER_HASHED_PWD_LEN)
+                       {
+                               SEC_SVR_DBG("%s", "Current password corrupted. resetting to previous one. 0");
+                               close(fd);
+                               fd = 0;
+                               unlink(path);
+                               continue;
+                       }
+                       close(fd);
+                       /* Compare */
+                       if(memcmp(history_pwd, requested_pwd, SECURITY_SERVER_HASHED_PWD_LEN) == 0)
+                       {
+                               SEC_SVR_DBG("%s", "Server: Password has been reused");
+                               retval2 =  SECURITY_SERVER_ERROR_PASSWORD_REUSED;
+                       }
+                       history_count--;
+
+               }
+
+               /* Remove too old or invalid password history */
+               retval = validate_pwd_file(mydirent[num]->d_name);
+               if(retval != SECURITY_SERVER_SUCCESS || file_count > (SECURITY_SERVER_MAX_PASSWORD_HISTORY))
+               {
+                       SEC_SVR_DBG("Removing too old password. %s", path);
+                       unlink(path);
+               }
+               file_count++;
+               free(mydirent[num]);
+       }
+       free(mydirent);
+       if(retval2 == SECURITY_SERVER_ERROR_PASSWORD_REUSED)
+               retval = retval2;
+       return retval;
+}
+
+/* Password file format */
+/*  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * |                                                               |
+ * |                                                               |
+ * |                       Hashed PWD (32 bytes)                   |
+ * |                                                               |
+ * |---------------------------------------------------------------|
+ * |                       Max attempts (4 bytes)                  |
+ * |---------------------------------------------------------------|
+ * |              Expiration time in seconds (4 bytes)             |
+ * |---------------------------------------------------------------|
+ */
+int set_password(const unsigned char *requested_new_pwd, const unsigned int attempts,
+                       const unsigned int expire_time)
+{
+       int retval, fd;
+       char pwd_path[255];
+
+       /* New file created */
+       retval = time(NULL);
+       snprintf(pwd_path, 255, "%s/%d.pwd", SECURITY_SERVER_DATA_DIRECTORY_PATH, retval);
+
+       /* Save new password as current password */
+       fd = open(pwd_path, O_WRONLY | O_NONBLOCK | O_CREAT, 0600);
+       if(fd < 0)
+       {
+               SEC_SVR_DBG("Cannot open current password file. errno: %d", errno);
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+       retval = fchmod(fd, 0600);
+       if(retval != 0)
+       {
+               SEC_SVR_DBG("Cannot chmod current password file. errno: %d", errno);
+               close(fd);
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+       retval = write(fd, requested_new_pwd, SECURITY_SERVER_HASHED_PWD_LEN);
+       if(retval < SECURITY_SERVER_HASHED_PWD_LEN)
+       {
+               SEC_SVR_DBG("%s", "Cannot write password");
+               close(fd);
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+       retval = write(fd, &attempts, sizeof(unsigned int));
+       if(retval < sizeof(unsigned int))
+       {
+               SEC_SVR_DBG("%s", "Cannot write password");
+               close(fd);
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+       retval = write(fd, &expire_time, sizeof(unsigned int));
+       if(retval < sizeof(unsigned int))
+       {
+               SEC_SVR_DBG("%s", "Cannot write password");
+               close(fd);
+               return SECURITY_SERVER_ERROR_FILE_OPERATION;
+       }
+       fsync(fd);
+       close(fd);
+       SEC_SVR_DBG("%s", "Password file created");
+       return SECURITY_SERVER_SUCCESS;
+}
+
+int check_retry(const struct timeval cur_try)
+{
+       int retval, interval_sec, interval_usec;
+       interval_sec = cur_try.tv_sec - prev_try.tv_sec;
+       interval_usec = cur_try.tv_usec - prev_try.tv_usec;
+       prev_try = cur_try;
+       if(interval_sec > SECURITY_SERVER_PASSWORD_RETRY_TIMEOUT_SECOND)
+               return SECURITY_SERVER_SUCCESS;
+
+       if(interval_sec == SECURITY_SERVER_PASSWORD_RETRY_TIMEOUT_SECOND
+                       && interval_usec >= 0)
+               return SECURITY_SERVER_SUCCESS;
+
+       SEC_SVR_DBG("%s", "retry timer hit");
+       return SECURITY_SERVER_ERROR_PASSWORD_RETRY_TIMER;
+}
+
+int process_valid_pwd_request(int sockfd)
+{
+       struct timeval cur_try;
+       int retval, current_attempts, password_set;
+       unsigned char cur_pwd[SECURITY_SERVER_HASHED_PWD_LEN];
+       unsigned int max_attempt, expire_time;
+
+/*
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "Client Authentication Failed");
+               retval = send_generic_response(client_sockfd,
+                               SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+*/
+
+       /* Check retry timer */
+       gettimeofday(&cur_try, NULL);
+       retval = check_retry(cur_try);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "Server: Retry timeout occurred");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_PASSWORD_RETRY_TIMER);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+       password_set = load_password(cur_pwd, &max_attempt, &expire_time);
+       if(password_set == SECURITY_SERVER_ERROR_SERVER_ERROR)
+       {
+               SEC_SVR_DBG("%s", "Server: Responding error because we cannot provide password service");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       current_attempts = get_current_attempt(0);
+       if(current_attempts < 0)
+       {
+               SEC_SVR_DBG("Server ERROR: Cannot get attempts: %d", current_attempts);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+       }
+
+       /* There is no password */
+       if(password_set == SECURITY_SERVER_ERROR_NO_PASSWORD)
+       {
+               retval = send_pwd_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_VALID_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_NO_PASSWORD,
+                               0, 0, 0);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send password response: %d", retval);
+               }
+               goto error;
+       }
+       if(password_set == SECURITY_SERVER_SUCCESS)
+       {
+               retval = send_pwd_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_VALID_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_PASSWORD_EXIST,
+                               current_attempts, max_attempt, expire_time);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send password response: %d", retval);
+               }
+               goto error;
+       }
+       SEC_SVR_DBG("Server ERROR: Unknown error: %d", retval);
+       retval = send_generic_response(sockfd,
+                       SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE,
+                       SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+       }
+error:
+       return retval;
+}
+
+int process_set_pwd_request(int sockfd)
+{
+       struct timeval cur_try;
+       int retval, password_set, current_attempt;
+       unsigned int max_attempt, expire_time, valid_days, received_attempts;
+       char  new_pwd_len = 0, cur_pwd_len = 0;
+       char requested_cur_pwd[SECURITY_SERVER_MAX_PASSWORD_LEN+1];
+       char requested_new_pwd[SECURITY_SERVER_MAX_PASSWORD_LEN+1];
+       unsigned char cur_pwd[SECURITY_SERVER_HASHED_PWD_LEN];
+       unsigned char hashed_challenge[SECURITY_SERVER_HASHED_PWD_LEN];
+       unsigned char hashed_new_pw[SECURITY_SERVER_HASHED_PWD_LEN];
+
+       SHA256_CTX context;
+
+       /* Authenticate client that peer is setting app goes here*/
+       /* Check SMACK 'rw' rule for the set password */
+       retval = SECURITY_SERVER_SUCCESS;
+/*
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "Client Authentication Failed");
+               retval = send_generic_response(client_sockfd,
+                               SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+*/
+
+       /* Check retry timer */
+       gettimeofday(&cur_try, NULL);
+       retval = check_retry(cur_try);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "Server: Retry timeout occurred");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_PASSWORD_RETRY_TIMER);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+       password_set = load_password(cur_pwd, &max_attempt, &expire_time);
+       /* If we cannot load password file */
+       if(password_set == SECURITY_SERVER_ERROR_SERVER_ERROR)
+       {
+               SEC_SVR_DBG("%s", "Server: Responding error because we cannot provide password service");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Receive size of pwds */
+       retval = read(sockfd, &cur_pwd_len, sizeof(char));
+       if(retval < sizeof(char) || cur_pwd_len > SECURITY_SERVER_MAX_PASSWORD_LEN)
+       {
+               SEC_SVR_DBG("Server Error: current password length recieve failed: %d, %d", retval, cur_pwd_len);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+       retval = read(sockfd, &new_pwd_len, sizeof(char));
+       if(retval < sizeof(char)  || new_pwd_len > SECURITY_SERVER_MAX_PASSWORD_LEN)
+       {
+               SEC_SVR_DBG("Server Error: new password length recieve failed: %d, %d", retval, new_pwd_len);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Receive current password */
+       if(cur_pwd_len > 0)
+       {
+               /* Check wheter current password is exist */
+               if(password_set == SECURITY_SERVER_SUCCESS)
+               retval = read(sockfd, requested_cur_pwd, cur_pwd_len);
+               if(retval < cur_pwd_len)
+               {
+                       SEC_SVR_DBG("Server Error: current password recieve failed: %d", retval);
+                       retval = send_generic_response(sockfd,
+                                       SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
+                                       SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+                       if(retval != SECURITY_SERVER_SUCCESS)
+                       {
+                               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+                       }
+                       goto error;
+               }
+               requested_cur_pwd[cur_pwd_len] = 0;
+       }
+       else /* Check first password set attempt but password is already set */
+       {
+               if(password_set == SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server Error: password is already set: %d", retval);
+                       retval = send_generic_response(sockfd,
+                                       SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
+                                       SECURITY_SERVER_RETURN_CODE_PASSWORD_EXIST);
+                       if(retval != SECURITY_SERVER_SUCCESS)
+                       {
+                               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+                       }
+                       goto error;
+               }
+       }
+
+       /* Receive new password */
+       retval = read(sockfd, requested_new_pwd, new_pwd_len);
+       if(retval < new_pwd_len)
+       {
+               SEC_SVR_DBG("Server Error:  new password recieve failed: %d", retval);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+       requested_new_pwd[new_pwd_len] = 0;
+
+       /* Receive max attempt */
+       retval = read(sockfd, &received_attempts, sizeof(unsigned int));
+       if(retval < sizeof(unsigned int))
+       {
+               SEC_SVR_DBG("Sever Error:  Max attempt receive failed: %d", retval);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Receive valid period  */
+       retval = read(sockfd, &valid_days, sizeof(unsigned int));
+       if(retval < sizeof(unsigned int))
+       {
+               SEC_SVR_DBG("Sever Error:  Max attempt receive failed: %d", retval);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Hash requested password */
+       SHA256_Init(&context);
+       SHA256_Update(&context, (unsigned char*)requested_cur_pwd, strlen(requested_cur_pwd));
+       SHA256_Final(hashed_challenge, &context);
+
+       SHA256_Init(&context);
+       SHA256_Update(&context, (unsigned char*)requested_new_pwd, strlen(requested_new_pwd));
+       SHA256_Final(hashed_new_pw, &context);
+
+       /* check current password */
+       if(password_set  == SECURITY_SERVER_SUCCESS)
+       {
+               retval = check_password(cur_pwd, hashed_challenge, max_attempt, expire_time, &current_attempt);
+               if(retval == SECURITY_SERVER_ERROR_PASSWORD_MISMATCH)
+               {
+                       SEC_SVR_DBG("%s", "Server: Wrong password");
+                       retval = send_generic_response(sockfd,
+                                       SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
+                                       SECURITY_SERVER_RETURN_CODE_PASSWORD_MISMATCH);
+                       if(retval != SECURITY_SERVER_SUCCESS)
+                       {
+                               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+                       }
+                       goto error;
+               }
+               if(retval == SECURITY_SERVER_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED)
+               {
+                       SEC_SVR_DBG("%s", "Server: Too many challange");
+                       retval = send_generic_response(sockfd,
+                                       SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
+                                       SECURITY_SERVER_RETURN_CODE_PASSWORD_MAX_ATTEMPTS_EXCEEDED);
+                       if(retval != SECURITY_SERVER_SUCCESS)
+                       {
+                               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+                       }
+                       goto error;
+               }
+               if(retval == SECURITY_SERVER_ERROR_PASSWORD_EXPIRED)
+               {
+                       SEC_SVR_DBG("%s", "Server: Password expired");
+                       retval = send_generic_response(sockfd,
+                                       SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
+                                       SECURITY_SERVER_RETURN_CODE_PASSWORD_EXPIRED);
+                       if(retval != SECURITY_SERVER_SUCCESS)
+                       {
+                               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+                       }
+                       goto error;
+               }
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Error: Password check failed: %d", retval);
+                       retval = send_generic_response(sockfd,
+                                       SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
+                                       SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+                       if(retval != SECURITY_SERVER_SUCCESS)
+                       {
+                               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+                       }
+                       goto error;
+               }
+               retval = check_history(hashed_new_pw);
+               if(retval == SECURITY_SERVER_ERROR_PASSWORD_REUSED)
+               {
+                       retval = send_generic_response(sockfd,
+                                       SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
+                                       SECURITY_SERVER_RETURN_CODE_PASSWORD_REUSED);
+                       if(retval != SECURITY_SERVER_SUCCESS)
+                       {
+                               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+                       }
+                       goto error;
+               }
+       }
+       else if(cur_pwd_len != 0)
+       {
+               /* Client ask to set with current password, but there is no password now */
+               SEC_SVR_DBG("%s", "Server: There is no current password. But try to set with current password");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_PASSWORD_MISMATCH);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Calculate expire time in seconds */
+       if(valid_days == 0)
+               expire_time = 0;
+       else
+               expire_time = time(NULL) + (valid_days * 86400);
+
+       /* set new password */
+       retval = set_password(hashed_new_pw, received_attempts, expire_time);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("Server Error: Password set failed: %d", retval);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               password_set = SECURITY_SERVER_ERROR_SERVER_ERROR;
+               goto error;
+       }
+       password_set = SECURITY_SERVER_SUCCESS;
+       retval = reset_attempt();
+
+       /* All done. send response */
+       SEC_SVR_DBG("%s", "Server: Password has been successfully modified");
+       retval = send_generic_response(sockfd,
+                       SECURITY_SERVER_MSG_TYPE_SET_PWD_RESPONSE,
+                       SECURITY_SERVER_RETURN_CODE_SUCCESS);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+       }
+error:
+       return retval;
+}
+
+int process_reset_pwd_request(int sockfd)
+{
+       int retval, password_set;
+       char new_pwd_len;
+       unsigned int valid_days, received_attempts, expire_time;
+       char requested_new_pwd[SECURITY_SERVER_MAX_PASSWORD_LEN +1];
+       unsigned char hashed_new_pw[SECURITY_SERVER_HASHED_PWD_LEN];
+       unsigned char cur_pwd[SECURITY_SERVER_HASHED_PWD_LEN];
+       struct timeval cur_try;
+
+       SHA256_CTX context;
+
+       /* Authenticate client that peer is setting app goes here*/
+/*
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "Client Authentication Failed");
+               retval = send_generic_response(client_sockfd,
+                               SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+*/
+
+       /* Check retry timer */
+       gettimeofday(&cur_try, NULL);
+       retval = check_retry(cur_try);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "Server: Retry timeout occurred");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_RESET_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_PASSWORD_RETRY_TIMER);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       password_set = load_password(cur_pwd, &valid_days, &expire_time);
+       if(password_set == SECURITY_SERVER_ERROR_SERVER_ERROR)
+       {
+               SEC_SVR_DBG("%s", "Server: Responding error because we cannot provide password service");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_GENERIC_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Receive size of pwd */
+       retval = read(sockfd, &new_pwd_len, sizeof(char));
+       if(retval < sizeof(char)  || new_pwd_len > SECURITY_SERVER_MAX_PASSWORD_LEN)
+       {
+               SEC_SVR_DBG("Server Error: new password length recieve failed: %d, %d", retval, new_pwd_len);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_RESET_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Receive new password */
+       retval = read(sockfd, requested_new_pwd, new_pwd_len);
+       if(retval < new_pwd_len)
+       {
+               SEC_SVR_DBG("Server Error:  new password recieve failed: %d", retval);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_RESET_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+       requested_new_pwd[new_pwd_len] = 0;
+
+       /* Receive max attempt */
+       retval = read(sockfd, &received_attempts, sizeof(unsigned int));
+       if(retval < sizeof(unsigned int))
+       {
+               SEC_SVR_DBG("Sever Error:  Max attempt receive failed: %d", retval);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_RESET_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Receive valid period  */
+       retval = read(sockfd, &valid_days, sizeof(unsigned int));
+       if(retval < sizeof(unsigned int))
+       {
+               SEC_SVR_DBG("Sever Error:  Max attempt receive failed: %d", retval);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_RESET_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Calculate expire time in seconds */
+       if(valid_days == 0)
+               expire_time = 0;
+       else
+               expire_time = time(NULL) + (valid_days * 86400);
+
+       /* Hash requested password */
+       SHA256_Init(&context);
+       SHA256_Update(&context, (unsigned char*)requested_new_pwd, strlen(requested_new_pwd));
+       SHA256_Final(hashed_new_pw, &context);
+       /* set new password */
+       retval = set_password(hashed_new_pw, received_attempts, expire_time);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("Server Error: Password set failed: %d", retval);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_RESET_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+       retval = reset_attempt();
+
+       /* All done. send response */
+       SEC_SVR_DBG("%s", "Server: Password has been successfully modified");
+       retval = send_generic_response(sockfd,
+                       SECURITY_SERVER_MSG_TYPE_RESET_PWD_RESPONSE,
+                       SECURITY_SERVER_RETURN_CODE_SUCCESS);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+       }
+error:
+       return retval;
+}
+
+int process_chk_pwd_request(int sockfd)
+{
+       int retval, password_set, current_attempt;
+       unsigned int max_attempt, expire_time;
+       char requested_challenge[SECURITY_SERVER_MAX_PASSWORD_LEN+1];
+       char challenge_len;
+       unsigned char cur_pwd[SECURITY_SERVER_HASHED_PWD_LEN];
+       unsigned char hashed_challenge[SECURITY_SERVER_HASHED_PWD_LEN];
+       struct timeval cur_try;
+
+       SHA256_CTX context;
+
+       /* Authenticate client that peer is proper app goes here*/
+       /* Check SMACK rule for the 'r' for password */
+       retval = SECURITY_SERVER_SUCCESS;
+/*
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "Client Authentication Failed");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+*/
+       /* Check retry timer */
+       gettimeofday(&cur_try, NULL);
+       retval = check_retry(cur_try);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "Server: Retry timeout occurred");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_PASSWORD_RETRY_TIMER);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* If we cannot load password file */
+       password_set = load_password(cur_pwd, &max_attempt, &expire_time);;
+       if(password_set == SECURITY_SERVER_ERROR_SERVER_ERROR)
+       {
+               SEC_SVR_DBG("%s", "ServerERROR: Responding error because we cannot provide password service");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Receive size of challenge */
+       retval = read(sockfd, &challenge_len, sizeof(char));
+       if(retval < sizeof(char) || challenge_len > SECURITY_SERVER_MAX_PASSWORD_LEN)
+       {
+               SEC_SVR_DBG("Server ERROR: challenge length recieve failed: %d", retval);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+       /* Receive challenge */
+       if(challenge_len > 0)
+       {
+               retval = read(sockfd, requested_challenge, challenge_len);
+               if(retval < challenge_len)
+               {
+                       SEC_SVR_DBG("Server ERROR: current password recieve failed: %d", retval);
+                       retval = send_generic_response(sockfd,
+                                       SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE,
+                                       SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+                       if(retval != SECURITY_SERVER_SUCCESS)
+                       {
+                               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+                       }
+                       goto error;
+               }
+               requested_challenge[challenge_len] = 0;
+       }
+       else
+       {
+               SEC_SVR_DBG("Error: Challenge length too short: %d", retval);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Hash requested password */
+       SHA256_Init(&context);
+       SHA256_Update(&context, (unsigned char*)requested_challenge, challenge_len);
+       SHA256_Final(hashed_challenge, &context);
+
+       /* check current password */
+       if(password_set  == SECURITY_SERVER_SUCCESS)
+       {
+               retval = check_password(cur_pwd, hashed_challenge, max_attempt, expire_time, &current_attempt);
+               if(retval == SECURITY_SERVER_ERROR_PASSWORD_MISMATCH)
+               {
+                       SEC_SVR_DBG("%s", "Server: Wrong password");
+                       retval = send_pwd_response(sockfd,
+                                       SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE,
+                                       SECURITY_SERVER_RETURN_CODE_PASSWORD_MISMATCH,
+                                       current_attempt, max_attempt, expire_time);
+                       if(retval != SECURITY_SERVER_SUCCESS)
+                       {
+                               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+                       }
+                       goto error;
+               }
+               if(retval == SECURITY_SERVER_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED)
+               {
+                       SEC_SVR_DBG("%s", "Server: Too many trial");
+                       retval = send_pwd_response(sockfd,
+                                       SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE,
+                                       SECURITY_SERVER_RETURN_CODE_PASSWORD_MAX_ATTEMPTS_EXCEEDED,
+                                       current_attempt, max_attempt, expire_time);
+                       if(retval != SECURITY_SERVER_SUCCESS)
+                       {
+                               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+                       }
+                       goto error;
+               }
+               if(retval == SECURITY_SERVER_ERROR_PASSWORD_EXPIRED)
+               {
+                       SEC_SVR_DBG("%s", "Server: Password expired");
+                       retval = send_pwd_response(sockfd,
+                                       SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE,
+                                       SECURITY_SERVER_RETURN_CODE_PASSWORD_EXPIRED,
+                                       current_attempt, max_attempt, 0);
+                       if(retval != SECURITY_SERVER_SUCCESS)
+                       {
+                               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+                       }
+                       goto error;
+               }
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Password check failed: %d", retval);
+                       retval = send_generic_response(sockfd,
+                                       SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE,
+                                       SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+                       if(retval != SECURITY_SERVER_SUCCESS)
+                       {
+                               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+                       }
+                       goto error;
+               }
+
+               /* Password matched */
+               SEC_SVR_DBG("%s", "Server: Password matched");
+               retval = send_pwd_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_SUCCESS,
+                               current_attempt, max_attempt, expire_time);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               retval = reset_attempt();
+               goto error;
+       }
+
+       /* There is no password */
+
+       SEC_SVR_DBG("%s", "Server: There is no password to be checked");
+       retval = send_generic_response(sockfd,
+                       SECURITY_SERVER_MSG_TYPE_CHK_PWD_RESPONSE,
+                       SECURITY_SERVER_RETURN_CODE_NO_PASSWORD);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+       }
+error:
+       return retval;
+}
+
+int process_set_pwd_history_request(int sockfd)
+{
+       int retval;
+       char history_num;
+       struct timeval cur_try;
+
+       /* Authenticate client that peer is setting app goes here*/
+/*
+       f(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "Client Authentication Failed");
+               retval = send_generic_response(client_sockfd,
+                               SECURITY_SERVER_MSG_TYPE_TOOL_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_AUTHENTICATION_FAILED);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+*/
+
+       /* Check retry timer */
+       gettimeofday(&cur_try, NULL);
+       retval = check_retry(cur_try);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("%s", "Server: Retry timeout occurred");
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_SET_PWD_HISTORY_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_PASSWORD_RETRY_TIMER);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       /* Receive size of pwds */
+       retval = read(sockfd, &history_num, sizeof(char));
+       if(retval < sizeof(char) || history_num > SECURITY_SERVER_MAX_PASSWORD_HISTORY || history_num < 0 )
+       {
+               SEC_SVR_DBG("Server Error: History number recieve failed: %d, %d", retval, history_num);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_SET_PWD_HISTORY_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+               goto error;
+       }
+
+       retval = set_history((int)history_num);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("Server Error: History number set failed: %d", retval);
+               retval = send_generic_response(sockfd,
+                               SECURITY_SERVER_MSG_TYPE_SET_PWD_HISTORY_RESPONSE,
+                               SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+               if(retval != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+               }
+       }
+       SEC_SVR_DBG("Server History has been set to %d", history_num);
+       retval = send_generic_response(sockfd,
+                       SECURITY_SERVER_MSG_TYPE_SET_PWD_HISTORY_RESPONSE,
+                       SECURITY_SERVER_RETURN_CODE_SUCCESS);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+       }
+error:
+       return retval;
+}
+
+
+int process_set_pwd_max_challenge_request(int sockfd)
+{
+    unsigned int max_challenge, current_challenge, current_validity;
+    unsigned char cur_pwd[SECURITY_SERVER_HASHED_PWD_LEN];
+    int retval;
+
+    // TODO here we should probably check if the peer has rights to change
+    // this value (max challenge) for current password
+
+    retval = read(sockfd, &max_challenge, sizeof(unsigned int));
+    if(retval < sizeof(unsigned int))
+    {
+        SEC_SVR_DBG("Server Error: recieve failed: %d", retval);
+        retval = send_generic_response(sockfd,
+                SECURITY_SERVER_MSG_TYPE_SET_PWD_MAX_CHALLENGE_RESPONSE,
+                SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+        if(retval != SECURITY_SERVER_SUCCESS)
+        {
+            SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+        }
+        goto error;
+    }
+
+    SEC_SVR_DBG("Server max challenge request: %d", max_challenge);
+
+    // Getting currently set password
+    retval = load_password(cur_pwd, &current_challenge, &current_validity);
+    /* If we cannot load password file */
+    if(retval == SECURITY_SERVER_ERROR_NO_PASSWORD)
+    {
+        SEC_SVR_DBG("%s", "Server: can't read current password");
+        retval = send_generic_response(sockfd,
+                SECURITY_SERVER_MSG_TYPE_SET_PWD_MAX_CHALLENGE_RESPONSE,
+                SECURITY_SERVER_RETURN_CODE_NO_PASSWORD);
+        if(retval != SECURITY_SERVER_SUCCESS)
+        {
+            SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+        }
+        goto error;
+    }
+    else if(retval != SECURITY_SERVER_SUCCESS)
+    {
+        SEC_SVR_DBG("%s", "Server: can't read current password");
+        retval = send_generic_response(sockfd,
+                SECURITY_SERVER_MSG_TYPE_SET_PWD_MAX_CHALLENGE_RESPONSE,
+                SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+        if(retval != SECURITY_SERVER_SUCCESS)
+        {
+            SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+        }
+        goto error;
+    }
+
+    // Set 'new' password file with old password and new max challenge
+    retval = set_password(cur_pwd, max_challenge, time(NULL) + current_validity);
+    if(retval != SECURITY_SERVER_SUCCESS)
+    {
+        SEC_SVR_DBG("Server Error: Password set failed: %d", retval);
+        retval = send_generic_response(sockfd,
+                SECURITY_SERVER_MSG_TYPE_SET_PWD_MAX_CHALLENGE_RESPONSE,
+                SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+        if(retval != SECURITY_SERVER_SUCCESS)
+        {
+            SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+        }
+        goto error;
+    }
+
+    retval = send_generic_response(sockfd,
+            SECURITY_SERVER_MSG_TYPE_SET_PWD_MAX_CHALLENGE_RESPONSE,
+            SECURITY_SERVER_RETURN_CODE_SUCCESS);
+    if(retval != SECURITY_SERVER_SUCCESS)
+    {
+        SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+    }
+    retval = reset_attempt();
+error:
+    return retval;
+}
+
+int process_set_pwd_validity_request(int sockfd)
+{
+    unsigned int current_challenge, current_validity, validity;
+    unsigned char cur_pwd[SECURITY_SERVER_HASHED_PWD_LEN];
+    int retval;
+
+    // TODO here we should probably check if the peer has rights to change
+    // this value (validity) for current password
+
+    retval = read(sockfd, &validity, sizeof(unsigned int));
+    if(retval < sizeof(unsigned int))
+    {
+        SEC_SVR_DBG("Server Error: recieve failed: %d", retval);
+        retval = send_generic_response(sockfd,
+                SECURITY_SERVER_MSG_TYPE_SET_PWD_VALIDITY_RESPONSE,
+                SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+        if(retval != SECURITY_SERVER_SUCCESS)
+        {
+            SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+        }
+        goto error;
+    }
+
+    SEC_SVR_DBG("Server validity request: %d", validity);
+
+    // Calculating validity in seconds
+    if(validity == 0)
+        validity = 0;
+    else
+        validity = time(NULL) + (validity * 86400);
+
+    // Getting currently set password
+    retval = load_password(cur_pwd, &current_challenge, &current_validity);
+    /* If we cannot load password file */
+    if(retval == SECURITY_SERVER_ERROR_NO_PASSWORD)
+    {
+        SEC_SVR_DBG("%s", "Server: can't read current password");
+        retval = send_generic_response(sockfd,
+                SECURITY_SERVER_MSG_TYPE_SET_PWD_VALIDITY_RESPONSE,
+                SECURITY_SERVER_RETURN_CODE_NO_PASSWORD);
+        if(retval != SECURITY_SERVER_SUCCESS)
+        {
+            SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+        }
+        goto error;
+    }
+    else if(retval != SECURITY_SERVER_SUCCESS)
+    {
+        SEC_SVR_DBG("%s", "Server: can't read current password");
+        retval = send_generic_response(sockfd,
+                SECURITY_SERVER_MSG_TYPE_SET_PWD_VALIDITY_RESPONSE,
+                SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+        if(retval != SECURITY_SERVER_SUCCESS)
+        {
+            SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+        }
+        goto error;
+    }
+
+    // Set 'new' password file with old password and new validity
+    retval = set_password(cur_pwd, current_challenge, validity);
+    if(retval != SECURITY_SERVER_SUCCESS)
+    {
+        SEC_SVR_DBG("Server Error: Password set failed: %d", retval);
+        retval = send_generic_response(sockfd,
+                SECURITY_SERVER_MSG_TYPE_SET_PWD_VALIDITY_RESPONSE,
+                SECURITY_SERVER_RETURN_CODE_SERVER_ERROR);
+        if(retval != SECURITY_SERVER_SUCCESS)
+        {
+            SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+        }
+        goto error;
+    }
+
+    retval = send_generic_response(sockfd,
+            SECURITY_SERVER_MSG_TYPE_SET_PWD_VALIDITY_RESPONSE,
+            SECURITY_SERVER_RETURN_CODE_SUCCESS);
+    if(retval != SECURITY_SERVER_SUCCESS)
+    {
+        SEC_SVR_DBG("Server ERROR: Cannot send generic response: %d", retval);
+    }
+    retval = reset_attempt();
+error:
+    return retval;
+}
diff --git a/src/security-srv/util/security-server-util-common.c b/src/security-srv/util/security-server-util-common.c
new file mode 100644 (file)
index 0000000..e28786a
--- /dev/null
@@ -0,0 +1,367 @@
+/*
+ *  security-server
+ *
+ *  Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ *
+ */
+
+
+#include <poll.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/socket.h>
+#include <sys/types.h>
+#include <fcntl.h>
+#include <sys/un.h>
+#include <errno.h>
+#include <unistd.h>
+
+#include "security-server-common.h"
+#include "security-server-cookie.h"
+#include "security-server-comm.h"
+#include "security-server-util.h"
+#include "security-server.h"
+
+
+/* Get all cookie info response *
+ * packet format
+ *  0                   1                   2                   3
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x52 |       Message Length          |
+ * |---------------------------------------------------------------|
+ * |  return code  |             tot # of cooks (32bit)            |
+ * |---------------------------------------------------------------|
+ * |   cont'd...   |            1st cmdline_len (32bit)            |
+ * |---------------------------------------------------------------|
+ * |   cont'd...   |           1st permission_len (32bit)          |
+ * ----------------------------------------------------------------|
+ * |   cont'd...   |                                               |
+ * |----------------                                               |
+ * |                         1st cookie                            |
+ * |                                                               |
+ * |---------------------------------------------------------------|
+ * |                         1st PID (32bit)                       |
+ * |---------------------------------------------------------------|
+ * |                     1st cmdline (string)                      |
+ * |---------------------------------------------------------------|
+ * |                           1st perm_1                          |
+ * |---------------------------------------------------------------|
+ * |                           1st perm_2                          |
+ * |---------------------------------------------------------------|
+ * |                              ...                              |
+ * |---------------------------------------------------------------|
+ * |                      2nd cmdline_len  (32bit)                 |
+ * |---------------------------------------------------------------|
+ * |                     2nd permission_len (32bit)                |
+ * |---------------------------------------------------------------|
+ * |                                                               |
+ * |                        2nd cookie                             |
+ * |                                                               |
+ * |---------------------------------------------------------------|
+ * |                         2nd PID (32 bit)                      |
+ * |---------------------------------------------------------------|
+ * |                     2nd cmdline (string)                      |
+ * |---------------------------------------------------------------|
+ * |                           2st perm_1                          |
+ * |---------------------------------------------------------------|
+ * |                           2st perm_2                          |
+ * |---------------------------------------------------------------|
+ * |                              ...                              |
+ * |---------------------------------------------------------------|
+ * |                                                               |
+ * |                             ...                               |
+ * |                                                               |
+ * |                                                               |
+ */
+ unsigned char * get_all_cookie_info(cookie_list *list, int *size)
+{
+       cookie_list *current = list;
+       int ptr, total_num, total_size, tempnum, i;
+       unsigned char *buf = NULL, *tempptr = NULL;
+       response_header hdr;
+
+       total_size = sizeof(hdr) + sizeof(int);
+
+       buf = malloc(total_size); /* header size */
+       ptr = sizeof(hdr) + sizeof(int);
+       total_num = 0;  /* Total # of cookies initial value */
+
+       while(current != NULL)
+       {
+               current = garbage_collection(current);
+               if(current == NULL)
+                       break;
+
+               total_num++;
+               total_size += sizeof(int) + sizeof(int) + SECURITY_SERVER_COOKIE_LEN + sizeof(int) + current->path_len + (current->permission_len * sizeof(int));
+               tempptr = realloc(buf, total_size);
+               if(tempptr == NULL)
+               {
+                       SEC_SVR_DBG("%s", "Out of memory");
+                       return NULL;
+               }
+               buf = tempptr;
+
+               tempnum = current->path_len;
+               memcpy(buf+ptr, &tempnum, sizeof(int));
+               ptr += sizeof(int);
+               tempnum = current->permission_len;
+               memcpy(buf+ptr, &tempnum, sizeof(int));
+               ptr += sizeof(int);
+               memcpy(buf+ptr, current->cookie, SECURITY_SERVER_COOKIE_LEN);
+               ptr += SECURITY_SERVER_COOKIE_LEN;
+               tempnum = current->pid;
+               memcpy(buf+ptr, &tempnum, sizeof(int));
+               ptr += sizeof(int);
+               memcpy(buf+ptr, current->path, current->path_len);
+               ptr += current->path_len;
+
+               for(i=0;i<current->permission_len;i++)
+               {
+                       tempnum = current->permissions[i];
+                       memcpy(buf+ptr, &tempnum, sizeof(int));
+                       ptr += sizeof(int);
+               }
+               current = current->next;
+       }
+
+       if(total_size > 65530)
+       {
+               SEC_SVR_DBG("Packet too big. message length overflow: %d", total_size);
+               free(buf);
+               return  NULL;
+       }
+
+       hdr.basic_hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.basic_hdr.msg_id = SECURITY_SERVER_MSG_TYPE_GET_ALL_COOKIES_RESPONSE;
+       hdr.basic_hdr.msg_len =(unsigned short)( total_size - sizeof(hdr));
+       hdr.return_code = SECURITY_SERVER_RETURN_CODE_SUCCESS;
+       memcpy(buf, &hdr, sizeof(hdr));
+       tempnum = total_num;
+       memcpy(buf + sizeof(hdr), &tempnum, sizeof(int));
+       *size = total_size;
+       return buf;
+}
+
+int send_all_cookie_info(const unsigned char *buf, int size, int sockfd)
+{
+       int ret;
+       /* Check poll */
+       ret = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(ret == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       if(ret == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+
+       /* Send to client */
+       ret = write(sockfd, buf, size);
+
+       if(ret < size)
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Get one cookie info response *
+ * packet format
+ *  0                   1                   2                   3
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x54 |       Message Length          |
+ * |---------------------------------------------------------------|
+ * |  return code  |              cmdline_len (32bit)t)            |
+ * |---------------------------------------------------------------|
+ * |   cont'd...   |              permission_len (32bit)           |
+ * ----------------------------------------------------------------|
+ * |   cont'd...   |                                               |
+ * |----------------                                               |
+ * |                             cookie                            |
+ * |                                                               |
+ * |---------------------------------------------------------------|
+ * |                           PID (32bit)                         |
+ * |---------------------------------------------------------------|
+ * |                         cmdline (string)                      |
+ * |---------------------------------------------------------------|
+ * |                             perm_1                            |
+ * |---------------------------------------------------------------|
+ * |                             perm_2                            |
+ * |---------------------------------------------------------------|
+ * |                              ...                              |
+ * |---------------------------------------------------------------|
+*/
+int send_one_cookie_info(const cookie_list *list, int sockfd)
+{
+       unsigned char *buf = NULL;
+       response_header hdr;
+       int total_size, ptr = 0, tempnum, ret, i;
+
+       total_size = sizeof(hdr) + sizeof(int) + sizeof(int) + SECURITY_SERVER_COOKIE_LEN + sizeof(int) + list->path_len + (list->permission_len * sizeof(int));
+       buf = malloc(total_size);
+       if(buf == NULL)
+       {
+               SEC_SVR_DBG("%s", "Out of memory");
+               return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
+       }
+
+       hdr.basic_hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.basic_hdr.msg_id = SECURITY_SERVER_MSG_TYPE_GET_COOKIEINFO_RESPONSE;
+       hdr.basic_hdr.msg_len =sizeof(int) + sizeof(int) + SECURITY_SERVER_COOKIE_LEN + sizeof(int) + list->path_len + (list->permission_len * sizeof(int));
+       hdr.return_code = SECURITY_SERVER_RETURN_CODE_SUCCESS;
+       memcpy(buf, &hdr, sizeof(hdr));
+       ptr += sizeof(hdr);
+
+       tempnum = list->path_len;
+       memcpy(buf+ptr, &tempnum, sizeof(int));
+       ptr += sizeof(int);
+       tempnum = list->permission_len;
+       memcpy(buf+ptr, &tempnum, sizeof(int));
+       ptr += sizeof(int);
+       memcpy(buf+ptr, list->cookie, SECURITY_SERVER_COOKIE_LEN);
+       ptr += SECURITY_SERVER_COOKIE_LEN;
+       tempnum = list->pid;
+       memcpy(buf+ptr, &tempnum, sizeof(int));
+       ptr += sizeof(int);
+       memcpy(buf+ptr, list->path, list->path_len);
+       ptr += list->path_len;
+
+       for(i=0;i<list->permission_len;i++)
+       {
+               tempnum = list->permissions[i];
+               memcpy(buf+ptr, &tempnum, sizeof(int));
+               ptr += sizeof(int);
+       }
+
+       ret = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(ret == SECURITY_SERVER_ERROR_POLL)
+       {
+               SEC_SVR_DBG("%s", "poll() error");
+               free(buf);
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       if(ret == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               SEC_SVR_DBG("%s", "poll() timeout");
+               free(buf);
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+
+       /* Send to client */
+       ret = write(sockfd, buf, total_size);
+       free(buf);
+       if(ret < total_size)
+           return SECURITY_SERVER_ERROR_SEND_FAILED;
+       return SECURITY_SERVER_SUCCESS;
+}
+
+int util_process_all_cookie(int sockfd, cookie_list* list)
+{
+       unsigned char *buf = NULL;
+       int ret;
+       buf = get_all_cookie_info(list, &ret);
+       if(buf == NULL)
+       {
+               return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
+       }
+
+       ret = send_all_cookie_info(buf, ret, sockfd);
+
+       if(buf != NULL)
+               free(buf);
+       return ret;
+}
+int util_process_cookie_from_pid(int sockfd, cookie_list* list)
+{
+       int pid, ret;
+       cookie_list *result = NULL;
+
+       ret = read(sockfd, &pid, sizeof(int));
+       if(ret < sizeof(int))
+       {
+               SEC_SVR_DBG("Received cookie size is too small: %d", ret);
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+       if(pid == 0)
+       {
+               SEC_SVR_DBG("%s", "ERROR: Default cookie is not allowed to be retrieved");
+               ret = send_generic_response(sockfd, SECURITY_SERVER_MSG_TYPE_GET_COOKIEINFO_RESPONSE,
+                       SECURITY_SERVER_RETURN_CODE_BAD_REQUEST);
+               if(ret != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", ret);
+               }
+       }
+       result = search_cookie_from_pid(list, pid);
+       if(result == NULL)
+       {
+               ret = send_generic_response(sockfd, SECURITY_SERVER_MSG_TYPE_GET_COOKIEINFO_RESPONSE,
+                       SECURITY_SERVER_RETURN_CODE_NO_SUCH_COOKIE);
+               if(ret != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", ret);
+               }
+       }
+       else
+       {
+               ret = send_one_cookie_info(result, sockfd);
+               if(ret != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send cookie info response: %d", ret);
+               }
+       }
+       
+       return ret;
+}
+
+int util_process_cookie_from_cookie(int sockfd, cookie_list* list)
+{
+       unsigned char cookie[SECURITY_SERVER_COOKIE_LEN];
+       int ret;
+       cookie_list *result = NULL;
+
+       ret = read(sockfd, cookie, SECURITY_SERVER_COOKIE_LEN);
+       if(ret < SECURITY_SERVER_COOKIE_LEN)
+       {
+               SEC_SVR_DBG("Received cookie size is too small: %d", ret);
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+       result = search_cookie(list, cookie, 0);
+       if(result == NULL)
+       {
+               ret = send_generic_response(sockfd, SECURITY_SERVER_MSG_TYPE_GET_COOKIEINFO_RESPONSE,
+                       SECURITY_SERVER_RETURN_CODE_NO_SUCH_COOKIE);
+               if(ret != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send generic response: %d", ret);
+               }
+       }
+       else
+       {
+               ret = send_one_cookie_info(result, sockfd);
+               if(ret != SECURITY_SERVER_SUCCESS)
+               {
+                       SEC_SVR_DBG("ERROR: Cannot send cookie info response: %d", ret);
+               }
+       }
+       
+       return ret;
+}
diff --git a/src/security-srv/util/security-server-util.c b/src/security-srv/util/security-server-util.c
new file mode 100644 (file)
index 0000000..9e6e516
--- /dev/null
@@ -0,0 +1,773 @@
+/*
+ *  security-server
+ *
+ *  Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Contact: Bumjin Im <bj.im@samsung.com>
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ *
+ */
+
+#include <poll.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/socket.h>
+#include <sys/types.h>
+#include <fcntl.h>
+#include <sys/un.h>
+#include <errno.h>
+#include <unistd.h>
+
+#include "security-server.h"
+#include "security-server-common.h"
+#include "security-server-util.h"
+#include "security-server-comm.h"
+
+#define TOTAL_PATH_MAX 256
+
+#define mszBase64Table  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
+#define BASE64_PAD      '='
+
+
+
+ void printusage(char *cmdline)
+{
+       printf("%s\n", "Usage: ");
+       printf("%s [Options]\n", cmdline);
+       printf("%s\n", "[Options]");
+       printf("%s\n", "-a:\tList all active cookies ");
+       printf("%s\n", "-f [filename]:\tList a specific cookie information from file");
+       printf("%s\n", "\tThe file must contain binary form of cookie");
+       printf("%s\n", "-p [pid]:\tList a specific cookie information for a process by PID");
+       printf("%s\n", "-s [base64 encoded cookie]:\tList a specific cookie information for a process by given base64 encoded cookie value");
+       printf("%s\n", "Example:");
+       printf("%s -a\n", cmdline);
+       printf("%s -f /tmp/mycookie.bin\n", cmdline);
+       printf("%s -p 2115\n", cmdline);
+       printf("%s -s asC34fddaxd6NDVDA43GFD345TfCADF==\n", cmdline);
+}
+
+void printstr(const unsigned char *data, int size)
+{
+       int i;
+       for(i=0;i<size;i++)
+       {
+               printf("%c", data[i]);
+       }
+       printf("\n");
+}
+
+void printperm(const unsigned char *data, int num)
+{
+       int i, ptr, tempnum;
+       for(i=0, ptr=0;i<num;i++)
+       {
+               memcpy(&tempnum, data+ptr, sizeof(int));
+               printf("%d, ", tempnum);
+               ptr+= sizeof(int);
+               if(i % 6 == 0 && i != 0)
+                       printf("\n");
+       }
+       printf("\n");
+}
+
+/* Send all cookie information request packet to security server *
+ * 
+ * Message format
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x51 |       Message Length = 0      |
+ * |---------------------------------------------------------------|
+ */
+int send_all_cookie_info_request(int sockfd)
+{
+
+       basic_header hdr;
+       int retval;
+
+       /* Assemble header */
+       hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_GET_ALL_COOKIES_REQUEST;
+       hdr.msg_len = 0;
+
+       /* Check poll */
+       retval = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               printf("Error: %s\n", "poll() error");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               printf("Error: %s\n", "poll() timeout");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+
+       /* Send to server */
+       retval = write(sockfd, &hdr, sizeof(hdr));
+       if(retval < sizeof(hdr))
+       {
+               /* Write error */
+               printf("Error on write(): %d\n", retval);
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       return SECURITY_SERVER_SUCCESS; 
+}
+
+int recv_all_cookie_info(int sockfd)
+{
+       int retval, total_cookie, ptr = 0, i, cmdline_len, perm_len, recved_pid;
+       response_header hdr;
+       unsigned char *buf = NULL;
+
+       /* Check poll */
+       retval = check_socket_poll(sockfd, POLLIN, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               printf("Error: %s\n", "poll() error");
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               printf("Error: %s\n", "poll() timeout");
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+
+       /* Receive response */
+       retval = read(sockfd, &hdr, sizeof(response_header));
+       if(retval < sizeof(hdr) )
+       {
+               /* Error on socket */
+               printf("Error: Receive failed %d\n", retval);
+               return  SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+
+       if(hdr.return_code != SECURITY_SERVER_RETURN_CODE_SUCCESS)
+       {
+               printf("Error: response error: %d\n", hdr.return_code);
+               return return_code_to_error_code(hdr.return_code);
+       }
+
+       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_GET_ALL_COOKIES_RESPONSE)
+       {
+               printf("Error: response error: different msg type %d\n", hdr.basic_hdr.msg_id );
+               return SECURITY_SERVER_ERROR_BAD_RESPONSE;
+       }
+
+       buf = malloc(hdr.basic_hdr.msg_len);
+       if(buf == NULL)
+       {
+               printf("Error: Out of memory\n");
+               return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
+       }
+
+       retval = read(sockfd, buf, hdr.basic_hdr.msg_len);
+       if(retval < hdr.basic_hdr.msg_len)
+       {
+               printf("Error: receiving too small amount. %d, %d\n", retval,  hdr.basic_hdr.msg_len);
+               printhex(buf, retval);
+               if(buf != NULL)
+                       free(buf);
+               return SECURITY_SERVER_ERROR_BAD_RESPONSE;
+       }
+
+       memcpy(&total_cookie, buf, sizeof(int));
+       if(total_cookie == 0)
+       {
+               printf("There is no cookie available\n");
+               if(buf != NULL)
+                       free(buf);
+               return SECURITY_SERVER_SUCCESS;
+       }
+       ptr = sizeof(int);
+       printf("--------------------------------\n");
+       for(i=0;i<total_cookie;i++)
+       {
+               printf("%dth cookie:\n", i+1);
+               memcpy(&cmdline_len, buf+ptr, sizeof(int));
+               ptr += sizeof(int);
+               memcpy(&perm_len, buf+ptr, sizeof(int));
+               ptr+= sizeof(int);
+
+               printf("%s\n", "Cookie:");
+               printhex(buf + ptr, SECURITY_SERVER_COOKIE_LEN);
+               ptr += SECURITY_SERVER_COOKIE_LEN;
+               memcpy(&recved_pid, buf+ptr, sizeof(int));
+               ptr+= sizeof(int);
+               if(recved_pid == 0)
+               {
+                       printf("PID: %d (default cookie - for all root processes)\n", recved_pid);
+                       printf("%s\n", "cmdline: N/A");
+                       printf("%s\n", "Permissions (gids): N/A");
+               }
+               else
+               {
+                       printf("PID: %d\n", recved_pid);
+
+                       printf("%s\n", "cmdline:");
+                       printstr(buf + ptr, cmdline_len);
+                       ptr += cmdline_len;
+
+                       printf("%s\n", "Permissions (gids):");
+                       printperm(buf + ptr, perm_len);
+                       ptr += (perm_len * sizeof(int));
+               }
+               printf("--------------------------------\n");
+       }
+       if(buf != NULL)
+               free(buf);
+       return SECURITY_SERVER_SUCCESS;
+}
+
+/* Send cookie information request from cookie packet to security server *
+ * 
+ * Message format
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x55 |       Message Length = 20     |
+ * |---------------------------------------------------------------|
+ * |                                                               |
+ * |                         cookie                                |
+ * |                                                               |
+ * |---------------------------------------------------------------|
+ */
+int send_cookie_info_request_from_cookie(int sockfd, const unsigned char *cookie)
+{
+
+       basic_header hdr;
+       int retval;
+       int size = sizeof(hdr) + SECURITY_SERVER_COOKIE_LEN;
+       unsigned char buf[size];
+
+       /* Assemble header */
+       hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_GET_COOKIEINFO_FROM_COOKIE_REQUEST;
+       hdr.msg_len = SECURITY_SERVER_COOKIE_LEN;
+
+       memcpy(buf, &hdr, sizeof(hdr));
+       memcpy(buf + sizeof(hdr), cookie, SECURITY_SERVER_COOKIE_LEN);
+
+       /* Check poll */
+       retval = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               printf("Error: %s\n", "poll() error");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               printf("Error: %s\n", "poll() timeout");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+
+       /* Send to server */
+       retval = write(sockfd, buf, size);
+       if(retval < size)
+       {
+               /* Write error */
+               printf("Error on write(): %d\n", retval);
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       return SECURITY_SERVER_SUCCESS; 
+}
+
+/* Send cookie information request from pid packet to security server *
+ * 
+ * Message format
+ *  0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+ * |---------------------------------------------------------------|
+ * | version=0x01  |MessageID=0x53 |       Message Length = 20     |
+ * |---------------------------------------------------------------|
+ * |                            pid                                |
+ * |---------------------------------------------------------------|
+ */
+int send_cookie_info_request_from_pid(int sockfd, int pid)
+{
+       basic_header hdr;
+       int retval;
+       int size = sizeof(hdr) + sizeof(int);
+       unsigned char buf[size];
+
+       /* Assemble header */
+       hdr.version = SECURITY_SERVER_MSG_VERSION;
+       hdr.msg_id = SECURITY_SERVER_MSG_TYPE_GET_COOKIEINFO_FROM_PID_REQUEST;
+       hdr.msg_len = SECURITY_SERVER_COOKIE_LEN;
+       memcpy(buf, &hdr, sizeof(hdr));
+       memcpy(buf+sizeof(hdr), &pid, sizeof(int));
+
+       /* Check poll */
+       retval = check_socket_poll(sockfd, POLLOUT, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               printf("Error: %s\n", "poll() error");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               printf("Error: %s\n", "poll() timeout");
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+
+       /* Send to server */
+       retval = write(sockfd, buf, size);
+       if(retval < size)
+       {
+               /* Write error */
+               printf("Error on write(): %d\n", retval);
+               return SECURITY_SERVER_ERROR_SEND_FAILED;
+       }
+       return SECURITY_SERVER_SUCCESS; 
+}
+
+int recv_cookie_info_response(sockfd)
+{
+       unsigned char *buf = NULL;
+       int retval, cmdline_len, perm_len, recved_pid, ptr = 0;
+       response_header hdr;
+
+       /* Check poll */
+       retval = check_socket_poll(sockfd, POLLIN, SECURITY_SERVER_SOCKET_TIMEOUT_MILISECOND);
+       if(retval == SECURITY_SERVER_ERROR_POLL)
+       {
+               printf("Error: %s\n", "poll() error");
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+       if(retval == SECURITY_SERVER_ERROR_TIMEOUT)
+       {
+               printf("Error: %s\n", "poll() timeout");
+               return SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+
+       /* Receive response */
+       retval = read(sockfd, &hdr, sizeof(response_header));
+       if(retval < sizeof(hdr) )
+       {
+               /* Error on socket */
+               printf("Error: Receive failed %d\n", retval);
+               return  SECURITY_SERVER_ERROR_RECV_FAILED;
+       }
+
+       if(hdr.return_code != SECURITY_SERVER_RETURN_CODE_SUCCESS)
+       {
+               printf("Error: response error: %d\n", hdr.return_code);
+               return return_code_to_error_code(hdr.return_code);
+       }
+
+       if(hdr.basic_hdr.msg_id != SECURITY_SERVER_MSG_TYPE_GET_COOKIEINFO_RESPONSE)
+       {
+               printf("Error: response error: different msg type %d\n" ,hdr.basic_hdr.msg_id);
+               return SECURITY_SERVER_ERROR_BAD_RESPONSE;
+       }
+
+       buf = malloc(hdr.basic_hdr.msg_len);
+       if(buf == NULL)
+       {
+               printf("Error: Out of memory\n");
+               return SECURITY_SERVER_ERROR_OUT_OF_MEMORY;
+       }
+
+       retval = read(sockfd, buf, hdr.basic_hdr.msg_len);
+       if(retval < hdr.basic_hdr.msg_len)
+       {
+               printf("Error: receiving too small amount. %d, %d\n", retval,  hdr.basic_hdr.msg_len);
+               printhex(buf, retval);
+               if(buf != NULL)
+                       free(buf);
+               return SECURITY_SERVER_ERROR_BAD_RESPONSE;
+       }
+
+       memcpy(&cmdline_len, buf+ptr, sizeof(int));
+       ptr += sizeof(int);
+       memcpy(&perm_len, buf+ptr, sizeof(int));
+       ptr+= sizeof(int);
+
+       printf("%s\n", "Cookie:");
+       printhex(buf + ptr, SECURITY_SERVER_COOKIE_LEN);
+       ptr += SECURITY_SERVER_COOKIE_LEN;
+       memcpy(&recved_pid, buf+ptr, sizeof(int));
+       ptr+= sizeof(int);
+       if(recved_pid == 0)
+       {
+               printf("PID: %d (default cookie - for all root processes)\n", recved_pid);
+               printf("%s\n", "cmdline: N/A");
+               printf("%s\n", "Permissions (gids): N/A");
+       }
+       else
+       {
+               printf("PID: %d\n", recved_pid);
+
+               printf("%s\n", "cmdline:");
+               printstr(buf + ptr, cmdline_len);
+               ptr += cmdline_len;
+
+               printf("%s\n", "Permissions (gids):");
+               printperm(buf + ptr, perm_len);
+       }
+
+       free(buf);
+
+       return SECURITY_SERVER_SUCCESS;
+}
+
+void util_send_all_cookie_info_request(void)
+{
+       int sockfd = -1, retval;
+
+       retval = connect_to_server(&sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               printf("Error: %s\n", "connection failed");
+               goto error;
+       }
+
+       /* make request packet */
+       retval = send_all_cookie_info_request(sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Error: send request failed: %d", retval);
+               goto error;
+       }
+       retval = recv_all_cookie_info(sockfd);
+       if(retval <0)
+       {
+               printf("Error: Error receiving cookie list: %d\n", retval);
+               goto error;
+       }
+
+error:
+       if(sockfd > 0)
+       {
+               close(sockfd);
+       }
+       return;
+}
+
+void util_read_cookie_from_bin_file(unsigned char *cookie, const char *path)
+{
+       char total_path[TOTAL_PATH_MAX] = {0, };
+       FILE *fp = NULL;
+       int ret;
+
+       if(path[0] == '/' || (path[0] == '.' && path[1] == '/'))
+       {
+               /* Using absolute path */
+               strncpy(total_path, path, TOTAL_PATH_MAX);
+       }
+       else
+       {
+               if (getcwd(total_path, TOTAL_PATH_MAX) == NULL)
+               {
+                       printf("Cannot open cookie file\n");
+                       exit(1);
+               }
+               snprintf(total_path, TOTAL_PATH_MAX, "%s/%s", total_path, path);
+       }
+
+       fp = fopen(total_path, "rb");
+       if(fp == NULL)
+       {
+               printf("Cannot open cookie file\n");
+               exit(1);
+       }
+
+       ret = fread(cookie, 1, SECURITY_SERVER_COOKIE_LEN, fp);
+       if(ret < SECURITY_SERVER_COOKIE_LEN)
+       {
+               printf("Cannot read cookie file: %d\n", ret);
+               fclose(fp);
+               exit(1);
+       }
+
+       fclose(fp);
+       return;
+}
+
+void util_send_cookie_info_request_from_cookie(unsigned char *cookie)
+{
+       int sockfd = -1, retval;
+
+       retval = connect_to_server(&sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               printf("Error: %s\n", "connection failed");
+               goto error;
+       }
+
+       /* make request packet */
+       retval = send_cookie_info_request_from_cookie(sockfd, cookie);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Error: send request failed: %d", retval);
+               goto error;
+       }
+       retval = recv_cookie_info_response(sockfd);
+       if(retval == SECURITY_SERVER_ERROR_NO_SUCH_COOKIE)
+       {
+               printf("There is no such cookie available\n");
+               goto error;
+       }
+       if(retval <0)
+       {
+               printf("Error: Error receiving cookie info: %d\n", retval);
+               goto error;
+       }
+
+error:
+       if(sockfd > 0)
+       {
+               close(sockfd);
+       }
+       return;
+}
+
+unsigned char* util_base64_decode(unsigned char* input, long inputLength, long* outputLength)
+{
+       unsigned char* pCurIn = input;
+       unsigned char* pCurOut;
+       long iOutCharNum = 0;
+       long lInputLength = inputLength;
+       char buf[4];
+       unsigned char* inCode;
+       unsigned char* output;
+       (*outputLength) = 0;
+       if((input == NULL) || (inputLength <= 0))
+       return NULL;
+
+        /* calculate length of output data */
+       for(; lInputLength > 0; lInputLength--)
+       {
+               if ((*pCurIn) == BASE64_PAD)
+               {
+                       (*outputLength) += ((iOutCharNum + 1) >> 1);
+                       if ((iOutCharNum == 2) &&
+                       ((lInputLength == 1) ||
+                       (*(pCurIn + 1) != BASE64_PAD)))
+                       {
+                               (*outputLength)++;
+                       }
+                       iOutCharNum = 0;
+                       break;
+               }
+               inCode = (unsigned char*)strchr(mszBase64Table, *(pCurIn++));
+               if (!inCode)
+                       continue;
+               iOutCharNum++;
+               if (iOutCharNum == 4)
+               {
+                       (*outputLength) += 3;
+                       iOutCharNum=0;
+               }
+       }
+       (*outputLength) += ((iOutCharNum + 1)/2);
+
+       /* allocate memory for output data*/
+       output = malloc( *outputLength + 1 );
+       if(NULL == output)
+       {
+               return NULL;
+       }
+       memset( output, 0, (*outputLength + 1) );
+       pCurOut = output;
+       iOutCharNum = buf[0] = buf[1] = buf[2] = buf[3] = 0;
+
+       /* decode data*/
+       pCurIn = input;
+
+       for(; inputLength>0; inputLength--)
+       {
+               if ((*pCurIn) == BASE64_PAD)
+               {
+                       /*end-padding processing*/
+                       if (iOutCharNum == 0)
+                       {
+                               return output;
+                       }
+                       (*(pCurOut++)) = ((buf[0] & 0x3F) << 2) + ((buf[1] & 0x30) >> 4);
+                       if ((iOutCharNum == 3)||((iOutCharNum == 2) && ((lInputLength == 0) ||
+                       ((*(pCurIn + 1)) != BASE64_PAD))))
+                       {
+                               (*(pCurOut++)) = ((buf[1] & 0x0F) << 4) + ((buf[2] & 0x3C) >> 2);
+                       }
+                       return output;
+               }
+               inCode = (unsigned char*)strchr(mszBase64Table, *(pCurIn++));
+               if (!inCode)
+               {
+                       continue;
+               }
+               buf[iOutCharNum++] = (char)((unsigned long)inCode - (unsigned long)mszBase64Table);
+               if (iOutCharNum == 4)
+               {
+                       *(pCurOut++) = ((buf[0] & 0x3F) << 2) + ((buf[1] & 0x30) >> 4);
+                       *(pCurOut++) = ((buf[1] & 0x0F) << 4) + ((buf[2] & 0x3C) >> 2);
+                       *(pCurOut++) = ((buf[2] & 0x03) << 6) + (buf[3] & 0x3F);
+                       iOutCharNum = buf[0] = buf[1] = buf[2] = buf[3] = 0;
+               }
+       }
+       if (iOutCharNum == 0)
+       {
+               return output;
+       }
+       (*(pCurOut++)) = ((buf[0] & 0x3F) << 2) + ((buf[1] & 0x30) >> 4);
+       if (iOutCharNum == 3)
+       {
+               (*(pCurOut++)) = ((buf[1] & 0x0F) << 4) + ((buf[2] & 0x3C) >> 2);
+       }
+       return output;
+}
+
+void util_read_cookie_from_base64_string(unsigned char *cookie, const char *encoded_cookie)
+{
+       unsigned char *decoded_cookie = NULL;
+       int encoded_len, decoded_len;
+       encoded_len = strlen(encoded_cookie);
+
+       decoded_cookie = util_base64_decode((unsigned char *)encoded_cookie, encoded_len, (long *)&decoded_len);
+       if(decoded_len != SECURITY_SERVER_COOKIE_LEN)
+       {
+               printf("Base64 decode failed: %d\n", decoded_len);
+               exit(1);
+       }
+
+       if(decoded_cookie == NULL)
+       {
+               printf("%s", "BASE64 decode failed:\n");
+               exit(1);
+       }
+
+       memcpy(cookie, decoded_cookie, SECURITY_SERVER_COOKIE_LEN);
+       if(decoded_cookie != NULL)
+               free(decoded_cookie);
+
+       return;
+}
+
+void util_send_cookie_info_request_from_pid(const char *str_pid)
+{
+       int retval, sockfd, pid;
+
+       if(str_pid == NULL)
+       {
+               printf("Wrong PID\n");
+               return;
+       }
+
+       errno = 0;
+       pid = strtoul(str_pid, 0, 10);
+       if (errno != 0)
+       {
+               SEC_SVR_DBG("cannot change string to integer [%s]", str_pid);
+               return;
+       }
+
+       retval = connect_to_server(&sockfd);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               printf("Error: %s\n", "connection failed");
+               goto error;
+       }
+
+       /* make request packet */
+       retval = send_cookie_info_request_from_pid(sockfd, pid);
+       if(retval != SECURITY_SERVER_SUCCESS)
+       {
+               /* Error on socket */
+               SEC_SVR_DBG("Error: send request failed: %d", retval);
+               goto error;
+       }
+       retval = recv_cookie_info_response(sockfd);
+       if(retval == SECURITY_SERVER_ERROR_NO_SUCH_COOKIE)
+       {
+               printf("There is no such cookie available\n");
+               goto error;
+       }
+       if(retval <0)
+       {
+               printf("Error: Error receiving cookie info: %d\n", retval);
+               goto error;
+       }
+
+error:
+       if(sockfd > 0)
+       {
+               close(sockfd);
+       }
+       return;
+}
+
+int main(int argc, char *argv[])
+{
+       int ret;
+       unsigned char cookie[20];
+       ret = getuid();
+       if(ret != 0)
+       {
+               printf("You must be root to test. Current UID: %d\nExiting...\n", ret);
+               exit(1);
+       }
+       if(argc < 2 || argc > 4)
+       {
+               printf("Wrong usage: %d\n", argc);
+               printusage(argv[0]);
+               exit(1);
+       }
+       if(strcmp(argv[1], "-a") == 0)
+       {
+               if(argc != 2)
+               {
+                       printf("Wrong usage: %d\n", argc);
+                       printusage(argv[0]);
+                       exit(1);
+               }
+                       
+               util_send_all_cookie_info_request();
+               exit(0);
+       }
+
+       if(argc < 3)
+       {
+               printf("Wrong usage: %d\n", argc);
+               printusage(argv[0]);
+               exit(1);
+       }
+
+       if(strcmp(argv[1], "-f") == 0)
+       {
+               util_read_cookie_from_bin_file(cookie, argv[2]);
+               util_send_cookie_info_request_from_cookie(cookie);
+               exit(0);
+       }
+
+       if(strcmp(argv[1], "-p") == 0)
+       {
+               util_send_cookie_info_request_from_pid(argv[2]);
+               exit(0);
+       }
+
+       if(strcmp(argv[1], "-s") == 0)
+       {
+               util_read_cookie_from_base64_string(cookie, argv[2]);
+               util_send_cookie_info_request_from_cookie(cookie);
+               exit(0);
+       }
+
+       printf("%s", "Wrong usage\n");
+       printusage(argv[0]);
+       exit(1);
+}
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..2a988a7
--- /dev/null
@@ -0,0 +1,716 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT 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)
+{
+    UNHANDLED_EXCEPTION_HANDLER_BEGIN
+    {
+        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;
+    }
+    UNHANDLED_EXCEPTION_HANDLER_END
+}
+
+int WebRuntimeImpl::getAttributesValues(const Request &request,
+        std::list<ATTRIBUTE>* attributes)
+{
+    UNHANDLED_EXCEPTION_HANDLER_BEGIN
+    {
+        // Get current execution state
+        WidgetExecutionPhase executionPhase =
+            request.getExecutionPhase();
+
+        return getAttributesValuesLoop(request, attributes, executionPhase);
+    }
+    UNHANDLED_EXCEPTION_HANDLER_END
+}
+
+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)
+{
+    UNHANDLED_EXCEPTION_HANDLER_BEGIN
+    {
+        // Get current execution state
+        WidgetExecutionPhase executionPhase =
+            request.getExecutionPhase();
+        return getAttributesValuesLoop(request, attributes, executionPhase);
+    }
+    UNHANDLED_EXCEPTION_HANDLER_END
+}
+
+ResourceInformationImpl::ResourceInformationImpl()
+{
+}
+
+/*
+ * class OperationSystemImpl
+ */
+
+int OperationSystemImpl::getAttributesValues(const Request &request,
+        std::list<ATTRIBUTE>* attributes)
+{
+    UNHANDLED_EXCEPTION_HANDLER_BEGIN
+    {
+        //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;
+
+                        typedef AttributeHandlerResponse::const_iterator Iter;
+                        FOREACH(it, attributeResponse)
+                        {
+                            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;
+    }
+    UNHANDLED_EXCEPTION_HANDLER_END
+}
+
+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..32d9b4b
--- /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..68df770
--- /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.
+ */
+/**
+ * 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/scoped_ptr.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;
+    DPL::ScopedPtr<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..48d7f8e
--- /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>
+
+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.IsNull()) {
+        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.IsNull())
+            && 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.IsNull())
+            && 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.IsNull())
+            && 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.IsNull())
+            && 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.IsNull()) {
+        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);
+            DPL::OptionalString 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..19e2b39
--- /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    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/fast_delegate.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 100644 (file)
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..8ff588a
--- /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        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>
+
+namespace RPC {
+
+void OcspServiceCallbacks::checkAccess(SocketConnection * connector){
+    int response = 0;
+    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/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/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..01c746a
--- /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(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..5ab9f85
--- /dev/null
@@ -0,0 +1,80 @@
+/*
+ * 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){
+    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;
+    }
+    LogInfo("Initialized");
+    return WRT_OCSP_OK;
+}
+
+wrt_ocsp_return_t wrt_ocsp_shutdown(void){
+    if (NULL == communicationClient) {
+        LogError("wrt_ocsp_api not initialized");
+        return WRT_OCSP_INTERNAL_ERROR;
+    }
+    delete communicationClient;
+    communicationClient = NULL;
+    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;
+
+  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;
+  }
+    (*status) = static_cast<wrt_ocsp_widget_verification_status_t>(intResponse);
+    LogInfo("Widget verified with response " << intResponse);
+    return WRT_OCSP_OK;
+}