Separate privacy-guard-client in 2 packages (client and settings) + checkstyle fixes 01/176501/4 accepted/tizen/unified/20180426.145833 submit/tizen/20180424.100801
authorSaulo Moraes <s.moraes@samsung.com>
Thu, 19 Apr 2018 19:17:36 +0000 (16:17 -0300)
committerSaulo Aldighieri Moraes <s.moraes@samsung.com>
Fri, 20 Apr 2018 13:01:25 +0000 (10:01 -0300)
Change-Id: Ic105fcdfcd1d2c0ca1e078d7101329c4ba32323b

79 files changed:
CMakeLists.txt [changed mode: 0755->0644]
CONTRIBUTORS [new file with mode: 0644]
ahocorasick/ahocorasick.h
ahocorasick/node.c
ahocorasick/node.h
ahocorasick/types.h
client/CMakeLists.txt
client/inc/DlpLogsManager.h
client/inc/DlpPacketParser.h
client/inc/DlpRulesManager.h
client/inc/PrivacyChecker.h [deleted file]
client/inc/PrivacyGuardDlp.h [new file with mode: 0644]
client/src/DlpLogsManager.cpp
client/src/DlpRulesManager.cpp
client/src/PrivacyChecker.cpp [deleted file]
client/src/PrivacyGuardDlp.cpp [new file with mode: 0644]
client/src/privacy_guard_dlp.cpp
common/inc/DlpPacketParserResult.h [moved from client/inc/DlpPacketParserResult.h with 100% similarity]
common/inc/IPrivacyGuard.h [changed mode: 0755->0644]
common/inc/PrivacyGuardCommon.h [changed mode: 0755->0644]
common/inc/PrivacyGuardTypes.h
common/inc/PrivacyIdInfo.h [changed mode: 0755->0644]
common/inc/SocketClient.h [moved from client/inc/SocketClient.h with 99% similarity, mode: 0644]
common/inc/SocketConnection.h
common/inc/SocketStream.h [changed mode: 0755->0644]
common/inc/Utils.h
common/inc/privacy_guard_utils.h
common/src/DlpUtils.cpp
common/src/PrivacyIdInfo.cpp [changed mode: 0755->0644]
common/src/SocketClient.cpp [moved from client/src/SocketClient.cpp with 97% similarity, mode: 0644]
common/src/SocketConnection.cpp [changed mode: 0755->0644]
common/src/SocketStream.cpp [changed mode: 0755->0644]
common/src/Utils.cpp [changed mode: 0755->0644]
include/CMakeLists.txt [changed mode: 0755->0644]
include/privacy_guard_client.h
packaging/libprivacy-guard-client.manifest [changed mode: 0755->0644]
packaging/libprivacy-guard-setting.manifest [new file with mode: 0644]
packaging/privacy-guard-client-devel.manifest [changed mode: 0755->0644]
packaging/privacy-guard-client.manifest [changed mode: 0755->0644]
packaging/privacy-guard-server-devel.manifest [changed mode: 0755->0644]
packaging/privacy-guard-server.manifest [changed mode: 0755->0644]
packaging/privacy-guard-server.service [changed mode: 0755->0644]
packaging/privacy-guard-server.socket [changed mode: 0755->0644]
packaging/privacy-guard-setting-devel.manifest [new file with mode: 0644]
packaging/privacy-guard-setting.manifest [new file with mode: 0644]
packaging/privacy-guard.changes [changed mode: 0755->0644]
packaging/privacy-guard.spec [changed mode: 0755->0644]
pkgmgr_plugin/CMakeLists.txt [changed mode: 0755->0644]
pkgmgr_plugin/privileges.cpp [changed mode: 0755->0644]
privacy-guard-setting.pc.in [new file with mode: 0644]
res/etc/rc.d/init.d/privacy-guard-server.sh [changed mode: 0755->0644]
server/CMakeLists.txt
server/inc/CynaraService.h [changed mode: 0755->0644]
server/inc/DlpPrivacyInfoData.h
server/inc/DlpRuleChangeNotification.h
server/inc/ICommonDb.h [changed mode: 0755->0644]
server/inc/PrivacyGuardDaemon.h [changed mode: 0755->0644]
server/inc/PrivacyGuardDb.h
server/inc/PrivacyInfoService.h
server/inc/SocketService.h [changed mode: 0755->0644]
server/inc/privacy_guard_daemon.h [changed mode: 0755->0644]
server/src/CynaraService.cpp [changed mode: 0755->0644]
server/src/DlpRuleChangeNotification.cpp
server/src/PrivacyGuardDaemon.cpp [changed mode: 0755->0644]
server/src/PrivacyGuardDb.cpp
server/src/SocketService.cpp [changed mode: 0755->0644]
server/src/main.cpp [changed mode: 0755->0644]
server/src/privacy_guard_daemon.cpp [changed mode: 0755->0644]
server/src/service/DlpPrivacyInfoData.cpp
server/src/service/PrivacyInfoService.cpp [changed mode: 0755->0644]
setting/CMakeLists.txt [new file with mode: 0755]
setting/inc/PrivacyGuardClient.h [moved from client/inc/PrivacyGuardClient.h with 91% similarity]
setting/inc/privacy_guard_client_internal.h [moved from client/inc/privacy_guard_client_internal.h with 98% similarity]
setting/src/PrivacyGuardClient.cpp [moved from client/src/PrivacyGuardClient.cpp with 92% similarity]
setting/src/privacy_guard_client.cpp [moved from client/src/privacy_guard_client.cpp with 99% similarity]
setting/src/privacy_guard_client_internal_types.h [moved from client/src/privacy_guard_client_internal_types.h with 96% similarity, mode: 0644]
test/CMakeLists.txt
test/tc-ahocorasick.c [new file with mode: 0644]
test/tc-dlp-performance.c

old mode 100755 (executable)
new mode 100644 (file)
index 1b2672f..e93feb2
@@ -15,6 +15,7 @@ STRING(REGEX MATCH "([^.]*)" API_VERSION "${VERSION}")
 ADD_DEFINITIONS("-DAPI_VERSION=\"$(API_VERSION)\"")
 
 ADD_SUBDIRECTORY(server)
+ADD_SUBDIRECTORY(setting)
 ADD_SUBDIRECTORY(client)
 ADD_SUBDIRECTORY(pkgmgr_plugin)
 ADD_SUBDIRECTORY(test)
