Release changes from Samsung private repository.
authorTomasz Swierczek <t.swierczek@samsung.com>
Mon, 29 Oct 2012 11:15:01 +0000 (12:15 +0100)
committerTomasz Swierczek <t.swierczek@samsung.com>
Mon, 29 Oct 2012 11:18:44 +0000 (12:18 +0100)
* merge of security-server and wrt-security-daemon
* added wrt-ocsp API
* added support for Orange certficates

Change-Id: I0d498b7070876c77d45ce18226f35c08f67c13bb

227 files changed:
CMakeLists.txt
LICENSE
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/dao/common_dao_types.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/CMakeLists.txt [new file with mode: 0644]
communication_client/include/SecurityCommunicationClient.h [new file with mode: 0644]
communication_client/src/CMakeLists.txt [new file with mode: 0644]
communication_client/src/SecurityCommunicationClient.cpp [new file with mode: 0644]
debian/changelog
debian/control
debian/libsecurity-server-client-0.install.in
debian/rules
debian/security-server.install.in
etc/CMakeLists.txt [new file with mode: 0644]
etc/certificates/CMakeLists.txt [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
popup_process/CMakeLists.txt [new file with mode: 0644]
popup_process/CommunicationBox.cpp [new file with mode: 0644]
popup_process/CommunicationBox.h [new file with mode: 0644]
popup_process/PopupEnum.h [new file with mode: 0644]
popup_process/PopupInvoker.cpp [new file with mode: 0644]
popup_process/PopupInvoker.h [new file with mode: 0644]
popup_process/PopupSerializer.cpp [new file with mode: 0644]
popup_process/PopupSerializer.h [new file with mode: 0644]
popup_process/YesNoPopup.cpp [new file with mode: 0644]
popup_process/YesNoPopup.h [new file with mode: 0644]
popup_process/wrt-popup.cpp [new file with mode: 0644]
popup_process/wrt-popup.h [new file with mode: 0644]
security-server.pc.in [deleted file]
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/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 [moved from src/client/security-server-client.c with 100% similarity]
src/security-srv/communication/security-server-comm.c [moved from src/communication/security-server-comm.c with 99% similarity]
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 [moved from include/security-server-comm.h with 100% similarity]
src/security-srv/include/security-server-common.h [moved from include/security-server-common.h with 100% similarity]
src/security-srv/include/security-server-cookie.h [moved from include/security-server-cookie.h with 100% similarity]
src/security-srv/include/security-server-password.h [moved from include/security-server-password.h with 100% similarity]
src/security-srv/include/security-server-util.h [moved from include/security-server-util.h with 100% similarity]
src/security-srv/include/security-server.h [moved from include/security-server.h with 100% similarity]
src/security-srv/mw-list [moved from mw-list with 100% similarity]
src/security-srv/security-serverd [moved from security-serverd with 100% similarity, mode: 0644]
src/security-srv/server/security-server-cookie.c [moved from src/server/security-server-cookie.c with 100% similarity]
src/security-srv/server/security-server-main.c [moved from src/server/security-server-main.c with 98% similarity]
src/security-srv/server/security-server-password.c [moved from src/server/security-server-password.c with 100% similarity]
src/security-srv/util/security-server-util-common.c [moved from src/util/security-server-util-common.c with 100% similarity]
src/security-srv/util/security-server-util.c [moved from src/util/security-server-util.c with 100% similarity]
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_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/ocsp/dbus/api/ocsp_server_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_service.cpp [new file with mode: 0644]
src/services/popup/dbus/api/popup_ace_data_types.h [new file with mode: 0644]
src/services/popup/dbus/api/popup_response_server_api.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]
testcases/debug-util.c [deleted file]
testcases/security_server_tc_client.c [deleted file]
testcases/security_server_tc_password.c [deleted file]
testcases/security_server_tc_pid_reuser.c [deleted file]
testcases/security_server_tc_server.c [deleted file]
testcases/test.h [deleted file]
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]

index 0dfb68e..643bd9a 100644 (file)
+# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES 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(secrutiy-server-C)
+PROJECT("security-server")
 
-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)
+############################# cmake packages ##################################
 
-#Verbose
-#SET(CMAKE_VERBOSE_MAKEFILE ON)
+INCLUDE(FindPkgConfig)
 
-INCLUDE_DIRECTORIES(${CMAKE_SOURCE_DIR}/include)
+############################# 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(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
+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_POPUP "wrt-popup")
+SET(TARGET_WRT_OCSP_LIB "wrt-ocsp")
+SET(TARGET_SEC_SRV_LIB "sec-srv")
+SET(security-server-client "security-server-client")
+
+############################# 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(popup_process)
+ADD_SUBDIRECTORY(src)
+ADD_SUBDIRECTORY(build)
+ADD_SUBDIRECTORY(etc)
 
-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/LICENSE b/LICENSE
index 8bcf8d7..247c97d 100644 (file)
--- a/LICENSE
+++ b/LICENSE
@@ -1,4 +1,3 @@
-
 Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
 
                                  Apache License
@@ -189,7 +188,7 @@ Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
       same "printed page" as the copyright notice for easier
       identification within third-party archives.
 
