From: SEUNGTAEK HAN Date: Tue, 29 Mar 2016 08:28:02 +0000 (+0900) Subject: Add Privacy-Guard X-Git-Tag: accepted/tizen/common/20160330.120237^0 X-Git-Url: http://review.tizen.org/git/?p=platform%2Fcore%2Fsecurity%2Fprivacy-guard.git;a=commitdiff_plain;h=0093fbd6e25c2614f6ceef46ad91ccfa4d969b0e Add Privacy-Guard Change-Id: Ic9d21fd261dcb7204f809f5426368ad4d7799782 --- diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100755 index 0000000..4af725f --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,19 @@ +CMAKE_MINIMUM_REQUIRED(VERSION 2.6) + +MESSAGE("build privacy-guard") + +SET(CMAKE_VERBOSE_MAKEFILE OFF) + +IF("${USE_AUTOSTART}" STREQUAL "1") + ADD_DEFINITIONS("-DUSE_AUTOSTART") +ENDIF() + +ADD_DEFINITIONS("-DCLIENT_IPC_THREAD") +ADD_DEFINITIONS("-DUSE_IPC_EPOLL") + +STRING(REGEX MATCH "([^.]*)" API_VERSION "${VERSION}") +ADD_DEFINITIONS("-DAPI_VERSION=\"$(API_VERSION)\"") + +ADD_SUBDIRECTORY(server) +ADD_SUBDIRECTORY(client) +ADD_SUBDIRECTORY(pkgmgr_plugin) diff --git a/LICENSE.APLv2 b/LICENSE.APLv2 new file mode 100755 index 0000000..a795f06 --- /dev/null +++ b/LICENSE.APLv2 @@ -0,0 +1,204 @@ +Copyright (c) 2000 - 2011 Samsung Electronics Co., Ltd. All rights reserved. + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT 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/client/CMakeLists.txt b/client/CMakeLists.txt new file mode 100755 index 0000000..b769f8c --- /dev/null +++ b/client/CMakeLists.txt @@ -0,0 +1,92 @@ +CMAKE_MINIMUM_REQUIRED(VERSION 2.6) +#PROJECT(privacy-guard-client) + +SET(CMAKE_INSTALL_PREFIX /usr) +SET(PREFIX ${CMAKE_INSTALL_PREFIX}) +SET(EXEC_PREFIX "\${prefix}") +SET(LIBDIR ${LIB_INSTALL_DIR}) +SET(INCLUDEDIR ${INCLUDE_INSTALL_DIR}) + +INCLUDE(FindPkgConfig) +pkg_check_modules(privacy-guard-client REQUIRED dlog sqlite3 dbus-1 dbus-glib-1 db-util pkgmgr-info libtzplatform-config) + +FOREACH(flag ${pkgs_CFLAGS}) + SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}") +ENDFOREACH(flag) + +SET(CMAKE_C_FLAGS_PROFILING " -g -pg") +SET(CMAKE_CXX_FLAGS_PROFILING " -std=c++0x -g -pg") +SET(CMAKE_C_FLAGS_DEBUG " -g") +SET(CMAKE_CXX_FLAGS_DEBUG " -std=c++0x -g") +SET(CMAKE_C_FLAGS_RELEASE " -g") +SET(CMAKE_CXX_FLAGS_RELEASE " -std=c++0x -g") +SET(CMAKE_C_FLAGS_CCOV " -g --coverage") +SET(CMAKE_CXX_FLAGS_CCOV " -std=c++0x -g --coverage") + +SET(client_src_dir "${CMAKE_SOURCE_DIR}/client/src") +SET(client_include_dir "${CMAKE_SOURCE_DIR}/client/inc/") +SET(common_src_dir "${CMAKE_SOURCE_DIR}/common/src/") +SET(common_include_dir "${CMAKE_SOURCE_DIR}/common/inc/") +SET(extern_include_dir "${CMAKE_SOURCE_DIR}/include/") + +## Additional flag +ADD_DEFINITIONS("-fvisibility=hidden") +ADD_DEFINITIONS("-Wall -Werror") +ADD_DEFINITIONS("-DDLOG_ERROR_ENABLED") +ADD_DEFINITIONS("-D_PRIVACY_GUARD_DEBUG") +OPTION (FILTER_LISTED_PKG "FILTER PKG BY LIST" ON) +IF(FILTER_LISTED_PKG) + MESSAGE("FILTER PKGs BY FILTERING LIST") + ADD_DEFINITIONS("-D__FILTER_LISTED_PKG") +ENDIF(FILTER_LISTED_PKG) +## SET PRIVACY_POPUP FLAG +OPTION (PRIVACY_POPUP "PRIVACY_POPUP" ON) +IF(PRIVACY_POPUP) + MESSAGE("PRIVACY_POPUP IS ENABLED") + ADD_DEFINITIONS("-D__PRIVACY_POPUP") +ENDIF(PRIVACY_POPUP) + +################################################################################################### +## for libprivacy-guard-client (executable) +INCLUDE_DIRECTORIES(${pkgs_INCLUDE_DIRS} ${client_include_dir} ${common_include_dir} ${extern_include_dir}) +SET(PRIVACY_GUARD_CLIENT_SOURCES + ${common_src_dir}/SocketConnection.cpp + ${common_src_dir}/SocketStream.cpp + ${common_src_dir}/PrivacyIdInfo.cpp + ${client_src_dir}/SocketClient.cpp + ${client_src_dir}/PrivacyChecker.cpp + ${client_src_dir}/PrivacyGuardClient.cpp + ${client_src_dir}/privacy_guard_client.cpp + ) +SET(PRIVACY_GUARD_CLIENT_HEADERS + ${client_include_dir}/PrivacyChecker.h + ${client_include_dir}/PrivacyGuardClient.h + ${client_include_dir}/privacy_guard_client_internal.h + ) +SET(PRIVACY_GUARD_EXTERN_HEADERS + ${extern_include_dir}/privacy_guard_client.h + ${extern_include_dir}/privacy_guard_client_types.h + ) + +SET(PRIVACY_GUARD_CLIENT_LDFLAGS " -module -avoid-version ") +SET(PRIVACY_GUARD_CLIENT_CFLAGS " ${CFLAGS} -fPIC ") + +ADD_DEFINITIONS("-DLOG_TAG=\"PRIVACY-GUARD-CLIENT\"") +ADD_LIBRARY(privacy-guard-client SHARED ${PRIVACY_GUARD_CLIENT_SOURCES}) +TARGET_LINK_LIBRARIES(privacy-guard-client ${pkgs_LDFLAGS} ${pkgs_LIBRARIES}) +SET_TARGET_PROPERTIES(privacy-guard-client PROPERTIES COMPILE_FLAGS "${PRIVACY_GUARD_CLIENT_CFLAGS}") +SET_TARGET_PROPERTIES(privacy-guard-client PROPERTIES SOVERSION ${API_VERSION}) +SET_TARGET_PROPERTIES(privacy-guard-client PROPERTIES VERSION ${VERSION}) +################################################################################################### + +SET(PC_NAME privacy-guard-client) +SET(PC_DESCRIPTION "Privacy Guard Client API") +SET(PC_LDFLAGS -lprivacy-guard-client) +SET(PC_CFLAGS -I\${includedir}/privacy_guard) + +CONFIGURE_FILE(../privacy-guard-client.pc.in privacy-guard-client.pc @ONLY) + +INSTALL(TARGETS privacy-guard-client DESTINATION ${LIB_INSTALL_DIR} COMPONENT RuntimeLibraries) +INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/privacy-guard-client.pc DESTINATION ${LIB_INSTALL_DIR}/pkgconfig) +INSTALL(FILES ${PRIVACY_GUARD_CLIENT_HEADERS} DESTINATION ${INCLUDE_INSTALL_DIR}/privacy_guard/client) +INSTALL(FILES ${PRIVACY_GUARD_EXTERN_HEADERS} DESTINATION ${INCLUDE_INSTALL_DIR}/privacy_guard) \ No newline at end of file diff --git a/client/inc/PrivacyChecker.h b/client/inc/PrivacyChecker.h new file mode 100755 index 0000000..515592a --- /dev/null +++ b/client/inc/PrivacyChecker.h @@ -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. + */ + +#ifndef _PRIVACY_CHECKER_H_ +#define _PRIVACY_CHECKER_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include "PrivacyGuardTypes.h" + +struct sqlite3; + +class EXTERN_API PrivacyChecker +{ +private: + static std::map < std::string, bool > m_privacyCache; + static std::map < std::string, std::map < std::string, bool > > m_privacyInfoCache; + static std::map < std::string, int > m_monitorPolicyCache; + static std::string m_pkgId; + static bool m_isInitialized; + static bool m_isMonitorEnable; + static std::mutex m_cacheMutex; + static std::mutex m_dbusMutex; + static std::mutex m_initializeMutex; + static DBusConnection* m_pDBusConnection; + static GMainLoop* m_pLoop; + static GMainContext* m_pHandlerGMainContext; + static pthread_t m_signalThread; + +private: + static int initializeDbus(void); + static int finalizeDbus(void); + static int updateCache(const std::string pkgId, std::string privacyId, std::map < std::string, bool >& pkgCacheMap); + static int updateCache(const std::string pkgId, std::map < std::string, bool >& pkgCacheMap); + static void printCache(void); + static void* runSignalListenerThread(void* pData); + static int getCurrentPkgId(std::string& pkgId); + static int check(const std::string privacyId, std::map < std::string, bool >& privacyMap); + +public: + // for Checking in App Process + static int initialize(void); + static int check(const std::string pkgId, const std::string privacyId); + static int checkWithPrivilege(const std::string pkgId, const std::string privilegeId); + static int checkWithDeviceCap(const std::string pkgId, const std::string deviceCap); + + // for Checking in Server Process + static int initializeGMain(void); + static int check(const std::string privacyId); + static void checkMonitorByPrivilege(const std::string privilegeId); + static int checkWithPrivilege(const std::string privilegeId); + static int checkMonitorPolicyWithPrivilege(const int userId, const std::string packageId, const std::string privilegeId, std::string &privacyId, int &monitorPolicy); + static int checkWithDeviceCap(const std::string deviceCap); + static void printMonitorPolicyCache(void); + static int initMonitorPolicyCache(void); + static int getMonitorPolicy(const int userId, const std::string packageId, const std::string privacyId, int &monitorPolicy); + // common + static int finalize(void); + static DBusHandlerResult handleNotification(DBusConnection* connection, DBusMessage* message, void* user_data); +}; + +#endif // _PRIVACY_CHECKER_H_ diff --git a/client/inc/PrivacyGuardClient.h b/client/inc/PrivacyGuardClient.h new file mode 100755 index 0000000..4950d8e --- /dev/null +++ b/client/inc/PrivacyGuardClient.h @@ -0,0 +1,93 @@ +/* + * 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. + */ + +#ifndef _PRIVACYGUARDCLIENT_H_ +#define _PRIVACYGUARDCLIENT_H_ + +#include +#include +#include +#include +#include +#include "PrivacyGuardTypes.h" + +class SocketClient; + +class EXTERN_API PrivacyGuardClient +{ +private: + static PrivacyGuardClient* m_pInstance; + static const std::string INTERFACE_NAME; + + std::unique_ptr< SocketClient > m_pSocketClient; + + static std::mutex m_singletonMutex; + + std::list > logInfoList; + + PrivacyGuardClient(); + ~PrivacyGuardClient(); + +public: + static PrivacyGuardClient* getInstance(void); + + int PgAddPrivacyAccessLog(const int userId, const std::string packageId, const std::string privacyId); + + int PgAddPrivacyAccessLogTest(const int userId, const std::string packageId, const std::string privacyId); + + int PgAddPrivacyAccessLogBeforeTerminate(void); + + int PgAddMonitorPolicy(const int userId, const std::string pkgId, const std::list < std::string >& list, int monitorPolicy); + + int PgDeleteAllLogsAndMonitorPolicy(void); + + int PgDeleteLogsByPackageId(const std::string packageId); + + int PgDeleteMonitorPolicyByPackageId(const std::string packageId); + + int PgForeachTotalPrivacyCountOfPackage(const int userId, const int startDate, const int endDate, std::list < std::pair > & packageInfoList) const; + + int PgForeachTotalPrivacyCountOfPrivacy(const int userId, const int startDate, const int endDate, std::list < std::pair > & privacyInfoList) const; + + int PgForeachPrivacyCountByPrivacyId(const int userId, const int startDate, const int endDate, const std::string privacyId, std::list < std::pair > & packageInfoList) const; + + int PgForeachPrivacyCountByPackageId(const int userId, const int startDate, const int endDate, const std::string packageId, std::list < std::pair > & privacyInfoList) const; + + int PgForeachPrivacyPackageId(const int userId, std::list < std::string > & packageList) const; + + int PgForeachPackageByPrivacyId(const int userId, const std::string privacyId, std::list < std::string > & packageList) const; + + int PgForeachMonitorPolicyByPackageId(const int userId, const std::string packageId, + std::list & privacyInfoList) const; + + int PgGetMonitorPolicy(const int userId, const std::string packageId, + const std::string privacyId, int& monitorPolicy) const; + + int PgGetAllMonitorPolicy(std::list < std::pair < std::string, int > > & monitorPolicyList) const; + + int PgCheckPrivacyPackage(const int userId, const std::string packageId, bool &isPrivacyPackage); + + int PgUpdateMonitorPolicy(const int userId, const std::string packageId, + const std::string privacyId, const int monitorPolicy); + + int PgGetMainMonitorPolicy(const int userId, bool &mainMonitorPolicy) const; + + int PgUpdateMainMonitorPolicy(const int userId, const bool mainMonitorPolicy); + + int PgDeleteMainMonitorPolicyByUserId(const int userId); +}; + +#endif // _PRIVACYGUARDCLIENT_H_ \ No newline at end of file diff --git a/client/inc/SocketClient.h b/client/inc/SocketClient.h new file mode 100755 index 0000000..a9d0fd1 --- /dev/null +++ b/client/inc/SocketClient.h @@ -0,0 +1,159 @@ +/* + * 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. + */ + +#ifndef _SOCKETCLIENT_H_ +#define _SOCKETCLIENT_H_ + +#include +#include +#include +#include "SocketConnection.h" + +/* IMPORTANT: + * Methods connect(), call() and disconnected() should be called one by one. + * Between connect() and disconnect() you can use call() only once. + * It is because of timeout on call, e.g. to avoid waiting for corrupted data. + */ + +/* USAGE: + * Class should be used according to this scheme: + * SocketClient client("Interface Name"); + * (...) + * client.connect(); + * client.call("Method name", in_arg1, in_arg2, ..., in_argN, + * out_arg1, out_arg2, ..., out_argM); + * client.disconnect(); + * (...) + * + * input parameters of the call are passed with reference, + * output ones are passed as pointers - parameters MUST be passed this way. + * + * Currently client supports serialization and deserialization of simple types + * (int, char, float, unsigned), strings (std::string and char*) and + * some STL containers (std::vector, std::list, std::map, std::pair). + * Structures and classes are not (yet) supported. + */ + +#include +#include +#include + +class EXTERN_API SocketClient +{ +public: + + SocketClient(const std::string &interfaceName); + int connect(); + int disconnect(); + + int call(std::string methodName) + { + PF_LOGI("call m_interfaceName : %s, methodName : %s", m_interfaceName.c_str(), methodName.c_str()); + + int res = make_call(m_interfaceName); + PF_LOGI("call make_call interface res : %d", res); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "make_call : %d", res); + + res = make_call(methodName); + PF_LOGI("call make_call method res : %d", res); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "make_call : %d", res); + + return PRIV_FLTR_ERROR_SUCCESS; + } + + template + int call(std::string methodName, const Args&... args) + { + PF_LOGI("call Args m_interfaceName : %s, methodName : %s", m_interfaceName.c_str(), methodName.c_str()); + int res = make_call(m_interfaceName); + PF_LOGI("call Args make_call interface res : %d", res); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "make_call : %d", res); + res = make_call(methodName); + PF_LOGI("call Args make_call method res : %d", res); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "make_call : %d", res); + res = make_call(args...); + PF_LOGI("call Args make_call args res : %d", res); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "make_call : %d", res); + + return PRIV_FLTR_ERROR_SUCCESS; + } + + template + int read(T* outvalue) + { + return m_socketConnector->read(outvalue); + } +private: + template + int make_call(const T& invalue, const Args&... args) + { + int res = make_call(invalue); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "make_call : %d", res); + res = make_call(args...); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "make_call : %d", res); + + return PRIV_FLTR_ERROR_SUCCESS; + } + + template + int make_call(const T& invalue) + { + return m_socketConnector->write(invalue); + } + + template + int make_call(const T* invalue, const Args&... args) + { + int res = make_call(invalue); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "make_call : %d", res); + res = make_call(args...); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "make_call : %d", res); + + return PRIV_FLTR_ERROR_SUCCESS; + } + + template + int make_call(const T* invalue) + { + return m_socketConnector->write(invalue); + } + + template + int make_call(T * outvalue, const Args&... args) + { + int res = make_call(outvalue); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "make_call : %d", res); + res = make_call(args...); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "make_call : %d", res); + + return PRIV_FLTR_ERROR_SUCCESS; + } + + template + int make_call(T* outvalue) + { + return m_socketConnector->read(outvalue); + } + + +private: + std::string m_serverAddress; + std::string m_interfaceName; + std::unique_ptr m_socketConnector; + int m_socketFd; +}; + +#endif // _SOCKETCLIENT_H_ \ No newline at end of file diff --git a/client/inc/privacy_guard_client_internal.h b/client/inc/privacy_guard_client_internal.h new file mode 100755 index 0000000..9bf5ce2 --- /dev/null +++ b/client/inc/privacy_guard_client_internal.h @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file privacy_guard_client_internal.h + * @brief APIs for privacy-guard-client + */ + +#ifndef _PRIVACY_GUARD_CLIENT_INTERNAL_H_ +#define _PRIVACY_GUARD_CLIENT_INTERNAL_H_ + +#include +#include "privacy_guard_client_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @fn int privacy_guard_client_add_privacy_access_log(const int user_id, const char *package_id, const char *privacy_id) + * @brief add log for usage of privacy api to StatisticsMonitor DB + * @param[in] user_id user ID + * @param[in] package_id package ID + * @param[in] privacy_id privacy ID [e.g. http://tizen.org/privacy/contact] + * @return the result of operation (ERRORCODE : success, ....) + */ +EXTERN_API int privacy_guard_client_add_privacy_access_log(const int user_id, const char *package_id, const char *privacy_id); + +/** + * @fn int privacy_guard_client_delete_all_logs_and_monitor_policy(void) + * @brief clear all data from StatisticsMonitor and MonitorPolicy DB + */ +EXTERN_API int privacy_guard_client_delete_all_logs_and_monitor_policy(void); + +/** + * @fn int privacy_guard_client_add_monitor_policy(const int user_id, const char *package_id, const char **privilege_list, const int monitor_policy) + * @brief add monitor policy by user id and specified package to MonitorPolicy DB + * @param[in] user_id The user ID + * @param[in] package_id The package ID + * @param[in] privilege_list The privilege list + * @param[in] monitor_policy The monitor policy (0 or 1) + */ +EXTERN_API int privacy_guard_client_add_monitor_policy(const int user_id, const char *package_id, const char **privilege_list, const int monitor_policy); + +/** + * @fn int privacy_guard_client_delete_logs_by_package_id(const char *package_id) + * @brief remove statistics info by specified package from StatisticsMonitor DB + * @param[in] package_id package ID + */ +EXTERN_API int privacy_guard_client_delete_logs_by_package_id(const char *package_id); + +/** + * @fn int privacy_guard_client_delete_monitor_policy_by_package_id(const char *package_id) + * @brief remove statistics info by specified package from MonitorPolicy DB + * @param[in] package_id The package ID + */ +EXTERN_API int privacy_guard_client_delete_monitor_policy_by_package_id(const char *package_id); + +#ifdef __cplusplus +} +#endif + + +#endif //_PRIVACY_GUARD_CLIENT_INTERNAL_H_ + diff --git a/client/src/PrivacyChecker.cpp b/client/src/PrivacyChecker.cpp new file mode 100755 index 0000000..d8c72b5 --- /dev/null +++ b/client/src/PrivacyChecker.cpp @@ -0,0 +1,448 @@ +/* + * 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. + */ + +#include +#include +#include +#include +#include +#include +#include +#include "PrivacyChecker.h" +#include "PrivacyIdInfo.h" +#include "PrivacyGuardClient.h" +#include "SocketClient.h" +#include "Utils.h" + +bool PrivacyChecker::m_isInitialized = false; +bool PrivacyChecker::m_isMonitorEnable = false; +std::map < std::string, bool >PrivacyChecker::m_privacyCache; +std::map < std::string, std::map < std::string, bool > > PrivacyChecker::m_privacyInfoCache; +std::map < std::string, int > PrivacyChecker::m_monitorPolicyCache; +std::mutex PrivacyChecker::m_cacheMutex; +std::mutex PrivacyChecker::m_dbusMutex; +std::mutex PrivacyChecker::m_initializeMutex; +std::string PrivacyChecker::m_pkgId; +DBusConnection* PrivacyChecker::m_pDBusConnection; +GMainLoop* PrivacyChecker::m_pLoop = NULL; +GMainContext* PrivacyChecker::m_pHandlerGMainContext = NULL; +const int MAX_LOCAL_BUF_SIZE = 128; +pthread_t PrivacyChecker::m_signalThread; + +int +PrivacyChecker::initialize(void) +{ + if (m_isInitialized) { + return PRIV_FLTR_ERROR_SUCCESS; + } + + std::lock_guard < std::mutex > guard(m_cacheMutex); + + int res = initMonitorPolicyCache(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, ,"Failed to update cache (%d)", res); + + res = initializeGMain(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, ,"Failed to initialize() (%d)", res); + + return PRIV_FLTR_ERROR_SUCCESS; +} + +int +PrivacyChecker::initializeGMain(void) +{ + std::unique_lock initlock(m_initializeMutex); + + TryReturn(!m_isInitialized, PRIV_FLTR_ERROR_SUCCESS, , "Already Initalized"); + + m_pHandlerGMainContext = g_main_context_new(); + TryReturn(m_pHandlerGMainContext != NULL, PRIV_FLTR_ERROR_SYSTEM_ERROR, ,"cannot create m_pHandlerGMainContext"); + + m_pLoop = g_main_loop_new(m_pHandlerGMainContext, FALSE); + TryReturn(m_pLoop != NULL, PRIV_FLTR_ERROR_SYSTEM_ERROR, ,"cannot create m_pLoop"); + + std::unique_lock lock(m_dbusMutex); + int res = pthread_create(&m_signalThread, NULL, &runSignalListenerThread, NULL); + TryReturn(res >= 0, PRIV_FLTR_ERROR_SYSTEM_ERROR, errno = res;, "Failed to create listener thread :%s", strerror(res)); + + m_isInitialized = true; + + return PRIV_FLTR_ERROR_SUCCESS; +} + +void +PrivacyChecker::printMonitorPolicyCache(void) +{ + for(std::map::iterator itr = m_monitorPolicyCache.begin(); itr != m_monitorPolicyCache.end(); itr++) { + PF_LOGD("PRIVACY string : %s", itr->first.c_str()); + PF_LOGD("PRIVACY monitor_policy : %d", itr->second); + } +} + +int +PrivacyChecker::initMonitorPolicyCache(void) +{ + PF_LOGD("PrivacyChecker::initCache"); + + std::list < std::pair < std::string, int > > monitorPolicyList; + int retval = PrivacyGuardClient::getInstance()->PgGetAllMonitorPolicy(monitorPolicyList); + if(retval == PRIV_FLTR_ERROR_SUCCESS && !monitorPolicyList.empty()) { + m_monitorPolicyCache.insert(monitorPolicyList.begin(), monitorPolicyList.end()); + } + return retval; +} + +int +PrivacyChecker::getMonitorPolicy(const int userId, const std::string packageId, const std::string privacyId, int &monitorPolicy) +{ + PF_LOGD("getMonitorPolicy m_isInitialized : %d", m_isInitialized); + + if (m_isInitialized == false) { + initialize(); + } +// printMonitorPolicyCache(); + + std::string userPkgIdPrivacyId = std::to_string(userId) + std::string("|") + packageId + std::string("|") + privacyId; + PF_LOGD("key : %s", userPkgIdPrivacyId.c_str()); + std::map::iterator itr = m_monitorPolicyCache.find(userPkgIdPrivacyId); + int res = PRIV_FLTR_ERROR_SUCCESS; + if(itr != m_monitorPolicyCache.end()) { + monitorPolicy = itr->second; + } + else { + monitorPolicy = 0; + res = PRIV_FLTR_ERROR_NO_DATA; + } + PF_LOGD("Here3"); + return res; +} + +void +PrivacyChecker::checkMonitorByPrivilege(const std::string privilegeId) +{ + PF_LOGD("checkMonitorByPrivilege"); + + if(privilegeId.compare("http://tizen.org/privilege/calendar.read") == 0 || + privilegeId.compare("http://tizen.org/privilege/calendar.write") == 0 || + privilegeId.compare("http://tizen.org/privilege/contact.read") == 0 || + privilegeId.compare("http://tizen.org/privilege/contact.write") == 0 || + privilegeId.compare("http://tizen.org/privilege/location") == 0 || + privilegeId.compare("http://tizen.org/privilege/messaging.write") == 0 || + privilegeId.compare("http://tizen.org/privilege/messaging.read") == 0 || + privilegeId.compare("http://tizen.org/privilege/messaging.send") == 0 || + privilegeId.compare("http://tizen.org/privilege/messaging.sms") == 0 || + privilegeId.compare("http://tizen.org/privilege/messaging.mms") == 0 || + privilegeId.compare("http://tizen.org/privilege/messaging.email") == 0) { + m_isMonitorEnable = true; + } + else { + m_isMonitorEnable = false; + } +} + +int +PrivacyChecker::checkMonitorPolicyWithPrivilege(const int userId, const std::string packageId, const std::string privilegeId, std::string &privacyId, int &monitorPolicy) +{ + checkMonitorByPrivilege(privilegeId); + if (m_isMonitorEnable == true) { + int res = PrivacyIdInfo::getPrivacyIdFromPrivilege(privilegeId, privacyId); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "getPrivacyIdFromPrivilege : %d", res); + return getMonitorPolicy(userId, packageId, privacyId, monitorPolicy); + } + else { + return PRIV_FLTR_ERROR_NO_DATA; + } +} + +void* +PrivacyChecker::runSignalListenerThread(void* pData) +{ + pthread_detach(pthread_self()); + LOGI("Running g main loop for signal"); + + initializeDbus(); + + g_main_loop_run(m_pLoop); + + finalizeDbus(); + + pthread_exit(NULL); + + return (void*) 0; +} + +int +PrivacyChecker::initializeDbus(void) +{ + DBusError error; + dbus_error_init(&error); + + m_pDBusConnection = dbus_bus_get_private(DBUS_BUS_SYSTEM, &error); + TryReturn(m_pDBusConnection != NULL, PRIV_FLTR_ERROR_SYSTEM_ERROR, dbus_error_free(&error), "dbus_bus_get_private [%s] : %d", PRIV_FLTR_ERROR_SYSTEM_ERROR); + + dbus_connection_setup_with_g_main(m_pDBusConnection, m_pHandlerGMainContext); + std::unique_ptr < char[] > pRule(new char[MAX_LOCAL_BUF_SIZE]); + + snprintf(pRule.get(), MAX_LOCAL_BUF_SIZE, "path='%s',type='signal',interface='%s'", DBUS_PATH.c_str(), DBUS_SIGNAL_INTERFACE.c_str()); + dbus_bus_add_match(m_pDBusConnection, pRule.get(), &error); + TryReturn(!dbus_error_is_set(&error), PRIV_FLTR_ERROR_SYSTEM_ERROR, dbus_error_free(&error), "dbus_bus_add_match[%s] : %d", error.message, PRIV_FLTR_ERROR_SYSTEM_ERROR); + + dbus_bool_t r = dbus_connection_add_filter(m_pDBusConnection, handleNotification, NULL, NULL); + TryReturn(r, PRIV_FLTR_ERROR_SYSTEM_ERROR, , "dbus_connection_add_filter: %d", PRIV_FLTR_ERROR_SYSTEM_ERROR); + + return PRIV_FLTR_ERROR_SUCCESS; +} + +int +PrivacyChecker::finalizeDbus(void) +{ + dbus_connection_remove_filter(m_pDBusConnection, handleNotification, NULL); + dbus_connection_close(m_pDBusConnection); + m_pDBusConnection = NULL; + + return PRIV_FLTR_ERROR_SUCCESS; +} + + +DBusHandlerResult +PrivacyChecker::handleNotification(DBusConnection* connection, DBusMessage* message, void* user_data) +{ + DBusError error; + dbus_bool_t r; + dbus_error_init(&error); + + char* pPkgId; + char* pPrivacyId; + + if (dbus_message_is_signal(message, DBUS_SIGNAL_INTERFACE.c_str(), DBUS_SIGNAL_SETTING_CHANGED.c_str())) + { + r = dbus_message_get_args(message, &error, + DBUS_TYPE_STRING, &pPkgId, + DBUS_TYPE_STRING, &pPrivacyId, + DBUS_TYPE_INVALID); + TryReturn(r, DBUS_HANDLER_RESULT_NOT_YET_HANDLED, , "Fail to get data : %s", error.message); + + std::lock_guard < std::mutex > guard(m_cacheMutex); + + if (std::string(pPkgId) == m_pkgId) + { + LOGI("Current app pkg privacy information updated"); + updateCache(m_pkgId, pPrivacyId, m_privacyCache); + //printCache(); + } + + std::map < std::string, std::map < std::string, bool > > :: iterator iter = m_privacyInfoCache.find(std::string(pPkgId)); + if (iter != m_privacyInfoCache.end()) + { + LOGI("Current pkg privacy is in cache"); + updateCache(std::string(pPkgId), pPrivacyId, iter->second); + } + + } + else if (dbus_message_is_signal(message, DBUS_SIGNAL_INTERFACE.c_str(), DBUS_SIGNAL_PKG_REMOVED.c_str())) + { + r = dbus_message_get_args(message, &error, + DBUS_TYPE_STRING, &pPkgId, + DBUS_TYPE_INVALID); + TryReturn(r, DBUS_HANDLER_RESULT_NOT_YET_HANDLED, , "Fail to get data : %s", error.message); + + std::lock_guard < std::mutex > guard(m_cacheMutex); + + std::map < std::string, std::map < std::string, bool > > :: iterator iter = m_privacyInfoCache.find(std::string(pPkgId)); + if (iter != m_privacyInfoCache.end()) + { + m_privacyInfoCache.erase(iter); + } + } + + // This event is not only for specific handler. All handlers of daemons should be check it and handle it. + return DBUS_HANDLER_RESULT_NOT_YET_HANDLED; +} + +int +PrivacyChecker::check(const std::string privacyId, std::map < std::string, bool >& privacyMap) +{ + TryReturn(m_isInitialized, PRIV_FLTR_ERROR_NOT_INITIALIZED, , "Not initialized"); + + std::map < std::string, bool >::iterator iter; + + iter = privacyMap.find(privacyId); + if (iter == privacyMap.end() ) + { + LOGD("The application cannot access the privacy inforamtion."); + return PRIV_FLTR_ERROR_USER_NOT_CONSENTED; + } + else if (!iter->second) + { + LOGD("User does not consented to access the privacy information"); + return PRIV_FLTR_ERROR_USER_NOT_CONSENTED; + } + + return PRIV_FLTR_ERROR_SUCCESS; +} + +int +PrivacyChecker::check(const std::string privacyId) +{ + if (!m_isInitialized) + return PRIV_FLTR_ERROR_NOT_INITIALIZED; + + std::lock_guard < std::mutex > guard(m_cacheMutex); + + int res = check(privacyId, m_privacyCache); + + return res; +} + +int +PrivacyChecker::check(const std::string pkgId, const std::string privacyId) +{ + if (!m_isInitialized) + initialize(); + + std::lock_guard < std::mutex > guard(m_cacheMutex); + int res; + + std::map < std::string, std::map < std::string, bool > >::iterator iter = m_privacyInfoCache.find(pkgId); + if (iter == m_privacyInfoCache.end() ) + { + std::map < std::string, bool > pkgCacheMap; + res = updateCache(pkgId, pkgCacheMap); + TryReturn( res == PRIV_FLTR_ERROR_SUCCESS, PRIV_FLTR_ERROR_DB_ERROR, , "Failed to update cache : %d", res); + + m_privacyInfoCache.insert( std::map < std::string, std::map < std::string, bool > >::value_type(std::string(pkgId), pkgCacheMap)); + iter = m_privacyInfoCache.find(pkgId); + } + + if (iter->second.size() == 0) + { + return PRIV_FLTR_ERROR_USER_NOT_CONSENTED; + } + + res = check(privacyId, iter->second); + + return res; +} + +int +PrivacyChecker::checkWithPrivilege(const std::string pkgId, const std::string privilege) +{ + std::string privacyId; + int res = PrivacyIdInfo::getPrivacyIdFromPrivilege(privilege, privacyId); + if (res == PRIV_FLTR_ERROR_NO_DATA) { + return PRIV_FLTR_ERROR_SUCCESS; + } + + TryReturn( res == PRIV_FLTR_ERROR_SUCCESS, res, , "getPrivacyIdFromPrivilege : %d", res); + + return check(pkgId, privacyId); +} + +int +PrivacyChecker::checkWithPrivilege(const std::string privilege) +{ + std::string privacyId; + int res = PrivacyIdInfo::getPrivacyIdFromPrivilege(privilege, privacyId); + if (res == PRIV_FLTR_ERROR_NO_DATA) { + return PRIV_FLTR_ERROR_SUCCESS; + } + + TryReturn( res == PRIV_FLTR_ERROR_SUCCESS, res, , "getPrivacyIdFromPrivilege : %d", res); + + return check(privacyId); +} + +int +PrivacyChecker::finalize(void) +{ + std::lock_guard guard (m_cacheMutex); + m_privacyCache.clear(); + m_privacyInfoCache.clear(); + + if (m_pLoop != NULL) + { + g_main_loop_quit(m_pLoop); + m_pLoop = NULL; + } + + if (m_pHandlerGMainContext != NULL) + { + g_main_context_unref(m_pHandlerGMainContext); + m_pHandlerGMainContext = NULL; + } + + m_isInitialized = false; + + return PRIV_FLTR_ERROR_SUCCESS; +} + +void +PrivacyChecker::printCache(void) +{ + std::map < std::string, bool >::const_iterator iter = m_privacyCache.begin(); + for (; iter != m_privacyCache.end(); ++iter) + { + LOGD(" %s : %d", iter->first.c_str(), iter->second); + } +} + +int +PrivacyChecker::updateCache(const std::string pkgId, std::string privacyId, std::map < std::string, bool >& pkgCacheMap) +{ + static const std::string PrivacyQuery = "SELECT IS_ENABLED from PrivacyInfo where PKG_ID=? and PRIVACY_ID=?"; + + openDb(PRIVACY_DB_PATH, pDbH, SQLITE_OPEN_READONLY); + prepareDb(pDbH, PrivacyQuery.c_str(), pPrivacyStmt); + int res = sqlite3_bind_text(pPrivacyStmt.get(), 1, pkgId.c_str(), -1, SQLITE_TRANSIENT); + TryReturn( res == 0, PRIV_FLTR_ERROR_DB_ERROR, , "sqlite3_bind_text : %d", res); + + res = sqlite3_bind_text(pPrivacyStmt.get(), 2, privacyId.c_str(), -1, SQLITE_TRANSIENT); + TryReturn( res == 0, PRIV_FLTR_ERROR_DB_ERROR, , "sqlite3_bind_text : %d", res); + + while ( sqlite3_step(pPrivacyStmt.get()) == SQLITE_ROW ) + { + bool privacyEnabled = sqlite3_column_int(pPrivacyStmt.get(), 0) > 0 ? true : false; + + SECURE_LOGD("Set result : %s : %d", privacyId.c_str(), privacyEnabled ); + pkgCacheMap.erase(privacyId); + pkgCacheMap.insert(std::map < std::string, bool >::value_type(privacyId, privacyEnabled)); + } + + return PRIV_FLTR_ERROR_SUCCESS; +} + +int +PrivacyChecker::updateCache(std::string pkgId, std::map < std::string, bool >& pkgCacheMap) +{ + static const std::string PrivacyQuery = "SELECT PRIVACY_ID, IS_ENABLED from PrivacyInfo where PKG_ID=?"; + + pkgCacheMap.clear(); + + openDb(PRIVACY_DB_PATH, pDbH, SQLITE_OPEN_READONLY); + prepareDb(pDbH, PrivacyQuery.c_str(), pPrivacyStmt); + int res = sqlite3_bind_text(pPrivacyStmt.get(), 1, pkgId.c_str(), -1, SQLITE_TRANSIENT); + TryReturn( res == SQLITE_OK, PRIV_FLTR_ERROR_DB_ERROR, , "sqlite3_bind_text : %d", res); + + while ( (res = sqlite3_step(pPrivacyStmt.get())) == SQLITE_ROW ) + { + const char* privacyId = reinterpret_cast < const char* > (sqlite3_column_text(pPrivacyStmt.get(), 0)); + bool privacyEnabled = sqlite3_column_int(pPrivacyStmt.get(), 1) > 0 ? true : false; + + pkgCacheMap.insert(std::map < std::string, bool >::value_type(std::string(privacyId), privacyEnabled)); + + SECURE_LOGD("Privacy found : %s %d", privacyId, privacyEnabled); + } + return PRIV_FLTR_ERROR_SUCCESS; +} diff --git a/client/src/PrivacyGuardClient.cpp b/client/src/PrivacyGuardClient.cpp new file mode 100755 index 0000000..14d2280 --- /dev/null +++ b/client/src/PrivacyGuardClient.cpp @@ -0,0 +1,444 @@ +/* + * 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. + */ + +#include +#include +#include "Utils.h" +#include "PrivacyGuardClient.h" +#include "SocketClient.h" +#include "PrivacyIdInfo.h" + +#define COUNT 10 + +#undef __READ_DB_IPC__ + +std::mutex PrivacyGuardClient::m_singletonMutex; +PrivacyGuardClient* PrivacyGuardClient::m_pInstance = NULL; +const std::string PrivacyGuardClient::INTERFACE_NAME("PrivacyInfoService"); + +PrivacyGuardClient::PrivacyGuardClient(void) +{ + std::unique_ptr pSocketClient(new SocketClient(INTERFACE_NAME)); + m_pSocketClient = std::move(pSocketClient); +} + +PrivacyGuardClient* +PrivacyGuardClient::getInstance(void) +{ + std::lock_guard guard(m_singletonMutex); + if (m_pInstance == NULL) + m_pInstance = new PrivacyGuardClient(); + return m_pInstance; +} + +int +PrivacyGuardClient::PgAddPrivacyAccessLog(const int userId, const std::string packageId, const std::string privacyId) +{ + int result = PRIV_FLTR_ERROR_SUCCESS; + logInfoList.push_back(std::pair (packageId, privacyId)); + PF_LOGD("PrivacyGuardClient userId : %d, PgAddPrivacyAccessLog logInfoList.size() : %d", userId, logInfoList.size()); + + if(logInfoList.size() >= COUNT) { + int res = m_pSocketClient->connect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "connect : %d", res); + + res = m_pSocketClient->call("PgAddPrivacyAccessLog", userId, logInfoList, &result); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, m_pSocketClient->disconnect(), "call : %d", res); + + res = m_pSocketClient->disconnect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "disconnect : %d", res); + logInfoList.clear(); + } + + return result; +} + +int +PrivacyGuardClient::PgAddPrivacyAccessLogTest(const int userId, const std::string packageId, const std::string privacyId) +{ + int result = PRIV_FLTR_ERROR_SUCCESS; + + int res = m_pSocketClient->connect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "connect : %d", res); + + res = m_pSocketClient->call("PgAddPrivacyAccessLogTest", userId, packageId, privacyId, &result); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, m_pSocketClient->disconnect(), "call : %d", res); + + res = m_pSocketClient->disconnect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "disconnect : %d", res); + + return result; +} + +int +PrivacyGuardClient::PgAddPrivacyAccessLogBeforeTerminate(void) +{ + int result = PRIV_FLTR_ERROR_SUCCESS; + PF_LOGD("PgAddPrivacyAccessLogBeforeTerminate, logInfoList.size() : %d", logInfoList.size()); + + if(logInfoList.size() > 0) { + int res = m_pSocketClient->connect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "connect : %d", res); + + res = m_pSocketClient->call("PgAddPrivacyAccessLog", logInfoList, &result); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, m_pSocketClient->disconnect(), "call : %d", res); + + res = m_pSocketClient->disconnect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "disconnect : %d", res); + logInfoList.clear(); + } + + return result; +} + +int +PrivacyGuardClient::PgAddMonitorPolicy(const int userId, const std::string pkgId, const std::list < std::string >& list, int monitorPolicy) +{ + + std::list < std::string > privacyList; + + int res = PrivacyIdInfo::getPrivacyIdListFromPrivilegeList(list, privacyList); + if (res != PRIV_FLTR_ERROR_SUCCESS ) + return res; + + if (privacyList.size() == 0) + return PRIV_FLTR_ERROR_SUCCESS; + + int result = PRIV_FLTR_ERROR_SUCCESS; + + res = m_pSocketClient->connect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "connect : %d", res); + + res = m_pSocketClient->call("PgAddMonitorPolicy", userId, pkgId, privacyList, monitorPolicy, &result); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, m_pSocketClient->disconnect(), "call : %d", res); + + res = m_pSocketClient->disconnect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "disconnect : %d", res); + + return result; +} + +int +PrivacyGuardClient::PgDeleteAllLogsAndMonitorPolicy(void) +{ + int result = PRIV_FLTR_ERROR_SUCCESS; + + int res = m_pSocketClient->connect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "connect : %d", res); + + res = m_pSocketClient->call("PgDeleteAllLogsAndMonitorPolicy", &result); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, m_pSocketClient->disconnect(), "call : %d", res); + + res = m_pSocketClient->disconnect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "disconnect : %d", res); + + return result; +} + +int +PrivacyGuardClient::PgDeleteLogsByPackageId(const std::string packageId) +{ + int result = PRIV_FLTR_ERROR_SUCCESS; + + int res = m_pSocketClient->connect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "connect : %d", res); + + res = m_pSocketClient->call("PgDeleteLogsByPackageId", packageId, &result); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, m_pSocketClient->disconnect(), "call : %d", res); + + res = m_pSocketClient->disconnect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "disconnect : %d", res); + + return result; +} + +int +PrivacyGuardClient::PgDeleteMonitorPolicyByPackageId(const std::string packageId) +{ + int result = PRIV_FLTR_ERROR_SUCCESS; + + int res = m_pSocketClient->connect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "connect : %d", res); + + res = m_pSocketClient->call("PgDeleteMonitorPolicyByPackageId", packageId, &result); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, m_pSocketClient->disconnect(), "call : %d", res); + + res = m_pSocketClient->disconnect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "disconnect : %d", res); + + return result; +} + +int +PrivacyGuardClient::PgForeachTotalPrivacyCountOfPackage(const int userId, const int startDate, const int endDate, std::list < std::pair > & packageInfoList) const +{ + int result = PRIV_FLTR_ERROR_SUCCESS; + + int res = m_pSocketClient->connect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "connect : %d", res); + + res = m_pSocketClient->call("PgForeachTotalPrivacyCountOfPackage", userId, startDate, endDate, &result, &packageInfoList); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, m_pSocketClient->disconnect(), "call : %d", res); + + res = m_pSocketClient->disconnect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "disconnect : %d", res); + + return result; +} + +int +PrivacyGuardClient::PgForeachTotalPrivacyCountOfPrivacy(const int userId, const int startDate, const int endDate, std::list < std::pair > & privacyInfoList) const +{ + int result = PRIV_FLTR_ERROR_SUCCESS; + + int res = m_pSocketClient->connect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "connect : %d", res); + + res = m_pSocketClient->call("PgForeachTotalPrivacyCountOfPrivacy", userId, startDate, endDate, &result, &privacyInfoList); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, m_pSocketClient->disconnect(), "call : %d", res); + + res = m_pSocketClient->disconnect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "disconnect : %d", res); + + return result; +} + +int +PrivacyGuardClient::PgForeachPrivacyCountByPrivacyId(const int userId, const int startDate, const int endDate, const std::string privacyId, std::list < std::pair > & packageInfoList) const +{ + int result = PRIV_FLTR_ERROR_SUCCESS; + + bool isValid = PrivacyIdInfo::isValidPrivacyId(privacyId); + + if (!isValid) + return PRIV_FLTR_ERROR_INVALID_PARAMETER; + + int res = m_pSocketClient->connect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "connect : %d", res); + + res = m_pSocketClient->call("PgForeachPrivacyCountByPrivacyId", userId, startDate, endDate, privacyId, &result, &packageInfoList); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, m_pSocketClient->disconnect(), "call : %d", res); + + res = m_pSocketClient->disconnect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "disconnect : %d", res); + + return result; +} + +int +PrivacyGuardClient::PgForeachPrivacyCountByPackageId(const int userId, const int startDate, const int endDate, const std::string packageId, std::list < std::pair > & privacyInfoList) const +{ + int result = PRIV_FLTR_ERROR_SUCCESS; + + int res = m_pSocketClient->connect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "connect : %d", res); + + res = m_pSocketClient->call("PgForeachPrivacyCountByPackageId", userId, startDate, endDate, packageId, &result, &privacyInfoList); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, m_pSocketClient->disconnect(), "call : %d", res); + + res = m_pSocketClient->disconnect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "disconnect : %d", res); + + return result; +} + +int +PrivacyGuardClient::PgForeachPrivacyPackageId(const int userId, std::list < std::string > & packageList) const +{ + int result = PRIV_FLTR_ERROR_SUCCESS; + + int res = m_pSocketClient->connect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "connect : %d", res); + + res = m_pSocketClient->call("PgForeachPrivacyPackageId", userId, &result, &packageList); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, m_pSocketClient->disconnect(), "call : %d", res); + + res = m_pSocketClient->disconnect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "connect : %d", res); + + return result; +} + +int +PrivacyGuardClient::PgForeachPackageByPrivacyId(const int userId, const std::string privacyId, std::list < std::string > & packageList) const +{ + int result = PRIV_FLTR_ERROR_SUCCESS; + + bool isValid = PrivacyIdInfo::isValidPrivacyId(privacyId); + + if (!isValid) + return PRIV_FLTR_ERROR_INVALID_PARAMETER; + + int res = m_pSocketClient->connect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "connect : %d", res); + + res = m_pSocketClient->call("PgForeachPackageByPrivacyId", userId, privacyId, &result, &packageList); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, m_pSocketClient->disconnect(), "call : %d", res); + + res = m_pSocketClient->disconnect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "connect : %d", res); + + return result; +} + +int +PrivacyGuardClient::PgForeachMonitorPolicyByPackageId(const int userId, const std::string packageId, + std::list & privacyInfoList) const +{ + int result = PRIV_FLTR_ERROR_SUCCESS; + + int res = m_pSocketClient->connect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "connect : %d", res); + + res = m_pSocketClient->call("PgForeachMonitorPolicyByPackageId", userId, packageId, &result, &privacyInfoList); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, m_pSocketClient->disconnect(), "call : %d", res); + + res = m_pSocketClient->disconnect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "disconnect : %d", res); + + return result; +} + +int +PrivacyGuardClient::PgGetMonitorPolicy(const int userId, const std::string packageId, + const std::string privacyId, int &monitorPolicy) const +{ + int result = PRIV_FLTR_ERROR_SUCCESS; + + bool isValid = PrivacyIdInfo::isValidPrivacyId(privacyId); + + if (!isValid) + return PRIV_FLTR_ERROR_INVALID_PARAMETER; + + int res = m_pSocketClient->connect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "connect : %d", res); + + res = m_pSocketClient->call("PgGetMonitorPolicy", userId, packageId, privacyId, &result, &monitorPolicy); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, m_pSocketClient->disconnect(), "call : %d", res); + + res = m_pSocketClient->disconnect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "connect : %d", res); + + return result; +} + +int +PrivacyGuardClient::PgGetAllMonitorPolicy(std::list < std::pair < std::string, int > > & monitorPolicyList) const +{ + int result = PRIV_FLTR_ERROR_SUCCESS; + + int res = m_pSocketClient->connect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "connect : %d", res); + + res = m_pSocketClient->call("PgGetAllMonitorPolicy", &result, &monitorPolicyList); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, m_pSocketClient->disconnect(), "call : %d", res); + + res = m_pSocketClient->disconnect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "connect : %d", res); + + return result; +} + +int +PrivacyGuardClient::PgCheckPrivacyPackage(const int userId, const std::string packageId, bool &isPrivacyPackage) +{ + int result = PRIV_FLTR_ERROR_SUCCESS; + + int res = m_pSocketClient->connect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "connect : %d", res); + + res = m_pSocketClient->call("PgCheckPrivacyPackage", userId, packageId, &result, &isPrivacyPackage); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, m_pSocketClient->disconnect(), "call : %d", res); + + res = m_pSocketClient->disconnect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "connect : %d", res); + + return result; +} + +int +PrivacyGuardClient::PgUpdateMonitorPolicy(const int userId, const std::string packageId, + const std::string privacyId, const int monitorPolicy) +{ + int result = PRIV_FLTR_ERROR_SUCCESS; + + bool isValid = PrivacyIdInfo::isValidPrivacyId(privacyId); + + if (!isValid) + return PRIV_FLTR_ERROR_INVALID_PARAMETER; + + int res = m_pSocketClient->connect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "connect : %d", res); + + res = m_pSocketClient->call("PgUpdateMonitorPolicy", userId, packageId, privacyId, monitorPolicy, &result); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, m_pSocketClient->disconnect(), "call : %d", res); + + res = m_pSocketClient->disconnect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "connect : %d", res); + + return result; +} + +int +PrivacyGuardClient::PgGetMainMonitorPolicy(const int userId, bool &mainMonitorPolicy) const +{ + int result = PRIV_FLTR_ERROR_SUCCESS; + + int res = m_pSocketClient->connect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "connect : %d", res); + + res = m_pSocketClient->call("PgGetMainMonitorPolicy", userId, &result, &mainMonitorPolicy); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, m_pSocketClient->disconnect(), "call : %d", res); + + res = m_pSocketClient->disconnect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "connect : %d", res); + + return result; +} + +int +PrivacyGuardClient::PgUpdateMainMonitorPolicy(const int userId, const bool mainMonitorPolicy) +{ + int result = PRIV_FLTR_ERROR_SUCCESS; + + int res = m_pSocketClient->connect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "connect : %d", res); + + res = m_pSocketClient->call("PgUpdateMainMonitorPolicy", userId, mainMonitorPolicy, &result); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, m_pSocketClient->disconnect(), "call : %d", res); + + res = m_pSocketClient->disconnect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "connect : %d", res); + + return result; +} + +int +PrivacyGuardClient::PgDeleteMainMonitorPolicyByUserId(const int userId) +{ + int result = PRIV_FLTR_ERROR_SUCCESS; + + int res = m_pSocketClient->connect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "connect : %d", res); + + res = m_pSocketClient->call("PgDeleteMainMonitorPolicyByUserId", userId, &result); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, m_pSocketClient->disconnect(), "call : %d", res); + + res = m_pSocketClient->disconnect(); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "disconnect : %d", res); + + return result; +} diff --git a/client/src/SocketClient.cpp b/client/src/SocketClient.cpp new file mode 100755 index 0000000..0652b0c --- /dev/null +++ b/client/src/SocketClient.cpp @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include +#include "PrivacyGuardTypes.h" +#include "SocketClient.h" +#include "Utils.h" + +#define throwWithErrnoMessage(specificInfo) do {\ + LOGE("%s : %s", specificInfo, strerror(errno)); \ + return -1; \ + } while(0) + +SocketClient::SocketClient(const std::string& interfaceName) +{ + m_interfaceName = interfaceName; + m_serverAddress = SERVER_ADDRESS; + PF_LOGI("Client created m_interfaceName : %s, m_serverAddress : %s", m_interfaceName.c_str(), m_serverAddress.c_str()); +} + +int SocketClient::connect() +{ + struct sockaddr_un remote; + m_socketFd = socket(AF_UNIX, SOCK_STREAM,0); + TryReturn( m_socketFd != -1, PRIV_FLTR_ERROR_IPC_ERROR, , "socket : %s", strerror(errno)); + + int res; + //socket needs to be nonblocking, because read can block after select + int flags; + if ( (flags = fcntl(m_socketFd, F_GETFL, 0)) == -1 ) + flags = 0; + res = fcntl(m_socketFd, F_SETFL, flags | O_NONBLOCK); + TryReturn( m_socketFd != -1, PRIV_FLTR_ERROR_IPC_ERROR, , "fcntl : %s", strerror(errno)); + + bzero(&remote, sizeof(remote)); + remote.sun_family = AF_UNIX; + strcpy(remote.sun_path, m_serverAddress.c_str()); + res = ::connect(m_socketFd, (struct sockaddr *)&remote, SUN_LEN(&remote)); + TryReturn( res != -1, PRIV_FLTR_ERROR_IPC_ERROR, , "connect : %s", strerror(errno)); + + m_socketConnector.reset(new SocketConnection(m_socketFd)); + + LOGI("Client connected"); + + return PRIV_FLTR_ERROR_SUCCESS; +} + +int SocketClient::disconnect() +{ + //Socket should be already closed by server side, + //even though we should close it in case of any errors + close(m_socketFd); + LOGI("Client disconnected"); + + return PRIV_FLTR_ERROR_SUCCESS; +} diff --git a/client/src/privacy_guard_client.cpp b/client/src/privacy_guard_client.cpp new file mode 100755 index 0000000..5ba9830 --- /dev/null +++ b/client/src/privacy_guard_client.cpp @@ -0,0 +1,379 @@ +/* + * Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include "PrivacyChecker.h" +#include "PrivacyGuardClient.h" +#include "privacy_guard_client.h" +#include "privacy_guard_client_internal.h" +#include "privacy_guard_client_internal_types.h" +#include "Utils.h" + +#define MONITOR_POLICY_OFF 0 +#define MONITOR_POLICY_ON 1 + +#ifndef TIZEN_PATH_MIN +#define TIZEN_PATH_MIN 5 +#endif + +#ifndef TIZEN_PATH_MAX +#define TIZEN_PATH_MAX 1024 +#endif + +int privacy_guard_client_add_privacy_access_log(const int user_id, const char *package_id, const char *privilege_id) +{ + if (user_id < 0 || package_id == NULL || privilege_id == NULL) + return PRIV_FLTR_ERROR_INVALID_PARAMETER; + + int monitor_policy = 0; + std::string privacy_id; + + PF_LOGD("user_id : %d, package_id : %s, privilege_id : %s", user_id, package_id, privilege_id); + + int retval = PrivacyChecker::checkMonitorPolicyWithPrivilege(user_id, std::string(package_id), std::string(privilege_id), privacy_id, monitor_policy); + + PF_LOGD("monitor policy : %d", monitor_policy); + + if (retval == PRIV_FLTR_ERROR_SUCCESS && monitor_policy == MONITOR_POLICY_ON) { + PrivacyGuardClient *pInst = PrivacyGuardClient::getInstance(); + retval = pInst->PgAddPrivacyAccessLog(user_id, std::string(package_id), std::string(privacy_id)); + } + PF_LOGD("retval : %d", retval); + return retval; +} + +int privacy_guard_client_delete_all_logs_and_monitor_policy(void) +{ + PrivacyGuardClient *pInst = PrivacyGuardClient::getInstance(); + + int retval = pInst->PgDeleteAllLogsAndMonitorPolicy(); + + return retval; +} + +int privacy_guard_client_delete_logs_by_package_id(const char *package_id) +{ + if (package_id == NULL) + return PRIV_FLTR_ERROR_INVALID_PARAMETER; + + PrivacyGuardClient *pInst = PrivacyGuardClient::getInstance(); + + int retval = pInst->PgDeleteLogsByPackageId(std::string(package_id)); + + return retval; +} + +int privacy_guard_client_delete_monitor_policy_by_package_id(const char *package_id) +{ + if (package_id == NULL) + return PRIV_FLTR_ERROR_INVALID_PARAMETER; + + PrivacyGuardClient *pInst = PrivacyGuardClient::getInstance(); + + int retval = pInst->PgDeleteMonitorPolicyByPackageId(std::string(package_id)); + + return retval; +} + +int privacy_guard_client_foreach_total_privacy_count_of_package(const int user_id, const time_t start_date, + const time_t end_date, privacy_guard_client_privacy_count_of_package_cb callback, void *user_data) +{ + if (user_id < 0 || start_date > end_date || start_date <= 0) + return PRIV_FLTR_ERROR_INVALID_PARAMETER; + PrivacyGuardClient *pInst = PrivacyGuardClient::getInstance(); + std::list > list; + + PF_LOGD("start_date : %d, end_date : %d", start_date, end_date); + int retval = pInst->PgForeachTotalPrivacyCountOfPackage(user_id, start_date, end_date, list); + + if (retval != PRIV_FLTR_ERROR_SUCCESS) + return retval; + if (list.size() == 0) + return PRIV_FLTR_ERROR_NO_DATA; + + for (std::list >::iterator iter = list.begin(); iter != list.end(); ++iter) { + PF_LOGD("result > package_id : %s, count : %d", iter->first.c_str(), iter->second); + bool ret = callback(iter->first.c_str(), iter->second, user_data); + if (ret == false) + break; + } + + return retval; +} + +int privacy_guard_client_foreach_total_privacy_count_of_privacy(const int user_id, const time_t start_date, + const time_t end_date, privacy_guard_client_privacy_count_cb callback, void *user_data) +{ + if (user_id < 0 || start_date > end_date || start_date <= 0) + return PRIV_FLTR_ERROR_INVALID_PARAMETER; + + PrivacyGuardClient *pInst = PrivacyGuardClient::getInstance(); + std::list > list; + + PF_LOGD("start_date : %d, end_date : %d", start_date, end_date); + int retval = pInst->PgForeachTotalPrivacyCountOfPrivacy(user_id, start_date, end_date, list); + + if (retval != PRIV_FLTR_ERROR_SUCCESS) + return retval; + if (list.size() == 0) + return PRIV_FLTR_ERROR_NO_DATA; + + for (std::list >::iterator iter = list.begin(); iter != list.end(); ++iter) { + PF_LOGD("result > privacy_id : %s, count : %d", iter->first.c_str(), iter->second); + bool ret = callback(iter->first.c_str(), iter->second, user_data); + if (ret == false) + break; + } + + return retval; +} + +int privacy_guard_client_foreach_privacy_count_by_privacy_id(const int user_id, const time_t start_date, + const time_t end_date, const char *privacy_id, + privacy_guard_client_privacy_count_of_package_cb callback, void *user_data) +{ + if (user_id < 0 || start_date > end_date || start_date <= 0 || privacy_id == NULL) + return PRIV_FLTR_ERROR_INVALID_PARAMETER; + + PrivacyGuardClient *pInst = PrivacyGuardClient::getInstance(); + std::list > list; + + PF_LOGD("start_date : %d, end_date : %d", start_date, end_date); + int retval = pInst->PgForeachPrivacyCountByPrivacyId(user_id, start_date, end_date, std::string(privacy_id), list); + + if (retval != PRIV_FLTR_ERROR_SUCCESS) + return retval; + if (list.size() == 0) + return PRIV_FLTR_ERROR_NO_DATA; + + for (std::list >::iterator iter = list.begin(); iter != list.end(); ++iter) { + PF_LOGD("result > package_id : %s, count : %d", iter->first.c_str(), iter->second); + bool ret = callback(iter->first.c_str(), iter->second, user_data); + if (ret == false) + break; + } + + return retval; +} + + +int privacy_guard_client_foreach_privacy_count_by_package_id(const int user_id, const time_t start_date, + const time_t end_date, const char *package_id, + privacy_guard_client_privacy_count_cb callback, void *user_data) +{ + if (user_id < 0 || start_date > end_date || start_date <= 0 || package_id == NULL) + return PRIV_FLTR_ERROR_INVALID_PARAMETER; + + PrivacyGuardClient *pInst = PrivacyGuardClient::getInstance(); + std::list > list; + + PF_LOGD("start_date : %d, end_date : %d", start_date, end_date); + int retval = pInst->PgForeachPrivacyCountByPackageId(user_id, start_date, end_date, std::string(package_id), list); + + if (retval != PRIV_FLTR_ERROR_SUCCESS) + return retval; + if (list.size() == 0) + return PRIV_FLTR_ERROR_NO_DATA; + + for (std::list >::iterator iter = list.begin(); iter != list.end(); ++iter) { + PF_LOGD("result > privacy_id : %s, count : %d", iter->first.c_str(), iter->second); + bool ret = callback(iter->first.c_str(), iter->second, user_data); + if (ret == false) + break; + } + + return retval; +} + +int privacy_guard_client_add_monitor_policy(const int user_id, const char *package_id, const char **privilege_list, const int monitor_policy) +{ + if (user_id < 0 || package_id == NULL) + return PRIV_FLTR_ERROR_INVALID_PARAMETER; + + PrivacyGuardClient *pInst = PrivacyGuardClient::getInstance(); + std::list < std::string > privilegeList; + + while (*privilege_list[0] != '\0') + { + PF_LOGD("privacyList : %s", *privilege_list); + privilegeList.push_back(std::string(*privilege_list++)); + } + + int retval = pInst->PgAddMonitorPolicy(user_id, std::string(package_id), privilegeList, monitor_policy); + + return retval; +} + +int privacy_guard_client_update_monitor_policy(const int user_id, const char *package_id, const char *privacy_id, const int monitor_policy) +{ + if (user_id < 0 || package_id == NULL || privacy_id == NULL) + return PRIV_FLTR_ERROR_INVALID_PARAMETER; + + PrivacyGuardClient *pInst = PrivacyGuardClient::getInstance(); + + int retval = pInst->PgUpdateMonitorPolicy(user_id, std::string(package_id), std::string(privacy_id), monitor_policy); + + return retval; +} + +int privacy_guard_client_foreach_monitor_policy_by_package_id(const int user_id, const char *package_id, + privacy_guard_client_monitor_policy_cb callback, void *user_data) +{ + if (user_id < 0 || package_id == NULL) + return PRIV_FLTR_ERROR_INVALID_PARAMETER; + + PF_LOGD("package_id : %s", package_id); + + std::list privacyInfoList; + int retval = -1; + + retval = PrivacyGuardClient::getInstance()->PgForeachMonitorPolicyByPackageId(user_id, std::string(package_id), privacyInfoList); + + if (retval != PRIV_FLTR_ERROR_SUCCESS) { + PF_LOGE("PgForeachMonitorPolicyByPackageId : fail"); + return retval; + } + + if (privacyInfoList.size() == 0) { + PF_LOGE("PgForeachMonitorPolicyByPackageId (privacyList.size = 0): fail"); + return PRIV_FLTR_ERROR_NO_DATA; + } + + for (std::list ::iterator iter = privacyInfoList.begin(); iter != privacyInfoList.end(); ++iter) { + PF_LOGD("result > privacy_id : %s, monitor_policy : %d", + iter->privacy_id, iter->monitor_policy); + bool ret = callback(iter->privacy_id, iter->monitor_policy, user_data); + if (ret == false) + break; + } + + return retval; +} + +int privacy_guard_client_check_privacy_package(const int user_id, const char *package_id, bool *is_privacy_package) +{ + if (user_id < 0 || package_id == NULL) + return PRIV_FLTR_ERROR_INVALID_PARAMETER; + + PrivacyGuardClient* pInst = PrivacyGuardClient::getInstance(); + + PF_LOGD("user_id : %d, package_id : %s", user_id, package_id); + int retval = pInst->PgCheckPrivacyPackage(user_id, std::string(package_id), *is_privacy_package); + PF_LOGD("result > is_privacy_package : %d", *is_privacy_package); + + return retval; +} + +int privacy_guard_client_foreach_privacy_package_id(const int user_id, privacy_guard_client_package_id_cb callback, void *user_data) +{ + if (user_id < 0) + return PRIV_FLTR_ERROR_INVALID_PARAMETER; + + PrivacyGuardClient* pInst = PrivacyGuardClient::getInstance(); + + std::list < std::string > packageList; + + int retval = pInst->PgForeachPrivacyPackageId(user_id, packageList); + if (retval != PRIV_FLTR_ERROR_SUCCESS) { + PF_LOGE("PgForeachPrivacyPackageId : fail"); + return retval; + } + + if (packageList.size() == 0) { + PF_LOGE("PgForeachPrivacyPackageId (packageList.size = 0): fail"); + return PRIV_FLTR_ERROR_NO_DATA; + } + + for (std::list < std::string >::iterator iter = packageList.begin(); iter != packageList.end(); ++iter) { + PF_LOGD("package_id : %s", iter->c_str()); + bool ret = callback(iter->c_str(), user_data); + if (ret == false) + break; + } + + return retval; +} + +int privacy_guard_client_foreach_package_by_privacy_id(const int user_id, const char *privacy_id, privacy_guard_client_package_id_cb callback, void *user_data) +{ + if (user_id < 0 || privacy_id == NULL) + return PRIV_FLTR_ERROR_INVALID_PARAMETER; + + PrivacyGuardClient* pInst = PrivacyGuardClient::getInstance(); + + std::list < std::string > packageList; + + int retval = pInst->PgForeachPackageByPrivacyId(user_id, std::string(privacy_id), packageList); + if (retval != PRIV_FLTR_ERROR_SUCCESS) { + PF_LOGE("PgForeachPackageByPrivacyId : fail"); + return retval; + } + + if (packageList.size() == 0) { + PF_LOGE("PgForeachPackageByPrivacyId (packageList.size = 0): fail"); + return PRIV_FLTR_ERROR_NO_DATA; + } + + for (std::list < std::string >::iterator iter = packageList.begin(); iter != packageList.end(); ++iter) { + PF_LOGD("package_id : %s", iter->c_str()); + bool ret = callback(iter->c_str(), user_data); + if (ret == false) + break; + } + + return retval; +} + +int privacy_guard_client_update_main_monitor_policy(const int user_id, const bool main_monitor_policy) +{ + if (user_id < 0) + return PRIV_FLTR_ERROR_INVALID_PARAMETER; + + PrivacyGuardClient *pInst = PrivacyGuardClient::getInstance(); + + int retval = pInst->PgUpdateMainMonitorPolicy(user_id, main_monitor_policy); + + return retval; +} + +int privacy_guard_client_get_main_monitor_policy(const int user_id, bool *main_monitor_policy) +{ + if (user_id < 0) + return PRIV_FLTR_ERROR_INVALID_PARAMETER; + + PrivacyGuardClient* pInst = PrivacyGuardClient::getInstance(); + + PF_LOGD("user_id : %d", user_id); + int retval = pInst->PgGetMainMonitorPolicy(user_id, *main_monitor_policy); + PF_LOGD("result > main_monitor_policy : %d", *main_monitor_policy); + + return retval; +} + +int privacy_guard_client_delete_main_monitor_policy_by_user_id(const int user_id) +{ + if (user_id < 0) + return PRIV_FLTR_ERROR_INVALID_PARAMETER; + + PrivacyGuardClient *pInst = PrivacyGuardClient::getInstance(); + + int retval = pInst->PgDeleteMainMonitorPolicyByUserId(user_id); + + return retval; +} diff --git a/client/src/privacy_guard_client_internal_types.h b/client/src/privacy_guard_client_internal_types.h new file mode 100755 index 0000000..ce59c3b --- /dev/null +++ b/client/src/privacy_guard_client_internal_types.h @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _PRIVACY_GUARD_CLIENT_INTERNAL_TYPES_H_ +#define _PRIVACY_GUARD_CLIENT_INTERNAL_TYPES_H_ + +#include + +#ifdef __cplusplus +extern "C" { +#endif + + +#ifdef __cplusplus +} +#endif + + +#endif //_PRIVACY_GUARD_CLIENT_INTERNAL_TYPES_H_ \ No newline at end of file diff --git a/common/inc/IPrivacyGuard.h b/common/inc/IPrivacyGuard.h new file mode 100755 index 0000000..9daa076 --- /dev/null +++ b/common/inc/IPrivacyGuard.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _IPRIVACYGUARD_H_ +#define _IPRIVACYGUARD_H_ + +#include +#include +#include +#include +#include +#include "PrivacyGuardTypes.h" + +class SocketClient; + +class EXTERN_API IPrivacyGuard +{ +public: + int addAppPackagePrivacyInfo(const std::string pkgId, const std::list < std::string >& pList, bool privacyPopupRequired); + + int removeAppPackagePrivacyInfo(const std::string pkgId); + + int setPrivacySetting(const std::string pkgId, const std::string privacyId, bool isEnabled); + + int getPrivacyAppPackages(std::list < std::string >& pList); + + int getAppPackagePrivacyInfo(const std::string pkgId, std::list < std::pair > & pList); +}; + +#endif // _IPRIVACYGUARD_H_ \ No newline at end of file diff --git a/common/inc/PrivacyGuardCommon.h b/common/inc/PrivacyGuardCommon.h new file mode 100755 index 0000000..3018420 --- /dev/null +++ b/common/inc/PrivacyGuardCommon.h @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _PRIVACY_GUARD_COMMON_H_ +#define _PRIVACY_GUARD_COMMON_H_ + +#include +#include +#include + +#endif // PRIVACYGUARDCOMMON_H_ diff --git a/common/inc/PrivacyGuardTypes.h b/common/inc/PrivacyGuardTypes.h new file mode 100755 index 0000000..1fd3deb --- /dev/null +++ b/common/inc/PrivacyGuardTypes.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _PRIVACYGUARDTYPES_H_ +#define _PRIVACYGUARDTYPES_H_ + +#include +#include +#include "privacy_guard_client_types.h" + +#define PRIVACY_DB_PATH tzplatform_mkpath(TZ_SYS_DB,".privacy_guard.db") +#define PRIVACY_INFO_DB_PATH tzplatform_mkpath(TZ_SYS_DB,".privacy_guard_privacylist.db") + +typedef struct _privacy_data_s { + char* privacy_id; + int monitor_policy; +} privacy_data_s; + +static const std::string SERVER_ADDRESS ("/tmp/privacy_guard_server"); +static const std::string DBUS_PATH("/privacy_guard/dbus_notification"); +static const std::string DBUS_SIGNAL_INTERFACE("org.tizen.privacy_guard.signal"); +static const std::string DBUS_SIGNAL_SETTING_CHANGED("privacy_setting_changed"); +static const std::string DBUS_SIGNAL_PKG_REMOVED("privacy_pkg_removed"); + +#endif // _PRIVACYGUARDTYPES_H_ diff --git a/common/inc/PrivacyIdInfo.h b/common/inc/PrivacyIdInfo.h new file mode 100755 index 0000000..3504f48 --- /dev/null +++ b/common/inc/PrivacyIdInfo.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _PRIVACYIDINFO_H_ +#define _PRIVACYIDINFO_H_ + +#include +#include +#include + +class PrivacyIdInfo +{ +private: + static std::map< std::string, std::string > m_privilegeToPrivacyMap; + static bool m_isInitialized; + +public: + static int initialize(void); + static int getPrivacyIdFromPrivilege(const std::string privilege, std::string& privacyId); + static int getPrivilegeListFromPrivacyId(const std::string privacyId, std::list< std::string > & privilegeList); + static int getPrivacyIdListFromPrivilegeList(const std::list< std::string > privilegeList, std::list< std::string >& privacyIdList); + static bool isValidPrivacyId(const std::string privacyId); + static int getAllPrivacyId(std::list< std::string >& privacyIdList); + static int getPrivaycDisplayName(const std::string privacyId, std::string& displayName); + static int getPrivaycDescription(const std::string privacyId, std::string& description); + static int isFeatureEnabled(const char* feature, bool& enabled); +}; + +#endif //_PRIVACYIDINFO_H_ diff --git a/common/inc/SocketConnection.h b/common/inc/SocketConnection.h new file mode 100755 index 0000000..01bf9a4 --- /dev/null +++ b/common/inc/SocketConnection.h @@ -0,0 +1,398 @@ +/* + * Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _SOCKETCONNECTION_H_ +#define _SOCKETCONNECTION_H_ + +#include +#include +#include +#include +#include +#include "Utils.h" +#include "SocketStream.h" +#include "PrivacyGuardTypes.h" + +/* + * This class implements interface for generic read and write from given socket. + * It does not maintain socket descriptor, so any connecting and disconnecting should be + */ + +/* + * Throws SocketConnectionException when read/write will not succeed or if any bad allocation + * exception occurs during read. + */ + +class EXTERN_API SocketConnection +{ + +public: + + explicit SocketConnection(int socket_fd) : m_socketStream(socket_fd){ + LOGI("Created"); + } + + template + int read(T* out, const Args&... args ) + { + int res = read(out); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "read : %d", res); + res = read(args...); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "read : %d", res); + + return PRIV_FLTR_ERROR_SUCCESS; + } + + template + int read(T* out) + { + int length = 0; + int res = m_socketStream.readStream(sizeof(length), &length); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "readStream : %d", res); + char* pBuf = new (std::nothrow) char[length + 1]; + TryReturn(pBuf != NULL, PRIV_FLTR_ERROR_OUT_OF_MEMORY, , "new : %d", PRIV_FLTR_ERROR_OUT_OF_MEMORY); + + res = m_socketStream.readStream(length, pBuf); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, delete[] pBuf, "readStream : %d", res); + + pBuf[length] = 0; + + out = T(pBuf); + + delete[] pBuf; + + return PRIV_FLTR_ERROR_SUCCESS; + } + + int read(bool* pB) + { + int length = 0; + int res = m_socketStream.readStream(sizeof(length), &length); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "readStream : %d", res); + + char* pBuf = new (std::nothrow) char[length + 1]; + TryReturn(pBuf != NULL, PRIV_FLTR_ERROR_OUT_OF_MEMORY, , "new : %d", PRIV_FLTR_ERROR_OUT_OF_MEMORY); + + res = m_socketStream.readStream(length, pBuf); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, delete[] pBuf, "readStream : %d", res); + + pBuf[length] = 0; + + *pB = * reinterpret_cast (pBuf); + + delete[] pBuf; + + return PRIV_FLTR_ERROR_SUCCESS; + } + + int read(bool& b) + { + return read(&b); + } + + int read(int& i) + { + return read(&i); + } + + int read(int* pI) + { + int length = 0; + int res = m_socketStream.readStream(sizeof(length), &length); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "readStream : %d", res); + + char* pBuf = new (std::nothrow) char[length + 1]; + TryReturn(pBuf != NULL, PRIV_FLTR_ERROR_OUT_OF_MEMORY, , "new : %d", PRIV_FLTR_ERROR_OUT_OF_MEMORY); + + res = m_socketStream.readStream(length, pBuf); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, delete[] pBuf, "readStream : %d", res); + + pBuf[length] = 0; + + *pI = * reinterpret_cast (pBuf); + + delete[] pBuf; + + return PRIV_FLTR_ERROR_SUCCESS; + } + + int read(unsigned int* pUi) + { + int length = 0; + int res = m_socketStream.readStream(sizeof(length), &length); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "readStream : %d", res); + + char* pBuf = new (std::nothrow) char[length + 1]; + TryReturn(pBuf != NULL, PRIV_FLTR_ERROR_OUT_OF_MEMORY, , "new : %d", PRIV_FLTR_ERROR_OUT_OF_MEMORY); + + res = m_socketStream.readStream(length, pBuf); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, delete[] pBuf, "readStream : %d", res); + + pBuf[length] = 0; + + *pUi = * reinterpret_cast (pBuf); + + delete[] pBuf; + + return PRIV_FLTR_ERROR_SUCCESS; + } + int read(std::string* pStr) + { + int length = 0; + int res = m_socketStream.readStream(sizeof(length), &length); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "readStream : %d", res); + + char* pBuf = new (std::nothrow) char[length + 1]; + TryReturn(pBuf != NULL, PRIV_FLTR_ERROR_OUT_OF_MEMORY, , "new : %d", PRIV_FLTR_ERROR_OUT_OF_MEMORY); + + m_socketStream.readStream(length, pBuf); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, delete[] pBuf, "readStream : %d", res); + + pBuf[length] = 0; + + *pStr = std::string(pBuf); + delete[] pBuf; + + return PRIV_FLTR_ERROR_SUCCESS; + } + + int read(std::string& str) + { + return read(&str); + } + + int read(privacy_data_s& out) + { + int length = 0; + int res = 0; + char* pBuf; + // privacy id + res = m_socketStream.readStream(sizeof(length), &length); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "readStream : %d", res); + pBuf = new (std::nothrow) char[length + 1]; + TryReturn(pBuf != NULL, PRIV_FLTR_ERROR_OUT_OF_MEMORY, , "new : %d", PRIV_FLTR_ERROR_OUT_OF_MEMORY); + m_socketStream.readStream(length, pBuf); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, delete[] pBuf, "readStream : %d", res); + pBuf[length] = 0; + out.privacy_id = strdup(pBuf); + delete[] pBuf; + + // monitor policy + res = read(&(out.monitor_policy)); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "readStream : %d", res); + + return PRIV_FLTR_ERROR_SUCCESS; + } + template < typename T > + int read (std::list& list) + { + int length = 0; + int res = read(length); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "read : %d", res); + + for (int i = 0; i < length; ++i) + { + T obj; + res = read (obj); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "read : %d", res); + list.push_back(obj); + } + + return PRIV_FLTR_ERROR_SUCCESS; + } + + template < typename T > + int read (std::list* pList) + { + return read(*pList); + } + + template < typename K, typename P > + int read (std::pair& pair) + { + int res = read( pair.first); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "read : %d", res); + res = read( pair.second); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "read : %d", res); + + return PRIV_FLTR_ERROR_SUCCESS; + } + + template < typename K, typename P > + int read (std::pair* pPair) + { + return read( *pPair); + } + + template + int write(const T& in, const Args&... args) + { + int res = write(in); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "write : %d", res); + res = write(args...); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "write : %d", res); + + return PRIV_FLTR_ERROR_SUCCESS; + } + + int write(const std::string& in) + { + int length = in.size(); + int res = m_socketStream.writeStream(sizeof(length), &length); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "writeStream : %d", res); + res = m_socketStream.writeStream(length, in.c_str()); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "writeStream : %d", res); + + return PRIV_FLTR_ERROR_SUCCESS; + } + + int write(const unsigned int& in) + { + int length = sizeof(in); + int res = m_socketStream.writeStream(sizeof(length), &length); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "writeStream : %d", res); + res = m_socketStream.writeStream(length, &in); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "writeStream : %d", res); + + return PRIV_FLTR_ERROR_SUCCESS; + } + + int write(const int& in) + { + int length = sizeof(in); + int res = m_socketStream.writeStream(sizeof(length), &length); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "writeStream : %d", res); + res = m_socketStream.writeStream(length, &in); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "writeStream : %d", res); + + return PRIV_FLTR_ERROR_SUCCESS; + } + + int write(const bool& in) + { + int length = sizeof(in); + int res = m_socketStream.writeStream(sizeof(length), &length); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "writeStream : %d", res); + res = m_socketStream.writeStream(length, &in); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "writeStream : %d", res); + + return PRIV_FLTR_ERROR_SUCCESS; + } + + int write(const char*& in) + { + int length = strlen(in); + int res = m_socketStream.writeStream(sizeof(length), &length); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "writeStream : %d", res); + res = m_socketStream.writeStream(length, in); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "writeStream : %d", res); + + return PRIV_FLTR_ERROR_SUCCESS; + } + + int write(const char* in_str, const int in_int1, const int in_int2) + { + int res = 0; + res = write(in_str); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "write : %d", res); + res = write(in_int1); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "write : %d", res); + res = write(in_int2); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "write : %d", res); + return PRIV_FLTR_ERROR_SUCCESS; + } + + int write(const privacy_data_s& in) + { + // privacy id + int length = strlen(in.privacy_id); + int res = 0; + res = m_socketStream.writeStream(sizeof(length), &length); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "writeStream : %d", res); + res = m_socketStream.writeStream(length, in.privacy_id); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "writeStream : %d", res); + + // monitor policy + res = write(in.monitor_policy); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "write : %d", res); + + return PRIV_FLTR_ERROR_SUCCESS; + } + template + int write(const T* in, const Args&... args) + { + int res = write(in); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "write : %d", res); + res = write(args...); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "write : %d", res); + + return PRIV_FLTR_ERROR_SUCCESS; + } + + template + int write(const std::pair p) + { + int res = write(p.first); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "write : %d", res); + res = write(p.second); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "write : %d", res); + + return PRIV_FLTR_ERROR_SUCCESS; + } + + template + int write(const std::pair p) + { + int res = write(p.first); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "write : %d", res); + res = write(p.second); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "write : %d", res); + + return PRIV_FLTR_ERROR_SUCCESS; + } + + template + int write(const std::pair* pPair) + { + return write(*pPair); + } + + template + int write(const std::list list) + { + int length = list.size(); + int res = write(length); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "write : %d", res); + for (typename std::list ::const_iterator iter = list.begin(); iter != list.end(); iter++) { + res = write(*iter); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "write : %d", res); + } + + return PRIV_FLTR_ERROR_SUCCESS; + } + + template + int write(const std::list * pList) + { + return write(*pList); + } + + +private: + SocketStream m_socketStream; +}; + +#endif // _SOCKETCONNECTION_H_ diff --git a/common/inc/SocketStream.h b/common/inc/SocketStream.h new file mode 100755 index 0000000..6fe3449 --- /dev/null +++ b/common/inc/SocketStream.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _SOCKETSTREAM_H_ +#define _SOCKETSTREAM_H_ + +#include +#include "PrivacyGuardTypes.h" + +class EXTERN_API SocketStream +{ +public: + explicit SocketStream(int socket_fd) + : m_socketFd(socket_fd) + , m_bytesRead(0) + ,m_bytesWrote(0) + { + LOGI("Created"); + } + + int readStream(size_t num, void * bytes); + int writeStream(size_t num, const void * bytes); +private: + int throwWithErrnoMessage(std::string specificInfo); + int m_socketFd; + int m_bytesRead; + int m_bytesWrote; +}; + +#endif //_SOCKETSTREAM_H_ \ No newline at end of file diff --git a/common/inc/Utils.h b/common/inc/Utils.h new file mode 100755 index 0000000..2c66fe0 --- /dev/null +++ b/common/inc/Utils.h @@ -0,0 +1,132 @@ +/* + * Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _UTILS_H_ +#define _UTILS_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// debug print ///////////////////////////////////////////// + +#if defined(_PRIVACY_GUARD_DEBUG) || defined(_PRIVACY_GUARD_DEBUG_INFO) || defined(_PRIVACY_GUARD_DEBUG_ERROR) +#ifdef _PRIVACY_GUARD_DEBUG +#define PF_LOGD(fmt, arg...) LOGD(fmt, ##arg) +#define PF_LOGI(fmt, arg...) LOGI(fmt, ##arg) +#define PF_LOGE(fmt, arg...) LOGE(fmt, ##arg) + +// _PRIVACY_GUARD_DEBUG_INFO +#elif _PRIVACY_GUARD_DEBUG_INFO +#define PF_LOGD(fmt, arg...) +#define PF_LOGI(fmt, arg...) LOGI(fmt, ##arg) +#define PF_LOGE(fmt, arg...) LOGE(fmt, ##arg) + +// _PRIVACY_GUARD_DEBUG_ERROR +#elif _PRIVACY_GUARD_DEBUG_ERROR +#define PF_LOGD(fmt, arg...) +#define PF_LOGI(fmt, arg...) +#define PF_LOGE(fmt, arg...) LOGE(fmt, ##arg) +#endif + +#else +#define PF_LOGD(fmt, arg...) +#define PF_LOGI(fmt, arg...) +#define PF_LOGE(fmt, arg...) +#endif + +////////////////////////////////////////////////////////////////////////// + + +#define IF_MATCH_RET_ERROR(condition, msgFormat, error) \ + if (condition) { \ + PF_LOGE(msgFormat, error); \ + return error; \ + } else {;} +#define TryCatchLogReturn(condition, expr, r, logFormat) if (!(condition)) { \ + LOGE(logFormat); \ + expr; \ + return r; \ + } else {;} + +#define TryCatchResLogReturn(condition, expr, r, logFormat, res) if (!(condition)) { \ + LOGE(logFormat, res); \ + expr; \ + return r; \ + } else {;} + + +#define TryReturn(condition, r, expr, ...) \ + if ( !(condition) ) { \ + LOGE(__VA_ARGS__); \ + expr; \ + return r; \ + } else {;} + +#define SAFE_FREE(var) \ + if(var != NULL) { \ + free(var); \ + var = NULL; \ + } + +auto StmtDeleter = [&](sqlite3_stmt* pPtr) { sqlite3_reset (pPtr); sqlite3_finalize(pPtr); }; +auto DbDeleter = [&](sqlite3* pPtr) { /*sqlite3_close(pPtr);*/ db_util_close(pPtr); }; + +#define setStmtToUniquePtr(x, y) std::unique_ptr < sqlite3_stmt, decltype(StmtDeleter) > x (y, StmtDeleter); +#define setDbToUniquePtr(x, y) std::unique_ptr < sqlite3, decltype(DbDeleter) > x (y, DbDeleter); + +#define openDb(dbpath, pHandler, mode) sqlite3* pHandler##Temp = NULL;\ + {\ + /*int res = sqlite3_open_v2(dbpath, &pHandler##Temp, mode , NULL);*/\ + int res = db_util_open_with_options(dbpath, &pHandler##Temp, mode, NULL);\ + TryCatchResLogReturn(res == SQLITE_OK, , PRIV_FLTR_ERROR_DB_ERROR, "db_util_open_with_options : %d", res);\ + }\ + setDbToUniquePtr(pHandler, pHandler##Temp);\ + +static const int MAX_DATABASE_RETRY_COUNT = 5; +static const int SLEEP_TIME = 50000; +#define prepareDb(pHandler, sql, pStmt) sqlite3_stmt* pStmt##Temp;\ + {\ + int res = SQLITE_OK;\ + for (int dbRetryCount = 0; dbRetryCount < MAX_DATABASE_RETRY_COUNT; dbRetryCount++)\ + {\ + res = sqlite3_prepare_v2(pHandler.get(), sql, -1, & pStmt##Temp, NULL);\ + if (res != SQLITE_BUSY)\ + {\ + break;\ + }\ + else\ + {\ + LOGE("[DbRetryCount][%d]: Database is busy!", dbRetryCount); \ + usleep(SLEEP_TIME);\ + }\ + }\ + TryCatchResLogReturn(res == SQLITE_OK, , PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_prepare_v2 : %d", res);\ + }\ + setStmtToUniquePtr(pStmt, pStmt##Temp); + +class Utils +{ +public: + static std::string toHash (std::string src); +}; +#endif //_UTILS_H_ diff --git a/common/src/PrivacyIdInfo.cpp b/common/src/PrivacyIdInfo.cpp new file mode 100755 index 0000000..e756841 --- /dev/null +++ b/common/src/PrivacyIdInfo.cpp @@ -0,0 +1,287 @@ +/* + * Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include "PrivacyIdInfo.h" +#include "privacy_guard_client_types.h" +#include "PrivacyGuardTypes.h" +#include "Utils.h" + +std::map< std::string, std::string > PrivacyIdInfo::m_privilegeToPrivacyMap; +bool PrivacyIdInfo:: m_isInitialized; + +int +PrivacyIdInfo::initialize(void) +{ + static const std::string sqlPrivilege("SELECT PRIVILEGE_ID, PRIVACY_ID from PrivilegeToPrivacyTable"); + static const std::string sqlPrivacyInfo("SELECT FEATURE FROM PrivacyInfo where PRIVACY_ID=?"); + + openDb(PRIVACY_INFO_DB_PATH, pDbHandler, SQLITE_OPEN_READONLY); + prepareDb(pDbHandler, sqlPrivilege.c_str(), pStmtPrivilege); + + int res; + while ((res = sqlite3_step(pStmtPrivilege.get())) == SQLITE_ROW) + { + const char* privilegeId = reinterpret_cast < const char* > (sqlite3_column_text(pStmtPrivilege.get(), 0)); + const char* privacyId = reinterpret_cast < const char* > (sqlite3_column_text(pStmtPrivilege.get(), 1)); + + prepareDb(pDbHandler, sqlPrivacyInfo.c_str(), pStmtPrivacyInfo); + res = sqlite3_bind_text(pStmtPrivacyInfo.get(), 1, privacyId, -1, SQLITE_TRANSIENT); + TryReturn(res == SQLITE_OK, PRIV_FLTR_ERROR_DB_ERROR, , "sqlite3_bind_text : %d", res); + res = sqlite3_step(pStmtPrivacyInfo.get()); + LOGD("privacy id : %s", privacyId); + TryReturn(res == SQLITE_DONE || res == SQLITE_ROW, PRIV_FLTR_ERROR_DB_ERROR, , "sqlite3_step : %d", res); + + const char* feature = reinterpret_cast < const char* > (sqlite3_column_text(pStmtPrivacyInfo.get(), 0)); + if (feature != NULL) + { + bool isSupported = false; + + res = isFeatureEnabled(feature, isSupported); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "isFeatureEnabled : %d", res); + + if (!isSupported) + { + continue; + } + } + + m_privilegeToPrivacyMap.insert(std::map< std::string, std::string >::value_type(std::string(privilegeId), std::string(privacyId))); + } + + m_isInitialized = true; + + return PRIV_FLTR_ERROR_SUCCESS; +} + +int +PrivacyIdInfo::getPrivacyIdFromPrivilege(const std::string privilege, std::string& privacyId) +{ + if (!m_isInitialized) + { + initialize(); + } + + std::map< std::string, std::string >::iterator iter = m_privilegeToPrivacyMap.find(privilege); + if (iter == m_privilegeToPrivacyMap.end()) + { + return PRIV_FLTR_ERROR_NO_DATA; + } + privacyId = iter->second; + + return PRIV_FLTR_ERROR_SUCCESS; +} + +int +PrivacyIdInfo::getPrivilegeListFromPrivacyId(const std::string privacyId, std::list< std::string >& privilegeList) +{ + if (!m_isInitialized) + { + initialize(); + } + + privilegeList.clear(); + for (std::map< std::string, std::string >::iterator iter = m_privilegeToPrivacyMap.begin(); iter != m_privilegeToPrivacyMap.end(); ++iter) + { + if (privacyId.compare((iter->second)) == 0) + { + privilegeList.push_back(iter->first); + } + } + + if (privilegeList.size() == 0) + { + LOGE("PrivilegeList of %s privacy is empty!", privacyId.c_str()); + return PRIV_FLTR_ERROR_NO_DATA; + } + + return PRIV_FLTR_ERROR_SUCCESS; +} + +int +PrivacyIdInfo::getPrivacyIdListFromPrivilegeList(const std::list< std::string > privilegeList, std::list< std::string >& privacyIdList) +{ + if (!m_isInitialized) + { + initialize(); + } + + privacyIdList.clear(); + + std::set< std::string > privacyIdSet; + + for (std::list< std::string >::const_iterator iter = privilegeList.begin(); iter != privilegeList.end(); ++iter) + { + std::string privacyId; + int res = getPrivacyIdFromPrivilege(*iter, privacyId); + if (res == PRIV_FLTR_ERROR_SUCCESS) + { + privacyIdSet.insert(privacyId); + } + } + + for (std::set< std::string >::iterator iter = privacyIdSet.begin(); iter != privacyIdSet.end(); ++iter) + { + privacyIdList.push_back(*iter); + } + + return PRIV_FLTR_ERROR_SUCCESS; +} + +bool +PrivacyIdInfo::isValidPrivacyId(const std::string privacyId) +{ + if (!m_isInitialized) { + initialize(); + } + + for (std::map< std::string, std::string >::iterator iter = m_privilegeToPrivacyMap.begin(); iter != m_privilegeToPrivacyMap.end(); ++iter) { + if (privacyId.compare((iter->second)) == 0) { + return true; + } + } + + return false; +} + +int +PrivacyIdInfo::getAllPrivacyId(std::list< std::string >& privacyIdList) +{ + static const std::string sql("SELECT PRIVACY_ID, FEATURE from PrivacyInfo"); + + if (!m_isInitialized) + { + initialize(); + } + + openDb(PRIVACY_INFO_DB_PATH, pDbHandler, SQLITE_OPEN_READONLY); + prepareDb(pDbHandler, sql.c_str(), pStmt); + + int res; + while ((res = sqlite3_step(pStmt.get())) == SQLITE_ROW) + { + const char* privacyId = reinterpret_cast < const char* > (sqlite3_column_text(pStmt.get(), 0)); + const char* feature = reinterpret_cast < const char* > (sqlite3_column_text(pStmt.get(), 1)); + LOGD("privacy: %s, feature: %s", privacyId, feature); + + if (feature != NULL) + { + bool isSupported = false; + res = isFeatureEnabled(feature, isSupported); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "isFeatureEnabled : %d", res); + if (!isSupported) + { + continue; + } + } + + privacyIdList.push_back(std::string(privacyId)); + SECURE_LOGD(" privacy Id : %s", privacyId); + } + + return PRIV_FLTR_ERROR_SUCCESS; +} + +int +PrivacyIdInfo::getPrivaycDisplayName(const std::string privacyId, std::string& displayName) +{ + if (!m_isInitialized) + { + initialize(); + } + + std::string sql = std::string("SELECT STR_MODULE_ID, STR_NAME_ID from PrivacyInfo where PRIVACY_ID=?"); + + openDb(PRIVACY_INFO_DB_PATH, pDbHandler, SQLITE_OPEN_READONLY); + prepareDb(pDbHandler, sql.c_str(), pStmt); + + int res = sqlite3_bind_text(pStmt.get(), 1, privacyId.c_str(), -1, SQLITE_TRANSIENT); + TryReturn(res == SQLITE_OK, PRIV_FLTR_ERROR_DB_ERROR, , "sqlite3_bind_text : %d", res); + + if (sqlite3_step(pStmt.get()) == SQLITE_ROW) + { + const char* pModuleId = reinterpret_cast < const char* > (sqlite3_column_text(pStmt.get(), 0)); + const char* pNameId = reinterpret_cast < const char* > (sqlite3_column_text(pStmt.get(), 1)); + + if (pNameId == NULL) + { + displayName = privacyId; + } + else + { + displayName = std::string(dgettext(pModuleId, pNameId)); + } + } + else + { + LOGI("Cannot find privacy string %s ", privacyId.c_str()); + return PRIV_FLTR_ERROR_NO_DATA; + } + + return PRIV_FLTR_ERROR_SUCCESS; +} + +int +PrivacyIdInfo::getPrivaycDescription(const std::string privacyId, std::string& displayName) +{ + if (!m_isInitialized) + { + initialize(); + } + + std::string sql = std::string("SELECT STR_MODULE_ID, STR_NAME_ID from PrivacyInfo where PRIVACY_ID=?"); + + openDb(PRIVACY_INFO_DB_PATH, pDbHandler, SQLITE_OPEN_READONLY); + prepareDb(pDbHandler, sql.c_str(), pStmt); + + int res = sqlite3_bind_text(pStmt.get(), 1, privacyId.c_str(), -1, SQLITE_TRANSIENT); + TryReturn(res == SQLITE_OK, PRIV_FLTR_ERROR_DB_ERROR, , "sqlite3_bind_text : %d", res); + + if (sqlite3_step(pStmt.get()) == SQLITE_ROW) + { + const char* pModuleId = reinterpret_cast < const char* > (sqlite3_column_text(pStmt.get(), 0)); + const char* pNameId = reinterpret_cast < const char* > (sqlite3_column_text(pStmt.get(), 1)); + + displayName = std::string(dgettext(pModuleId, pNameId)); + } + else + { + LOGI("Cannot find privacy string %s ", privacyId.c_str()); + return PRIV_FLTR_ERROR_NO_DATA; + } + + return PRIV_FLTR_ERROR_SUCCESS; +} + +int +PrivacyIdInfo::isFeatureEnabled(const char* feature, bool& enabled) +{ + int res = PRIV_FLTR_ERROR_SUCCESS; + + if (feature == NULL) + { + enabled = true; + return res; + } + + res = system_info_get_platform_bool(feature, &enabled); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, PRIV_FLTR_ERROR_SYSTEM_ERROR, , "system_info_get_platform_bool : %d", res); + + return PRIV_FLTR_ERROR_SUCCESS; +} diff --git a/common/src/SocketConnection.cpp b/common/src/SocketConnection.cpp new file mode 100755 index 0000000..bb9101c --- /dev/null +++ b/common/src/SocketConnection.cpp @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "SocketConnection.h" + +// +// Note: +// +// The file here is left blank to enable precompilation +// of templates in corresponding header file. +// Do not remove this file. +// diff --git a/common/src/SocketStream.cpp b/common/src/SocketStream.cpp new file mode 100755 index 0000000..c0ad730 --- /dev/null +++ b/common/src/SocketStream.cpp @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + +#include +#include +#include +#include +#include +#include +#include "Utils.h" +#include "SocketStream.h" + +#define READ_TIEMOUT_SEC 1 +#define READ_TIMEUOT_NSEC 0 +#define WRITE_TIMEOUT_SEC 0 +#define WRITE_TIMEOUT_NSEC 100000000 +#define MAX_BUFFER 10240 + +int +SocketStream::throwWithErrnoMessage(std::string function_name) +{ + LOGE("%s : %s", function_name.c_str(), strerror(errno)); + return errno; +} + +int +SocketStream::readStream(size_t num, void* pBytes) +{ + TryReturn(pBytes != NULL, -1, , "Null pointer to buffer"); + + m_bytesRead += num; + + TryReturn(m_bytesRead <= MAX_BUFFER, -1, , "Too big buffer requested!"); + + char partBuffer[MAX_BUFFER]; + std::string wholeBuffer; + + fd_set rset, allset; + int maxFd; + ssize_t bytesRead = 0; + ssize_t bytesToRead = (ssize_t) num; + + timespec timeout; + + maxFd = m_socketFd; + ++maxFd; + + FD_ZERO(&allset); + FD_SET(m_socketFd, &allset); + + int ret = -1; + + while(bytesToRead != 0) + { + timeout.tv_sec = READ_TIEMOUT_SEC; + timeout.tv_nsec = READ_TIMEUOT_NSEC; + rset = allset; + + if ( (ret = pselect(maxFd, &rset, NULL, NULL, &timeout, NULL)) == -1 ) + { + if (errno == EINTR) + continue; + LOGD("pselect : %s", strerror(errno)); + return -1; + } + //This means pselect got timedout + //This is not a proper behavior in reading data from UDS + //And could mean we got corrupted connection + TryReturn(ret != 0, -1, , "Couldn't read whole data"); + + if ( FD_ISSET(m_socketFd, &rset) ) + { + bytesRead = read(m_socketFd, partBuffer, num); + if ( bytesRead <= 0 ) + { + if(errno == ECONNRESET || errno == ENOTCONN || errno == ETIMEDOUT) + { + LOGI("Connection closed : %s", strerror(errno)); + return -1; + } + else if (errno != EAGAIN && errno != EWOULDBLOCK){ + LOGI("read()"); + return -1; + } + } + + wholeBuffer.append(partBuffer, bytesRead); + bytesToRead -= bytesRead; + bytesRead = 0; + continue; + } + + } + memcpy(pBytes, wholeBuffer.c_str(), num); + + return 0; +} + +int +SocketStream::writeStream(size_t num, const void* pBytes) +{ + TryReturn(pBytes != NULL, -1, , "Null pointer to buffer"); + + m_bytesWrote += num; + + TryReturn(m_bytesRead <= MAX_BUFFER, -1, , "Too big buffer requested!"); + + fd_set wset, allset; + int maxFd; + + timespec timeout; + + maxFd = m_socketFd; + ++maxFd; + + FD_ZERO(&allset); + FD_SET(m_socketFd, &allset); + + int res; + int writeRes; + int bytesToWrite = num; + unsigned int currentOffset = 0; + + while(currentOffset != num) + { + timeout.tv_sec = WRITE_TIMEOUT_SEC; + timeout.tv_nsec = WRITE_TIMEOUT_NSEC; + wset = allset; + + if ( (res = pselect(maxFd, NULL, &wset, NULL, &timeout, NULL)) == -1 ) + { + if(errno == EINTR) + continue; + LOGD("pselect : %s", strerror(errno)); + return -1; + } + + if(FD_ISSET(m_socketFd, &wset)) + { + if ( (writeRes = write(m_socketFd, reinterpret_cast(pBytes) + currentOffset, bytesToWrite)) == -1) + { + if(errno == ECONNRESET || errno == EPIPE) + { + LOGI("Connection closed : %s", strerror(errno)); + return -1; + + } + else if(errno != EAGAIN && errno != EWOULDBLOCK) + { + LOGE("write()"); + return -1; + } + } + currentOffset += writeRes; + bytesToWrite -= writeRes; + } + } + return 0; +} \ No newline at end of file diff --git a/common/src/Utils.cpp b/common/src/Utils.cpp new file mode 100755 index 0000000..af8052e --- /dev/null +++ b/common/src/Utils.cpp @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "Utils.h" + +std::string Utils::toHash(std::string src) +{ + return src; +} \ No newline at end of file diff --git a/include/CMakeLists.txt b/include/CMakeLists.txt new file mode 100755 index 0000000..70766ea --- /dev/null +++ b/include/CMakeLists.txt @@ -0,0 +1,11 @@ +CMAKE_MINIMUM_REQUIRED(VERSION 2.6) +#PROJECT(privacy-guard-client) + +SET(PF_INCLUDE_PATH ${PROJECT_SOURCE_DIR}/include) + +SET(PRIVACY_GUARD_CLIENT_HEADERS + ${PF_INCLUDE_PATH}/privacy_guard_client.h + ${PF_INCLUDE_PATH}/privacy_guard_client_types.h + ) + +INSTALL(FILES ${PRIVACY_GUARD_CLIENT_HEADERS} DESTINATION ${INCLUDE_INSTALL_DIR}/privacy_guard) diff --git a/include/privacy_guard_client.h b/include/privacy_guard_client.h new file mode 100755 index 0000000..c42b206 --- /dev/null +++ b/include/privacy_guard_client.h @@ -0,0 +1,210 @@ +/* + * Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * @file privacy_guard_client.h + * @brief APIs for privacy-guard-client + */ + +#ifndef _PRIVACY_GUARD_CLIENT_H_ +#define _PRIVACY_GUARD_CLIENT_H_ + +#include +#include "privacy_guard_client_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/** + * @brief Called when the reply of the monitor policy request is delivered. + * @since tizen 3.0 + * + * @param[in] privacy_id The privacy ID + * @param[in] monitor_policy The monitor policy (0 or 1) + * @param[in] user_data The user data passed from the callback registration function + * + * @returns: true to continue with the next iteration of the loop, otherwise return false to break out of the loop + * + * @see privacy_guard_client_foreach_monitor_policy_by_package_id() + */ +typedef bool (*privacy_guard_client_monitor_policy_cb) (const char *privacy_id, const int monitor_policy, void *user_data); + +/** + * @brief Called when the reply of the package id request is delivered. + * @since tizen 3.0 + * + * @param[in] package_id The package ID + * @param[in] user_data The user data passed from the callback registration function + * + * @returns: true to continue with the next iteration of the loop, otherwise return false to break out of the loop + * + * @see privacy_guard_client_foreach_privacy_package_id() + */ +typedef bool (*privacy_guard_client_package_id_cb) (const char *package_id, void *user_data); + +/** + * @brief Called when the reply of the privacy count request is delivered. + * @since tizen 3.0 + * + * @param[in] privacy_id The privacy ID + * @param[in] count The privacy count + * @param[in] user_data The user data passed from the callback registration function + * + * @returns: true to continue with the next iteration of the loop, otherwise return false to break out of the loop + * + * @see privacy_guard_client_foreach_log_count_by_privacy_id() + */ +typedef bool (*privacy_guard_client_privacy_count_cb) (const char *privacy_id, const int count, void *user_data); + +/** + * @brief Called when the reply of the privacy count request of package is delivered. + * @since tizen 3.0 + * + * @param[in] privacy_id The privacy ID + * @param[in] count The privacy count of a package + * @param[in] user_data The user data passed from the callback registration function + * + * @returns: true to continue with the next iteration of the loop, otherwise return false to break out of the loop + * + * @see privacy_guard_client_foreach_log_count_by_package_id() + */ +typedef bool (*privacy_guard_client_privacy_count_of_package_cb) (const char *package_id, const int count, void *user_data); + +/** + * @fn int privacy_guard_client_foreach_total_privacy_count_of_package(const int user_id, const int start_date, const int end_date, privacy_guard_client_privacy_count_of_package_cb callback, void *user_data) + * @brief get total privacy access count for each packcage + * @param[in] user_id user ID + * @param[in] start_date start date to be monitored (Unix time) + * @param[in] end_date end date to be monitored (Unix time) + * @param[in] callback The callback function to invoke + * @param[in] user_data The user data to be passed to the callback function + */ +EXTERN_API int privacy_guard_client_foreach_total_privacy_count_of_package(const int user_id, const time_t start_date, const time_t end_date, privacy_guard_client_privacy_count_of_package_cb callback, void *user_data); + +/** + * @fn int privacy_guard_client_foreach_total_privacy_count_of_privacy(const int user_id, const int start_date, const int end_date, privacy_guard_client_privacy_count_cb callback, void *user_data) + * @brief get total privacy access count for each privacy + * @param[in] user_id user ID + * @param[in] start_date start date to be monitored (Unix time) + * @param[in] end_date end date to be monitored (Unix time) + * @param[in] callback The callback function to invoke + * @param[in] user_data The user data to be passed to the callback function + */ +EXTERN_API int privacy_guard_client_foreach_total_privacy_count_of_privacy(const int user_id, const time_t start_date, const time_t end_date, privacy_guard_client_privacy_count_cb callback, void *user_data); + +/** + * @fn int privacy_guard_client_foreach_privacy_count_by_privacy_id(const int user_id, const int start_date, const int end_date, const char* privacy_id, privacy_guard_client_privacy_count_of_package_cb callback, void *user_data) + * @brief get privacy access count by specified privacy + * @param[in] user_id user ID + * @param[in] start_date start date to be monitored (Unix time) + * @param[in] end_date end date to be monitored (Unix time) + * @param[in] privacy_id privacy ID + * @param[in] callback The callback function to invoke + * @param[in] user_data The user data to be passed to the callback function + */ +EXTERN_API int privacy_guard_client_foreach_privacy_count_by_privacy_id(const int user_id, const time_t start_date, const time_t end_date, const char *privacy_id, privacy_guard_client_privacy_count_of_package_cb callback, void *user_data); + +/** + * @fn int privacy_guard_client_foreach_privacy_count_by_package_id(const int user_id, const int start_date, const int end_date, const char *package_id, privacy_guard_client_privacy_count_cb callback, void *user_data) + * @brief get privacy access count by specified package + * @param[in] user_id user ID + * @param[in] start_date start date to be monitored (Unix time) + * @param[in] end_date end date to be monitored (Unix time) + * @param[in] package_id package ID + * @param[in] callback The callback function to invoke + * @param[in] user_data The user data to be passed to the callback function + */ +EXTERN_API int privacy_guard_client_foreach_privacy_count_by_package_id(const int user_id, const time_t start_date, const time_t end_date, const char *package_id, privacy_guard_client_privacy_count_cb callback, void *user_data); + +/** + * @fn int privacy_guard_client_update_monitor_policy(const int user_id, const char *package_id, const char *privacy_id, int monitor_policy) + * @brief update monitor policy + * @param[in] user_id The user ID + * @param[in] package_id The package ID + * @param[in] privacy_id The privacy ID + * @param[in] monitor_policy monitor policy (0 or 1) to be set + */ +EXTERN_API int privacy_guard_client_update_monitor_policy(const int user_id, const char *package_id, const char *privacy_id, const int monitor_policy); + +/** + * @fn int privacy_guard_client_foreach_monitor_policy_by_package_id(const int user_id, const char *package_id, + privacy_guard_client_monitor_policy_cb callback, void *user_data) + * @brief get monitor policy by package + * @param[in] user_id The user ID + * @param[in] package_id The package ID + * @param[in] callback The callback function to invoke + */ +EXTERN_API int privacy_guard_client_foreach_monitor_policy_by_package_id(const int user_id, const char *package_id, + privacy_guard_client_monitor_policy_cb callback, void *user_data); + +/** + * @fn int privacy_guard_client_check_privacy_package(const int user_id, const char *package_id, bool *is_privacy_package) + * @brief check whether the package use a privacy or not + * @param[in] user_id The user ID + * @param[in] package_id The package ID + * @param[out] is_privacy_package The result of privacy package or not + * @return the result of operation (ERRORCODE : success, ....) + */ +EXTERN_API int privacy_guard_client_check_privacy_package(const int user_id, const char *package_id, bool *is_privacy_package); + +/** + * @fn int privacy_guard_client_foreach_privacy_package_id(const int user_id, privacy_guard_client_package_id_cb callback, void *user_data) + * @brief get package using one or more privacy + * @param[in] user_id The user ID + * @param[in] callback The callback function to invoke + * @param[in] user_data The user data to be passed to the callback function + */ +EXTERN_API int privacy_guard_client_foreach_privacy_package_id(const int user_id, privacy_guard_client_package_id_cb callback, void *user_data); + +/** + * @fn int privacy_guard_client_foreach_package_by_privacy_id(const int user_id, const char *privacy_id, privacy_guard_client_package_id_cb callback, void *user_data) + * @brief get package using specified privacy + * @param[in] user_id The user ID + * @param[in] privacy_id The privacy ID + * @param[in] callback The callback function to invoke + * @param[in] user_data The user data to be passed to the callback function + */ +EXTERN_API int privacy_guard_client_foreach_package_by_privacy_id(const int user_id, const char *privacy_id, privacy_guard_client_package_id_cb callback, void *user_data); + +/** + * @fn int privacy_guard_client_update_main_monitor_policy(const int user_id, const bool main_monitor_policy) + * @brief update main monitor policy + * @param[in] user_id The user ID + * @param[in] main_monitor_policy The main monitor policy (false or true) to be set + */ +EXTERN_API int privacy_guard_client_update_main_monitor_policy(const int user_id, const bool main_monitor_policy); + +/** + * @fn int privacy_guard_client_update_main_monitor_policy(const int user_id, const bool main_monitor_policy) + * @brief get main monitor policy + * @param[in] user_id The user ID + * @param[out] main_monitor_policy The value of main monitor policy + */ +EXTERN_API int privacy_guard_client_get_main_monitor_policy(const int user_id, bool *main_monitor_policy); + +/** + * @fn int privacy_guard_client_update_main_monitor_policy(const int user_id, const bool main_monitor_policy) + * @brief Delete main monitor policy + * @param[in] user_id The user ID to be deleted + */ +EXTERN_API int privacy_guard_client_delete_main_monitor_policy_by_user_id(const int user_id); +#ifdef __cplusplus +} +#endif + + +#endif //_PRIVACY_GUARD_CLIENT_H_ diff --git a/include/privacy_guard_client_types.h b/include/privacy_guard_client_types.h new file mode 100755 index 0000000..bdce8a9 --- /dev/null +++ b/include/privacy_guard_client_types.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _PRIVACY_GUARD_CLIENT_TYPES_H_ +#define _PRIVACY_GUARD_CLIENT_TYPES_H_ + +#ifdef __cplusplus +extern "C" { +#endif + +#ifndef EXTERN_API +#define EXTERN_API __attribute__((visibility("default"))) +#endif + +enum { + PRIV_FLTR_ERROR_SUCCESS = 0, + + PRIV_FLTR_ERROR_NOT_INITIALIZED = -10, + PRIV_FLTR_ERROR_INVALID_PARAMETER = -11, + PRIV_FLTR_ERROR_OUT_OF_MEMORY = -12, + PRIV_FLTR_ERROR_IO_ERROR = -13, + PRIV_FLTR_ERROR_NO_DATA = -14, + PRIV_FLTR_ERROR_DB_ERROR = -15, + PRIV_FLTR_ERROR_IPC_ERROR = -16, + PRIV_FLTR_ERROR_INVALID_STATE = -17, + PRIV_FLTR_ERROR_SYSTEM_ERROR = -18, + PRIV_FLTR_ERROR_USER_NOT_CONSENTED = -19, + + PRIV_FLTR_ERROR_UNKNOWN = -(0x99), +}; + + +#ifdef __cplusplus +} +#endif + +#endif //_PRIVACY_GUARD_CLIENT_TYPES_H_ diff --git a/packaging/libprivacy-guard-client.manifest b/packaging/libprivacy-guard-client.manifest new file mode 100755 index 0000000..c00c25b --- /dev/null +++ b/packaging/libprivacy-guard-client.manifest @@ -0,0 +1,5 @@ + + + + + diff --git a/packaging/privacy-guard-client-devel.manifest b/packaging/privacy-guard-client-devel.manifest new file mode 100755 index 0000000..c00c25b --- /dev/null +++ b/packaging/privacy-guard-client-devel.manifest @@ -0,0 +1,5 @@ + + + + + diff --git a/packaging/privacy-guard-client.manifest b/packaging/privacy-guard-client.manifest new file mode 100755 index 0000000..c00c25b --- /dev/null +++ b/packaging/privacy-guard-client.manifest @@ -0,0 +1,5 @@ + + + + + diff --git a/packaging/privacy-guard-server-devel.manifest b/packaging/privacy-guard-server-devel.manifest new file mode 100755 index 0000000..c00c25b --- /dev/null +++ b/packaging/privacy-guard-server-devel.manifest @@ -0,0 +1,5 @@ + + + + + diff --git a/packaging/privacy-guard-server.manifest b/packaging/privacy-guard-server.manifest new file mode 100755 index 0000000..c00c25b --- /dev/null +++ b/packaging/privacy-guard-server.manifest @@ -0,0 +1,5 @@ + + + + + diff --git a/packaging/privacy-guard-server.service b/packaging/privacy-guard-server.service new file mode 100755 index 0000000..3d6b105 --- /dev/null +++ b/packaging/privacy-guard-server.service @@ -0,0 +1,14 @@ +[Unit] +Description=Privacy Guard Server + +[Service] +User=system +Group=system +Type=simple +ExecStart=/usr/bin/privacy-guard-server +Sockets=privacy-guard-server.socket +Restart=always +RestartSec=0 + +[Install] +WantedBy=multi-user.target diff --git a/packaging/privacy-guard-server.socket b/packaging/privacy-guard-server.socket new file mode 100755 index 0000000..9d165a2 --- /dev/null +++ b/packaging/privacy-guard-server.socket @@ -0,0 +1,13 @@ +[Unit] +Description=Privacy Guard Socket + +[Socket] +SocketUser=system +SocketGroup=system +ListenStream=/tmp/privacy_guard_server +SocketMode=0777 + +Service=privacy-guard-server.service + +[Install] +WantedBy=sockets.target diff --git a/packaging/privacy-guard.changes b/packaging/privacy-guard.changes new file mode 100755 index 0000000..8b13789 --- /dev/null +++ b/packaging/privacy-guard.changes @@ -0,0 +1 @@ + diff --git a/packaging/privacy-guard.spec b/packaging/privacy-guard.spec new file mode 100755 index 0000000..f50f614 --- /dev/null +++ b/packaging/privacy-guard.spec @@ -0,0 +1,131 @@ +Name: privacy-guard-server +Version: 0.0.1 +Release: 1 +License: Apache-2.0 +Summary: Privacy Management +Group: Security/Libraries +Source0: %{name}-%{version}.tar.gz +Source1: privacy-guard-server.service +Source2: privacy-guard-server.socket +Source1001: privacy-guard-server.manifest +Source1002: privacy-guard-server-devel.manifest +Source1003: privacy-guard-client.manifest +Source1004: privacy-guard-client-devel.manifest +BuildRequires: cmake +BuildRequires: gettext-tools +BuildRequires: pkgconfig(capi-base-common) +BuildRequires: pkgconfig(db-util) +BuildRequires: pkgconfig(dbus-1) +BuildRequires: pkgconfig(dbus-glib-1) +BuildRequires: pkgconfig(dlog) +BuildRequires: pkgconfig(glib-2.0) +BuildRequires: pkgconfig(libxml-2.0) +BuildRequires: pkgconfig(pkgmgr-info) +BuildRequires: pkgconfig(sqlite3) +BuildRequires: pkgconfig(capi-system-info) +BuildRequires: pkgconfig(libtzplatform-config) +#BuildRequires: pkgconfig(cynara-monitor) + +Requires(post): /sbin/ldconfig +Requires(postun): /sbin/ldconfig + +%description +Privacy Management + +%package -n privacy-guard-server-devel +Summary: Privacy Guard Server +Requires: privacy-guard-server = %{version} + +%description -n privacy-guard-server-devel +privacy-guard server devel + +%package -n privacy-guard-client +Summary: Privacy Guard client +Requires: privacy-guard-server = %{version} + +%description -n privacy-guard-client +privacy-guard client + +%package -n privacy-guard-client-devel +Summary: Privacy Guard client devel +Requires: privacy-guard-client = %{version} + +%description -n privacy-guard-client-devel +Privacy Management(development files) + + +%prep +%setup -q +cp %{SOURCE1001} . +cp %{SOURCE1002} . +cp %{SOURCE1003} . +cp %{SOURCE1004} . + +%build +%{!?build_type:%define build_type "Release"} +%cmake . -DPREFIX=%{_prefix} \ + -DEXEC_PREFIX=%{_exec_prefix} \ + -DLIBDIR=%{_libdir} \ + -DINCLUDEDIR=%{_includedir} \ + -DCMAKE_BUILD_TYPE=%{build_type} \ + -DVERSION=%{version} \ + -DFILTER_LISTED_PKG=ON \ + -DPRIVACY_POPUP=OFF +make %{?_smp_mflags} + +%install +mkdir -p %{buildroot}%{_prefix}/bin +cp res/usr/bin/* %{buildroot}%{_bindir}/ +mkdir -p %{buildroot}%{TZ_SYS_DB} +cp res/opt/dbspace/.privacy_guard_privacylist.db /%{buildroot}%{TZ_SYS_DB} + +%make_install +mkdir -p %{buildroot}%{_libdir}/systemd/system/multi-user.target.wants +install -m 0644 %{SOURCE1} %{buildroot}%{_libdir}/systemd/system/privacy-guard-server.service +ln -sf /usr/lib/systemd/system/privacy-guard-server.service %{buildroot}%{_libdir}/systemd/system/multi-user.target.wants/privacy-guard-server.service +mkdir -p %{buildroot}%{_libdir}/systemd/system/socket.target.wants +install -m 0644 %{SOURCE2} %{buildroot}%{_libdir}/systemd/system/privacy-guard-server.socket +ln -sf /usr/lib/systemd/system/privacy-guard-server.socket %{buildroot}%{_libdir}/systemd/system/socket.target.wants/privacy-guard-server.socket + + +%post -n privacy-guard-server +/sbin/ldconfig + +echo "Check privacy guard DB" +if [ ! -f %{TZ_SYS_DB}/.privacy_guard.db ] +then + echo "Create privacy guard DB" + %{_bindir}/privacy_guard_create_clean_db.sh +fi + +%postun -p /sbin/ldconfig + +%post -n privacy-guard-client -p /sbin/ldconfig +%postun -n privacy-guard-client -p /sbin/ldconfig + +/usr/sbin/setcap cap_chown,cap_dac_override,cap_lease+eip /usr/bin/privacy-guard-server + + +%files -n privacy-guard-server +%defattr(-,root,root,-) +%license LICENSE.APLv2 +%manifest privacy-guard-server.manifest +%{TZ_SYS_DB}/.privacy_guard_privacylist.db +%{_bindir}/* +%{_libdir}/systemd/system/* + + +%files -n privacy-guard-server-devel +%{_libdir}/pkgconfig/privacy-guard-server.pc + +%files -n privacy-guard-client +%defattr(-,root,root,-) +%license LICENSE.APLv2 +%manifest privacy-guard-client.manifest +%{_libdir}/libprivacy-guard-client.so* + +%files -n privacy-guard-client-devel +%defattr(-,root,root,-) +%manifest privacy-guard-client-devel.manifest +%{_includedir}/* +%{_libdir}/pkgconfig/privacy-guard-client.pc diff --git a/pkgmgr_plugin/CMakeLists.txt b/pkgmgr_plugin/CMakeLists.txt new file mode 100755 index 0000000..ef56e81 --- /dev/null +++ b/pkgmgr_plugin/CMakeLists.txt @@ -0,0 +1,66 @@ +CMAKE_MINIMUM_REQUIRED(VERSION 2.6) + +SET (this_target privileges) + +SET(LIBRARY_OUTPUT_PATH ${CMAKE_SOURCE_DIR}/cmake_build_tmp/output) + +INCLUDE(FindPkgConfig) +pkg_check_modules(pkg REQUIRED glib-2.0 dlog libxml-2.0 ) + +FOREACH(flag ${privileges_CFLAGS}) + SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}") +ENDFOREACH(flag) + +INCLUDE_DIRECTORIES( + /usr/include + /usr/include/glib-2.0 + /usr/include/libxml2 + /usr/include/package_manager + /usr/include/dlog + "${CMAKE_SOURCE_DIR}/client/inc/" + "${CMAKE_SOURCE_DIR}/common/inc/" + "${CMAKE_SOURCE_DIR}/include/" + ) + +SET (${this_target}_SOURCE_FILES + privileges.cpp + ) + +ADD_DEFINITIONS("-DDLOG_ERROR_ENABLED") +ADD_DEFINITIONS("-DLOG_TAG=\"PRIVILEGE_PLUGIN\"") +SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} -Wall" ) + +SET(CMAKE_C_FLAGS_PROFILING " -g -pg") +SET(CMAKE_CXX_FLAGS_PROFILING " -std=c++0x -g -pg") +SET(CMAKE_C_FLAGS_DEBUG " -g") +SET(CMAKE_CXX_FLAGS_DEBUG " -std=c++0x -g") +SET(CMAKE_C_FLAGS_RELEASE " -g") +SET(CMAKE_CXX_FLAGS_RELEASE " -std=c++0x -g") +SET(CMAKE_C_FLAGS_CCOV " -g --coverage") +SET(CMAKE_CXX_FLAGS_CCOV " -std=c++0x -g --coverage") + +## Create Library +ADD_LIBRARY (${this_target} SHARED ${${this_target}_SOURCE_FILES} ) +ADD_DEPENDENCIES(${this_target} privacy-guard-client) +## SET LINKER FLAGS +SET(CMAKE_SHARED_LINKER_FLAGS -Wl,--no-undefined) +## SET PRIVACY_POPUP FLAG +OPTION (PRIVACY_POPUP "PRIVACY_POPUP" ON) +IF(PRIVACY_POPUP) + MESSAGE("PRIVACY_POPUP IS ENABLED") + ADD_DEFINITIONS("-D__PRIVACY_POPUP") +ENDIF(PRIVACY_POPUP) + + +TARGET_LINK_LIBRARIES(${this_target} ${pkg_LDFLAGS} ${pkg_LIBRARIES}) +TARGET_LINK_LIBRARIES(${this_target} "-lprivacy-guard-client" "-L../client" ) + +ADD_CUSTOM_COMMAND(TARGET ${this_target} + POST_BUILD + COMMAND ${CMAKE_COMMAND} -E copy ${LIBRARY_OUTPUT_PATH}/${CMAKE_SHARED_LIBRARY_PREFIX}${this_target}${CMAKE_SHARED_LIBRARY_SUFFIX} ${LIBRARY_OUTPUT_PATH}/debug/${CMAKE_SHARED_LIBRARY_PREFIX}${this_target}${CMAKE_SHARED_LIBRARY_SUFFIX} + COMMAND ${CMAKE_STRIP} --strip-unneeded ${LIBRARY_OUTPUT_PATH}/${CMAKE_SHARED_LIBRARY_PREFIX}${this_target}${CMAKE_SHARED_LIBRARY_SUFFIX} + COMMENT "strip ${this_target}" + ) + +#INSTALL(TARGETS ${this_target} DESTINATION "../etc/package-manager/parserlib") + diff --git a/pkgmgr_plugin/privileges.cpp b/pkgmgr_plugin/privileges.cpp new file mode 100755 index 0000000..2c348b0 --- /dev/null +++ b/pkgmgr_plugin/privileges.cpp @@ -0,0 +1,167 @@ +// +// Open Service Platform +// Copyright (c) 2013 Samsung Electronics Co., Ltd. +// +// Licensed under the Apache License, Version 2.0 (the License); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT 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 +#include +#include +#include +#include +#include +#include "privacy_guard_client_internal.h" +#include "PrivacyGuardClient.h" + +static const xmlChar _NODE_PRIVILEGES[] = "privileges"; +static const xmlChar _NODE_PRIVILEGE[] = "privilege"; + +void destroy_char_list(char** ppList, int size) +{ + int i; + for (i = 0; i < size; ++i) + { + if (ppList[i]) + free(ppList[i]); + } + free(ppList); +} + +extern "C" +__attribute__ ((visibility("default"))) +int PKGMGR_PARSER_PLUGIN_INSTALL(xmlDocPtr docPtr, const char* packageId) +{ + int ret; + + // Node: + xmlNodePtr curPtr = xmlFirstElementChild(xmlDocGetRootElement(docPtr)); + + curPtr = curPtr->xmlChildrenNode; + if (curPtr == NULL) + { + LOGD("No privileges"); + return 0; + } + + std::list privilegeList; + while (curPtr != NULL) + { + if (xmlStrcmp(curPtr->name, _NODE_PRIVILEGE) == 0) + { + xmlChar* pPrivilege = xmlNodeListGetString(docPtr, curPtr->xmlChildrenNode, 1); + + if (pPrivilege == NULL) + { + LOGE("Failed to get value"); + return -EINVAL; + } + else + { + privilegeList.push_back(std::string( reinterpret_cast (pPrivilege))); + } + } + curPtr = curPtr->next; + } + + char** ppPrivilegeList = (char**) calloc(privilegeList.size() + 1, sizeof(char*)); + std::list ::iterator iter = privilegeList.begin(); + for (int i = 0; i < privilegeList.size(); ++i) + { + ppPrivilegeList[i] = (char*)calloc (strlen(iter->c_str()) + 1, sizeof(char)); + if (ppPrivilegeList[i] == NULL) + { + destroy_char_list(ppPrivilegeList, privilegeList.size() + 1); + return -ENOMEM; + } + memcpy(ppPrivilegeList[i], iter->c_str(), strlen(iter->c_str())); + ++iter; + } + + ppPrivilegeList[privilegeList.size()] = (char*)calloc (2, sizeof(char)); + memcpy(ppPrivilegeList[privilegeList.size()], "\0", 1); + + // TO DO : get user id + int user_id = 1; + int monitor_policy = 1; + + if (user_id < 0 || packageId == NULL) + return PRIV_FLTR_ERROR_INVALID_PARAMETER; + + PrivacyGuardClient *pInst = PrivacyGuardClient::getInstance(); + std::list < std::string > privilege_List; + + while (*ppPrivilegeList[0] != '\0') + { + LOGD("privacyList : %s", *ppPrivilegeList); + privilege_List.push_back(std::string(*ppPrivilegeList++)); + } + int retval = pInst->PgAddMonitorPolicy(user_id, std::string(packageId), privilege_List, monitor_policy); + + destroy_char_list(ppPrivilegeList, privilegeList.size() + 1); + + if (ret != PRIV_FLTR_ERROR_SUCCESS) + { + LOGD("Failed to install monitor policy: %d", ret); + return -EINVAL; + } + + return 0; +} + +extern "C" +__attribute__ ((visibility("default"))) +int PKGMGR_PARSER_PLUGIN_UNINSTALL(xmlDocPtr docPtr, const char* packageId) +{ + if (packageId == NULL) + return PRIV_FLTR_ERROR_INVALID_PARAMETER; + + PrivacyGuardClient *pInst = PrivacyGuardClient::getInstance(); + + int res = pInst->PgDeleteLogsByPackageId(std::string(packageId)); + if (res != PRIV_FLTR_ERROR_SUCCESS) + { + LOGD("Failed to delete logs"); + return 0; + } + + res = pInst->PgDeleteMonitorPolicyByPackageId(std::string(packageId)); + if (res != PRIV_FLTR_ERROR_SUCCESS) + { + LOGD("Failed to delete monitor policy"); + } + + return 0; +} + +extern "C" +__attribute__ ((visibility("default"))) +int PKGMGR_PARSER_PLUGIN_UPGRADE(xmlDocPtr docPtr, const char* packageId) +{ + int res = 0; + + LOGD("Update privacy Info"); + + res = PKGMGR_PARSER_PLUGIN_UNINSTALL(docPtr, packageId); + if (res != 0) + { + LOGD("Privacy info can be already uninstalled"); + } + + res = PKGMGR_PARSER_PLUGIN_INSTALL(docPtr, packageId); + if (res != 0) + { + LOGD("Failed to install privacy Info: %d", res); + } + return res; +} diff --git a/privacy-guard-client.pc.in b/privacy-guard-client.pc.in new file mode 100755 index 0000000..6f117ea --- /dev/null +++ b/privacy-guard-client.pc.in @@ -0,0 +1,11 @@ +prefix=@PREFIX@ +exec_prefix=@EXEC_PREFIX@ +libdir=@LIBDIR@ +includedir=/usr/include + +Name: @PC_NAME@ +Description: @PC_DESCRIPTION@ +Version: @VERSION@ +Libs: -L${libdir} @PC_LDFLAGS@ +Cflags: @PC_CFLAGS@ +Requires: diff --git a/privacy-guard-server.pc.in b/privacy-guard-server.pc.in new file mode 100755 index 0000000..6f117ea --- /dev/null +++ b/privacy-guard-server.pc.in @@ -0,0 +1,11 @@ +prefix=@PREFIX@ +exec_prefix=@EXEC_PREFIX@ +libdir=@LIBDIR@ +includedir=/usr/include + +Name: @PC_NAME@ +Description: @PC_DESCRIPTION@ +Version: @VERSION@ +Libs: -L${libdir} @PC_LDFLAGS@ +Cflags: @PC_CFLAGS@ +Requires: diff --git a/res/etc/rc.d/init.d/privacy-guard-server.sh b/res/etc/rc.d/init.d/privacy-guard-server.sh new file mode 100755 index 0000000..efb8097 --- /dev/null +++ b/res/etc/rc.d/init.d/privacy-guard-server.sh @@ -0,0 +1,4 @@ +#!/bin/sh + +/usr/bin/privacy-guard-server & +set_pmon -p privacy-guard-server diff --git a/res/opt/dbspace/.privacy_guard_privacylist.db b/res/opt/dbspace/.privacy_guard_privacylist.db new file mode 100755 index 0000000..7b9b282 Binary files /dev/null and b/res/opt/dbspace/.privacy_guard_privacylist.db differ diff --git a/res/usr/bin/privacy_guard_create_clean_db.sh b/res/usr/bin/privacy_guard_create_clean_db.sh new file mode 100755 index 0000000..0edc96a --- /dev/null +++ b/res/usr/bin/privacy_guard_create_clean_db.sh @@ -0,0 +1,32 @@ +#!/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. +# +source /etc/tizen-platform.conf +for name in privacy_guard +do + rm -f ${TZ_SYS_DB}/.$name.db + rm -f ${TZ_SYS_DB}/.$name.db-journal + SQL="PRAGMA journal_mode = PERSIST;" + sqlite3 ${TZ_SYS_DB}/.$name.db "$SQL" + SQL=".read ${TZ_SYS_BIN}/"$name"_db.sql" + sqlite3 ${TZ_SYS_DB}/.$name.db "$SQL" + touch ${TZ_SYS_DB}/.$name.db-journal + chown root:root ${TZ_SYS_DB}/.$name.db + chown root:root ${TZ_SYS_DB}/.$name.db-journal + chmod 666 ${TZ_SYS_DB}/.$name.db + chmod 666 ${TZ_SYS_DB}/.$name.db-journal +done + + diff --git a/res/usr/bin/privacy_guard_db.sql b/res/usr/bin/privacy_guard_db.sql new file mode 100755 index 0000000..961afaa --- /dev/null +++ b/res/usr/bin/privacy_guard_db.sql @@ -0,0 +1,26 @@ +PRAGMA foreign_keys = ON; BEGIN TRANSACTION; + +CREATE TABLE StatisticsMonitorInfo( + USER_ID INTEGER not null, + PKG_ID TEXT not null, + PRIVACY_ID TEXT not null, + USE_DATE INTEGER not null, +CHECK(1) ); + +CREATE TABLE MonitorPolicy( + USER_ID INTEGER not null, + PKG_ID TEXT not null, + PRIVACY_ID TEXT not null, + MONITOR_POLICY INTEGER not null, + PRIMARY KEY(USER_ID, PKG_ID, PRIVACY_ID) +CHECK(1) ); + +CREATE TABLE MainMonitorPolicy( + USER_ID INTEGER not null, + MAIN_MONITOR_POLICY BOOLEAN DEFAULT FALSE, + PRIMARY KEY(USER_ID) +CHECK(1) ); + +COMMIT; +BEGIN TRANSACTION; +CREATE TABLE DB_VERSION_0_1 (version INT); COMMIT; diff --git a/server/CMakeLists.txt b/server/CMakeLists.txt new file mode 100755 index 0000000..3bdaac1 --- /dev/null +++ b/server/CMakeLists.txt @@ -0,0 +1,87 @@ +CMAKE_MINIMUM_REQUIRED(VERSION 2.6) +PROJECT(privacy-guard) + +SET(CMAKE_INSTALL_PREFIX /usr) +SET(PREFIX ${CMAKE_INSTALL_PREFIX}) +SET(EXEC_PREFIX "\${prefix}") +SET(INCLUDEDIR "\${prefix}/include") + +INCLUDE(FindPkgConfig) +#pkg_check_modules(pkgs REQUIRED dlog sqlite3 dbus-1 dbus-glib-1 db-util pkgmgr-info capi-system-info libtzplatform-config cynara-monitor) +pkg_check_modules(pkgs REQUIRED dlog sqlite3 dbus-1 dbus-glib-1 db-util pkgmgr-info capi-system-info libtzplatform-config) + +FOREACH(flag ${pkgs_CFLAGS}) + SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}") +ENDFOREACH(flag) + +SET(CMAKE_C_FLAGS_PROFILING " -g -pg") +SET(CMAKE_CXX_FLAGS_PROFILING " -std=c++0x -g -pg") +SET(CMAKE_C_FLAGS_DEBUG " -g") +SET(CMAKE_CXX_FLAGS_DEBUG " -std=c++0x -g") +SET(CMAKE_C_FLAGS_RELEASE " -g") +SET(CMAKE_CXX_FLAGS_RELEASE " -std=c++0x -g") +SET(CMAKE_C_FLAGS_CCOV " -g --coverage") +SET(CMAKE_CXX_FLAGS_CCOV " -std=c++0x -g --coverage") + +SET(server_src_dir "${CMAKE_SOURCE_DIR}/server/src") +SET(server_include_dir "${CMAKE_SOURCE_DIR}/server/inc/") +SET(common_src_dir "${CMAKE_SOURCE_DIR}/common/src/") +SET(common_include_dir "${CMAKE_SOURCE_DIR}/common/inc/") +SET(extern_include_dir "${CMAKE_SOURCE_DIR}/include/") +SET(dbus_include_dir "/usr/include/dbus-1.0") + +## Additional flag +ADD_DEFINITIONS("-fvisibility=hidden") +ADD_DEFINITIONS("-Wall -Werror") +ADD_DEFINITIONS("-DDLOG_ERROR_ENABLED") +ADD_DEFINITIONS("-D_PRIVACY_GUARD_DEBUG") +OPTION (FILTER_LISTED_PKG "FILTER PKG BY LIST" ON) +IF(FILTER_LISTED_PKG) + MESSAGE("FILTER PKGs BY FILTERING LIST") + ADD_DEFINITIONS("-D__FILTER_LISTED_PKG") +ENDIF(FILTER_LISTED_PKG) + +################################################################################################### +## for privacy-guard-server (executable) +INCLUDE_DIRECTORIES( + ${pkgs_INCLUDE_DIRS} + ${server_include_dir} + ${common_include_dir} + ${extern_include_dir} + ${dbus_include_dir} + ) + +SET(PRIVACY_GUARD_SERVER_SOURCES + ${common_src_dir}/SocketConnection.cpp + ${common_src_dir}/SocketStream.cpp + ${common_src_dir}/PrivacyIdInfo.cpp + ${server_src_dir}/PrivacyGuardDb.cpp + ${server_src_dir}/main.cpp + ${server_src_dir}/SocketService.cpp +# ${server_src_dir}/CynaraService.cpp + ${server_src_dir}/PrivacyGuardDaemon.cpp + ${server_src_dir}/service/PrivacyInfoService.cpp + ${server_src_dir}/NotificationServer.cpp + ) +SET(PRIVACY_GUARD_SERVER_LDFLAGS " -module -avoid-version ") +SET(PRIVACY_GUARD_SERVER_CFLAGS " ${CFLAGS} -fPIE ") +#SET(PRIVACY_GUARD_SERVER_LIBADD " ") + +ADD_DEFINITIONS("-DLOG_TAG=\"PRIVACY-GUARD-SERVER\"") +ADD_EXECUTABLE(privacy-guard-server ${PRIVACY_GUARD_SERVER_SOURCES}) +TARGET_LINK_LIBRARIES(privacy-guard-server ${pkgs_LDFLAGS} ${pkgs_LIBRARIES} "-ldl -pie -lpthread") +SET_TARGET_PROPERTIES(privacy-guard-server PROPERTIES COMPILE_FLAGS "${PRIVACY_GUARD_SERVER_CFLAGS}") +#SET_TARGET_PROPERTIES(privacy-guard-server PROPERTIES SOVERSION ${API_VERSION}) +#SET_TARGET_PROPERTIES(privacy-guard-server PROPERTIES VERSION ${VERSION}) +################################################################################################### + +SET(PC_NAME privacy-guard-server) +SET(PC_DESCRIPTION "Privacy Guard Server API") +SET(PC_LDFLAGS -lprivacy-guard-server) +SET(PC_CFLAGS -I\${includedir}/privacy_guard) + +CONFIGURE_FILE(../privacy-guard-server.pc.in privacy-guard-server.pc @ONLY) + +INSTALL(TARGETS privacy-guard-server DESTINATION /usr/bin COMPONENT RuntimeLibraries) +INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/privacy-guard-server.pc DESTINATION ${LIB_INSTALL_DIR}/pkgconfig) +#INSTALL(FILES ${PRIVACY_GUARD_SERVER_HEADERS} DESTINATION ${INCLUDE_INSTALL_DIR}/privacy_guard/server) diff --git a/server/inc/CynaraService.h b/server/inc/CynaraService.h new file mode 100755 index 0000000..aced859 --- /dev/null +++ b/server/inc/CynaraService.h @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _CYNARASERVICE_H_ +#define _CYNARASERVICE_H_ + +#include +#include +#include +#include +#include +#include +#include + +class CynaraService +{ +private: + int m_signalToClose; + pthread_t m_cynaraThread; + +private: + static void* getEntriesThread(void* ); + static void* flushThread(void* ); +public: + CynaraService(void); + ~CynaraService(void); + int initialize(void); + int start(void); + int stop(void); + int shutdown(void); + static int updateDb(cynara_monitor_entry** monitor_entries); +}; + +#endif //_CYNARASERVICE_H_ diff --git a/server/inc/ICommonDb.h b/server/inc/ICommonDb.h new file mode 100755 index 0000000..33c16d5 --- /dev/null +++ b/server/inc/ICommonDb.h @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _ICOMMONDB_H_ +#define _ICOMMONDB_H_ + +#include "PrivacyGuardCommon.h" + +class ICommonDb +{ +public: + + std::mutex m_dbMutex; + sqlite3* m_sqlHandler; + sqlite3_stmt* m_stmt; + bool m_bDBOpen; + + ICommonDb() { + m_sqlHandler = NULL; + m_stmt = NULL; + m_bDBOpen = false; + } + + virtual ~ICommonDb() {} + + virtual void openSqliteDB(void) = 0; + +}; + +#endif // _ICOMMONDB_H_ diff --git a/server/inc/NotificationServer.h b/server/inc/NotificationServer.h new file mode 100755 index 0000000..b033b43 --- /dev/null +++ b/server/inc/NotificationServer.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _NOTIFICATIONSERVER_H_ +#define _NOTIFICATIONSERVER_H_ + +#include +#include +#include +#include +#include +#include + +class NotificationServer +{ +private: + bool m_initialized; + DBusConnection* m_pDBusConnection; +public: + + NotificationServer(void); + ~NotificationServer(void); + int initialize(void); + int notifySettingChanged(const std::string pkgId, const std::string privacyId); + int notifyPkgRemoved(const std::string pkgId); +}; + + +#endif // _NOTIFICATIONSERVER_H_ \ No newline at end of file diff --git a/server/inc/PrivacyGuardDaemon.h b/server/inc/PrivacyGuardDaemon.h new file mode 100755 index 0000000..281bdea --- /dev/null +++ b/server/inc/PrivacyGuardDaemon.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _PRIVACYGUARDDAEMON_H_ +#define _PRIVACYGUARDDAEMON_H_ + +#include "privacy_guard_client_types.h" + +class SocketService; +#if 0 +// [CYNARA] +class CynaraService; +#endif + +class EXTERN_API PrivacyGuardDaemon +{ +private: + static PrivacyGuardDaemon* pInstance; + SocketService* pSocketService; +#if 0 + // [CYNARA] + CynaraService* pCynaraService; +#endif + +private: + PrivacyGuardDaemon(void); + ~PrivacyGuardDaemon(void); + + +public: + static PrivacyGuardDaemon* getInstance(void); + int initialize(void); + int start(void); + int stop(void); + int shutdown(void); +}; + +#endif // _PRIVACYGUARDDAEMON_H_ diff --git a/server/inc/PrivacyGuardDb.h b/server/inc/PrivacyGuardDb.h new file mode 100755 index 0000000..250f088 --- /dev/null +++ b/server/inc/PrivacyGuardDb.h @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _PRIVACYGUARDDB_H_ +#define _PRIVACYGUARDDB_H_ + +#include +#include +#include +#include +#include "ICommonDb.h" +#include "privacy_guard_client_types.h" +#include "PrivacyGuardTypes.h" + +#ifdef __FILTER_LISTED_PKG +#include +#endif + +class PrivacyGuardDb : public ICommonDb +{ +private: + static std::mutex m_singletonMutex; + static PrivacyGuardDb* m_pInstance; +#ifdef __FILTER_LISTED_PKG + const static std::string PRIVACY_FILTER_LIST_FILE; + const static std::string FILTER_KEY; + static std::map < std::string, bool > m_filteredPkgList; +#endif + +private: + void createDB(void); + + PrivacyGuardDb(void); + + ~PrivacyGuardDb(void); + +public: + static PrivacyGuardDb* getInstance(void); + + virtual void openSqliteDB(void); + + int PgAddPrivacyAccessLog(const int userId, std::list < std::pair < std::string, std::string > > logInfoList); + + int PgAddPrivacyAccessLogForCynara(const int userId, const std::string packageId, const std::string privilege, const timespec *timestamp); + + int PgAddPrivacyAccessLogTest(const int userId, const std::string packageId, const std::string privacyId); + + int PgAddMonitorPolicy(const int userId, const std::string packageId, const std::list < std::string > privacyList, bool monitorPolicy); + + int PgCheckPrivacyPackage(const int userId, const std::string packageId, bool &isPrivacyPackage); + + int PgDeleteAllLogsAndMonitorPolicy(void); + + int PgDeleteLogsByPackageId(const std::string packageId); + + int PgDeleteMonitorPolicyByPackageId(const std::string packageId); + + int PgForeachTotalPrivacyCountOfPackage(const int userId, const int startDate, const int endDate, + std::list < std::pair < std::string, int > >& packageInfoList); + + int PgForeachTotalPrivacyCountOfPrivacy(const int userId, const int startDate, const int endDate, + std::list < std::pair < std::string, int > >& privacyInfoList); + + int PgForeachPrivacyCountByPrivacyId(const int userId, const int startDate, const int endDate, + const std::string privacyId, std::list < std::pair < std::string, int > >& packageInfoList); + + int PgForeachPrivacyCountByPackageId(const int userId, const int startDate, const int endDate, + const std::string packageId, std::list < std::pair < std::string, int > >& privacyInfoList); + + int PgGetMonitorPolicy(const int userId, const std::string packageId, const std::string privacyId, int& monitorPolicy); + + int PgGetAllMonitorPolicy(std::list < std::pair < std::string, int > >& monitorPolicyList); + + int PgForeachMonitorPolicyByPackageId(const int userId, const std::string packageId, std::list & privacyInfoList); + + int PgForeachPrivacyPackageId(const int userId, std::list < std::string > & packageList); + + int PgForeachPackageByPrivacyId(const int userId, const std::string privacyId, std::list < std::string > &packageList); + + int PgUpdateMonitorPolicy(const int userId, const std::string packageId, const std::string privacyId, const int monitorPolicy); + + int PgAddMainMonitorPolicy(const int userId); + + int PgUpdateMainMonitorPolicy(const int userId, const bool mainMonitorPolicy); + + int PgGetMainMonitorPolicy(const int userId, bool &mainMonitorPolicy); + + int PgDeleteMainMonitorPolicyByUserId(const int userId); +}; + + +#endif // _PRIVACYGUARDDB_H_ diff --git a/server/inc/PrivacyInfoService.h b/server/inc/PrivacyInfoService.h new file mode 100755 index 0000000..9edea84 --- /dev/null +++ b/server/inc/PrivacyInfoService.h @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _PRIVACYINFOSERVICE_H_ +#define _PRIVACYINFOSERVICE_H_ + +#include "SocketConnection.h" +#include "SocketService.h" + +class PrivacyInfoService { +private: + inline static std::string getInterfaceName(void) + { + return "PrivacyInfoService"; + } + +public: + static void registerCallbacks(SocketService* pSocketService) + { + pSocketService->registerServiceCallback(getInterfaceName(), std::string("PgAddPrivacyAccessLog"), PgAddPrivacyAccessLog); + pSocketService->registerServiceCallback(getInterfaceName(), std::string("PgAddPrivacyAccessLogTest"), PgAddPrivacyAccessLogTest); + pSocketService->registerServiceCallback(getInterfaceName(), std::string("PgAddMonitorPolicy"), PgAddMonitorPolicy); + pSocketService->registerServiceCallback(getInterfaceName(), std::string("PgDeleteAllLogsAndMonitorPolicy"), PgDeleteAllLogsAndMonitorPolicy); + pSocketService->registerServiceCallback(getInterfaceName(), std::string("PgDeleteLogsByPackageId"), PgDeleteLogsByPackageId); + pSocketService->registerServiceCallback(getInterfaceName(), std::string("PgDeleteMonitorPolicyByPackageId"), PgDeleteMonitorPolicyByPackageId); + pSocketService->registerServiceCallback(getInterfaceName(), std::string("PgForeachTotalPrivacyCountOfPackage"), PgForeachTotalPrivacyCountOfPackage); + pSocketService->registerServiceCallback(getInterfaceName(), std::string("PgForeachTotalPrivacyCountOfPrivacy"), PgForeachTotalPrivacyCountOfPrivacy); + pSocketService->registerServiceCallback(getInterfaceName(), std::string("PgForeachPrivacyCountByPrivacyId"), PgForeachPrivacyCountByPrivacyId); + pSocketService->registerServiceCallback(getInterfaceName(), std::string("PgForeachPrivacyCountByPackageId"), PgForeachPrivacyCountByPackageId); + pSocketService->registerServiceCallback(getInterfaceName(), std::string("PgForeachPrivacyPackageId"), PgForeachPrivacyPackageId); + pSocketService->registerServiceCallback(getInterfaceName(), std::string("PgForeachPackageByPrivacyId"), PgForeachPackageByPrivacyId); + pSocketService->registerServiceCallback(getInterfaceName(), std::string("PgForeachMonitorPolicyByPackageId"), PgForeachMonitorPolicyByPackageId); + pSocketService->registerServiceCallback(getInterfaceName(), std::string("PgGetMonitorPolicy"), PgGetMonitorPolicy); + pSocketService->registerServiceCallback(getInterfaceName(), std::string("PgGetAllMonitorPolicy"), PgGetAllMonitorPolicy); + pSocketService->registerServiceCallback(getInterfaceName(), std::string("PgCheckPrivacyPackage"), PgCheckPrivacyPackage); + pSocketService->registerServiceCallback(getInterfaceName(), std::string("PgUpdateMonitorPolicy"), PgUpdateMonitorPolicy); + pSocketService->registerServiceCallback(getInterfaceName(), std::string("PgGetMainMonitorPolicy"), PgGetMainMonitorPolicy); + pSocketService->registerServiceCallback(getInterfaceName(), std::string("PgUpdateMainMonitorPolicy"), PgUpdateMainMonitorPolicy); + pSocketService->registerServiceCallback(getInterfaceName(), std::string("PgDeleteMainMonitorPolicyByUserId"), PgDeleteMainMonitorPolicyByUserId); + } + + static void PgAddPrivacyAccessLog(SocketConnection* pConnector); + static void PgAddPrivacyAccessLogTest(SocketConnection* pConnector); + static void PgAddMonitorPolicy(SocketConnection* pConnector); + static void PgDeleteAllLogsAndMonitorPolicy(SocketConnection* pConnector); + static void PgDeleteLogsByPackageId(SocketConnection* pConnector); + static void PgDeleteMonitorPolicyByPackageId(SocketConnection* pConnector); + static void PgForeachTotalPrivacyCountOfPackage(SocketConnection* pConnector); + static void PgForeachTotalPrivacyCountOfPrivacy(SocketConnection* pConnector); + static void PgForeachPrivacyCountByPrivacyId(SocketConnection* pConnector); + static void PgForeachPrivacyCountByPackageId(SocketConnection* pConnector); + static void PgForeachPrivacyPackageId(SocketConnection* pConnector); + static void PgForeachPackageByPrivacyId(SocketConnection* pConnector); + static void PgForeachMonitorPolicyByPackageId(SocketConnection* pConnector); + static void PgGetMonitorPolicy(SocketConnection* pConnector); + static void PgGetAllMonitorPolicy(SocketConnection* pConnector); + static void PgCheckPrivacyPackage(SocketConnection* pConnector); + static void PgUpdateMonitorPolicy(SocketConnection* pConnector); + static void PgGetMainMonitorPolicy(SocketConnection* pConnector); + static void PgUpdateMainMonitorPolicy(SocketConnection* pConnector); + static void PgDeleteMainMonitorPolicyByUserId(SocketConnection* pConnector); +}; +#endif // _PRIVACYINFOSERVICE_H_ \ No newline at end of file diff --git a/server/inc/SocketService.h b/server/inc/SocketService.h new file mode 100755 index 0000000..2f18d68 --- /dev/null +++ b/server/inc/SocketService.h @@ -0,0 +1,84 @@ +/* + * Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _SOCKETSERVICE_H_ +#define _SOCKETSERVICE_H_ + +#include +#include +#include +#include +#include +#include +#include "SocketConnection.h" + +typedef void(*socketServiceCallback)(SocketConnection* pConnector); + +class SocketService +{ + struct ConnectionInfo{ + ConnectionInfo(int fd, void* pData) : connFd(fd), pData(pData) {} + int connFd; + void* pData; + }; + class ServiceCallback + { + public: + ServiceCallback(socketServiceCallback callback) + : serviceCallback(callback) + {} + socketServiceCallback serviceCallback; + }; + +private: + static const int MAX_LISTEN; + static const int TIMEOUT_SEC; + static const int TIMEOUT_NSEC; + int m_listenFd; + int m_signalToClose; + pthread_t m_mainThread; + + typedef std::shared_ptr ServiceCallbackPtr; + //Map for callback methods, key is a method name and value is a callback to method + typedef std::map ServiceMethodCallbackMap; + //Map for interface methods, key is an interface name and value is a map of available methods with callbacks + std::map m_callbackMap; + + std::list < int > m_clientSocketList; + std::mutex m_clientSocketListMutex; + +private: + static void* serverThread(void* ); + static void* connectionThread(void* pData); + int connectionService(int fd); + int mainloop(void); + void closeConnections(void); + + void addClientSocket(int clientSocket); + void removeClientSocket(int clientSocket); + bool popClientSocket(int* pClientSocket); + +public: + SocketService(void); + ~SocketService(void); + int initialize(void); + int registerServiceCallback(const std::string &interfaceName, const std::string &methodName, socketServiceCallback callbackMethod); + int start(void); + int stop(void); + int shutdown(void); +}; + +#endif //_SOCKETSERVICE_H_ \ No newline at end of file diff --git a/server/inc/privacy_guard_daemon.h b/server/inc/privacy_guard_daemon.h new file mode 100755 index 0000000..db04b25 --- /dev/null +++ b/server/inc/privacy_guard_daemon.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef _PRIVACY_GUARD_DAEMON_H_ +#define _PRIVACY_GUARD_DAEMON_H_ + +#include "privacy_guard_client_types.h" + +#ifdef __cplusplus +extern "C" { +#endif + +int EXTERN_API privacy_guard_daemon_initialize(void); +int EXTERN_API privacy_guard_daemon_start(void); +int EXTERN_API privacy_guard_daemon_stop(void); +int EXTERN_API privacy_guard_daemon_shutdown(void); + +#ifdef __cplusplus +} +#endif + +#endif //_PRIVACY_GUARD_DAEMON_H_ + diff --git a/server/src/CMakeLists.txt b/server/src/CMakeLists.txt new file mode 100755 index 0000000..b496320 --- /dev/null +++ b/server/src/CMakeLists.txt @@ -0,0 +1,75 @@ +CMAKE_MINIMUM_REQUIRED(VERSION 2.6) +#PROJECT(privacy-guard-server) + +SET(CMAKE_INSTALL_PREFIX /usr) +SET(PREFIX ${CMAKE_INSTALL_PREFIX}) +SET(EXEC_PREFIX "\${prefix}") +SET(LIBDIR ${LIB_INSTALL_DIR}) +SET(INCLUDEDIR ${INCLUDE_INSTALL_DIR}) +SET(VERSION 0.0) + +SET(VERSION_MAJOR 0) +SET(VERSION "${VERSION_MAJOR}.0.1") + +INCLUDE_DIRECTORIES(${CMAKE_SOURCE_DIR}/include) + +INCLUDE(FindPkgConfig) +#pkg_check_modules(pkgs REQUIRED dlog pkgmgr-info cynara-monitor) +pkg_check_modules(pkgs REQUIRED dlog pkgmgr-info) + +FOREACH(flag ${pkgs_CFLAGS}) + SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}") +ENDFOREACH(flag) + +SET(CMAKE_C_FLAGS_PROFILING " -g -pg") +SET(CMAKE_CXX_FLAGS_PROFILING " -std=c++0x -g -pg") +SET(CMAKE_C_FLAGS_DEBUG " -g") +SET(CMAKE_CXX_FLAGS_DEBUG " -std=c++0x -g") +SET(CMAKE_C_FLAGS_RELEASE " -g") +SET(CMAKE_CXX_FLAGS_RELEASE " -std=c++0x -g") +SET(CMAKE_C_FLAGS_CCOV " -g --coverage") +SET(CMAKE_CXX_FLAGS_CCOV " -std=c++0x -g --coverage") + +SET(src_dir "./") +SET(include_dir "./../inc/") +SET(common_src_dir "./../../common/src/") +SET(common_include_dir "./../../common/inc/") + +## Additional flag +ADD_DEFINITIONS("-fvisibility=hidden") +ADD_DEFINITIONS("-Wall -Werror") +ADD_DEFINITIONS("-DDLOG_ERROR_ENABLED") + +################################################################################################### +## for libprivacy-guard-server.so (library) +INCLUDE_DIRECTORIES(${pkgs_INCLUDE_DIRS}) +SET(PRIVACY_GUARD_SERVER_SOURCES + ${src_dir}/main.cpp + ${src_dir}/SocketService.cpp +# ${src_dir}/CynaraService.cpp + ${src_dir}/PrivacyGuardDaemon.cpp + ${common_src_dir}/SocketConnection.cpp + ${common_src_dir}/SocketStream.cpp + ) +SET(PRIVACY_GUARD_SERVER_HEADERS + ${include_dir}/SocketService.h +# ${include_dir}/CynaraService.h + ${include_dir}/PrivacyGuardDaemon.h + ${common_include_dir}/SocketConnection.h +) +SET(PRIVACY_GUARD_SERVER_LDFLAGS " -module -avoid-version ") +SET(PRIVACY_GUARD_SERVER_CFLAGS " ${CFLAGS} -fPIC -I${include_dir}" -I${common_include_dir}) +#SET(PRIVACY_GUARD_SERVER_LIBADD " ") + +ADD_EXECUTABLE(privacy-guard-server ${PRIVACY_GUARD_SERVER_SOURCES}) +TARGET_LINK_LIBRARIES(privacy-guard-server ${pkgs_LDFLAGS} ${pkgs_LIBRARIES}) +SET_TARGET_PROPERTIES(privacy-guard-server PROPERTIES COMPILE_FLAGS "${PRIVACY_GUARD_SERVER_CFLAGS}") +SET_TARGET_PROPERTIES(privacy-guard-server PROPERTIES SOVERSION ${VERSION_MAJOR}) +SET_TARGET_PROPERTIES(privacy-guard-server PROPERTIES VERSION ${VERSION}) +################################################################################################### + +CONFIGURE_FILE(../../privacy-guard-server.pc.in privacy-guard-server.pc @ONLY) + +INSTALL(TARGETS privacy-guard-server DESTINATION ${LIB_INSTALL_DIR} COMPONENT RuntimeLibraries) +INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/privacy-guard-server.pc DESTINATION ${LIB_INSTALL_DIR}/pkgconfig) +INSTALL(FILES ${PRIVACY_GUARD_SERVER_HEADERS} DESTINATION ${INCLUDE_INSTALL_DIR}) diff --git a/server/src/CynaraService.cpp b/server/src/CynaraService.cpp new file mode 100755 index 0000000..8c36c01 --- /dev/null +++ b/server/src/CynaraService.cpp @@ -0,0 +1,208 @@ +/* + * Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "PrivacyGuardTypes.h" +#include "Utils.h" +#include "CynaraService.h" +#include "PrivacyGuardDb.h" + +static cynara_monitor_configuration *p_conf; +static cynara_monitor *p_cynara_monitor; +static cynara_monitor_entry **monitor_entries; + +CynaraService::CynaraService(void) + : m_signalToClose(-1) + , m_cynaraThread(-1) +{ + +} + +CynaraService::~CynaraService(void) +{ + +} + +int +CynaraService::initialize(void) +{ + LOGI("CynaraService initializing"); + + int res = cynara_monitor_configuration_create(&p_conf); + if(res != CYNARA_API_SUCCESS){ + LOGE("cynara_monitor_configuration_create FAIL"); + return PRIV_FLTR_ERROR_SYSTEM_ERROR; + } +// cynara_monitor_configuration_set_buffer_size(p_conf, buffer_size); +// res = cynara_monitor_initialize(&p_cynara_monitor, p_conf); + res = cynara_monitor_initialize(&p_cynara_monitor, nullptr); + if(res != CYNARA_API_SUCCESS){ + LOGE("cynara_monitor_initialize FAIL"); + return PRIV_FLTR_ERROR_SYSTEM_ERROR; + } + +// cynara_monitor_configuration_set_filter + + LOGI("CynaraService initialized"); + + return PRIV_FLTR_ERROR_SUCCESS; +} + +int +CynaraService::start(void) +{ + LOGI("CynaraService starting"); + + int res = 0; + + sigset_t sigset; + sigemptyset(&sigset); + res = pthread_sigmask(SIG_BLOCK, &sigset, NULL); + TryReturn( res >= 0, PRIV_FLTR_ERROR_SYSTEM_ERROR, , "pthread_sigmask : %s", strerror(errno)); + + pthread_t cynaraThread; + res = pthread_create(&cynaraThread, NULL, &getEntriesThread, this); + TryReturn( res >= 0, PRIV_FLTR_ERROR_SYSTEM_ERROR, errno = res, "pthread_create : %s", strerror(res)); + + m_cynaraThread = cynaraThread; + + LOGI("CynaraService started"); + + return PRIV_FLTR_ERROR_SUCCESS; +} + +void* +CynaraService::getEntriesThread(void* pData) +{ + pthread_detach(pthread_self()); + LOGI("Running get entries thread"); + + pthread_t testThread; + int result = pthread_create(&testThread, NULL, &flushThread, NULL); + if(result){ + LOGE("pthread_create FAIL"); + return (void*) PRIV_FLTR_ERROR_SYSTEM_ERROR; + } + +// while(1) +// { + // cynara_monitor_entries_get + int res = cynara_monitor_entries_get(p_cynara_monitor, &monitor_entries); + if(res != CYNARA_API_SUCCESS){ + LOGE("cynara_monitor_entries_get FAIL"); + return (void*) PRIV_FLTR_ERROR_SYSTEM_ERROR; + } + + res = CynaraService::updateDb(monitor_entries); + if(res != PRIV_FLTR_ERROR_SUCCESS){ + LOGE("updateDb FAIL"); + return (void*) res; + } +// } + + pthread_join(testThread, NULL); + + cynara_monitor_entries_free(monitor_entries); + + return (void*) 0; +} + +void* +CynaraService::flushThread(void* pData) + { + pthread_detach(pthread_self()); + LOGI("Running get flush thread"); + + for(int i = 0; i < 1000000000;i++); + + int ret= cynara_monitor_entries_flush(p_cynara_monitor); + if(ret != CYNARA_API_SUCCESS){ + LOGE("cynara_monitor_entries_flush FAIL"); + return (void*) PRIV_FLTR_ERROR_SYSTEM_ERROR; + } + else{ + LOGI("cynara_monitor_entries_flush SUCCESS"); + } + + return (void*) 0; +} + +int +CynaraService::updateDb(cynara_monitor_entry** monitor_entries) +{ + cynara_monitor_entry **entryIter = monitor_entries; + + LOGI("entryIter = %x", entryIter); + +// DB update + int userId = 0; + std::string packageId; + std::string privilege; + const timespec *timestamp = { 0 };; + + while (*entryIter != nullptr) { + packageId = cynara_monitor_entry_get_client(*entryIter); + userId = (int)*cynara_monitor_entry_get_user(*entryIter); + privilege = cynara_monitor_entry_get_privilege(*entryIter); + timestamp = cynara_monitor_entry_get_timestamp(*entryIter); + + int ret = PrivacyGuardDb::getInstance()->PgAddPrivacyAccessLogForCynara(userId, packageId, privilege, timestamp); + if(ret != PRIV_FLTR_ERROR_SUCCESS){ + LOGE("PgAddPrivacyAccessLogForCynara FAIL"); + } + else{ + LOGI("PgAddPrivacyAccessLogForCynara SUCCESS"); + } + + ++entryIter; + } + + return PRIV_FLTR_ERROR_SUCCESS; +} + + +int +CynaraService::stop(void) +{ + LOGI("Stopping"); + + int returned_value; + if((returned_value = pthread_kill(m_cynaraThread, m_signalToClose)) < 0) + { + errno = returned_value; + LOGE("pthread_kill() : %s", strerror(errno)); + return PRIV_FLTR_ERROR_IPC_ERROR; + } + pthread_join(m_cynaraThread, NULL); + + LOGI("Stopped"); + return PRIV_FLTR_ERROR_SUCCESS; +} + +int +CynaraService::shutdown(void) +{ + return PRIV_FLTR_ERROR_SUCCESS; +} diff --git a/server/src/NotificationServer.cpp b/server/src/NotificationServer.cpp new file mode 100755 index 0000000..7846962 --- /dev/null +++ b/server/src/NotificationServer.cpp @@ -0,0 +1,118 @@ +/* + * 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. + */ + +#include +#include +#include "NotificationServer.h" +#include "PrivacyGuardTypes.h" +#include "Utils.h" + +auto DBusConnectionDeleter = [&](DBusConnection* pPtr) { dbus_connection_close(pPtr); pPtr = NULL;}; +const int MAX_LOCAL_BUF_SIZE = 128; + +NotificationServer::NotificationServer(void) + : m_initialized(false) + , m_pDBusConnection(NULL) +{ + +} + +NotificationServer::~NotificationServer(void) +{ + if (m_pDBusConnection) + { + dbus_connection_close(m_pDBusConnection); + m_pDBusConnection = NULL; + } +} + +int +NotificationServer::initialize(void) +{ + if (m_initialized) + return PRIV_FLTR_ERROR_SUCCESS; + + DBusError error; + dbus_error_init(&error); + + m_pDBusConnection = dbus_bus_get_private(DBUS_BUS_SYSTEM, &error); + TryReturn(m_pDBusConnection != NULL, PRIV_FLTR_ERROR_SYSTEM_ERROR, dbus_error_free(&error), "dbus_bus_get_private : %s", error.message); + + dbus_connection_setup_with_g_main(m_pDBusConnection, NULL); + std::unique_ptr < char[] > pRule(new char[MAX_LOCAL_BUF_SIZE]); + + snprintf(pRule.get(), MAX_LOCAL_BUF_SIZE, "path='%s',type='signal',interface='%s'", DBUS_PATH.c_str(), DBUS_SIGNAL_INTERFACE.c_str()); + + dbus_bus_add_match(m_pDBusConnection, pRule.get(), &error); + TryReturn(!dbus_error_is_set(&error), PRIV_FLTR_ERROR_SYSTEM_ERROR, dbus_error_free(&error), "dbus_bus_add_match : %s", error.message); + + m_initialized = true; + return PRIV_FLTR_ERROR_SUCCESS; +} + +int +NotificationServer::notifySettingChanged(const std::string pkgId, const std::string privacyId) +{ + if (!m_initialized) + return PRIV_FLTR_ERROR_INVALID_STATE; + + char* pPkgId = const_cast (pkgId.c_str()); + char* pPrivacyId = const_cast (privacyId.c_str()); + + DBusMessage* pMessage = dbus_message_new_signal(DBUS_PATH.c_str(), DBUS_SIGNAL_INTERFACE.c_str(), DBUS_SIGNAL_SETTING_CHANGED.c_str()); + TryReturn(pMessage != NULL, PRIV_FLTR_ERROR_IPC_ERROR, , "dbus_message_new_signal"); + + dbus_bool_t r; + r = dbus_message_append_args(pMessage, + DBUS_TYPE_STRING, &pPkgId, + DBUS_TYPE_STRING, &pPrivacyId, + DBUS_TYPE_INVALID); + TryReturn(r, PRIV_FLTR_ERROR_IPC_ERROR, , "dbus_message_append_args"); + + r = dbus_connection_send(m_pDBusConnection, pMessage, NULL); + TryReturn(r, PRIV_FLTR_ERROR_IPC_ERROR, dbus_message_unref(pMessage);, "dbus_connection_send"); + + dbus_connection_flush(m_pDBusConnection); + dbus_message_unref(pMessage); + + return PRIV_FLTR_ERROR_SUCCESS; +} + +int +NotificationServer::notifyPkgRemoved(const std::string pkgId) +{ + if (!m_initialized) + return PRIV_FLTR_ERROR_INVALID_STATE; + + char* pPkgId = const_cast (pkgId.c_str()); + + DBusMessage* pMessage = dbus_message_new_signal(DBUS_PATH.c_str(), DBUS_SIGNAL_INTERFACE.c_str(), DBUS_SIGNAL_PKG_REMOVED.c_str()); + TryReturn(pMessage != NULL, PRIV_FLTR_ERROR_IPC_ERROR, , "dbus_message_new_signal"); + + dbus_bool_t r; + r = dbus_message_append_args(pMessage, + DBUS_TYPE_STRING, &pPkgId, + DBUS_TYPE_INVALID); + TryReturn(r, PRIV_FLTR_ERROR_IPC_ERROR, , "dbus_message_append_args"); + + r = dbus_connection_send(m_pDBusConnection, pMessage, NULL); + TryReturn(r, PRIV_FLTR_ERROR_IPC_ERROR, dbus_message_unref(pMessage);, "dbus_connection_send"); + + dbus_connection_flush(m_pDBusConnection); + dbus_message_unref(pMessage); + + return PRIV_FLTR_ERROR_SUCCESS; +} diff --git a/server/src/PrivacyGuardDaemon.cpp b/server/src/PrivacyGuardDaemon.cpp new file mode 100755 index 0000000..e15e018 --- /dev/null +++ b/server/src/PrivacyGuardDaemon.cpp @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include "PrivacyGuardDaemon.h" +#include "PrivacyInfoService.h" +#include "SocketService.h" +#if 0 +// [CYNARA] +#include +#endif + +PrivacyGuardDaemon* PrivacyGuardDaemon::pInstance = NULL; + +PrivacyGuardDaemon::PrivacyGuardDaemon(void) + : pSocketService(NULL) +{ +} + +PrivacyGuardDaemon::~PrivacyGuardDaemon(void) +{ +} + +PrivacyGuardDaemon* +PrivacyGuardDaemon::getInstance(void) +{ + if (pInstance == NULL) + pInstance = new PrivacyGuardDaemon(); + return pInstance; +} + +int +PrivacyGuardDaemon::initialize(void) +{ + if (pSocketService == NULL) + pSocketService = new SocketService(); +#if 0 + // [CYNARA] + if (pCynaraService == NULL) + pCynaraService = new CynaraService(); +#endif + pSocketService->initialize(); +#if 0 + // [CYNARA] + pCynaraService->initialize(); +#endif + + PrivacyInfoService::registerCallbacks(pSocketService); + + return 0; +} + +int +PrivacyGuardDaemon::start(void) +{ + int res = 0; + + if (pSocketService == NULL) + return PRIV_FLTR_ERROR_NOT_INITIALIZED; + res = pSocketService->start(); + if(res != PRIV_FLTR_ERROR_SUCCESS){ + PF_LOGE("FAIL"); + } +#if 0 + // [CYNARA] + if (pCynaraService == NULL) + return PRIV_FLTR_ERROR_NOT_INITIALIZED; + res = pCynaraService->start(); + if(res != PRIV_FLTR_ERROR_SUCCESS){ + PF_LOGE("FAIL"); + } +#endif + return res; +} + +int +PrivacyGuardDaemon::stop(void) +{ + pSocketService->stop(); +#if 0 + // [CYNARA] + pCynaraService->stop(); +#endif + + return 0; +} + +int +PrivacyGuardDaemon::shutdown(void) +{ + pSocketService->shutdown(); + return 0; +} diff --git a/server/src/PrivacyGuardDb.cpp b/server/src/PrivacyGuardDb.cpp new file mode 100755 index 0000000..e9ca8b3 --- /dev/null +++ b/server/src/PrivacyGuardDb.cpp @@ -0,0 +1,1179 @@ +/* + * Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include "Utils.h" +#include "PrivacyGuardDb.h" +#include "PrivacyIdInfo.h" +#if 0 +// [CYNARA] +#include "CynaraService.h" + +//static cynara_monitor_configuration *p_conf; +static cynara_monitor *p_cynara_monitor; +static cynara_monitor_entry **monitor_entries; +#endif + +std::mutex PrivacyGuardDb::m_singletonMutex; +PrivacyGuardDb* PrivacyGuardDb::m_pInstance = NULL; + +static const char* privacy_list[5] = { "http://tizen.org/privacy/location", + "http://tizen.org/privacy/contact", + "http://tizen.org/privacy/calendar", + "http://tizen.org/privacy/messaging", + "http://tizen.org/privacy/callhistory" }; + +#ifdef __FILTER_LISTED_PKG +const std::string PrivacyGuardDb::PRIVACY_FILTER_LIST_FILE = std::string("/usr/share/privacy-guard/privacy-guard-list.ini"); +const std::string PrivacyGuardDb::FILTER_KEY = std::string("package_id"); +std::map < std::string, bool > PrivacyGuardDb::m_filteredPkgList; +#endif + +void +PrivacyGuardDb::createDB(void) +{ + +} + +void +PrivacyGuardDb::openSqliteDB(void) +{ + int res = -1; + res = sqlite3_open_v2(PRIVACY_DB_PATH, &m_sqlHandler, SQLITE_OPEN_READWRITE, NULL); + if(res == SQLITE_OK) { + PF_LOGI("monitor db is opened successfully"); +// sqlite3_wal_autocheckpoint(m_sqlHandler, 1); + m_bDBOpen = true; + } + else { + PF_LOGE("fail : monitor db open(%d)", res); + } +} + +int +PrivacyGuardDb::PgAddPrivacyAccessLog(const int userId, std::list < std::pair < std::string, std::string > > logInfoList) +{ + time_t current_date; + current_date = time(NULL); + localtime(¤t_date); + + if(current_date <= 0) { + return PRIV_FLTR_ERROR_INVALID_PARAMETER; + } + + int res = -1; + + static const std::string QUERY_INSERT = std::string("INSERT INTO StatisticsMonitorInfo(USER_ID, PKG_ID, PRIVACY_ID, USE_DATE) VALUES(?, ?, ?, ?)"); + + m_dbMutex.lock(); + // open db + if(m_bDBOpen == false) { + openSqliteDB(); + } + TryCatchResLogReturn(m_bDBOpen == true, m_dbMutex.unlock(), PRIV_FLTR_ERROR_IO_ERROR, "openSqliteDB : %d", res); + + PF_LOGD("addlogToDb m_sqlHandler : %p", m_sqlHandler); + + // prepare + res = sqlite3_prepare_v2(m_sqlHandler, QUERY_INSERT.c_str(), -1, &m_stmt, NULL); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_prepare_v2 : %d", res); + + for (std::list >::iterator iter = logInfoList.begin(); iter != logInfoList.end(); ++iter) { + PF_LOGD("packageID : %s, PrivacyID : %s", iter->first.c_str(), iter->second.c_str()); + + // bind + res = sqlite3_bind_int(m_stmt, 1, userId); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res); + + res = sqlite3_bind_text(m_stmt, 2, iter->first.c_str(), -1, SQLITE_TRANSIENT); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_text : %d", res); + + res = sqlite3_bind_text(m_stmt, 3, iter->second.c_str(), -1, SQLITE_TRANSIENT); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_text : %d", res); + + res = sqlite3_bind_int(m_stmt, 4, current_date); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res); + + res = sqlite3_step(m_stmt); + TryCatchResLogReturn(res == SQLITE_DONE, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_step : %d", res); + + sqlite3_reset(m_stmt); + } + m_dbMutex.unlock(); + + return PRIV_FLTR_ERROR_SUCCESS; +} + +int +PrivacyGuardDb::PgAddPrivacyAccessLogForCynara(const int userId, const std::string packageId, const std::string privilege, const timespec* timestamp) +{ + if(timestamp->tv_sec <= 0) { + return PRIV_FLTR_ERROR_INVALID_PARAMETER; + } + + int res = SQLITE_OK; + + // change from privilege to privacy + std::string privacyId; + res = PrivacyIdInfo::getPrivacyIdFromPrivilege(privilege, privacyId); + if (res == PRIV_FLTR_ERROR_NO_DATA) { + return PRIV_FLTR_ERROR_SUCCESS; + } + TryReturn( res == PRIV_FLTR_ERROR_SUCCESS, res, , "getPrivacyIdFromPrivilege : %d", res); + + // change from timespec to time_t + time_t logging_date; + logging_date = timestamp->tv_sec; + + static const std::string QUERY_INSERT = std::string("INSERT INTO StatisticsMonitorInfo(USER_ID, PKG_ID, PRIVACY_ID, USE_DATE) VALUES(?, ?, ?, ?)"); + + m_dbMutex.lock(); + // open db + if(m_bDBOpen == false) { + openSqliteDB(); + } + TryCatchResLogReturn(m_bDBOpen == true, m_dbMutex.unlock(), PRIV_FLTR_ERROR_IO_ERROR, "openSqliteDB : %d", res); + + PF_LOGD("addlogToDb m_sqlHandler : %p", m_sqlHandler); + + // prepare + res = sqlite3_prepare_v2(m_sqlHandler, QUERY_INSERT.c_str(), -1, &m_stmt, NULL); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_prepare_v2 : %d", res); + + // bind + res = sqlite3_bind_int(m_stmt, 1, userId); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res); + + res = sqlite3_bind_text(m_stmt, 2, packageId.c_str(), -1, SQLITE_TRANSIENT); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_text : %d", res); + + res = sqlite3_bind_text(m_stmt, 3, privacyId.c_str(), -1, SQLITE_TRANSIENT); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_text : %d", res); + + res = sqlite3_bind_int(m_stmt, 4, logging_date); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res); + + res = sqlite3_step(m_stmt); + TryCatchResLogReturn(res == SQLITE_DONE, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_step : %d", res); + + sqlite3_reset(m_stmt); + + m_dbMutex.unlock(); + + return PRIV_FLTR_ERROR_SUCCESS; +} + +int +PrivacyGuardDb::PgAddPrivacyAccessLogTest(const int userId, const std::string packageId, const std::string privacyId) +{ + time_t current_date; + current_date = time(NULL); + localtime(¤t_date); + + if(current_date <= 0) { + return PRIV_FLTR_ERROR_INVALID_PARAMETER; + } + + int res = SQLITE_OK; + + static const std::string QUERY_INSERT = std::string("INSERT INTO StatisticsMonitorInfo(USER_ID, PKG_ID, PRIVACY_ID, USE_DATE) VALUES(?, ?, ?, ?)"); + + m_dbMutex.lock(); + // open db + if(m_bDBOpen == false) { + openSqliteDB(); + } + TryCatchResLogReturn(m_bDBOpen == true, m_dbMutex.unlock(), PRIV_FLTR_ERROR_IO_ERROR, "openSqliteDB : %d", res); + + PF_LOGD("addlogToDb m_sqlHandler : %p", m_sqlHandler); + + // prepare + res = sqlite3_prepare_v2(m_sqlHandler, QUERY_INSERT.c_str(), -1, &m_stmt, NULL); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_prepare_v2 : %d", res); + + // bind + res = sqlite3_bind_int(m_stmt, 1, userId); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res); + + res = sqlite3_bind_text(m_stmt, 2, packageId.c_str(), -1, SQLITE_TRANSIENT); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_text : %d", res); + + res = sqlite3_bind_text(m_stmt, 3, privacyId.c_str(), -1, SQLITE_TRANSIENT); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_text : %d", res); + + res = sqlite3_bind_int(m_stmt, 4, current_date); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res); + + res = sqlite3_step(m_stmt); + TryCatchResLogReturn(res == SQLITE_DONE, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_step : %d", res); + + sqlite3_reset(m_stmt); + + m_dbMutex.unlock(); + + return PRIV_FLTR_ERROR_SUCCESS; +} + + +int +PrivacyGuardDb::PgAddMonitorPolicy(const int userId, const std::string packageId, const std::list < std::string > privacyList, bool monitorPolicy) +{ + int res = -1; + + static const std::string QUERY_INSERT = std::string("INSERT INTO MonitorPolicy(USER_ID, PKG_ID, PRIVACY_ID, MONITOR_POLICY) VALUES(?, ?, ?, ?)"); + + m_dbMutex.lock(); + // open db + if(m_bDBOpen == false) { + openSqliteDB(); + } + TryCatchResLogReturn(m_bDBOpen == true, m_dbMutex.unlock(), PRIV_FLTR_ERROR_IO_ERROR, "openSqliteDB : %d", res); + + PF_LOGD("addlogToDb m_sqlHandler : %p", m_sqlHandler); + + // prepare + res = sqlite3_prepare_v2(m_sqlHandler, QUERY_INSERT.c_str(), -1, &m_stmt, NULL); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_prepare_v2 : %d", res); + + for (std::list ::const_iterator iter = privacyList.begin(); iter != privacyList.end(); ++iter) { + PF_LOGD("PrivacyID : %s", iter->c_str()); + + // bind + res = sqlite3_bind_int(m_stmt, 1, userId); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res); + + res = sqlite3_bind_text(m_stmt, 2, packageId.c_str(), -1, SQLITE_TRANSIENT); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_text : %d", res); + + res = sqlite3_bind_text(m_stmt, 3, iter->c_str(), -1, SQLITE_TRANSIENT); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_text : %d", res); + + res = sqlite3_bind_int(m_stmt, 4, monitorPolicy); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res); + + res = sqlite3_step(m_stmt); + TryCatchResLogReturn(res == SQLITE_DONE, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_step : %d", res); + + sqlite3_reset(m_stmt); + } + m_dbMutex.unlock(); + + return PRIV_FLTR_ERROR_SUCCESS; +} + +int +PrivacyGuardDb::PgCheckPrivacyPackage(const int userId, const std::string packageId, bool &isPrivacyPackage) +{ + int res = -1; + static const std::string query = std::string("SELECT COUNT(*) FROM MonitorPolicy WHERE USER_ID=? AND PKG_ID=?"); + + m_dbMutex.lock(); + // open db + if(m_bDBOpen == false) { + openSqliteDB(); + } + TryCatchResLogReturn(m_bDBOpen == true, m_dbMutex.unlock(), PRIV_FLTR_ERROR_IO_ERROR, "openSqliteDB : %d", res); + + // prepare + res = sqlite3_prepare_v2(m_sqlHandler, query.c_str(), -1, &m_stmt, NULL); + TryCatchResLogReturn( res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_prepare_v2 : %d", res); + + // bind + res = sqlite3_bind_int(m_stmt, 1, userId); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res); + + res = sqlite3_bind_text(m_stmt, 2, packageId.c_str(), -1, SQLITE_TRANSIENT); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_text : %d", res); + + int count = -1; + + // step + if ((res = sqlite3_step(m_stmt)) == SQLITE_ROW) { + count = sqlite3_column_int(m_stmt, 0); + } + m_dbMutex.unlock(); + + if (count > 0) { + isPrivacyPackage = true; + } + else { + isPrivacyPackage = false; + } + + return PRIV_FLTR_ERROR_SUCCESS; +} + +int +PrivacyGuardDb::PgDeleteAllLogsAndMonitorPolicy(void) +{ + PF_LOGD("PgDeleteAllLogsAndMonitorPolicy"); + + int res = -1; + + static const std::string LOG_DELETE = std::string("DELETE FROM StatisticsMonitorInfo"); + static const std::string POLICY_DELETE = std::string("DELETE FROM MonitorPolicy"); + static const std::string MAIN_POLICY_DELETE = std::string("DELETE FROM MainMonitorPolicy"); + + m_dbMutex.lock(); + // open db + if(m_bDBOpen == false) { + openSqliteDB(); + } + TryCatchResLogReturn(m_bDBOpen == true, m_dbMutex.unlock(), PRIV_FLTR_ERROR_IO_ERROR, "openSqliteDB : %d", res); + + // prepare + res = sqlite3_prepare_v2(m_sqlHandler, LOG_DELETE.c_str(), -1, &m_stmt, NULL); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_prepare_v2 : %d", res); + + res = sqlite3_step(m_stmt); + TryCatchResLogReturn(res == SQLITE_DONE, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_step : %d", res); + + res = sqlite3_prepare_v2(m_sqlHandler, POLICY_DELETE.c_str(), -1, &m_stmt, NULL); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_prepare_v2 : %d", res); + + res = sqlite3_step(m_stmt); + TryCatchResLogReturn(res == SQLITE_DONE, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_step : %d", res); + + res = sqlite3_prepare_v2(m_sqlHandler, MAIN_POLICY_DELETE.c_str(), -1, &m_stmt, NULL); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_prepare_v2 : %d", res); + + res = sqlite3_step(m_stmt); + TryCatchResLogReturn(res == SQLITE_DONE, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_step : %d", res); + + m_dbMutex.unlock(); + + return PRIV_FLTR_ERROR_SUCCESS; +} + + +int +PrivacyGuardDb::PgDeleteLogsByPackageId(const std::string packageId) +{ + PF_LOGD("PrivacyGuardDb::PgDeleteLogsByPackageId packageid : %s", packageId.c_str()); + + int res = -1; + + static const std::string QUERY_DELETE = std::string("DELETE FROM StatisticsMonitorInfo WHERE PKG_ID=?"); + + m_dbMutex.lock(); + // open db + if(m_bDBOpen == false) { + openSqliteDB(); + } + TryCatchResLogReturn(m_bDBOpen == true, m_dbMutex.unlock(), PRIV_FLTR_ERROR_IO_ERROR, "openSqliteDB : %d", res); + + // prepare + res = sqlite3_prepare_v2(m_sqlHandler, QUERY_DELETE.c_str(), -1, &m_stmt, NULL); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_prepare_v2 : %d", res); + + // bind + res = sqlite3_bind_text(m_stmt, 1, packageId.c_str(), -1, SQLITE_TRANSIENT); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_text : %d", res); + + // step + res = sqlite3_step(m_stmt); + TryCatchResLogReturn(res == SQLITE_DONE, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_step : %d", res); + + m_dbMutex.unlock(); + + return PRIV_FLTR_ERROR_SUCCESS; +} + +int +PrivacyGuardDb::PgDeleteMonitorPolicyByPackageId(const std::string packageId) +{ + PF_LOGD("PrivacyGuardDb::PgDeleteMonitorPolicyByPackageId packageid : %s", packageId.c_str()); + + int res = -1; + + static const std::string QUERY_DELETE = std::string("DELETE FROM MonitorPolicy WHERE PKG_ID=?"); + + m_dbMutex.lock(); + // open db + if(m_bDBOpen == false) { + openSqliteDB(); + } + TryCatchResLogReturn(m_bDBOpen == true, m_dbMutex.unlock(), PRIV_FLTR_ERROR_IO_ERROR, "openSqliteDB : %d", res); + + // prepare + res = sqlite3_prepare_v2(m_sqlHandler, QUERY_DELETE.c_str(), -1, &m_stmt, NULL); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_prepare_v2 : %d", res); + + // bind + res = sqlite3_bind_text(m_stmt, 1, packageId.c_str(), -1, SQLITE_TRANSIENT); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_text : %d", res); + + // step + res = sqlite3_step(m_stmt); + TryCatchResLogReturn(res == SQLITE_DONE, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_step : %d", res); + + m_dbMutex.unlock(); + + return PRIV_FLTR_ERROR_SUCCESS; +} + +int +PrivacyGuardDb::PgForeachTotalPrivacyCountOfPackage(const int userId, const int startDate, const int endDate, + std::list < std::pair < std::string, int > >& packageInfoList) +{ + int res = -1; + +#if 0 + // [CYNARA] Fluch Entries + int ret= cynara_monitor_entries_flush(p_cynara_monitor); + if(ret != CYNARA_API_SUCCESS){ + LOGE("cynara_monitor_entries_flush FAIL"); + return PRIV_FLTR_ERROR_SYSTEM_ERROR; + } + + // [CYNARA] Get Entries + ret = cynara_monitor_entries_get(p_cynara_monitor, &monitor_entries); + if(ret != CYNARA_API_SUCCESS){ + LOGE("cynara_monitor_entries_get FAIL"); + return PRIV_FLTR_ERROR_SYSTEM_ERROR; + } + + // [CYNARA] Update DB + ret = CynaraService::updateDb(monitor_entries); + if(ret != PRIV_FLTR_ERROR_SUCCESS){ + LOGE("updateDb FAIL"); + return ret; + } +#endif + + static const std::string PKGID_SELECT = std::string("SELECT DISTINCT PKG_ID FROM StatisticsMonitorInfo WHERE USER_ID=? AND USE_DATE>=? AND USE_DATE<=?"); + static const std::string PKGINFO_SELECT = std::string("SELECT COUNT(*) FROM StatisticsMonitorInfo WHERE USER_ID=? AND PKG_ID=? AND USE_DATE>=? AND USE_DATE<=?"); + sqlite3_stmt* infoStmt; + + m_dbMutex.lock(); + // open db + if(m_bDBOpen == false) { + openSqliteDB(); + } + TryCatchResLogReturn(m_bDBOpen == true, m_dbMutex.unlock(), PRIV_FLTR_ERROR_IO_ERROR, "openSqliteDB : %d", res); + + // prepare + res = sqlite3_prepare_v2(m_sqlHandler, PKGID_SELECT.c_str(), -1, &m_stmt, NULL); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_prepare_v2 : %d", res); + + res = sqlite3_bind_int(m_stmt, 1, userId); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res); + + res = sqlite3_bind_int(m_stmt, 2, startDate); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res); + + res = sqlite3_bind_int(m_stmt, 3, endDate); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res); + + while ((res = sqlite3_step(m_stmt)) == SQLITE_ROW) { + const char* packageId = reinterpret_cast < const char* > (sqlite3_column_text(m_stmt, 0)); + if(packageId == NULL) { continue; } + + // prepare + res = sqlite3_prepare_v2(m_sqlHandler, PKGINFO_SELECT.c_str(), -1, &infoStmt, NULL); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_prepare_v2 : %d", res); + + res = sqlite3_bind_int(infoStmt, 1, userId); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res); + + res = sqlite3_bind_text(infoStmt, 2, packageId, -1, SQLITE_TRANSIENT); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_text : %d", res); + + res = sqlite3_bind_int(infoStmt, 3, startDate); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res); + + res = sqlite3_bind_int(infoStmt, 4, endDate); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res); + + while ((res = sqlite3_step(infoStmt)) == SQLITE_ROW) { + int count = sqlite3_column_int(infoStmt, 0); + if (count == 0) { + continue; + } + packageInfoList.push_back(std::pair (std::string(packageId), count)); + } + sqlite3_reset(infoStmt); + } + m_dbMutex.unlock(); + + return PRIV_FLTR_ERROR_SUCCESS; +} + +int +PrivacyGuardDb::PgForeachTotalPrivacyCountOfPrivacy(const int userId, const int startDate, const int endDate, + std::list < std::pair < std::string, int > >& privacyInfoList) +{ + int res = -1; + +#if 0 + // [CYNARA] Fluch Entries + int ret= cynara_monitor_entries_flush(p_cynara_monitor); + if(ret != CYNARA_API_SUCCESS){ + LOGE("cynara_monitor_entries_flush FAIL"); + return PRIV_FLTR_ERROR_SYSTEM_ERROR; + } + + // [CYNARA] Get Entries + ret = cynara_monitor_entries_get(p_cynara_monitor, &monitor_entries); + if(ret != CYNARA_API_SUCCESS){ + LOGE("cynara_monitor_entries_get FAIL"); + return PRIV_FLTR_ERROR_SYSTEM_ERROR; + } + + // [CYNARA] Update DB + ret = CynaraService::updateDb(monitor_entries); + if(ret != PRIV_FLTR_ERROR_SUCCESS){ + LOGE("updateDb FAIL"); + return ret; + } +#endif + + static const std::string PRIVACY_SELECT = std::string("SELECT COUNT(*) FROM StatisticsMonitorInfo WHERE USER_ID=? AND PRIVACY_ID=? AND USE_DATE>=? AND USE_DATE<=?"); + + m_dbMutex.lock(); + // open db + if(m_bDBOpen == false) { + openSqliteDB(); + } + TryCatchResLogReturn(m_bDBOpen == true, m_dbMutex.unlock(), PRIV_FLTR_ERROR_IO_ERROR, "openSqliteDB : %d", res); + + int i; + int cnt_privacy = sizeof(privacy_list) / sizeof(privacy_list[0]); + + for (i = 0; i < cnt_privacy; i++) { + // prepare + res = sqlite3_prepare_v2(m_sqlHandler, PRIVACY_SELECT.c_str(), -1, &m_stmt, NULL); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_prepare_v2 : %d", res); + + // bind + res = sqlite3_bind_int(m_stmt, 1, userId); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res); + + res = sqlite3_bind_text(m_stmt, 2, privacy_list[i], -1, SQLITE_TRANSIENT); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_text : %d", res); + + res = sqlite3_bind_int(m_stmt, 3, startDate); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res); + + res = sqlite3_bind_int(m_stmt, 4, endDate); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res); + + // step + if ((res = sqlite3_step(m_stmt)) == SQLITE_ROW) { + int count = sqlite3_column_int(m_stmt, 0); + if (count == 0) { + continue; + } + const char* privacyId = privacy_list[i]; + privacyInfoList.push_back(std::pair (std::string(privacyId), count)); + } + sqlite3_reset(m_stmt); + } + + m_dbMutex.unlock(); + + return PRIV_FLTR_ERROR_SUCCESS; +} + +int +PrivacyGuardDb::PgForeachPrivacyCountByPrivacyId(const int userId, const int startDate, const int endDate, + const std::string privacyId, std::list < std::pair < std::string, int > >& packageInfoList) +{ + int res = -1; + +#if 0 + // [CYNARA] Fluch Entries + int ret= cynara_monitor_entries_flush(p_cynara_monitor); + if(ret != CYNARA_API_SUCCESS){ + LOGE("cynara_monitor_entries_flush FAIL"); + return PRIV_FLTR_ERROR_SYSTEM_ERROR; + } + + // [CYNARA] Get Entries + ret = cynara_monitor_entries_get(p_cynara_monitor, &monitor_entries); + if(ret != CYNARA_API_SUCCESS){ + LOGE("cynara_monitor_entries_get FAIL"); + return PRIV_FLTR_ERROR_SYSTEM_ERROR; + } + + // [CYNARA] Update DB + ret = CynaraService::updateDb(monitor_entries); + if(ret != PRIV_FLTR_ERROR_SUCCESS){ + LOGE("updateDb FAIL"); + return ret; + } +#endif + + static const std::string PKGID_SELECT = std::string("SELECT DISTINCT PKG_ID FROM StatisticsMonitorInfo WHERE USER_ID=? AND PRIVACY_ID=? AND USE_DATE>=? AND USE_DATE<=?"); + static const std::string PKGINFO_SELECT = std::string("SELECT COUNT(*) FROM StatisticsMonitorInfo WHERE USER_ID=? AND PKG_ID=? AND PRIVACY_ID=? AND USE_DATE>=? AND USE_DATE<=?"); + sqlite3_stmt* infoStmt; + + m_dbMutex.lock(); + // open db + if(m_bDBOpen == false) { + openSqliteDB(); + } + TryCatchResLogReturn(m_bDBOpen == true, m_dbMutex.unlock(), PRIV_FLTR_ERROR_IO_ERROR, "openSqliteDB : %d", res); + + // prepare + res = sqlite3_prepare_v2(m_sqlHandler, PKGID_SELECT.c_str(), -1, &m_stmt, NULL); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_prepare_v2 : %d", res); + + // bind + res = sqlite3_bind_int(m_stmt, 1, userId); + TryReturn(res == SQLITE_OK, PRIV_FLTR_ERROR_DB_ERROR, , "sqlite3_bind_int : %d", res); + + res = sqlite3_bind_text(m_stmt, 2, privacyId.c_str(), -1, SQLITE_TRANSIENT); + TryReturn(res == SQLITE_OK, PRIV_FLTR_ERROR_DB_ERROR, , "sqlite3_bind_text : %d", res); + + res = sqlite3_bind_int(m_stmt, 3, startDate); + TryReturn(res == SQLITE_OK, PRIV_FLTR_ERROR_DB_ERROR, , "sqlite3_bind_int : %d", res); + + res = sqlite3_bind_int(m_stmt, 4, endDate); + TryReturn(res == SQLITE_OK, PRIV_FLTR_ERROR_DB_ERROR, , "sqlite3_bind_int : %d", res); + + while ((res = sqlite3_step(m_stmt)) == SQLITE_ROW) { + const char* packageId = reinterpret_cast < const char* > (sqlite3_column_text(m_stmt, 0)); + if(packageId == NULL) { continue; } + + // prepare + res = sqlite3_prepare_v2(m_sqlHandler, PKGINFO_SELECT.c_str(), -1, &infoStmt, NULL); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_prepare_v2 : %d", res); + + // bind + res = sqlite3_bind_int(infoStmt, 1, userId); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res); + + res = sqlite3_bind_text(infoStmt, 2, packageId, -1, SQLITE_TRANSIENT); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_text : %d", res); + + res = sqlite3_bind_text(infoStmt, 3, privacyId.c_str(), -1, SQLITE_TRANSIENT); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_text : %d", res); + + res = sqlite3_bind_int(infoStmt, 4, startDate); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res); + + res = sqlite3_bind_int(infoStmt, 5, endDate); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res); + + if ((res = sqlite3_step(infoStmt)) == SQLITE_ROW) { + int count = sqlite3_column_int(infoStmt, 0); + if (count == 0) { + continue; + } + packageInfoList.push_back(std::pair (std::string(packageId), count)); + } + sqlite3_reset(infoStmt); + } + + m_dbMutex.unlock(); + + return PRIV_FLTR_ERROR_SUCCESS; +} + +int +PrivacyGuardDb::PgForeachPrivacyCountByPackageId(const int userId, const int startDate, const int endDate, + const std::string packageId, std::list < std::pair < std::string, int > >& privacyInfoList) +{ + int res = -1; + +#if 0 + // [CYNARA] Fluch Entries + int ret= cynara_monitor_entries_flush(p_cynara_monitor); + if(ret != CYNARA_API_SUCCESS){ + LOGE("cynara_monitor_entries_flush FAIL"); + return PRIV_FLTR_ERROR_SYSTEM_ERROR; + } + + // [CYNARA] Get Entries + ret = cynara_monitor_entries_get(p_cynara_monitor, &monitor_entries); + if(ret != CYNARA_API_SUCCESS){ + LOGE("cynara_monitor_entries_get FAIL"); + return PRIV_FLTR_ERROR_SYSTEM_ERROR; + } + + // [CYNARA] Update DB + ret = CynaraService::updateDb(monitor_entries); + if(ret != PRIV_FLTR_ERROR_SUCCESS){ + LOGE("updateDb FAIL"); + return ret; + } +#endif + + static const std::string PRIVACY_SELECT = std::string("SELECT COUNT(*) FROM StatisticsMonitorInfo WHERE USER_ID=? AND PKG_ID=? AND PRIVACY_ID=? AND USE_DATE>=? AND USE_DATE<=?"); + + m_dbMutex.lock(); + // open db + if(m_bDBOpen == false) { + openSqliteDB(); + } + TryCatchResLogReturn(m_bDBOpen == true, m_dbMutex.unlock(), PRIV_FLTR_ERROR_IO_ERROR, "openSqliteDB : %d", res); + + int i; + int cnt_privacy = sizeof(privacy_list) / sizeof(privacy_list[0]); + + for (i = 0; i < cnt_privacy; i++) { + // prepare + res = sqlite3_prepare_v2(m_sqlHandler, PRIVACY_SELECT.c_str(), -1, &m_stmt, NULL); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_prepare_v2 : %d", res); + + //bind + res = sqlite3_bind_int(m_stmt, 1, userId); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res); + + res = sqlite3_bind_text(m_stmt, 2, packageId.c_str(), -1, SQLITE_TRANSIENT); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_text : %d", res); + + res = sqlite3_bind_text(m_stmt, 3, privacy_list[i], -1, SQLITE_TRANSIENT); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_text : %d", res); + + res = sqlite3_bind_int(m_stmt, 4, startDate); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res); + + res = sqlite3_bind_int(m_stmt, 5, endDate); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res); + + if ((res = sqlite3_step(m_stmt)) == SQLITE_ROW) { + int count = sqlite3_column_int(m_stmt, 0); + if (count == 0) { + continue; + } + const char* privacyId = privacy_list[i]; + privacyInfoList.push_back(std::pair (std::string(privacyId), count)); + } + sqlite3_reset(m_stmt); + } + + m_dbMutex.unlock(); + + return PRIV_FLTR_ERROR_SUCCESS; +} + +int +PrivacyGuardDb::PgGetMonitorPolicy(const int userId, const std::string packageId, const std::string privacyId, int& monitorPolicy) +{ + + int res = -1; + static const std::string query = std::string("SELECT MONITOR_POLICY FROM MonitorPolicy WHERE USER_ID=? AND PKG_ID=? AND PRIVACY_ID=?"); + + m_dbMutex.lock(); + // open db + if(m_bDBOpen == false) { + openSqliteDB(); + } + TryCatchResLogReturn(m_bDBOpen == true, m_dbMutex.unlock(), PRIV_FLTR_ERROR_IO_ERROR, "openSqliteDB : %d", res); + + // prepare + res = sqlite3_prepare_v2(m_sqlHandler, query.c_str(), -1, &m_stmt, NULL); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_prepare_v2 : %d", res); + + // bind + res = sqlite3_bind_int(m_stmt, 1, userId); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res); + + res = sqlite3_bind_text(m_stmt, 2, packageId.c_str(), -1, SQLITE_TRANSIENT); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_text : %d", res); + + res = sqlite3_bind_text(m_stmt, 3, privacyId.c_str(), -1, SQLITE_TRANSIENT); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_text : %d", res); + + // step + monitorPolicy = 0; + if ((res = sqlite3_step(m_stmt)) == SQLITE_ROW) { + monitorPolicy = sqlite3_column_int(m_stmt, 0); + } + m_dbMutex.unlock(); + + return PRIV_FLTR_ERROR_SUCCESS; +} + +int +PrivacyGuardDb::PgGetAllMonitorPolicy(std::list < std::pair < std::string, int > >& monitorPolicyList) +{ + int res = -1; + + static const std::string MONITOR_POLICY_SELECT = std::string("SELECT * FROM MonitorPolicy"); + + m_dbMutex.lock(); + // open db + if(m_bDBOpen == false) { + openSqliteDB(); + } + TryCatchResLogReturn(m_bDBOpen == true, m_dbMutex.unlock(), PRIV_FLTR_ERROR_IO_ERROR, "openSqliteDB : %d", res); + + // prepare + res = sqlite3_prepare_v2(m_sqlHandler, MONITOR_POLICY_SELECT.c_str(), -1, &m_stmt, NULL); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_prepare_v2 : %d", res); + + // step + int monitorPolicy = 0; + while ((res = sqlite3_step(m_stmt)) == SQLITE_ROW) { + int userId = sqlite3_column_int(m_stmt, 0); + char* tmpPkgId = (char*)sqlite3_column_text(m_stmt, 1); + char* tmpPrivacyId = (char*)sqlite3_column_text(m_stmt, 2); + if(tmpPkgId == NULL || tmpPrivacyId == NULL) { + continue; + } + std::string userPkgIdPrivacyId = std::to_string(userId); + userPkgIdPrivacyId.append("|").append(std::string(tmpPkgId)); + userPkgIdPrivacyId.append("|").append(std::string(tmpPrivacyId)); + monitorPolicy = sqlite3_column_int(m_stmt, 3); + monitorPolicyList.push_back(std::pair < std::string, int > (userPkgIdPrivacyId, monitorPolicy)); + } + + m_dbMutex.unlock(); + if(monitorPolicyList.size() > 0) { + res = PRIV_FLTR_ERROR_SUCCESS; + } + else { + res = PRIV_FLTR_ERROR_NO_DATA; + } + + return res; +} + +int +PrivacyGuardDb::PgForeachMonitorPolicyByPackageId(const int userId, const std::string packageId, std::list & privacyInfoList) +{ + int res = -1; + static const std::string query = std::string("SELECT DISTINCT PRIVACY_ID, MONITOR_POLICY FROM MonitorPolicy WHERE USER_ID=? AND PKG_ID=?"); + + m_dbMutex.lock(); + // open db + if(m_bDBOpen == false) { + openSqliteDB(); + } + TryCatchResLogReturn(m_bDBOpen == true, m_dbMutex.unlock(), PRIV_FLTR_ERROR_IO_ERROR, "openSqliteDB : %d", res); + + // prepare + res = sqlite3_prepare_v2(m_sqlHandler, query.c_str(), -1, &m_stmt, NULL); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock();, PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_prepare_v2 : %d", res); + + // bind + res = sqlite3_bind_int(m_stmt, 1, userId); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res); + + res = sqlite3_bind_text(m_stmt, 2, packageId.c_str(), -1, SQLITE_TRANSIENT); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_text : %d", res); + + // step + while ((res = sqlite3_step(m_stmt)) == SQLITE_ROW) { + + char* tmp_data = (char*)sqlite3_column_text(m_stmt, 0); + if(tmp_data == NULL) { + continue; + } + privacy_data_s p_data; + p_data.privacy_id = strdup(tmp_data); + p_data.monitor_policy= sqlite3_column_int(m_stmt, 1); + + privacyInfoList.push_back(p_data); + } + m_dbMutex.unlock(); + + return PRIV_FLTR_ERROR_SUCCESS; +} + +int +PrivacyGuardDb::PgForeachPrivacyPackageId(const int userId, std::list < std::string > &packageList) +{ + int res = -1; + static const std::string query = std::string("SELECT DISTINCT PKG_ID FROM MonitorPolicy WHERE USER_ID=?"); + + m_dbMutex.lock(); + // open db + if(m_bDBOpen == false) { + openSqliteDB(); + } + TryCatchResLogReturn(m_bDBOpen == true, m_dbMutex.unlock(), PRIV_FLTR_ERROR_IO_ERROR, "openSqliteDB : %d", res); + + // prepare + res = sqlite3_prepare_v2(m_sqlHandler, query.c_str(), -1, &m_stmt, NULL); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock();, PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_prepare_v2 : %d", res); + + // bind + res = sqlite3_bind_int(m_stmt, 1, userId); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res); + + // step + while ((res = sqlite3_step(m_stmt)) == SQLITE_ROW) { + char* p_data = (char*)sqlite3_column_text(m_stmt, 0); + if(p_data == NULL) { + continue; + } + packageList.push_back(std::string(p_data)); + } + m_dbMutex.unlock(); + + return PRIV_FLTR_ERROR_SUCCESS; +} + +int +PrivacyGuardDb::PgForeachPackageByPrivacyId(const int userId, const std::string privacyId, std::list < std::string > &packageList) +{ + int res = -1; + static const std::string query = std::string("SELECT DISTINCT PKG_ID FROM MonitorPolicy WHERE USER_ID=? AND PRIVACY_ID=?"); + + m_dbMutex.lock(); + // open db + if(m_bDBOpen == false) { + openSqliteDB(); + } + TryCatchResLogReturn(m_bDBOpen == true, m_dbMutex.unlock(), PRIV_FLTR_ERROR_IO_ERROR, "openSqliteDB : %d", res); + + // prepare + res = sqlite3_prepare_v2(m_sqlHandler, query.c_str(), -1, &m_stmt, NULL); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock();, PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_prepare_v2 : %d", res); + + // bind + res = sqlite3_bind_int(m_stmt, 1, userId); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res); + + res = sqlite3_bind_text(m_stmt, 2, privacyId.c_str(), -1, SQLITE_TRANSIENT); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_text : %d", res); + + // step + while ((res = sqlite3_step(m_stmt)) == SQLITE_ROW) { + char* p_data = (char*)sqlite3_column_text(m_stmt, 0); + if(p_data == NULL) { + continue; + } + packageList.push_back(std::string(p_data)); + } + m_dbMutex.unlock(); + + return PRIV_FLTR_ERROR_SUCCESS; +} + +int +PrivacyGuardDb::PgUpdateMonitorPolicy(const int userId, const std::string packageId, const std::string privacyId, const int monitorPolicy) +{ + int res = -1; + static const std::string query = std::string("UPDATE MonitorPolicy SET MONITOR_POLICY=? WHERE USER_ID=? AND PKG_ID=? AND PRIVACY_ID=?"); + + m_dbMutex.lock(); + // open db + if(m_bDBOpen == false) { + openSqliteDB(); + } + TryCatchResLogReturn(m_bDBOpen == true, m_dbMutex.unlock(), PRIV_FLTR_ERROR_IO_ERROR, "openSqliteDB : %d", res); + + // prepare + res = sqlite3_prepare_v2(m_sqlHandler, query.c_str(), -1, &m_stmt, NULL); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_prepare_v2 : %d", res); + + // bind + res = sqlite3_bind_int(m_stmt, 1, monitorPolicy); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res); + + res = sqlite3_bind_int(m_stmt, 2, userId); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res); + + res = sqlite3_bind_text(m_stmt, 3, packageId.c_str(), -1, SQLITE_TRANSIENT); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_text : %d", res); + + res = sqlite3_bind_text(m_stmt, 4, privacyId.c_str(), -1, SQLITE_TRANSIENT); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_text : %d", res); + + // step + res = sqlite3_step(m_stmt); + TryCatchResLogReturn(res == SQLITE_DONE, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_step : %d", res); + + m_dbMutex.unlock(); + + return PRIV_FLTR_ERROR_SUCCESS; +} + +int +PrivacyGuardDb::PgAddMainMonitorPolicy(const int userId) +{ + int res = -1; + + static const std::string QUERY_INSERT = std::string("INSERT INTO MainMonitorPolicy(USER_ID) VALUES(?)"); + + m_dbMutex.lock(); + // open db + if(m_bDBOpen == false) { + openSqliteDB(); + } + TryCatchResLogReturn(m_bDBOpen == true, m_dbMutex.unlock(), PRIV_FLTR_ERROR_IO_ERROR, "openSqliteDB : %d", res); + + PF_LOGD("addlogToDb m_sqlHandler : %p", m_sqlHandler); + + // prepare + res = sqlite3_prepare_v2(m_sqlHandler, QUERY_INSERT.c_str(), -1, &m_stmt, NULL); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_prepare_v2 : %d", res); + + //bind + res = sqlite3_bind_int(m_stmt, 1, userId); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res); + + //step + res = sqlite3_step(m_stmt); + TryCatchResLogReturn(res == SQLITE_DONE, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_step : %d", res); + + m_dbMutex.unlock(); + + return PRIV_FLTR_ERROR_SUCCESS; +} + +int +PrivacyGuardDb::PgUpdateMainMonitorPolicy(const int userId, const bool mainMonitorPolicy) +{ + int res = -1; + static const std::string query = std::string("UPDATE MainMonitorPolicy SET MAIN_MONITOR_POLICY=? WHERE USER_ID=?"); + + m_dbMutex.lock(); + // open db + if(m_bDBOpen == false) { + openSqliteDB(); + } + TryCatchResLogReturn(m_bDBOpen == true, m_dbMutex.unlock(), PRIV_FLTR_ERROR_IO_ERROR, "openSqliteDB : %d", res); + + // prepare + res = sqlite3_prepare_v2(m_sqlHandler, query.c_str(), -1, &m_stmt, NULL); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_prepare_v2 : %d", res); + + // bind + res = sqlite3_bind_int(m_stmt, 1, mainMonitorPolicy); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res); + + res = sqlite3_bind_int(m_stmt, 2, userId); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res); + + // step + res = sqlite3_step(m_stmt); + TryCatchResLogReturn(res == SQLITE_DONE, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_step : %d", res); + + m_dbMutex.unlock(); + +#if 0 + // [CYNARA] Set Filter + cynara_monitor_configuration_set_filter(); +#endif + + return PRIV_FLTR_ERROR_SUCCESS; +} + +int +PrivacyGuardDb::PgGetMainMonitorPolicy(const int userId, bool &mainMonitorPolicy) +{ + + int res = -1; + static const std::string query = std::string("SELECT MAIN_MONITOR_POLICY FROM MainMonitorPolicy WHERE USER_ID=?"); + + m_dbMutex.lock(); + // open db + if(m_bDBOpen == false) { + openSqliteDB(); + } + TryCatchResLogReturn(m_bDBOpen == true, m_dbMutex.unlock(), PRIV_FLTR_ERROR_IO_ERROR, "openSqliteDB : %d", res); + + // prepare + res = sqlite3_prepare_v2(m_sqlHandler, query.c_str(), -1, &m_stmt, NULL); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_prepare_v2 : %d", res); + + // bind + res = sqlite3_bind_int(m_stmt, 1, userId); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res); + + // step + mainMonitorPolicy = false; + if ((res = sqlite3_step(m_stmt)) == SQLITE_ROW) { + mainMonitorPolicy = sqlite3_column_int(m_stmt, 0); + m_dbMutex.unlock(); + } + else { + m_dbMutex.unlock(); + res = PgAddMainMonitorPolicy(userId); + TryReturn(res == PRIV_FLTR_ERROR_SUCCESS, res, , "PgAddMainMonitorPolicy failed : %d", res); + } + + return PRIV_FLTR_ERROR_SUCCESS; +} + +int +PrivacyGuardDb::PgDeleteMainMonitorPolicyByUserId(const int userId) +{ + int res = -1; + + static const std::string QUERY_DELETE = std::string("DELETE FROM MainMonitorPolicy WHERE USER_ID=?"); + + m_dbMutex.lock(); + // open db + if(m_bDBOpen == false) { + openSqliteDB(); + } + TryCatchResLogReturn(m_bDBOpen == true, m_dbMutex.unlock(), PRIV_FLTR_ERROR_IO_ERROR, "openSqliteDB : %d", res); + + // prepare + res = sqlite3_prepare_v2(m_sqlHandler, QUERY_DELETE.c_str(), -1, &m_stmt, NULL); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_prepare_v2 : %d", res); + + // bind + res = sqlite3_bind_int(m_stmt, 1, userId); + TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res); + + // step + res = sqlite3_step(m_stmt); + TryCatchResLogReturn(res == SQLITE_DONE, m_dbMutex.unlock(), PRIV_FLTR_ERROR_DB_ERROR, "sqlite3_step : %d", res); + + m_dbMutex.unlock(); + + return PRIV_FLTR_ERROR_SUCCESS; +} + +PrivacyGuardDb::PrivacyGuardDb(void) +{ + + // open DB + m_bDBOpen = false; + m_sqlHandler = NULL; + m_dbMutex.lock(); + openSqliteDB(); + m_dbMutex.unlock(); + m_stmt = NULL; +} + +PrivacyGuardDb::~PrivacyGuardDb(void) +{ + // close DB + if(m_bDBOpen == true) { + m_dbMutex.lock(); + sqlite3_finalize(m_stmt); + sqlite3_close(m_sqlHandler); + m_bDBOpen = false; + m_dbMutex.unlock(); + } +} + +PrivacyGuardDb* +PrivacyGuardDb::getInstance(void) +{ + std::lock_guard < std::mutex > guard(m_singletonMutex); + + if (m_pInstance == NULL) + { + m_pInstance = new PrivacyGuardDb(); + } + + return m_pInstance; +} diff --git a/server/src/SocketService.cpp b/server/src/SocketService.cpp new file mode 100755 index 0000000..1173c60 --- /dev/null +++ b/server/src/SocketService.cpp @@ -0,0 +1,374 @@ +/* + * Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include "PrivacyGuardTypes.h" +#include "Utils.h" +#include "SocketService.h" +#include "SocketConnection.h" + +const int SocketService::MAX_LISTEN = 5; + +SocketService::SocketService(void) + : m_listenFd(-1) + , m_signalToClose(-1) + , m_mainThread(-1) +{ + +} + +SocketService::~SocketService(void) +{ + +} + +int +SocketService::initialize(void) +{ + LOGI("SocketService initializing"); + + m_listenFd = socket(AF_UNIX, SOCK_STREAM, 0); + TryReturn( m_listenFd != -1, PRIV_FLTR_ERROR_SYSTEM_ERROR, , "socket : %s", strerror(errno)); + + int flags = -1; + int res; + if ( (flags = fcntl(m_listenFd, F_GETFL, 0)) == -1) + flags = 0; + res = fcntl(m_listenFd, F_SETFL, flags | O_NONBLOCK); + TryReturn( res != -1, PRIV_FLTR_ERROR_SYSTEM_ERROR, , "fcntl : %s", strerror(errno)); + + sockaddr_un server_address; + bzero(&server_address, sizeof(server_address)); + server_address.sun_family = AF_UNIX; + strcpy(server_address.sun_path, SERVER_ADDRESS.c_str()); + unlink(server_address.sun_path); + + mode_t socket_umask, original_umask; + socket_umask = 0; + original_umask = umask(socket_umask); + + res = bind(m_listenFd, (struct sockaddr*)&server_address, SUN_LEN(&server_address)); + TryReturn( res != -1, PRIV_FLTR_ERROR_SYSTEM_ERROR, , "bind : %s", strerror(errno)); + + umask(original_umask); + + LOGI("SocketService initialized"); + + return PRIV_FLTR_ERROR_SUCCESS; +} + +int +SocketService::start(void) +{ + LOGI("SocketService starting"); + + sigset_t sigset; + sigemptyset(&sigset); +// if ( sigaddset(&sigset, m_signalToClose) == -1 ) +// { +// LOGE("Failed to sigaddset : %s", strerror(errno)); +// return -1; +// } + + int res = 0; + res = pthread_sigmask(SIG_BLOCK, &sigset, NULL); + TryReturn( res >= 0, PRIV_FLTR_ERROR_SYSTEM_ERROR, , "pthread_sigmask : %s", strerror(errno)); + + pthread_t mainThread; + res = pthread_create(&mainThread, NULL, &serverThread, this); + TryReturn( res >= 0, PRIV_FLTR_ERROR_SYSTEM_ERROR, errno = res, "pthread_create : %s", strerror(res)); + + m_mainThread = mainThread; + + LOGI("SocketService started"); + + return PRIV_FLTR_ERROR_SUCCESS; +} + +void* +SocketService::serverThread(void* pData) +{ + pthread_detach(pthread_self()); + SocketService &t = *static_cast< SocketService* > (pData); + LOGI("Running main thread"); + int ret = t.mainloop(); + if (ret < 0) + { + return (void*) 1; + } + return (void*) 0; +} + +int +SocketService::mainloop(void) +{ + if( listen(m_listenFd, MAX_LISTEN) == -1 ){ + LOGE("listen : %s", strerror(errno)); + return PRIV_FLTR_ERROR_IPC_ERROR; + } + + //Settings to catch closing signal in select + int signal_fd; + sigset_t sigset; + int res; + res = sigemptyset(&sigset); + TryReturn( res != -1, PRIV_FLTR_ERROR_SYSTEM_ERROR, , "sigemptyset : %s", strerror(errno)); + +// if( sigaddset(&sigset, m_signalToClose) == -1) { +// LOGE("sigaddset : %s", strerror(errno)); +// return -1; +// } + signal_fd = signalfd(-1, &sigset, 0); + TryReturn( signal_fd >= 0, PRIV_FLTR_ERROR_SYSTEM_ERROR, , "signalfd : %s", strerror(errno)); + + //Setting descriptors for pselect + fd_set allset, rset; + int maxfd; + FD_ZERO(&allset); + FD_SET(m_listenFd, &allset); + FD_SET(signal_fd, &allset); + maxfd = (m_listenFd > signal_fd) ? (m_listenFd) : (signal_fd); + ++maxfd; + //this will block SIGPIPE for this thread and every thread created in it + //reason : from here on we don't won't to receive SIGPIPE on writing to closed socket + //instead of signal we want to receive error from write - hence blocking SIGPIPE + sigset_t set; + sigemptyset(&set); + sigaddset(&set, SIGPIPE); + pthread_sigmask(SIG_BLOCK, &set, NULL); + + while(1) + { + rset = allset; + if(pselect(maxfd, &rset, NULL, NULL, NULL, NULL) == -1) + { + closeConnections(); + LOGE("pselect()"); + return PRIV_FLTR_ERROR_SYSTEM_ERROR; + } + + if(FD_ISSET(signal_fd, &rset)) + { + LOGI("Got signal to close"); + signalfd_siginfo siginfo; + ssize_t res; + res = read(signal_fd, &siginfo, sizeof(siginfo)); + TryReturn( res > 0, PRIV_FLTR_ERROR_IPC_ERROR, closeConnections();, "read : %s", strerror(errno)); + TryReturn( (size_t)res == sizeof(siginfo), PRIV_FLTR_ERROR_IPC_ERROR, closeConnections();, "couldn't read whole siginfo"); + + if((int)siginfo.ssi_signo == m_signalToClose) + { + LOGI("Server thread got signal to close"); + closeConnections(); + return PRIV_FLTR_ERROR_SUCCESS; + } + else + { + LOGI("Got not handled signal"); + } + } + if(FD_ISSET(m_listenFd, &rset)) + { + int clientFd; + clientFd = accept(m_listenFd, NULL, NULL); + TryReturn( clientFd != -1, PRIV_FLTR_ERROR_IPC_ERROR, closeConnections();, "accept : %s", strerror(errno)); + + LOGI("Got incoming connection"); + ConnectionInfo * connection = new ConnectionInfo(clientFd, (void *)this); + int res; + pthread_t client_thread; + if((res = pthread_create(&client_thread, NULL, &connectionThread, connection)) < 0) + { + delete connection; + errno = res; + closeConnections(); + LOGE("pthread_create()"); + return PRIV_FLTR_ERROR_SYSTEM_ERROR; + } + addClientSocket(clientFd); + } + } +} + +void* +SocketService::connectionThread(void* pData) +{ + pthread_detach(pthread_self()); + std::unique_ptr connectionInfo (static_cast(pData)); + SocketService &t = *static_cast(connectionInfo->pData); + LOGI("Starting connection thread"); + int ret = t.connectionService(connectionInfo->connFd); + if (ret < 0) + { + LOGE("Connection thread error"); + t.removeClientSocket(connectionInfo->connFd); + close(connectionInfo->connFd); + return (void*)1; + } + LOGI("Client serviced"); + return (void*)0; +} + +int +SocketService::connectionService(int fd) +{ + + SocketConnection connector = SocketConnection(fd); + std::string interfaceName, methodName; + + int res = connector.read(&interfaceName, &methodName); + if (res != PRIV_FLTR_ERROR_SUCCESS) + { + LOGE("read : %d", res); + return res; + } + + LOGD("Got interface : %s", interfaceName.c_str()); + LOGD("Got method : %s", methodName.c_str()); + + if( m_callbackMap.find(interfaceName) == m_callbackMap.end()) + { + LOGE("Unknown interface : %s", interfaceName.c_str()); + return PRIV_FLTR_ERROR_NO_DATA; + } + + if(m_callbackMap[interfaceName].find(methodName) == m_callbackMap[interfaceName].end()) + { + LOGE("Unknown method : %s", methodName.c_str()); + return PRIV_FLTR_ERROR_NO_DATA; + } + +// if(m_callbackMap[interfaceName][methodName]->securityCallback != NULL){ +// if(!m_callbackMap[interfaceName][methodName]->securityCallback(fd)){ +// LOGE("Security check returned false"); +// return -1; +// } +// } + + LOGI("Calling service"); + m_callbackMap[interfaceName][methodName]->serviceCallback(&connector); + + LOGI("Removing client"); + removeClientSocket(fd); + close(fd); + + LOGI("Call served"); + + return PRIV_FLTR_ERROR_SUCCESS; +} + +int +SocketService::stop(void) +{ + LOGI("Stopping"); + if(close(m_listenFd) == -1) + if(errno != ENOTCONN) + { + LOGE("close() : %s", strerror(errno)); + return PRIV_FLTR_ERROR_IPC_ERROR; + } + + int returned_value; + if((returned_value = pthread_kill(m_mainThread, m_signalToClose)) < 0) + { + errno = returned_value; + LOGE("pthread_kill() : %s", strerror(errno)); + return PRIV_FLTR_ERROR_IPC_ERROR; + } + pthread_join(m_mainThread, NULL); + + LOGI("Stopped"); + return PRIV_FLTR_ERROR_SUCCESS; +} + +int +SocketService::shutdown(void) +{ + return PRIV_FLTR_ERROR_SUCCESS; +} + +int +SocketService::registerServiceCallback(const std::string &interfaceName, const std::string &methodName, socketServiceCallback callbackMethod) +{ + if(NULL == callbackMethod) + { + LOGE("Null callback"); + return PRIV_FLTR_ERROR_INVALID_PARAMETER; + } + if(interfaceName.empty() || methodName.empty()) + { + LOGE("Interface and method name cannot be empty"); + return PRIV_FLTR_ERROR_INVALID_PARAMETER; + } + + auto serviceCallbackPtr = std::make_shared(ServiceCallback(callbackMethod)); + m_callbackMap[interfaceName][methodName] = serviceCallbackPtr; + + return PRIV_FLTR_ERROR_SUCCESS; +} + +void +SocketService::addClientSocket(int clientSocket) +{ + std::lock_guard guard(m_clientSocketListMutex); + m_clientSocketList.push_back(clientSocket); +} + +void +SocketService::removeClientSocket(int clientSocket) +{ + std::lock_guard guard(m_clientSocketListMutex); + m_clientSocketList.remove(clientSocket); +} + +bool +SocketService::popClientSocket(int * pClientSocket) +{ + std::lock_guard guard(m_clientSocketListMutex); + if(m_clientSocketList.empty()) + return false; + *pClientSocket = m_clientSocketList.front(); + m_clientSocketList.pop_front(); + return true; +} + + +void +SocketService::closeConnections(void) +{ + int clientSocket; + LOGI("Closing client sockets"); + while(popClientSocket(&clientSocket)) + { + if(close(clientSocket) == -1) + { + LOGE("close() : %s", strerror(errno)); + } + } + + LOGI("Connections closed"); +} diff --git a/server/src/main.cpp b/server/src/main.cpp new file mode 100755 index 0000000..528355b --- /dev/null +++ b/server/src/main.cpp @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include "PrivacyGuardDaemon.h" + +int +main(int argc, char* argv[]) +{ + PrivacyGuardDaemon* pDaemon = PrivacyGuardDaemon::getInstance(); + + pDaemon->initialize(); + pDaemon->start(); + + GMainLoop* pLoop; + pLoop = g_main_new(TRUE); + + g_main_loop_run(pLoop); + + pDaemon->stop(); + pDaemon->shutdown(); + + return 0; +} \ No newline at end of file diff --git a/server/src/privacy_guard_daemon.cpp b/server/src/privacy_guard_daemon.cpp new file mode 100755 index 0000000..892bfe1 --- /dev/null +++ b/server/src/privacy_guard_daemon.cpp @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved + * + * Licensed under the Apache License, Version 2.0 (the License); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an AS IS BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "privacy_guard_daemon.h" +#include "PrivacyGuardDaemon.h" + +int privacy_guard_daemon_initialize(void) +{ + PrivacyGuardDaemon* pPrivacyDaemon = PrivacyGuardDaemon::getInstance(); + + return pPrivacyDaemon->initialize(); +} + +int privacy_guard_daemon_start(void) +{ + PrivacyGuardDaemon* pInstance = PrivacyGuardDaemon::getInstance(); + + return pInstance->start(); +} + +int privacy_guard_daemon_stop(void) +{ + PrivacyGuardDaemon* pInstance = PrivacyGuardDaemon::getInstance(); + + return pInstance->stop(); +} + +int privacy_guard_daemon_shutdown(void) +{ + PrivacyGuardDaemon* pInstance = PrivacyGuardDaemon::getInstance(); + + return pInstance->shutdown(); +} diff --git a/server/src/service/PrivacyInfoService.cpp b/server/src/service/PrivacyInfoService.cpp new file mode 100755 index 0000000..e4d153d --- /dev/null +++ b/server/src/service/PrivacyInfoService.cpp @@ -0,0 +1,324 @@ +/* + * 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. + */ + +#include +#include "PrivacyInfoService.h" +#include "PrivacyGuardDb.h" +#include "Utils.h" + +void +PrivacyInfoService::PgAddPrivacyAccessLog(SocketConnection* pConnector) +{ + LOGI("PRIVACY PrivacyInfoService PgAddPrivacyAccessLog"); + + int userId = 0; + std::list > logInfoList; + + pConnector->read(&userId, &logInfoList); + PF_LOGD("PrivacyInfoService PgAddPrivacyAccessLog userId : %d", userId); + + int result = PrivacyGuardDb::getInstance()->PgAddPrivacyAccessLog(userId, logInfoList); + + pConnector->write(result); +} + +void +PrivacyInfoService::PgAddPrivacyAccessLogTest(SocketConnection* pConnector) +{ + LOGI("PRIVACY PrivacyInfoService PgAddPrivacyAccessLogTest"); + + int userId = 0; + std::string packageId; + std::string privacyId; + + pConnector->read(&userId, &packageId, &privacyId); + PF_LOGD("PrivacyInfoService PgAddPrivacyAccessLogTest userId : %d", userId); + + int result = PrivacyGuardDb::getInstance()->PgAddPrivacyAccessLogTest(userId, packageId, privacyId); + + pConnector->write(result); +} + +void +PrivacyInfoService::PgAddMonitorPolicy(SocketConnection* pConnector) +{ + int userId = 0; + std::string pkgId; + std::list < std::string > list; + bool privacyPopupRequired = true; + pConnector->read(&userId, &pkgId, &list, &privacyPopupRequired); + + int result = PrivacyGuardDb::getInstance()->PgAddMonitorPolicy(userId, pkgId, list, privacyPopupRequired); + + pConnector->write(result); +} + +void +PrivacyInfoService::PgDeleteAllLogsAndMonitorPolicy(SocketConnection* pConnector) +{ + int result = PrivacyGuardDb::getInstance()->PgDeleteAllLogsAndMonitorPolicy(); + + pConnector->write(result); +} + +void +PrivacyInfoService::PgDeleteLogsByPackageId(SocketConnection* pConnector) +{ + std::string packageId; + pConnector->read(&packageId); + + int result = PrivacyGuardDb::getInstance()->PgDeleteLogsByPackageId(packageId); + + pConnector->write(result); +} + +void +PrivacyInfoService::PgDeleteMonitorPolicyByPackageId(SocketConnection* pConnector) +{ + std::string packageId; + pConnector->read(&packageId); + + int result = PrivacyGuardDb::getInstance()->PgDeleteMonitorPolicyByPackageId(packageId); + + pConnector->write(result); +} + +void +PrivacyInfoService::PgForeachTotalPrivacyCountOfPackage(SocketConnection* pConnector) +{ + int userId = 0; + int startDate = -1; + int endDate = -1; + std::list < std::pair < std::string, int > > packageInfoList; + pConnector->read(&userId, &startDate, &endDate); + + PF_LOGD("requested > userId : %d, startDate : %d, endDate : %d", userId, startDate, endDate); + int result = PrivacyGuardDb::getInstance()->PgForeachTotalPrivacyCountOfPackage(userId, startDate, endDate, packageInfoList); + PF_LOGD("response > packageInfoList size : %d", packageInfoList.size()); + + pConnector->write(result); + pConnector->write(packageInfoList); +} + +void +PrivacyInfoService::PgForeachTotalPrivacyCountOfPrivacy(SocketConnection* pConnector) +{ + int userId = 0; + int startDate = -1; + int endDate = -1; + std::list < std::pair < std::string, int > > privacyInfoList; + pConnector->read(&userId, &startDate, &endDate); + + PF_LOGD("requested > startDate : %d, endDate : %d", startDate, endDate); + int result = PrivacyGuardDb::getInstance()->PgForeachTotalPrivacyCountOfPrivacy(userId, startDate, endDate, privacyInfoList); + PF_LOGD("response > privacyInfoList size : %d", privacyInfoList.size()); + + pConnector->write(result); + pConnector->write(privacyInfoList); +} + +void +PrivacyInfoService::PgForeachPrivacyCountByPrivacyId(SocketConnection* pConnector) +{ + int userId = 0; + int startDate = -1; + int endDate = -1; + std::string privacyId; + std::list < std::pair < std::string, int > > packageInfoList; + pConnector->read(&userId, &startDate, &endDate, &privacyId); + + PF_LOGD("requested > startDate : %d, endDate : %d, privacyId : %s", + startDate, endDate, privacyId.c_str()); + int result = PrivacyGuardDb::getInstance()->PgForeachPrivacyCountByPrivacyId(userId, startDate, endDate, + privacyId, packageInfoList); + PF_LOGD("response > packageInfoList size : %d", packageInfoList.size()); + + pConnector->write(result); + pConnector->write(packageInfoList); +} + +void +PrivacyInfoService::PgForeachPrivacyCountByPackageId(SocketConnection* pConnector) +{ + int userId = 0; + int startDate = -1; + int endDate = -1; + std::string packageId; + std::list < std::pair < std::string, int > > privacyInfoList; + pConnector->read(&userId, &startDate, &endDate, &packageId); + + PF_LOGD("requested > startDate : %d, endDate : %d, packageId : %s", + startDate, endDate, packageId.c_str()); + int result = PrivacyGuardDb::getInstance()->PgForeachPrivacyCountByPackageId(userId, startDate, endDate, + packageId, privacyInfoList); + PF_LOGD("response > privacyInfoList size : %d", privacyInfoList.size()); + + pConnector->write(result); + pConnector->write(privacyInfoList); +} + +void +PrivacyInfoService::PgForeachPrivacyPackageId(SocketConnection* pConnector) +{ + int userId = 0; + std::list < std::string > packageList; + + pConnector->read(&userId); + PF_LOGD("requested > userId : %d", userId); + + int result = PrivacyGuardDb::getInstance()->PgForeachPrivacyPackageId(userId, packageList); + PF_LOGD("response > packageList size : %d", packageList.size()); + + pConnector->write(result); + pConnector->write(packageList); +} + +void +PrivacyInfoService::PgForeachMonitorPolicyByPackageId(SocketConnection* pConnector) +{ + int userId = 0; + std::string packageId; + pConnector->read(&userId, &packageId); + + std::list privacyInfoList; + int result = -1; + result = PrivacyGuardDb::getInstance()->PgForeachMonitorPolicyByPackageId(userId, packageId, privacyInfoList); + + PF_LOGD("response > privacyInfoList size : %d", privacyInfoList.size()); + + pConnector->write(result); + pConnector->write(privacyInfoList); +} + +void +PrivacyInfoService::PgGetMonitorPolicy(SocketConnection* pConnector) +{ + int userId = 0; + std::string packageId; + std::string privacyId; + pConnector->read(&userId, &packageId, &privacyId); + + PF_LOGD("requested > packageId : %s, privacyId : %s", packageId.c_str(), privacyId.c_str()); + int monitorPolicy = 1; + int result = -1; + result = PrivacyGuardDb::getInstance()->PgGetMonitorPolicy(userId, packageId, privacyId, monitorPolicy); + + PF_LOGD("response > monitorPolicy : %d", monitorPolicy); + + pConnector->write(result); + pConnector->write(monitorPolicy); +} + +void +PrivacyInfoService::PgGetAllMonitorPolicy(SocketConnection* pConnector) +{ + std::list < std::pair < std::string, int > > monitorPolicyList; + + int result = PrivacyGuardDb::getInstance()->PgGetAllMonitorPolicy(monitorPolicyList); + + pConnector->write(result); + pConnector->write(monitorPolicyList); +} + +void +PrivacyInfoService::PgForeachPackageByPrivacyId(SocketConnection* pConnector) +{ + int userId = 0; + std::string privacyId; + std::list < std::string > packageList; + + pConnector->read(&userId, &privacyId); + PF_LOGD("requested > userId : %d, privacyId : %s", userId, privacyId.c_str()); + + int result = PrivacyGuardDb::getInstance()->PgForeachPackageByPrivacyId(userId, privacyId, packageList); + PF_LOGD("response > packageList size : %d", packageList.size()); + + pConnector->write(result); + pConnector->write(packageList); +} + +void +PrivacyInfoService::PgCheckPrivacyPackage(SocketConnection* pConnector) +{ + int userId = 0; + std::string packageId; + bool isPrivacyPackage = false; + pConnector->read(&userId, &packageId); + + PF_LOGD("requested > packageId : %s", packageId.c_str()); + int result = PrivacyGuardDb::getInstance()->PgCheckPrivacyPackage(userId, packageId, isPrivacyPackage); + + pConnector->write(result); + pConnector->write(isPrivacyPackage); +} + +void +PrivacyInfoService::PgUpdateMonitorPolicy(SocketConnection* pConnector) +{ + int userId = 0; + std::string packageId; + std::string privacyId; + int monitorPolicy = 1; + pConnector->read(&userId, &packageId, &privacyId, &monitorPolicy); + + PF_LOGD("requested > packageId : %s, privacyId : %s, monitorPolicy : %d", + packageId.c_str(), privacyId.c_str(), monitorPolicy); + int result = PrivacyGuardDb::getInstance()->PgUpdateMonitorPolicy(userId, packageId, privacyId, monitorPolicy); + + pConnector->write(result); +} + +void +PrivacyInfoService::PgUpdateMainMonitorPolicy(SocketConnection* pConnector) +{ + int userId = 0; + bool mainMonitorPolicy = false; + pConnector->read(&userId, &mainMonitorPolicy); + + PF_LOGD("requested > mainMonitorPolicy : %d", mainMonitorPolicy); + int result = PrivacyGuardDb::getInstance()->PgUpdateMainMonitorPolicy(userId, mainMonitorPolicy); + + pConnector->write(result); +} + +void +PrivacyInfoService::PgGetMainMonitorPolicy(SocketConnection* pConnector) +{ + int userId = 0; + pConnector->read(&userId); + + PF_LOGD("PgGetMainMonitorPolicy userId : %d", userId); + + bool mainMonitorPolicy = false; + int result = -1; + result = PrivacyGuardDb::getInstance()->PgGetMainMonitorPolicy(userId, mainMonitorPolicy); + + PF_LOGD("response > mainMonitorPolicy : %d", mainMonitorPolicy); + + pConnector->write(result); + pConnector->write(mainMonitorPolicy); +} + +void +PrivacyInfoService::PgDeleteMainMonitorPolicyByUserId(SocketConnection* pConnector) +{ + int userId = 0; + pConnector->read(&userId); + + int result = PrivacyGuardDb::getInstance()->PgDeleteMainMonitorPolicyByUserId(userId); + + pConnector->write(result); +}