\ No newline at end of file
diff --git a/CONTRIBUTORS b/CONTRIBUTORS
new file mode 100644 (file)
index 0000000..97d7c58
--- /dev/null
@@ -0,0 +1,17 @@
+# This file contains a list of people who've made non-trivial contribution
+# to the Privacy Setting project. People who commit code to the project are
+# encouraged to add their names here. Please keep the list sorted by first
+# names.
+
+Bartlomiej Grzelewski <b.grzelewski@samsung.com>
+Eduardo Iyoda <emi@cesar.org.br>
+Fabio Urquiza <flus@cesar.org.br>
+Gabriel Finch <gf@cesar.org.br>
+Jooseong Lee <jooseong.lee@samsung.com>
+Jungkon Kim <jungkon.kim@samsung.com>
+Kim Kidong <kd0228.kim@samsung.com>
+Kyoungyong Lee <k.y.lee@samsung.com>
+MyungJoo Ham <myungjoo.ham@samsung.com>
+Saulo Moraes <s.moraes@samsung.com>
+Seonil Kim <seonil47.kim@samsung.com>
+Yunjin Lee <yunjin-.lee@samsung.com>
index bceaafe..62d03e8 100644 (file)
@@ -37,19 +37,19 @@ extern "C" {
 EXTERN_API ac_instance *ahocorasick_init(void);
 
 /**
- * @fn                                         int ahocorasick_add_string(ac_instance *ac, const char *string, void *user_data)
+ * @fn                                 int ahocorasick_add_string(ac_instance *ac, const char *string, void *user_data)
  * @brief                              Add another string to the list for matching *
  * @param[in] ac               An instance returned from ahocorasick_init()
  * @param[in] string   The string to add
  * @param[in] user_data        User data to associate with any resulting matches
- * @return                             Count of total strings added
+ * @return                             Count of total strings added
  * @callgraph
  */
 EXTERN_API int ahocorasick_add_string(ac_instance *ac, const char *string, void *user_data);
 
 /**
  * @fn                                 void ahocorasick_set_text(ac_instance *ac, const char *text, size_t textlen, int cont)
- * @brief                              Set the text to be scanned for matches
+ * @brief                              Set the text to be scanned for matches
  * @param[in] ac               An instance returned from ahocorasick_init()
  * @param[in] text             The text to be scanned
  * @param[in] textlen   The length of the text to be scanned, in bytes
@@ -62,14 +62,14 @@ EXTERN_API void ahocorasick_set_text(ac_instance *ac, const char *text, size_t t
  * @fn                                 ac_match *ahocorasick_find_next(ac_instance *ac)
  * @brief                              Find the next match in the text
  * @param[in] ac        An instance returned from ahocorasick_init()
- * @return                             The next match in the text, or NULL. Matches are returned
- *                                             in the order in which they end in the text, in alphanumeric order.
+ * @return                             The next match in the text, or NULL. Matches are returned
+ *                                             in the order in which they end in the text, in alphanumeric order.
  * @callgraph
  */
 EXTERN_API ac_match *ahocorasick_find_next(ac_instance *ac);
 
 /**
- * @fn                                         oid ahocorasick_free(ac_instance *ac);
+ * @fn                                 oid ahocorasick_free(ac_instance *ac);
  * @brief                              Free an ahocorasick instance
  * @param[in] ac        An instance returned from ahocorasick_init()
  * @callgraph
index 1b2dd9e..ab4c00c 100644 (file)
 /**
    Create a new node using the given rule id and text string
  */
-static ac_node *new_node(void *user_data, const char *text)
+static ac_node *new_node_strlen(void *user_data, const char *text, size_t textlen)
 {
        ac_node *node = (ac_node *)malloc(sizeof(ac_node));
        memset(node, 0, sizeof(ac_node));
-       node->branch = strdup(text);
+       if (textlen > 0) {
+               node->branch = (char *)malloc(textlen);
+               memcpy(node->branch, text, textlen);
+               node->brlen = (int)textlen;
+       }
        node->user_data = user_data;
-       node->is_match = TRUE;
+       node->checked = FALSE;
+       node->terminal = TRUE;
        return node;
 }
 
+static ac_node *new_node(void *user_data, const char *text)
+{
+       return new_node_strlen(user_data, text, strlen(text));
+}
+
 /**
    Append child (leaf) node to parent at position idx
  */
@@ -47,7 +57,6 @@ static void add_child(ac_node *parent, int idx, ac_node *child)
 {
 
        int nleaves = 2;
-       int i;
        ac_node **old_leaves = parent->leaves;
        if (parent->leaves != NULL) {
                while (parent->leaves[nleaves - 2] != NULL)
@@ -55,6 +64,7 @@ static void add_child(ac_node *parent, int idx, ac_node *child)
        }
        parent->leaves = (ac_node **)malloc(nleaves * sizeof(ac_node *));
        if (parent->leaves != NULL) {
+               int i;
                for (i = 0; i < nleaves - 1; i++) {
                        if (i < idx)
                                parent->leaves[i] = old_leaves[i];
@@ -72,48 +82,37 @@ static void add_child(ac_node *parent, int idx, ac_node *child)
 /**
        Compare string s1 with string s2
        return value:
-        0                              => s1 before s2
-        -1                     => s1 after s2
-        other values   => Number of initial letters in common
+       0                               => s1 before s2
+       -1                              => s1 after s2
+       other values    => Number of initial letters in common
+#ifdef CASE_INSENSITIVE
+       case conversion (tolower) should be done before calling compare()
+#endif
 */
-static int compare(const char *s1, const char *s2)
+static int compare(const char *s1, size_t s1len, const char *s2, size_t s2len)
 {
        int i;
-       size_t commonlen, s2len;
-
-       if (strlen(s1) == 0)
-               return 0;
+       size_t commonlen;
 
-       if (strlen(s2) == 0)
-               return -1;
-
-#ifdef CASE_INSENSITIVE
-       if (tolower(s1[0]) < tolower(s2[0]))
+       if (s1len == 0)
                return 0;
 
-       if (tolower(s2[0]) < tolower(s1[0]))
+       if (s2len == 0)
                return -1;
 
-#else
        if (s1[0] < s2[0])
                return 0;
 
        if (s2[0] < s1[0])
                return -1;
 
-#endif
-       commonlen = strlen(s1);
-       if ((s2len = strlen(s2)) < commonlen)
+       commonlen = s1len;
+       if (s2len < commonlen)
                commonlen = s2len;
 
        for (i = 1; i < commonlen; i++) {
-#ifdef CASE_INSENSITIVE
-               if (tolower(s1[i]) != tolower(s2[i]))
-                       return i;
-#else
                if (s1[i] != s2[i])
                        return i;
-#endif
        }
        return commonlen;
 }
@@ -125,7 +124,7 @@ static ac_match *create_match(void *user_data, int pos, int size)
 {
        ac_match *match = (ac_match *)malloc(sizeof(ac_match));
 
-       if(match) {
+       if (match) {
                match->user_data = user_data;
                match->position = pos;
                match->size = size;
@@ -165,7 +164,6 @@ static void ancestors_decrement_sposns(ac_node *node, int count)
 static void add_sposn(ac_node *node, int offs)
 {
        int *old_sposns = node->sposns;
-       int i;
 
        /* do not add same position twice */
        if (node->nsposns > 0 && node->sposns[0] == offs)
@@ -174,9 +172,10 @@ static void add_sposn(ac_node *node, int offs)
        node->nsposns++;
        node->sposns = (int *)malloc(node->nsposns * sizeof(int));
 
-       if(node->sposns) {
+       if (node->sposns) {
                node->sposns[0] = offs;
 
+               int i;
                for (i = 1; i < node->nsposns; i++)
                        node->sposns[i] = old_sposns[i - 1];
        }
@@ -194,7 +193,7 @@ static void clean_bad_sposns(ac_node *node)
 {
        int *old_sposns = node->sposns;
        int nbad = 0;
-       int i, j = 0;
+       int i;
 
        for (i = 0; i < node->nsposns; i++) {
                if (node->sposns[i] == -1)
@@ -212,6 +211,7 @@ static void clean_bad_sposns(ac_node *node)
        } else {
                node->sposns = (int *)malloc(node->nsposns * sizeof(int));
 
+               int j = 0;
                for (i = 0; i < node->nsposns; i++) {
                        while (old_sposns[j] == -1)
                                j++;
@@ -227,23 +227,47 @@ static void clean_bad_sposns(ac_node *node)
 */
 static int get_totlen(ac_node *node)
 {
-       size_t len = strlen(node->branch);
-       while (node->stem != NULL) {
-               node = node->stem;
-               len += strlen(node->branch);
-       }
-       return (int)len;
+       int len = node->brlen;
+       if (node->stem != NULL)
+               len += get_totlen(node->stem);
+       return len;
+}
+
+#ifdef CASE_INSENSITIVE
+/**
+   convert string to all lower case. Result should be freed after use.
+*/
+static char *string_tolower(const char *string, size_t len)
+{
+       int i;
+       char *tl_string = (char *)malloc(len + 1);
+       if (!tl_string) return NULL;
+       for (i = 0; i < len; i++)
+               tl_string[i] = (char)tolower(string[i]);
+       tl_string[len] = 0;
+       return tl_string;
 }
+#endif
 
 void add_node(ac_instance *ac, const char *string, void *user_data)
 {
-       char *ptr = (char *)string;
+       char *ptr, *tmpptr;
+       size_t stlen = strlen(string);
        ac_node *node = ac->root, *xnode;
-       int finished = 0;
+       boolean finished = FALSE;
        int res;
        int i = 0;
 
+#ifdef CASE_INSENSITIVE
+       char *xstring = string_tolower(string, stlen);
+       if (xstring == NULL) return;
+       ptr = xstring;
+#else
+       ptr = (char *)string;
+#endif
+
        while (!finished) {
+               boolean override_finished = FALSE;
                if (node != NULL && node->leaves != NULL) {
                        /* starting with the root node, we look at each leaf in turn */
                        for (i = 0; (xnode = node->leaves[i]) != NULL; i++) {
@@ -254,7 +278,7 @@ void add_node(ac_instance *ac, const char *string, void *user_data)
                                 *  - if common is l.t branch, common part becomes node, and branch and node become children
                                 * c) xnode->branch > text, insert node before xnode */
 
-                               res = compare(xnode->branch, ptr);
+                               res = compare(xnode->branch, xnode->brlen, ptr, stlen);
 
                                if (res == 0)
                                        /* xnode before new node */
@@ -268,26 +292,34 @@ void add_node(ac_instance *ac, const char *string, void *user_data)
                                } else {
                                        ac_node *child1;
                                        /* res letters were in common */
-                                       if (res == strlen(xnode->branch)) {
+                                       node = xnode; // consider only this child node
+                                       if (res == node->brlen) {
                                                /* all letters in common, so now we check the leaves */
-                                               node = xnode;
                                                ptr += res;
-                                               if (strlen(ptr) == 0) {
+                                               stlen = strlen(ptr);
+                                               if (stlen == 0) {
                                                        /* duplicate string */
                                                        node->user_data = user_data;
-                                                       node->is_match = TRUE;
+                                                       node->terminal = TRUE;
+#ifdef CASE_INSENSITIVE
+                                                       free(xstring);
+#endif
                                                        return;
                                                }
                                                /* leave for() loop and continue in while (!finished) */
-                                               i = 0;
+                                               if (node->leaves != NULL) {
+                                                       // if it also has child leaves, override setting of finished
+                                                       override_finished = TRUE;
+                                               } else i = 0; // otherwise add us as the first child
                                                break;
                                        }
                                        /* the common part was l.t. all
                                         * the common part becomes the new node
                                         * we add both this node with all its children and the new node as children */
-                                       child1 = new_node(xnode->user_data, (const char *)(xnode->branch + res));
+                                       child1 = new_node_strlen(xnode->user_data, (const char *)(xnode->branch + res), xnode->brlen - res);
                                        child1->leaves = xnode->leaves;
                                        child1->stem = xnode;
+                                       child1->terminal = xnode->terminal;
                                        if (child1->leaves != NULL) {
                                                for (i = 0; (node = child1->leaves[i]) != NULL; i++) {
                                                        /* adjust stems for each of these */
@@ -295,44 +327,52 @@ void add_node(ac_instance *ac, const char *string, void *user_data)
                                                }
                                        }
                                        /* remove xnodes leaves and shorten its text */
-                                       memset(xnode->branch + res, 0, 1);
+                                       tmpptr = (char *)malloc(res);
+                                       memcpy(tmpptr, xnode->branch, res);
+                                       free(xnode->branch);
+                                       xnode->branch = tmpptr;
+                                       xnode->brlen = res;
 
-                                       if (strlen(ptr) > res) {
+                                       if (stlen > res) {
                                                ac_node *child2;
                                                /* remainder of new string is added as child2 */
-                                               xnode->is_match = FALSE;
+                                               xnode->terminal = FALSE;
                                                xnode->leaves = (ac_node **)malloc(3 * sizeof(ac_node *));
                                                if (xnode->leaves != NULL) {
-                                                 child2 = new_node(user_data, (const char *)(ptr + res));
-                                                 ac->added++;
-                                                 child2->stem = xnode;
-
-                                                 res = compare(child1->branch, child2->branch);
-                                                 if (res == 0) {
-                                                       /* child1 before child2 */
-                                                       xnode->leaves[0] = child1;
-                                                       xnode->leaves[1] = child2;
-                                                 } else {
-                                                       /* child1 before child2 */
-                                                       xnode->leaves[0] = child2;
-                                                       xnode->leaves[1] = child1;
-                                                 }
-                                                 xnode->leaves[2] = NULL;
+                                                       child2 = new_node(user_data, (const char *)(ptr + res));
+                                                       ac->added++;
+                                                       child2->stem = xnode;
+
+                                                       res = compare(child1->branch, child1->brlen, child2->branch, child2->brlen);
+                                                       if (res == 0) {
+                                                               /* child1 before child2 */
+                                                               xnode->leaves[0] = child1;
+                                                               xnode->leaves[1] = child2;
+                                                       } else {
+                                                               /* child1 before child2 */
+                                                               xnode->leaves[0] = child2;
+                                                               xnode->leaves[1] = child1;
+                                                       }
+                                                       xnode->leaves[2] = NULL;
                                                }
                                        } else {
                                                /* the common part consumed all of new string, so we only have 1 child to add */
+                                               xnode->terminal = TRUE;
                                                xnode->leaves = (ac_node **)malloc(2 * sizeof(ac_node *));
                                                if (xnode->leaves != NULL) {
-                                                 xnode->user_data = user_data;
-                                                 xnode->leaves[0] = child1;
-                                                 xnode->leaves[1] = NULL;
+                                                       xnode->user_data = user_data;
+                                                       xnode->leaves[0] = child1;
+                                                       xnode->leaves[1] = NULL;
                                                }
                                        }
                                }
+#ifdef CASE_INSENSITIVE
+                               free(xstring);
+#endif
                                return;
                        }
                }
-               finished = 1;
+               if (!override_finished) finished = TRUE;
        }
 
        /* we checked all children and none were after ptr */
@@ -341,110 +381,112 @@ void add_node(ac_instance *ac, const char *string, void *user_data)
        if (ac->root == NULL) {
                /* new root - make a root node and add us as a leaf */
                node = ac->root = new_node(NULL, "");
-               ac->root->is_match = FALSE;
+               ac->root->terminal = FALSE;
        }
        add_child(node, i, xnode);
+#ifdef CASE_INSENSITIVE
+       free(xstring);
+#endif
 }
 
 /**
  * @callgraph
  */
-ac_match *parse_char(char ch, int offs, ac_node *node)
+static ac_match *parse_char_with_case(unsigned char ch, int offs, ac_node *node)
 {
        ac_match *acm = NULL;
        ac_node *xnode;
-       size_t brlen;
-       int child_sposns = 0;
-       int i, j;
+       int i;
 
-       if (node->checked)
-               return NULL;
+       if (!node || node->checked) return NULL;
 
-       brlen = strlen(node->branch);
-       if (brlen > 0) {
-#ifdef CASE_INSENSITIVE
-               if (node->stem->stem == NULL && tolower(node->branch[0]) == tolower(ch)) {
-                       /* leaf of root node, and first char matched, start a new sposn */
-                       add_sposn(node, offs);
+       if (node->leaves != NULL && (node->brlen == 0 || node->child_sposns != 0)) {
+               /* starting from the root, we look at each unchecked child in turn and check (recursively) for matches
+                * (skip if there are no child_sposns, to avoid parsing the whole tree) */
+               for (i = 0; (xnode = node->leaves[i]) != NULL && !xnode->checked; i++) {
+                       if (node->brlen == 0 || xnode->nsposns > 0 || xnode->child_sposns > 0) {
+                               acm = parse_char_with_case(ch, offs, xnode);
+                               if (acm != NULL)
+                                       return acm;
+                       }
                }
-#else
-               if (node->stem->stem == NULL && node->branch[0] == ch) {
+       }
+
+       /* after checking the child nodes, we look at the node itself */
+
+       if (node->brlen > 0) {
+               /* the cast is just to prevent SVACE warnings, as long as both types are the same it does not matter */
+               if (node->stem->stem == NULL && (unsigned char)node->branch[0] == ch) {
                        /* leaf of root node, and first char matched, start a new sposn */
                        add_sposn(node, offs);
                }
-#endif
+
                if (node->nsposns > 0) {
+                       int child_sposns = 0;
                        /* first check the ongoing matches in sposns */
                        for (i = 0; i < node->nsposns; i++) {
-                               if (node->sposns[i] > offs)
-                                       continue;
-
-#ifdef CASE_INSENSITIVE
-                               if (tolower(node->branch[offs - node->sposns[i]]) != tolower(ch)) {
-                                       /* mark for removal */
-                                       node->sposns[i] = -1;
-                               } else {
-#else
-                               if (node->branch[offs - node->sposns[i]] != ch) {
-                                       /* mark for removal */
+                               int sposn = node->sposns[i];
+                               /* the cast is just to prevent SVACE warnings, as long as both types are the same it does not matter */
+                               if ((unsigned char)node->branch[offs - sposn] != ch) {
+                                       /* mismatch, mark for removal */
                                        node->sposns[i] = -1;
-                               } else {
-#endif
-                                       /* continuing match */
-                                       if (offs - node->sposns[i] == brlen - 1) {
-                                               /* the entirety of this branch was matched */
-                                               if (node->leaves == NULL || node->is_match) {
-                                                       /* we got a match ! */
-                                                       int totlen = get_totlen(node);
-                                                       acm = create_match(node->user_data, node->sposns[i] - totlen + brlen, totlen);
+                               } else if (offs - sposn == node->brlen - 1) {
+                                       /* the entirety of this branch was matched */
+                                       if (node->terminal) {
+                                               /* we got a match ! */
+                                               int totlen = get_totlen(node);
+                                               if (acm == NULL) {
+                                                       // since the values of node->sposns[] are unique, acm should always be NULL
+                                                       // the check is added to prevent SVACE warnings
+                                                       acm = create_match(node->user_data, sposn - totlen + node->brlen, totlen);
                                                }
-                                               if (node->leaves != NULL) {
-                                                       /* otherwise place possible matches at next char for all children */
-                                                       for (j = 0; (xnode = node->leaves[j]) != NULL; j++) {
-                                                               add_sposn(xnode, offs + 1);
-                                                               child_sposns++;
-                                                       }
+                                       }
+                                       if (node->leaves != NULL) {
+                                               /* place possible matches at next char for all children */
+                                               int j;
+                                               for (j = 0; (xnode = node->leaves[j]) != NULL; j++) {
+                                                       add_sposn(xnode, offs + 1);
+                                                       child_sposns++;
                                                }
-                                               /* mark for removal */
-                                               node->sposns[i] = -1;
+                                               /* increase child sposn count for node and all ancestors */
+                                               ancestors_increment_sposns(node, child_sposns);
                                        }
+                                       /* mark for removal */
+                                       node->sposns[i] = -1;
                                }
                        }
-               }
-
-               /* after checking all sposns we clean up bad matches */
-               clean_bad_sposns(node);
-       }
 
-
-       if (acm == NULL) {
-               if (node->leaves != NULL && (brlen == 0 || node->child_sposns != 0)) {
-                       /* starting from the root, we look at each leaf in turn and check for matches
-                        * (skip if there are no child_sposns, to avoid parsing the whole tree) */
-                       for (i = 0; (xnode = node->leaves[i]) != NULL; i++) {
-                               acm = parse_char(ch, offs, xnode);
-                               if (acm != NULL)
-                                       return acm;
-                       }
+                       /* after checking all sposns we clean up bad matches */
+                       clean_bad_sposns(node);
                }
-       }
 
-       /* increase child sposn count for node and all ancestors */
-       if (child_sposns != 0)
-               ancestors_increment_sposns(node, child_sposns);
+               /* mark this node as checked for this position */
+               node->checked = TRUE;
+       }
 
-       /* mark this node as checked for this position */
-       node->checked = 1;
        return acm;
 }
 
+/**
+ * @callgraph
+ */
+ac_match *parse_char(unsigned char ch, int offs, ac_node *node)
+{
+#ifdef CASE_INSENSITIVE
+       return parse_char_with_case(tolower(ch), offs, node);
+#else
+       return parse_char_with_case(ch, offs, node);
+#endif
+}
+
 void reset_checks(ac_node *node)
 {
-       int i;
-       node->checked = 0;
+       if (!node) return;
+       node->checked = FALSE;
        if (node->leaves != NULL) {
                ac_node *xnode;
 
+               int i;
                for (i = 0; (xnode = node->leaves[i]) != NULL; i++)
                        reset_checks(xnode);
        }
@@ -452,13 +494,13 @@ void reset_checks(ac_node *node)
 
 void tree_free(ac_node *node)
 {
-       int i;
        if (node->branch != NULL)
                free(node->branch);
 
        if (node->leaves != NULL) {
                ac_node *xnode;
 
+               int i;
                for (i = 0; (xnode = node->leaves[i]) != NULL; i++)
                        tree_free(xnode);
 
@@ -468,27 +510,52 @@ void tree_free(ac_node *node)
        free(node);
 }
 
-void dump_tree(ac_node *node)
+void dump_tree(ac_node *node, FILE *stream)
 {
        int i;
        ac_node *xnode;
-       printf("%s (%p)", node->branch, node->user_data);
+       int otabbing, xtabbing;
+       static int tabbing;
+
+       if (!node) return;
+
+       if (node->branch == NULL || node->stem->brlen == 0)
+               tabbing = 0;
+
+       for (i = 0; i < tabbing; i++)
+               fprintf(stream, " ");
+
+       otabbing = tabbing;
+
+       if (node->brlen > 0) {
+               char *word = malloc(node->brlen + 1);
+               memcpy(word, node->branch, node->brlen);
+               memset(word + node->brlen, 0, 1);
+               fprintf(stream, "%s (%p)", word, node->user_data);
+               free(word);
+               tabbing += node->brlen + 10;
+               if (node->terminal) fprintf(stream, " |");
+       }
 
        if (node->leaves == NULL) {
-               printf("\n");
+               fprintf(stream, "\n");
                return;
        }
 
-       printf(" ");
+       fprintf(stream, "->\n");
+
+       xtabbing = tabbing;
+
+       for (i = 0; (xnode = node->leaves[i]) != NULL; i++) {
+               dump_tree(xnode, stream);
+               tabbing = xtabbing;
+       }
 
-       for (i = 0; (xnode = node->leaves[i]) != NULL; i++)
-               dump_tree(xnode);
+       tabbing = otabbing;
 }
 
 void clear_sposns(ac_node *node)
 {
-       int i;
-
        if (node == NULL)
                return;
 
@@ -501,6 +568,7 @@ void clear_sposns(ac_node *node)
        if (node->leaves != NULL) {
                ac_node *xnode;
 
+               int i;
                for (i = 0; (xnode = node->leaves[i]) != NULL; i++)
                        clear_sposns(xnode);
        }
index 6ca983b..2e0dea1 100644 (file)
@@ -22,6 +22,8 @@
 #ifndef _AHOCORASICK_NODE_H_
 #define _AHOCORASICK_NODE_H_
 
+#include <stdio.h>
+
 #include "types.h"
 
 #ifdef __cplusplus
@@ -39,7 +41,7 @@ extern "C" {
 void add_node(ac_instance *ac, const char *string, void *user_data);
 
 /**
- * @fn                                 ac_match *parse_char(char ch, int offs, ac_node *node)
+ * @fn                                 ac_match *parse_char(unsigned char ch, int offs, ac_node *node)
  * @brief                              Parse char at offs in the source text, using the tree rooted at node
  * @param[in] ch        The character at offs in the source text
  * @param[in] offs      The offset of the character in the source text
@@ -47,7 +49,7 @@ void add_node(ac_instance *ac, const char *string, void *user_data);
  * @return                             The next match at position offs, or NULL if no more matches.
  * @callgraph
  */
-ac_match *parse_char(char ch, int offs, ac_node *node);
+ac_match *parse_char(unsigned char ch, int offs, ac_node *node);
 
 /**
  * @fn                                 void clear_sposns(ac_node *node)
@@ -68,7 +70,7 @@ void tree_free(ac_node *node);
 /**
  * @fn                                 void reset_checks(ac_node *node)
  * @brief                              Each node is marked checked as the tree is traversed. When there are no more matches
- *                                             at a position, this function is called to clear the checks.
+ *                                             at a position, this function is called to clear the checks.
  * @param[in] node      the root of the tree to be traversed.
  * @callgraph
  */
@@ -78,9 +80,10 @@ void reset_checks(ac_node *node);
  * @fn                                 void dump_tree(ac_node *node)
  * @brief                              This is a test function which prints out the current tree of string fragments.
  * @param[in] node      The root of the tree to be traversed.
+ * @param[in] stream    The stream to print the output to, e.g. stdout, stderr.
  * @callgraph
  */
-void dump_tree(ac_node *node);
+void dump_tree(ac_node *node, FILE *stream);
 
 #ifdef __cplusplus
 }
index de40ad3..21ac34d 100644 (file)
@@ -33,7 +33,7 @@ extern "C" {
 #endif
 
 typedef struct _ac_node ac_node;
-typedef int boolean;
+typedef unsigned char boolean;
 
 #ifndef TRUE
 #define TRUE 1
@@ -42,14 +42,15 @@ typedef int boolean;
 
 struct _ac_node {
        void *user_data;        ///< the user_data which was added with the string
-       boolean is_match;       ///< is this node the terminal of some match
+       boolean terminal;       ///< is this node the terminal of some match
        ac_node *stem;          ///< node which this is a leaf of (or NULL)
-       char *branch;           ///< differential text following stem
+       char *branch;           ///< differential text following stem (not NUL terminated)
+       int brlen;              ///< length of *branch* (bytes)
        ac_node **leaves;       ///< various bits of text which can be appended to stem | branch
        int *sposns;            ///< used during matching - possible start positions of this branch
        int nsposns;            ///< number of sposns
        int child_sposns;       ///< number of sposns of descendents
-       int checked;            ///< if the node has been checked for the current position
+       boolean checked;        ///< if the node + children has been checked for the current position
 };
 
 typedef struct {
@@ -64,7 +65,7 @@ typedef struct {
        int offs;                       ///< how far we have parsed
        ac_match *match;        ///< latest match
        ac_node *root;          ///< pointer to the string matching tree
-       int added;                      ///< how many nodes added
+       int added;                      ///< how many strings added
 } ac_instance;
 
 #ifdef __cplusplus
index 482a238..0ce189c 100755 (executable)
@@ -10,7 +10,7 @@ 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 libpcre)
+pkg_check_modules(privacy-guard-client REQUIRED dlog libtzplatform-config libpcre)
 
 FOREACH(flag ${pkgs_CFLAGS})
        SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}")
@@ -42,39 +42,39 @@ ADD_DEFINITIONS("-D_PRIVACY_GUARD_DEBUG")
 ## for libprivacy-guard-client
 INCLUDE_DIRECTORIES(${pkgs_INCLUDE_DIRS} ${client_include_dir} ${common_include_dir} ${extern_include_dir})
 SET(PRIVACY_GUARD_CLIENT_SOURCES
+       ${ahocorasick_dir}/ahocorasick.c
+       ${ahocorasick_dir}/node.c
+       ${common_src_dir}/DlpUtils.cpp
+       ${common_src_dir}/privacy_guard_utils.c
+       ${common_src_dir}/SocketClient.cpp
        ${common_src_dir}/SocketConnection.cpp
        ${common_src_dir}/SocketStream.cpp
-       ${common_src_dir}/PrivacyIdInfo.cpp
-       ${common_src_dir}/DlpUtils.cpp
        ${common_src_dir}/Utils.cpp
-       ${common_src_dir}/privacy_guard_utils.c
-       ${client_src_dir}/SocketClient.cpp
-       ${client_src_dir}/PrivacyChecker.cpp
-       ${client_src_dir}/PrivacyGuardClient.cpp
-       ${client_src_dir}/privacy_guard_client.cpp
-       ${client_src_dir}/privacy_guard_dlp.cpp
+       ${client_src_dir}/DlpLogsManager.cpp
        ${client_src_dir}/DlpPacketParser.cpp
        ${client_src_dir}/DlpRulesManager.cpp
-       ${client_src_dir}/DlpLogsManager.cpp
-       ${ahocorasick_dir}/ahocorasick.c
-       ${ahocorasick_dir}/node.c
+       ${client_src_dir}/PrivacyGuardDlp.cpp
+       ${client_src_dir}/privacy_guard_dlp.cpp
        )
 SET(PRIVACY_GUARD_CLIENT_HEADERS
-       ${client_include_dir}/PrivacyChecker.h
-       ${client_include_dir}/PrivacyGuardClient.h
-       ${client_include_dir}/DlpPacketParserResult.h
-       ${client_include_dir}/DlpPacketParser.h
-       ${client_include_dir}/privacy_guard_client_internal.h
-       ${client_include_dir}/DlpRulesManager.h
-       ${client_include_dir}/DlpLogsManager.h
        ${ahocorasick_dir}/ahocorasick.h
        ${ahocorasick_dir}/node.h
        ${ahocorasick_dir}/types.h
+       ${common_include_dir}/DlpPacketParserResult.h
+       ${common_include_dir}/DlpUtils.h
+       ${common_include_dir}/privacy_guard_utils.h
+       ${common_include_dir}/SocketClient.h
+       ${common_include_dir}/SocketConnection.h
+       ${common_include_dir}/SocketStream.h
+       ${common_include_dir}/Utils.h
+       ${client_include_dir}/DlpLogsManager.h
+       ${client_include_dir}/DlpPacketParser.h
+       ${client_include_dir}/DlpRulesManager.h
+       ${client_include_dir}/PrivacyGuardDlp.h
        )
 SET(PRIVACY_GUARD_EXTERN_HEADERS
-       ${extern_include_dir}/privacy_guard_client.h
-       ${extern_include_dir}/privacy_guard_dlp.h
        ${extern_include_dir}/privacy_guard_client_types.h
+       ${extern_include_dir}/privacy_guard_dlp.h
        )
 
 SET(PRIVACY_GUARD_CLIENT_LDFLAGS " -module -avoid-version ")
@@ -98,4 +98,4 @@ 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)
+INSTALL(FILES ${PRIVACY_GUARD_EXTERN_HEADERS} DESTINATION ${INCLUDE_INSTALL_DIR}/privacy_guard)
\ No newline at end of file
index b24b9c6..93fa8c0 100644 (file)
@@ -27,7 +27,6 @@
 #include <list>
 #include "DlpPacketParser.h"
 #include "DlpPacketParserResult.h"
-#include "PrivacyGuardClient.h"
 #include "PrivacyGuardTypes.h"
 
 typedef struct _leak_log_queue_entry_s {
@@ -38,6 +37,7 @@ typedef struct _leak_log_queue_entry_s {
        current_rules_list rlist;
 } leak_log_queue_entry_s;
 
+class PrivacyGuardDlp;
 
 class EXTERN_API DlpLogsManager
 {
@@ -45,7 +45,7 @@ private:
        static std::mutex m_singletonMutex;
        static DlpLogsManager *m_pInstance;
        std::list<leak_log_queue_entry_s> m_logQueue;
-       PrivacyGuardClient *m_privacyGuardClient;
+       PrivacyGuardDlp *m_privacyGuardDlp;
        std::mutex m_logQueueMutex;
        std::mutex m_leakLogSendMutex;
 
@@ -66,9 +66,9 @@ private:
         *
         * @param[in] entry             The leaked information to be verified
         *
-        * @return                      The overall action to be taken given the individual results,
-        *                              either PRIV_GUARD_DLP_RESULT_ALLOW (all results allow or sanitize),
-        *                              or PRIV_GUARD_DLP_RESULT_DENY.
+        * @return                              The overall action to be taken given the individual results,
+        *                                              either PRIV_GUARD_DLP_RESULT_ALLOW (all results allow or sanitize),
+        *                                              or PRIV_GUARD_DLP_RESULT_DENY.
         */
        PgDlpResult ParseAndLogLeakNow(leak_log_queue_entry_s &entry);
 
@@ -83,9 +83,9 @@ public:
         * @param[in] len               The length of the data packet in bytes
         * @param[in] rules             The rules to use when parsing the data
         *
-        * @return                      The overall action to be taken given the individual results,
-        *                              either PRIV_GUARD_DLP_RESULT_ALLOW (all results allow or sanitize),
-        *                              or PRIV_GUARD_DLP_RESULT_DENY.
+        * @return                              The overall action to be taken given the individual results,
+        *                                              either PRIV_GUARD_DLP_RESULT_ALLOW (all results allow or sanitize),
+        *                                              or PRIV_GUARD_DLP_RESULT_DENY.
         */
        PgDlpResult ParseAndLogLeak(const char *hostname, char *mem, size_t len, const current_rules_list &rules);
 
index 2f4781b..4a6beae 100644 (file)
@@ -37,7 +37,7 @@ public:
         * @brief                               Set the rules for the packet parser
         *
         * @param[in] rules             Pointer to a std::list of current_rules_s.
-        *                      The rules are not copied so they must remain valid while parsePacket() or sanitize() is called.
+        *                                              The rules are not copied so they must remain valid while parsePacket() or sanitize() is called.
         *
         * @return                              count of rules in the list
         */
@@ -46,17 +46,17 @@ public:
        /**
         * @fn                                  PgDlpResult parsePacket(char * const pdata, size_t length, DlpPacketParserResultList &rl)
         * @brief                               Parse a packet of data and return a std::list of DlpPacketParserResult.
-        *                              Before calling this it is necessary to set rules (once) with setRules().
-        *                              After calling this you may call sanitize() to sanitize the packet.
+        *                                              Before calling this it is necessary to set rules (once) with setRules().
+        *                                              After calling this you may call sanitize() to sanitize the packet.
         *
-        * @param[in]  pdata    pointer to the packet data to be parsed. If sanitization is to be performed,
-        *                      the data must not be freed until after sanitize() is called.
-        * @param[in]  length   byte length of the packet data to be parsed
-        * @param[out] rl       std::list of DlpPacketParserResult. List may be empty.
+        * @param[in]  pdata    pointer to the packet data to be parsed. If sanitization is to be performed,
+        *                                              the data must not be freed until after sanitize() is called.
+        * @param[in]  length   byte length of the packet data to be parsed
+        * @param[out] rl               std::list of DlpPacketParserResult. List may be empty.
         *
-        * @return                      The overall action to be taken given the individual results,
-        *                              either PRIV_GUARD_DLP_RESULT_ALLOW (all results allow or sanitize),
-        *                              or PRIV_GUARD_DLP_RESULT_DENY.
+        * @return                              The overall action to be taken given the individual results,
+        *                                              either PRIV_GUARD_DLP_RESULT_ALLOW (all results allow or sanitize),
+        *                                              or PRIV_GUARD_DLP_RESULT_DENY.
         */
        PgDlpResult parsePacket(char * const pdata, size_t length, DlpPacketParserResultList &rl);
 
@@ -65,7 +65,7 @@ public:
         * @brief                               Get the overall action given a list of DlpPacketParserResult.
         *
         * @param[in]  pdata    pointer to the packet data to be parsed. If sanitization is to be performed,
-        *                              the data must not be freed until after sanitize() is called.
+        *                                              the data must not be freed until after sanitize() is called.
         * @param[in]  length   byte length of the packet data to be parsed
         * @param[in]  rl               std::list of DlpPacketParserResult. List may be empty.
         *
index eb9892b..887c12d 100644 (file)
@@ -16,7 +16,7 @@
 
 /**
  * @file       DlpRulesManager.h
- * @brief      Manages the packet parsing rules for a client
+ * @brief      Manages the packet parsing rules for dlp library
  */
 
 #ifndef _DLPRULESMANAGER_H_
 #include <string>
 #include <mutex>
 #include <list>
-#include "PrivacyGuardClient.h"
 #include "PrivacyGuardTypes.h"
 
+class PrivacyGuardDlp;
+
 class EXTERN_API DlpRulesManager
 {
 private:
        static std::mutex m_singletonMutex;
        static DlpRulesManager *m_pInstance;
        std::list<current_rules_s> m_currentRules;
-       PrivacyGuardClient *m_privacyGuardClient;
+       PrivacyGuardDlp *m_privacyGuardDlp;
        std::mutex m_rulesMutex;
 
        DlpRulesManager();
diff --git a/client/inc/PrivacyChecker.h b/client/inc/PrivacyChecker.h
deleted file mode 100755 (executable)
index 9f01a8a..0000000
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-
-/**
- * @file       PrivacyChecker.h
- */
-
-#ifndef _PRIVACY_CHECKER_H_
-#define _PRIVACY_CHECKER_H_
-
-#include <string>
-#include <mutex>
-#include <list>
-#include <vector>
-#include <memory>
-#include <map>
-#include <dbus/dbus.h>
-#include <glib.h>
-#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 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 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/PrivacyGuardDlp.h b/client/inc/PrivacyGuardDlp.h
new file mode 100644 (file)
index 0000000..1341cc8
--- /dev/null
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *    Licensed under the Apache License, Version 2.0 (the "License");
+ *    you may not use this file except in compliance with the License.
+ *    You may obtain a copy of the License at
+ *
+ *        http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *    Unless required by applicable law or agreed to in writing, software
+ *    distributed under the License is distributed on an "AS IS" BASIS,
+ *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *    See the License for the specific language governing permissions and
+ *    limitations under the License.
+ */
+
+/**
+ * @file       PrivacyGuardDlp.h
+ */
+
+#ifndef _PRIVACYGUARDDLP_H_
+#define _PRIVACYGUARDDLP_H_
+
+#include <string>
+#include <mutex>
+#include <list>
+#include "PrivacyGuardTypes.h"
+
+class EXTERN_API PrivacyGuardDlp
+{
+private:
+       static PrivacyGuardDlp* m_pInstance;
+       static const std::string INTERFACE_NAME;
+
+       static std::mutex m_singletonMutex;
+
+       PrivacyGuardDlp();
+       ~PrivacyGuardDlp();
+
+       //void loadApplicationInfo();
+
+public:
+       static PrivacyGuardDlp* getInstance();
+
+       /**
+        * @brief       add a list of leak logs to the database
+        *
+        * @param[in]   userId                  The ID of the user running the application 
+        * @param[in]   pId                             The process ID of the application
+        * @param[in]   destination             The host which the data is to be sent to
+        * @param[in]   rawPacket               The data packet to be sent
+        * @param[in]   len                             The length of the packet data in bytes
+        * @param[in]   logList                 The std::list of leaks to be added.
+        *
+        * @return      An error code
+        * @since       Tizen 4.0
+        */
+       int PgAddLeakLog(const int userId, const int pId, const char *destination, const void *rawPacket, const size_t len, const std::list<leak_log_insert_data_s> &logList) const;
+
+       /**
+        * @brief       get the current parsing rules for the application
+        *
+        * @param[in]   userId                  The ID of the user
+        * @param[in]   pId                             The process ID of the application
+        * @param[out]  currentRules    A std::list of rules for the user and application
+        *
+        * @note        The rules can be updated at any time while the application is running.
+        * @see         DlpRuleChangeNotification::addDlpClient()
+        * @return      An error code
+        * @since       Tizen 4.0
+        */
+       int PgGetDlpCurrentRules(const int userId, const int pId, std::list<current_rules_s> &currentRules) const;
+};
+
+#endif // _PRIVACYGUARDDLP_H_
index 04e4bc3..86f5ff6 100644 (file)
@@ -20,7 +20,7 @@
  */
 
 #include "DlpLogsManager.h"
-#include "PrivacyGuardClient.h"
+#include "PrivacyGuardDlp.h"
 #include "Utils.h"
 
 std::mutex DlpLogsManager::m_singletonMutex;
@@ -29,7 +29,7 @@ DlpLogsManager *DlpLogsManager::m_pInstance = NULL;
 DlpLogsManager::DlpLogsManager(void)
 {
        pthread_t notify_thread;
-       m_privacyGuardClient = PrivacyGuardClient::getInstance();
+       m_privacyGuardDlp = PrivacyGuardDlp::getInstance();
 
        // launch leak log send thread
        m_leakLogSendMutex.lock();
@@ -61,14 +61,17 @@ DlpLogsManager::ParseAndLogLeak(const char *hostname, char *mem, size_t len, con
        entry.len = len;
        entry.rlist = rules;
 
-       // check if we have only ALLOW actions on the rules list
-       for (auto &it : rules) {
-               if (it.action != PRIV_GUARD_DLP_ACTION_ALLOW) {
-                       // if we have any rule different from ALLOW we need to parse now
-                       res = ParseAndLogLeakNow(entry);
-                       break;
-               }
-       }
+       /** This verification is not necessary in current implementation
+        *  as it supports only ALLOW action.
+        * // check if we have only ALLOW actions on the rules list
+        * for (auto &it : rules) {
+        *      if (it.action != PRIV_GUARD_DLP_ACTION_ALLOW) {
+        *              // if we have any rule different from ALLOW we need to parse now
+        *              res = ParseAndLogLeakNow(entry);
+        *              break;
+        *      }
+        *}
+        */
 
        if (!entry.rlist.empty() || !entry.llist.empty()) {
                // add entry to the m_logQueue to be processed when the thread awakes
@@ -118,6 +121,7 @@ DlpLogsManager::LeakLogSendThreadFunc(void *_this)
 void*
 DlpLogsManager::LeakLogSendThread()
 {
+       uid_t pid = getpid();
        uid_t uid = getuid();
 
        for (;;) {
@@ -126,13 +130,16 @@ DlpLogsManager::LeakLogSendThread()
 
                // with new entries, try to process them
                m_logQueueMutex.lock();
-               for (auto &it : m_logQueue) {
+               for (auto it = m_logQueue.begin(); it != m_logQueue.end(); it++) {
+                       m_logQueueMutex.unlock();
                        // if packet has not been parsed yet, parse now
-                       if (!it.rlist.empty())
-                               ParseAndLogLeakNow(it);
+                       if (!it->rlist.empty())
+                               ParseAndLogLeakNow(*it);
+
+                       if (!it->llist.empty())
+                               m_privacyGuardDlp->PgAddLeakLog(uid, pid, it->hostname.c_str(), it->mem, it->len, it->llist);
 
-                       if (!it.llist.empty())
-                               m_privacyGuardClient->PgAddLeakLog(uid, it.hostname.c_str(), it.mem, it.len, it.llist);
+                       m_logQueueMutex.lock();
                }
 
                // all entries processed, call clear destroying each element from queue
index e71e0c9..4fb4615 100644 (file)
@@ -22,6 +22,7 @@
 #include <sys/types.h>
 #include <sys/stat.h>
 #include <fcntl.h>
+#include "PrivacyGuardDlp.h"
 #include "DlpRulesManager.h"
 #include "Utils.h"
 
@@ -33,7 +34,7 @@ DlpRulesManager *DlpRulesManager::m_pInstance = NULL;
 DlpRulesManager::DlpRulesManager(void)
 {
        pthread_t notify_thread;
-       m_privacyGuardClient = PrivacyGuardClient::getInstance();
+       m_privacyGuardDlp = PrivacyGuardDlp::getInstance();
 
        // Launch privacy guard notification thread
        m_rulesMutex.lock();
@@ -81,11 +82,11 @@ DlpRulesManager::NewRulesNotificationThread()
                                 S_IRWXU |
                                 S_IRGRP | S_IWGRP |
                                 S_IROTH | S_IWOTH,
-                                0);
+                                                               0);
        umask(umask_value);
 
        // Get rules from server for the first time
-       m_privacyGuardClient->PgGetDlpCurrentRules(uid, pid, m_currentRules);
+       m_privacyGuardDlp->PgGetDlpCurrentRules(uid, pid, m_currentRules);
 
        if (semaphore == SEM_FAILED) {
                PG_LOGE("errro unlink sem: %s - %s", sem_name, strerror_r(errno, buf, sizeof(buf)));
@@ -105,7 +106,7 @@ DlpRulesManager::NewRulesNotificationThread()
 
                // Get rules from server
                m_rulesMutex.lock();
-               m_privacyGuardClient->PgGetDlpCurrentRules(uid, pid, m_currentRules);
+               m_privacyGuardDlp->PgGetDlpCurrentRules(uid, pid, m_currentRules);
        }
 
        return NULL;
diff --git a/client/src/PrivacyChecker.cpp b/client/src/PrivacyChecker.cpp
deleted file mode 100755 (executable)
index 8bc8b92..0000000
+++ /dev/null
@@ -1,396 +0,0 @@
-/*
- * Copyright (c) 2012 Samsung Electronics Co., Ltd All Rights Reserved
- *
- *    Licensed under the Apache License, Version 2.0 (the "License");
- *    you may not use this file except in compliance with the License.
- *    You may obtain a copy of the License at
- *
- *        http://www.apache.org/licenses/LICENSE-2.0
- *
- *    Unless required by applicable law or agreed to in writing, software
- *    distributed under the License is distributed on an "AS IS" BASIS,
- *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *    See the License for the specific language governing permissions and
- *    limitations under the License.
- */
-
-/**
- * @file       PrivacyChecker.cpp
- */
-
-#include <algorithm>
-#include <memory>
-#include <sqlite3.h>
-#include <dbus/dbus-glib-lowlevel.h>
-#include <sys/types.h>
-#include <unistd.h>
-#include <privilege_info.h>
-#include "PrivacyChecker.h"
-#include "PrivacyIdInfo.h"
-#include "PrivacyGuardClient.h"
-#include "SocketClient.h"
-#include "Utils.h"
-
-#define BUF_SIZE 256
-
-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_GUARD_ERROR_SUCCESS;
-       }
-
-       std::lock_guard < std::mutex > guard(m_cacheMutex);
-
-       int res = initMonitorPolicyCache();
-       TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, , "Failed to update cache (%d)", res);
-
-       res = initializeGMain();
-       TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, , "Failed to initialize() (%d)", res);
-
-       return PRIV_GUARD_ERROR_SUCCESS;
-}
-
-int
-PrivacyChecker::initializeGMain(void)
-{
-       std::unique_lock<std::mutex> initlock(m_initializeMutex);
-
-       TryReturn(!m_isInitialized, PRIV_GUARD_ERROR_SUCCESS, , "Already Initalized");
-
-       m_pHandlerGMainContext = g_main_context_new();
-       TryReturn(m_pHandlerGMainContext != NULL, PRIV_GUARD_ERROR_SYSTEM_ERROR, , "cannot create m_pHandlerGMainContext");
-
-       m_pLoop = g_main_loop_new(m_pHandlerGMainContext, FALSE);
-       TryReturn(m_pLoop != NULL, PRIV_GUARD_ERROR_SYSTEM_ERROR, , "cannot create m_pLoop");
-
-       std::unique_lock<std::mutex> lock(m_dbusMutex);
-       char buf[BUF_SIZE];
-       int res = pthread_create(&m_signalThread, NULL, &runSignalListenerThread, NULL);
-       TryReturn(res >= 0, PRIV_GUARD_ERROR_SYSTEM_ERROR, errno = res;, "Failed to create listener thread :%s", strerror_r(res, buf, sizeof(buf)));
-
-       m_isInitialized = true;
-
-       return PRIV_GUARD_ERROR_SUCCESS;
-}
-
-void
-PrivacyChecker::printMonitorPolicyCache(void)
-{
-       for(std::map<std::string, int>::iterator itr = m_monitorPolicyCache.begin(); itr != m_monitorPolicyCache.end(); itr++) {
-               PG_LOGD("PRIVACY string : %s", itr->first.c_str());
-               PG_LOGD("PRIVACY monitor_policy : %d", itr->second);
-       }
-}
-
-int
-PrivacyChecker::initMonitorPolicyCache(void)
-{
-       std::list < std::pair < std::string, int > > monitorPolicyList;
-
-       int retval = PrivacyGuardClient::getInstance()->PgGetAllMonitorPolicy(monitorPolicyList);
-       if(retval == PRIV_GUARD_ERROR_SUCCESS && !monitorPolicyList.empty()) {
-               m_monitorPolicyCache.insert(monitorPolicyList.begin(), monitorPolicyList.end());
-       } else {
-               PG_LOGD("ret: [%d], monitorPolicyList size: [%d]", retval, monitorPolicyList.size());
-       }
-
-       return retval;
-}
-
-int
-PrivacyChecker::getMonitorPolicy(const int userId, const std::string packageId, const std::string privacyId, int &monitorPolicy)
-{
-       int res = PRIV_GUARD_ERROR_SUCCESS;
-       PG_LOGD("m_isInitialized: %d", m_isInitialized);
-
-       if (m_isInitialized == false) {
-               initialize();
-       }
-
-       std::string userPkgIdPrivacyId = std::to_string(userId) + std::string("|") + packageId + std::string("|") + privacyId;
-       PG_LOGD("key: %s", userPkgIdPrivacyId.c_str());
-       std::map<std::string, int>::iterator itr = m_monitorPolicyCache.find(userPkgIdPrivacyId);
-
-       if(itr != m_monitorPolicyCache.end()) {
-               monitorPolicy = itr->second;
-       } else  {
-               monitorPolicy = 0;
-               res = PRIV_GUARD_ERROR_NO_DATA;
-       }
-
-       return res;
-}
-
-void
-PrivacyChecker::checkMonitorByPrivilege(const std::string privilegeId)
-{
-       PG_LOGD("checkMonitorByPrivilege called with privilege: [%s]", privilegeId.c_str());
-
-       if (privilege_info_is_privacy(privilegeId.c_str()))     {
-               m_isMonitorEnable = true;
-       } else  {
-               PG_LOGD("[%s] is not related to a privacy.", privilegeId.c_str());
-               m_isMonitorEnable = false;
-       }
-}
-
-void*
-PrivacyChecker::runSignalListenerThread(void* pData)
-{
-       pthread_detach(pthread_self());
-
-       PG_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_GUARD_ERROR_SYSTEM_ERROR, dbus_error_free(&error), "dbus_bus_get_private [%s] : %d", PRIV_GUARD_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_GUARD_ERROR_SYSTEM_ERROR, dbus_error_free(&error), "dbus_bus_add_match[%s] : %d", error.message, PRIV_GUARD_ERROR_SYSTEM_ERROR);
-
-       dbus_bool_t r = dbus_connection_add_filter(m_pDBusConnection, handleNotification, NULL, NULL);
-       TryReturn(r, PRIV_GUARD_ERROR_SYSTEM_ERROR, , "dbus_connection_add_filter: %d", PRIV_GUARD_ERROR_SYSTEM_ERROR);
-
-       return PRIV_GUARD_ERROR_SUCCESS;
-}
-
-int
-PrivacyChecker::finalizeDbus(void)
-{
-       dbus_connection_remove_filter(m_pDBusConnection, handleNotification, NULL);
-       dbus_connection_close(m_pDBusConnection);
-       m_pDBusConnection = NULL;
-
-       return PRIV_GUARD_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)
-               {
-                       PG_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()) {
-                       PG_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_GUARD_ERROR_NOT_INITIALIZED, , "Not initialized");
-
-       std::map < std::string, bool >::iterator iter;
-
-       iter = privacyMap.find(privacyId);
-       if (iter == privacyMap.end()) {
-               PG_LOGD("The application cannot access the privacy inforamtion.");
-               return PRIV_GUARD_ERROR_USER_NOT_CONSENTED;
-       } else if (!iter->second) {
-               PG_LOGD("User does not consented to access the privacy information");
-               return PRIV_GUARD_ERROR_USER_NOT_CONSENTED;
-       }
-
-       return PRIV_GUARD_ERROR_SUCCESS;
-}
-
-int
-PrivacyChecker::check(const std::string privacyId)
-{
-       if (!m_isInitialized)
-               return PRIV_GUARD_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_GUARD_ERROR_SUCCESS, PRIV_GUARD_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_GUARD_ERROR_USER_NOT_CONSENTED;
-       }
-
-       res = check(privacyId, iter->second);
-
-       return res;
-}
-
-int
-PrivacyChecker::finalize(void)
-{
-       std::lock_guard<std::mutex> 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_GUARD_ERROR_SUCCESS;
-}
-
-void
-PrivacyChecker::printCache(void)
-{
-       std::map < std::string, bool >::const_iterator iter = m_privacyCache.begin();
-       for (; iter != m_privacyCache.end(); ++iter)
-       {
-               PG_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_GUARD_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_GUARD_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;
-
-               PG_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_GUARD_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_GUARD_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));
-
-               PG_LOGD("Privacy found : %s %d", privacyId, privacyEnabled);
-       }
-       return PRIV_GUARD_ERROR_SUCCESS;
-}
diff --git a/client/src/PrivacyGuardDlp.cpp b/client/src/PrivacyGuardDlp.cpp
new file mode 100644 (file)
index 0000000..84d33e8
--- /dev/null
@@ -0,0 +1,88 @@
+/*
+ * 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 <aul.h>
+#include "PrivacyGuardDlp.h"
+#include "SocketClient.h"
+
+#undef __READ_DB_IPC__
+
+std::mutex PrivacyGuardDlp::m_singletonMutex;
+PrivacyGuardDlp* PrivacyGuardDlp::m_pInstance = NULL;
+const std::string PrivacyGuardDlp::INTERFACE_NAME("PrivacyInfoService");
+
+PrivacyGuardDlp::PrivacyGuardDlp()
+{
+}
+
+/**
+ * @callgraph
+ */
+PrivacyGuardDlp*
+PrivacyGuardDlp::getInstance()
+{
+       std::lock_guard<std::mutex> guard(m_singletonMutex);
+       if (m_pInstance == NULL)
+               m_pInstance = new(std::nothrow) PrivacyGuardDlp();
+       return m_pInstance;
+}
+
+/**
+ * @callgraph
+ */
+int
+PrivacyGuardDlp::PgAddLeakLog(const int userId, const int pId, const char *destination, const void *rawPacket, const size_t len, const std::list<leak_log_insert_data_s> &logList) const
+{
+       if (destination == NULL || rawPacket == NULL)
+               return PRIV_GUARD_ERROR_INVALID_PARAMETER;
+
+       int result = PRIV_GUARD_ERROR_SUCCESS;
+       SocketClient socketClient(INTERFACE_NAME);
+       packet_data_s packetData = { (int)len, (void *)rawPacket};
+
+       int res = socketClient.connect();
+       TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, , "connect : %d", res);
+
+       res = socketClient.call("PgAddLeakLog", userId, pId, destination, packetData, logList, &result);
+       TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, socketClient.disconnect(), "call : %d", res);
+
+       res = socketClient.disconnect();
+       TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, , "disconnect : %d", res);
+
+       return result;
+}
+
+/**
+ * @callgraph
+ */
+int
+PrivacyGuardDlp::PgGetDlpCurrentRules(const int userId, const int pId, std::list<current_rules_s> &currentRules) const
+{
+       int result = PRIV_GUARD_ERROR_SUCCESS;
+       SocketClient socketClient(INTERFACE_NAME);
+
+       int res = socketClient.connect();
+       TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, , "connect : %d", res);
+
+       currentRules.clear();
+       res = socketClient.call("PgGetDlpCurrentRules", userId, pId, &result, &currentRules);
+       TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, socketClient.disconnect(), "call : %d", res);
+
+       res = socketClient.disconnect();
+       TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, , "disconnect : %d", res);
+
+       return result;
+}
index dd35806..f58d619 100644 (file)
  */
 void privacy_guard_dlp_init(void)
 {
-       DlpRulesManager::getInstance();
-       DlpLogsManager::getInstance();
+//     DlpRulesManager::getInstance();
+//     DlpLogsManager::getInstance();
        PG_LOGD("Initializing DLP");
+       pid_t pid = getpid();
+       uid_t uid = getuid();
+       PG_LOGD("privacy_guard_dlp_check_leak - pid: %d - uid: %d", pid, uid);
 }
 
 /**
@@ -39,20 +42,27 @@ void privacy_guard_dlp_init(void)
  */
 PgDlpResult privacy_guard_dlp_check_leak(const char *hostname, char * const mem, size_t len)
 {
+
+       pid_t pid = getpid();
+       uid_t uid = getuid();
+       PG_LOGD("privacy_guard_dlp_check_leak - pid: %d - uid: %d", pid, uid);
+
+       DlpRulesManager::getInstance();
+       DlpLogsManager::getInstance();
+
 #ifdef PERF_TEST
        struct timespec tp_before, tp_after;
        long interval;
        clock_gettime(CLOCK_REALTIME, &tp_before);
 #endif
        current_rules_list rules;
-       PgDlpResult res;
        DlpRulesManager *pRules = DlpRulesManager::getInstance();
        DlpLogsManager *pLogs = DlpLogsManager::getInstance();
 
        /* return DENY if called with NULL values or zero len */
        if (hostname == NULL || mem == NULL || len == 0) {
                PG_LOGE("DLP check leak received and empty request, message denied");
-               return PRIV_GUARD_DLP_RESULT_DENY;
+               return PRIV_GUARD_DLP_RESULT_ALLOW;
        }
 
        /* get cached rules from server */
@@ -67,7 +77,7 @@ PgDlpResult privacy_guard_dlp_check_leak(const char *hostname, char * const mem,
                return PRIV_GUARD_DLP_RESULT_ALLOW;
        }
 
-       res = pLogs->ParseAndLogLeak(hostname, mem, len, rules);
+       pLogs->ParseAndLogLeak(hostname, mem, len, rules);
 
 #ifdef PERF_TEST
        clock_gettime(CLOCK_REALTIME, &tp_after);
@@ -75,14 +85,6 @@ PgDlpResult privacy_guard_dlp_check_leak(const char *hostname, char * const mem,
        PG_LOGD("DLP check time: %ld us", interval);
 #endif
 
-#ifdef _PRIVACY_GUARD_DEBUG
-       if (res == PRIV_GUARD_DLP_RESULT_ALLOW) {
-               PG_LOGD("Packet allowed");
-       } else {
-               PG_LOGD("Packet denied");
-       }
-#endif
-
-       return res;
+       return PRIV_GUARD_DLP_RESULT_ALLOW;
 }
 
old mode 100755 (executable)
new mode 100644 (file)
old mode 100755 (executable)
new mode 100644 (file)
index b28fcc0..44fcf84
@@ -22,7 +22,6 @@
 #define _PRIVACY_GUARD_COMMON_H_
 
 #include <sqlite3.h>
-#include <db-util.h>
 #include <stdbool.h>
 
 #endif // _PRIVACY_GUARD_COMMON_H_
index a2bb71a..4b11cc3 100644 (file)
@@ -68,11 +68,7 @@ typedef struct _packet_data_s {
 
 typedef struct _leak_log_insert_common_data_s {
        int user_id;
-       char application_id[LEN_APPLICATION_ID];
-       char application_name[LEN_APPLICATION_NAME];
-       char application_version[LEN_APPLICATION_VERSION];
-       char application_icon[LEN_APPLICATION_ICON];
-       char package_id[LEN_PACKAGE_ID];
+       int pid;
        char destination[LEN_DESTINATION];
        packet_data_s pkt_data;
 } leak_log_insert_common_data_s;
@@ -94,9 +90,18 @@ typedef struct _current_rules_s {
 
 typedef std::list<current_rules_s> current_rules_list;
 
+typedef struct _privacy_semaphore_app_info_s {
+       char application_id[LEN_APPLICATION_ID];
+       char application_name[LEN_APPLICATION_NAME];
+       char application_version[LEN_APPLICATION_VERSION];
+       char application_icon[LEN_APPLICATION_ICON];
+       char package_id[LEN_PACKAGE_ID];
+} privacy_semaphore_app_info_s;
+
 typedef struct _privacy_semaphore_s {
        int pid;
        sem_t *sem;
+       privacy_semaphore_app_info_s app_info;
 } privacy_semaphore_s;
 
 typedef struct _custom_rule_s {
old mode 100755 (executable)
new mode 100644 (file)
old mode 100755 (executable)
new mode 100644 (file)
similarity index 99%
rename from client/inc/SocketClient.h
rename to common/inc/SocketClient.h
index 956e312..f767dc8
@@ -148,7 +148,7 @@ private:
        int make_call(T *outvalue)
        {
                return m_socketConnector->read(outvalue);
-    }
+       }
 
 private:
        std::string m_serverAddress;
index 334c1b5..25d83d6 100755 (executable)
@@ -445,24 +445,8 @@ public:
                int res = read(&out.user_id);
                TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, , "read : %d", res);
 
-               // application ID
-               res = read(out.application_id, LEN_APPLICATION_ID);
-               TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, , "read : %d", res);
-
-               // application name
-               res = read(out.application_name, LEN_APPLICATION_NAME);
-               TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, , "read : %d", res);
-
-               // application version
-               res = read(out.application_version, LEN_APPLICATION_VERSION);
-               TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, , "read : %d", res);
-
-               // application icon
-               res = read(out.application_icon, LEN_APPLICATION_ICON);
-               TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, , "read : %d", res);
-
-               // package ID
-               res = read(out.package_id, LEN_PACKAGE_ID);
+               // pid
+               res = read(&out.pid);
                TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, , "read : %d", res);
 
                // destination
old mode 100755 (executable)
new mode 100644 (file)
index fb2d45b..9efdfb9 100755 (executable)
@@ -29,7 +29,6 @@
 #include <memory>
 #include <string>
 #include <unistd.h>
-#include <db-util.h>
 #include "privacy_guard_utils.h"
 
 // debug print /////////////////////////////////////////////
@@ -76,7 +75,7 @@
                LOGE(logFormat, res);                                                                                                                           \
                expr;                                                                                                                                                           \
                return r;                                                                                                                                                       \
-       } else {;}
+       } else {; }
 
 
 #define TryReturn(condition, r, expr, ...)     \
                        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_GUARD_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_stmtpStmt##Temp;                                                                                              \
+#define prepareDb(pHandler, sql, pStmt)        sqlite3_stmt *pStmt##Temp;                                                                                              \
        {                                                                                                                                                                                                                               \
                int res = SQLITE_OK;                                                                                                                                                                            \
                for (int dbRetryCount = 0; dbRetryCount < MAX_DATABASE_RETRY_COUNT; dbRetryCount++) {                                           \
index 01e7298..533f926 100644 (file)
@@ -28,6 +28,6 @@
  * @param[in]   src       a pointer to the string to be copied from.
  * @param[in]   dstsize   the maximum number of bytes to be copied.
  */
- extern "C" void pg_strlcpy(char *dst, const char *src, size_t dstsize);
- #endif //_PRIVACY_GUARD_UTILS_H_
\ No newline at end of file
+extern "C" void pg_strlcpy(char *dst, const char *src, size_t dstsize);
+
+ #endif //_PRIVACY_GUARD_UTILS_H_
index 3c21ad9..3d60d52 100644 (file)
@@ -195,13 +195,13 @@ void dlp_pcre_search(SUB_PARSER_PTR ptr, const char *data, size_t length, DlpPac
        std::list<DlpPcre> *complist = (std::list<DlpPcre> *)ptr;
 
        int subStrVec[30];
-       int rc, i, offs, idx = 0;
+       int i, offs, idx = 0;
 
        offs = 0;
 
        for (auto it = complist->begin(); it != complist->end();) {
                /* Try to find the regex in aLineToMatch, and report results. */
-               rc = pcre_exec((*it).compiled,
+               int rc = pcre_exec((*it).compiled,
                               (*it).extra,
                               data,
                               length,                 // length of string
old mode 100755 (executable)
new mode 100644 (file)
old mode 100755 (executable)
new mode 100644 (file)
similarity index 97%
rename from client/src/SocketClient.cpp
rename to common/src/SocketClient.cpp
index df1884d..4963069
@@ -56,7 +56,7 @@ int SocketClient::connect()
        int flags;
        if ( (flags = fcntl(m_socketFd, F_GETFL, 0)) == -1 )
                flags = 0;
-       res = fcntl(m_socketFd, F_SETFL, flags | O_NONBLOCK);
+       fcntl(m_socketFd, F_SETFL, flags | O_NONBLOCK);
        TryReturn( m_socketFd != -1, PRIV_GUARD_ERROR_IPC_ERROR, , "fcntl : %s", strerror_r(errno, buf, sizeof(buf)));
 
        bzero(&remote, sizeof(remote));
old mode 100755 (executable)
new mode 100644 (file)
old mode 100755 (executable)
new mode 100644 (file)
index 6a1301b..6ec51bd
@@ -59,7 +59,6 @@ SocketStream::readStream(size_t num, void* pBytes)
        FD_ZERO(&allset);
        FD_SET(m_socketFd, &allset);
 
-       int ret;
        unsigned int currentOffset = 0;
 
        while (currentOffset < num)
@@ -67,6 +66,7 @@ SocketStream::readStream(size_t num, void* pBytes)
                timeout.tv_sec = READ_TIEMOUT_SEC;
                timeout.tv_nsec = READ_TIMEUOT_NSEC;
                rset = allset;
+               int ret;
 
                if ( (ret = pselect(maxFd, &rset, NULL, NULL, &timeout, NULL)) == -1 )
                {
@@ -119,7 +119,6 @@ SocketStream::writeStream(size_t num, const void* pBytes)
        FD_ZERO(&allset);
        FD_SET(m_socketFd, &allset);
 
-       int res;
        ssize_t writeRes;
        unsigned int currentOffset = 0;
 
@@ -129,7 +128,7 @@ SocketStream::writeStream(size_t num, const void* pBytes)
                timeout.tv_nsec = WRITE_TIMEOUT_NSEC;
                wset = allset;
 
-               if ( (res = pselect(maxFd, NULL, &wset, NULL, &timeout, NULL)) == -1 )
+               if ( pselect(maxFd, NULL, &wset, NULL, &timeout, NULL) == -1 )
                {
                        if(errno == EINTR)
                                continue;
old mode 100755 (executable)
new mode 100644 (file)
old mode 100755 (executable)
new mode 100644 (file)
index 108f858..5219179
@@ -1,11 +1,11 @@
 CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
-#PROJECT(privacy-guard-client)
+#PROJECT(privacy-guard-setting)
 
 SET(PG_INCLUDE_PATH ${PROJECT_SOURCE_DIR}/include)
 
-SET(PRIVACY_GUARD_CLIENT_HEADERS
+SET(PRIVACY_GUARD_SETTING_HEADERS
        ${PG_INCLUDE_PATH}/privacy_guard_client.h
        ${PG_INCLUDE_PATH}/privacy_guard_client_types.h
        )
 
-INSTALL(FILES ${PRIVACY_GUARD_CLIENT_HEADERS} DESTINATION ${INCLUDE_INSTALL_DIR}/privacy_guard)
+INSTALL(FILES ${PRIVACY_GUARD_SETTING_HEADERS} DESTINATION ${INCLUDE_INSTALL_DIR}/privacy_guard)
index 6f62b09..00d071b 100755 (executable)
@@ -16,7 +16,7 @@
 
 /**
  * @file       privacy_guard_client.h
- * @brief      API for privacy-guard-client (C / C++)
+ * @brief      API for privacy-guard-setting (C / C++)
  */
 
 #ifndef _PRIVACY_GUARD_CLIENT_H_
@@ -433,9 +433,9 @@ EXTERN_API int privacy_guard_client_delete_dlp_custom_rule(int rule_id);
  * @param[in] rule_id                          The existing rule ID
  * @param[in] action                           The new action to be taken (allow, deny, sanitize)
  * @param[in] pattern_id                       The new pattern ID
- * @param[in] name                             The new rule name
- * @param[in] description                      The new rule description
- * @param[in] application_id                   The new app id
+ * @param[in] name                                     The new rule name
+ * @param[in] description                      The new rule description
+ * @param[in] application_id           The new app id
  *
  * @return the result of operation (ERRORCODE : success, ....)
  */
old mode 100755 (executable)
new mode 100644 (file)
index c00c25b..3103acf
@@ -2,4 +2,4 @@
         <request>
                 <domain name="_" />
         </request>
-</manifest>
+</manifest>
\ No newline at end of file
diff --git a/packaging/libprivacy-guard-setting.manifest b/packaging/libprivacy-guard-setting.manifest
new file mode 100644 (file)
index 0000000..c00c25b
--- /dev/null
@@ -0,0 +1,5 @@
+<manifest>
+        <request>
+                <domain name="_" />
+        </request>
+</manifest>
old mode 100755 (executable)
new mode 100644 (file)
index c00c25b..3103acf
@@ -2,4 +2,4 @@
         <request>
                 <domain name="_" />
         </request>
-</manifest>
+</manifest>
\ No newline at end of file
old mode 100755 (executable)
new mode 100644 (file)
index c00c25b..3103acf
@@ -2,4 +2,4 @@
         <request>
                 <domain name="_" />
         </request>
-</manifest>
+</manifest>
\ No newline at end of file
old mode 100755 (executable)
new mode 100644 (file)
old mode 100755 (executable)
new mode 100644 (file)
old mode 100755 (executable)
new mode 100644 (file)
old mode 100755 (executable)
new mode 100644 (file)
diff --git a/packaging/privacy-guard-setting-devel.manifest b/packaging/privacy-guard-setting-devel.manifest
new file mode 100644 (file)
index 0000000..c00c25b
--- /dev/null
@@ -0,0 +1,5 @@
+<manifest>
+        <request>
+                <domain name="_" />
+        </request>
+</manifest>
diff --git a/packaging/privacy-guard-setting.manifest b/packaging/privacy-guard-setting.manifest
new file mode 100644 (file)
index 0000000..c00c25b
--- /dev/null
@@ -0,0 +1,5 @@
+<manifest>
+        <request>
+                <domain name="_" />
+        </request>
+</manifest>
old mode 100755 (executable)
new mode 100644 (file)
old mode 100755 (executable)
new mode 100644 (file)
index 50123c9..726f6f1
@@ -1,5 +1,5 @@
 Name:           privacy-guard-server
-Version:        0.9.6
+Version:        0.9.7
 Release:        1
 License:        Apache-2.0
 Summary:        Privacy Management
@@ -9,12 +9,13 @@ 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
+Source1003:     privacy-guard-setting.manifest
+Source1004:     privacy-guard-setting-devel.manifest
+Source1005:     privacy-guard-client.manifest
+Source1006:     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)
@@ -49,6 +50,19 @@ Requires:       privacy-guard-server = %{version}
 %description -n privacy-guard-server-devel
 privacy-guard server devel
 
+%package -n privacy-guard-setting
+Summary:        Privacy Guard Setting
+
+%description -n privacy-guard-setting
+privacy-guard setting
+
+%package -n privacy-guard-setting-devel
+Summary:        Privacy Guard setting devel
+Requires:       privacy-guard-setting = %{version}
+
+%description -n privacy-guard-setting-devel
+Privacy Management(development files)
+
 %package -n privacy-guard-client
 Summary:        Privacy Guard Client
 Requires:       privacy-guard-server = %{version}
@@ -75,6 +89,8 @@ cp %{SOURCE1001} .
 cp %{SOURCE1002} .
 cp %{SOURCE1003} .
 cp %{SOURCE1004} .
+cp %{SOURCE1005} .
+cp %{SOURCE1006} .
 
 %build
 %{!?build_type:%define build_type "Release"}
@@ -115,6 +131,9 @@ chsmack -a System %{TZ_SYS_DB}/.privacy_guard.db-journal
 
 %postun -p /sbin/ldconfig
 
+%post -n privacy-guard-setting -p /sbin/ldconfig
+%postun -n privacy-guard-setting -p /sbin/ldconfig
+
 %post -n privacy-guard-client -p /sbin/ldconfig
 %postun -n privacy-guard-client -p /sbin/ldconfig
 
@@ -134,19 +153,36 @@ chsmack -a System %{TZ_SYS_DB}/.privacy_guard.db-journal
 %files -n privacy-guard-server-devel
 %{_libdir}/pkgconfig/privacy-guard-server.pc
 
+%files -n privacy-guard-setting
+%defattr(-,root,root,-)
+%license  LICENSE.APLv2
+%manifest privacy-guard-setting.manifest
+%{_libdir}/libprivacy-guard-setting.so*
+%{_sysconfdir}/package-manager/parserlib/libprivileges.so
+
+%files -n privacy-guard-setting-devel
+%defattr(-,root,root,-)
+%manifest privacy-guard-setting-devel.manifest
+%{_includedir}/privacy_guard/setting/*
+%{_includedir}/privacy_guard/privacy_guard_client_types.h
+%{_includedir}/privacy_guard/privacy_guard_client.h
+%{_libdir}/pkgconfig/privacy-guard-setting.pc
+
 %files -n privacy-guard-client
 %defattr(-,root,root,-)
 %license  LICENSE.APLv2
 %manifest privacy-guard-client.manifest
 %{_libdir}/libprivacy-guard-client.so*
-%{_sysconfdir}/package-manager/parserlib/libprivileges.so
 
 %files -n privacy-guard-client-devel
 %defattr(-,root,root,-)
 %manifest privacy-guard-client-devel.manifest
-%{_includedir}/*
+%{_includedir}/privacy_guard/client/*
+%{_includedir}/privacy_guard/privacy_guard_client_types.h
+%{_includedir}/privacy_guard/privacy_guard_dlp.h
 %{_libdir}/pkgconfig/privacy-guard-client.pc
 
 %files -n tc-privacy-guard
 %{_bindir}/tc-privacy-guard
 %{_bindir}/tc-dlp
+%{_bindir}/tc-ahocorasick
old mode 100755 (executable)
new mode 100644 (file)
index d2a47a2..650f2f2
@@ -18,7 +18,7 @@ INCLUDE_DIRECTORIES(
     /usr/include/pkgmgr
     /usr/include/package_manager
     /usr/include/dlog
-    "${CMAKE_SOURCE_DIR}/client/inc/"
+    "${CMAKE_SOURCE_DIR}/setting/inc/"
     "${CMAKE_SOURCE_DIR}/common/inc/"
     "${CMAKE_SOURCE_DIR}/include/"
     )
@@ -43,12 +43,12 @@ 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)
+ADD_DEPENDENCIES(${this_target} privacy-guard-setting)
 ## SET LINKER FLAGS
 SET(CMAKE_SHARED_LINKER_FLAGS -Wl,--no-undefined)
 
 TARGET_LINK_LIBRARIES(${this_target} ${pkg_LDFLAGS} ${pkg_LIBRARIES})
-TARGET_LINK_LIBRARIES(${this_target} "-lprivacy-guard-client" "-L../client" )
+TARGET_LINK_LIBRARIES(${this_target} "-lprivacy-guard-setting" "-L../setting" )
 
 ADD_CUSTOM_COMMAND(TARGET ${this_target}
     POST_BUILD
old mode 100755 (executable)
new mode 100644 (file)
index eefcd13..5530410
@@ -30,10 +30,8 @@ static const xmlChar _NODE_PRIVILEGE[]               = "privilege";
 
 void destroy_char_list(char** ppList, int size)
 {
-       int i = 0;
-
        if (ppList) {
-               for (i = 0; i < size; ++i) {
+               for (int i = 0; i < size; ++i) {
                        if (ppList[i])
                                free(ppList[i]);
                }
@@ -42,14 +40,14 @@ void destroy_char_list(char** ppList, int size)
 }
 
 extern "C"
-__attribute__ ((visibility("default")))
+__attribute__((visibility("default")))
 int PKGMGR_PARSER_PLUGIN_PRE_INSTALL(const char *packageId)
 {
        return 0;
 }
 
 extern "C"
-__attribute__ ((visibility("default")))
+__attribute__((visibility("default")))
 int PKGMGR_PARSER_PLUGIN_INSTALL(xmlDocPtr docPtr, const char* packageId)
 {
        if (packageId == NULL) {
@@ -86,7 +84,7 @@ int PKGMGR_PARSER_PLUGIN_INSTALL(xmlDocPtr docPtr, const char* packageId)
                                LOGE("Failed to get privilege value.");
                                return -EINVAL;
                        } else {
-                               privilegeList.push_back(std::string( reinterpret_cast<char*> (pPrivilege)));
+                               privilegeList.push_back(std::string(reinterpret_cast<char*> (pPrivilege)));
                                LOGD("Succeeded to get privilege value.");
                        }
                }
@@ -145,21 +143,21 @@ int PKGMGR_PARSER_PLUGIN_INSTALL(xmlDocPtr docPtr, const char* packageId)
 }
 
 extern "C"
-__attribute__ ((visibility("default")))
+__attribute__((visibility("default")))
 int PKGMGR_PARSER_PLUGIN_POST_INSTALL(const char *packageId)
 {
        return 0;
 }
 
 extern "C"
-__attribute__ ((visibility("default")))
+__attribute__((visibility("default")))
 int PKGMGR_PARSER_PLUGIN_PRE_UNINSTALL(const char *packageId)
 {
        return 0;
 }
 
 extern "C"
-__attribute__ ((visibility("default")))
+__attribute__((visibility("default")))
 int PKGMGR_PARSER_PLUGIN_UNINSTALL(xmlDocPtr docPtr, const char* packageId)
 {
        if (packageId == NULL) {
@@ -185,21 +183,21 @@ int PKGMGR_PARSER_PLUGIN_UNINSTALL(xmlDocPtr docPtr, const char* packageId)
 }
 
 extern "C"
-__attribute__ ((visibility("default")))
+__attribute__((visibility("default")))
 int PKGMGR_PARSER_PLUGIN_POST_UNINSTALL(const char *packageId)
 {
        return 0;
 }
 
 extern "C"
-__attribute__ ((visibility("default")))
+__attribute__((visibility("default")))
 int PKGMGR_PARSER_PLUGIN_PRE_UPGRADE(const char *packageId)
 {
        return 0;
 }
 
 extern "C"
-__attribute__ ((visibility("default")))
+__attribute__((visibility("default")))
 int PKGMGR_PARSER_PLUGIN_UPGRADE(xmlDocPtr docPtr, const char* packageId)
 {
        if (packageId == NULL) {
@@ -223,7 +221,7 @@ int PKGMGR_PARSER_PLUGIN_UPGRADE(xmlDocPtr docPtr, const char* packageId)
 }
 
 extern "C"
-__attribute__ ((visibility("default")))
+__attribute__((visibility("default")))
 int PKGMGR_PARSER_PLUGIN_POST_UPGRADE(const char *packageId)
 {
        return 0;
diff --git a/privacy-guard-setting.pc.in b/privacy-guard-setting.pc.in
new file mode 100644 (file)
index 0000000..54ee982
--- /dev/null
@@ -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:
old mode 100755 (executable)
new mode 100644 (file)
index 64e0671..a5d60ec 100755 (executable)
@@ -9,7 +9,7 @@ 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
+pkg_check_modules(pkgs REQUIRED dlog sqlite3 dbus-1 dbus-glib-1 pkgmgr-info capi-system-info
        libtzplatform-config security-privilege-manager cynara-monitor security-manager aul
        capi-telephony capi-network-connection capi-network-wifi capi-location-manager
        contacts-service2)
old mode 100755 (executable)
new mode 100644 (file)
index 432423d..7c3ce01 100644 (file)
@@ -66,7 +66,7 @@ public:
        /**
         * @brief start the thread which returns real time updated data
         *
-        * @return              true if the thread started without error
+        * @return              true if the thread started without error
         * @see stop()
         * @since Tizen 3.0
         */
@@ -89,6 +89,7 @@ private:
        void loadMyProfile(void);
        void loadInfo(const int userId);
        static void *startLocation(void *_this);
+       bool waitForModemReady(const telephony_h handle) const;
 
        connection_h m_connection;
        std::list<char *> m_imei_list;
index a121f0d..028c6b4 100644 (file)
@@ -41,11 +41,23 @@ public:
        /**
         * @brief add a new client to list of clients to inform about rule changes
         * @param[in] pId                       The process id of the client to be added
+        * @param[in] userId            The user id of the client to be added
+        * @param[in] appId                     The buffer to write the application id
         *
         * @return the result of operation (ERRORCODE : success, ....)
         * @since Tizen 3.0
         */
-       int addDlpClient(int pId);
+       int addDlpClient(int pId, int userId, char *appId);
+
+       /**
+        * @brief get the application info for the pid
+        * @param[in] pId                       The process id of the client look of info
+        * @param[out] app_info         The privacy_semaphore_app_info_s struct related to pid
+        *
+        * @return the result of operation (ERRORCODE : success, ....)
+        * @since Tizen 3.0
+        */
+        int getAppInfo(int pId, privacy_semaphore_app_info_s **app_info);
 
        /**
         * @brief send notification to all registered clients that a rule may have changed
old mode 100755 (executable)
new mode 100644 (file)
old mode 100755 (executable)
new mode 100644 (file)
index a637523..9cfd397 100755 (executable)
@@ -223,14 +223,13 @@ public:
        /**
         * @brief get the list of current rules
         * @param[in] userId                            The user ID to get the rules for
-        * @param[in] AppId                             The application name (or empty string)
         * @param[in] pId                               The process ID, to be added to the list of rule change notification clients
         * @param[out] rules                            The rules which were retrieved
         *
         * @return the result of operation (ERRORCODE : success, ....)
         * @since Tizen 4.0
         */
-       int PgGetDlpCurrentRules(const int userId, const char *AppId, const int pId, std::list<current_rules_s> &rules);
+       int PgGetDlpCurrentRules(const int userId, const int pId, std::list<current_rules_s> &rules);
 
        /**
         * @brief retrieve the list of email addresses for the specified user
index cac730e..1fa0c82 100755 (executable)
 
 class PrivacyInfoService {
 private:
-       inline static std::string getInterfaceName(void)
+       static inline std::string getInterfaceName(void)
        {
                return "PrivacyInfoService";
        }
 
 public:
-static void registerCallbacks(SocketService* pSocketService) {
+static void registerCallbacks(SocketService* pSocketService)
+{
        pSocketService->registerServiceCallback(getInterfaceName(), std::string("PgAddPrivacyAccessLog"), PgAddPrivacyAccessLog);
        pSocketService->registerServiceCallback(getInterfaceName(), std::string("PgAddMonitorPolicy"), PgAddMonitorPolicy);
        pSocketService->registerServiceCallback(getInterfaceName(), std::string("PgDeleteLogsByPackageId"), PgDeleteLogsByPackageId);
old mode 100755 (executable)
new mode 100644 (file)
old mode 100755 (executable)
new mode 100644 (file)
old mode 100755 (executable)
new mode 100644 (file)
index dbd19d3..e5ed495
@@ -129,8 +129,6 @@ CynaraService::getEntriesThread(void* pData)
 {
        //PG_LOGD("Running get entries thread");
 
-       int res = -1;
-
        pthread_detach(pthread_self());
        while (exit_flag == false) {
                if (monitor_entries) {
@@ -139,7 +137,7 @@ CynaraService::getEntriesThread(void* pData)
                }
 
                // returned when the cynara buffer is full or cynara_monitor_entries_flush() is called from another thread
-               res = cynara_monitor_entries_get(p_cynara_monitor, &monitor_entries);
+               int res = cynara_monitor_entries_get(p_cynara_monitor, &monitor_entries);
                if(res != CYNARA_API_SUCCESS){
                        PG_LOGE("cynara_monitor_entries_get() is failed. [%d]", res);
 #if defined(USE_PTHREAD_WAITING)
@@ -178,21 +176,20 @@ int
 CynaraService::updateDb(cynara_monitor_entry **monitor_entries)
 {
        cynara_monitor_entry **entryIter = monitor_entries;
-       const char *user = NULL, *client = NULL, *privilege = NULL;
+       const char *user = NULL, *client = NULL;
        const timespec *timestamp = NULL;
        uid_t user_id;
        std::string privacyId;
        time_t date;
-       int res = -1;
        char *pkg_name = NULL, *app_name = NULL;
 
        while (*entryIter != nullptr) {
-               privilege = cynara_monitor_entry_get_privilege(*entryIter);
+               const char *privilege = cynara_monitor_entry_get_privilege(*entryIter);
                TryReturn(privilege != NULL, PRIV_GUARD_ERROR_SYSTEM_ERROR, , "Privilege Id in the entry is NULL");
 
                // change from privilege to privacy
                privacyId.clear();
-               res = PrivacyIdInfo::getPrivacyIdFromPrivilege(privilege, privacyId);
+               int res = PrivacyIdInfo::getPrivacyIdFromPrivilege(privilege, privacyId);
                //PG_LOGD("########## res: [%d] privilege: [%s] privacy: [%s]", res, privilege, privacyId.c_str());
                if (res != PRIV_GUARD_ERROR_NO_DATA) {
                        //PG_LOGD("#Privilege: [%s]", privilege);
@@ -251,7 +248,6 @@ CynaraService::updateDb(cynara_monitor_entry **monitor_entries)
 int
 CynaraService::stop(void)
 {
-       char buf[BUF_SIZE];
        int ret;
 
        // set thread exit condition
@@ -269,6 +265,8 @@ CynaraService::stop(void)
        }
 
        if((ret = pthread_kill(m_cynaraThread, m_signalToClose)) < 0) {
+               char buf[BUF_SIZE];
+
                PG_LOGE("pthread_kill(): %s", strerror_r(ret, buf, sizeof(buf)));
                return PRIV_GUARD_ERROR_IPC_ERROR;
        }
index 99c16cc..9c33e04 100644 (file)
@@ -23,6 +23,8 @@
 #include <sys/types.h>
 #include <signal.h>
 #include <errno.h>
+#include <aul.h>
+#include <pkgmgr-info.h>
 #include "DlpRuleChangeNotification.h"
 #include "Utils.h"
 
@@ -42,18 +44,17 @@ DlpRuleChangeNotification::getInstance(void)
 }
 
 int
-DlpRuleChangeNotification::addDlpClient(int pId)
+DlpRuleChangeNotification::addDlpClient(int pId, int userId, char *appId)
 {
        int res = PRIV_GUARD_ERROR_SUCCESS;
        bool first_request_by_pid = true;
-       char sem_name[sizeof(PRIVACY_SEM_INITVAL)+5];
-       char buf[BUF_SIZE];
 
        std::lock_guard<std::mutex> guard(m_singletonMutex);
        for (auto it = m_semaphore_list.begin(); it != m_semaphore_list.end();) {
                if (it->pid == pId) {
                        // Process found, no need to add it to sem list
                        first_request_by_pid = false;
+                       strncpy(appId, it->app_info.application_id, LEN_APPLICATION_ID);
                } else {
                        // Just checking if the process still exists, no signal is sent
                        if (kill(it->pid, 0) == -1 && errno == ESRCH) {
@@ -67,11 +68,56 @@ DlpRuleChangeNotification::addDlpClient(int pId)
        }
 
        if (first_request_by_pid) {
+               char sem_name[sizeof(PRIVACY_SEM_INITVAL)+5];
                // First request from process, to add it to sem list
                snprintf(sem_name, sizeof(PRIVACY_SEM_INITVAL)+5, PRIVACY_SEM_INITVAL, pId);
                privacy_semaphore_s ps;
+               pkgmgrinfo_appinfo_h appinfo = NULL;
+               pkgmgrinfo_pkginfo_h pkginfo = NULL;
+               char *data = NULL;
+
+               // load application ID
+               ps.app_info.application_id[0] = '\0';
+               int ret = aul_app_get_appid_bypid(pId, ps.app_info.application_id, LEN_APPLICATION_ID);
+               if (ret == 0) {
+                       // load application info
+                       ret = pkgmgrinfo_appinfo_get_usr_appinfo(ps.app_info.application_id, userId, &appinfo);
+                       if (ret == 0) {
+                               // load application name
+                               ret = pkgmgrinfo_appinfo_get_label(appinfo, &data);
+                               if (ret == 0)
+                                       pg_strlcpy(ps.app_info.application_name, data, LEN_APPLICATION_NAME);
+
+                               // load package ID
+                               ret = pkgmgrinfo_appinfo_get_pkgid(appinfo, &data);
+                               if (ret == 0)
+                                       pg_strlcpy(ps.app_info.package_id, data, LEN_PACKAGE_ID);
+
+                               // load application icon
+                               ret = pkgmgrinfo_appinfo_get_icon(appinfo, &data);
+                               if (ret == 0)
+                                       pg_strlcpy(ps.app_info.application_icon, data, LEN_APPLICATION_ICON);
+
+                               // load package info
+                               ret = pkgmgrinfo_pkginfo_get_pkginfo(ps.app_info.package_id, &pkginfo);
+                               if (ret == 0) {
+                                       // load application version
+                                       ret = pkgmgrinfo_pkginfo_get_version(pkginfo, &data);
+                                       if (ret == 0)
+                                               pg_strlcpy(ps.app_info.application_version, data, LEN_APPLICATION_VERSION);
+
+                                       pkgmgrinfo_pkginfo_destroy_pkginfo(pkginfo);
+                               }
+
+                               pkgmgrinfo_appinfo_destroy_appinfo(appinfo);
+                       }
+               }
+
+               strncpy(appId, ps.app_info.application_id, LEN_APPLICATION_ID);
                ps.sem = sem_open(sem_name, 0);
                if (ps.sem == SEM_FAILED) {
+                       char buf[BUF_SIZE];
+
                        PG_LOGE("errro opening sem: %s  - %s", sem_name, strerror_r(errno, buf, sizeof(buf)));
                        res = errno;
                } else {
@@ -84,6 +130,17 @@ DlpRuleChangeNotification::addDlpClient(int pId)
 }
 
 int
+DlpRuleChangeNotification::getAppInfo(int pId, privacy_semaphore_app_info_s **app_info) {
+       for (auto &it: m_semaphore_list) {
+               if (it.pid == pId) {
+                       *app_info = &(it.app_info);
+                       return PRIV_GUARD_ERROR_SUCCESS;
+               }
+       }
+       return PRIV_GUARD_ERROR_NO_DATA;
+}
+
+int
 DlpRuleChangeNotification::notifyDlpClients()
 {
        char buf[BUF_SIZE];
old mode 100755 (executable)
new mode 100644 (file)
index d5ed496..fcd8bd6
@@ -92,7 +92,7 @@ PrivacyGuardDaemon::start(void)
 
        PG_LOGI("Starting DLP");
        res = DlpPrivacyInfoData::getInstance()->start();
-       if (res != true)
+       if ((bool) res != true)
                PG_LOGE("Can not start DLP");
 
        return res;
index 02efe5c..6ca9edd 100644 (file)
@@ -78,8 +78,7 @@ PrivacyGuardDb::initialize(void)
 void
 PrivacyGuardDb::openSqliteDB(void)
 {
-       int res = -1;
-       res = sqlite3_open_v2(PRIVACY_DB_PATH, &m_sqlHandler, SQLITE_OPEN_READWRITE, NULL);
+       int res = sqlite3_open_v2(PRIVACY_DB_PATH, &m_sqlHandler, SQLITE_OPEN_READWRITE, NULL);
        if(res == SQLITE_OK) {
                PG_LOGI("monitor db is opened successfully");
                //sqlite3_wal_autocheckpoint(m_sqlHandler, 1);
@@ -97,11 +96,9 @@ PrivacyGuardDb::PgAddPrivacyAccessLog(const int userId, const std::string packag
                return PRIV_GUARD_ERROR_INVALID_PARAMETER;
        }
 
-       int res = -1;
-
        // check monitor policy using userId, packageId, privacyId
        int monitorPolicy;
-       res = PgGetMonitorPolicy(userId, packageId, privacyId, monitorPolicy);
+       int res = PgGetMonitorPolicy(userId, packageId, privacyId, monitorPolicy);
        TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, , "PgGetMonitorPolicy is failed: [%d]", res);
        if (monitorPolicy == 0) {
                PG_LOGD("Monitor Policy is 0. So skip it. UserId:[%d], PrivacyId:[%s], PackageId:[%s], Policy:[%d]", userId, privacyId.c_str(), packageId.c_str(), monitorPolicy);
@@ -257,7 +254,6 @@ PrivacyGuardDb::PgAddMonitorPolicy(const int userId, const std::string packageId
 int
 PrivacyGuardDb::PgCheckPrivacyPackage(const int userId, const std::string packageId, bool &isPrivacyPackage)
 {
-       int res = -1;
        char buf[BUF_SIZE];
 
        snprintf(buf, BUF_SIZE, "SELECT COUNT(*) FROM MonitorPolicy WHERE USER_ID=? AND PKG_ID=?");
@@ -266,7 +262,7 @@ PrivacyGuardDb::PgCheckPrivacyPackage(const int userId, const std::string packag
        ///////////////////////////////////////////////////
        // prepare privacy monitor policy for global apps
        ///////////////////////////////////////////////////
-       res = prepareGlobalPackagePolicy(userId);
+       int res = prepareGlobalPackagePolicy(userId);
        TryCatchResLogReturn(res == PRIV_GUARD_ERROR_SUCCESS, m_dbMutex.unlock();, PRIV_GUARD_ERROR_INTERNAL_ERROR, "PgPrepareGlobalPackagePolicy: %d", res);
 
        m_dbMutex.lock();
@@ -297,7 +293,7 @@ PrivacyGuardDb::PgCheckPrivacyPackage(const int userId, const std::string packag
        int count = -1;
 
        // step
-       if ((res = sqlite3_step(m_stmt)) == SQLITE_ROW) {
+       if (sqlite3_step(m_stmt) == SQLITE_ROW) {
                count = sqlite3_column_int(m_stmt, 0);
        }
 
@@ -484,14 +480,13 @@ PrivacyGuardDb::PgDeleteMonitorPolicyByPackageId(const std::string packageId)
 int
 PrivacyGuardDb::PgForeachTotalPrivacyCountOfPackage(const int userId, const int startDate, const int endDate, std::list < std::pair < std::string, int > >& packageInfoList)
 {
-       int res = -1;
        char buf[BUF_SIZE];
        sqlite3_stmt* infoStmt;
 
        ///////////////////////////////////////////////////
        // prepare privacy monitor policy for global apps
        ///////////////////////////////////////////////////
-       res = prepareGlobalPackagePolicy(userId);
+       int res = prepareGlobalPackagePolicy(userId);
        TryCatchResLogReturn(res == PRIV_GUARD_ERROR_SUCCESS, m_dbMutex.unlock();, PRIV_GUARD_ERROR_INTERNAL_ERROR, "PgPrepareGlobalPackagePolicy: %d", res);
 
        // [CYNARA] Flush Entries
@@ -577,13 +572,12 @@ PrivacyGuardDb::PgForeachTotalPrivacyCountOfPackage(const int userId, const int
 int
 PrivacyGuardDb::PgForeachTotalPrivacyCountOfPrivacy(const int userId, const int startDate, const int endDate, std::list < std::pair < std::string, int > >& privacyInfoList)
 {
-       int res = -1;
        char buf[BUF_SIZE];
 
        ///////////////////////////////////////////////////
        // prepare privacy monitor policy for global apps
        ///////////////////////////////////////////////////
-       res = prepareGlobalPackagePolicy(userId);
+       int res = prepareGlobalPackagePolicy(userId);
        TryCatchResLogReturn(res == PRIV_GUARD_ERROR_SUCCESS, m_dbMutex.unlock();, PRIV_GUARD_ERROR_INTERNAL_ERROR, "PgPrepareGlobalPackagePolicy: %d", res);
 
        // [CYNARA] Flush Entries
@@ -655,14 +649,13 @@ 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;
        sqlite3_stmt* infoStmt;
        char buf[BUF_SIZE];
 
        ///////////////////////////////////////////////////
        // prepare privacy monitor policy for global apps
        ///////////////////////////////////////////////////
-       res = prepareGlobalPackagePolicy(userId);
+       int res = prepareGlobalPackagePolicy(userId);
        TryCatchResLogReturn(res == PRIV_GUARD_ERROR_SUCCESS, m_dbMutex.unlock();, PRIV_GUARD_ERROR_INTERNAL_ERROR, "PgPrepareGlobalPackagePolicy: %d", res);
 
        // [CYNARA] Flush Entries
@@ -756,13 +749,12 @@ 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;
        char buf[BUF_SIZE];
 
        ///////////////////////////////////////////////////
        // prepare privacy monitor policy for global apps
        ///////////////////////////////////////////////////
-       res = prepareGlobalPackagePolicy(userId);
+       int res = prepareGlobalPackagePolicy(userId);
        TryCatchResLogReturn(res == PRIV_GUARD_ERROR_SUCCESS, m_dbMutex.unlock();, PRIV_GUARD_ERROR_INTERNAL_ERROR, "PgPrepareGlobalPackagePolicy: %d", res);
 
        // [CYNARA] Flush Entries
@@ -835,13 +827,12 @@ PrivacyGuardDb::PgForeachPrivacyCountByPackageId(const int userId, const int sta
 int
 PrivacyGuardDb::PgGetMonitorPolicy(const int userId, const std::string packageId, const std::string privacyId, int& monitorPolicy)
 {
-       int res = -1;
        char buf[BUF_SIZE];
 
        ///////////////////////////////////////////////////
        // prepare privacy monitor policy for global apps
        ///////////////////////////////////////////////////
-       res = prepareGlobalPackagePolicy(userId);
+       int res = prepareGlobalPackagePolicy(userId);
        TryCatchResLogReturn(res == PRIV_GUARD_ERROR_SUCCESS, m_dbMutex.unlock();, PRIV_GUARD_ERROR_INTERNAL_ERROR, "PgPrepareGlobalPackagePolicy: %d", res);
 
        snprintf(buf, BUF_SIZE, "SELECT MONITOR_POLICY FROM MonitorPolicy WHERE USER_ID=? AND PKG_ID=? AND PRIVACY_ID=?");
@@ -877,7 +868,7 @@ PrivacyGuardDb::PgGetMonitorPolicy(const int userId, const std::string packageId
 
        // step
        monitorPolicy = 0;
-       if ((res = sqlite3_step(m_stmt)) == SQLITE_ROW) {
+       if (sqlite3_step(m_stmt) == SQLITE_ROW) {
                monitorPolicy = sqlite3_column_int(m_stmt, 0);
        }
 
@@ -945,13 +936,12 @@ PrivacyGuardDb::PgGetAllMonitorPolicy(std::list < std::pair < std::string, int >
 int
 PrivacyGuardDb::PgForeachMonitorPolicyByPackageId(const int userId, const std::string packageId, std::list <privacy_data_s>& privacyInfoList)
 {
-       int res = -1;
        char buf[BUF_SIZE];
 
        ///////////////////////////////////////////////////
        // prepare privacy monitor policy for global apps
        ///////////////////////////////////////////////////
-       res = prepareGlobalPackagePolicy(userId);
+       int res = prepareGlobalPackagePolicy(userId);
        TryCatchResLogReturn(res == PRIV_GUARD_ERROR_SUCCESS, m_dbMutex.unlock();, PRIV_GUARD_ERROR_INTERNAL_ERROR, "PgPrepareGlobalPackagePolicy: %d", res);
 
        snprintf(buf, BUF_SIZE, "SELECT DISTINCT PRIVACY_ID, MONITOR_POLICY FROM MonitorPolicy WHERE USER_ID=? AND PKG_ID=?");
@@ -983,7 +973,7 @@ PrivacyGuardDb::PgForeachMonitorPolicyByPackageId(const int userId, const std::s
        TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_GUARD_ERROR_DB_ERROR, "sqlite3_bind_text : %d", res);
 
        // step
-       while ((res = sqlite3_step(m_stmt)) == SQLITE_ROW) {
+       while (sqlite3_step(m_stmt) == SQLITE_ROW) {
                char* tmp_data = (char*)sqlite3_column_text(m_stmt, 0);
                if(tmp_data == NULL) {
                        continue;
@@ -1006,7 +996,6 @@ PrivacyGuardDb::PgForeachMonitorPolicyByPackageId(const int userId, const std::s
 int
 PrivacyGuardDb::PgForeachPackageIdUsingPrivacy(const int userId, std::list < std::string > &packageList)
 {
-       int res = -1;
        char buf[BUF_SIZE];
 
        snprintf(buf, BUF_SIZE, "SELECT DISTINCT PKG_ID FROM MonitorPolicy WHERE USER_ID=?");
@@ -1015,7 +1004,7 @@ PrivacyGuardDb::PgForeachPackageIdUsingPrivacy(const int userId, std::list < std
        ///////////////////////////////////////////////////
        // prepare privacy monitor policy for global apps
        ///////////////////////////////////////////////////
-       res = prepareGlobalPackagePolicy(userId);
+       int res = prepareGlobalPackagePolicy(userId);
        TryCatchResLogReturn(res == PRIV_GUARD_ERROR_SUCCESS, m_dbMutex.unlock();, PRIV_GUARD_ERROR_INTERNAL_ERROR, "PgPrepareGlobalPackagePolicy: %d", res);
 
        m_dbMutex.lock();
@@ -1041,7 +1030,7 @@ PrivacyGuardDb::PgForeachPackageIdUsingPrivacy(const int userId, std::list < std
        TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_GUARD_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res);
 
        // step
-       while ((res = sqlite3_step(m_stmt)) == SQLITE_ROW) {
+       while (sqlite3_step(m_stmt) == SQLITE_ROW) {
                char* p_data = (char*)sqlite3_column_text(m_stmt, 0);
                if(p_data == NULL) {
                        continue;
@@ -1140,7 +1129,7 @@ PrivacyGuardDb::prepareGlobalPackagePolicy(const int userId)
        TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock();, PRIV_GUARD_ERROR_DB_ERROR, "sqlite3_prepare_v2 : %d", res);
 
        // step
-       while ((res = sqlite3_step(m_stmt)) == SQLITE_ROW) {
+       while (sqlite3_step(m_stmt) == SQLITE_ROW) {
                char *package_id = (char*)sqlite3_column_text(m_stmt, 0);
                char *privacy_id = (char*)sqlite3_column_text(m_stmt, 1);
                if(package_id == NULL || privacy_id == NULL) {
@@ -1180,7 +1169,6 @@ PrivacyGuardDb::prepareGlobalPackagePolicy(const int userId)
 int
 PrivacyGuardDb::PgForeachPackageInfoByPrivacyId(const int userId, const std::string privacyId, std::list < package_data_s > &packageInfoList)
 {
-       int res = -1;
        sqlite3_stmt* infoStmt;
        time_t start_date, today_midnight, end_date;
        struct tm date;
@@ -1189,7 +1177,7 @@ PrivacyGuardDb::PgForeachPackageInfoByPrivacyId(const int userId, const std::str
        ///////////////////////////////////////////////////
        // prepare privacy monitor policy for global apps
        ///////////////////////////////////////////////////
-       res = prepareGlobalPackagePolicy(userId);
+       int res = prepareGlobalPackagePolicy(userId);
        TryCatchResLogReturn(res == PRIV_GUARD_ERROR_SUCCESS, m_dbMutex.unlock();, PRIV_GUARD_ERROR_INTERNAL_ERROR, "PgPrepareGlobalPackagePolicy: %d", res);
 
 
@@ -1305,7 +1293,6 @@ PrivacyGuardDb::PgForeachPackageInfoByPrivacyId(const int userId, const std::str
 int
 PrivacyGuardDb::PgUpdateMonitorPolicy(const int userId, const std::string packageId, const std::string privacyId, const int monitorPolicy)
 {
-       int res = -1;
        char buf[BUF_SIZE];
 
        snprintf(buf, BUF_SIZE, "UPDATE MonitorPolicy SET MONITOR_POLICY=? WHERE USER_ID=? AND PKG_ID=? AND PRIVACY_ID=?");
@@ -1314,7 +1301,7 @@ PrivacyGuardDb::PgUpdateMonitorPolicy(const int userId, const std::string packag
        ///////////////////////////////////////////////////
        // prepare privacy monitor policy for global apps
        ///////////////////////////////////////////////////
-       res = prepareGlobalPackagePolicy(userId);
+       int res = prepareGlobalPackagePolicy(userId);
        TryCatchResLogReturn(res == PRIV_GUARD_ERROR_SUCCESS, m_dbMutex.unlock();, PRIV_GUARD_ERROR_INTERNAL_ERROR, "PgPrepareGlobalPackagePolicy: %d", res);
 
        m_dbMutex.lock();
@@ -1362,14 +1349,12 @@ PrivacyGuardDb::PgUpdateMonitorPolicy(const int userId, const std::string packag
 int
 PrivacyGuardDb::PgAddMainMonitorPolicy(const int userId)
 {
-       int res = -1;
-
        static const std::string QUERY_INSERT = std::string("INSERT INTO MainMonitorPolicy(USER_ID) VALUES(?)");
 
        ///////////////////////////////////////////////////
        // prepare privacy monitor policy for global apps
        ///////////////////////////////////////////////////
-       res = prepareGlobalPackagePolicy(userId);
+       int res = prepareGlobalPackagePolicy(userId);
        TryCatchResLogReturn(res == PRIV_GUARD_ERROR_SUCCESS, m_dbMutex.unlock();, PRIV_GUARD_ERROR_INTERNAL_ERROR, "PgPrepareGlobalPackagePolicy: %d", res);
 
        m_dbMutex.lock();
@@ -1410,7 +1395,6 @@ PrivacyGuardDb::PgAddMainMonitorPolicy(const int userId)
 int
 PrivacyGuardDb::PgUpdateMainMonitorPolicy(const int userId, const int mainMonitorPolicy)
 {
-       int res = -1;
        char buf[BUF_SIZE];
 
        snprintf(buf, BUF_SIZE, "UPDATE MainMonitorPolicy SET MAIN_MONITOR_POLICY=? WHERE USER_ID=? ");
@@ -1419,7 +1403,7 @@ PrivacyGuardDb::PgUpdateMainMonitorPolicy(const int userId, const int mainMonito
        ///////////////////////////////////////////////////
        // prepare privacy monitor policy for global apps
        ///////////////////////////////////////////////////
-       res = prepareGlobalPackagePolicy(userId);
+       int res = prepareGlobalPackagePolicy(userId);
        TryCatchResLogReturn(res == PRIV_GUARD_ERROR_SUCCESS, m_dbMutex.unlock();, PRIV_GUARD_ERROR_INTERNAL_ERROR, "PgPrepareGlobalPackagePolicy: %d", res);
 
        m_dbMutex.lock();
@@ -1466,7 +1450,6 @@ PrivacyGuardDb::PgUpdateMainMonitorPolicy(const int userId, const int mainMonito
 int
 PrivacyGuardDb::PgGetMainMonitorPolicy(const int userId, int &mainMonitorPolicy)
 {
-       int res = -1;
        char buf[BUF_SIZE];
 
        snprintf(buf, BUF_SIZE, "SELECT MAIN_MONITOR_POLICY FROM MainMonitorPolicy WHERE USER_ID=?");
@@ -1475,7 +1458,7 @@ PrivacyGuardDb::PgGetMainMonitorPolicy(const int userId, int &mainMonitorPolicy)
        ///////////////////////////////////////////////////
        // prepare privacy monitor policy for global apps
        ///////////////////////////////////////////////////
-       res = prepareGlobalPackagePolicy(userId);
+       int res = prepareGlobalPackagePolicy(userId);
        TryCatchResLogReturn(res == PRIV_GUARD_ERROR_SUCCESS, m_dbMutex.unlock();, PRIV_GUARD_ERROR_INTERNAL_ERROR, "PgPrepareGlobalPackagePolicy: %d", res);
 
        m_dbMutex.lock();
@@ -1520,14 +1503,12 @@ PrivacyGuardDb::PgGetMainMonitorPolicy(const int userId, int &mainMonitorPolicy)
 int
 PrivacyGuardDb::PgDeleteMainMonitorPolicyByUserId(const int userId)
 {
-       int res = -1;
-
        static const std::string QUERY_DELETE = std::string("DELETE FROM MainMonitorPolicy WHERE USER_ID=?");
 
        ///////////////////////////////////////////////////
        // prepare privacy monitor policy for global apps
        ///////////////////////////////////////////////////
-       res = prepareGlobalPackagePolicy(userId);
+       int res = prepareGlobalPackagePolicy(userId);
        TryCatchResLogReturn(res == PRIV_GUARD_ERROR_SUCCESS, m_dbMutex.unlock();, PRIV_GUARD_ERROR_INTERNAL_ERROR, "PgPrepareGlobalPackagePolicy: %d", res);
 
        m_dbMutex.lock();
@@ -1578,6 +1559,11 @@ PrivacyGuardDb::PgAddLeakLog(leak_log_insert_common_data_s &data, const std::lis
        const char *insertl = "INSERT INTO DlpLeakLog(REQUEST_ID, PATTERN_ID, ACTION, LEAK_OFFSET, LEAK_LEN) "
                              "VALUES(?, ?, ?, ?, ?)";
 
+       privacy_semaphore_app_info_s *app_info;
+       if(DlpRuleChangeNotification::getInstance() == NULL || PRIV_GUARD_ERROR_SUCCESS !=
+               DlpRuleChangeNotification::getInstance()->getAppInfo(data.pid, &app_info))
+               return PRIV_GUARD_ERROR_DB_ERROR;
+
        m_dbMutex.lock();
 
        // initialize
@@ -1604,19 +1590,19 @@ PrivacyGuardDb::PgAddLeakLog(leak_log_insert_common_data_s &data, const std::lis
        res = sqlite3_bind_int(m_stmt, 2, time(NULL));
        TryCatchResLogReturn(res == SQLITE_OK, sqlite3_finalize(m_stmt); m_dbMutex.unlock(), PRIV_GUARD_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res);
 
-       res = sqlite3_bind_text(m_stmt, 3, data.application_name, -1, SQLITE_TRANSIENT);
+       res = sqlite3_bind_text(m_stmt, 3, app_info->application_name, -1, SQLITE_TRANSIENT);
        TryCatchResLogReturn(res == SQLITE_OK, sqlite3_finalize(m_stmt); m_dbMutex.unlock(), PRIV_GUARD_ERROR_DB_ERROR, "sqlite3_bind_text : %d", res);
 
-       res = sqlite3_bind_text(m_stmt, 4, data.application_icon, -1, SQLITE_TRANSIENT);
+       res = sqlite3_bind_text(m_stmt, 4, app_info->application_icon, -1, SQLITE_TRANSIENT);
        TryCatchResLogReturn(res == SQLITE_OK, sqlite3_finalize(m_stmt); m_dbMutex.unlock(), PRIV_GUARD_ERROR_DB_ERROR, "sqlite3_bind_text : %d", res);
 
-       res = sqlite3_bind_text(m_stmt, 5, data.application_id, -1, SQLITE_TRANSIENT);
+       res = sqlite3_bind_text(m_stmt, 5, app_info->application_id, -1, SQLITE_TRANSIENT);
        TryCatchResLogReturn(res == SQLITE_OK, sqlite3_finalize(m_stmt); m_dbMutex.unlock(), PRIV_GUARD_ERROR_DB_ERROR, "sqlite3_bind_text : %d", res);
 
-       res = sqlite3_bind_text(m_stmt, 6, data.application_version, -1, SQLITE_TRANSIENT);
+       res = sqlite3_bind_text(m_stmt, 6, app_info->application_version, -1, SQLITE_TRANSIENT);
        TryCatchResLogReturn(res == SQLITE_OK, sqlite3_finalize(m_stmt); m_dbMutex.unlock(), PRIV_GUARD_ERROR_DB_ERROR, "sqlite3_bind_text : %d", res);
 
-       res = sqlite3_bind_text(m_stmt, 7, data.package_id, -1, SQLITE_TRANSIENT);
+       res = sqlite3_bind_text(m_stmt, 7, app_info->package_id, -1, SQLITE_TRANSIENT);
        TryCatchResLogReturn(res == SQLITE_OK, sqlite3_finalize(m_stmt); m_dbMutex.unlock(), PRIV_GUARD_ERROR_DB_ERROR, "sqlite3_bind_text : %d", res);
 
        res = sqlite3_bind_text(m_stmt, 8, data.destination, -1, SQLITE_TRANSIENT);
@@ -1926,7 +1912,6 @@ int
 PrivacyGuardDb::PgGetLeakLogDetails(int userId, int logId, leak_log_get_detail_data_s &logDetail)
 {
        int res = -1;
-       int fragment_offset;
        const char *query = "SELECT L.ACTION, RE.APP_ID, RE.APP_NAME, RE.APP_VERSION, RE.APP_ICON, RE.PKG_ID, " \
                                                "RE.DESTINATION, P.NAME, P.CATEGORY_ID, LENGTH(CAST(RE.RAW_PACKET AS BLOB)), "                          \
                                                " CAST(RE.RAW_PACKET AS BLOB), L.LEAK_OFFSET, "                                                                                 \
@@ -1957,6 +1942,8 @@ PrivacyGuardDb::PgGetLeakLogDetails(int userId, int logId, leak_log_get_detail_d
 
        // step
        if (sqlite3_step(m_stmt) == SQLITE_ROW) {
+               int fragment_offset;
+
                logDetail.action = (PgDlpAction)sqlite3_column_int(m_stmt, 0);
                pg_strlcpy(logDetail.application_id, (const char *)sqlite3_column_text(m_stmt, 1), LEN_APPLICATION_ID);
                pg_strlcpy(logDetail.application_name, (const char *)sqlite3_column_text(m_stmt, 2), LEN_APPLICATION_NAME);
@@ -1988,7 +1975,6 @@ PrivacyGuardDb::PgGetLeakLogDetails(int userId, int logId, leak_log_get_detail_d
 
 int PrivacyGuardDb::purgeUnusedDeletedPatterns()
 {
-       int patternId;
        const char *query1 = "SELECT ID FROM DlpPatterns WHERE STATE=?";
        const char *query2 = "SELECT ID FROM DlpLeakLog WHERE PATTERN_ID=?";
        const char *query3 = "DELETE FROM DlpPatterns WHERE ID=?";
@@ -2005,7 +1991,7 @@ int PrivacyGuardDb::purgeUnusedDeletedPatterns()
 
        while (sqlite3_step(m_stmt) == SQLITE_ROW) {
                // step through all patterns marked as STATE=PRIV_GUARD_DLP_PATTERN_STATE_DELETED
-               patternId = sqlite3_column_int(m_stmt, 0);
+               int patternId = sqlite3_column_int(m_stmt, 0);
 
                // query leak logs to see if any has a reference to the pattern. Otherwise we delete the pattern
                // prepare
@@ -2234,7 +2220,6 @@ PrivacyGuardDb::PgSetDlpProfile(const int userId, const dlp_profile_s &profile)
 {
        int res = -1;
        const char *query = "UPDATE DlpProfile SET ENABLED=?, PROFILE=?, KEEP_LOG_DAYS=? WHERE USER_ID=?";
-       const char *insert = "INSERT INTO DlpProfile(USER_ID, ENABLED, PROFILE, KEEP_LOG_DAYS) VALUES(?, ?, ?, ?)";
 
        m_dbMutex.lock();
 
@@ -2273,6 +2258,8 @@ PrivacyGuardDb::PgSetDlpProfile(const int userId, const dlp_profile_s &profile)
 
        // insert profile if not found
        if (sqlite3_changes(m_sqlHandler) == 0) {
+               const char *insert = "INSERT INTO DlpProfile(USER_ID, ENABLED, PROFILE, KEEP_LOG_DAYS) VALUES(?, ?, ?, ?)";
+
                sqlite3_finalize(m_stmt);
 
                // prepare
@@ -2353,14 +2340,17 @@ PrivacyGuardDb::PgGetDlpProfile(const int userId, dlp_profile_s &profile)
 }
 
 int
-PrivacyGuardDb::PgGetDlpCurrentRules(const int userId, const char *appId, const int pId, std::list<current_rules_s> &rules)
+PrivacyGuardDb::PgGetDlpCurrentRules(const int userId, const int pId, std::list<current_rules_s> &rules)
 {
        int res = -1;
        char query[256];
+       char appId[LEN_APPLICATION_ID] = {0};
        dlp_profile_s profile;
 
        if(DlpRuleChangeNotification::getInstance() != NULL)
-               DlpRuleChangeNotification::getInstance()->addDlpClient(pId);
+               DlpRuleChangeNotification::getInstance()->addDlpClient(pId, userId, appId);
+       else
+               return PRIV_GUARD_ERROR_DB_ERROR;
 
        // get current profile
        PgGetDlpProfile(userId, profile);
@@ -2432,7 +2422,7 @@ PrivacyGuardDb::PgGetDlpCurrentRules(const int userId, const char *appId, const
                        const PgDlpPatternType type = (PgDlpPatternType)sqlite3_column_int(m_stmt, 4);
 
                        // rule found, replace it
-                       for (it = rules.begin(); it != rules.end(); it++) {
+                       for (it = rules.begin(); it != rules.end(); ++it) {
                                if (it->pattern_id == pattern_id && it->type == type) {
                                        // replaces a general rule with an app specific one
                                        it->id = sqlite3_column_int(m_stmt, 0);
@@ -2466,7 +2456,6 @@ int
 PrivacyGuardDb::PgGetAccountEmails(const int userId, std::set<std::string> &emails)
 {
        sqlite3 *sqlHandler = NULL;
-       int res = -1;
        sqlite3_stmt *stmt;
        const char *email_query = "SELECT DISTINCT email_address FROM account";
        char account_uid_db_path[sizeof("%d/.account.db") + 8];
@@ -2476,7 +2465,7 @@ PrivacyGuardDb::PgGetAccountEmails(const int userId, std::set<std::string> &emai
        //////////////////////////////
 
        snprintf(account_uid_db_path, sizeof("%d/.account.db") + 8, "%d/.account.db", userId);
-       res = sqlite3_open_v2(tzplatform_mkpath(TZ_SYS_DB, account_uid_db_path), &sqlHandler, SQLITE_OPEN_READONLY, NULL);
+       int res = sqlite3_open_v2(tzplatform_mkpath(TZ_SYS_DB, account_uid_db_path), &sqlHandler, SQLITE_OPEN_READONLY, NULL);
        TryCatchResLogReturn(res == SQLITE_OK, ;, PRIV_GUARD_ERROR_DB_ERROR, "sqlite3_open_v2 : %d", res);
 
        // prepare
@@ -2586,16 +2575,13 @@ PrivacyGuardDb::PgAddDlpCustomRule(int userId, const custom_rule_s &rule)
 
 int PrivacyGuardDb::markUnusedPatterns(int ruleId, int newPatternId, sqlite3_stmt* update_stmt)
 {
-       int res = -1;
-       int patternId, patternCount;
+       int patternId;
 
        const char *query1 = "SELECT PATTERN_ID FROM DlpRules WHERE ID=?";
-       const char *query2 = "SELECT COUNT(*) FROM DlpRules WHERE PATTERN_ID=?";
-       const char *query3 = "UPDATE DlpPatterns SET STATE=? WHERE ID=? AND STATE=?";
 
        // get old PATTERN_ID
        // prepare
-       res = sqlite3_prepare_v2(m_sqlHandler, query1, -1, &m_stmt, NULL);
+       int res = sqlite3_prepare_v2(m_sqlHandler, query1, -1, &m_stmt, NULL);
        TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_GUARD_ERROR_DB_ERROR, "sqlite3_prepare_v2 : %d", res);
 
        // bind
@@ -2615,6 +2601,8 @@ int PrivacyGuardDb::markUnusedPatterns(int ruleId, int newPatternId, sqlite3_stm
        sqlite3_finalize(update_stmt);
 
        if (newPatternId != patternId) {
+               const char *query2 = "SELECT COUNT(*) FROM DlpRules WHERE PATTERN_ID=?";
+
                // rule was deleted or updated
                // get count of PATTERN_ID now
 
@@ -2630,10 +2618,12 @@ int PrivacyGuardDb::markUnusedPatterns(int ruleId, int newPatternId, sqlite3_stm
                res = sqlite3_step(m_stmt);
                TryCatchResLogReturn(res == SQLITE_ROW, sqlite3_finalize(m_stmt); m_dbMutex.unlock(), PRIV_GUARD_ERROR_DB_ERROR, "sqlite3_step : %d", res);
 
-               patternCount = sqlite3_column_int(m_stmt, 0);
+               int patternCount = sqlite3_column_int(m_stmt, 0);
                sqlite3_finalize(m_stmt);
 
                if (patternCount == 0) {
+                       const char *query3 = "UPDATE DlpPatterns SET STATE=? WHERE ID=? AND STATE=?";
+
                        // we can delete the pattern as we were the only one using it
                        // for now we just mark it as STATE=PRIV_GUARD_DLP_PATTERN_STATE_DELETED. This is because some log details may refer to it.
                        // We will delete these patterns from the database during leak log cleanup.
@@ -2799,13 +2789,6 @@ int
 PrivacyGuardDb::PgForeachDlpRules(int userId, int profile, std::list<get_custom_rule_s> &rules)
 {
        int res = -1;
-       const char *queryc = "SELECT R.ID, R.ACTION, R.PATTERN_ID, R.NAME, R.DESCRIPTION, P.NAME, P.DESCRIPTION, R.APP_ID, "
-         "(SELECT COUNT(LL.ID) FROM DlpLeakLog AS LL WHERE LL.PATTERN_ID == R.PATTERN_ID) FROM DlpRules AS R, "
-         "DlpPatterns AS P WHERE R.PATTERN_ID=P.ID AND R.USER_ID=? AND PROFILE=?";
-
-       const char *query = "SELECT R.ID, R.ACTION, R.PATTERN_ID, R.NAME, R.DESCRIPTION, P.NAME, P.DESCRIPTION, R.APP_ID, "
-         "(SELECT COUNT(LL.ID) FROM DlpLeakLog AS LL WHERE LL.PATTERN_ID == R.PATTERN_ID) FROM DlpRules AS R, "
-         "DlpPatterns AS P WHERE R.PATTERN_ID=P.ID AND PROFILE=?";
 
        m_dbMutex.lock();
 
@@ -2823,6 +2806,10 @@ PrivacyGuardDb::PgForeachDlpRules(int userId, int profile, std::list<get_custom_
 
        // prepare
        if (profile == PRIV_GUARD_DLP_PROFILE_CUSTOM) {
+               const char *queryc = "SELECT R.ID, R.ACTION, R.PATTERN_ID, R.NAME, R.DESCRIPTION, P.NAME, P.DESCRIPTION, R.APP_ID, "
+                         "(SELECT COUNT(LL.ID) FROM DlpLeakLog AS LL WHERE LL.PATTERN_ID == R.PATTERN_ID) FROM DlpRules AS R, "
+                         "DlpPatterns AS P WHERE R.PATTERN_ID=P.ID AND R.USER_ID=? AND PROFILE=?";
+
                res = sqlite3_prepare_v2(m_sqlHandler, queryc, -1, &m_stmt, NULL);
                TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_GUARD_ERROR_DB_ERROR, "sqlite3_prepare_v2 : %d", res);
 
@@ -2833,6 +2820,10 @@ PrivacyGuardDb::PgForeachDlpRules(int userId, int profile, std::list<get_custom_
                res = sqlite3_bind_int(m_stmt, 2, profile);
                TryCatchResLogReturn(res == SQLITE_OK, sqlite3_finalize(m_stmt); m_dbMutex.unlock(), PRIV_GUARD_ERROR_DB_ERROR, "sqlite3_bind_int : %d", res);
        } else {
+               const char *query = "SELECT R.ID, R.ACTION, R.PATTERN_ID, R.NAME, R.DESCRIPTION, P.NAME, P.DESCRIPTION, R.APP_ID, "
+                         "(SELECT COUNT(LL.ID) FROM DlpLeakLog AS LL WHERE LL.PATTERN_ID == R.PATTERN_ID) FROM DlpRules AS R, "
+                         "DlpPatterns AS P WHERE R.PATTERN_ID=P.ID AND PROFILE=?";
+
                res = sqlite3_prepare_v2(m_sqlHandler, query, -1, &m_stmt, NULL);
                TryCatchResLogReturn(res == SQLITE_OK, m_dbMutex.unlock(), PRIV_GUARD_ERROR_DB_ERROR, "sqlite3_prepare_v2 : %d", res);
 
@@ -3136,3 +3127,4 @@ PrivacyGuardDb::getInstance(void)
 
        return m_pInstance;
 }
+
old mode 100755 (executable)
new mode 100644 (file)
old mode 100755 (executable)
new mode 100644 (file)
old mode 100755 (executable)
new mode 100644 (file)
index 79238f4..9bb87e6 100644 (file)
@@ -23,6 +23,9 @@
 #include <contacts.h>
 #include <wifi.h>
 
+#include <chrono>
+#include <thread>
+
 #include "Utils.h"
 #include "DlpPrivacyInfoData.h"
 #include "PrivacyGuardDb.h"
@@ -354,6 +357,27 @@ DlpPrivacyInfoData::loadMyProfile(void)
        contacts_list_destroy(contact_list, true);
 }
 
+bool
+DlpPrivacyInfoData::waitForModemReady(const telephony_h handle) const
+{
+       constexpr int max_retries{ 25 };
+       constexpr auto retry_delay = std::chrono::milliseconds(20);
+       int ret = TELEPHONY_ERROR_NONE - 1;
+       int retry = 0;
+
+       while (retry < max_retries && ret != TELEPHONY_ERROR_NONE) {
+               telephony_modem_power_status_e modem_power_status;
+               ret = telephony_modem_get_power_status(handle, &modem_power_status);
+               if (TELEPHONY_ERROR_NONE != ret) {
+                       PG_LOGE("telephony_modem_get_power_status() failed. Error=%d", ret);
+                       std::this_thread::sleep_for(retry_delay);
+               }
+               ++retry;
+       }
+
+       return ret == TELEPHONY_ERROR_NONE;
+}
+
 void
 DlpPrivacyInfoData::loadInfo(const int userId)
 {
@@ -371,9 +395,13 @@ DlpPrivacyInfoData::loadInfo(const int userId)
        // Loading IMEIs, phone numbers
        if (m_handle_list.handle == NULL && telephony_init(&m_handle_list) == TELEPHONY_ERROR_NONE) {
                for (unsigned int i = 0; i < m_handle_list.count; i++) {
-                       ret = telephony_modem_get_imei(m_handle_list.handle[i], &imei);
-                       if (ret == TELEPHONY_ERROR_NONE && imei && strlen(imei))
-                               m_imei_list.push_back(imei);
+                       if (waitForModemReady(m_handle_list.handle[i])) {
+                               ret = telephony_modem_get_imei(m_handle_list.handle[i], &imei);
+                               if (ret == TELEPHONY_ERROR_NONE && imei && strlen(imei))
+                                       m_imei_list.push_back(imei);
+                       } else {
+                               PG_LOGE("Modem is not ready. IMEI can not be monitored.");
+                       }
 
                        ret = telephony_sim_get_subscriber_number(m_handle_list.handle[i], &phoneno);
                        if (ret == TELEPHONY_ERROR_NONE && phoneno && strlen(phoneno))
old mode 100755 (executable)
new mode 100644 (file)
index 3720870..98c6a75
@@ -490,20 +490,14 @@ void
 PrivacyInfoService::PgGetDlpCurrentRules(SocketConnection* pConnector)
 {
        int userId = 0;
-       char appId[LEN_PACKAGE_ID];
        int pId = 0;
        std::list<current_rules_s> templateRules;
        std::list<current_rules_s> rules;
 
        pConnector->read(&userId);
-       int res = pConnector->read(appId, LEN_PACKAGE_ID);
-       if (res != PRIV_GUARD_ERROR_SUCCESS) {
-               PG_LOGE("fail : pConnector->read(appId, LEN_PACKAGE_ID) (%d)", res);
-               return;
-       }
        pConnector->read(&pId);
 
-       int result = PrivacyGuardDb::getInstance()->PgGetDlpCurrentRules(userId, appId, pId, templateRules);
+       int result = PrivacyGuardDb::getInstance()->PgGetDlpCurrentRules(userId, pId, templateRules);
 
        // replace all rule templates
        if (result == PRIV_GUARD_ERROR_SUCCESS)
diff --git a/setting/CMakeLists.txt b/setting/CMakeLists.txt
new file mode 100755 (executable)
index 0000000..7662b2d
--- /dev/null
@@ -0,0 +1,87 @@
+CMAKE_MINIMUM_REQUIRED(VERSION 2.6)
+#PROJECT(privacy-guard-setting)
+
+FIND_PACKAGE(Threads REQUIRED)
+
+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-setting REQUIRED dlog sqlite3 dbus-1 dbus-glib-1 libtzplatform-config libpcre)
+
+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(setting_src_dir "${CMAKE_SOURCE_DIR}/setting/src")
+SET(setting_include_dir "${CMAKE_SOURCE_DIR}/setting/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(ahocorasick_dir "${CMAKE_SOURCE_DIR}/ahocorasick/")
+
+## Additional flag
+ADD_DEFINITIONS("-fvisibility=hidden")
+ADD_DEFINITIONS("-Wall -Werror")
+ADD_DEFINITIONS("-DDLOG_ERROR_ENABLED")
+ADD_DEFINITIONS("-D_PRIVACY_GUARD_DEBUG")
+
+###################################################################################################
+## for libprivacy-guard-setting
+INCLUDE_DIRECTORIES(${pkgs_INCLUDE_DIRS} ${setting_include_dir} ${common_include_dir} ${extern_include_dir})
+SET(PRIVACY_GUARD_SETTING_SOURCES
+       ${common_src_dir}/SocketClient.cpp
+       ${common_src_dir}/SocketConnection.cpp
+       ${common_src_dir}/SocketStream.cpp
+       ${common_src_dir}/PrivacyIdInfo.cpp
+       ${common_src_dir}/DlpUtils.cpp
+       ${common_src_dir}/Utils.cpp
+       ${common_src_dir}/privacy_guard_utils.c
+       ${setting_src_dir}/PrivacyGuardClient.cpp
+       ${setting_src_dir}/privacy_guard_client.cpp
+       ${ahocorasick_dir}/ahocorasick.c
+       ${ahocorasick_dir}/node.c
+       )
+SET(PRIVACY_GUARD_SETTING_HEADERS
+       ${setting_include_dir}/PrivacyGuardClient.h
+       ${setting_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_SETTING_LDFLAGS " -module -avoid-version ")
+SET(PRIVACY_GUARD_SETTING_CFLAGS  " ${CFLAGS} -fPIC ")
+
+ADD_DEFINITIONS("-DLOG_TAG=\"PRIVACY-GUARD-SETTING\"")
+ADD_LIBRARY(privacy-guard-setting SHARED ${PRIVACY_GUARD_SETTING_SOURCES})
+TARGET_LINK_LIBRARIES(privacy-guard-setting -pthread ${pkgs_LDFLAGS} ${pkgs_LIBRARIES})
+SET_TARGET_PROPERTIES(privacy-guard-setting PROPERTIES COMPILE_FLAGS "${PRIVACY_GUARD_SETTING_CFLAGS}")
+SET_TARGET_PROPERTIES(privacy-guard-setting PROPERTIES SOVERSION ${API_VERSION})
+SET_TARGET_PROPERTIES(privacy-guard-setting PROPERTIES VERSION ${VERSION})
+###################################################################################################
+
+SET(PC_NAME privacy-guard-setting)
+SET(PC_DESCRIPTION "Privacy Guard Setting API")
+SET(PC_LDFLAGS -lprivacy-guard-setting -lpcre)
+SET(PC_CFLAGS -I\${includedir}/privacy_guard)
+
+CONFIGURE_FILE(../privacy-guard-setting.pc.in privacy-guard-setting.pc @ONLY)
+
+INSTALL(TARGETS privacy-guard-setting DESTINATION ${LIB_INSTALL_DIR} COMPONENT RuntimeLibraries)
+INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/privacy-guard-setting.pc DESTINATION ${LIB_INSTALL_DIR}/pkgconfig)
+INSTALL(FILES ${PRIVACY_GUARD_SETTING_HEADERS} DESTINATION ${INCLUDE_INSTALL_DIR}/privacy_guard/setting)
+INSTALL(FILES ${PRIVACY_GUARD_EXTERN_HEADERS} DESTINATION ${INCLUDE_INSTALL_DIR}/privacy_guard)
similarity index 91%
rename from client/inc/PrivacyGuardClient.h
rename to setting/inc/PrivacyGuardClient.h
index 66641dd..633884d 100644 (file)
@@ -36,11 +36,6 @@ std::mutex m_dbMutex;
 sqlite3* m_sqlHandler;
 sqlite3_stmt* m_stmt;
 bool m_bDBOpen;
-char m_applicationId[LEN_APPLICATION_ID] = { 0 };
-char m_applicationName[LEN_APPLICATION_NAME] = { 0 };
-char m_applicationVersion[LEN_APPLICATION_VERSION] = { 0 };
-char m_applicationIcon[LEN_APPLICATION_ICON] = { 0 };
-char m_packageId[LEN_PACKAGE_ID] = { 0 };
 
 static PrivacyGuardClient* m_pInstance;
 static const std::string INTERFACE_NAME;
@@ -105,20 +100,6 @@ int PgUpdateMainMonitorPolicy(const int userId, const int mainMonitorPolicy);
 // DLP features
 
 /**
- * @brief      add a list of leak logs to the database
- *
- * @param[in]  userId                  The ID of the user running the application 
- * @param[in]  destination             The host which the data is to be sent to
- * @param[in]  rawPacket               The data packet to be sent
- * @param[in]  len                             The length of the packet data in bytes
- * @param[in]  logList                 The std::list of leaks to be added.
- *
- * @return     An error code
- * @since      Tizen 4.0
- */
-int PgAddLeakLog(const int userId, const char *destination, const void *rawPacket, const size_t len, const std::list<leak_log_insert_data_s> &logList) const;
-
-/**
  * @brief      get all logs from leaked packets.
  *
  * @param[in]  userId                  The ID of the user
@@ -255,7 +236,7 @@ int PgGetDlpProfile(const int userId, dlp_profile_s *profile) const;
  * @since      Tizen 4.0
  */
 int PgGetDlpCurrentRules(const int userId, const int pId, std::list<current_rules_s> &currentRules) const;
+
 /**
  * @brief      add a custom DLP rule for user userId
  *
@@ -310,11 +291,11 @@ int PgForeachDlpRules(int userId, PgDlpProfile profile, std::list<get_custom_rul
 /**
  * @brief      add a new DLP pattern
  *
- * @param[in]  name                    Pattern name
- * @param[in]  description             Pattern description
- * @param[in]  category                Pattern category
- * @param[in]  pattern                 The pattern to match
- * @param[in]  type                    Pattern type (STRING, REGEX)
+ * @param[in]  name                    Pattern name
+ * @param[in]  description             Pattern description
+ * @param[in]  category                Pattern category
+ * @param[in]  pattern                 The pattern to match
+ * @param[in]  type                    Pattern type (STRING, REGEX)
  *
  * @return     the result of operation (ERRORCODE : success, ....)
  */
similarity index 98%
rename from client/inc/privacy_guard_client_internal.h
rename to setting/inc/privacy_guard_client_internal.h
index ca35d6b..26eb5ad 100755 (executable)
@@ -16,7 +16,7 @@
 
 /**
  * @file       privacy_guard_client_internal.h
- * @brief      Internal API for privacy-guard-client
+ * @brief      Internal API for privacy-guard-setting
  */
 
 #ifndef _PRIVACY_GUARD_CLIENT_INTERNAL_H_
similarity index 92%
rename from client/src/PrivacyGuardClient.cpp
rename to setting/src/PrivacyGuardClient.cpp
index 55d0902..4d52ac7 100644 (file)
@@ -18,8 +18,6 @@
 #include <memory>
 #include <fcntl.h>
 #include <strings.h>
-#include <aul.h>
-#include <pkgmgr-info.h>
 #include "Utils.h"
 #include "DlpUtils.h"
 #include "PrivacyGuardClient.h"
@@ -36,7 +34,6 @@ char PrivacyGuardClient::m_categories[MAX_CATEGORIES][LEN_CATEGORY];
 
 PrivacyGuardClient::PrivacyGuardClient(void):m_sqlHandler(NULL), m_stmt(NULL), m_bDBOpen(false)
 {
-       loadApplicationInfo();
        int res = loadDlpCategories();
        if (res != PRIV_GUARD_ERROR_SUCCESS) {
                PG_LOGE("fail : loadDlpCategories (%d)", res);
@@ -60,51 +57,6 @@ PrivacyGuardClient::category_text_to_id(const char *txt)
   return -1;
 }
 
-void
-PrivacyGuardClient::loadApplicationInfo()
-{
-       int ret;
-       char *data = NULL;
-       pkgmgrinfo_appinfo_h appinfo = NULL;
-       pkgmgrinfo_pkginfo_h pkginfo = NULL;
-
-       // load application ID
-       ret = aul_app_get_appid_bypid(getpid(), m_applicationId, LEN_APPLICATION_ID);
-       if (ret == 0) {
-               // load application info
-               ret = pkgmgrinfo_appinfo_get_usr_appinfo(m_applicationId, getuid(), &appinfo);
-               if (ret == 0) {
-                       // load application name
-                       ret = pkgmgrinfo_appinfo_get_label(appinfo, &data);
-                       if (ret == 0)
-                               pg_strlcpy(m_applicationName, data, LEN_APPLICATION_NAME);
-
-                       // load package ID
-                       ret = pkgmgrinfo_appinfo_get_pkgid(appinfo, &data);
-                       if (ret == 0)
-                               pg_strlcpy(m_packageId, data, LEN_PACKAGE_ID);
-
-                       // load application icon
-                       ret = pkgmgrinfo_appinfo_get_icon(appinfo, &data);
-                       if (ret == 0)
-                               pg_strlcpy(m_applicationIcon, data, LEN_APPLICATION_ICON);
-
-                       // load package info
-                       ret = pkgmgrinfo_pkginfo_get_pkginfo(m_packageId, &pkginfo);
-                       if (ret == 0) {
-                               // load application version
-                               ret = pkgmgrinfo_pkginfo_get_version(pkginfo, &data);
-                               if (ret == 0)
-                                       pg_strlcpy(m_applicationVersion, data, LEN_APPLICATION_VERSION);
-
-                               pkgmgrinfo_pkginfo_destroy_pkginfo(pkginfo);
-                       }
-
-                       pkgmgrinfo_appinfo_destroy_appinfo(appinfo);
-               }
-       }
-}
-
 /**
  * @callgraph
  */
@@ -120,8 +72,7 @@ PrivacyGuardClient::getInstance(void)
 void
 PrivacyGuardClient::openSqliteDB(void)
 {
-       int res = -1;
-       res = sqlite3_open_v2(PRIVACY_DB_PATH, &m_sqlHandler, SQLITE_OPEN_READWRITE, NULL);
+       int res = sqlite3_open_v2(PRIVACY_DB_PATH, &m_sqlHandler, SQLITE_OPEN_READWRITE, NULL);
        if(res == SQLITE_OK) {
                PG_LOGI("monitor db is opened successfully");
                m_bDBOpen = true;
@@ -596,34 +547,6 @@ PrivacyGuardClient::PgUpdateMainMonitorPolicy(const int userId, const int mainMo
        return result;
 }
 
-/**
- * @callgraph
- */
-int
-PrivacyGuardClient::PgAddLeakLog(const int userId, const char *destination, const void *rawPacket, const size_t len, const std::list<leak_log_insert_data_s> &logList) const
-{
-       if (destination == NULL || rawPacket == NULL)
-               return PRIV_GUARD_ERROR_INVALID_PARAMETER;
-
-       int result = PRIV_GUARD_ERROR_SUCCESS;
-       SocketClient socketClient(INTERFACE_NAME);
-       packet_data_s packetData = { (int)len, (void *)rawPacket};
-
-       int res = socketClient.connect();
-       TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, , "connect : %d", res);
-
-       res = socketClient.call("PgAddLeakLog", userId, (const char *)m_applicationId,
-                                                               (const char *)m_applicationName, (const char *)m_applicationVersion,
-                                                               (const char *)m_applicationIcon, (const char *)m_packageId,
-                                                               destination, packetData, logList, &result);
-       TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, socketClient.disconnect(), "call : %d", res);
-
-       res = socketClient.disconnect();
-       TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, , "disconnect : %d", res);
-
-       return result;
-}
-
 int
 PrivacyGuardClient::PgForeachLeakLogs(const int userId, std::list<leak_log_get_data_s> &logList) const
 {
@@ -848,8 +771,7 @@ PrivacyGuardClient::PgGetDlpCurrentRules(const int userId, const int pId, std::l
        TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, , "connect : %d", res);
 
        currentRules.clear();
-       res = socketClient.call("PgGetDlpCurrentRules", userId, (const char *)m_applicationId,
-                                                               pId, &result, &currentRules);
+       res = socketClient.call("PgGetDlpCurrentRules", userId, pId, &result, &currentRules);
        TryReturn(res == PRIV_GUARD_ERROR_SUCCESS, res, socketClient.disconnect(), "call : %d", res);
 
        res = socketClient.disconnect();
similarity index 99%
rename from client/src/privacy_guard_client.cpp
rename to setting/src/privacy_guard_client.cpp
index bf1137a..540835c 100644 (file)
 
 /**
  * @file       privacy_guard_client.cpp
- * @brief      API for privacy-guard-client (C / C++)
+ * @brief      API for privacy-guard-setting (C / C++)
  */
 
 #include <string.h>
 #include <string>
 #include <memory>
-#include "PrivacyChecker.h"
 #include "PrivacyGuardClient.h"
 #include "privacy_guard_client.h"
 #include "privacy_guard_client_internal.h"
@@ -226,9 +225,7 @@ int privacy_guard_client_foreach_monitor_policy_by_package_id(const int user_id,
        }
 
        std::list <privacy_data_s> privacyInfoList;
-       int retval = -1;
-
-       retval = PrivacyGuardClient::getInstance()->PgForeachMonitorPolicyByPackageId(user_id, std::string(package_id), privacyInfoList);
+       int retval = PrivacyGuardClient::getInstance()->PgForeachMonitorPolicyByPackageId(user_id, std::string(package_id), privacyInfoList);
        if (retval != PRIV_GUARD_ERROR_SUCCESS) {
                PG_LOGE("Failed to do PrivacyGuardClient::PgForeachMonitorPolicyByPackageId() [%d]", retval);
                return retval;
old mode 100755 (executable)
new mode 100644 (file)
similarity index 96%
rename from client/src/privacy_guard_client_internal_types.h
rename to setting/src/privacy_guard_client_internal_types.h
index 5cf4c64..aabe480
@@ -11,7 +11,7 @@
  * distributed under the License is distributed on an AS IS BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
- * limitations under the License. 
+ * limitations under the License.
  */
 
 /**
index a62c055..9831876 100644 (file)
@@ -5,12 +5,14 @@ PROJECT(${PACKAGE_NAME})
 SET(TC1_NAME tc-privacy-guard)
 SET(TC2_NAME tc-dlp)
 SET(TC3_NAME tc-dlp-performance)
+SET(TC4_NAME tc-ahocorasick)
 
 SET(TC1_SRCS ${TC1_NAME}.c)
 SET(TC2_SRCS ${TC2_NAME}.c)
 SET(TC3_SRCS ${TC3_NAME}.c)
+SET(TC4_SRCS ${TC4_NAME}.c)
 
-INCLUDE_DIRECTORIES(${CMAKE_SOURCE_DIR}/include ${CMAKE_SOURCE_DIR}/client/inc ${CMAKE_SOURCE_DIR}/common/inc ${CMAKE_SOURCE_DIR}/common/src)
+INCLUDE_DIRECTORIES(${CMAKE_SOURCE_DIR}/include ${CMAKE_SOURCE_DIR}/setting/inc ${CMAKE_SOURCE_DIR}/client/inc ${CMAKE_SOURCE_DIR}/common/inc ${CMAKE_SOURCE_DIR}/common/src)
 
 SET(requires glib-2.0 dlog libpcre)
 INCLUDE(FindPkgConfig)
@@ -33,11 +35,14 @@ SET(PC_LDFLAGS -lpcre)
 ADD_EXECUTABLE(${TC1_NAME} ${TC1_SRCS} ${SOURCES})
 ADD_EXECUTABLE(${TC2_NAME} ${TC2_SRCS} ${SOURCES})
 ADD_EXECUTABLE(${TC3_NAME} ${TC3_SRCS} ${SOURCES})
+ADD_EXECUTABLE(${TC4_NAME} ${TC4_SRCS} ${SOURCES})
 
-TARGET_LINK_LIBRARIES(${TC1_NAME} "privacy-guard-client")
-TARGET_LINK_LIBRARIES(${TC2_NAME} "privacy-guard-client")
-TARGET_LINK_LIBRARIES(${TC3_NAME} "privacy-guard-client" "rt")
+TARGET_LINK_LIBRARIES(${TC1_NAME} "privacy-guard-setting")
+TARGET_LINK_LIBRARIES(${TC2_NAME} "privacy-guard-setting" "privacy-guard-client")
+TARGET_LINK_LIBRARIES(${TC3_NAME} "privacy-guard-setting" "privacy-guard-client" "rt")
+TARGET_LINK_LIBRARIES(${TC4_NAME} "privacy-guard-setting")
 
 INSTALL(TARGETS ${TC1_NAME} DESTINATION /usr/bin)
 INSTALL(TARGETS ${TC2_NAME} DESTINATION /usr/bin)
 #INSTALL(TARGETS ${TC3_NAME} DESTINATION /usr/bin)
+INSTALL(TARGETS ${TC4_NAME} DESTINATION /usr/bin)
diff --git a/test/tc-ahocorasick.c b/test/tc-ahocorasick.c
new file mode 100644 (file)
index 0000000..52313cb
--- /dev/null
@@ -0,0 +1,253 @@
+#include <stdio.h>
+#include <stdlib.h>
+#include <sys/types.h>
+#include <unistd.h>
+#include <privacy_guard_client.h>
+#include <privacy_guard_client_internal.h>
+#include <time.h>
+
+#include "privacy_guard_dlp.h"
+#include "../ahocorasick/ahocorasick.h"
+#include "../ahocorasick/node.h"
+
+#define BRIGHTNESS             0
+#define RED                    31
+#define GREEN                  32
+#define YELLOW                 33
+#define BG_BLACK               40
+
+static int fail_cnt = 0;
+static int success_cnt = 0;
+
+/* scenario settings */
+
+/** Test aho-corasick algorithm.
+ * Instructions: uncomment exactly ONE of the scenarios below. Set the number of target words (NWORDS).
+ * Adjust the other settings as required.
+ */
+
+/* only uncomment ONE of these at a time */
+#define SCENARIO_1 // pull words from text, parse same text
+//#define SCENARIO_2 // pull words from text, parse different text
+//#define SCENARIO_3 // pull words from text, parse random text
+//#define SCENARIO_4 // create random words, parse random text
+
+#define NWORDS 1000 // target number of words to search for
+
+#define WORD_SRCFILE "/tmp/smatch.txt"
+#define TEXT_SRCFILE "/tmp/smatch2.txt"
+
+#define SMATCH_BUFSIZE 65536 // text packet buffer size
+
+//#define SHOW_ADDED // uncomment to show strings as they are added
+#define DUMP_TREE  // uncomment to dump the tree after adding strings
+//#define SHOW_MATCHES // uncomment to show details of each match
+
+///////////////////////////////////////////////////////////////////////////////
+// test utilities (aho-corasick)
+///////////////////////////////////////////////////////////////////////////////
+
+#include <sys/stat.h>
+#include <sys/time.h>
+#include <fcntl.h>
+
+static int fastrand(int max)
+{
+       static int next = 0;
+       next = next * 1103515245 + 12345;
+       return ((unsigned)(next / 65536) % max);
+}
+
+static void __change_color_to_red(void)
+{
+       printf("%c[%d;%dm", 0x1B, BRIGHTNESS, RED);
+}
+
+static void __change_color_to_green(void)
+{
+       printf("%c[%d;%dm", 0x1B, BRIGHTNESS, GREEN);
+}
+
+static void __change_color_to_yellow(void)
+{
+       printf("%c[%d;%dm", 0x1B, BRIGHTNESS, YELLOW);
+}
+
+static void __change_color_to_origin(void)
+{
+       printf("%c[%dm", 0x1B, 0);
+}
+
+static void __start_test(const char *function_name)
+{
+       __change_color_to_yellow();
+       printf("================================================================================\n");
+       printf("\t%s\n", function_name);
+       printf("================================================================================\n");
+       __change_color_to_origin();
+}
+
+///////////////////////////////////////////////////////////////////////////////
+// test verfication utility
+///////////////////////////////////////////////////////////////////////////////
+
+// Test String Match (ahocorasick)
+static void __test_string_match()
+{
+       __start_test(__FUNCTION__);
+       unsigned int i = 0;
+       unsigned long stime;
+
+       printf("Search match: ");
+
+       int awl = 0;
+       char buf[SMATCH_BUFSIZE];
+
+#ifndef SCENARIO_4
+       // load text from file
+       int fd = open(WORD_SRCFILE, O_RDONLY);
+       if (fd < 0) {
+               printf("Could not open " WORD_SRCFILE ". It should be a text file for me to find source words.\n");
+               return;
+       }
+       ssize_t tsize = read(fd, buf, SMATCH_BUFSIZE - 1);
+       if (tsize <= 0) {
+               printf("Could not read from " WORD_SRCFILE "\n");
+               close(fd);
+               return;
+       }
+       close(fd);
+       memset(buf + tsize, 0, 1);
+
+       // count words in text
+       int nwords = 1;
+
+       for (i = 0; i < tsize; i++) {
+               if (buf[i] == ' ') nwords++;
+       }
+#endif
+
+       int res = 0;
+       ac_instance *ac = ahocorasick_init();
+       struct timeval tv;
+
+       gettimeofday(&tv, NULL);
+       stime = tv.tv_sec * 1000000 + tv.tv_usec;
+
+       for (i = 1; i <= NWORDS; i++) {
+#ifdef SCENARIO_4
+               int j;
+               char *word = malloc(8);
+               for (j = 0; j < 7; j++) word[j] = (char)('a' + fastrand(20));
+               word[7] = 0;
+#else
+               // get a random number between 1 and nwords
+               int start = -1, j;
+               int idxword = fastrand(nwords - 1) + 1;
+
+               for (j = 0; idxword > 0; j++) {
+                       if (idxword == 1 && start == -1) start = j;
+                       if (buf[j] == ' ') idxword--;
+               }
+               if (j - start < 6) {
+                       i--;
+                       continue;
+               }
+
+               char *word = strndup(buf + start, j - start - 1);
+#endif
+               awl += strlen(word);
+               int nres = ahocorasick_add_string(ac, word, (void *)i);
+#ifdef SHOW_ADDED
+               printf("Added: .%s. %d\n", word, strlen(word));
+#endif
+               res = nres;
+               free(word);
+       }
+
+       awl = awl / i;
+
+       gettimeofday(&tv, NULL);
+       stime = tv.tv_sec * 1000000 + tv.tv_usec - stime;
+       printf("Build tree took %.2f msec for %d words (%d unique), average word len was %d\n", stime / 1000., NWORDS, res, awl);
+       stime = tv.tv_sec * 1000000 + tv.tv_usec;
+
+#ifdef SCENARIO_2
+       // load alternate text
+       fd = open(TEXT_SRCFILE, O_RDONLY);
+       if (fd < 0) {
+               printf("Could not open " TEXT_SRCFILE ". It should be a related text file for me to search for matches.\n");
+               return;
+       }
+       tsize = read(fd, buf, SMATCH_BUFSIZE - 1);
+       if (tsize <= 0) {
+               printf("Could not read from " TEXT_SRCFILE "\n");
+               return;
+       }
+       close(fd);
+       memset(buf + tsize, 0, 1);
+#endif
+
+#if defined SCENARIO_3 || defined SCENARIO_4
+       for (i = 0; i < 32768; i++)
+               buf[i] = (char)fastrand(100) + 30;
+       buf[32768] = 0;
+
+#endif
+       const char *text = buf;
+       ac_match *match;
+
+#ifdef DUMP_TREE
+       dump_tree(ac->root, stdout);
+#endif
+
+       ahocorasick_set_text(ac, text, strlen(text), 0);
+
+       res = 0;
+       do {
+               match = ahocorasick_find_next(ac);
+
+               if (match != NULL) {
+#ifdef SHOW_MATCHES
+                       for (i = match->position; i < match->position + match->size; i++) printf("%c", text[i]);
+                       printf("\n");
+                       printf("got match for %p at %d len %d\n", match->user_data, match->position, match->size);
+#endif
+                       res++;
+               }
+       } while (match != NULL);
+
+       gettimeofday(&tv, NULL);
+       stime = tv.tv_sec * 1000000 + tv.tv_usec - stime;
+       printf("Parsing took %.2f msec\n", stime / 1000.);
+
+       printf("Got a total of %d matches.\n", res);
+
+       ahocorasick_free(ac);
+}
+
+//////////////////////////////////////////////////////////////////////////
+// Main
+//////////////////////////////////////////////////////////////////////////
+int main()
+{
+       __change_color_to_green();
+       printf("DLP Test Start\n");
+       __change_color_to_origin();
+
+       /////////////////////////////////////////////////////////////////////////
+       // Test String Match (ahocorasick)
+       __test_string_match();
+
+       //////////////////////////////////////////////////////////////////////////
+
+       __change_color_to_green();
+
+       printf("Test Complete\n");
+       printf("success : %d, ", success_cnt);
+       __change_color_to_red();
+       printf("fail : %d\n", fail_cnt);
+       __change_color_to_origin();
+
+       return 0;
+}
index a5a7c17..67a3942 100644 (file)
@@ -22,10 +22,6 @@ static int fail_cnt = 0;
 static int success_cnt = 0;
 static long interval[5000];
 
-typedef struct rec {
-               char char_vec[32000];
-} RECORD;
-
 // Packet to match 6 rules: Personal Document, Birth Date, Email, Address, Full Name and PhoneNumber
 char packet_match_6rules[] = "GET /sync/pubmatic/csrc/7/44D1C4FE-60A-4 HTTP/1.1" \
                                                        "Host: pr-bh.ybp.yahoo.com" \