-   Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
+   Copyright [yyyy] [name of copyright owner]
 
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
@@ -202,4 +201,3 @@ Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved.
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
-
diff --git a/ace/CMakeLists.txt b/ace/CMakeLists.txt
new file mode 100644 (file)
index 0000000..8bf6209
--- /dev/null
@@ -0,0 +1,166 @@
+# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+######################################################################
+
+#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
+    dpl-wrt-dao-ro
+    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/AbstractPolicyEnforcementPoint.h
+    include/ace/AbstractTreeElement.h
+    include/ace/Attribute.h
+    include/ace/AsyncVerdictResultListener.h
+    include/ace/Combiner.h
+    include/ace/CombinerImpl.h
+    include/ace/ConfigurationManager.h
+    include/ace/Constants.h
+    include/ace/Effect.h
+    include/ace/PermissionTriple.h
+    include/ace/Policy.h
+    include/ace/PolicyEffect.h
+    include/ace/PolicyEnforcementPoint.h
+    include/ace/PolicyEvaluator.h
+    include/ace/PolicyEvaluatorFactory.h
+    include/ace/PolicyInformationPoint.h
+    include/ace/PolicyResult.h
+    include/ace/Preference.h
+    include/ace/PromptDecision.h
+    include/ace/Request.h
+    include/ace/SettingsLogic.h
+    include/ace/Subject.h
+    include/ace/TreeNode.h
+    include/ace/UserDecision.h
+    include/ace/WRT_INTERFACE.h
+    include/ace/Verdict.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..bc09fae
--- /dev/null
@@ -0,0 +1,429 @@
+<policy-set id="Tizen-Policy" combine="first-matching-target">
+   <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 alarm -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="alarm" />
+                <resource-match attr="device-cap" func="equal" match="alarm.read" />
+                <resource-match attr="device-cap" func="equal" match="alarm.write" />
+            </condition>
+        </rule>
+
+        <!-- access to application -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="application" />
+                <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" />
+                <resource-match attr="device-cap" func="equal" match="application.manager" />
+                <resource-match attr="device-cap" func="equal" match="application.service" />
+            </condition>
+        </rule>
+
+        <!-- access to bluetooth -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="bluetooth" />
+                <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" />
+                <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="call" />
+                <resource-match attr="device-cap" func="equal" match="call.history" />
+                <resource-match attr="device-cap" func="equal" match="call.history.read" />
+                <resource-match attr="device-cap" func="equal" match="call.history.write" />
+                <resource-match attr="device-cap" func="equal" match="call.state" />
+            </condition>
+        </rule>
+
+        <!-- access to contact -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="contact" />
+                <resource-match attr="device-cap" func="equal" match="contact.read" />
+                <resource-match attr="device-cap" func="equal" match="contact.write" />
+            </condition>
+        </rule>
+
+        <!-- access to filesystem -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="filesystem" />
+                <resource-match attr="device-cap" func="equal" match="filesystem.read" />
+                <resource-match attr="device-cap" func="equal" match="filesystem.write" />
+            </condition>
+        </rule>
+
+        <!-- access to geo coder -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="geocoder" />
+            </condition>
+        </rule>
+
+        <!-- access to mediacontent -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="mediacontent" />
+                <resource-match attr="device-cap" func="equal" match="mediacontent.read" />
+                               <resource-match attr="device-cap" func="equal" match="mediacontent.write" />
+            </condition>
+        </rule>
+
+        <!-- access to Messaging -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="messaging" />
+                <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>
+
+        <!-- access to NFC -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="nfc" />
+                <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.admin" />
+            </condition>
+        </rule>
+
+        <!-- access to Sensors -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="sensors" />
+            </condition>
+        </rule>
+
+        <!-- access to systeminfo -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="systeminfo" />
+            </condition>
+        </rule>
+
+        <!-- access to timeutil -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="time" />
+                <resource-match attr="device-cap" func="equal" match="time.read" />
+                <resource-match attr="device-cap" func="equal" match="time.write" />
+            </condition>
+        </rule>
+
+        <!-- access to lbs -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="lbs" />
+            </condition>
+        </rule>
+
+        <!-- access to map -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="map" />
+            </condition>
+        </rule>
+
+        <!-- access to poi -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="poi" />
+                <resource-match attr="device-cap" func="equal" match="poi.read" />
+                <resource-match attr="device-cap" func="equal" match="poi.write" />
+            </condition>
+        </rule>
+
+        <!-- access to route -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="route" />
+            </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>
+
+        <!-- access to power feature -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="power" />
+            </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 notification feature -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="notification" />
+            </condition>
+        </rule>
+        <rule effect="permit" />
+    </policy>
+
+    <policy id="Tizen-Policy-Untrusted" description="Tizen's policy for untrusted domain" combine="deny-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 alarm -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="alarm" />
+                <resource-match attr="device-cap" func="equal" match="alarm.read" />
+                <resource-match attr="device-cap" func="equal" match="alarm.write" />
+            </condition>
+        </rule>
+
+        <!-- access to application -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="application" />
+                <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" />
+                <resource-match attr="device-cap" func="equal" match="application.manager" />
+                <resource-match attr="device-cap" func="equal" match="application.service" />
+            </condition>
+        </rule>
+
+        <!-- access to bluetooth -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="bluetooth" />
+                <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" />
+                <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="call" />
+                <resource-match attr="device-cap" func="equal" match="call.history" />
+                <resource-match attr="device-cap" func="equal" match="call.history.read" />
+                <resource-match attr="device-cap" func="equal" match="call.history.write" />
+                <resource-match attr="device-cap" func="equal" match="call.state" />
+            </condition>
+        </rule>
+
+        <!-- access to contact -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="contact" />
+                <resource-match attr="device-cap" func="equal" match="contact.read" />
+                <resource-match attr="device-cap" func="equal" match="contact.write" />
+            </condition>
+        </rule>
+
+        <!-- access to filesystem -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="filesystem" />
+                <resource-match attr="device-cap" func="equal" match="filesystem.read" />
+                <resource-match attr="device-cap" func="equal" match="filesystem.write" />
+            </condition>
+        </rule>
+
+        <!-- access to geo coder -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="geocoder" />
+            </condition>
+        </rule>
+
+        <!-- access to mediacontent -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="mediacontent" />
+                <resource-match attr="device-cap" func="equal" match="mediacontent.read" />
+                <resource-match attr="device-cap" func="equal" match="mediacontent.write" />
+            </condition>
+        </rule>
+
+        <!-- access to Messaging -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="messaging" />
+                <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>
+
+        <!-- access to NFC -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="nfc" />
+                <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.admin" />
+            </condition>
+        </rule>
+
+        <!-- access to Sensors -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="sensors" />
+            </condition>
+        </rule>
+
+        <!-- access to systeminfo -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="systeminfo" />
+            </condition>
+        </rule>
+
+        <!-- access to timeutil -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="time" />
+                <resource-match attr="device-cap" func="equal" match="time.read" />
+                <resource-match attr="device-cap" func="equal" match="time.write" />
+            </condition>
+        </rule>
+
+        <!-- access to lbs -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="lbs" />
+            </condition>
+        </rule>
+
+        <!-- access to map -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="map" />
+            </condition>
+        </rule>
+
+        <!-- access to poi -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="poi" />
+                <resource-match attr="device-cap" func="equal" match="poi.read" />
+                <resource-match attr="device-cap" func="equal" match="poi.write" />
+            </condition>
+        </rule>
+
+        <!-- access to route -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="route" />
+            </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>
+
+        <!-- access to power feature -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="power" />
+            </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 notification feature -->
+        <rule effect="permit">
+            <condition combine="or">
+                <resource-match attr="device-cap" func="equal" match="notification" />
+            </condition>
+        </rule>
+
+    </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..7a2bd00
--- /dev/null
@@ -0,0 +1,424 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES 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::setWidgetType(WidgetHandle handle, AppTypes widgetType)
+{
+    Try {
+        ScopedTransaction transaction(&AceDaoUtilities::m_databaseInterface);
+
+        ACE_DB_INSERT(insert, AceSubjectType, &AceDaoUtilities::m_databaseInterface);
+        AceSubjectType::Row row;
+        row.Set_app_id(handle);
+        row.Set_app_type(appTypeToInt(widgetType));
+        insert->Values(row);
+        insert->Execute();
+        transaction.Commit();
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed in setWidgetType");
+    }
+}
+
+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");
+    }
+}
+
+}
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..20bdd58
--- /dev/null
@@ -0,0 +1,405 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES 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/assert.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");
+    }
+}
+
+AppTypes AceDAOReadOnly::getWidgetType(WidgetHandle handle)
+{
+    Try {
+        ACE_DB_SELECT(select, AceSubjectType, &AceDaoUtilities::m_databaseInterface);
+        select->Where(Equals<AceSubjectType::app_id>(handle));
+        std::list<AceSubjectType::Row> rows = select->GetRowList();
+        if (rows.empty()) {
+            return AppTypes::Unknown;
+        }
+        AceSubjectType::Row row = rows.front();
+        return intToAppType(row.Get_app_type());
+    }
+    Catch(DPL::DB::SqlConnection::Exception::Base) {
+        ReThrowMsg(Exception::DatabaseError, "Failed to getWidgetType");
+    }
+}
+
+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");
+    }
+}
+
+}
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..a5ba241
--- /dev/null
@@ -0,0 +1,103 @@
+
+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)
+
+INSTALL(FILES
+    ${PROJECT_SOURCE_DIR}/ace/include/ace-dao-ro/PromptModel.h
+    ${PROJECT_SOURCE_DIR}/ace/include/ace-dao-ro/PreferenceTypes.h
+    ${PROJECT_SOURCE_DIR}/ace/include/ace-dao-ro/BaseAttribute.h
+    ${PROJECT_SOURCE_DIR}/ace/include/ace-dao-ro/BasePermission.h
+    ${PROJECT_SOURCE_DIR}/ace/include/ace-dao-ro/VerdictTypes.h
+    ${PROJECT_SOURCE_DIR}/ace/include/ace-dao-ro/TimedVerdict.h
+    ${PROJECT_SOURCE_DIR}/ace/include/ace-dao-ro/IRequest.h
+    ${PROJECT_SOURCE_DIR}/ace/include/ace-dao-ro/ValidityTypes.h
+    ${PROJECT_SOURCE_DIR}/ace/include/ace-dao-ro/AceDAOReadOnly.h
+    ${PROJECT_SOURCE_DIR}/ace/include/ace-dao-ro/AceDatabase.h
+    ${PROJECT_SOURCE_DIR}/ace/include/ace-dao-ro/common_dao_types.h
+    ${PROJECT_SOURCE_DIR}/ace/include/ace-dao-ro/AceDAOConversions.h
+    ${PROJECT_SOURCE_DIR}/ace/include/ace-dao-ro/AppTypes.h
+    DESTINATION include/ace-dao-ro
+)
+
+INSTALL(FILES
+    ${PROJECT_SOURCE_DIR}/ace/include/ace-dao-rw/AceDAO.h
+    DESTINATION include/ace-dao-rw
+)
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/dao/common_dao_types.cpp b/ace/dao/common_dao_types.cpp
new file mode 100644 (file)
index 0000000..8ae5613
--- /dev/null
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES 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  Michal Ciepielski (m.ciepielski@samsung.com)
+ * @version 1.0
+ * @brief   This file contains the implementation of common data types for wrtdb
+ */
+
+#include <dpl/wrt-dao-ro/common_dao_types.h>
+
+#include <dpl/log/log.h>
+
+namespace WrtDB {
+} // namespace WrtDB
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..a23f712
--- /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/wrt-dao-ro/widget_dao_read_only.h>
+#include <dpl/wrt-dao-ro/WrtDatabase.h>
+#include <dpl/assert.h>
+#include <dpl/foreach.h>
+
+#include <ace/Attribute.h>
+#include <ace-dao-ro/BaseAttribute.h>
+
+using namespace AceDB;
+
+PolicyInformationPoint::PolicyInformationPoint(IWebRuntime *wrt,
+        IResourceInformation *resource,
+        IOperationSystem *system) : wrtInterface(wrt),
+    resourceInformation(resource),
+    operationSystem(system)
+{
+    WrtDB::WrtDatabase::attachToThreadRO();
+}
+
+PolicyInformationPoint::~PolicyInformationPoint()
+{
+    WrtDB::WrtDatabase::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
+                WrtDB::WidgetDAOReadOnly widgetDao(request->getWidgetHandle());
+                std::list<std::string> attrValue;
+                Try {
+                    WrtDB::AppType appType = widgetDao.getWidgetType().appType;
+                    switch (appType) {
+                    case WrtDB::AppType::APP_TYPE_TIZENWEBAPP : {
+                        attrValue.push_back(POLICY_NAME_TIZEN);
+                        LogDebug("==== Using Tizen policy in PIP ====");
+                        break;}
+                    case WrtDB::AppType::APP_TYPE_WAC20 : {
+                        attrValue.push_back(POLICY_NAME_WAC2_0);
+                        LogDebug("==== Using WAC policy in PIP ====");
+                        break;}
+                    default: {
+                        LogError("Invalid widget type");
+                        }
+                    }
+                } Catch (WrtDB::WidgetDAOReadOnly::Exception::WidgetNotExist)
+                {
+                    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..26cd5cc
--- /dev/null
@@ -0,0 +1,745 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT 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);
+}
+
+Attribute::Match Parser::convertToMatchFunction(xmlChar * func)
+{
+    if (func == NULL) {
+        LogError("[ERROR] match function value is NULL");
+        return Attribute::Match::Error;
+    }
+
+    if (*func == 'g') {
+        return Attribute::Match::Glob;
+    } else if (*func == 'e') {
+        return Attribute::Match::Equal;
+    } else if (*func == 'r') {
+        return Attribute::Match::Regexp;
+    } else {
+        LogError("[ERROR] match function value is NULL");
+        return Attribute::Match::Error;
+    }
+    Assert(false);
+}
+
+void Parser::handleAttr(xmlTextReaderPtr reader)
+{
+    xmlChar * attrValue = xmlTextReaderGetAttribute(reader, BAD_CAST("attr")); //get the first attribute
+    Assert(attrValue != NULL && "Error while obtaining attribute");
+
+    std::string temp(reinterpret_cast<const char*>(attrValue));
+    currentAttribute->addValue(&temp);
+
+    xmlFree(attrValue);
+}
+
+void Parser::consumeCurrentText()
+{
+    Assert(currentText != NULL);
+    currentAttribute->addValue(currentText);
+    delete currentText;
+
+    currentText = NULL;
+}
+
+void Parser::consumeCurrentAttribute()
+{
+    Assert(currentAttribute != NULL);
+
+    currentCondition->addAttribute(*currentAttribute);
+    delete currentAttribute;
+
+    currentAttribute = NULL;
+}
+
+void Parser::consumeCurrentSubject()
+{
+    Policy * policy = dynamic_cast<Policy *>(currentRoot->getElement());
+    Assert(policy != NULL);
+    policy->addSubject(currentSubject);
+    //TODO maybe keep subjects not subject pointers in Policies and consume subjects here
+    currentSubject = NULL;
+}
+
+void Parser::consumeCurrentCondition()
+{
+    Condition * temp = NULL;
+    if (currentCondition != NULL) {
+        if (currentCondition->getParent() != NULL) { //Condition is a child of another condition
+            currentCondition->getParent()->addCondition(*currentCondition);
+        } else { //Condition parent is a Rule
+            Rule * rule = dynamic_cast<Rule *>(currentRoot->getElement());
+            Assert(rule != NULL);
+            rule->setCondition(*currentCondition);
+        }
+        temp = currentCondition->getParent();
+        delete currentCondition;
+    }
+    currentCondition = temp;  //switch current condition ( it may be switched to NULL if condition's parent was rule
+}
+
+void Parser::consumeSubjectMatch(xmlChar * value)
+{
+    Assert(
+        currentAttribute != NULL &&
+        "consuming subject match without attribute set");
+
+    if (currentSubject != NULL) {
+        currentSubject->addNewAttribute(*currentAttribute);
+        //[CR] matching/modyfing functions transform uri.host to uri ( etc. ) so strncmp is not needed, string equality will do
+        if (!strncmp(currentAttribute->getName()->c_str(), "uri",
+                     3) ||
+            !strncmp(currentAttribute->getName()->c_str(), "id", 2)) {
+            if (value != NULL) {
+                currentSubject->setSubjectId(reinterpret_cast<const char *>(
+                                                 value));
+            } else if (currentAttribute->getValue()->size()) {
+                currentSubject->setSubjectId(
+                    currentAttribute->getValue()->front());
+            } else {
+                Assert(false);
+            }
+        }
+    } else if (currentCondition != NULL) {
+        currentCondition->addAttribute(*currentAttribute);
+    }
+
+    delete currentAttribute;
+    currentAttribute = NULL;
+}
+
+void Parser::trim(std::string * str)
+{
+    std::string::size_type pos = str->find_last_not_of(whitespaces);
+    if (pos != std::string::npos) {
+        str->erase(pos + 1);
+        pos = str->find_first_not_of(whitespaces);
+        if (pos != std::string::npos) {
+            str->erase(0, pos);
+        }
+    } else {
+        str->erase(str->begin(), str->end());
+        LogInfo("Warning, empty string as attribute value");
+    }
+}
+
+// KW void Parser::canonicalize(const char * input, const char * output, CanonicalizationAlgorithm canonicalizationAlgorithm){
+// KW
+// KW     xmlDocPtr       doc =  xmlParseFile(input);
+// KW     //xmlDocDump(stdout, doc);
+// KW
+// KW     if(doc == NULL)
+// KW     {
+// KW         LogError("Canonicalization error, cannot parser xml file");
+// KW     }
+// KW
+// KW
+// KW     int mode = -1;
+// KW     if(canonicalizationAlgorithm == C14N)
+// KW     {
+// KW         mode = 0;
+// KW     }
+// KW     else if(canonicalizationAlgorithm == C14NEXCLUSIVE)
+// KW     {
+// KW         mode = 1;
+// KW     }
+// KW
+// KW
+// KW     xmlC14NDocSave(doc, NULL, mode, NULL, 0, output, 0);
+// KW
+// KW     xmlFreeDoc(doc);
+// KW
+// KW }
+
+// KW int Parser::extractNodeToFile(xmlTextReaderPtr reader, const char * filename){
+// KW
+// KW        xmlNodePtr node = xmlTextReaderExpand(reader);
+// KW        xmlBufferPtr buff = xmlBufferCreate();
+// KW        xmlNodeDump(buff, node->doc, node, 0, 0);
+// KW        FILE * file = fopen(filename, "w");
+// KW        if(file == NULL){
+// KW            LogError("Error while trying to open file "<<filename);
+// KW            return -1;
+// KW        }
+// KW        int ret = xmlBufferDump(file, buff);
+// KW        fclose(file);
+// KW        xmlBufferFree(buff);
+// KW        return ret;
+// KW
+// KW }
+
diff --git a/ace/include/ace-dao-ro/AceDAOConversions.h b/ace/include/ace-dao-ro/AceDAOConversions.h
new file mode 100644 (file)
index 0000000..e91c850
--- /dev/null
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ *
+ *
+ * @file       AceDAOConversions.h
+ * @author     Grzegorz Krawczyk (g.krawczyk@samsung.com)
+ * @version    0.1
+ * @brief
+ */
+
+#ifndef WRT_ACE_DAO_CONVERSIONS_H_
+#define WRT_ACE_DAO_CONVERSIONS_H_
+
+#include <dpl/string.h>
+#include <ace-dao-ro/BaseAttribute.h>
+
+namespace AceDB {
+namespace AceDaoConversions {
+
+DPL::String convertToHash(const BaseAttributeSet &attributes);
+
+}
+}
+
+#endif
diff --git a/ace/include/ace-dao-ro/AceDAOReadOnly.h b/ace/include/ace-dao-ro/AceDAOReadOnly.h
new file mode 100644 (file)
index 0000000..b57815e
--- /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       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);
+
+    // widget type
+    static AppTypes getWidgetType(WidgetHandle handle);
+
+    // 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);
+
+  protected:
+    static int promptDecisionToInt(PromptDecision decision);
+    static PromptDecision intToPromptDecision(int decision);
+    static int appTypeToInt(AppTypes app_type);
+    static AppTypes intToAppType(int app_type);
+} __attribute__ ((deprecated));
+
+}
+
+#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..bbe1d66
--- /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    common_dao_types.h
+ * @author  Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+ * @version 1.0
+ * @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>
+
+typedef int WidgetHandle;
+typedef std::list<WidgetHandle> WidgetHandleList;
+
+#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..bb17c88
--- /dev/null
@@ -0,0 +1,115 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ *
+ *
+ * @file       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);
+
+    // setting widget type
+    static void setWidgetType(WidgetHandle handle, AppTypes widgetType);
+
+    // 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);
+
+} __attribute__ ((deprecated));
+}
+#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..f9319a3
--- /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
+    } __attribute__ ((deprecated));
+
+    // !! DEPRECATED !!
+    std::string getCurrentPolicyFile(void) const __attribute__ ((deprecated));
+    std::string getFullPathToCurrentPolicyFile(void) const __attribute__ ((deprecated));
+    std::string getFullPathToCurrentPolicyXMLSchema(void) const __attribute__ ((deprecated));
+    int addPolicyFile(const std::string & filePath) __attribute__ ((deprecated));
+    int removePolicyFile(const std::string& fileName) __attribute__ ((deprecated));
+    int changeCurrentPolicyFile(const std::string& filePath) __attribute__ ((deprecated));
+    std::string extractFilename(const std::string& path) const __attribute__ ((deprecated));
+
+    /**
+     * 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&) __attribute__ ((deprecated));
+    bool copyFile(FILE*, FILE*, int lenght = 1024) const __attribute__ ((deprecated));
+    bool checkIfFileExistst(const std::string&) const __attribute__ ((deprecated));
+    const std::list<std::string> & getPolicyFiles() const __attribute__ ((deprecated));
+    const std::string & getConfigFile() const __attribute__ ((deprecated));
+
+    ConfigurationManager()
+    {
+    }
+    virtual ~ConfigurationManager()
+    {
+    }
+
+private:
+
+    static ConfigurationManager * instance;
+} __attribute__ ((deprecated));
+
+#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..f97bc2a
--- /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) __attribute__ ((deprecated));
+    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;
+} __attribute__ ((deprecated));
+
+#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..b7e9d88
--- /dev/null
@@ -0,0 +1,155 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+//
+//
+//
+//  @ Project : Access Control Engine
+//  @ File Name : PolicyEvaluator.h
+//  @ Date : 2009-05-06
+//  @ Author : Samsung
+//
+//
+
+#ifndef _POLICY_EVALUATOR_H
+#define _POLICY_EVALUATOR_H
+
+#include <memory>
+#include <set>
+#include <string>
+
+#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
+    } __attribute__ ((deprecated));
+  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();
+
+    // !! DEPRECATED !!
+    virtual int updatePolicy(const char *) __attribute__ ((deprecated));
+    // This function updates policy from well known locations
+    virtual void updatePolicy();
+
+    // !! DEPRECATED !!
+    std::string getCurrentPolicy() __attribute__ ((deprecated));
+} __attribute__ ((deprecated));
+
+#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..2f342b6
--- /dev/null
@@ -0,0 +1,100 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT 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>
+
+typedef int PipResponse;
+
+class PolicyInformationPoint
+{
+  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;
+    }
+} __attribute__ ((deprecated));
+
+#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..bb1f4e5
--- /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()
+    {
+    }
+
+} __attribute__ ((deprecated));
+
+#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..9ae64c0
--- /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>
+
+#include <ace-dao-ro/common_dao_types.h>
+
+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..ff10dc3
--- /dev/null
@@ -0,0 +1,75 @@
+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(AceSubjectType)
+    COLUMN_NOT_NULL(app_id,        INTEGER,  not null)
+    COLUMN_NOT_NULL(app_type,      INTEGER,  not null)
+    TABLE_CONSTRAINTS(unique(app_id))
+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..ebfcb90
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES 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>
+
+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>;
+} __attribute__ ((deprecated));
+
+typedef DPL::Singleton<AceThinClient> AceThinClientSingleton
+        __attribute__ ((deprecated));
+
+} // 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..e707ac5
--- /dev/null
@@ -0,0 +1,72 @@
+include(FindPkgConfig)
+
+PKG_CHECK_MODULES(ACE_CLIENT_DEPS
+    dpl-wrt-dao-ro
+    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
+    ${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
+    ${PROJECT_SOURCE_DIR}/popup_process/PopupInvoker.cpp
+    ${PROJECT_SOURCE_DIR}/popup_process/PopupSerializer.cpp
+    )
+
+SET(ACE_CLIENT_INCLUDES
+    ${ACE_CLIENT_DEPS_INCLUDE_DIRS}
+    ${ACE_CLIENT_INCLUDE_DIR}
+    ${PROJECT_SOURCE_DIR}/ace_common/include
+    ${PROJECT_SOURCE_DIR}/src/services/ace/dbus/api    
+    ${PROJECT_SOURCE_DIR}/src/services/ace/logic
+    ${PROJECT_SOURCE_DIR}/src/services/popup/dbus/api
+    ${PROJECT_SOURCE_DIR}/src/daemon/dbus    
+    ${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..283e347
--- /dev/null
@@ -0,0 +1,717 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES 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 "security_daemon_dbus_config.h"
+
+#include "ace-client/ace_client.h"
+#include "ace-client/ace_client_helper.h"
+#include <attribute_facade.h>
+#include <ace/Request.h>
+#include <dpl/wrt-dao-ro/wrt_db_types.h>
+#include <dpl/wrt-dao-ro/widget_dao_read_only.h>
+#include <dpl/wrt-dao-ro/WrtDatabase.h>
+
+// ACE tests need to use mock implementations
+#ifdef ACE_CLIENT_TESTS
+
+#include "PopupInvoker_mock.h"
+#include "AceDAOReadOnly_mock.h"
+#include "dbus_client_mock.h"
+#include "PolicyInformationPoint_mock.h"
+
+#else
+
+#include "PopupInvoker.h"
+#include <ace-dao-ro/AceDAOReadOnly.h>
+#include <dpl/dbus/dbus_client.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:
+    DPL::DBus::Client *m_dbusClient, *m_dbusPopupValidationClient;
+
+    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_dbusClient(NULL),
+    m_dbusPopupValidationClient(NULL),
+    m_pip(new WebRuntimeImpl(),
+          new ResourceInformationImpl(),
+          new OperationSystemImpl())
+{
+    AceDB::AceDAOReadOnly::attachToThreadRO();
+    WrtDB::WrtDatabase::attachToThreadRO();
+    Try {
+        m_dbusClient = new DPL::DBus::Client(
+               WrtSecurity::SecurityDaemonConfig::OBJECT_PATH(),
+               WrtSecurity::SecurityDaemonConfig::SERVICE_NAME(),
+               WrtSecurity::AceServerApi::INTERFACE_NAME());
+        m_dbusPopupValidationClient = new DPL::DBus::Client(
+               WrtSecurity::SecurityDaemonConfig::OBJECT_PATH(),
+               WrtSecurity::SecurityDaemonConfig::SERVICE_NAME(),
+               WrtSecurity::PopupServerApi::INTERFACE_NAME());
+        std::string hello = "RPC test.";
+        std::string response;
+        m_dbusClient->call(WrtSecurity::AceServerApi::ECHO_METHOD(),
+                          hello,
+                          &response);
+        LogInfo("Security daemon response from echo: " << response);
+    } Catch (DPL::DBus::Client::Exception::DBusClientException) {
+        ReThrowMsg(AceThinClient::Exception::AceThinClientException,
+                "Failed to call security daemon");
+    }
+}
+
+AceThinClientImpl::~AceThinClientImpl()
+{
+    Assert(NULL != m_dbusClient);
+    Assert(NULL != m_dbusPopupValidationClient);
+    delete m_dbusClient;
+    delete m_dbusPopupValidationClient;
+    m_dbusClient = NULL;
+    m_dbusPopupValidationClient = NULL;
+    WrtDB::WrtDatabase::detachFromThread();
+    AceDB::AceDAOReadOnly::detachFromThread();
+}
+
+bool AceThinClientImpl::isInitialized() const
+{
+    return NULL != m_dbusClient && NULL != m_dbusPopupValidationClient;
+}
+
+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_dbusClient->call(WrtSecurity::AceServerApi::CHECK_ACCESS_METHOD(),
+                                   ace_request.widgetHandle,
+                                   request.getSubjectId(),
+                                   request.getResourceId(),
+                                   request.getFunctionParam().getKeys(),
+                                   request.getFunctionParam().getValues(),
+                                   ace_request.sessionId,
+                                   &serializedPolicyResult);
+            } Catch (DPL::DBus::Client::Exception::DBusClientException) {
+                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");
+
+    // TODO this is evaluation version of popup code
+    // that uses UI handler if it is setup with new ACE API
+    // Final version should use ONLY popup func here
+
+    if (NULL != popup_func) {
+        LogInfo("Using popup handler function");
+
+        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;
+    } else {
+        bool result = true;
+        // We do not use rpc client popup in current implementation.
+        // Assert(m_popupClientInitialized && "Client was not initialized");
+        switch(popupType) {
+        //these case statements without break are made on purpose
+        case PolicyEffect::PROMPT_ONESHOT:
+        case PolicyEffect::PROMPT_SESSION:
+        case PolicyEffect::PROMPT_BLANKET: {
+            AceUserdata aceData;
+            aceData.handle = ace_request.widgetHandle;
+            aceData.subject = request.getSubjectId();
+            aceData.resource = request.getResourceId();
+            aceData.paramKeys = request.getFunctionParam().getKeys();
+            aceData.paramValues = request.getFunctionParam().getValues();
+            aceData.sessionId = ace_request.sessionId;
+
+            //Calling Popup process directly!
+            result = PopupInvoker().showSyncPopup(
+                    static_cast<int>(popupType),
+                    aceData);
+
+            if (result)
+                m_grantedDevCaps->insert(
+                    DPL::FromASCIIString(request.getResourceId()));
+            break; }
+        default:
+            LogError("Unknown popup type passed!");
+            LogError("Maybe effect isn't a popup?");
+            LogError("Effect number is: " << static_cast<int>(popupType));
+            Assert(0);
+        }
+
+        return result;
+    }
+}
+
+bool AceThinClientImpl::validatePopupResponse(
+        const AceRequest& ace_request,
+        const AceBasicRequest& request,
+        bool answer,
+        Prompt::Validity validity
+        )
+{
+    bool response = false;
+    Try{
+        m_dbusPopupValidationClient->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 (DPL::DBus::Client::Exception::DBusClientException) {
+        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
+{
+    // TODO remove subject use in AceRequest
+    //      remove dependency AceThinClient and WrtDaoRo from CMakeLists.txt
+    WrtDB::WidgetDAOReadOnly w_dao(handle);
+    try {
+        DPL::OptionalString widgetGUID = w_dao.getGUID();
+        return !widgetGUID ? "" : DPL::ToUTF8String(*widgetGUID);
+    }
+    catch (WrtDB::WidgetDAOReadOnly::Exception::WidgetNotExist& /*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..9911337
--- /dev/null
@@ -0,0 +1,148 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES 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;
+
+/*
+ * Sets widget 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_set_widget_type(ace_widget_handle_t handle,
+                                 ace_widget_type_t type);
+
+/*
+ * 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..900277f
--- /dev/null
@@ -0,0 +1,59 @@
+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
+    ${ACE_INSTALL_SRC_DIR}/ace_api_install.cpp    
+    )
+
+SET(ACE_INSTALL_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/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..3d32cbf
--- /dev/null
@@ -0,0 +1,277 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES 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 <dpl/dbus/dbus_client.h>
+#include <ace-dao-rw/AceDAO.h>
+#include "ace_server_api.h"
+#include "security_daemon_dbus_config.h"
+
+#include "ace_api_install.h"
+
+static DPL::DBus::Client *dbusClient = 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 != dbusClient) {
+        LogError("ace_api_install already initialized");
+        return ACE_INTERNAL_ERROR;
+    }
+    AceDB::AceDAO::attachToThreadRW();
+    Try {
+        dbusClient = new DPL::DBus::Client(
+                   WrtSecurity::SecurityDaemonConfig::OBJECT_PATH(),
+                   WrtSecurity::SecurityDaemonConfig::SERVICE_NAME(),
+                   WrtSecurity::AceServerApi::INTERFACE_NAME());
+        std::string hello = "RPC test.";
+        std::string response;
+        dbusClient->call(WrtSecurity::AceServerApi::ECHO_METHOD(),
+                          hello,
+                          &response);
+        LogInfo("Security daemon response from echo: " << response);
+    } Catch (DPL::DBus::Client::Exception::DBusClientException) {
+        LogError("Can't connect to daemon");
+        return ACE_INTERNAL_ERROR;
+    }
+    return ACE_OK;
+}
+
+ace_return_t ace_install_shutdown(void)
+{
+    if (NULL == dbusClient) {
+        LogError("ace_api_install not initialized");
+        return ACE_INTERNAL_ERROR;
+    }
+    delete dbusClient;
+    dbusClient = NULL;
+    AceDB::AceDAO::detachFromThread();
+    return ACE_OK;
+}
+
+ace_return_t ace_update_policy(void)
+{
+    Try {
+        dbusClient->call(WrtSecurity::AceServerApi::UPDATE_POLICY_METHOD());
+    } Catch (DPL::DBus::Client::Exception::DBusClientException) {
+        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_set_widget_type(ace_widget_handle_t handle,
+                                 ace_widget_type_t type)
+{
+    Try {
+        AceDB::AceDAO::setWidgetType(
+                handle, to_db_app_type(type));
+    } 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);
+       dbusClient->call(WrtSecurity::AceServerApi::CHECK_ACCESS_INSTALL_METHOD(),
+                        handle,
+                        resource_str,
+                        &serializedPolicyResult);
+   } Catch (DPL::DBus::Client::Exception::DBusClientException) {
+       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..47c27ef
--- /dev/null
@@ -0,0 +1,59 @@
+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
+    ${ACE_POPUP_VALIDATION_SRC_DIR}/ace_api_popup_validation.cpp    
+    )
+
+SET(ACE_POPUP_VALIDATION_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/popup/dbus/api
+    ${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..9184cd2
--- /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        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 <dpl/dbus/dbus_client.h>
+#include "popup_response_server_api.h"
+#include "security_daemon_dbus_config.h"
+#include "ace_api_popup_validation.h"
+
+namespace {
+static DPL::DBus::Client *dbusClient = 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 != dbusClient) {
+        LogError("ace_api_popup_validation already initialized");
+        return ACE_INTERNAL_ERROR;
+    }
+    Try {
+        dbusClient = new DPL::DBus::Client(
+                   WrtSecurity::SecurityDaemonConfig::OBJECT_PATH(),
+                   WrtSecurity::SecurityDaemonConfig::SERVICE_NAME(),
+                   WrtSecurity::PopupServerApi::INTERFACE_NAME());
+    } Catch (DPL::DBus::Client::Exception::DBusClientException) {
+        LogError("Can't connect to daemon");
+        return ACE_INTERNAL_ERROR;
+    }
+}
+
+ace_return_t ace_popup_validation_shutdown(void)
+{
+    if (NULL == dbusClient) {
+        LogError("ace_api_popup_validation not initialized");
+        return ACE_INTERNAL_ERROR;
+    }
+    delete dbusClient;
+    dbusClient = NULL;
+}
+
+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{
+        dbusClient->call(WrtSecurity::PopupServerApi::VALIDATION_METHOD(),
+                         dbusAnswer,
+                         dbusValidity,
+                         handle,
+                         subjectId,
+                         resourceId,
+                         keys,
+                         values,
+                         sessionId,
+                         &response);
+    } Catch (DPL::DBus::Client::Exception::DBusClientException) {
+        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..2798c5e
--- /dev/null
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        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);
+
+#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..2f275bb
--- /dev/null
@@ -0,0 +1,173 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES 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;
+}
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/CMakeLists.txt b/communication_client/CMakeLists.txt
new file mode 100644 (file)
index 0000000..4681770
--- /dev/null
@@ -0,0 +1,2 @@
+ADD_SUBDIRECTORY(src)
+
diff --git a/communication_client/include/SecurityCommunicationClient.h b/communication_client/include/SecurityCommunicationClient.h
new file mode 100644 (file)
index 0000000..50c8964
--- /dev/null
@@ -0,0 +1,81 @@
+/*
+ * 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
+ *
+ */
+
+#ifndef SECURITYCOMMUNICATIONCLIENT_H_
+#define SECURITYCOMMUNICATIONCLIENT_H_
+
+#include <dpl/dbus/dbus_client.h>
+#include <dpl/log/log.h>
+#include <dpl/scoped_ptr.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);
+
+  void connect();
+
+  template<typename ... Args>
+  void call(const char* methodName, const Args& ... args)
+  {
+    //#ifdef DBUS_CONNECTION
+    Try{
+      m_dbusClient->call(methodName, args...);
+    } Catch (DPL::DBus::Client::Exception::DBusClientException){
+      LogError("Error getting response");
+      ReThrowMsg(Exception::SecurityCommunicationClientException,
+               "Error getting response");
+    }
+    //#endif
+    LogInfo("Call served");
+  }
+
+  template<typename ...Args>
+  void call(std::string methodName, const Args&... args)
+  {
+      call(methodName.c_str(), args...);
+  }
+
+  void disconnect();
+private:
+
+  std::string m_interfaceName;
+  //#ifdef DBUS_CONNECTION
+  std::unique_ptr<DPL::DBus::Client> m_dbusClient;
+  //#endif
+};
+} // namespace Communication
+} // namespace WrtSecurity
+
+#endif /* SECURITYCOMMUNICATIONCLIENT_H_ */
diff --git a/communication_client/src/CMakeLists.txt b/communication_client/src/CMakeLists.txt
new file mode 100644 (file)
index 0000000..599bb78
--- /dev/null
@@ -0,0 +1,52 @@
+include(FindPkgConfig)
+
+PKG_CHECK_MODULES(COMMUNICATION_CLIENT_DEPS
+    dpl-efl
+    dpl-dbus-efl
+    REQUIRED
+    )
+
+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
+    )
+
+SET(COMMUNICATION_CLIENT_INCLUDES
+    ${COMMUNICATION_CLIENT_DEPS_INCLUDE_DIRS}
+    ${COMMUNICATION_CLIENT_INCLUDE_DIR}
+    ${PROJECT_SOURCE_DIR}/src/daemon/dbus
+    )
+
+ADD_DEFINITIONS(${COMMUNICATION_CLIENT_DEPS_CFLAGS})
+ADD_DEFINITIONS(${COMMUNICATION_CLIENT_CFLAGS_OTHER})
+
+INCLUDE_DIRECTORIES(${COMMUNICATION_CLIENT_INCLUDES})
+
+ADD_LIBRARY(${TARGET_COMMUNICATION_CLIENT_LIB} SHARED ${COMMUNICATION_CLIENT_SOURCES})
+
+SET_TARGET_PROPERTIES(${COMMUNICATION_CLIENT_LIB} PROPERTIES
+    SOVERSION ${API_VERSION}
+    VERSION ${VERSION})
+
+SET_TARGET_PROPERTIES(${COMMUNICATION_CLIENT_LIB} PROPERTIES
+    COMPILE_FLAGS -fPIC)
+
+TARGET_LINK_LIBRARIES(${TARGET_COMMUNICATION_CLIENT_LIB}
+    ${COMMUNICATION_CLIENT_DEPS_LIBRARIES}
+    ${COMMUNICATION_CLIENT_DEPS_LDFLAGS}
+    )
+
+INSTALL(TARGETS ${TARGET_COMMUNICATION_CLIENT_LIB}
+    DESTINATION lib)
+
diff --git a/communication_client/src/SecurityCommunicationClient.cpp b/communication_client/src/SecurityCommunicationClient.cpp
new file mode 100644 (file)
index 0000000..b51c0f3
--- /dev/null
@@ -0,0 +1,66 @@
+/*
+ * 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){
+    //#ifdef DBUS_CONNECTION
+    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(m_dbusClient.get() == NULL){
+      LogError("Couldn't get client");
+      ThrowMsg(Exception::SecurityCommunicationClientException,
+               "Error getting client");
+    }
+    LogInfo("Created communication client");
+    //#endif
+  }
+
+  void Client::connect(){
+    LogInfo("Connected");
+  }
+
+  void Client::disconnect(){
+    LogInfo("Disconnected");
+  }
+
+
+} // namespace Communication
+
+} // namespace WrtSecurity
+
index 6be8b40..6403086 100644 (file)
-security-server (0.0.36) unstable; urgency=low
+security-server (0.0.45) unstable; urgency=low
 
-  * Reverted merge with wrt-security
-  * Git: framework/security/security/server
-  * Tag: security-server_0.0.36
+  * added orange certificates
 
- -- Tomasz Swierczek <t.swierczek@samsung.com>  Tue, 14 Aug 2012 14:17:00 +0200
+  * Git: framework/security/security-server
+  * Tag: security-server_0.0.45
+
+ -- Bartlomiej Grzelewski <b.grzelewski@samsung.com>  Thu, 25 Oct 2012 11:20:00 +0100
+
+security-server (0.0.44) unstable; urgency=low
+
+  * add licence to rpm package
+  * add support for new wrt-common api
+
+  * Git: framework/security/security-server
+  * Tag: security-server_0.0.44
+
+ -- Bartlomiej Grzelewski <b.grzelewski@samsung.com>  Fri, 12 Oct 2012 14:07:00 +0100
+
+security-server (0.0.43) unstable; urgency=low
+
+  * added manifest with "define" section only
+  * added API for WRT OCSP
+  * added dlog tag "SECURITY_DAEMON" for easier debugging
+
+  * Git: framework/security/security-server
+  * Tag: security-server_0.0.43
+
+ -- Tomasz Swierczek <t.swierczek@samsung.com>  Fri, 5 Oct 2012 16:07:00 +0100
+
+security-server (0.0.42) unstable; urgency=low
+
+  * added manifest with "define" section only
+  * added API for WRT OCSP
+  * added dlog tag "SECURITY_DAEMON" for easier debugging
+
+  * Git: framework/security/security-server
+  * Tag: security-server_0.0.42
+
+ -- Tomasz Swierczek <t.swierczek@samsung.com>  Fri, 5 Oct 2012 15:48:00 +0100
+
+security-server (0.0.41) unstable; urgency=low
+
+  * added API for WRT OCSP
+  * added dlog tag "SECURITY_DAEMON" for easier debugging
+
+  * Git: framework/security/security-server
+  * Tag: security-server_0.0.41
+
+ -- Tomasz Swierczek <t.swierczek@samsung.com>  Fri, 5 Oct 2012 09:29:00 +0100
+
+security-server (0.0.40) unstable; urgency=low
+
+  * Updated TizenPolicy.xml with recent changes from wrt-security repository
+
+  * Git: slp/pkgs/s/security-server
+  * Tag: security-server_0.0.40
+
+ -- Tomasz Swierczek <t.swierczek@samsung.com>  Tue, 25 Sep 2012 12:56:00 +0200
+
+security-server (0.0.39) unstable; urgency=low
+
+  * Refactoring of PC files for security-server client libraries.
+  * Fixed error in pc file of security-dao-rw.
+  * Added old security-server tests to test suite.
+
+  * Git: slp/pkgs/s/security-server
+  * Tag: security-server_0.0.39
+
+ -- Tomasz Swierczek <t.swierczek@samsung.com>  Fri, 21 Sep 2012 14:08:00 +0200
+
+security-server (0.0.38) unstable; urgency=low
+
+  * Use new functions from libsmack and libprivilege-control instead of working with SMACK label directly
+  * Fix policy logic in ace-client
+  * Prepare geolocation tests to be run on test server
+  * Remove deprecated constructor from DeveloperModeValidator
+  * Unify WAC 2.0 with Tizen policy
+  * Reject invalid widget handler
+  * Fix XMLHTTPRequest and externalNetworkAccess in ace_client
+  * Prepare smack tests to be run on test server
+  * Register dlog TAG in security server
+
+  * Git: slp/pkgs/s/security-server
+  * Tag: security-server_0.0.38
+
+ -- Tomasz Swierczek <t.swierczek@samsung.com>  Thu, 13 Sep 2012 15:51:00 +0200
+
+security-server (0.0.37) unstable; urgency=low
+
+  * security-server and wrt-security merge preparation
+  * Git: slp/pkgs/s/security-server
+  * Tag: security-server_0.0.37
+
+ -- Jihoon Chung <jihoon.chung@samsung.com>  Tue, 11 Sep 2012 15:24:19 +0900
+
+security-server (0.0.35) unstable; urgency=low
+
+  * Fix security-server.pc file.
+  * Git: slp/pkgs/s/security-server
+  * Tag: security-server_0.0.35
+
+ -- Bartlomiej Grzelewski <b.grzelewski@samsung.com>  Mon, 30 Jul 2012 14:33:00 +0200
+
+security-server (0.0.34) unstable; urgency=low
+
+  * Fixing dependencies for WRT
+  * Git: slp/pkgs/s/security-server
+  * Tag: security-server_0.0.34
+
+ -- Tomasz Swierczek <t.swierczek@samsung.com>  Wed, 25 Jul 2012 11:39:00 +0200
+
+security-server (0.0.33) unstable; urgency=low
+
+  * Merge with wrt-security (security-server merged with wrt-security-daemon)
+  * Moved the main thread to a separate thread
+  * Git: slp/pkgs/s/security-server
+  * Tag: security-server_0.0.33
+
+ -- Tomasz Swierczek <t.swierczek@samsung.com>  Fri, 20 Jul 2012 12:15:00 +0200
+
+security-server (0.0.32) unstable; urgency=low
+
+  * Merge with wrt-security
+  * Git: slp/pkgs/s/security-server
+  * Tag: security-server_0.0.29
+
+ -- Piotr KożbiaÅ‚ <p.kozbial@samsung.com>  Tue, 08 Jun 2012 11:36:00 +0100
 
 security-server (0.0.1-48) unstable; urgency=low
  
index 5c83a71..9079926 100644 (file)
@@ -1,31 +1,71 @@
 Source: security-server
+Section: base
 Priority: extra
-Maintainer: Bumjin Im <bj.im@samsung.com>, Kidong Kim <kd0228.kim@samsung.com>
-Build-Depends: debhelper (>= 5), autotools-dev, dlog-dev, libssl-dev, libattr1-dev, libsmack-dev
+Maintainer: Bumjin Im <bj.im@samsung.com>, Kidong Kim <kd0228.kim@samsung.com>, Bartlomiej Grzelewski <b.grzelewski@samsung.com>, Piotr Kozbial <p.kozbial@samsung.com>, Piotr Fatyga <p.fatyga@samsung.com>
+Uploaders: Tomasz Swierczek <t.swierczek@samsung.com>, Yunchan Cho <yunchan.cho@samsung.com>
+Build-Depends:
+    debhelper (>= 5), autotools-dev, dlog-dev, libssl-dev, libattr1-dev, libsmack-dev,
+    libglib2.0-dev, libsqlite3-dev, libwebkit-engine-dev, libelm-webview-dev,
+    libxml2-dev, libdbus-1-dev, libefreet-dev, libappcore-efl-dev, openssl (>= 0.9.7),
+    libcert-svc-dev, wrt-commons-dev (>= 0.2.22), libpcre-dev, libelm-dev, libecore-dev,
+    libeina-dev, libui-gadget-dev, libslp-utilx-dev, libsecurity-server-client-dev,
+    libpkgmgr-installer-dev, libxmlsec1-dev, libidn11-dev, libpkgmgr-types-dev,
+    libss-client-dev, libiri-dev
 Standards-Version: 3.7.2
-Section: base
-Homepage: N/A
 
 Package: libsecurity-server-client-dev
-Section: libs
 Architecture: any
+Section: libs
 Depends: ${misc:Depends}, libsecurity-server-client-0 (= ${Source-Version}), dlog-dev
 Description: security server client library develpoment package
 
 Package: libsecurity-server-client-0
-Section: libs
 Architecture: any
+Section: libs
 Depends: ${shlibs:Depends}, ${misc:Depends}
 Description: security server client library package
 
 Package: security-server
-Section: base
 Architecture: any
-Depends: ${shlibs:Depends}, ${misc:Depends}, libsecurity-server-client-0 (= ${Source-Version}), openssl
+Section: base
+Depends: ${shlibs:Depends}, ${misc:Depends},
+         libsecurity-server-client-0 (= ${Source-Version}), openssl
 Description: security server
 
 Package: security-server-dbg
-Section: debug
 Architecture: any
+Section: debug
 Depends: ${misc:Depends}, security-server (= ${Source-Version})
 Description: debug package of security server source package
+
+Package: wrt-security
+Architecture: any
+Section: libs
+Depends: ${shlibs:Depends}, ${misc:Depends}, openssl, libug-picker-efl,
+         sqlite3, wrt-commons (>= 0.2.22)
+Replaces: wrt-security
+Provides: wrt-security
+Conflicts: wrt-security
+Description: online widget(W3C, BONDI, JIL, MSC) platform
+
+Package: wrt-security-dev
+Architecture: any
+Section: libs
+Depends: wrt-security (= ${Source-Version}), wrt-commons-dev (>= 0.2.22),
+         openssl, libxml2-dev, libsoup2.4-dev
+Description: wrt security platform - dev
+
+Package: wrt-security-test
+Architecture: any
+Section: libs
+Depends: wrt-security (= ${Source-Version}), wrt-commons (>=0.2.9)
+Description: wrt security platform - test programs
+
+Package: wrt-security-dbg
+Architecture: any
+Replaces: wrt-security-dbg
+Provides: wrt-security-dbg
+Conflicts: wrt-security-dbg
+Section: debug
+Depends: ${shlibs:Depends}, ${misc:Depends}
+Description: online widget(W3C, BONDI, JIL, MSC) platform - debug
index 5443644..1163112 100755 (executable)
@@ -9,12 +9,23 @@
 # Uncomment this to turn on verbose mode.
 #export DH_VERBOSE=1
 
-CFLAGS ?= -Wall -g
-CXXFLAGS ?=  -Wall -g
-LDFLAGS ?= 
+PACKAGE_VERSION ?= $(shell dpkg-parsechangelog | sed -n 's/^Version: // p')
+
 PREFIX ?= /usr
 DATADIR ?= /opt
 
+CFLAGS ?= -Wall -g
+CXXFLAGS ?=  -Wall -g
+LDFLAGS += -Wl,--rpath=$(PREFIX)/lib -Wl,--as-needed
+
+CMAKE_BUILD_DIR ?= $(CURDIR)/cmake_build_tmp
+
+ifeq (,$(findstring no,$(DPL_LOGS)))
+       DPL_LOGS_STATUS = "ON"
+else
+       DPL_LOGS_STATUS = "OFF"
+endif
+
 ifneq (,$(findstring noopt,$(DEB_BUILD_OPTIONS)))
        CFLAGS += -O0
        CXXFLAGS += -O0
@@ -23,53 +34,69 @@ else
        CXXFLAGS += -O2
 endif
 
-LDFLAGS += -Wl,--rpath=$(PREFIX)/lib -Wl,--as-needed
 
-configure: configure-stamp
-configure-stamp:
+config.status:
        dh_testdir
        # Add here commands to configure the package.
-       CFLAGS="$(CFLAGS)" CXXFLAGS="$(CXXFLAGS)" LDFLAGS="$(LDFLAGS)" cmake . -DCMAKE_INSTALL_PREFIX=$(PREFIX)
-
-       touch configure-stamp
+       mkdir -p $(CMAKE_BUILD_DIR) && cd $(CMAKE_BUILD_DIR) && \
+       cmake ${SRCDIR} \
+               -DCMAKE_INSTALL_PREFIX="${PREFIX}"      \
+               -DDPL_LOG=$(DPL_LOGS_STATUS)            \
+               -DVERSION=${PACKAGE_VERSION} ..
 
 build: build-stamp
 
-build-stamp: configure-stamp 
+build-stamp:  config.status
        dh_testdir
-
        # Add here commands to compile the package.
-       $(MAKE)
-       #docbook-to-man debian/wavplayer.sgml > wavplayer.1
-
-       for f in `find $(CURDIR)/debian/ -name "*.in"`; do \
+       cd $(CMAKE_BUILD_DIR) && $(MAKE)
+#### -j 4
+       #docbook-to-man debian/ncurses.sgml > ncurses.1
+       for f in `find $(CURDIR)/ -name "*.in"`; do \
                cat $$f > $${f%.in}; \
                sed -i -e "s#@PREFIX@#$(PREFIX)#g" $${f%.in}; \
                sed -i -e "s#@DATADIR@#$(DATADIR)#g" $${f%.in}; \
        done
-
-
        touch $@
 
+
 clean:
        dh_testdir
        dh_testroot
-       rm -f build-stamp configure-stamp
+       rm -f build-stamp
 
        # Add here commands to clean up after the build process.
-       -$(MAKE) clean
-       rm -rf CMakeCache.txt
-       rm -rf CMakeFiles
-       rm -rf cmake_install.cmake
+       -find . -name CMakeFiles -exec rm -rf {} \;
+       -find . -name cmake_install.cmake -exec rm {} \;
+       #-find . -name Makefile -exec rm {} \;
+       rm CMakeCache.txt -rf
+       #-$(MAKE) distclean
+       rm -rf $(CMAKE_BUILD_DIR)
+       rm -rf autotools
+       rm -rf aclocal.m4
+       rm -rf configure
        rm -rf Makefile
+       rm -rf Makefile.in
+       rm -rf m4
+       rm -rf libtool
+       rm -rf build/config.*
+       rm -rf build/depcomp
+       rm -rf build/install-sh
+       rm -rf build/ltmain.sh
+       rm -rf build/missing
        rm -rf install_manifest.txt
        rm -rf *.so
        rm -rf *.pc
-
+ifneq "$(wildcard /usr/share/misc/config.sub)" ""
+       cp -f /usr/share/misc/config.sub config.sub
+endif
+ifneq "$(wildcard /usr/share/misc/config.guess)" ""
+       cp -f /usr/share/misc/config.guess config.guess
+endif
        for f in `find $(CURDIR)/debian/ -name "*.in"`; do \
                rm -f $${f%.in}; \
        done
-
+       rm -rf config.*
        dh_clean
 
 install: build
@@ -78,8 +105,8 @@ install: build
        dh_clean -k 
        dh_installdirs
 
-       # Add here commands to install the package into debian/wavplayer.
-       $(MAKE) DESTDIR=$(CURDIR)/debian/tmp install
+       cd $(CMAKE_BUILD_DIR) && $(MAKE) DESTDIR=$(CURDIR)/debian/tmp install
+
        mkdir -p $(CURDIR)/debian/tmp/etc/rc.d/rc3.d/
        mkdir -p $(CURDIR)/debian/tmp/etc/rc.d/rc5.d/
        ln -s ../init.d/security-serverd $(CURDIR)/debian/tmp/etc/rc.d/rc3.d/S10security-server
@@ -123,4 +150,4 @@ binary-arch: build install
        dh_builddeb
 
 binary: binary-indep binary-arch
-.PHONY: build clean binary-indep binary-arch binary install configure
+.PHONY: build clean binary-indep binary-arch binary install
index 6a751a4..355f090 100644 (file)
@@ -3,4 +3,4 @@ etc/rc.d/rc3.d/S10security-server
 etc/rc.d/rc5.d/S10security-server
 etc/rc.d/init.d/security-serverd
 usr/share/security-server/mw-list
-/usr/bin/sec-svr-util
+#/usr/bin/sec-svr-util
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/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..6ffc374
--- /dev/null
@@ -0,0 +1,25 @@
+<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 -->
+    </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..a1fc4e8
--- /dev/null
@@ -0,0 +1,17 @@
+#!/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.
+#
+
+dbus-send --system --print-reply --dest=org.tizen.SecurityDaemon /org/tizen/SecurityDaemon org.tizen.AceCheckAccessInterface.update_policy
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>
index 8fe6ce6..d64c943 100644 (file)
@@ -1,30 +1,44 @@
-#sbs-git:slp/pkgs/s/security-server security-server 0.0.1 41964751bdbad7b215eea8f7ca955aa365348e4a
+#sbs-git:slp/pkgs/s/security-server security-server 0.0.37
 Name:       security-server
-Summary:    Security server
-Version:    0.0.36
+Summary:    Security server and utilities
+Version:    0.0.46
 Release:    1
 Group:      TO_BE/FILLED_IN
-License:    Apache2.0
+License:    Apache License, Version 2.0
+URL:        N/A
 Source0:    %{name}-%{version}.tar.gz
-BuildRequires:  cmake
-BuildRequires:  pkgconfig(dlog)
-BuildRequires:  pkgconfig(openssl)
-BuildRequires:  libattr-devel
-BuildRequires:  pkgconfig(libsmack)
+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-wrt-dao-rw)
+BuildRequires: pkgconfig(dpl-dbus-efl)
+BuildRequires: pkgconfig(libpcrecpp)
+BuildRequires: pkgconfig(icu-i18n)
+BuildRequires: pkgconfig(libsoup-2.4)
+BuildRequires: pkgconfig(xmlsec1)
 
 %description
-Security server package
+Security server and utilities
 
 %package -n libsecurity-server-client
 Summary:    Security server (client)
 Group:      Development/Libraries
-Requires:   %{name} = %{version}-%{release}
+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
@@ -33,19 +47,45 @@ 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
-cmake . -DCMAKE_INSTALL_PREFIX=%{_prefix}
-
+export LDFLAGS+="-Wl,--rpath=%{_prefix}/lib"
 
+cmake . -DCMAKE_INSTALL_PREFIX=%{_prefix} \
+        -DDPL_LOG="ON"                    \
+        -DVERSION=%{version}
 make %{?jobs:-j%jobs}
 
+
 %install
 rm -rf %{buildroot}
+mkdir -p %{buildroot}/usr/share/license
+cp LICENSE %{buildroot}/usr/share/license/%{name}
+cp LICENSE %{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
@@ -53,6 +93,36 @@ 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
+ln -s -f /opt/dbspace/.cert_svc_vcore.db-journal /opt/dbspace/.vcore.db-journal
+ln -s -f /opt/dbspace/.cert_svc_vcore.db /opt/dbspace/.vcore.db
+
+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
@@ -63,21 +133,60 @@ rm -f /etc/rc.d/rc5.d/S10security-server
 %postun -n libsecurity-server-client -p /sbin/ldconfig
 
 
-%files
+%files -n security-server
+%manifest %{_datadir}/security-server.manifest
 %defattr(-,root,root,-)
-/etc/rc.d/init.d/security-serverd
-/usr/bin/security-server
-/usr/bin/sec-svr-util
 /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.*
+%{_libdir}/libcommunication-client.so*
+/usr/share/wrt-engine/*
+%attr(755,root,root) %{_bindir}/wrt-popup
+%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-dao-ro/*
+%{_includedir}/ace-dao-rw/*
+%{_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/popup_process/CMakeLists.txt b/popup_process/CMakeLists.txt
new file mode 100644 (file)
index 0000000..0873cdc
--- /dev/null
@@ -0,0 +1,52 @@
+# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+
+PKG_CHECK_MODULES(WRT_POPUP_DEPS
+    dpl-efl
+    dpl-event-efl
+    dpl-popup-efl        
+    REQUIRED
+)
+
+INCLUDE_DIRECTORIES(
+    ${CMAKE_CURRENT_SOURCE_DIR}
+    ${WRT_POPUP_DEPS_INCLUDE_DIRS}
+    ${PROJECT_SOURCE_DIR}/src/services/popup/dbus/api
+    ${PROJECT_SOURCE_DIR}/ace/include
+)
+
+SET(WRT_POPUP_SRCS
+    wrt-popup.cpp
+    PopupSerializer.cpp
+    YesNoPopup.cpp
+    CommunicationBox.cpp
+)
+
+ADD_EXECUTABLE(${TARGET_WRT_POPUP}
+    ${WRT_POPUP_SRCS}
+)
+
+TARGET_LINK_LIBRARIES(${TARGET_WRT_POPUP}
+    ${WRT_POPUP_DEPS_LIBRARIES}
+    ${TARGET_ACE_DAO_RO_LIB}
+)
+
+SET_TARGET_PROPERTIES(${TARGET_WRT_POPUP} PROPERTIES
+    LINK_FLAGS "-Wl,--as-needed -Wl,--hash-style=both -Wl"
+    BUILD_WITH_INSTALL_RPATH ON
+    INSTALL_RPATH_USE_LINK_PATH ON
+)
+
+INSTALL(TARGETS ${TARGET_WRT_POPUP} DESTINATION bin)
diff --git a/popup_process/CommunicationBox.cpp b/popup_process/CommunicationBox.cpp
new file mode 100644 (file)
index 0000000..d3d5282
--- /dev/null
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/* @file        CommunicationBox.cpp
+ * @author      Justyna Mejzner (j.kwiatkowsk@samsung.com)
+ * @version     1.0
+ *
+ */
+#include "CommunicationBox.h"
+#include <stddef.h>
+#include <dpl/log/log.h>
+
+void CommunicationBox::showAsync(
+        const Prompt::PromptModel::PromptType promptType,
+        const std::string& mainLabel,
+        const std::vector<std::string>& buttonLabels,
+        const DPL::OptionalString& checkLabel,
+        ResponseDelegate callback,
+        void* userdata)
+{
+    m_callback = callback;
+    m_userdata = userdata;
+    m_promptType = promptType;
+    using namespace DPL::Popup;
+
+    CtrlPopupPtr popup = PopupControllerSingleton::Instance().CreatePopup();
+    popup->Append(new PopupObject::Label(mainLabel));
+
+    if (!!checkLabel)
+    {
+        popup->Append(new PopupObject::Check(DPL::ToUTF8String(*checkLabel)));
+    }
+
+    for (size_t questionIndex = 0; questionIndex < buttonLabels.size();
+         ++questionIndex)
+    {
+        popup->Append(new PopupObject::Button(
+                buttonLabels[questionIndex],questionIndex));
+    }
+
+
+    ListenForAnswer(popup);
+
+     //nested loop is not used here
+    ShowPopupEventShort event(popup,
+                              MakeAnswerCallback(
+                                     this,
+                                     &CommunicationBox::AnswerCallback));
+
+    CONTROLLER_POST_EVENT(PopupController,
+                          event);
+}
+
+void CommunicationBox::AnswerCallback(const DPL::Popup::AnswerCallbackData &answer)
+{
+    m_callback(answer.buttonAnswer, answer.chackState, m_userdata);
+}
+
+
+Prompt::PromptModel::PromptType CommunicationBox::getPromptType() const
+{
+    return m_promptType;
+}
diff --git a/popup_process/CommunicationBox.h b/popup_process/CommunicationBox.h
new file mode 100644 (file)
index 0000000..d584b29
--- /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        CommunicationBox.h
+ * @author      Justyna Mejzner (j.kwiatkowsk@samsung.com)
+ * @version     1.0
+ *
+ */
+
+#ifndef _WRT_SRC_DOMAIN_EFL_COMMUNICATION_BOX_H
+#define _WRT_SRC_DOMAIN_EFL_COMMUNICATION_BOX_H
+
+#include <memory>
+#include <iostream>
+#include <dpl/string.h>
+#include <dpl/fast_delegate.h>
+#include <dpl/optional_typedefs.h>
+#include <dpl/popup/popup_controller.h>
+#include <dpl/popup/popup_manager.h>
+#include <dpl/popup/popup_renderer.h>
+#include <dpl/framework_efl.h>
+#include <ace-dao-ro/PromptModel.h>
+
+class CommunicationBox :
+    public DPL::Popup::PopupControllerUser
+{
+  private:
+    void AnswerCallback(const DPL::Popup::AnswerCallbackData &answer);
+
+  public:
+    typedef DPL::FastDelegate<void (int buttonAnswer,
+                                    bool checkState,
+                                    void* userdata)>
+    ResponseDelegate;
+
+    CommunicationBox() :
+        m_promptType(Prompt::PromptModel::PROMPT_ONESHOT),
+        m_callback(NULL),
+        m_userdata(NULL)
+    {
+    }
+
+    void showAsync(const Prompt::PromptModel::PromptType promptType,
+            const std::string& mainLabel,
+            const std::vector<std::string>& buttonLabels,
+            const DPL::OptionalString& checkLabel,
+            ResponseDelegate callback,
+            void* userdata);
+
+    Prompt::PromptModel::PromptType getPromptType() const;
+
+  private:
+
+    Prompt::PromptModel::PromptType m_promptType;
+    ResponseDelegate m_callback;
+    void* m_userdata;
+};
+
+#endif  //_WRT_SRC_DOMAIN_EFL_COMMUNICATION_BOX_H
diff --git a/popup_process/PopupEnum.h b/popup_process/PopupEnum.h
new file mode 100644 (file)
index 0000000..2a4d5b3
--- /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.
+ */
+
+#ifndef WRT_POPUP_ENUM_H
+#define WRT_POPUP_ENUM_H
+
+enum PopupType {
+    ACE_PROMPT = 1,
+    YES_NO_PROMPT
+};
+
+#endif
+
diff --git a/popup_process/PopupInvoker.cpp b/popup_process/PopupInvoker.cpp
new file mode 100644 (file)
index 0000000..e94e66f
--- /dev/null
@@ -0,0 +1,227 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT 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 "PopupInvoker.h"
+#include <sstream>
+#include <unistd.h>
+#include <stdio.h>
+#include <dpl/log/log.h>
+#include <dpl/waitable_handle.h>
+#include <dpl/binary_queue.h>
+#include <dpl/serialization.h>
+#include <unistd.h>
+#include <stdlib.h>
+#include "PopupEnum.h"
+#include "PopupSerializer.h"
+#include "security_daemon_dbus_config.h"
+#include "popup_response_server_api.h"
+
+namespace {
+const char *POPUP_EXEC = "/usr/bin/wrt-popup";
+}
+
+PopupInvoker::PopupInvoker() :
+    m_inputName(tmpnam(NULL)),
+    m_outputName(tmpnam(NULL))
+{
+    Try
+    {
+        m_input.Create(m_inputName);
+        m_output.Create(m_outputName);
+        LogDebug("Pipes created");
+    }
+    Catch (DPL::Exception)
+    {
+        LogError("Cannot create pipes");
+    }
+}
+
+PopupInvoker::~PopupInvoker()
+{
+    Try
+    {
+        m_input.Destroy(m_inputName);
+        m_output.Destroy(m_outputName);
+        LogDebug("Pipes destroyed");
+    }
+    Catch (DPL::Exception)
+    {
+        LogError("Cannot destroy pipes");
+    }
+}
+
+bool PopupInvoker::showSyncPopup(int popupType, const AceUserdata& aceData)
+{
+    Try
+    {
+        DPL::BinaryQueue data;
+        PopupSerializer::appendArg(ACE_PROMPT, data);
+        PopupSerializer::appendArg(popupType, data);
+        PopupSerializer::appendArg(aceData.resource, data);
+        DPL::NamedInputPipe tmp;
+        tmp.Open(m_outputName);
+        m_output.Open(m_outputName);
+        m_input.Open(m_inputName);
+        m_output.Write(data, data.Size());
+
+        executePopup();
+
+        //Result from popup application is available. Read it.
+        DPL::BinaryQueueAutoPtr resultData =
+            m_input.Read(std::numeric_limits<std::size_t>::max());
+        const int result = PopupSerializer::getIntArg(*resultData);
+        const int validity = PopupSerializer::getIntArg(*resultData);
+
+        Assert(resultData->Empty());
+
+        tmp.Close();
+        m_input.Close();
+        m_output.Close();
+
+        Prompt::PromptAnswer answer(result,
+                                    static_cast<Prompt::Validity>(validity));
+
+        LogDebug("Answer: " << result << " Validity: " << validity);
+
+        //ASK SECURITY DAEMON
+        if (!result &&
+            Prompt::Validity::ONCE == answer.getValidity())
+        {
+            LogInfo("User answer is DENY ONCE. Don't call security daemon");
+        }
+        else
+        {
+            LogInfo("calling security daemon");
+            bool securityResponse =
+                    securityDaemonCall(answer.isAccessAllowed(),
+                                       answer.getValidity(),
+                                       aceData);
+
+            if(!securityResponse)
+            {
+                LogError("Security Daemon has responded with false!");
+                return false;
+            }
+            LogInfo("Security Daemon has responded with true");
+        }
+
+        return answer.isAccessAllowed();
+    }
+    Catch(DPL::Exception)
+    {
+        LogError("error occured");
+    }
+    // if error then return deny once
+    return false;
+}
+
+bool PopupInvoker::askYesNo(const std::string& title, const std::string& message)
+{
+    Try
+    {
+        DPL::BinaryQueue data;
+        PopupSerializer::appendArg(YES_NO_PROMPT, data);
+        PopupSerializer::appendArg(title, data);
+        PopupSerializer::appendArg(message, data);
+        DPL::NamedInputPipe tmp;
+        tmp.Open(m_outputName);
+        m_output.Open(m_outputName);
+        m_input.Open(m_inputName);
+        m_output.Write(data, data.Size());
+
+        executePopup();
+
+        //Result from popup application is available. Read it.
+        DPL::BinaryQueueAutoPtr resultData =
+            m_input.Read(std::numeric_limits<std::size_t>::max());
+        const int result = PopupSerializer::getIntArg(*resultData);
+
+        LogDebug("Popup result is: " << result);
+
+        Assert(resultData->Empty());
+
+        tmp.Close();
+        m_input.Close();
+        m_output.Close();
+
+        return (!!result);
+    }
+    Catch(DPL::Exception)
+    {
+        LogError("error occured");
+    }
+
+    return false;
+}
+
+void PopupInvoker::executePopup()
+{
+    pid_t pid = fork();
+    if (pid == -1)
+    {
+        //error occured
+        LogError("Cannot display popup!");
+        Assert(false);
+    }
+    if (pid == 0)
+    {
+        //child process
+        int ret = execl(POPUP_EXEC,
+                        POPUP_EXEC,
+                        m_outputName.c_str(),
+                        m_inputName.c_str(),
+                        NULL);
+        if (ret == -1) {
+            //execl returns -1 on error
+            LogError("Cannot display popup!");
+            Assert(false);
+        }
+    }
+
+    DPL::WaitableHandle handle = m_input.WaitableReadHandle();
+    DPL::WaitForSingleHandle(handle);
+}
+
+bool PopupInvoker::securityDaemonCall(bool allowed,
+                                           Prompt::Validity valid,
+                                           const AceUserdata &data)
+{
+    if(!m_dbusPopupClient)
+        m_dbusPopupClient.Reset(new DPL::DBus::Client(
+                    WrtSecurity::SecurityDaemonConfig::OBJECT_PATH(),
+                    WrtSecurity::SecurityDaemonConfig::SERVICE_NAME(),
+                    WrtSecurity::PopupServerApi::INTERFACE_NAME()));
+
+    bool response = false;
+    Try {
+        m_dbusPopupClient->call(
+                WrtSecurity::PopupServerApi::VALIDATION_METHOD(),
+                       allowed,
+                       static_cast<int>(valid),
+                       data.handle,
+                       data.subject,
+                       data.resource,
+                       data.paramKeys,
+                       data.paramValues,
+                       data.sessionId,
+                       &response);
+    } Catch (DPL::DBus::Client::Exception::DBusClientException) {
+        ReThrowMsg(PopupInvoker::Exception::PopupInvokerException,
+                 "Failed to call security daemon");
+    }
+
+    return response;
+}
\ No newline at end of file
diff --git a/popup_process/PopupInvoker.h b/popup_process/PopupInvoker.h
new file mode 100644 (file)
index 0000000..c36e33f
--- /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.
+ */
+
+#ifndef WRT_POPUP_INVOKER_H
+#define WRT_POPUP_INVOKER_H
+
+#include <ace-dao-ro/PromptModel.h>
+
+#include <string>
+#include <dpl/named_input_pipe.h>
+#include <dpl/named_output_pipe.h>
+#include <dpl/dbus/dbus_client.h>
+#include <dpl/scoped_ptr.h>
+
+#include "popup_ace_data_types.h"
+
+/*
+
+ Example usage:
+
+ bool result = PopupInvoker().askYesNo("title", "message");
+
+ */
+
+class PopupInvoker
+{
+public:
+    class Exception
+    {
+      public:
+        DECLARE_EXCEPTION_TYPE(DPL::Exception, Base)
+        DECLARE_EXCEPTION_TYPE(Base, PopupInvokerException)
+    };
+
+    PopupInvoker();
+    ~PopupInvoker();
+
+    bool showSyncPopup(int popupType, const AceUserdata& aceData);
+
+    bool askYesNo(const std::string &title, const std::string &message);
+
+private:
+
+    void executePopup();
+    bool securityDaemonCall(bool allowed,
+                            Prompt::Validity valid,
+                            const AceUserdata &data);
+
+    DPL::NamedInputPipe m_input;
+    DPL::NamedOutputPipe m_output;
+    const std::string m_inputName;
+    const std::string m_outputName;
+    DPL::ScopedPtr<DPL::DBus::Client> m_dbusPopupClient;
+};
+
+#endif
diff --git a/popup_process/PopupSerializer.cpp b/popup_process/PopupSerializer.cpp
new file mode 100644 (file)
index 0000000..f62367c
--- /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.
+ */
+
+#include "PopupSerializer.h"
+#include <dpl/scoped_array.h>
+
+namespace PopupSerializer {
+
+void appendArg(int arg, DPL::BinaryQueue &buffer)
+{
+    size_t argSize = sizeof(arg);
+    buffer.AppendCopy(&argSize, sizeof(argSize));
+    buffer.AppendCopy(&arg, sizeof(arg));
+}
+
+void appendArg(const std::string &arg, DPL::BinaryQueue &buffer)
+{
+    size_t argSize = arg.size();
+    buffer.AppendCopy(&argSize, sizeof(argSize));
+    buffer.AppendCopy(arg.c_str(), argSize);
+}
+
+int getIntArg(DPL::BinaryQueue &buffer)
+{
+    int result;
+    size_t argSize;
+    buffer.FlattenConsume(&argSize, sizeof(argSize));
+    buffer.FlattenConsume(&result, argSize);
+    //TODO: what if argSize != sizeof(int)
+    //This should not be problem if this is run on the same machine.
+    return result;
+}
+
+std::string getStringArg(DPL::BinaryQueue &buffer)
+{
+    std::string::size_type size;
+    buffer.FlattenConsume(&size, sizeof(size));
+    DPL::ScopedArray<char> str(new char[size]);
+    buffer.FlattenConsume(str.Get(), size);
+    return std::string(str.Get(), str.Get() + size);
+}
+
+}
\ No newline at end of file
diff --git a/popup_process/PopupSerializer.h b/popup_process/PopupSerializer.h
new file mode 100644 (file)
index 0000000..1e8102c
--- /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 WRT_POPUP_SERIALIZER_H
+#define WRT_POPUP_SERIALIZER_H
+
+#include <string>
+#include <dpl/binary_queue.h>
+
+namespace PopupSerializer {
+
+void appendArg(int arg, DPL::BinaryQueue &buffer);
+void appendArg(const std::string &arg, DPL::BinaryQueue &buffer);
+
+int getIntArg(DPL::BinaryQueue &buffer);
+std::string getStringArg(DPL::BinaryQueue &buffer);
+
+}
+
+#endif
\ No newline at end of file
diff --git a/popup_process/YesNoPopup.cpp b/popup_process/YesNoPopup.cpp
new file mode 100644 (file)
index 0000000..cb67f24
--- /dev/null
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @file        YesNoPopup.cpp
+ * @author      Andrzej Surdej (a.surdej@samsung.com)
+ * @version     1.0
+ * @brief       Popup that contains 'Yes' and 'No' buttons. Inplementation
+ */
+
+#include "YesNoPopup.h"
+#include <memory>
+#include <string.h>
+#include <dpl/popup/popup_manager.h>
+#include "PopupSerializer.h"
+
+namespace {
+const char YES_LABEL[] = "Yes";
+const char NO_LABEL[] = "No";
+const int POPUP_YES_VALUE = 1;
+const int POPUP_NO_VALUE = 2;
+} //anonymous
+
+namespace PopupProcess {
+using namespace DPL::Popup;
+
+void YesNoPopup::show(DPL::BinaryQueueAutoPtr data, WrtPopup* parent)
+{
+    LogDebug("Entered");
+    std::string title = PopupSerializer::getStringArg(*data);
+    std::string message = PopupSerializer::getStringArg(*data);
+    Assert(data->Empty());
+    LogDebug("title: " << title << " message: " << message);
+
+    m_parent = parent;
+
+    CtrlPopupPtr popup = PopupControllerSingleton::Instance().CreatePopup();
+
+    popup->SetTitle(title);
+    popup->Append(new PopupObject::Label(message));
+
+    popup->Append(new PopupObject::Button(YES_LABEL, POPUP_YES_VALUE));
+    popup->Append(new PopupObject::Button(NO_LABEL, POPUP_NO_VALUE));
+
+    ListenForAnswer(popup);
+
+     //nested loop is not used here
+    ShowPopupEventShort event(popup,
+                              MakeAnswerCallback(
+                                     this,
+                                     &YesNoPopup::responseCallback));
+
+    CONTROLLER_POST_EVENT(PopupController,
+                          event);
+
+    LogDebug("Exited");
+    return;
+}
+
+void YesNoPopup::responseCallback(const DPL::Popup::AnswerCallbackData &answer)
+{
+    bool result = (POPUP_YES_VALUE == answer.buttonAnswer);
+    DPL::BinaryQueue retValue;
+    PopupSerializer::appendArg(result, retValue);
+    m_parent->response(retValue);
+}
+
+} // PopupProcess
+
diff --git a/popup_process/YesNoPopup.h b/popup_process/YesNoPopup.h
new file mode 100644 (file)
index 0000000..ccfbf84
--- /dev/null
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @file        YesNoPopup.h
+ * @author      Andrzej Surdej (a.surdej@samsung.com)
+ * @version     1.0
+ * @brief       Popup that contains 'Yes' and 'No' buttons
+ */
+
+#ifndef WRT_YES_NO_POPUP_H
+#define WRT_YES_NO_POPUP_H
+
+#include "wrt-popup.h"
+
+namespace PopupProcess {
+
+class YesNoPopup : public IPopup
+{
+public:
+    virtual void show(DPL::BinaryQueueAutoPtr data, WrtPopup* parent);
+
+private:
+
+    void responseCallback(const DPL::Popup::AnswerCallbackData &answer);
+    WrtPopup* m_parent;
+};
+
+} // PopupProcess
+
+#endif /* WRT_YES_NO_POPUP_H */
+
diff --git a/popup_process/wrt-popup.cpp b/popup_process/wrt-popup.cpp
new file mode 100644 (file)
index 0000000..7257315
--- /dev/null
@@ -0,0 +1,276 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT 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 "wrt-popup.h"
+#include <limits>
+#include <memory>
+
+#include <aul.h>
+#include <dpl/log/log.h>
+#include <dpl/exception.h>
+#include <dpl/assert.h>
+
+#include "PopupEnum.h"
+#include "PopupSerializer.h"
+#include "YesNoPopup.h"
+
+#include <CommunicationBox.h>
+#include <ace-dao-ro/PromptModel.h>
+#include <ace/PolicyEffect.h>
+
+namespace {
+struct PopupsUserdata
+{
+    PopupsUserdata(CommunicationBox* pCommunicationBox) :
+        communicationBox(pCommunicationBox)
+    {
+    }
+    std::unique_ptr<CommunicationBox> communicationBox;
+    Prompt::PromptLabelsPtr promptLabels;
+};
+
+Prompt::PromptLabels* getPromptLabelsFromPolicyEffect(
+        const PolicyEffect promptEffect, const std::string& resource)
+{
+    switch(promptEffect) {
+    case PolicyEffect::PROMPT_ONESHOT: {
+        return Prompt::PromptModel::getOneShotModel(resource);
+    }
+    case PolicyEffect::PROMPT_SESSION: {
+        return Prompt::PromptModel::getSessionModel(resource);
+    }
+    case PolicyEffect::PROMPT_BLANKET: {
+        return Prompt::PromptModel::getBlanketModel(resource);
+    }
+    default:
+        LogError("Policy Effect not an prompt");
+        Assert(0);
+        return NULL;
+    }
+}
+
+} // namespace anonymous
+
+namespace PopupProcess {
+
+bool WrtPopup::openPipes()
+{
+    Try
+    {
+        if (m_argc != 3) {
+            LogError("Wrong arguments!");
+            return false;
+        }
+        m_input.Open(m_argv[1]);
+        //open output pipe
+        m_output.Open(m_argv[2]);
+
+        DPL::WaitableHandleWatchSupport::InheritedContext()->
+            AddWaitableHandleWatch(this,
+                                   m_input.WaitableReadHandle(),
+                                   DPL::WaitMode::Read);
+        m_pipesOpened = true;
+        return true;
+    }
+    Catch(DPL::Exception)
+    {
+        LogError("cannot open pipes");
+    }
+    return false;
+}
+
+void WrtPopup::closePipes()
+{
+    Try
+    {
+        if (m_pipesOpened)
+        {
+            DPL::WaitableHandleWatchSupport::InheritedContext()->
+                RemoveWaitableHandleWatch(this,
+                                          m_input.WaitableReadHandle(),
+                                          DPL::WaitMode::Read);
+            m_input.Close();
+            m_output.Close();
+            m_pipesOpened = false;
+        }
+    }
+    Catch(DPL::Exception)
+    {
+        LogError("cannot close pipes");
+    }
+}
+
+void WrtPopup::OnEventReceived(const QuitEvent &/* event */)
+{
+    LogDebug("Quiting");
+    closePipes();
+    Quit();
+}
+
+void WrtPopup::OnWaitableHandleEvent(DPL::WaitableHandle waitableHandle,
+                                     DPL::WaitMode::Type /*mode*/)
+{
+    if (waitableHandle == m_input.WaitableReadHandle())
+    {
+        readInputData();
+    }
+}
+
+void WrtPopup::readInputData()
+{
+    DPL::BinaryQueueAutoPtr data =
+        m_input.Read(std::numeric_limits<std::size_t>::max());
+    int popupType = PopupSerializer::getIntArg(*data);
+    LogDebug("popup type " << popupType);
+    switch(popupType) {
+    case ACE_PROMPT:
+        // TODO: fix this to use IPopup interface
+        showAcePrompt(data);
+        break;
+    case YES_NO_PROMPT: {
+        m_popup.reset(new YesNoPopup());
+        m_popup->show(data, this);
+        break; }
+    default:
+        Assert(false);
+    }
+}
+
+void WrtPopup::showAcePrompt(DPL::BinaryQueueAutoPtr data)
+{
+    int promptType = PopupSerializer::getIntArg(*data);
+    std::string resource = PopupSerializer::getStringArg(*data);
+    Assert(data->Empty());
+    LogDebug("PopupType: " << promptType << " resource: " << resource);
+
+    PopupsUserdata* popupsUserdata =
+            new PopupsUserdata(new CommunicationBox());
+
+    using namespace Prompt;
+    popupsUserdata->promptLabels.reset(
+            getPromptLabelsFromPolicyEffect(static_cast<PolicyEffect>(promptType),
+                                            resource));
+    popupsUserdata->communicationBox->showAsync(
+            static_cast<PromptModel::PromptType>(
+                    popupsUserdata->promptLabels->getPromptType()),
+            popupsUserdata->promptLabels->getMainLabel(),
+            popupsUserdata->promptLabels->getButtonLabels(),
+            popupsUserdata->promptLabels->getCheckLabel(),
+            CommunicationBox::ResponseDelegate(
+                    this,
+                    &WrtPopup::communicationBoxResponse),
+            popupsUserdata);
+}
+
+void WrtPopup::communicationBoxResponse(int buttonAnswer,
+                                        bool checkState,
+                                        void* userdata)
+{
+    LogDebug("Communication box response");
+    Assert(userdata);
+    std::unique_ptr<PopupsUserdata> popupsUserdata(
+            static_cast<PopupsUserdata*>(userdata));
+    //following code can be moved to different place, but this is only a stub
+
+    Prompt::PromptAnswer promptAnswer(
+            popupsUserdata->promptLabels->getPromptType(),
+            buttonAnswer, checkState);
+
+    const bool allowed = promptAnswer.isAccessAllowed();
+    const Prompt::Validity validity = promptAnswer.getValidity();
+
+    DPL::BinaryQueue result;
+    PopupSerializer::appendArg(allowed, result);
+    PopupSerializer::appendArg(static_cast<int>(validity), result);
+    m_output.Write(result, result.Size());
+    PostEvent(QuitEvent());
+}
+
+void WrtPopup::response(DPL::BinaryQueue result)
+{
+    m_output.Write(result, result.Size());
+    PostEvent(QuitEvent());
+}
+
+void WrtPopup::OnStop()
+{
+    LogInfo("On Stop");
+}
+
+void WrtPopup::OnCreate()
+{
+    if (!openPipes())
+    {
+        PostEvent(QuitEvent());
+    }
+    LogInfo("On Create");
+}
+
+void WrtPopup::OnResume()
+{
+    LogDebug("OnResume");
+}
+
+void WrtPopup::OnPause()
+{
+    LogDebug("OnPause");
+}
+
+void WrtPopup::OnReset(bundle */*b*/)
+{
+    LogDebug("OnReset");
+}
+
+void WrtPopup::OnTerminate()
+{
+    LogDebug("Wrt Shutdown now");
+}
+
+WrtPopup::WrtPopup(int argc, char **argv) :
+    Application(argc, argv, "wrt-popup", false),
+    m_pipesOpened(false),
+    m_popup(NULL)
+{
+    Touch();
+    DPL::Popup::PopupControllerSingleton::Instance().Touch();
+    DPL::Popup::PopupManagerSingleton::Instance().Initialize(
+        DPL::Popup::PopupRendererPtr(new DPL::Popup::PopupRenderer));
+    LogDebug("App Created");
+}
+
+WrtPopup::~WrtPopup()
+{
+    DPL::Popup::PopupManagerSingleton::Instance().Deinitialize();
+    LogDebug("App Finished");
+}
+
+} // PopupProcess
+
+int main(int argc, char *argv[])
+{
+    // Output on stdout will be flushed after every newline character,
+    // even if it is redirected to a pipe. This is useful for running
+    // from a script and parsing output.
+    // (Standard behavior of stdlib is to use full buffering when
+    // redirected to a pipe, which means even after an end of line
+    // the output may not be flushed).
+    setlinebuf(stdout);
+
+    DPL::Log::LogSystemSingleton::Instance().SetTag("WRT-POPUP");
+    PopupProcess::WrtPopup app(argc, argv);
+    int ret = app.Exec();
+    LogDebug("App returned: " << ret);
+    return ret;
+}
diff --git a/popup_process/wrt-popup.h b/popup_process/wrt-popup.h
new file mode 100644 (file)
index 0000000..a254d8e
--- /dev/null
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT 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_POPUP_H
+#define WRT_POPUP_H
+
+#include <memory>
+#include <dpl/application.h>
+#include <dpl/generic_event.h>
+#include <dpl/event/controller.h>
+#include <dpl/type_list.h>
+#include <dpl/named_input_pipe.h>
+#include <dpl/named_output_pipe.h>
+#include <dpl/waitable_handle_watch_support.h>
+#include <dpl/binary_queue.h>
+#include <dpl/popup/popup_controller.h>
+
+namespace PopupProcess {
+
+DECLARE_GENERIC_EVENT_0(QuitEvent)
+class WrtPopup;
+
+class IPopup : public DPL::Popup::PopupControllerUser
+{
+public:
+    virtual void show(DPL::BinaryQueueAutoPtr data, WrtPopup* parent) = 0;
+};
+
+typedef std::unique_ptr<IPopup> IPopupPtr;
+
+
+class WrtPopup :
+    public DPL::WaitableHandleWatchSupport::WaitableHandleListener,
+    public DPL::Application,
+    private DPL::Event::Controller<DPL::TypeListDecl<QuitEvent>::Type>
+{
+public:
+    WrtPopup(int argc, char **argv);
+    virtual ~WrtPopup();
+
+    void response(DPL::BinaryQueue result);
+
+protected:
+    //DPL::Application functions
+    virtual void OnStop();
+    virtual void OnCreate();
+    virtual void OnResume();
+    virtual void OnPause();
+    virtual void OnReset(bundle *b);
+    virtual void OnTerminate();
+    virtual void OnEventReceived(const QuitEvent &event);
+    virtual void OnWaitableHandleEvent(DPL::WaitableHandle waitableHandle,
+                                       DPL::WaitMode::Type mode);
+private:
+
+    void showAcePrompt(DPL::BinaryQueueAutoPtr data);
+    void communicationBoxResponse(int buttonAnswer,
+                                  bool checkState,
+                                  void* userdata);
+    bool m_pipesOpened;
+    IPopupPtr m_popup;
+
+    bool openPipes();
+    void closePipes();
+    void readInputData();
+
+    DPL::NamedInputPipe m_input;
+    DPL::NamedOutputPipe m_output;
+};
+
+} // PopupProcess
+
+#endif // WRT_POPUP_H
diff --git a/security-server.pc.in b/security-server.pc.in
deleted file mode 100644 (file)
index fab62e9..0000000
+++ /dev/null
@@ -1,11 +0,0 @@
-prefix=@PREFIX@
-exec_prefix=@EXEC_PREFIX@
-libdir=@LIBDIR@
-includedir=@INCLUDEDIR@
-
-Name: security-server 
-Description: Security Server Package
-Version: @VERSION@
-#Requires: openssl
-Libs: -L${libdir} -lsecurity-server-client
-Cflags: -I${includedir}/security-server 
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
new file mode 100644 (file)
index 0000000..ef30ec9
--- /dev/null
@@ -0,0 +1,156 @@
+# Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+#
+#    Licensed under the Apache License, Version 2.0 (the "License");
+#    you may not use this file except in compliance with the License.
+#    You may obtain a copy of the License at
+#
+#        http://www.apache.org/licenses/LICENSE-2.0
+#
+#    Unless required by applicable law or agreed to in writing, software
+#    distributed under the License is distributed on an "AS IS" BASIS,
+#    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+#    See the License for the specific language governing permissions and
+#    limitations under the License.
+#
+#
+# @file     CMakeLists.txt
+# @author   Bartlomiej Grzelewski (b.grzelewski@samsung.com)
+#
+
+SET(DAEMON_BASIC_DEP
+    dpl-efl
+    dpl-wrt-dao-rw
+    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
+    ${DAEMON_SOURCES_PATH}/daemon/dbus/security_dbus_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/ocsp_service.cpp
+    #ace
+    ${DAEMON_SOURCES_PATH}/services/ace/dbus/ace_server_dbus_interface.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
+  )
+
+SET_SOURCE_FILES_PROPERTIES(${DAEMON_SOURCES} PROPERTIES COMPILE_FLAGS "-std=c++0x")
+SET(DAEMON_SOURCES
+    ${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(
+    ${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)
+#daemon
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/daemon)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/daemon/dbus)
+#ace
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ace/dbus)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ace/logic)
+#ocsp
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ocsp/dbus)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/ocsp/logic)
+#popup
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/popup/dbus)
+INCLUDE_DIRECTORIES(${PROJECT_SOURCE_DIR}/src/services/popup/logic)
+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/dbus/api/ace_server_api.h
+    ${PROJECT_SOURCE_DIR}/src/services/ocsp/dbus/api/ocsp_server_api.h
+    ${PROJECT_SOURCE_DIR}/src/services/popup/dbus/api/popup_response_server_api.h
+    ${PROJECT_SOURCE_DIR}/src/services/popup/dbus/api/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..0d218c6
--- /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        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();
+}
+
+DAEMON_REGISTER_SERVICE_MODULE(SecurityDBusService)
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..6277ba5
--- /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        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 <dpl/wrt-dao-ro/WrtDatabase.h>
+#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();
+    WrtDB::WrtDatabase::attachToThreadRW();
+}
+
+void deinitialize(void)
+{
+    LogDebug("Ace/Wrt database services deinitializing...");
+    AceDB::AceDAO::detachFromThread();
+    WrtDB::WrtDatabase::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..85244c6
--- /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        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/main.cpp b/src/main.cpp
new file mode 100644 (file)
index 0000000..f3b80b6
--- /dev/null
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/*
+ * @file        main.cpp
+ * @author      Lukasz Wrzosek (l.wrzosek@samsung.com)
+ * @version     1.0
+ * @brief       This is main routing for Security Daemon
+ */
+
+#include <string>
+
+#include <dpl/application.h>
+#include <dpl/log/log.h>
+#include <dpl/single_instance.h>
+#include <dpl/wrt-dao-ro/global_config.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;
+    if (!instance.TryLock(DAEMON_INSTANCE_UUID)) {
+        LogError("Security Daemon is already running");
+        return -1;
+    }
+
+    auto& daemon = SecurityDaemonSingleton::Instance();
+
+    daemon.initialize(argc, argv);
+
+    //Run daemon
+    auto retVal = daemon.execute();
+
+    daemon.shutdown();
+    instance.Release();
+
+    pthread_exit(NULL);
+    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)
  *
  */
 
-#include <poll.h>
+#include <sys/poll.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <sys/socket.h>
 #include <sys/types.h>
-#include <sys/xattr.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"
@@ -225,7 +226,7 @@ int create_new_socket(int *sockfd)
                goto error;
        }
 
-       if((fsetxattr(localsockfd, "security.SMACK64IPOUT", "@", 2, 0)) < 0)
+       if(smack_fsetlabel(localsockfd, "@", SMACK_LABEL_IPOUT) != 0)
        {
                SEC_SVR_DBG("%s", "SMACK labeling failed");
                if(errno != EOPNOTSUPP)
@@ -235,7 +236,7 @@ int create_new_socket(int *sockfd)
                        goto error;
                }
        }
-       if((fsetxattr(localsockfd, "security.SMACK64IPIN", "*", 2, 0)) < 0)
+       if(smack_fsetlabel(localsockfd, "*", SMACK_LABEL_IPIN) != 0)
        {       SEC_SVR_DBG("%s", "SMACK labeling failed");
                if(errno != EOPNOTSUPP)
                {
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
+
+*/
+/**
+*@}
+*/
similarity index 100%
rename from mw-list
rename to src/security-srv/mw-list
old mode 100755 (executable)
new mode 100644 (file)
similarity index 100%
rename from security-serverd
rename to src/security-srv/security-serverd
similarity index 98%
rename from src/server/security-server-main.c
rename to src/security-srv/server/security-server-main.c
index 2e87f2f..0577bdf 100644 (file)
@@ -1074,16 +1074,14 @@ error:
        pthread_exit(NULL);
 }
 
-
-
-int main(int argc, char* argv[])
+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");
+       SEC_SVR_DBG("%s", "Starting Security Server main thread");
 
        /* security server must be executed by root */
        if(getuid() != 0)
@@ -1169,6 +1167,28 @@ int main(int argc, char* argv[])
 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/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..4e617d8
--- /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_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_api.h b/src/services/ace/dbus/api/ace_server_api.h
new file mode 100644 (file)
index 0000000..daf6f7c
--- /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        ace_server_api.h
+ * @author      Tomasz Swierczek (t.swierczek@samsung.com)
+ * @version     1.0
+ * @brief       This file contains definitions ACE server interface & 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";
+    }
+
+    // RPC test function
+    // IN std::string
+    // OUT std::string
+    inline const std::string ECHO_METHOD()
+    {
+        return "echo";
+    }
+
+    // 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/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..ee74c3e
--- /dev/null
@@ -0,0 +1,882 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT 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 <dpl/wrt-dao-ro/wrt_db_types.h>
+#include <dpl/wrt-dao-rw/widget_dao.h>
+#include <dpl/wrt-dao-rw/feature_dao.h>
+#include <ace/WRT_INTERFACE.h>
+#include <map>
+#include <dpl/log/log.h>
+#include <attribute_facade.h>
+#include <ace/Request.h>
+#include <simple_roaming_agent.h>
+
+using namespace WrtDB;
+
+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;
+    WidgetDAOReadOnly dao(widgetHandle);
+
+    std::string value = dao.getShareHref();
+
+    if (!value.empty()) {
+        response.push_back(value);
+    }
+
+    return response;
+}
+
+AttributeHandlerResponse AttributeVersionHandler(const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle &widgetHandle)
+{
+    AttributeHandlerResponse response;
+    WidgetDAOReadOnly dao(widgetHandle);
+
+    DPL::Optional<DPL::String> value = dao.getVersion();
+
+    if (!!value) {
+        response.push_back(DPL::ToUTF8String(*value));
+    }
+
+    return response;
+}
+
+AttributeHandlerResponse AttributeDistributorKeyCnHandler(
+        const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle &widgetHandle)
+{
+    AttributeHandlerResponse response;
+    WidgetDAOReadOnly dao(widgetHandle);
+
+    response = dao.getKeyCommonNameList(WidgetCertificateData::DISTRIBUTOR,
+                                        WidgetCertificateData::ENDENTITY);
+
+    return response;
+}
+
+AttributeHandlerResponse AttributeDistributorKeyFingerprintHandler(
+        const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle &widgetHandle)
+{
+    AttributeHandlerResponse response;
+    WidgetDAOReadOnly dao(widgetHandle);
+
+    response = dao.getKeyFingerprints(WidgetCertificateData::DISTRIBUTOR,
+                                      WidgetCertificateData::ENDENTITY);
+
+    return response;
+}
+
+AttributeHandlerResponse AttributeDistributorKeyRootCnHandler(
+        const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle &widgetHandle)
+{
+    AttributeHandlerResponse response;
+    WidgetDAOReadOnly dao(widgetHandle);
+
+    response = dao.getKeyCommonNameList(WidgetCertificateData::DISTRIBUTOR,
+                                        WidgetCertificateData::ROOT);
+
+    return response;
+}
+
+AttributeHandlerResponse AttributeDistributorKeyRootFingerprintHandler(
+        const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle &widgetHandle)
+{
+    AttributeHandlerResponse response;
+    WidgetDAOReadOnly dao(widgetHandle);
+
+    response = dao.getKeyFingerprints(WidgetCertificateData::DISTRIBUTOR,
+                                      WidgetCertificateData::ROOT);
+
+    return response;
+}
+
+AttributeHandlerResponse AttributeAuthorKeyCnHandler(
+        const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle &widgetHandle)
+{
+    AttributeHandlerResponse response;
+    WidgetDAOReadOnly dao(widgetHandle);
+
+    response = dao.getKeyCommonNameList(WidgetCertificateData::AUTHOR,
+                                        WidgetCertificateData::ENDENTITY);
+
+    return response;
+}
+
+AttributeHandlerResponse AttributeAuthorKeyFingerprintHandler(
+        const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle &widgetHandle)
+{
+    AttributeHandlerResponse response;
+    WidgetDAOReadOnly dao(widgetHandle);
+
+    response = dao.getKeyFingerprints(WidgetCertificateData::AUTHOR,
+                                      WidgetCertificateData::ENDENTITY);
+
+    return response;
+}
+
+AttributeHandlerResponse AttributeAuthorKeyRootCnHandler(
+        const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle &widgetHandle)
+{
+    AttributeHandlerResponse response;
+    WidgetDAOReadOnly dao(widgetHandle);
+
+    response = dao.getKeyCommonNameList(WidgetCertificateData::AUTHOR,
+                                        WidgetCertificateData::ROOT);
+
+    return response;
+}
+
+AttributeHandlerResponse AttributeAuthorKeyRootFingerprintHandler(
+        const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle &widgetHandle)
+{
+    AttributeHandlerResponse response;
+    WidgetDAOReadOnly dao(widgetHandle);
+
+    response = dao.getKeyFingerprints(WidgetCertificateData::AUTHOR,
+                                      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;
+    WidgetDAOReadOnly dao(widgetHandle);
+    WidgetGUID wGUID = dao.getGUID();
+
+    if (!!wGUID) {
+        response.push_back(DPL::ToUTF8String(*wGUID));
+    }
+    return response;
+}
+
+//AttributeHandlerResponse AttributeNameHandler(const WidgetExecutionPhase & /*phase*/,
+//        const WidgetHandle &widgetHandle)
+//{
+//    AttributeHandlerResponse response;
+//
+//    WidgetLocalizedInfo info =
+//        W3CFileLocalization::getLocalizedInfo(widgetHandle);
+//
+//    DPL::Optional<DPL::String> val = info.name;
+//    std::string value = !!val ? DPL::ToUTF8String(*val) : "";
+//
+//    response.push_back(value);
+//    return response;
+//}
+//
+//AttributeHandlerResponse AttributeWidgetAttrNameHandler(
+//        const WidgetExecutionPhase & /*phase*/,
+//        const WidgetHandle &widgetHandle)
+//{
+//    AttributeHandlerResponse response;
+//
+//    WidgetLocalizedInfo info =
+//        W3CFileLocalization::getLocalizedInfo(widgetHandle);
+//
+//    DPL::Optional<DPL::String> value = info.name;
+//
+//    if (!!value) {
+//        response.push_back(DPL::ToUTF8String(*value));
+//    }
+//
+//    return response;
+//}
+
+AttributeHandlerResponse AttributeAuthorNameHandler(
+        const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle &widgetHandle)
+{
+    AttributeHandlerResponse response;
+    WidgetDAOReadOnly dao(widgetHandle);
+
+    DPL::Optional<DPL::String> value = dao.getAuthorName();
+
+    if (!!value) {
+        response.push_back(DPL::ToUTF8String(*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);
+    }
+};
+
+class lambdaWidgetPrefixEquality :
+    public std::binary_function<WidgetFeature, std::string, bool>
+{
+  public:
+    bool operator()(const WidgetFeature& wFeature,
+            const std::string& prefix) const
+    {
+        return wFeature.name.find(DPL::FromUTF8String(prefix)) !=
+               DPL::String::npos;
+    }
+};
+
+class lambdaWidgetNameEquality :
+    public std::binary_function<WidgetFeature, std::string, bool>
+{
+  public:
+    bool operator()(const WidgetFeature& wFeature,
+            const std::string& prefix) const
+    {
+        return wFeature.name == DPL::FromUTF8String(prefix);
+    }
+};
+
+FeatureHandleList getFeatureHandleList(const WidgetHandle& widgetHandle,
+        const std::string& resourceId)
+{
+    FeatureHandleList featureHandleList;
+    WidgetDAOReadOnly widgetDAO(widgetHandle);
+    WidgetFeatureSet wFeatureSet = widgetDAO.getFeaturesList();
+    WidgetFeatureSet::iterator foundFeatures =
+        std::find_if(wFeatureSet.begin(),
+                     wFeatureSet.end(),
+                     std::bind2nd(lambdaWidgetPrefixEquality(), resourceId));
+
+    if (foundFeatures != wFeatureSet.end()) {
+        FeatureDAOReadOnly featureDAO(resourceId);
+        featureHandleList.push_back(featureDAO.GetFeatureHandle());
+    }
+    return featureHandleList;
+}
+
+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;
+
+    // We should return list of device-caps required by resourceId.
+    //    AttributeHandlerResponse response;
+    //
+    //    FeatureHandleList fHandleList =
+    //        getFeatureHandleList(widgetHandle, resourceId);
+    //    if( !fHandleList.empty() )
+    //    {
+    //        FeatureDAO feature( resourceId );
+    //        std::set<std::string> deviceCapLast =
+    //                feature.GetDeviceCapabilities();
+    //        std::for_each(
+    //                deviceCapList.begin(),
+    //                deviceCapList.end(),
+    //                lambdaCollectionPusher<DeviceCapList::value_type>(
+    //                        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;
+    // Wrt shouldn't ask about resource which is not listed in
+    // (widget) config.xml file
+    //
+    //    AttributeHandlerResponse response;
+    //    WidgetDAOReadOnly widgetDAO(widgetHandle);
+    //        WidgetFeatureSet wFeatureSet = widgetDAO.GetFeaturesList();
+    //       std::string featureName = resourceId;
+    //        WidgetFeatureSet::iterator foundFeatures =
+    //            std::find_if(wFeatureSet.begin(),
+    //                         wFeatureSet.end(),
+    //                         std::bind2nd(lambdaWidgetPrefixEquality(),
+    //                                      featureName));
+    //
+    //        while( foundFeatures != wFeatureSet.end() )
+    //        {
+    //            response.push_back( foundFeatures->name );
+    //            LogDebug("Found feature: " << foundFeatures->name );
+    //            foundFeatures++;
+    //        }
+    //
+    //        return response;
+}
+
+typedef std::string (FeatureDAOReadOnly::*FNMETHOD)() const;
+
+AttributeHandlerResponse GetFeatureAttributeGroup(const WidgetExecutionPhase & /*phase*/,
+        const WidgetHandle &widgetHandle,
+        const std::string& resourceId,
+        FNMETHOD function)
+{
+    AttributeHandlerResponse response;
+    FeatureHandleList fHandleList =
+        getFeatureHandleList(widgetHandle, resourceId);
+    if (!fHandleList.empty()) {
+        FeatureDAOReadOnly featureDAO(fHandleList.front());
+        std::string attribute = (featureDAO.*function)();
+        response.push_back(attribute);
+    }
+    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..b1a1ff4
--- /dev/null
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT 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>
+
+IMPLEMENT_SINGLETON(SecurityController)
+
+struct SecurityController::Impl
+{
+    SecurityLogic logic;
+};
+
+SecurityController::SecurityController()
+{
+    m_impl.Reset(new Impl);
+}
+
+SecurityController::~SecurityController()
+{
+}
+
+void SecurityController::OnEventReceived(
+    const SecurityControllerEvents::InitializeSyncEvent & /* event */)
+{
+    m_impl->logic.initialize();
+}
+
+void SecurityController::OnEventReceived(
+        const SecurityControllerEvents::UpdatePolicySyncEvent& /* event */)
+{
+    m_impl->logic.updatePolicy();
+}
+
+void SecurityController::OnEventReceived(
+    const SecurityControllerEvents::TerminateSyncEvent & /*event*/)
+{
+    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..e63ed9e
--- /dev/null
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * 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>
+
+#include <dpl/wrt-dao-ro/wrt_db_types.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..f80ff95
--- /dev/null
@@ -0,0 +1,389 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * This class simply redirects the access requests to access control engine.
+ * The aim is to hide access control engine specific details from WRT modules.
+ * It also implements WRT_INTERFACE.h interfaces, so that ACE could access
+ * WRT specific and other information during the decision making.
+ *
+ * @file    security_controller.h
+ # @author  Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
+ * @author  Ming Jin(ming79.jin@samsung.com)
+ * @author  Piotr Kozbial (p.kozbial@samsung.com)
+ * @version 1.0
+ * @brief   Header file for security logic
+ */
+
+#include <security_logic.h>
+#include <attribute_facade.h>
+#ifdef WRT_SMACK_ENABLED
+#include <privilege-control.h>
+#endif
+#include <ace-dao-rw/AceDAO.h>
+#include <ace-dao-ro/AceDAOConversions.h>
+#include <ace/PolicyInformationPoint.h>
+#include <ace/PromptDecision.h>
+#include <dpl/log/log.h>
+
+#include <dpl/wrt-dao-ro/widget_dao_read_only.h>
+#include <dpl/wrt-dao-ro/WrtDatabase.h>
+
+namespace {
+
+Request::ApplicationType getAppType(const Request *request) {
+    WrtDB::WidgetDAOReadOnly widgetDao(request->getWidgetHandle());
+    WrtDB::AppType appType = widgetDao.getWidgetType().appType;
+    switch (appType) {
+    case WrtDB::AppType::APP_TYPE_TIZENWEBAPP:
+        LogDebug("==== Found Tizen application. ====");
+        return Request::APP_TYPE_TIZEN;
+    case WrtDB::AppType::APP_TYPE_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() {
+    WrtDB::WrtDatabase::attachToThreadRO();
+    m_policyEnforcementPoint.initialize(new WebRuntimeImpl(),
+                                        new ResourceInformationImpl(),
+                                        new OperationSystemImpl());
+}
+
+void SecurityLogic::terminate() {
+    m_policyEnforcementPoint.terminate();
+    WrtDB::WrtDatabase::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 (WrtDB::WidgetDAOReadOnly::Exception::WidgetNotExist) {
+        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 (WrtDB::WidgetDAOReadOnly::Exception::WidgetNotExist) {
+        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 (WrtDB::WidgetDAOReadOnly::Exception::WidgetNotExist) {
+        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::AceDAO::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::AceDAO::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::AceDAO::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/ocsp/dbus/api/ocsp_server_api.h b/src/services/ocsp/dbus/api/ocsp_server_api.h
new file mode 100644 (file)
index 0000000..32138d1
--- /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        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<string>
+
+namespace WrtSecurity{
+namespace OcspServerApi{
+
+// DBus interface name
+inline const std::string INTERFACE_NAME()
+{
+    return "org.tizen.OcspCheck";
+}
+
+// RPC test function
+// IN std::string
+// OUT std::string
+inline const std::string ECHO_METHOD()
+{
+    return "echo";
+}
+
+// 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/dbus/ocsp_server_dbus_interface.cpp b/src/services/ocsp/dbus/ocsp_server_dbus_interface.cpp
new file mode 100644 (file)
index 0000000..40c7f85
--- /dev/null
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES 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"
+#include <dpl/foreach.h>
+#include <dpl/wrt-dao-ro/global_config.h>
+#include <dpl/wrt-dao-ro/widget_dao_read_only.h>
+#include <ace-dao-ro/common_dao_types.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);
+        WrtDB::DbWidgetHandle handle = static_cast<WrtDB::DbWidgetHandle>(
+                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..8151874
--- /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_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_service.cpp b/src/services/ocsp/ocsp_service.cpp
new file mode 100644 (file)
index 0000000..7747077
--- /dev/null
@@ -0,0 +1,64 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES 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 <string>
+#include <list>
+#include <memory>
+
+#include <dpl/log/log.h>
+#include <dpl/single_instance.h>
+#include <dpl/event/controller.h>
+#include <dpl/thread.h>
+#include <dpl/wrt-dao-ro/WrtDatabase.h>
+#include <dpl/wrt-dao-ro/global_config.h>
+#include "security_daemon.h"
+#include "security_dbus_service.h"
+#include "ocsp_server_dbus_interface.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/popup/dbus/api/popup_ace_data_types.h b/src/services/popup/dbus/api/popup_ace_data_types.h
new file mode 100644 (file)
index 0000000..4d27877
--- /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    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>
+#include <dpl/wrt-dao-ro/wrt_db_types.h>
+
+// 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) {}
+
+    WidgetHandle 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/dbus/api/popup_response_server_api.h b/src/services/popup/dbus/api/popup_response_server_api.h
new file mode 100644 (file)
index 0000000..92f0d7d
--- /dev/null
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+/**
+ * @file    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/dbus/popup_response_dbus_interface.cpp b/src/services/popup/dbus/popup_response_dbus_interface.cpp
new file mode 100644 (file)
index 0000000..96bee49
--- /dev/null
@@ -0,0 +1,109 @@
+/*
+ * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES 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 <api/popup_response_server_api.h>
+#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 "api/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..54a7ce8
--- /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 "api/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/testcases/debug-util.c b/testcases/debug-util.c
deleted file mode 100644 (file)
index 9925519..0000000
+++ /dev/null
@@ -1,45 +0,0 @@
-/*
- * security server
- *
- * Copyright (c) 2000 - 2010 Samsung Electronics Co., Ltd.
- * Contact: Bumjin Im <bj.im@samsung.com>
- * 
- */
-
- #include <stdio.h>
-#include <errno.h>
-#include <stdlib.h>
-#include "security-server.h"
-#define DEVELOPER_UID 5100
-
-int main(int argc, char *argv[])
-{
-       int uid, ret, i;
-
-       uid = getuid();
-       if(uid == DEVELOPER_UID)
-       {
-               printf("Sending request to security server...\n");
-               ret = security_server_launch_debug_tool(argc -1, (const char **) argv + 1);
-               if(ret != SECURITY_SERVER_API_SUCCESS)
-               {
-                       printf("Failed to launch tool[%d]\n", ret);
-                       exit(-1);
-               }
-               exit(0);
-       }
-       if(uid == 0)
-       {
-               printf("%s", "This is executed as root privilege\n");
-               printf("argc = %d\n");
-               for(i=0;i<argc;i++)
-               {
-                       printf("argv[%d]: [%s]\n", i, argv[i]);
-               }
-               exit(0);
-       }
-       printf("Wrong uid: %d\n", uid);
-       printf("You must run %s under root user or developer(%d) user\n", argv[0], DEVELOPER_UID);
-       exit(-1);
-       
-}
diff --git a/testcases/security_server_tc_client.c b/testcases/security_server_tc_client.c
deleted file mode 100644 (file)
index 8c7a32b..0000000
+++ /dev/null
@@ -1,597 +0,0 @@
-/*
- * security server
- *
- * Copyright (c) 2000 - 2010 Samsung Electronics Co., Ltd.
- * Contact: Bumjin Im <bj.im@samsung.com>
- *
- */
-
-#include <stdio.h>
-#include <errno.h>
-#include <stdlib.h>
-#include <sys/types.h>
-#include <sys/param.h>
-#include <fcntl.h>
-#include <sys/un.h>
-#include <unistd.h>
-#include <sys/socket.h>
-#include "security-server.h"
-#include "test.h"
-
-int *g_permissions = NULL;
-gid_t *g_groups = NULL;
-int g_perm_num, g_group_num;
-
-char *object_label = NULL;
-char *subject_label = NULL;
-char *access_rights = NULL;
-
-/*
- * 0 - old mode (uid/gid)
- * 1 - new mode (SMACK labels)
- */
-int mode_new = 0;
-
-void printusage(char *cmdline)
-{
-       printf("%s\n", "Usage: ");
-       printf("%s -u uid -g gid1 gid2 gid3... -p gid_a gid_b gid_c ...\n", cmdline);
-        printf("%s\n", "or:");
-       printf("%s -s subject -o object -a access-rights\n", cmdline);
-       printf("%s\n", "[Options]");
-       printf("%s\n", "-u: UID that the process are running as");
-       printf("%s\n", "    Only one UID is allowed.");
-       printf("%s\n", "-g: GIDs that the process belongs to");
-       printf("%s\n", "-p: GIDs that the process wants to get privilege");
-       printf("%s\n", "-s: subject label (label of the process)");
-       printf("%s\n", "-o: object label to be accessed");
-       printf("%s\n", "-a: accessed rights requested (one or more of the letterrs rwx)");
-       printf("%s\n", "Examples:");
-       printf("%s -u 5000 -g 6001 6002 6003 6004 6005 6006 6007 -p 6001 6002 6010\n", cmdline);
-       printf("%s -s mylabel -o objlabel -a rx\n", cmdline);
-}
-
-int privilege_control(int argc, char *argv[])
-{
-
-        if (argc == 7 && !strcmp(argv[1], "-s"))
-        {
-            return privilege_control_new(argc, argv);
-        }
-        else
-        {
-            return privilege_control_old(argc, argv);
-        }
-}
-
-int privilege_control_old(int argc, char *argv[])
-{
-       int option = 0; /* 0: no, 1: uID, 2: gid, 3: permission */
-       int uid_flag = 0, gid_flag= 0, perm_flag = 0, i = 1, number, uid = 0, j;
-
-       while(i < argc)
-       {
-               if(strcmp(argv[i], "-u") == 0)
-               {
-                       if(uid_flag != 0)
-                       {
-                               printf("%s\n", "-u option already used");
-                               printusage(argv[0]);
-                               exit(1);
-                       }
-                       option = 1;
-                       uid_flag = 1;
-               }
-               else if (strcmp(argv[i], "-g") == 0)
-               {
-                       if(gid_flag != 0)
-                       {
-                               printf("%s\n", "-g option already used");
-                               printusage(argv[0]);
-                               exit(1);
-                       }
-                       option = 2;
-                       gid_flag = 1;
-               }
-               else if (strcmp(argv[i], "-p") == 0)
-               {
-                       if(perm_flag != 0)
-                       {
-                               printf("%s\n", "-p option already used");
-                               printusage(argv[0]);
-                               exit(1);
-                       }
-                       option = 3;
-                       perm_flag = 1;
-               }
-               else
-               {
-                       errno = 0;
-                       number = strtoul(argv[i], 0, 10);
-                       if(errno != 0)
-                       {
-                               printf("%s\n", "Invalid option");
-                               printusage(argv[0]);
-                               exit(1);
-                       }
-                       switch(option)
-                       {
-                               case 1:
-                                       if(uid != 0)
-                                       {
-                                               printf("%s\n", "You cannot assign more than 1 uID");
-                                               printusage(argv[0]);
-                                               exit(1);
-                                       }
-                                       uid = number;
-                                       break;
-                               case 2:
-                                       for(j=0;i<g_group_num;j++)
-                                       {
-                                               if(number == g_groups[j])
-                                                       break;
-                                       }
-                                       g_groups = (gid_t *)realloc(g_groups, sizeof(gid_t) * (++g_group_num));
-                                       g_groups[g_group_num -1] = number;
-                                       break;
-                               case 3:
-                                       for(j=0;i<g_perm_num;j++)
-                                       {
-                                               if(number == g_permissions[j])
-                                                       break;
-                                       }
-                                       g_permissions = (int *)realloc(g_permissions, sizeof(int) * (++g_perm_num));
-                                       g_permissions[g_perm_num -1] = number;
-                                       break;
-                               default:
-                                       printf("%s\n", "Invalid option");
-                                       printusage(argv[0]);
-                                       exit(1);
-                                       break;
-                       }
-               }
-               i++;
-       }
-       if(g_group_num == 0 || g_perm_num == 0)
-       {
-               printf("%s\n", "You must assign groups and permissions");
-               printusage(argv[0]);
-               exit(1);
-       }
-       if(setgroups(g_group_num, g_groups) != 0)
-       {
-               printf("%s\n", "Error on setgroups{}");
-               exit(1);
-       }
-
-       setgid(uid);
-       setuid(uid);
-       return 0;
-}
-
-int privilege_control_new(int argc, char *argv[])
-{
-    if (argc == 7 && !strcmp(argv[1], "-s") &&
-                     !strcmp(argv[3], "-o") &&
-                     !strcmp(argv[5], "-a"))
-    {
-        int fd, len, ret; int e;
-        mode_new = 1;
-        subject_label = argv[2];
-        object_label = argv[4];
-        access_rights = argv[6];
-        fd = open("/proc/self/attr/current", O_WRONLY|O_TRUNC, 0);
-        if (fd < 0)
-        { 
-            printf("Cannot set my own smack label... maybe I'm not root?");
-            exit(1);
-        }
-        len = strlen(subject_label);
-        ret = write(fd, subject_label, len);
-        if (ret != len)
-        { 
-            e = errno;
-            printf("(2)Cannot set my own smack label... maybe I'm not root?");
-            exit(1);
-        }
-        close(fd);
-        setgid(1);
-        setuid(1);
-    }
-    else
-    {
-        printusage(argv[0]);
-        exit(1);
-    }
-
-    return 0;
-}
-
-int connect_to_testserver()
-{
-       struct sockaddr_un clientaddr;
-       int client_len = 0, localsockfd, ret;
-
-       /* Create a socket */
-       if((localsockfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0)
-       {
-               printf("%s\n", "Error on socket()");
-               return 0;
-       }
-
-       bzero(&clientaddr, sizeof(clientaddr));
-       clientaddr.sun_family = AF_UNIX;
-       strncpy(clientaddr.sun_path, SECURITY_SERVER_TEST_SOCK_PATH, strlen(SECURITY_SERVER_TEST_SOCK_PATH));
-       clientaddr.sun_path[strlen(SECURITY_SERVER_TEST_SOCK_PATH)] = 0;
-       client_len = sizeof(clientaddr);
-       if(connect(localsockfd, (struct sockaddr*)&clientaddr, client_len) < 0)
-       {
-               printf("%s\n", "Error on connect");
-               close(localsockfd);
-               return 0;
-       }
-       return localsockfd;
-}
-
-void printhex(unsigned char *data, int size)
-{
-       int i;
-       for(i=0;i<size;i++)
-       {
-               if(data[i] < 0x10)
-                       printf("0");
-
-               printf("%X ", data[i]);
-               if(((i+1) % 16) == 0 && i != 0)
-                       printf("\n");
-       }
-       printf("\n");
-}
-
-
-int send_request(int sock_fd, unsigned char *cookie, int perm)
-{
-       unsigned char buf[28] = {0, 0, 0, 0, };
-       int size;
-       memcpy(buf + 4, cookie, 20);
-       memcpy(buf + 24, &perm, sizeof(int));
-       size = write(sock_fd, buf, 28);
-       if(size < 28)
-       {
-               printf("Cannot send\n");
-               close(sock_fd);
-               exit(1);
-       }
-       return 0;
-}
-
-/*
- * @param direct 0=via security server 1=directly from IPC socket
- */
-int send_request_new_cookie(int sock_fd,
-                            const char *cookie,
-                            const char *subject_label,
-                            const char *access_rights)
-{
-    unsigned char buf[1024] = {17, 0, 0, 0, };
-    int olen, alen;
-    int size, ret;
-    olen = strlen(subject_label);
-    alen = strlen(access_rights);
-    size = 24+2*sizeof(int)+olen+alen;
-    memcpy(buf + 4, cookie, 20);
-    memcpy(buf + 24, &olen, sizeof(int));
-    memcpy(buf + 28, &alen, sizeof(int));
-    memcpy(buf + 32, subject_label, olen);
-    memcpy(buf + 32 + olen, access_rights, alen);
-    ret = write(sock_fd, buf, size);
-    if(ret < size)
-    {
-       printf("Cannot send\n");
-       close(sock_fd);
-       exit(1);
-    }
-    return 0;
-}
-
-int send_request_new_direct(int sock_fd,
-                            const char *object_label,
-                            const char *access_rights)
-{
-    unsigned char buf[1024] = {17, 0, 0, 1, };
-    int olen, alen;
-    int size, ret;
-    olen = strlen(object_label);
-    alen = strlen(access_rights);
-    size = 24+2*sizeof(int)+olen+alen;
-    memcpy(buf + 4, &olen, sizeof(int));
-    memcpy(buf + 8, &alen, sizeof(int));
-    memcpy(buf + 12, object_label, olen);
-    memcpy(buf + 12 + olen, access_rights, alen);
-    ret = write(sock_fd, buf, size);
-    if(ret < size)
-    {
-       printf("Cannot send\n");
-       close(sock_fd);
-       exit(1);
-    }
-    return 0;
-}
-
-int recv_result(int sock_fd)
-{
-       int buf, size;
-       size = read(sock_fd, &buf, sizeof(int));
-       if(size < sizeof(int))
-       {
-               printf("Cannot recv\n");
-               close(sock_fd);
-               exit(1);
-       }
-       return buf;
-}
-
-
-
-int main(int argc, char *argv[])
-{
-       int ret, sock_fd, i, cur_pid, cnt;
-       unsigned char cookie[20];
-       char tmpchar[100];
-
-       g_group_num = 0;
-       g_perm_num = 0;
-
-       ret = getuid();
-       if(ret != 0)
-       {
-               printf("You must be root to test. Current UID: %d\nExiting...\n", ret);
-               exit(1);
-       }
-
-       if(argc < 2)
-       {
-               printf("%s\n", "Error: No group identified");
-               printusage(argv[0]);
-               exit(1);
-       }
-
-       system("touch /opt/home/root/pid_cycle");
-       privilege_control(argc, argv);
-
-       printf("Strting test. My PID is %d\n", getpid());
-
-       printf("TC C1: security_server_get_cookie_size()\n");
-       ret = security_server_get_cookie_size();
-       if(ret != 20)
-       {
-               printf("TC C1 failed. %d\n", ret);
-               exit(1);
-
-       }
-       printf("TC C1: PASSED\n\n");
-       sleep(1);
-
-       printf("TC C2: security_server_request_cookie(): normal case\n");
-       ret = security_server_request_cookie(cookie, 20);
-       if(ret != SECURITY_SERVER_API_SUCCESS)
-       {
-               printf("TC C2 failed. %d\n", ret);
-               exit(1);
-       }
-       printhex(cookie, 20);
-       printf("TC C2: PASSED\n\n");
-       sleep(1);
-
-       printf("TC C3: security_server_request_cookie(): Too small buffer size\n");
-       ret = security_server_request_cookie(cookie, 10);
-       if(ret != SECURITY_SERVER_API_ERROR_BUFFER_TOO_SMALL)
-       {
-               printf("TC C3 failed. %d\n", ret);
-               exit(1);
-       }
-       printf("TC C3: PASSED\n\n");
-       sleep(1);
-
-       printf("TC C4: security_server_check_privilege(): client is not allowed\n");
-        if (mode_new)
-        {
-            printf("TC C4: SKIPPED because new mode (SMACK-based) was selected.\n");
-        }
-        else
-        {
-           ret = security_server_check_privilege(cookie, g_permissions[0]);
-           if(ret != SECURITY_SERVER_API_ERROR_AUTHENTICATION_FAILED)
-           {
-               printf("TC C4 failed. %d\n", ret);
-               exit(1);
-           }
-           printf("TC C4: PASSED\n\n");
-           sleep(1);
-        }
-
-       printf("TC C5: security_server_get_gid(): client is not allowed\n");
-       ret = security_server_get_gid("telephony");
-       if(ret != SECURITY_SERVER_API_ERROR_AUTHENTICATION_FAILED)
-       {
-               printf("TC C5 failed. %d\n", ret);
-               exit(1);
-       }
-       printf("TC C5: PASSED\n\n");
-       sleep(1);
-
-       printf("TC C6: security_server_get_object_name(): client is not allowed\n");
-        if (mode_new)
-        {
-            printf("TC C6: SKIPPED because new mode (SMACK-based) was selected.\n");
-        }
-        else
-        {
-           ret = security_server_get_object_name(g_groups[0], tmpchar, sizeof(tmpchar));
-           if(ret != SECURITY_SERVER_API_ERROR_AUTHENTICATION_FAILED)
-           {
-               printf("TC C6 failed. %d\n", ret);
-               exit(1);
-           }
-           printf("TC C6: PASSED\n\n");
-           sleep(1);
-        }
-
-       printf("TC C7: Requesting access to test server via security server\n");
-        if (mode_new)
-        {
-            printf("object:  >%s<\n", object_label);
-            printf("subject: >%s<\n", subject_label);
-            printf("access:  >%s<\n", access_rights);
-
-            sock_fd = connect_to_testserver();
-           if(sock_fd < 1)
-           {
-               printf("Socket connection error\n");
-               exit(1);
-           }
-           ret = send_request_new_cookie(sock_fd, cookie, object_label, access_rights);
-           if(ret != 0)
-           {
-               printf("send failed\n");
-               close(sock_fd);
-               exit(1);
-           }
-           ret = recv_result(sock_fd);
-           if(ret == SECURITY_SERVER_API_SUCCESS)
-           {
-               printf("Permission granted\n\n");
-           }
-           else if(ret == SECURITY_SERVER_API_ERROR_ACCESS_DENIED)
-           {
-               printf("Permission denied\n\n");
-           }
-           else
-           {
-               printf("Recv error\n");
-               close(sock_fd);
-               exit(1);
-           }
-           close(sock_fd);
-           sock_fd = 0;
-           sleep(1);
-        }
-        else
-        {
-           for(i=0;i<g_perm_num;i++)
-           {
-               sock_fd = connect_to_testserver();
-               if(sock_fd < 1)
-               {
-                       printf("Socket connection error\n");
-                       exit(1);
-               }
-               printf("%d: requesting %d permission...sockfd=%d\n", i, g_permissions[i], sock_fd);
-               ret = send_request(sock_fd, cookie, g_permissions[i]);
-               if(ret != 0)
-               {
-                       printf("send failed\n");
-                       close(sock_fd);
-                       exit(1);
-               }
-    
-               ret = recv_result(sock_fd);
-               if(ret == SECURITY_SERVER_API_SUCCESS)
-               {
-                       printf("Permission granted\n\n");
-               }
-               else if(ret == SECURITY_SERVER_API_ERROR_ACCESS_DENIED)
-               {
-                       printf("Permission denied\n\n");
-               }
-               else
-               {
-                       printf("Recv error\n");
-                       close(sock_fd);
-                       exit(1);
-               }
-               close(sock_fd);
-               sock_fd = 0;
-           }
-           sleep(1);
-        }
-
-       printf("TC C7a: Requesting access to test server with direct IPC\n");
-        if (mode_new)
-        {
-            printf("subject: >%s<\n", subject_label);
-            printf("object:  >%s<\n", object_label);
-            printf("access:  >%s<\n", access_rights);
-
-            sock_fd = connect_to_testserver();
-           if(sock_fd < 1)
-           {
-               printf("Socket connection error\n");
-               exit(1);
-           }
-           ret = send_request_new_direct(sock_fd, object_label, access_rights);
-           if(ret != 0)
-           {
-               printf("send failed\n");
-               close(sock_fd);
-               exit(1);
-           }
-           ret = recv_result(sock_fd);
-           if(ret == SECURITY_SERVER_API_SUCCESS)
-           {
-               printf("Permission granted\n\n");
-           }
-           else if(ret == SECURITY_SERVER_API_ERROR_ACCESS_DENIED)
-           {
-               printf("Permission denied\n\n");
-           }
-           else
-           {
-               printf("Recv error\n");
-               close(sock_fd);
-               exit(1);
-           }
-           close(sock_fd);
-           sock_fd = 0;
-           sleep(1);
-        }
-        else
-        {
-            printf("TC C7a: SKIPPED because old mode (uid/gid-based) was selected.\n");
-        }
-
-       printf("TC 08: Requesting cookie for same PID with different path\n");
-       printf("       Exiting this process to cycle different process as same PID.\n");
-       printf("       Please look at the test server's terminal for the result\n");
-       cur_pid = getpid();
-       sock_fd = connect_to_testserver();
-       if(sock_fd < 1)
-       {
-               printf("Socket connection error\n");
-               exit(1);
-       }
-
-       unsigned char buf[32] = {255, 255, 255, 255, };
-       int size;
-
-       memcpy(buf + 4, cookie, 20);
-       memcpy(buf + 24, &cur_pid, sizeof(int));
-       ret = getuid();
-       memcpy(buf + 28, &ret, sizeof(int));
-
-       size = write(sock_fd, buf, 32);
-       if(size < 32)
-       {
-               printf("Cannot send\n");
-               close(sock_fd);
-               exit(1);
-       }
-       if(sock_fd > 0)
-               close(sock_fd);
-       if(g_groups != NULL)
-               free(g_groups);
-       if(g_permissions != NULL)
-               free(g_permissions);
-       return 0;
-}
-
diff --git a/testcases/security_server_tc_password.c b/testcases/security_server_tc_password.c
deleted file mode 100644 (file)
index f31134b..0000000
+++ /dev/null
@@ -1,667 +0,0 @@
-/*
- * security server
- *
- * Copyright (c) 2000 - 2010 Samsung Electronics Co., Ltd.
- * Contact: Bumjin Im <bj.im@samsung.com>
- *
- */
-
-#include <stdio.h>
-#include <errno.h>
-#include <stdlib.h>
-#include <sys/types.h>
-#include <sys/param.h>
-#include <fcntl.h>
-#include <sys/un.h>
-#include <unistd.h>
-#include <sys/socket.h>
-#include <dirent.h>
-#include "security-server.h"
-#include "test.h"
-
-void printusage(char *cmdline)
-{
-       printf("%s\n", "Usage: ");
-       printf("%s password1, password2\n", cmdline);
-       printf("%s\n", "Example:");
-       printf("%s 123456 abcdef\n", cmdline);
-}
-
-void printhex(unsigned char *data, int size)
-{
-       int i;
-       for(i=0;i<size;i++)
-       {
-               if(data[i] < 0x10)
-                       printf("0");
-
-               printf("%X ", data[i]);
-               if(((i+1) % 16) == 0 && i != 0)
-                       printf("\n");
-       }
-       printf("\n");
-}
-
-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 main(int argc, char *argv[])
-{
-       int ret;
-       unsigned long i=1;
-       unsigned int attempt, max_attempt, expire_sec, temp_sec;
-       struct timeval cur_time;
-       char buf1[33], buf2[33];
-       struct dirent **mydirent;
-
-       if(argc < 2)
-       {
-               printf("%s\n", "Error: No password identified");
-               printusage(argv[0]);
-               exit(1);
-       }
-
-       if(getuid() == 0)
-       {
-               system("rm /opt/data/security-server/*");
-               sync();
-
-               printf("TC P1: security_server_is_pwd_empty(). no pwd case.\n");
-               ret = security_server_is_pwd_valid(&attempt, &max_attempt, &expire_sec);
-               if(ret != SECURITY_SERVER_API_ERROR_NO_PASSWORD || attempt != 0 || max_attempt != 0 || expire_sec != 0)
-               {
-                       printf("TC P1 failed. return = %d, current_attempt=%d, max_attempt=%d, expire_day=%d\n", ret, attempt, max_attempt, expire_sec);
-                       exit(1);
-               }
-               printf("TC P1: PASSED\n\n");
-               sleep(1);
-       }
-       else
-       {
-               printf("To run the TC as non root user, please remove password files (/opt/data/security-server/*) in root shell\n");
-               printf("If not, you will see some TC failures\n");
-       }
-
-       printf("TC P1.1: security_server_set_pwd_validity(): There is no password yet\n");
-       ret = security_server_set_pwd_validity(10);
-       if(ret != SECURITY_SERVER_API_ERROR_NO_PASSWORD)
-    {
-        printf("TC P1.1 failed. %d\n", ret);
-        exit(1);
-    }
-       ret = security_server_set_pwd_validity(11);
-    if(ret != SECURITY_SERVER_API_ERROR_NO_PASSWORD)
-    {
-        printf("TC P1.1 failed. %d\n", ret);
-        exit(1);
-    }
-
-    printf("TC P1.1: PASSED\n\n");
-    sleep(1);
-
-    printf("TC P1.2: security_server_set_pwd_max_challenge(): There is no password yet\n");
-       ret = security_server_set_pwd_max_challenge(5);
-    if(ret != SECURITY_SERVER_API_ERROR_NO_PASSWORD)
-    {
-        printf("TC P1.2 failed. %d\n", ret);
-        exit(1);
-    }
-       ret = security_server_set_pwd_max_challenge(6);
-    if(ret != SECURITY_SERVER_API_ERROR_NO_PASSWORD)
-    {
-        printf("TC P1.2 failed. %d\n", ret);
-        exit(1);
-    }
-
-    printf("TC P1.2: PASSED\n\n");
-    sleep(1);
-
-       printf("TC P2: security_server_chk_pwd(): Too long password case\n");
-       ret = security_server_chk_pwd("abcdefghijklmnopqrstuvwxyz0123456", &attempt, &max_attempt, &expire_sec); /* 33 chars */
-       if(ret != SECURITY_SERVER_API_ERROR_INPUT_PARAM)
-       {
-               printf("TC P2 failed. %d\n", ret);
-               exit(1);
-       }
-       printf("TC P2: PASSED\n\n");
-       sleep(1);
-
-       printf("TC P3: security_server_chk_pwd(): NULL input case\n");
-       ret = security_server_chk_pwd(NULL, &attempt, &max_attempt, &expire_sec);
-       if(ret != SECURITY_SERVER_API_ERROR_INPUT_PARAM)
-       {
-               printf("TC P3.1 failed. %d\n", ret);
-               exit(1);
-       }
-       ret = security_server_chk_pwd("password", NULL, &max_attempt, &expire_sec);
-       if(ret != SECURITY_SERVER_API_ERROR_INPUT_PARAM)
-       {
-               printf("TC P3.2 failed. %d\n", ret);
-               exit(1);
-       }
-       ret = security_server_chk_pwd("password", &attempt, NULL, &expire_sec);
-       if(ret != SECURITY_SERVER_API_ERROR_INPUT_PARAM)
-       {
-               printf("TC P3.3 failed. %d\n", ret);
-               exit(1);
-       }
-       ret = security_server_chk_pwd("password", &attempt, &max_attempt, NULL);
-       if(ret != SECURITY_SERVER_API_ERROR_INPUT_PARAM)
-       {
-               printf("TC P3.4 failed. %d\n", ret);
-               exit(1);
-       }
-       printf("TC P3: PASSED\n\n");
-       sleep(1);
-
-       printf("TC P4: security_server_chk_pwd(): no password case\n");
-       ret = security_server_chk_pwd("isthisempty", &attempt, &max_attempt, &expire_sec);
-       if(ret != SECURITY_SERVER_API_ERROR_NO_PASSWORD || max_attempt != 0 || expire_sec != 0)
-       {
-               printf("TC P4 failed. %d\n", ret);
-               exit(1);
-       }
-       printf("TC P4: PASSED\n\n");
-       sleep(1);
-
-       printf("TC P5: security_server_set_pwd(): NULL input case\n");
-       ret = security_server_set_pwd(NULL, NULL, 0, 0);
-       if(ret != SECURITY_SERVER_API_ERROR_INPUT_PARAM)
-       {
-               printf("TC P5 failed. %d\n", ret);
-               exit(1);
-       }
-       printf("TC P5: PASSED\n\n");
-       sleep(1);
-
-       printf("TC P6: security_server_set_pwd(): Too long input param\n");
-       ret = security_server_set_pwd("abcdefghijklmnopqrstuvwxyz0123456", "abcdefghijklmnopqrstuvwxyz0123456", 0, 0);
-       if(ret != SECURITY_SERVER_API_ERROR_INPUT_PARAM)
-       {
-               printf("TC P6 failed. %d\n", ret);
-               exit(1);
-       }
-       printf("TC P6: PASSED\n\n");
-       sleep(1);
-
-       printf("TC P7: security_server_set_pwd(): Normal case when current pwd is empty\n");
-       ret = security_server_set_pwd(NULL, argv[1], 0, 0);
-       if(ret != SECURITY_SERVER_API_SUCCESS)
-       {
-               printf("TC P7 failed. %d\n", ret);
-               exit(1);
-       }
-       printf("TC P7: PASSED\n\n");
-       sleep(1);
-
-
-       printf("TC P7.1: security_server_set_pwd_validity(): Normal case when there is a password\n");
-    ret = security_server_set_pwd_validity(1);
-    if(ret != SECURITY_SERVER_API_SUCCESS)
-    {
-        printf("TC P7.1 failed. %d\n", ret);
-        exit(1);
-    }
-
-    ret = security_server_set_pwd_validity(2);
-    if(ret != SECURITY_SERVER_API_SUCCESS)
-    {
-        printf("TC P7.1 failed. %d\n", ret);
-        exit(1);
-    }
-
-    ret = security_server_is_pwd_valid(&attempt, &max_attempt, &expire_sec);
-    if(ret != SECURITY_SERVER_API_ERROR_PASSWORD_EXIST)
-    {
-        printf("TC P7.1 failed. %d\n", ret);
-        exit(1);
-    }
-    if (expire_sec < 172798 || expire_sec > 172800) // About 2 days in seconds +-1 second
-    {
-        printf("TC P7.1 failed. Invalid expiration time in seconds: %d", expire_sec);
-        exit(1);
-    }
-
-    printf("TC P7.1: PASSED\n\n");
-    sleep(1);
-
-
-    printf("TC P7.2: security_server_set_pwd_max_challenge(): Normal case when there is a password\n");
-    ret = security_server_set_pwd_max_challenge(5);
-    if(ret != SECURITY_SERVER_API_SUCCESS)
-    {
-        printf("TC P7.2 failed. %d\n", ret);
-        exit(1);
-    }
-
-
-    ret = security_server_set_pwd_max_challenge(6);
-    if(ret != SECURITY_SERVER_API_SUCCESS)
-    {
-        printf("TC P7.2 failed. %d\n", ret);
-        exit(1);
-    }
-    ret = security_server_is_pwd_valid(&attempt, &max_attempt, &expire_sec);
-    if(ret != SECURITY_SERVER_API_ERROR_PASSWORD_EXIST)
-    {
-        printf("TC P7.1 failed. %d\n", ret);
-        exit(1);
-    }
-    if (6 != max_attempt)
-    {
-        printf("TC P7.2 failed. Invalid max_attempt: %d", max_attempt);
-        exit(1);
-    }
-
-    printf("TC P7.2: PASSED\n\n");
-    sleep(1);
-
-       printf("TC P8: security_server_chk_pwd(): normal(correct pwd) case\n");
-       ret = security_server_chk_pwd(argv[1], &attempt, &max_attempt, &expire_sec);
-       if(ret != SECURITY_SERVER_API_SUCCESS)
-       {
-               printf("TC P8 failed. %d\n", ret);
-               exit(1);
-       }
-       printf("TC P8: PASSED\n\n");
-       sleep(1);
-
-       printf("TC P9: security_server_is_pwd_empty(). password exists.\n");
-       ret = security_server_is_pwd_valid(&attempt, &max_attempt, &expire_sec);
-       if(ret != SECURITY_SERVER_API_ERROR_PASSWORD_EXIST)
-       {
-               printf("TC P9 failed. %d\n", ret);
-               exit(1);
-       }
-       printf("TC P9: PASSED\n\n");
-       sleep(1);
-
-       printf("TC P10: security_server_chk_pwd(): incorrect pwd case\n");
-       (argv[1])[0]++;
-       ret = security_server_chk_pwd(argv[1], &attempt, &max_attempt, &expire_sec);
-       if(ret != SECURITY_SERVER_API_ERROR_PASSWORD_MISMATCH)
-       {
-               printf("TC P10 failed. %d\n", ret);
-               exit(1);
-       }
-       printf("TC P10: PASSED\n\n");
-       sleep(1);
-
-       printf("TC P11: security_server_set_pwd(): Incorrect current password\n");
-       ret = security_server_set_pwd(argv[1], argv[2], 0, 0);
-       if(ret != SECURITY_SERVER_API_ERROR_PASSWORD_MISMATCH)
-       {
-               printf("TC P11 failed. %d\n", ret);
-               exit(1);
-       }
-       printf("TC P11: PASSED\n\n");
-       (argv[1])[0]--;
-       sleep(1);
-
-       printf("TC P12: security_server_set_pwd(): correct password\n");
-       ret = security_server_set_pwd(argv[1], argv[2], 0, 0);
-       if(ret != SECURITY_SERVER_API_SUCCESS)
-       {
-               printf("TC P12 failed. %d\n", ret);
-               exit(1);
-       }
-       printf("TC P12: PASSED\n\n");
-       sleep(1);
-
-       printf("TC P13: security_server_chk_pwd(): Check increasing attempts, with reset when correct password has been checked\n");
-       ret = security_server_set_pwd(argv[2], argv[1], 10, 0);
-       if(ret != SECURITY_SERVER_API_SUCCESS)
-       {
-               printf("TC P13.1 failed. %d\n", ret);
-               exit(1);
-       }
-       sleep(1);
-       for(i=0;i<5;i++)
-       {
-               printf("%d\n", i+1);
-               ret = security_server_chk_pwd(argv[2],  &attempt, &max_attempt, &expire_sec);
-               if(ret != SECURITY_SERVER_API_ERROR_PASSWORD_MISMATCH)
-               {
-                       printf("\nTC P13.%da failed. %d\n", i+2, ret);
-                       exit(1);
-               }
-               if(attempt != (i+1))
-               {
-                       printf("\nTC P13.%db failed. %d\n", i+2, ret);
-                       exit(1);
-               }
-               sleep(1);
-       }
-       printf("%d\n", i+1);
-       ret = security_server_chk_pwd(argv[1],  &attempt, &max_attempt, &expire_sec);
-       if(ret != SECURITY_SERVER_API_SUCCESS)
-       {
-               printf("TC P13.%d failed. %d\n", i+2, ret);
-               exit(1);
-       }
-       sleep(1);
-       printf("%d\n", i+2);
-       ret = security_server_is_pwd_valid(&attempt, &max_attempt, &expire_sec);
-       if(ret != SECURITY_SERVER_API_ERROR_PASSWORD_EXIST)
-       {
-               printf("TC P13.%d failed. %d\n", i+3, ret);
-               exit(1);
-       }
-       if(attempt != 0 || max_attempt != 10)
-       {
-               printf("TC P13.%d failed. %d\n", i+3, ret);
-               exit(1);
-       }
-       printf("TC P13: PASSED\n\n");
-       sleep(1);
-
-       printf("TC P14: security_server_chk_pwd(): attempt exceeding case\n");
-       for(i=0;i<10;i++)
-       {
-               printf("%d\n", i+1);
-               ret = security_server_chk_pwd(argv[2],  &attempt, &max_attempt, &expire_sec);
-               if(ret != SECURITY_SERVER_API_ERROR_PASSWORD_MISMATCH)
-               {
-                       printf("\nTC P14.%da failed. %d\n", i+1, ret);
-                       exit(1);
-               }
-               if(attempt != (i+1))
-               {
-                       printf("\nTC P14.%db failed. %d\n", i+1, ret);
-                       exit(1);
-               }
-               sleep(1);
-       }
-       printf("%d\n", i+1);
-       ret = security_server_chk_pwd(argv[1],  &attempt, &max_attempt, &expire_sec);
-       if(ret != SECURITY_SERVER_API_ERROR_PASSWORD_MAX_ATTEMPTS_EXCEEDED)
-       {
-               printf("TC P14.%d failed. %d\n", i+1, ret);
-               exit(1);
-       }
-       printf("TC P14: PASSED\n\n");
-       sleep(1);
-
-       printf("TC P15: security_server_reset_pwd(): Reset current password\n");
-       ret = security_server_reset_pwd(argv[1],0, 0);
-       if(ret != SECURITY_SERVER_API_SUCCESS)
-       {
-               printf("TC P15 failed. %d\n", ret);
-               exit(1);
-       }
-       printf("TC P15: PASSED\n\n");
-       sleep(1);
-
-       printf("TC P16: security_server_set_pwd(): Check expiration \n");
-       ret = security_server_set_pwd(argv[1], argv[2], 10, 1);
-       if(ret != SECURITY_SERVER_API_SUCCESS)
-       {
-               printf("TC P16.1 failed. %d\n", ret);
-               exit(1);
-       }
-       sleep(1);
-       ret = security_server_is_pwd_valid(&attempt, &max_attempt, &expire_sec);
-       if(ret != SECURITY_SERVER_API_ERROR_PASSWORD_EXIST)
-       {
-               printf("TC P16.2 failed. %d\n", ret);
-               exit(1);
-       }
-       if(expire_sec > 86400 || expire_sec < 86398)
-       {
-               printf("TC P16.3 failed. %d, %d\n", ret, expire_sec);
-               exit(1);
-       }
-       printf("TC P16: PASSED\n\n");
-       sleep(1);
-
-       printf("TC P17: security_server_chk_pwd(): Check expiration sec decreasing\n");
-       ret = security_server_is_pwd_valid(&attempt, &max_attempt, &expire_sec);
-       if(ret != SECURITY_SERVER_API_ERROR_PASSWORD_EXIST)
-       {
-               printf("TC P17.1 failed. %d\n", ret);
-               exit(1);
-       }
-       sleep(1);
-       temp_sec = 0;
-       for(i=0;i<5;i++)
-       {
-               expire_sec = 0;
-               ret = security_server_chk_pwd(argv[2],  &attempt, &max_attempt, &expire_sec);
-               if(ret != SECURITY_SERVER_API_SUCCESS)
-               {
-                       printf("\nTC P17.%da failed. %d\n", i+4, ret);
-                       exit(1);
-               }
-               if(temp_sec != 0 && ((temp_sec -expire_sec) > 2) && ((temp_sec -expire_sec) < 1))
-               {
-                       printf("\nTC P17.%db failed. %d, %d, %d\n", i+4, ret, temp_sec, expire_sec);
-                       exit(1);
-               }
-               temp_sec = expire_sec;
-               printf("%d\n", expire_sec);
-               sleep(1);
-       }
-       printf("\nTC P17: PASSED\n\n");
-
-       printf("TC P18: security_server_chk_pwd(): Check expiration with system time change\n");
-       ret = gettimeofday(&cur_time, NULL);
-       if(ret < 0)
-       {
-               printf("TC P18.1 failed. %d\n", ret);
-               exit(1);
-       }
-       cur_time.tv_sec += (expire_sec -4);
-       ret = settimeofday(&cur_time, NULL);
-       if(ret < 0)
-       {
-               printf("TC P18.2 failed. %d\n", ret);
-               exit(1);
-       }
-       temp_sec = 0;
-       for(i=0;i<5;i++)
-       {
-               expire_sec = 0;
-               ret = security_server_chk_pwd(argv[2],  &attempt, &max_attempt, &expire_sec);
-               if(ret != SECURITY_SERVER_API_SUCCESS && ret != SECURITY_SERVER_API_ERROR_PASSWORD_EXPIRED)
-               {
-                       printf("\nTC P18.%da failed. %d\n", i+1, ret);
-                       exit(1);
-               }
-               if(ret == SECURITY_SERVER_API_ERROR_PASSWORD_EXPIRED)
-                       break;
-
-               if(temp_sec != 0 && ((temp_sec -expire_sec) > 2) && ((temp_sec -expire_sec) < 1))
-               {
-                       printf("\nTC P18.%db failed. %d, %d, %d\n", i+1, ret, temp_sec, expire_sec);
-                       exit(1);
-               }
-               temp_sec = expire_sec;
-               printf("%d\n", expire_sec);
-               sleep(1);
-       }
-       if(ret != SECURITY_SERVER_API_ERROR_PASSWORD_EXPIRED)
-       {
-               printf("\nTC P18.%i failed. %d\n", i+1, ret);
-               exit(1);
-       }
-       printf("\nTC P18: PASSED\n\n");
-       sleep(1);
-
-       printf("TC P19: security_server_set_pwd_history(): Too big & small number\n");
-       ret = security_server_set_pwd_history(100);
-       if(ret != SECURITY_SERVER_API_ERROR_INPUT_PARAM)
-       {
-               printf("\nTC P19.1 failed. %d\n", ret);
-               exit(1);
-       }
-       ret = security_server_set_pwd_history(-5);
-       if(ret != SECURITY_SERVER_API_ERROR_INPUT_PARAM)
-       {
-               printf("\nTC P19.2 failed. %d\n", ret);
-               exit(1);
-       }
-       printf("\nTC P19: PASSED\n\n");
-       sleep(1);
-
-       printf("TC P20: security_server_set_pwd_history(): normal case\n");
-       ret = security_server_set_pwd_history(10);
-       if(ret != SECURITY_SERVER_API_SUCCESS)
-       {
-               printf("\nTC P20 failed. %d\n", ret);
-               exit(1);
-       }
-       printf("\nTC P20: PASSED\n\n");
-       sleep(1);
-
-       printf("TC P21: security_server_set_pwd_history(): Check history is working\n");
-       ret = security_server_reset_pwd("history1",0, 0);
-       if(ret != SECURITY_SERVER_API_SUCCESS)
-       {
-               printf("TC P21.1 failed. %d\n", ret);
-               exit(1);
-       }
-       printf("1\n");
-       sleep(1);
-       for(i=1;i<11;i++)
-       {
-               sprintf(buf1, "history%d", i);
-               sprintf(buf2, "history%d", i+1);
-               ret = security_server_set_pwd(buf1, buf2, 0, 0);
-               if(ret != SECURITY_SERVER_API_SUCCESS)
-               {
-                       printf("\nTC P21.%d failed. %d\n", i+1, ret);
-                       exit(1);
-               }
-               printf("%d\n", i+1);
-               sleep(1);
-       }
-       ret = security_server_set_pwd("history11", "history1", 0, 0);
-       if(ret != SECURITY_SERVER_API_SUCCESS)
-       {
-               printf("\nTC P21.%d failed. %d\n", i+1, ret);
-               exit(1);
-       }
-       sleep(1);
-       ret = security_server_set_pwd("history1", "history8", 0, 0);
-       if(ret != SECURITY_SERVER_API_ERROR_PASSWORD_REUSED)
-       {
-               printf("\nTC P21.%d failed. %d\n", i+2, ret);
-               exit(1);
-       }
-       printf("\nTC P21: PASSED\n\n");
-       sleep(1);
-
-       printf("TC P22: security_server_set_pwd(): Check Garbage collection\n");
-       ret = security_server_set_pwd("history1", "history12", 0, 0);
-       sprintf(buf1, "history12");
-       if(ret != SECURITY_SERVER_API_SUCCESS)
-       {
-               printf("\nTC P22.1 failed. %d\n", i+1, ret);
-               exit(1);
-       }
-       printf("12\n");
-       sleep(1);
-       for(i=12;i<60;i++)
-       {
-               sprintf(buf1, "history%d", i);
-               sprintf(buf2, "history%d", i+1);
-               ret = security_server_set_pwd(buf1, buf2, 0, 0);
-               if(ret != SECURITY_SERVER_API_SUCCESS)
-               {
-                       printf("\nTC P22.%d failed. %d\n", i+1, ret);
-                       exit(1);
-               }
-               printf("%d\n", i+1);
-               sleep(1);
-       }
-       ret = scandir("/opt/data/security-server", &mydirent, &dir_filter, alphasort);
-       i = ret;
-       while((i--))
-       {
-               free(mydirent[i]);
-       }
-       free(mydirent);
-       if( ret == 50 || ret == 51)
-       {
-               printf("\nTC P22: PASSED\n\n");
-               sleep(1);
-       }
-       else
-       {
-               printf("\nTC P22 failed. %d", ret);
-               exit(1);
-       }
-       printf("TC P23: security_server_chk_pwd(): incorrect with replay attack\n");
-       ret = security_server_chk_pwd("quickquickquick", &attempt, &max_attempt, &expire_sec);
-       do
-       {
-               i =  i + 100000;
-               ret = security_server_chk_pwd("quickquickquick", &attempt, &max_attempt, &expire_sec);
-               usleep(i);
-       }
-       while(ret == SECURITY_SERVER_API_ERROR_PASSWORD_RETRY_TIMER);
-
-       if(ret != SECURITY_SERVER_API_ERROR_PASSWORD_MISMATCH )
-       {
-               printf("TC P23 failed[1]. %d\n", ret);
-               exit(1);
-       }
-       i = i - 100000;
-       printf("Last interval was %d.%06d sec.\n", (i /1000000), (i % 1000000) );
-       printf("TC P23: PASSED\n\n");
-
-       printf("TC P24: security_server_chk_pwd(): wrong challenge on expired password\n");
-       sleep(2);
-       ret = security_server_set_pwd("history60", "newpwd23", 4, 1);
-    if(ret != SECURITY_SERVER_API_SUCCESS)
-    {
-        printf("TC P24 failed[1]. %d\n", ret);
-        exit(1);
-    }
-    sleep(2);
-       ret = security_server_chk_pwd("newpwd23", &attempt, &max_attempt, &expire_sec);
-    if(ret != SECURITY_SERVER_API_SUCCESS)
-    {
-        printf("TC P24 failed[2]. %d\n", ret);
-        exit(1);
-    }
-
-       ret = gettimeofday(&cur_time, NULL);
-    if(ret < 0)
-    {
-        printf("TC P24 failed[3]. %d\n", ret);
-        exit(1);
-    }
-    cur_time.tv_sec += (expire_sec + 1);
-    ret = settimeofday(&cur_time, NULL);
-    if(ret < 0)
-    {
-        printf("TC P24 failed[4]. %d\n", ret);
-        exit(1);
-    }
-    sleep(2);
-    ret = security_server_chk_pwd("newpwd23", &attempt, &max_attempt, &expire_sec);
-    if(ret != SECURITY_SERVER_API_ERROR_PASSWORD_EXPIRED)
-    {
-        printf("TC P24 failed[5]. %d\n", ret);
-        exit(1);
-    }
-    sleep(2);
-    ret = security_server_chk_pwd("newpwd23_invalid", &attempt, &max_attempt, &expire_sec);
-    if(ret != SECURITY_SERVER_API_ERROR_PASSWORD_MISMATCH)
-    {
-        printf("TC P24 failed[6]. %d\n", ret);
-        exit(1);
-    }
-    printf("TC P24: PASSED\n\n");
-       return 0;
-}
-
diff --git a/testcases/security_server_tc_pid_reuser.c b/testcases/security_server_tc_pid_reuser.c
deleted file mode 100644 (file)
index 6f3c1df..0000000
+++ /dev/null
@@ -1,173 +0,0 @@
-/*
- * security server
- *
- * Copyright (c) 2000 - 2010 Samsung Electronics Co., Ltd.
- *
- * Contact: Bumjin Im <bj.im@samsung.com>
- *
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <errno.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-#include <unistd.h>
-#include "security-server.h"
-#include "test.h"
-
-void printusage(const char *cmdline)
-{
-       printf("%s\n", "Usage: ");
-       printf("%s [uid] [pid] [hexa decimal cookie]\n", cmdline);
-       printf("%s\n", "[pid]: PID want to be reused");
-       printf("%s\n", "[hexa decimal cookie]: Cookie value which is issued to the previous process with the [pid] for comparison\nThe cookie must be hexa decimal, with lower case and without whitespace and new line characters\n");
-       printf("%s\n", "* This test program must be executed as root process");
-}
-
-void printhex(unsigned char *data, int size)
-{
-       int i;
-       for(i=0;i<size;i++)
-       {
-               if(data[i] < 0x10)
-                       printf("0");
-
-               printf("%X ", data[i]);
-               if(((i+1) % 16) == 0 && i != 0)
-                       printf("\n");
-       }
-       printf("\n");
-}
-
-void convert_prev_cookie(const char *cmdline, const char *prev, unsigned char *now)
-{
-       int i, cnt;
-       char tmphexnum[3] = {0};
-       cnt = security_server_get_cookie_size();
-       cnt = cnt * 2;
-       if(strlen(prev) != cnt)
-       {
-               printf("%s\n", "Cookie lenth is wrong");
-               printusage(cmdline);
-               exit(1);
-       }
-
-       for(i=0, cnt=0 ; i<strlen(prev) ; i=i+2)
-       {
-               strncpy(tmphexnum, prev+i, 2);
-               tmphexnum[2] = 0;
-               errno = 0;
-               now[cnt] = strtoul(tmphexnum, 0, 16);
-               if(errno != 0)
-               {
-                       printf("%s\n", "cannot convert hex cookie to binary");
-                       printusage(cmdline);
-                       exit(1);
-               }
-               cnt++;
-       }
-}
-
-void check_status()
-{
-       struct stat statbuf;
-       int ret;
-       ret = stat("/opt/home/root/pid_cycle", &statbuf);
-       if(ret != 0)
-       {
-               printf("Interrupt encountered. exiting...\n");
-               exit(0);
-       }
-       
-}
-
-void cycle_pid(int pid)
-{
-       int cur_pid = getpid();
-       int dotval;
-       
-       while(cur_pid != pid)
-       {
-               if(fork() != 0)
-               {
-                       dotval = cur_pid % 1000;
-                       if(dotval == 0)
-                               printf(".");
-                       exit(0);
-               }
-               cur_pid = getpid();
-               check_status();
-       }
-}
-
-int main(int argc, char *argv[])
-{
-       int ret, sock_fd, cookie_size, target_pid, target_uid;
-
-       target_uid = getuid();
-       if(target_uid != 0)
-       {
-               printusage(argv[0]);
-               exit(1);
-       }
-
-       cookie_size = security_server_get_cookie_size();
-       unsigned char prev_cookie[cookie_size], new_cookie[cookie_size];
-
-       if(argc < 3)
-       {
-               printusage(argv[0]);
-               exit(1);
-       }
-
-       errno = 0;
-       target_uid = strtoul(argv[1], 0, 10);
-       if(errno != 0)
-       {
-               printf("%s\n", "cannot convert string uid to integer");
-               printusage(argv[0]);
-               exit(1);
-       }
-       printf("Target UID is %d. change user...\n", target_uid);
-       setuid(target_uid);
-
-       errno = 0;
-       target_pid = strtoul(argv[2], 0, 10);
-       if(errno != 0)
-       {
-               printf("%s\n", "cannot convert string pid to integer");
-               printusage(argv[0]);
-               exit(1);
-       }
-       convert_prev_cookie(argv[0], argv[3], prev_cookie);
-       check_status();
-
-       printf("Cycling PID to %d\n", target_pid);
-
-       cycle_pid(target_pid);
-       unlink("/opt/home/root/pid_cycle");
-
-       ret = security_server_request_cookie(new_cookie, 20);
-       if(ret != SECURITY_SERVER_API_SUCCESS)
-       {
-               printf("get cookie failed. %d\n", ret);
-               exit(1);
-       }
-       printf("\nTarget PID: %d, Target UID: %d\n", target_pid, target_uid);
-       printf("Previous cookie:\n");
-       printhex(prev_cookie, 20);
-       printf("Newly issued cookie:\n");
-       printhex(new_cookie, 20);
-       
-       if(memcmp(prev_cookie, new_cookie, cookie_size) == 0)
-       {
-               printf("TC failed. same cookie\n");
-               exit(1);
-       }
-       
-       printf("TC C8: PASSED\n");
-       return 0;
-}
-
diff --git a/testcases/security_server_tc_server.c b/testcases/security_server_tc_server.c
deleted file mode 100644 (file)
index 6d8247b..0000000
+++ /dev/null
@@ -1,757 +0,0 @@
-/*
- * security server
- *
- * Copyright (c) 2000 - 2010 Samsung Electronics Co., Ltd.
- * Contact: Bumjin Im <bj.im@samsung.com>
- *
- */
-
-#include <stdio.h>
-#include <errno.h>
-#include <stdlib.h>
-#include <sys/types.h>
-#include <sys/param.h>
-#include <fcntl.h>
-#include <sys/un.h>
-#include <unistd.h>
-#include <poll.h>
-#include <sys/socket.h>
-#include <sys/stat.h>
-#include "security-server.h"
-#include "test.h"
-
-
-#define SECURITY_SERVER_SOCK_PATH      "/tmp/.security_server.sock"
-
-/* 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;
-
-
-/* Create a Unix domain socket and bind */
-int create_new_socket()
-{
-       int localsockfd = 0, flags;
-       struct sockaddr_un serveraddr;
-       mode_t sock_mode;
-
-       remove(SECURITY_SERVER_TEST_SOCK_PATH);
-
-       /* Create Unix domain socket */
-       if((localsockfd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0 )
-       {
-               localsockfd = -1;
-               printf("%s\n", "Socket creation failed");
-               goto error;
-       }
-
-       /* Make socket as non blocking */
-       if((flags = fcntl(localsockfd, F_GETFL, 0)) < 0 ||
-                       fcntl(localsockfd, F_SETFL, flags | O_NONBLOCK) < 0)
-       {
-               close(localsockfd);
-               localsockfd = -1;
-               printf("%s\n", "Cannot go to nonblocking mode");
-               goto error;
-       }
-
-       bzero (&serveraddr, sizeof(serveraddr));
-       serveraddr.sun_family = AF_UNIX;
-       strncpy(serveraddr.sun_path, SECURITY_SERVER_TEST_SOCK_PATH,
-                       strlen(SECURITY_SERVER_TEST_SOCK_PATH) + 1);
-
-       /* Bind the socket */
-       if((bind(localsockfd, (struct sockaddr *)&serveraddr, sizeof(serveraddr))) < 0)
-       {
-               printf("%s\n", "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_TEST_SOCK_PATH, sock_mode) < 0)                /* Flawfinder: ignore */
-       {
-               printf("%s\n", "chmod() error");
-               close(localsockfd);
-               localsockfd = -1;
-               goto error;
-       }
-error:
-       return localsockfd;
-}
-
-void printhex(unsigned char *data, int size)
-{
-       int i;
-       for(i=0;i<size;i++)
-       {
-               if(data[i] < 0x10)
-                       printf("0");
-
-               printf("%X ", data[i]);
-               if(((i+1) % 16) == 0 && i != 0)
-                       printf("\n");
-       }
-       printf("\n");
-}
-
-int check_socket_poll(int sockfd, int event, int timeout)
-{
-       struct pollfd poll_fd[1];
-       int retval;
-
-       poll_fd[0].fd = sockfd;
-       poll_fd[0].events = event;
-       retval = poll(poll_fd, 1, timeout);
-       if(retval < 0)
-       {
-               printf("%s", "poll() error");
-               return -1;
-       }
-
-       /* Timed out */
-       if(retval == 0)
-       {
-               /*SEC_SVR_DBG("%s", "poll() timeout");*/
-               return 0;
-       }
-       return 1;
-}
-
-int send_gid_request(int sock_fd, const char* object)
-{
-       basic_header hdr;
-       int retval, send_len = 0;
-       unsigned char *buf = NULL;
-
-       hdr.version = 0x01; /* SECURITY_SERVER_MSG_VERSION; */
-       hdr.msg_id = 0x07; /* SECURITY_SERVER_MSG_TYPE_GID_REQUEST; */
-       hdr.msg_len = strlen(object);
-
-       send_len = sizeof(hdr) + strlen(object);
-
-       buf = malloc(send_len);
-       if(buf == NULL)
-       {
-               printf("%s", "out of memory");
-               return -1;
-       }
-
-       memcpy(buf, &hdr, sizeof(hdr));
-       memcpy(buf + sizeof(hdr), object, strlen(object));
-
-       /* Check poll */
-       retval = check_socket_poll(sock_fd, POLLOUT, 1000);
-       if(retval == -1)
-       {
-               printf("%s", "poll() error");
-               if(buf != NULL)
-                       free(buf);
-               return -1;
-       }
-       if(retval == 0)
-       {
-               printf("%s", "poll() timeout");
-               if(buf != NULL)
-                       free(buf);              
-               return -1;
-       }
-
-       retval = write(sock_fd, buf, send_len);
-       if(retval < send_len)
-       {
-               /* Write error */
-               printf("Error on write(): %d. errno=%d, sockfd=%d", retval, errno, sock_fd);
-               if(buf != NULL)
-                       free(buf);
-               return -1;
-       }
-       if(buf != NULL)
-               free(buf);
-
-       return 0;       
-}
-
-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)
-       {
-               printf("%s", "Error on socket()");
-               return -1;
-       }
-
-       /* Make socket as non blocking */
-       if((flags = fcntl(localsockfd, F_GETFL, 0)) < 0 || 
-                       fcntl(localsockfd, F_SETFL, flags | O_NONBLOCK) < 0)
-       {
-               close(localsockfd);
-               printf("%s", "Cannot go to nonblocking mode");
-               return -1;
-       }
-
-       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)
-               {
-                       printf("%s", "Connection is in progress");
-                       check_socket_poll(localsockfd, POLLOUT, 1000);
-                       if(ret == -1)
-                       {
-                               printf("%s", "poll() error");
-                               close(localsockfd);
-                               return -1;
-                       }
-                       if(ret == 0)
-                       {
-                               printf("%s", "poll() timeout");
-                               close(localsockfd);
-                               return -1;
-                       }
-                       ret = connect(localsockfd, (struct sockaddr*)&clientaddr, client_len);
-                       if(ret < 0)
-                       {
-                               printf("%s", "connection failed");
-                               close(localsockfd);
-                               return -1;
-                       }
-               }
-               else
-               {
-                       printf("%s", "Connection failed");
-                       close(localsockfd);
-                       return -1;
-               }
-       }
-
-       *fd = localsockfd;
-       return 0;
-}
-
-
-int fake_get_gid(const char *object)
-{
-        int sockfd = -1, retval, gid;
-     response_header hdr;
-     retval = connect_to_server(&sockfd);
-     if(retval != 0)
-     {
-         /* Error on socket */
-         printf("Connection failed: %d", retval);
-         goto error;
-     }
-    /* make request packet and send to server*/
-     retval = send_gid_request(sockfd, object);
-     if(retval != 0)
-     {
-         /* Error on socket */
-         printf("Send request failed: %d", retval);
-         goto error;
-     }
-        printf("%s", "Just closing the socket and exit\n");
-
-error:
-        if(sockfd > 0)
-                close(sockfd);
-
-        return 0;
-}
-
-
-int main(int argc, char *argv[])
-{
-       int server_sockfd, client_sockfd, ret, recved_gid, client_len, i;
-       unsigned char cookie[20], recved_cookie[20], recvbuf[33], wrong_cookie[20];
-       char obj_name[30];
-       struct pollfd accept_poll[1], client_poll[1];
-       struct sockaddr_un clientaddr;
-        int olen, alen;
-        char olabel[1024];
-        char arights[32];
-
-       ret = getuid();
-       if(ret != 0)
-       {
-               printf("TC must be executed by root\n");
-               exit(1);
-       }
-
-       printf("TC S1: Getting default cookie\n");
-       ret = security_server_request_cookie(cookie, 20);
-       if(ret != SECURITY_SERVER_API_SUCCESS)
-       {
-               printf("TC S1 failed to get cookie. %d\n", ret);
-               exit(1);
-       }
-       printhex(cookie, 20);
-       printf("TC S1: PASSED\n\n");
-       sleep(1);
-
-       printf("TC S2: security_server_get_gid(): normal case. trying to get GID of \"tel_gprs\" \n");
-       ret = security_server_get_gid("tel_gprs");
-       if(ret < 0)
-       {
-               printf("Test failed: %d\n", ret);
-               exit(-1);
-       }
-       printf("TC S2: PASSED with gid %d\n\n", ret);
-       sleep(1);
-
-       printf("TC S3: security_server_get_gid(): empty object name\n");
-       ret = security_server_get_gid("");
-       if(ret != SECURITY_SERVER_API_ERROR_INPUT_PARAM)
-       {
-               printf("Test failed: %d\n", ret);
-               exit(-1);
-       }
-       printf("TC S3: PASSED\n\n");
-       sleep(1);
-
-       printf("TC S4: security_server_get_gid(): wrong object name. \"teltel\"\n");
-       ret = security_server_get_gid("teltel");
-       if(ret != SECURITY_SERVER_API_ERROR_NO_SUCH_OBJECT)
-       {
-               printf("Test failed: %d\n", ret);
-               exit(-1);
-       }
-       printf("TC S4: PASSED\n\n");
-       sleep(1);
-
-       printf("TC S5: security_server_get_object_name(): normal case. trying 6001\n");
-       ret = security_server_get_object_name(6001, obj_name, sizeof(obj_name));
-       if(ret != SECURITY_SERVER_API_SUCCESS)
-       {
-               printf("Test failed: %d\n", ret);
-               exit(-1);
-       }
-       printf("Result: %s\n", obj_name);
-       printf("TC S5: PASSED\n\n");
-       sleep(1);
-
-       printf("TC S6: security_server_get_object_name(): Too small buffer size\n");
-       ret = security_server_get_object_name(6001, obj_name, 5);
-       if(ret != SECURITY_SERVER_API_ERROR_BUFFER_TOO_SMALL)
-       {
-               printf("Test failed: %d\n", ret);
-               exit(-1);
-       }
-       printf("TC S6: PASSED\n\n");
-       sleep(1);
-
-       printf("TC S7: security_server_get_object_name(): Invalid gid\n");
-       ret = security_server_get_object_name(9876, obj_name, sizeof(obj_name));
-       if(ret != SECURITY_SERVER_API_ERROR_NO_SUCH_OBJECT)
-       {
-               printf("Test failed: %d\n", ret);
-               exit(-1);
-       }
-       printf("TC S7: PASSED\n\n");
-       sleep(1);
-
-       printf("TC S8: Ask for priviege with default cookie. Normal case to check \"audio\" privilege \n");
-       ret = security_server_get_gid("audio");
-       ret = security_server_check_privilege(cookie, ret);
-       if(ret != SECURITY_SERVER_API_SUCCESS)
-       {
-               printf("Test failed: %d\n", ret);
-               exit(-1);
-       }
-       printf("TC S8: PASSED\n\n");
-       sleep(1);
-
-       printf("TC S9: Ask for priviege with default cookie. with wrong cookie \n");
-       ret = security_server_get_gid("audio");
-       srand(time(NULL));
-       for(i=0;i<20;i++)
-               wrong_cookie[i] = rand() % 255;
-
-       ret = security_server_check_privilege(wrong_cookie, ret);
-       if(ret != SECURITY_SERVER_API_ERROR_ACCESS_DENIED)
-       {
-               printf("Test failed: %d\n", ret);
-               exit(-1);
-       }
-       printf("TC S9: PASSED\n\n");
-       sleep(1);
-
-       printf("TC S10: Close socket just after sending request msg. This is done not by library call with simulating security_server_get_gid() API \n");
-       ret = fake_get_gid("audio");
-       printf("TC S10: Watch whether security server has crhashed or not.\n\n");
-       sleep(1);
-
-       printf("TC S11: get PID of a given cookie --> default cookie case \n");
-       ret = security_server_get_cookie_pid(cookie);
-       if(ret != 0)
-       {
-               printf("Test failed: %d\n", ret);
-               exit(-1);
-       }
-       printf("TC S11: PASSED\n\n");
-       sleep(1);
-
-       printf("TC S12: get PID of a given cookie --> non existing cookie \n");
-       ret = security_server_get_cookie_pid(wrong_cookie);
-       if(ret != SECURITY_SERVER_API_ERROR_NO_SUCH_COOKIE)
-       {
-               printf("Test failed: %d\n", ret);
-               exit(-1);
-       }
-       printf("TC S12: PASSED\n\n");
-       sleep(1);
-
-       printf("TC S13: get PID of a given cookie --> NULL cookie \n");
-       ret = security_server_get_cookie_pid(NULL);
-       if(ret != SECURITY_SERVER_API_ERROR_INPUT_PARAM)
-       {
-               printf("Test failed: %d\n", ret);
-               exit(-1);
-       }
-       printf("TC S13: PASSED\n\n");
-       sleep(1);
-
-       printf("TC S14: Communicating with client and test cookie and privilege control \n");
-       printf("\tWaiting for client...\n");
-       server_sockfd = create_new_socket();
-       if(server_sockfd < 1)
-       {
-               printf("Error on creating a new socket\n");
-               printf("Test failed: %d\n", ret);
-               exit(1);
-       }
-
-       if(listen(server_sockfd, 5) < 0)
-       {
-               printf("%s\n", "listen() failed. exiting...");
-               printf("Test failed: %d\n", ret);
-               goto error;
-       }
-
-       while(1)
-       {       
-               accept_poll[0].fd = server_sockfd;
-               accept_poll[0].events = POLLIN;
-               ret = poll(accept_poll, 1, 5000);
-
-               /* Call poll() to wait for socket connection */
-               ret = poll(accept_poll, 1, 5000);
-               if(ret < 0)
-               {
-                       printf("%s\n", "poll() error");
-                       printf("Test failed: %d\n", ret);
-                       goto error;
-               }
-               if(ret == 0)
-               {
-                       continue;
-               }
-
-               errno = 0;
-               client_len = sizeof(clientaddr);
-               client_sockfd = accept(server_sockfd,
-                               (struct sockaddr *)&clientaddr,
-                               &client_len);
-               if(client_sockfd < 0)
-               {
-                       printf("Cannot accept client. errno=%d\n", errno);
-                       printf("Test failed: %d\n", ret);
-                       goto error;
-               }
-
-               printf("New session accepted\n");
-
-               /* Wait until packet received */
-               client_poll[0].fd = client_sockfd;
-               client_poll[0].events = POLLIN;
-
-               /* Poll here */
-               ret = poll(client_poll, 1, 500);
-               if(ret < 0)
-               {
-                       printf("%s\n", "poll() error");
-                       printf("Test failed: %d\n", ret);
-                       goto error;
-               }
-               if(ret == 0)
-               {
-                       close(client_sockfd);
-                       client_sockfd = 0;
-                       printf("%s\n", "No request from client. closing socket");
-                       continue;
-               }
-
-               ret = read(client_sockfd, recvbuf, 4);
-               if(recvbuf[0] == 0 && recvbuf[1] == 0 && recvbuf[2] == 0 && recvbuf[3] == 0)
-               {
-                       ret = read(client_sockfd, recvbuf, 24);
-                       if(ret < 24)
-                       {
-                               close(client_sockfd);
-                               printf("cannot read request:%d\n", ret);
-                               close(client_sockfd);
-                               continue;
-                       }
-
-                       memcpy(recved_cookie, recvbuf, 20);
-                       memcpy(&recved_gid, recvbuf+20, sizeof(int));
-
-                       printf("requested cookie: \n");
-                       printhex(recved_cookie, 20);
-                       printf("requested gid: %d\n", recved_gid);
-
-                       ret = security_server_check_privilege(recved_cookie, recved_gid);
-                       if(ret != SECURITY_SERVER_API_SUCCESS && ret != SECURITY_SERVER_API_ERROR_ACCESS_DENIED)
-                       {
-                               printf("Unexpected error occurred: %d\n");
-                               printf("Test failed: %d\n", ret);
-                               goto error;
-                       }
-
-                       printf("Privilege for the request: %d\n", ret);
-
-                       ret = write(client_sockfd, &ret, sizeof(int));
-                       if(ret < sizeof(int))
-                       {
-                               printf("Send error: %d\n", ret);
-                               printf("Test failed: %d\n", ret);
-                               goto error;
-                       }
-
-                       ret = security_server_get_cookie_pid(recved_cookie);
-                       {
-                               if(ret < 0)
-                               {
-                                       printf("Unexpected error occurred: %d\n", ret);
-                                       printf("Test failed: %d\n", ret);
-                                       goto error;
-                               }
-                               if(ret == 0)
-                               {
-                                       printf("client is root process\n");
-                               }
-                               else
-                               {
-                                       printf("Peer PID is %d\n", ret);
-                               }
-                       }
-               }
-               else if(recvbuf[0] == 255 && recvbuf[1] == 255 && recvbuf[2] == 255 && recvbuf[3] == 255)
-                       {
-                               char *myargv[5] = {NULL};
-                               int i, cnt;
-                               ret = read(client_sockfd, recvbuf, 28);
-                               if(ret < 28)
-                               {
-                                       close(client_sockfd);
-                                       printf("cannot read request:%d\n", ret);
-                                       close(client_sockfd);
-                                       continue;
-                               }
-
-                               memcpy(recved_cookie, recvbuf, 20);
-                               memcpy(&recved_gid, recvbuf + 20, sizeof(int));
-                               memcpy(&cnt, recvbuf + 24, sizeof(int));
-
-                               if(fork() == 0)
-                               {
-                                       myargv[0] = malloc(strlen("/opt/home/root/security_server_tc_pid_reuser") + 1);
-                                       sprintf(myargv[0], "/opt/home/root/security_server_tc_pid_reuser");
-                                       myargv[1] = malloc(6);
-                                       sprintf(myargv[1], "%d", cnt);
-                                       myargv[2] = malloc(6);
-                                       sprintf(myargv[2], "%d", recved_gid);
-                                       myargv[3] = malloc(40);
-                                       myargv[4] = NULL;
-                                       for(i=0, cnt=0;i<20;i++)
-                                       {
-                                               if(recved_cookie[i] < 0x10)
-                                                       sprintf(myargv[3] + cnt, "0%x", recved_cookie[i]);
-                                               else
-                                                       sprintf(myargv[3] + cnt, "%x", recved_cookie[i]);
-                                               cnt += 2;
-                                       }
-                                       printf("argv[0]=%s, argv[1]=%s, argv[2]=%s, argv[3]=%s\n", myargv[0], myargv[1], myargv[2], myargv[3]);
-                                       ret = execve("/opt/home/root/security_server_tc_pid_reuser", myargv, NULL);
-                                       printf("execve failed. errno=%d\n", errno);
-
-                                       if(myargv[0] != NULL)
-                                               free(myargv[0]);
-                                       if(myargv[1] != NULL)
-                                               free(myargv[1]);
-                                       if(myargv[2] != NULL)
-                                               free(myargv[2]);
-                                       if(myargv[3] != NULL)
-                                               free(myargv[3]);
-                               }
-                       }
-               else if(recvbuf[0] == 17 )
-                {
-                    if (recvbuf[3] == 0)
-                    {
-                       ret = read(client_sockfd, recvbuf, 20);
-                       if(ret < 20)
-                       {
-                               close(client_sockfd);
-                               printf("cannot read request:%d\n", ret);
-                               close(client_sockfd);
-                               continue;
-                       }
-                       memcpy(recved_cookie, recvbuf, 20);
-                        ret = read(client_sockfd, &olen, 4);
-                       if(ret < 4)
-                       {
-                               close(client_sockfd);
-                               printf("cannot read request:%d\n", ret);
-                               close(client_sockfd);
-                               continue;
-                       }
-                        ret = read(client_sockfd, &alen, 4);
-                       if(ret < 4)
-                       {
-                               close(client_sockfd);
-                               printf("cannot read request:%d\n", ret);
-                               close(client_sockfd);
-                               continue;
-                       }
-                        ret = read(client_sockfd, olabel, olen);
-                       if(ret < olen)
-                       {
-                               close(client_sockfd);
-                               printf("cannot read request:%d\n", ret);
-                               close(client_sockfd);
-                               continue;
-                       }
-                        olabel[olen] = '\0';
-                        ret = read(client_sockfd, arights, alen);
-                       if(ret < alen)
-                       {
-                               close(client_sockfd);
-                               printf("cannot read request:%d\n", ret);
-                               close(client_sockfd);
-                               continue;
-                       }
-                        arights[alen] = '\0';
-                       printf("Check by cookie requested.\n");
-                       printf("requested cookie: \n");
-                       printhex(recved_cookie, 20);
-                        printf("olen: %d\n", olen);
-                        printf("object label: >%s<\n", olabel);
-                        printf("alen: %d\n", alen);
-                        printf("access rights: >%s<\n", arights);
-
-                        ret = security_server_check_privilege_by_cookie(
-                                  recved_cookie, olabel, arights);
-
-                        printf("return: %d\n", ret);
-
-                       ret = write(client_sockfd, &ret, sizeof(int));
-                       if(ret < sizeof(int))
-                       {
-                               printf("Send error: %d\n", ret);
-                               printf("Test failed: %d\n", ret);
-                               goto error;
-                       }
-                    }
-                    else if (recvbuf[3] == 1)
-                    {
-                        ret = read(client_sockfd, &olen, 4);
-                       if(ret < 4)
-                       {
-                               close(client_sockfd);
-                               printf("cannot read request:%d\n", ret);
-                               close(client_sockfd);
-                               continue;
-                       }
-                        ret = read(client_sockfd, &alen, 4);
-                       if(ret < 4)
-                       {
-                               close(client_sockfd);
-                               printf("cannot read request:%d\n", ret);
-                               close(client_sockfd);
-                               continue;
-                       }
-                        ret = read(client_sockfd, olabel, olen);
-                       if(ret < olen)
-                       {
-                               close(client_sockfd);
-                               printf("cannot read request:%d\n", ret);
-                               close(client_sockfd);
-                               continue;
-                       }
-                        olabel[olen] = '\0';
-                        ret = read(client_sockfd, arights, alen);
-                       if(ret < alen)
-                       {
-                               close(client_sockfd);
-                               printf("cannot read request:%d\n", ret);
-                               close(client_sockfd);
-                               continue;
-                       }
-                        arights[alen] = '\0';
-                       printf("Check by sockfd requested.\n");
-                        printf("olen: %d\n", olen);
-                        printf("object label: >%s<\n", olabel);
-                        printf("alen: %d\n", alen);
-                        printf("access rights: >%s<\n", arights);
-
-                        ret = security_server_check_privilege_by_sockfd(
-                                  client_sockfd, olabel, arights);
-
-                       ret = write(client_sockfd, &ret, sizeof(int));
-                       if(ret < sizeof(int))
-                       {
-                               printf("Send error: %d\n", ret);
-                               printf("Test failed: %d\n", ret);
-                               goto error;
-                       }
-                    } else {
-                       printf("malformed request. %d, %d, %d, %d\n", recvbuf[0], recvbuf[1], recvbuf[2], recvbuf[3]);
-                       printf("Test failed: %d\n", ret);
-                       goto error;
-                    }
-                }
-               else
-               {
-                       printf("malformed request. %d, %d, %d, %d\n", recvbuf[0], recvbuf[1], recvbuf[2], recvbuf[3]);
-                       printf("Test failed: %d\n", ret);
-                       goto error;
-               }
-               if(client_sockfd > 0)
-               {
-                       close(client_sockfd);
-               }
-       }
-error:
-       if(server_sockfd > 0)
-               close(server_sockfd);
-       if(client_sockfd > 0)
-               close(client_sockfd);
-}
diff --git a/testcases/test.h b/testcases/test.h
deleted file mode 100644 (file)
index 076c992..0000000
+++ /dev/null
@@ -1,9 +0,0 @@
-/*
- * security server
- *
- * Copyright (c) 2000 - 2010 Samsung Electronics Co., Ltd.
- * Contact: Bumjin Im <bj.im@samsung.com>
- *
- */
-
-#define SECURITY_SERVER_TEST_SOCK_PATH "/tmp/.security-server-test"
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..af65d6f
--- /dev/null
@@ -0,0 +1,57 @@
+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
+    ${WRT_OCSP_SRC_DIR}/wrt_ocsp_api.cpp
+    )
+
+SET(WRT_OCSP_INCLUDES
+    ${WRT_OCSP_DEPS_INCLUDE_DIRS}
+    ${WRT_OCSP_INCLUDE_DIR}
+    ${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..5349a8d
--- /dev/null
@@ -0,0 +1,81 @@
+/*
+ * 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 "security_daemon_dbus_config.h"
+
+#include "wrt_ocsp_api.h"
+
+static DPL::DBus::Client *dbusClient = NULL;
+
+wrt_ocsp_return_t wrt_ocsp_initialize(void){
+  if (NULL != dbusClient) {
+    LogError("wrt_ocsp_api already initialized");
+    return WRT_OCSP_INTERNAL_ERROR;
+  }
+  Try {
+    dbusClient = new DPL::DBus::Client(
+      WrtSecurity::SecurityDaemonConfig::OBJECT_PATH(),
+      WrtSecurity::SecurityDaemonConfig::SERVICE_NAME(),
+      WrtSecurity::OcspServerApi::INTERFACE_NAME());
+
+  } Catch (DPL::DBus::Client::Exception::DBusClientException) {
+    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 == dbusClient) {
+    LogError("wrt_ocsp_api not initialized");
+    return WRT_OCSP_INTERNAL_ERROR;
+  }
+  delete dbusClient;
+  dbusClient = 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){
+
+  if (NULL == status) {
+    LogError("Invalid arguments");
+    return WRT_OCSP_INVALID_ARGUMENTS;
+  }
+  int intResponse;
+  Try {
+  dbusClient->call(WrtSecurity::OcspServerApi::CHECK_ACCESS_METHOD(),
+    handle,
+    &intResponse);
+  } Catch (DPL::DBus::Client::Exception::DBusClientException){
+    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;
+}