Tests coverage increased. Code refactored.
authorLomtev Dmytro <d.lomtev@samsung.com>
Mon, 2 Oct 2017 11:55:28 +0000 (14:55 +0300)
committerLomtev Dmytro <d.lomtev@samsung.com>
Mon, 2 Oct 2017 12:04:20 +0000 (15:04 +0300)
77 files changed:
device_core/CMakeLists.txt
device_core/ctrl_app_lib/inc/ctrl_app_support.h
device_core/ctrl_app_lib/inc/hub_client.h
device_core/ctrl_app_lib/src/ctrl_app_support.cpp
device_core/ctrl_app_lib/src/hub_client.cpp
device_core/ctrl_app_lib/src/securitycontext.cpp
device_core/iotivity_lib/inc/device_control.h
device_core/iotivity_lib/inc/iotivity.h
device_core/iotivity_lib/inc/iotivity_impl.h [new file with mode: 0644]
device_core/iotivity_lib/src/iotivity.cpp
device_core/iotivity_lib/src/iotivity_impl.cpp [new file with mode: 0644]
device_core/mock/audit-trail-mock.h [new file with mode: 0644]
device_core/mock/audit-trail-stub.cpp [new file with mode: 0644]
device_core/mock/audit-trail-stub.h [new file with mode: 0644]
device_core/mock/audit-trail.h [new file with mode: 0644]
device_core/mock/common.h [new file with mode: 0644]
device_core/mock/dac.h [new file with mode: 0644]
device_core/mock/device-policy-manager-mock.h [new file with mode: 0644]
device_core/mock/device-policy-manager.cpp [new file with mode: 0644]
device_core/mock/device-policy-manager.h [new file with mode: 0644]
device_core/mock/iot_policy_enforce_mock.h [new file with mode: 0644]
device_core/mock/iotdevice_mock.h [new file with mode: 0644]
device_core/mock/iotivity_mock.h [new file with mode: 0644]
device_core/mock/mac.h [new file with mode: 0644]
device_core/mock/mqclient_mock.h [new file with mode: 0644]
device_core/mock/syscall.h [new file with mode: 0644]
device_core/nmdaemon/CMakeLists.txt
device_core/nmdaemon/application_service.cpp
device_core/nmdaemon/audit_trail_client.h
device_core/nmdaemon/commandhandler.h
device_core/nmdaemon/dpm/dpm_api_mapper.cpp
device_core/nmdaemon/hub_resource.cpp
device_core/nmdaemon/hub_resource.h
device_core/nmdaemon/main.cpp
device_core/nmdaemon/main_thread.cpp
device_core/nmdaemon/policyhandler.cpp
device_core/nmdaemon/policyhandler.h
device_core/nmdaemon/policyhandlerfactory.cpp
device_core/nmdaemon/policyhandlerfactory.h
device_core/nmdaemon/policyhandlermq.cpp
device_core/nmdaemon/policyhandlermq.h
device_core/nmdaemon/policyhandlerres.cpp
device_core/nmdaemon/policyhandlerres.h
device_core/nmdaemon/proxythread.h
device_core/nmdaemon/reporthandler_res.cpp
device_core/nmdaemon/reporthandler_res.h
device_core/nmdaemon/reporthandlerfactory.cpp
device_core/nmdaemon/reporthandlerfactory.h
device_core/nmdaemon/reporthandlermq.cpp
device_core/nmdaemon/reporthandlermq.h
device_core/packaging/ioswsec.spec
device_core/scripts/common.sh
device_core/utest/CMakeLists.txt
device_core/utest/local_test_resources_init.cpp
device_core/utest/test_IoT.cpp
device_core/utest/test_agentpolicyservice.cpp [new file with mode: 0644]
device_core/utest/test_all.cpp
device_core/utest/test_application_service.cpp [new file with mode: 0644]
device_core/utest/test_audit_trail_client.cpp [new file with mode: 0644]
device_core/utest/test_audit_trail_stub.cpp [new file with mode: 0644]
device_core/utest/test_commandhandler.cpp
device_core/utest/test_hubclient.cpp [new file with mode: 0644]
device_core/utest/test_hubresource.cpp
device_core/utest/test_iot_dev_manager.cpp
device_core/utest/test_iot_notification.cpp
device_core/utest/test_iot_policy_enforce.cpp [new file with mode: 0644]
device_core/utest/test_iot_tvext_policy_enforce.cpp [new file with mode: 0644]
device_core/utest/test_iotchilddevice_impl.cpp [new file with mode: 0644]
device_core/utest/test_mq.cpp
device_core/utest/test_policyhandler.cpp [new file with mode: 0644]
device_core/utest/test_proxythread.cpp
device_core/utest/test_reporthandler.cpp [new file with mode: 0644]
device_core/utest/test_reporthandlermq.cpp [new file with mode: 0644]
device_core/utest/test_rest.cpp
device_core/utest/test_threadbase.cpp [new file with mode: 0644]
device_core/utest/test_ubuntu_dpm.cpp [new file with mode: 0644]
device_core/utest/tests_stub.cpp [new file with mode: 0644]

index 3bec627..a266e34 100644 (file)
@@ -17,6 +17,8 @@ SET(CMAKE_C_FLAGS_RELEASE     "-O2 -s")
 SET(CMAKE_CXX_FLAGS_RELEASE    "-O2 -s")
 SET(CMAKE_C_FLAGS_CCOV         "-O0 --coverage")
 SET(CMAKE_CXX_FLAGS_CCOV       "-O0 --coverage")
+SET(CMAKE_C_FLAGS_TEST         "-O0 -s")
+SET(CMAKE_CXX_FLAGS_TEST       "-O0 -s")
 message(STATUS "CMAKE_BUILD_TYPE: ${CMAKE_BUILD_TYPE}")
 
 INCLUDE(FindPkgConfig)
@@ -93,7 +95,7 @@ else()
                SET (TESTS_DIR "/usr/apps/network-manager")
        endif (NOT DEFINED TESTS_DIR)
 
-        pkg_check_modules(pkgs REQUIRED iotivity>=1.3.0 boost libcurl dpm dlog audit-trail)
+       pkg_check_modules(pkgs REQUIRED iotivity>=1.3.0 boost libcurl dpm dlog audit-trail)
 
        FOREACH(flag ${pkgs_CFLAGS})
                SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}")
@@ -136,7 +138,7 @@ add_subdirectory(utest)
 add_subdirectory(nmdaemon)
 
 add_custom_target(runtests
-                  COMMAND utest 52.71.167.178
+                                 COMMAND utest -a 106.125.46.139
                   COMMENT "Run unit tests.\n")
 
 find_program(LCOV NAMES lcov)
index 969e830..e015cb1 100644 (file)
@@ -11,4 +11,35 @@ struct NM_DeviceList {
     NetworkManager::IoTDevicesMap::iterator it;
 };
 
+/**
+ * @brief setINIFilePath change default INI file path
+ * @param path [in] new path of INI file
+ */
+void setINIFilePath(const std::string& path);
+
+/**
+ * @brief setCloudHost set address of the IoT cloud server
+ * @param ip [in] IP address of the IoT cloud server
+ * @param port [in] Port used to connect to the IoT cloud server
+ */
+void setCloudHost(const std::string& ip, int port);
+
+/**
+ * @brief getCloudHost returns IoT cloud server address
+ * @return IoT cloud server address as std::string
+ */
+const std::string& getCloudHost();
+
+/**
+ * @brief setDSMURI set DSM server address
+ * @param uri [in] address of the DSM server
+ */
+void setDSMURI(const std::string& uri);
+
+/**
+ * @brief getDSMURI returns DSM server address
+ * @return DSM server address as std::string
+ */
+const std::string& getDSMURI();
+
 #endif // CTRL_APP_SUPPORT_CPP
index d774032..142a1b2 100644 (file)
@@ -31,12 +31,6 @@ public:
 
     /**
      * @brief Constructor
-     * @param host [in] IoT Cloud host address
-     */
-    HubClient(const std::string& host);
-
-    /**
-     * @brief Constructor
      * @param hub_resource [in] resource tied wiith hub device
      */
     HubClient(std::shared_ptr<OC::OCResource> hub_resource) : resource(hub_resource) {
index a96ba4c..11a4126 100644 (file)
@@ -40,23 +40,10 @@ using namespace NetworkManager;
 namespace
 {
 
-// nmdaemon configuration path
-const std::string INI_FILE_PATH
-{
-    CONFIG_FILE
-};
-// default iotcloud IP (local SRK server)
-const std::string DEFAULT_CLOUD_IP
-{"106.125.46.139"
-};
-// default iotcloud port
-const int DEFAULT_CLOUD_PORT = 5683;
-static std::string cloud_host;
-// default DSM URI (local SRK server)
-const std::string DEFAULT_DSM_URI
-{"http://106.125.46.139:8080/dsm/restapi/"
-};
-static std::string dsm_uri;
+// nmlib configuration path
+static std::string g_ini_file{CONFIG_FILE};
+static std::string g_cloud_host;
+static std::string g_dsm_uri;
 
 bool file_exists(const std::string& file_name)
 {
@@ -64,29 +51,6 @@ bool file_exists(const std::string& file_name)
     return f.good();
 }
 
-void setCloudHost(const std::string& ip, int port)
-{
-    cloud_host = std::string{"coap+tcp://"} + ip + std::string{":"} + std::to_string(port);
-    LOG_D(TAG, "Cloud URI: %s", cloud_host.c_str());
-}
-
-const std::string& getCloudHost()
-{
-    return cloud_host;
-}
-
-void setDSMURI(const std::string& uri)
-{
-    dsm_uri = uri;
-    LOG_D(TAG, "DSM URI: %s", dsm_uri.c_str());
-}
-
-const std::string& getDSMURI()
-{
-    return dsm_uri;
-}
-
-
 /**
  * @brief toASCIIZ allocates space for ASCIIZ string and copy data from std::string
  * @param s [in] input string
@@ -128,6 +92,33 @@ void sig_handler(int sig)
 
 }
 
+void setINIFilePath(const std::string& path)
+{
+    g_ini_file = path;
+}
+
+void setCloudHost(const std::string& ip, int port)
+{
+    g_cloud_host = std::string{"coap+tcp://"} + ip + std::string{":"} + std::to_string(port);
+    LOG_D(TAG, "Cloud URI: %s", g_cloud_host.c_str());
+}
+
+const std::string& getCloudHost()
+{
+    return g_cloud_host;
+}
+
+void setDSMURI(const std::string& uri)
+{
+    g_dsm_uri = uri;
+    LOG_D(TAG, "DSM URI: %s", g_dsm_uri.c_str());
+}
+
+const std::string& getDSMURI()
+{
+    return g_dsm_uri;
+}
+
 static NM_ErrorCode getUUIDs(const IoTDevicesMap& map, char** * uuids)
 {
     FN_VISIT
@@ -169,24 +160,30 @@ NM_ErrorCode NM_init(NM_hContext* ctx)
     *ctx = nullptr;
     bool fail = false;
 
-    if (file_exists(INI_FILE_PATH)) {
+    if (!g_ini_file.empty() && file_exists(g_ini_file)) {
         try {
-            LOG_D(TAG, "Reading configuration from: %s.", INI_FILE_PATH.c_str());
+            LOG_D(TAG, "Reading configuration from: %s.", g_ini_file.c_str());
             boost::property_tree::ptree properties;
-            boost::property_tree::read_ini(INI_FILE_PATH, properties);
-            int cloud_port = properties.get<int>("Cloud.port", DEFAULT_CLOUD_PORT);
-            std::string cloud_ip = properties.get<std::string>("Cloud.ip", DEFAULT_CLOUD_IP);
-            setCloudHost(cloud_ip, cloud_port);
-            std::string dsm_uri = properties.get<std::string>("DSM.uri", DEFAULT_DSM_URI);
-            setDSMURI(dsm_uri);
+            boost::property_tree::read_ini(g_ini_file, properties);
+            int cloud_port = properties.get<int>("Cloud.port", 0);
+            std::string cloud_ip = properties.get<std::string>("Cloud.ip", std::string{});
+            std::string dsm_uri = properties.get<std::string>("DSM.uri", std::string{});
+
+            if (!cloud_ip.empty()) {
+                setCloudHost(cloud_ip, cloud_port);
+            }
+
+            if (!dsm_uri.empty()) {
+                setDSMURI(dsm_uri);
+            }
         } catch (std::exception& e) {
-            LOG_E(TAG, "Config file \"%s\" read error: %s.", INI_FILE_PATH.c_str(), e.what());
+            LOG_E(TAG, "Config file \"%s\" read error: [%s].", g_ini_file.c_str(), e.what());
             return EC_INTERNAL_ERROR;
         }
     } else {
-        LOG_E(TAG, "Config file \"%s\" not found. Using default cloud ip:port and dsm URI", INI_FILE_PATH.c_str());
-        setCloudHost(DEFAULT_CLOUD_IP, DEFAULT_CLOUD_PORT);
-        setDSMURI(DEFAULT_DSM_URI);
+        LOG_E(TAG, "Config file \"%s\" not found.", g_ini_file.c_str());
+        LOG_W(TAG, "Use \"%s\" as IoT cloud address", g_cloud_host.c_str());
+        LOG_W(TAG, "Use \"%s\" as DSM server address", g_dsm_uri.c_str());
     }
 
     auto res = signal(SIGSEGV, sig_handler);
@@ -224,20 +221,23 @@ NM_ErrorCode NM_init(NM_hContext* ctx)
     return EC_OK;
 }
 
-void NM_cleanup(NM_hContext* ctx)
+void NM_cleanup(NM_hContext* hctx)
 {
     FN_VISIT
-    if (ctx != nullptr && *ctx != nullptr) {
-        SecurityContext* sec_context = (*ctx)->context;
+    if (hctx != nullptr && *hctx != nullptr) {
+        NM_hContext ctx = *hctx;
+        SecurityContext* sec_context = ctx->context;
+        if (ctx->instance != nullptr) {
+            ctx->instance->signOut();
+        }
 
         if (sec_context != nullptr) {
             delete sec_context;
         }
 
-        delete *ctx;
-        *ctx = nullptr;
+        delete ctx;
+        *hctx = nullptr;
     }
-    IoTivity::cleanUp();
 }
 
 NM_ErrorCode NM_signIn(NM_hContext ctx, const char* login, const char* pass)
@@ -303,9 +303,9 @@ NM_ErrorCode NM_subscribeDeviceStateChanged(NM_hContext ctx, NM_deviceStateChang
             return EC_NULL_POINTER;
         }
 
-        ctx->instance->setDevicePresenceHook([user_defined, callback](const std::string & di, bool online) {
-            callback(di.c_str(), online ? DS_Online : DS_Offline, user_defined);
-        });
+//        ctx->instance->setDevicePresenceHook([user_defined, callback](const std::string & di, bool online) {
+//            callback(di.c_str(), online ? DS_Online : DS_Offline, user_defined);
+//        });
     } catch (...) {
         return EC_OUT_OF_MEMORY;
     }
@@ -316,9 +316,9 @@ NM_ErrorCode NM_subscribeDeviceStateChanged(NM_hContext ctx, NM_deviceStateChang
 void NM_unsubscribeDeviceStateChanged(NM_hContext ctx)
 {
     FN_VISIT
-    if (ctx != nullptr) {
-        ctx->instance->removeDevicePresenceHook();
-    }
+//    if (ctx != nullptr) {
+//        ctx->instance->removeDevicePresenceHook();
+//    }
 }
 
 NM_ErrorCode NM_getOwnedDevices(NM_hContext ctx, NM_hDeviceList* dev_list)
index e0fac8f..4811e1a 100644 (file)
@@ -28,20 +28,6 @@ namespace NetworkManager
 
 const std::string HubClient::RESOURCE_TYPE{"device.hub"};
 
-HubClient::HubClient(const std::string& host)
-{
-    std::string requestURI{OC_RSRVD_WELL_KNOWN_URI};
-    FindResourceCallback::Sptr callback = std::make_shared<FindResourceCallback>(RESOURCE_TYPE);
-
-    OCPlatform::findResource(host, requestURI, CT_DEFAULT, bind_callback(callback, PH::_1));
-
-    if (!callback->wait()) {
-        LOG_E(TAG, "HubClient found callback not called.");
-    } else {
-        resource = callback->resource;
-    }
-}
-
 HubClient::operator bool() const
 {
     return (bool)resource;
index 2e75b9b..eeb8655 100644 (file)
@@ -213,7 +213,9 @@ const IoTDevicesMap& SecurityContext::getUnOwnedDevices()
 void SecurityContext::subscribeNotifications(NM_NotificationCb callback, void* userData)
 {
     FN_VISIT
-    iotivity->guardUnauthorized();
+    if (!iotivity->isSignedIn()) {
+        throw IoTInternalError("UNAUTHORIZED error", EC_UNAUTHORIZED);
+    }
 
     auto observCb = [callback, userData](const HeaderOptions,
                                          const OCRepresentation & rep,
index 43df948..0b1571a 100644 (file)
@@ -11,7 +11,6 @@
 #ifndef DEVICE_CONTROL_H
 #define DEVICE_CONTROL_H
 
-#include <OCApi.h>
 #include "iotivity.h"
 #include "nmlib.h"
 
index e8bcb60..c04f2d4 100644 (file)
@@ -1,16 +1,11 @@
-#ifndef __IOTIVITY_H__
-#define __IOTIVITY_H__
+#ifndef IOTIVITY_H
+#define IOTIVITY_H
 
-#include "iotdevice.h"
-#include <memory>
-#include <functional>
-#include <vector>
 #include <OCApi.h>
 #include <OCPlatform.h>
 #include <escommon.h>
-#include <mutex>
-#include <condition_variable>
 #include "nmexceptions.h"
+#include "iotdevice.h"
 #include "imqclient.h"
 
 namespace NetworkManager
@@ -22,39 +17,54 @@ class IoTivity
 {
 public:
     static const std::string DEFAULT_PROVIDER;
-    static const int DEFAULT_TIMEOUT;
+
+    /**
+     * @brief setPersistentStoragePath changes default path to persistent storage file (.dat)
+     * @param psPath path to persistent storage file (.dat)
+     */
+    static void setPersistentStoragePath(std::string psPath);
+
+    /**
+     * @brief getPersistentStoragePath returns path to persistent storage file (.dat)
+     * @return path to persistent storage file (.dat)
+     */
+    static const std::string& getPersistentStoragePath();
+
+    /**
+     * @brief getInstance returns pointer to IoTivity singletone instance
+     * @return IoTivity* pointer or nullptr on failure
+     */
+    static IoTivity* getInstance();
 
     /**
      * Indicates that user is signed in
      * @return true if user if signed in
      */
-    bool isSignedIn();
+    virtual bool isSignedIn() = 0;
 
     /**
      * Indicates state of conection to the iot cloud
      * @return true if connected
      */
-    bool isConnected() {
-        return connected;
-    }
+    virtual bool isConnected() = 0;
 
     /**
-     * @brief getInstance returns pointer to IoTivity singletone instance
-     * @return IoTivity* pointer or nullptr on failure
+     * Set connected state of iotivity instance
+     * @param state [in] connection state
      */
-    static IoTivity* getInstance();
+    virtual void setConnected(bool state) = 0;
 
     /**
      * @brief Set hook callback to create subscribtion on device presence notifications. Only one hook can be set.
      * @param hook [in] callback
      */
-    void setDevicePresenceHook(PresenceHook&& hook);
+//    virtual void setDevicePresenceHook(PresenceHook&& hook) = 0;
 
     /**
      * @brief Remove subscribtion on device presence notifications
      * @param hook [in] callback
      */
-    void removeDevicePresenceHook();
+//    virtual void removeDevicePresenceHook() = 0;
 
     /**
      * @brief signIn performs authorization to iotvitiy cloud through OAuth2.
@@ -64,13 +74,13 @@ public:
      * @param auth_provider name of OAuth2 service provider
      * @param access_token OAuth2 access token
      */
-    void signUp(const std::string& host, const std::string& auth_provider, const std::string& access_token);
+    virtual void signUp(const std::string& host, const std::string& auth_provider, const std::string& access_token) = 0;
 
     /**
      * @brief signIn hack method to restore connection with iotivity cloud.
      * Now used after unsubscribeOwnedPresence() due to broken iotivity logic.
      */
-    void signIn();
+    virtual void signIn() = 0;
 
     /**
      * @brief signIn method to restore connection with iotivity cloud.
@@ -78,24 +88,19 @@ public:
      * @param uid id of iot cloud connection to restore
      * @param access_token access token for connection to restore
      */
-    void signIn(const std::string& host, const std::string& uid, const std::string& access_token);
+    virtual void signIn(const std::string& host, const std::string& uid, const std::string& access_token) = 0;
 
     /**
      * @brief signOut performs signout from iotivity cloud
      */
-    void signOut();
+    virtual void signOut() = 0;
 
     /**
      * @brief delete device from IoTivity cloud
      */
-    void deleteFromAccount();
-
-    /**
-     * @brief cleanUp free memory occupied by IoTivity singletone instance
-     */
-    static void cleanUp();
+    virtual void deleteFromAccount() = 0;
 
-    void registerDeviceInfo(const std::string& name, const std::string& model, const std::string& type);
+    virtual void registerDeviceInfo(const std::string& name, const std::string& model, const std::string& type) = 0;
 
     /**
      * @brief findDevices return found devices
@@ -104,10 +109,10 @@ public:
      * @param cloud search on cloud flag, default false - search locally
      * @return vector of found devices shared pointers
      */
-    std::vector<IoTDevicePtr> findDevices(
+    virtual std::vector<IoTDevicePtr> findDevices(
         bool cloud = false,
         OCConnectivityType con_type = CT_DEFAULT,
-        const std::string& uri = "/oic/res?rt=" OC_RSRVD_ES_RES_TYPE_EASYSETUP);
+        const std::string& uri = "/oic/res?rt=" OC_RSRVD_ES_RES_TYPE_EASYSETUP) = 0;
 
     /**
      * @brief API for Resource Discovery.
@@ -117,156 +122,84 @@ public:
      *                           interface. Example: CT_DEFAULT, CT_ADAPTER_IP, CT_ADAPTER_TCP.
      * @param cloud search on cloud flag (default false - search locally)
      */
-    std::shared_ptr<OC::OCResource> findResource(
+    virtual std::shared_ptr<OC::OCResource> findResource(
         bool cloud,
         const std::string& type,
         const std::string& uri = OC_RSRVD_WELL_KNOWN_URI,
-        OCConnectivityType con_type = CT_DEFAULT);
+        OCConnectivityType con_type = CT_DEFAULT) = 0;
 
-    std::vector<std::shared_ptr<OC::OCResource>> findResourceList(
+    virtual std::vector<std::shared_ptr<OC::OCResource>> findResourceList(
                 bool cloud,
                 const std::string& type,
                 const std::string& uri = OC_RSRVD_WELL_KNOWN_URI,
-                OCConnectivityType con_type = CT_DEFAULT);
+                OCConnectivityType con_type = CT_DEFAULT) = 0;
 
-    std::shared_ptr<OC::OCResource> findResource(
+    virtual std::shared_ptr<OC::OCResource> findResource(
         const std::string& host,
         const std::string& type,
         const std::string& uri = OC_RSRVD_WELL_KNOWN_URI,
-        OCConnectivityType con_type = CT_DEFAULT);
+        OCConnectivityType con_type = CT_DEFAULT) = 0;
 
-    std::shared_ptr<OC::OCResource> findResource(
+    virtual std::shared_ptr<OC::OCResource> findResource(
         const std::string& host,
         const std::string& type,
         const std::string& uri,
-        const std::string& sid);
+        const std::string& sid) = 0;
 
     /**
      * @brief getDeviceID returns device id (DUID) from iotivity persistant storage
      * @return string that indicates duid
      */
-    const std::string& getDeviceID();
+    virtual const std::string& getDeviceID() = 0;
 
     /**
      * @brief Publish resources to resource directory. If handles is empty the device info and
      *        the platform info are published.
      * @param handles [in] handles of the resources to be published.
      */
-    void publishResources(OC::ResourceHandles& handles);
+    virtual void publishResources(OC::ResourceHandles& handles) = 0;
 
     /**
      * @brief Delete resources from resource directory.
      * @param handles [in] handles of the resources to be deleted.
      */
-    void unPublishResources(OC::ResourceHandles& handles);
+    virtual void unPublishResources(OC::ResourceHandles& handles) = 0;
 
     /**
      * @brief Delete all resources from resource directory.
      */
-    void unPublishAllResources();
-
-    /**
-     * @brief setPersistentStoragePath changes default path to persistent storage file (.dat)
-     * @param psPath path to persistent storage file (.dat)
-     */
-    static void setPersistentStoragePath(std::string psPath);
-
-    /**
-     * @brief getPersistentStoragePath returns path to persistent storage file (.dat)
-     * @return path to persistent storage file (.dat)
-     */
-    const std::string& getPersistentStoragePath();
+    virtual void unPublishAllResources() = 0;
 
     /**
      * @brief host address of iot cloud
      * @return returns iot cloud host address if set or empty string otherwise
      */
-    const std::string& host() {
-        return cloud_host;
-    }
+    virtual const std::string& host() = 0;
 
     /**
      * @brief cloudId provide iot cloud server id information
      * @return iot cloud server identifier
      */
-    const std::string& cloudId() {
-        return cloud_sid;
-    }
-
-    /**
-     * @brief guardUnauthorized throws if not authorized on iot cloud
-     */
-    void guardUnauthorized();
+    virtual const std::string& cloudId() = 0;
 
     /**
      * @brief getCloudAuthId returns id used for iot cloud signIn method
      * @return id or empty string if not set
      */
-    const std::string& getCloudAuthId() {
-        return cloud_uid;
-    }
+    virtual const std::string& getCloudAuthId() = 0;
 
     /**
      * @brief getCloudAccessToken returns access token used for iot cloud signIn method
      * @return
      */
-    const std::string& getCloudAccessToken() {
-        return cloud_access_token;
-    }
-
-    IMqClient* getMqHandler();
+    virtual const std::string& getCloudAccessToken() = 0;
 
+    virtual IMqClient* getMqHandler() = 0;
 
-private:
-    /**
-     * @brief unsubscribeOwnedPresence unsubscribe from device presence
-     * callback after calling getOwnedDevices()
-     */
-    void unsubscribeOwnedPresence();
-
-    /*
-    void devicePresenceHandle(
-        const OC::HeaderOptions& hOptions,
-        const OC::OCRepresentation& rep,
-        const int eCode,
-        const int seqN);
-        */
-
-    static void connectionChangedCallback(const std::string& url, int con_type, bool state);
-
-    IoTivity();
-    ~IoTivity();
-
-    static IoTivity instance;
-    /**
-     * Path to persistent storage to get device id.
-     * Default depends on -DPS_PATH definition.
-     */
+protected:
     static std::string persistent_storage_path;
-    static OCPersistentStorage persistent_storage;
-    static OC::PlatformConfig platform_config;
-
-    std::string device_id;
-    std::string cloud_host;
-    std::string cloud_sid;
-    std::string cloud_uid;
-    std::string cloud_access_token;
-
-    OC::OCAccountManager::Ptr account_mgr;
-    IMqClient::Ptr mq_handler;
-    PresenceHook presence_hook;
-    OC::OCPlatform::OCPresenceHandle presence_handle;
-
-    std::condition_variable presence_cb_cv;
-
-    std::mutex instance_mutex;
-    std::mutex notification_mtx;
-
-    bool signed_in;
-    bool connected;
 };
 
-
 }
 
-#endif //__IOTIVITY_H__
+#endif // IOTIVITY_H
diff --git a/device_core/iotivity_lib/inc/iotivity_impl.h b/device_core/iotivity_lib/inc/iotivity_impl.h
new file mode 100644 (file)
index 0000000..3bce843
--- /dev/null
@@ -0,0 +1,251 @@
+#ifndef __IOTIVITY_IMPL_H__
+#define __IOTIVITY_IMPL_H__
+
+#include <mutex>
+#include <condition_variable>
+#include "iotivity.h"
+
+namespace NetworkManager
+{
+
+typedef std::function<void(const std::string&, bool)> PresenceHook;
+
+class IoTivity_impl: public IoTivity
+{
+public:
+
+    IoTivity_impl();
+    ~IoTivity_impl();
+
+    /**
+     * Indicates that user is signed in
+     * @return true if user if signed in
+     */
+    bool isSignedIn() override;
+
+    /**
+     * Indicates state of conection to the iot cloud
+     * @return true if connected
+     */
+    bool isConnected() override
+    {
+        std::lock_guard<std::mutex> lock(instance_mutex);
+        return connected;
+    }
+
+    /**
+     * Set connected state of iotivity instance
+     * @param state [in] connection state
+     */
+    void setConnected(bool state) override
+    {
+        std::lock_guard<std::mutex> lock(instance_mutex);
+        connected = state;
+    }
+
+    /**
+     * @brief Set hook callback to create subscribtion on device presence notifications. Only one hook can be set.
+     * @param hook [in] callback
+     */
+//    void setDevicePresenceHook(PresenceHook&& hook) override;
+
+    /**
+     * @brief Remove subscribtion on device presence notifications
+     * @param hook [in] callback
+     */
+//    void removeDevicePresenceHook() override;
+
+    /**
+     * @brief signIn performs authorization to iotvitiy cloud through OAuth2.
+     * Currently used own samsung OAuth2 provider.
+     *
+     * @param host address of server. ex: "coap+tcp://106.125.46.44:5683"
+     * @param auth_provider name of OAuth2 service provider
+     * @param access_token OAuth2 access token
+     */
+    void signUp(const std::string& host, const std::string& auth_provider, const std::string& access_token) override;
+
+    /**
+     * @brief signIn hack method to restore connection with iotivity cloud.
+     * Now used after unsubscribeOwnedPresence() due to broken iotivity logic.
+     */
+    void signIn() override;
+
+    /**
+     * @brief signIn method to restore connection with iotivity cloud.
+     * @param host address of the host to connect to
+     * @param uid id of iot cloud connection to restore
+     * @param access_token access token for connection to restore
+     */
+    void signIn(const std::string& host, const std::string& uid, const std::string& access_token) override;
+
+    /**
+     * @brief signOut performs signout from iotivity cloud
+     */
+    void signOut() override;
+
+    /**
+     * @brief delete device from IoTivity cloud
+     */
+    void deleteFromAccount() override;
+
+    void registerDeviceInfo(const std::string& name, const std::string& model, const std::string& type) override;
+
+    /**
+     * @brief findDevices return found devices
+     * @param uri specific device uri
+     * @param con_type specific connectivity type
+     * @param cloud search on cloud flag, default false - search locally
+     * @return vector of found devices shared pointers
+     */
+    std::vector<IoTDevicePtr> findDevices(
+        bool cloud = false,
+        OCConnectivityType con_type = CT_DEFAULT,
+        const std::string& uri = "/oic/res?rt=" OC_RSRVD_ES_RES_TYPE_EASYSETUP) override;
+
+    /**
+     * @brief API for Resource Discovery.
+     * @param type resource type to filter
+     * @param uri name of the resource. If null or empty, performs search for all resource names
+     * @param connectivityType ::OCConnectivityType type of connectivity indicating the
+     *                           interface. Example: CT_DEFAULT, CT_ADAPTER_IP, CT_ADAPTER_TCP.
+     * @param cloud search on cloud flag (default false - search locally)
+     */
+    std::shared_ptr<OC::OCResource> findResource(
+        bool cloud,
+        const std::string& type,
+        const std::string& uri = OC_RSRVD_WELL_KNOWN_URI,
+        OCConnectivityType con_type = CT_DEFAULT) override;
+
+    std::vector<std::shared_ptr<OC::OCResource>> findResourceList(
+                bool cloud,
+                const std::string& type,
+                const std::string& uri = OC_RSRVD_WELL_KNOWN_URI,
+                OCConnectivityType con_type = CT_DEFAULT) override;
+
+    std::shared_ptr<OC::OCResource> findResource(
+        const std::string& host,
+        const std::string& type,
+        const std::string& uri = OC_RSRVD_WELL_KNOWN_URI,
+        OCConnectivityType con_type = CT_DEFAULT) override;
+
+    std::shared_ptr<OC::OCResource> findResource(
+        const std::string& host,
+        const std::string& type,
+        const std::string& uri,
+        const std::string& sid) override;
+
+    /**
+     * @brief getDeviceID returns device id (DUID) from iotivity persistant storage
+     * @return string that indicates duid
+     */
+    const std::string& getDeviceID() override;
+
+    /**
+     * @brief Publish resources to resource directory. If handles is empty the device info and
+     *        the platform info are published.
+     * @param handles [in] handles of the resources to be published.
+     */
+    void publishResources(OC::ResourceHandles& handles) override;
+
+    /**
+     * @brief Delete resources from resource directory.
+     * @param handles [in] handles of the resources to be deleted.
+     */
+    void unPublishResources(OC::ResourceHandles& handles) override;
+
+    /**
+     * @brief Delete all resources from resource directory.
+     */
+    void unPublishAllResources() override;
+
+    /**
+     * @brief host address of iot cloud
+     * @return returns iot cloud host address if set or empty string otherwise
+     */
+    const std::string& host() override
+    {
+        return cloud_host;
+    }
+
+    /**
+     * @brief cloudId provide iot cloud server id information
+     * @return iot cloud server identifier
+     */
+    const std::string& cloudId() override
+    {
+        return cloud_sid;
+    }
+
+    /**
+     * @brief getCloudAuthId returns id used for iot cloud signIn method
+     * @return id or empty string if not set
+     */
+    const std::string& getCloudAuthId() override
+    {
+        return cloud_uid;
+    }
+
+    /**
+     * @brief getCloudAccessToken returns access token used for iot cloud signIn method
+     * @return
+     */
+    const std::string& getCloudAccessToken() override
+    {
+        return cloud_access_token;
+    }
+
+    IMqClient* getMqHandler() override;
+
+
+private:
+
+    friend class IoTivity;
+    /**
+     * @brief unsubscribeOwnedPresence unsubscribe from device presence
+     * callback after calling getOwnedDevices()
+     */
+    void unsubscribeOwnedPresence();
+
+    /*
+    void devicePresenceHandle(
+        const OC::HeaderOptions& hOptions,
+        const OC::OCRepresentation& rep,
+        const int eCode,
+        const int seqN);
+        */
+
+    static void connectionChangedCallback(const std::string& url, int con_type, bool state);
+
+    /**
+     * Path to persistent storage to get device id.
+     * Default depends on -DPS_PATH definition.
+     */
+    static OCPersistentStorage persistent_storage;
+    static OC::PlatformConfig platform_config;
+    static IoTivity_impl instance;
+
+    std::string device_id;
+    std::string cloud_host;
+    std::string cloud_sid;
+    std::string cloud_uid;
+    std::string cloud_access_token;
+
+    OC::OCAccountManager::Ptr account_mgr;
+    IMqClient::Ptr mq_handler;
+    PresenceHook presence_hook;
+    OC::OCPlatform::OCPresenceHandle presence_handle;
+
+    std::condition_variable presence_cb_cv;
+
+    std::mutex instance_mutex;
+    std::mutex notification_mtx;
+
+    bool signed_in;
+    bool connected;
+};
+
+
+}
+
+#endif //__IOTIVITY_IMPL_H__
index 4881a77..03c5e09 100644 (file)
 #include "iotivity.h"
-#include "iotdevice_impl.h"
-#include <iostream>
-#include <chrono>
-#include <sstream>
-#include <iomanip>
-#include "nmlib.h"
-#include "iotutils.h"
-#include "nmexceptions.h"
+#include "iotivity_impl.h"
 
-#pragma GCC diagnostic push
-#pragma GCC diagnostic ignored "-Wreorder"
-#include <OCApi.h>
-#include <OCPlatform.h>
-#include "RDClient.h"
-#pragma GCC diagnostic pop
-#include <logging.h>
-#include <CAManager.h>
-#include "resource_callbacks.h"
-#include "mqclient.h"
-
-using namespace std;
-using namespace OC;
-namespace PH = std::placeholders;
-
-#define TAG "NetworkManager"
 #define STRINGIFY(x) #x
 #define TOSTRING(x) STRINGIFY(x)
 
-namespace
-{
-
-const std::string SIGNUP = "Sign up";
-const std::string SIGNIN = "Sign in";
-const std::string SIGNOUT = "Sign out";
-
-} // namespace
-
 namespace NetworkManager
 {
 
-const std::string IoTivity::DEFAULT_PROVIDER = "Samsung";
-const int IoTivity::DEFAULT_TIMEOUT = 3;
+const std::string IoTivity::DEFAULT_PROVIDER{"Samsung"};
 std::string IoTivity::persistent_storage_path = TOSTRING(PS_PATH) "/./nmlib_ps.dat";
-static FILE* openPersistentStorage(const char* ps_path, const char* mode);
-
-OCPersistentStorage IoTivity::persistent_storage{openPersistentStorage, fread, fwrite, fclose, unlink};
-
-OC::PlatformConfig IoTivity::platform_config{
-    OC::ServiceType::InProc,
-    OC::ModeType::Both,
-    "0.0.0.0",
-    0,
-    OC::QualityOfService::HighQos,
-    &IoTivity::persistent_storage
-};
-
-IoTivity IoTivity::instance;
-
-FILE* openPersistentStorage(const char* ps_path, const char* mode)
-{
-    if (0 == strcmp(ps_path, OC_SECURITY_DB_DAT_FILE_NAME)) {
-        string path = IoTivity::getInstance()->getPersistentStoragePath();
-        return fopen(path.c_str(), mode);
-    } else {
-        return fopen(ps_path, mode);
-    }
-}
-
-void adapterChangedCallback(OCTransportAdapter adapter, bool state)
-{
-    LOG_D(TAG, "Adapter Changed adapter[%s] = %s", getAdapter(adapter), state ? "true" : "false");
-}
-
-void IoTivity::connectionChangedCallback(const std::string& conn, /*OCConnectivityType*/int con_type, bool state)
-{
-    LOG_D(TAG, "Connection Changed connection[%s], type = %s, state = %s", conn.c_str(),
-          getConType((OCConnectivityType)con_type).c_str(), state ? "true" : "false");
-
-    IoTivity* iotivity = IoTivity::getInstance();
-    std::unique_lock<std::mutex> lock(iotivity->instance_mutex);
-
-    if (iotivity->cloud_host.find(conn) != std::string::npos) {
-        LOG_I(TAG, "Cloud connection changed");
-        if (!state) {
-            LOG_D(TAG, "Connection lost.");
-//            iotivity->connected = false;
-        }
-
-        iotivity->connected = state;
-    }
-}
-
-IoTivity::IoTivity(): cloud_host(), account_mgr(nullptr), presence_handle(nullptr), signed_in(false), connected(false)
-{
-    FN_VISIT
-    auto res = CAManager::setNetworkMonitorHandler(adapterChangedCallback, connectionChangedCallback);
-    if (OC_STACK_OK != res) {
-        LOG_E(TAG, "CAManager::setNetworkMonitorHandler failed with code = %d", res);
-    }
-
-    OC::OCPlatform::Configure(IoTivity::platform_config);
-}
-
-IoTivity::~IoTivity()
-{
-    FN_VISIT
-    try {
-        CAManager::unsetNetworkMonitorHandler();
-        signOut();
-    } catch (...) {
-    }
-}
 
 IoTivity* IoTivity::getInstance()
 {
-    return &instance;
-}
-
-IMqClient* IoTivity::getMqHandler()
-{
-    IMqClient* handler = mq_handler.get();
-
-    if (handler == nullptr) {
-        LOG_W(TAG, "getMqHandler(): MqHandler uninitialized");
-        throw std::runtime_error("Failed to connect to message queue");
-    }
-
-    return handler;
-}
-
-void IoTivity::cleanUp()
-{
-    instance.signOut();
-}
-
-void IoTivity::registerDeviceInfo(const std::string& name, const std::string& model, const std::string& type)
-{
-    OCDeviceInfo di;
-    OCStringLL dt;
-    OCStringLL dm;
-    dt.value = (char*)type.c_str();
-    dt.next = NULL;
-    dm.value = (char*)model.c_str();
-    dm.next = NULL;
-    di.deviceName = (char*)name.c_str();
-    di.types = &dt;
-    di.specVersion = NULL;
-    di.dataModelVersions = &dm;
-
-    auto result = OCPlatform::registerDeviceInfo(di);
-    if (OC_STACK_OK != result) {
-        throw IoTInternalError("registerDeviceInfo failed", result);
-    }
-}
-
-std::vector<IoTDevicePtr> IoTivity::findDevices(bool cloud, OCConnectivityType con_type, const std::string& uri)
-{
-    if (cloud) {
-        if (!signed_in) {
-            throw IoTInternalError("Not signed in", EC_UNAUTHORIZED);
-        } else if (!connected) {
-            signIn();
-        }
-    }
-
-    std::vector<IoTDevicePtr> devices;
-    FindDeviceListCallback::Sptr callback = std::make_shared<FindDeviceListCallback>(devices, con_type);
-
-    OC::OCPlatform::findResourceList(cloud ? cloud_host : "", uri, con_type, bind_callback(callback, PH::_1),
-                                     OC::QualityOfService::HighQos);
-    callback->wait_timeout(std::chrono::seconds(DEFAULT_TIMEOUT));
-
-    return devices;
-}
-
-std::shared_ptr<OC::OCResource> IoTivity::findResource(bool cloud, const std::string& type, const std::string& uri,
-        OCConnectivityType con_type)
-{
-    FindResourceCallback::Sptr callback = std::make_shared<FindResourceCallback>(type);
-    OCPlatform::findResource(cloud ? cloud_host : "", uri, con_type, bind_callback(callback, PH::_1));
-
-    if (!callback->wait()) {
-        LOG_E(TAG, "IoTivity::findResource callback not called. cloud: \"%s\", Uri: \"%s\", Type: \"%s\"",
-              (cloud ? "true" : "false"), uri.c_str(), type.c_str());
-    }
-
-    return callback->resource;
-}
-
-std::vector<std::shared_ptr<OC::OCResource>> IoTivity::findResourceList(bool cloud, const std::string& type,
-        const std::string& uri, OCConnectivityType con_type)
-{
-    std::vector<std::shared_ptr<OC::OCResource>> resources;
-    FindResourceListCallback::Sptr callback = std::make_shared<FindResourceListCallback>(resources, con_type, type);
-    OCPlatform::findResourceList(cloud ? cloud_host : "", uri, con_type, bind_callback(callback, PH::_1));
-
-    callback->wait_timeout();
-    if (!callback->fired) {
-        LOG_E(TAG, "IoTivity::findResourceList callback not called. cloud: \"%s\", Uri: \"%s\", Type: \"%s\"",
-              (cloud ? "true" : "false"), uri.c_str(), type.c_str());
-    }
-
-    return resources;
-}
-
-std::shared_ptr<OC::OCResource> IoTivity::findResource(const std::string& host, const std::string& type,
-        const std::string& uri, OCConnectivityType con_type)
-{
-    FindResourceCallback::Sptr callback = std::make_shared<FindResourceCallback>(type);
-    OCPlatform::findResource(host, uri, con_type, bind_callback(callback, PH::_1));
-
-    if (!callback->wait()) {
-        LOG_E(TAG, "IoTivity::findResource callback not called. Host: \"%s\", Uri: \"%s\", Type: \"%s\"",
-              host.c_str(), uri.c_str(), type.c_str());
-    }
-
-    return callback->resource;
-}
-
-std::shared_ptr<OC::OCResource> IoTivity::findResource(
-    const std::string& host,
-    const std::string& type,
-    const std::string& uri,
-    const std::string& sid)
-{
-    FindResourceCallback::Sptr callback = std::make_shared<FindResourceCallback>(type, CT_DEFAULT, sid);
-    OCPlatform::findResource(host, uri, CT_DEFAULT, bind_callback(callback, PH::_1));
-
-    if (!callback->wait()) {
-        LOG_E(TAG, "IoTivity::findResource callback not called. Host: \"%s\", Uri: \"%s\", Type: \"%s\"",
-              host.c_str(), uri.c_str(), type.c_str());
-    }
-
-    return callback->resource;
-}
-
-void IoTivity::guardUnauthorized()
-{
-    if (!signed_in) {
-        throw IoTInternalError("UNAUTHORIZED error", EC_UNAUTHORIZED);
-    }
-}
-
-struct SignInCallback {
-    int resultCode = 0;
-    bool timeout = true;
-    std::condition_variable condVar;
-    std::string sid;
-
-    static void call(weak_ptr<SignInCallback> wptr,
-                     const HeaderOptions&,
-                     const OCRepresentation& rep,
-                     const int resultCode) {
-        if (auto p = wptr.lock()) {
-            p->resultCode = resultCode;
-            p->timeout = false;
-            p->sid = rep.getValueToString("sid");
-            p->condVar.notify_all();
-        }
-    }
-};
-
-struct SignUpCallback {
-    int resultCode = 0;
-    bool timeout = true;
-    std::condition_variable condVar;
-
-    std::string uid;
-    std::string sid;
-    std::string accessToken;
-
-    static void call(weak_ptr<SignUpCallback> wptr,
-                     const HeaderOptions&,
-                     const OCRepresentation& rep,
-                     const int resultCode) {
-        if (auto p = wptr.lock()) {
-            p->resultCode = resultCode;
-            if (resultCode == 4) {
-                p->uid = rep.getValueToString("uid");
-                p->sid = rep.getValueToString("sid");
-                p->accessToken = rep.getValueToString("accesstoken");
-            }
-            p->timeout = false;
-            p->condVar.notify_all();
-        }
-    }
-};
-
-void IoTivity::signUp(const std::string& host, const std::string& auth_provider, const std::string& access_token)
-{
-    FN_VISIT
-    if (host.empty() || auth_provider.empty() || access_token.empty()) {
-        throw std::invalid_argument("Wrong signUp credentials");
-    }
-
-    OCAccountManager::Ptr accountMgr = OCPlatform::constructAccountManagerObject(host, CT_ADAPTER_TCP);
-
-
-    if (!accountMgr) {
-        throw IoTInternalError("Can not create account manager", EC_IOTIVITY_ERROR);
-    }
-
-    std::unique_lock<std::mutex> lock(instance_mutex);
-
-    signed_in = false;
-
-    shared_ptr<SignUpCallback> signUpCb = make_shared<SignUpCallback>();
-
-    guardErrorCode(accountMgr->signUp(
-                       auth_provider,
-                       access_token,
-                       std::bind(SignUpCallback::call, weak_ptr<SignUpCallback>(signUpCb), PH::_1, PH::_2, PH::_3)), SIGNUP);
-
-
-    signUpCb->condVar.wait_for(lock, std::chrono::seconds(DEFAULT_TIMEOUT));
-    guardTimeout(signUpCb->timeout, SIGNUP);
-    guardPostErrorCode(signUpCb->resultCode, SIGNUP);
-
-    cloud_host = host;
-    cloud_uid = signUpCb->uid;
-    cloud_sid = signUpCb->sid;
-    cloud_access_token = signUpCb->accessToken;
-    account_mgr = accountMgr;
-
-    lock.unlock();
-    signIn();
-}
-
-void IoTivity::signIn(const std::string& host, const std::string& uid, const std::string& access_token)
-{
-    cloud_host = host;
-    cloud_uid = uid;
-    cloud_access_token = access_token;
-    if (!account_mgr) {
-        account_mgr = OCPlatform::constructAccountManagerObject(host, CT_ADAPTER_TCP);
-    }
-    signIn();
-}
-
-void IoTivity::signIn()
-{
-    FN_VISIT
-    if (!account_mgr) {
-        throw IoTInternalError("No account manager", EC_IOTIVITY_ERROR);
-    }
-
-    std::unique_lock<std::mutex> lock(instance_mutex);
-
-    shared_ptr<SignInCallback> signInCb = make_shared<SignInCallback>();
-
-    guardErrorCode(account_mgr->signIn(
-                       cloud_uid,
-                       cloud_access_token,
-                       std::bind(SignInCallback::call, weak_ptr<SignInCallback>(signInCb), PH::_1, PH::_2, PH::_3)), SIGNIN);
-
-    signInCb->condVar.wait_for(lock, std::chrono::seconds(DEFAULT_TIMEOUT));
-    guardTimeout(signInCb->timeout, SIGNIN);
-    guardPostErrorCode(signInCb->resultCode, SIGNIN);
-
-    if (cloud_sid.empty()) {
-        cloud_sid = signInCb->sid;
-    }
-    signed_in = true;
-    connected = true;
-
-    mq_handler = std::make_shared<MqClient>(cloud_host);
-}
-
-void IoTivity::signOut()
-{
-    FN_VISIT
-    if (!signed_in) {
-        return;
-    }
-    signed_in = false;
-
-    if (cloud_host.empty() || cloud_access_token.empty()) {
-        LOG_W(TAG, "SignOut without SignIn");
-        return;
-    }
-
-    if (!account_mgr) {
-        throw IoTInternalError("No account manager", EC_IOTIVITY_ERROR);
-    }
-
-    std::mutex mtx;
-    std::unique_lock<std::mutex> lock(mtx);
-
-    shared_ptr<SignInCallback> signOutCb = make_shared<SignInCallback>();
-
-    guardErrorCode(account_mgr->signOut(
-                       cloud_access_token,
-                       std::bind(SignInCallback::call, weak_ptr<SignInCallback>(signOutCb), PH::_1, PH::_2, PH::_3)), SIGNOUT);
-
-    signOutCb->condVar.wait_for(lock, std::chrono::seconds(DEFAULT_TIMEOUT));
-    guardTimeout(signOutCb->timeout, SIGNOUT);
-
-    // No need to throw OC_STACK_UNAUTHORIZED_REQ error
-    if (signOutCb->resultCode != OC_STACK_UNAUTHORIZED_REQ) {
-        guardPostErrorCode(signOutCb->resultCode, SIGNOUT);
-    }
-}
-
-void IoTivity::deleteFromAccount()
-{
-    FN_VISIT
-    if (!signed_in) {
-        return;
-    }
-    signed_in = false;
-
-    if (cloud_host.empty() || cloud_access_token.empty()) {
-        LOG_W(TAG, "SignOut without SignIn");
-        return;
-    }
-
-    if (!account_mgr) {
-        throw IoTInternalError("No account manager", EC_IOTIVITY_ERROR);
-    }
-
-    auto deleteMutex = std::make_shared<std::mutex>();
-    weak_ptr<std::mutex> deleteMutexWptr(deleteMutex);
-    std::unique_lock<std::mutex> lock(*deleteMutex);
-    std::condition_variable cv;
-    bool called = false;
-    int code = OC_STACK_ERROR;
-
-    auto deleteCallback = [deleteMutexWptr, &cv, &called, &code](const HeaderOptions&, const int ecode) {
-        if (auto mtx = deleteMutexWptr.lock()) {
-            called = true;
-            code = ecode;
-            cv.notify_all();
-        }
-    };
-
-    account_mgr->deleteDevice(cloud_access_token, getDeviceID(), deleteCallback);
-
-    cv.wait_for(lock, std::chrono::seconds(DEFAULT_TIMEOUT), [&called] { return called; });
-
-    if (!called || code > OC_STACK_RESOURCE_CHANGED) {
-        throw IoTInternalError("Failed to delete device from account", EC_IOTIVITY_ERROR);
-    }
-}
-
-/*
-void IoTivity::devicePresenceHandle(
-    const HeaderOptions& hOptions,
-    const OCRepresentation& rep,
-    const int eCode,
-    const int seqN)
-{
-    FN_VISIT
-
-    std::string state{"off"};
-    std::string di;
-    rep.getValue("state", state);
-
-    if (rep.getValue("di", di))
-    {
-        bool isOn = state == "on";
-
-        if ((bool)presence_hook)
-        {
-            presence_hook(di, isOn);
-        }
-    }
-}
-*/
-
-void IoTivity::setDevicePresenceHook(PresenceHook&& hook)
-{
-    presence_hook = hook;
-}
-
-void IoTivity::removeDevicePresenceHook()
-{
-    presence_hook = PresenceHook{};
-}
-
-bool IoTivity::isSignedIn()
-{
-    return signed_in;
-}
-
-const string& IoTivity::getDeviceID()
-{
-    if (device_id.empty()) {
-        OCUUIdentity deviceId;
-        if (OC_STACK_OK == OC::OCPlatform::getDeviceId(&deviceId)) {
-            unsigned char* id = deviceId.id;
-            ostringstream os;
-            os << hex << setfill('0');
-            os << setw(2) << (unsigned)id[0];
-            os << setw(2) << (unsigned)id[1];
-            os << setw(2) << (unsigned)id[2];
-            os << setw(2) << (unsigned)id[3] << '-';
-
-            os << setw(2) << (unsigned)id[4];
-            os << setw(2) << (unsigned)id[5] << '-';
-
-            os << setw(2) << (unsigned)id[6];
-            os << setw(2) << (unsigned)id[7] << '-';
-
-            os << setw(2) << (unsigned)id[8];
-            os << setw(2) << (unsigned)id[9] << '-';
-
-            os << setw(2) << (unsigned)id[10];
-            os << setw(2) << (unsigned)id[11];
-            os << setw(2) << (unsigned)id[12];
-            os << setw(2) << (unsigned)id[13];
-            os << setw(2) << (unsigned)id[14];
-            os << setw(2) << (unsigned)id[15];
-            device_id = os.str();
-        }
-    }
-
-    return device_id;
-
-}
-
-void IoTivity::publishResources(OC::ResourceHandles& handles)
-{
-    ResourcePublishCallback::Sptr callback = std::make_shared<ResourcePublishCallback>();
-    auto res = RDClient::Instance().publishResourceToRD(cloud_host, CT_ADAPTER_TCP, handles, bind_callback(callback, PH::_1,
-               PH::_2));
-
-    if (res != OC_STACK_OK) {
-        throw IoTInternalError("Failed to publish resources", res);
-    }
-
-    bool ok = callback->wait();
-
-    if (!ok || callback->errorCode > OC_STACK_RESOURCE_CHANGED) {
-        throw IoTInternalError("Failed to publish resources", callback->errorCode);
-    }
-}
-
-void IoTivity::unPublishResources(OC::ResourceHandles& handles)
-{
-    ResourcePublishCallback::Sptr callback = std::make_shared<ResourcePublishCallback>();
-    auto res = RDClient::Instance().deleteResourceFromRD(cloud_host, CT_ADAPTER_TCP, handles, bind_callback(callback,
-               OCRepresentation{}, PH::_1));
-
-    if (res != OC_STACK_OK) {
-        throw IoTInternalError("Failed to unpublish resources", res);
-    }
-
-    bool ok = callback->wait();
-
-    if (!ok || callback->errorCode > OC_STACK_RESOURCE_CHANGED) {
-        throw IoTInternalError("Failed to unpublish resources", callback->errorCode);
-    }
-}
-
-void IoTivity::unPublishAllResources()
-{
-    OC::ResourceHandles handles;
-    RDClient::Instance().deleteResourceFromRD(cloud_host, CT_ADAPTER_TCP, handles, [](int) {});
+    return &IoTivity_impl::instance;
 }
 
 void IoTivity::setPersistentStoragePath(std::string newPath)
 {
-    instance.device_id.clear();
+    IoTivity_impl::instance.device_id.clear();
     persistent_storage_path = newPath;
 }
 
diff --git a/device_core/iotivity_lib/src/iotivity_impl.cpp b/device_core/iotivity_lib/src/iotivity_impl.cpp
new file mode 100644 (file)
index 0000000..0384c4a
--- /dev/null
@@ -0,0 +1,537 @@
+#include "iotivity_impl.h"
+#include "iotdevice_impl.h"
+#include <iostream>
+#include <chrono>
+#include <sstream>
+#include <iomanip>
+#include "nmlib.h"
+#include "iotutils.h"
+#include "nmexceptions.h"
+
+#pragma GCC diagnostic push
+#pragma GCC diagnostic ignored "-Wreorder"
+#include <OCPlatform.h>
+#include "RDClient.h"
+#pragma GCC diagnostic pop
+#include <logging.h>
+#include <CAManager.h>
+#include "resource_callbacks.h"
+#include "mqclient.h"
+
+using namespace std;
+using namespace OC;
+namespace PH = std::placeholders;
+
+#define TAG "NetworkManager"
+
+namespace
+{
+
+const std::string SIGNUP = "Sign up";
+const std::string SIGNIN = "Sign in";
+const std::string SIGNOUT = "Sign out";
+const int DEFAULT_TIMEOUT = 3;
+
+} // namespace
+
+namespace NetworkManager
+{
+
+static FILE* openPersistentStorage(const char* ps_path, const char* mode);
+
+OCPersistentStorage IoTivity_impl::persistent_storage{openPersistentStorage, fread, fwrite, fclose, unlink};
+
+OC::PlatformConfig IoTivity_impl::platform_config{
+    OC::ServiceType::InProc,
+    OC::ModeType::Both,
+    "0.0.0.0",
+    0,
+    OC::QualityOfService::HighQos,
+    &IoTivity_impl::persistent_storage
+};
+
+IoTivity_impl IoTivity_impl::instance;
+
+FILE* openPersistentStorage(const char* ps_path, const char* mode)
+{
+    if (0 == strcmp(ps_path, OC_SECURITY_DB_DAT_FILE_NAME)) {
+        string path = IoTivity::getPersistentStoragePath();
+        return fopen(path.c_str(), mode);
+    } else {
+        return fopen(ps_path, mode);
+    }
+}
+
+void adapterChangedCallback(OCTransportAdapter adapter, bool state)
+{
+    LOG_D(TAG, "Adapter Changed adapter[%s] = %s", getAdapter(adapter), state ? "true" : "false");
+}
+
+void IoTivity_impl::connectionChangedCallback(const std::string& conn, /*OCConnectivityType*/int con_type, bool state)
+{
+    LOG_D(TAG, "Connection Changed connection[%s], type = %s, state = %s", conn.c_str(),
+          getConType((OCConnectivityType)con_type).c_str(), state ? "true" : "false");
+
+    IoTivity* iotivity = IoTivity::getInstance();
+
+    if (iotivity->host().find(conn) != std::string::npos) {
+        LOG_I(TAG, "Cloud connection changed");
+        if (!state) {
+            LOG_D(TAG, "Connection lost.");
+        }
+
+        iotivity->setConnected(state);
+    }
+}
+
+IoTivity_impl::IoTivity_impl(): cloud_host(), account_mgr(nullptr), presence_handle(nullptr), signed_in(false), connected(false)
+{
+    FN_VISIT
+    auto res = CAManager::setNetworkMonitorHandler(adapterChangedCallback, connectionChangedCallback);
+    if (OC_STACK_OK != res) {
+        LOG_E(TAG, "CAManager::setNetworkMonitorHandler failed with code = %d", res);
+    }
+
+    OC::OCPlatform::Configure(IoTivity_impl::platform_config);
+}
+
+IoTivity_impl::~IoTivity_impl()
+{
+    FN_VISIT
+    try {
+        CAManager::unsetNetworkMonitorHandler();
+        signOut();
+    } catch (...) {
+    }
+}
+
+IMqClient* IoTivity_impl::getMqHandler()
+{
+    IMqClient* handler = mq_handler.get();
+
+    if (handler == nullptr) {
+        LOG_W(TAG, "getMqHandler(): MqHandler uninitialized");
+        throw std::runtime_error("Failed to connect to message queue");
+    }
+
+    return handler;
+}
+
+void IoTivity_impl::registerDeviceInfo(const std::string& name, const std::string& model, const std::string& type)
+{
+    OCDeviceInfo di;
+    OCStringLL dt;
+    OCStringLL dm;
+    dt.value = (char*)type.c_str();
+    dt.next = NULL;
+    dm.value = (char*)model.c_str();
+    dm.next = NULL;
+    di.deviceName = (char*)name.c_str();
+    di.types = &dt;
+    di.specVersion = NULL;
+    di.dataModelVersions = &dm;
+
+    auto result = OCPlatform::registerDeviceInfo(di);
+    if (OC_STACK_OK != result) {
+        throw IoTInternalError("registerDeviceInfo failed", result);
+    }
+}
+
+std::vector<IoTDevicePtr> IoTivity_impl::findDevices(bool cloud, OCConnectivityType con_type, const std::string& uri)
+{
+    if (cloud) {
+        if (!signed_in) {
+            throw IoTInternalError("Not signed in", EC_UNAUTHORIZED);
+        } else if (!connected) {
+            signIn();
+        }
+    }
+
+    std::vector<IoTDevicePtr> devices;
+    FindDeviceListCallback::Sptr callback = std::make_shared<FindDeviceListCallback>(devices, con_type);
+
+    OC::OCPlatform::findResourceList(cloud ? cloud_host : "", uri, con_type, bind_callback(callback, PH::_1),
+                                     OC::QualityOfService::HighQos);
+    callback->wait_timeout(std::chrono::seconds(DEFAULT_TIMEOUT));
+
+    return devices;
+}
+
+std::shared_ptr<OC::OCResource> IoTivity_impl::findResource(bool cloud, const std::string& type, const std::string& uri,
+        OCConnectivityType con_type)
+{
+    FindResourceCallback::Sptr callback = std::make_shared<FindResourceCallback>(type);
+    OCPlatform::findResource(cloud ? cloud_host : "", uri, con_type, bind_callback(callback, PH::_1));
+
+    if (!callback->wait()) {
+        LOG_E(TAG, "IoTivity::findResource callback not called. cloud: \"%s\", Uri: \"%s\", Type: \"%s\"",
+              (cloud ? "true" : "false"), uri.c_str(), type.c_str());
+    }
+
+    return callback->resource;
+}
+
+std::vector<std::shared_ptr<OC::OCResource>> IoTivity_impl::findResourceList(bool cloud, const std::string& type,
+        const std::string& uri, OCConnectivityType con_type)
+{
+    std::vector<std::shared_ptr<OC::OCResource>> resources;
+    FindResourceListCallback::Sptr callback = std::make_shared<FindResourceListCallback>(resources, con_type, type);
+    OCPlatform::findResourceList(cloud ? cloud_host : "", uri, con_type, bind_callback(callback, PH::_1));
+
+    callback->wait_timeout();
+    if (!callback->fired) {
+        LOG_E(TAG, "IoTivity::findResourceList callback not called. cloud: \"%s\", Uri: \"%s\", Type: \"%s\"",
+              (cloud ? "true" : "false"), uri.c_str(), type.c_str());
+    }
+
+    return resources;
+}
+
+std::shared_ptr<OC::OCResource> IoTivity_impl::findResource(const std::string& host, const std::string& type,
+        const std::string& uri, OCConnectivityType con_type)
+{
+    FindResourceCallback::Sptr callback = std::make_shared<FindResourceCallback>(type);
+    OCPlatform::findResource(host, uri, con_type, bind_callback(callback, PH::_1));
+
+    if (!callback->wait()) {
+        LOG_E(TAG, "IoTivity::findResource callback not called. Host: \"%s\", Uri: \"%s\", Type: \"%s\"",
+              host.c_str(), uri.c_str(), type.c_str());
+    }
+
+    return callback->resource;
+}
+
+std::shared_ptr<OC::OCResource> IoTivity_impl::findResource(
+    const std::string& host,
+    const std::string& type,
+    const std::string& uri,
+    const std::string& sid)
+{
+    FindResourceCallback::Sptr callback = std::make_shared<FindResourceCallback>(type, CT_DEFAULT, sid);
+    OCPlatform::findResource(host, uri, CT_DEFAULT, bind_callback(callback, PH::_1));
+
+    if (!callback->wait()) {
+        LOG_E(TAG, "IoTivity::findResource callback not called. Host: \"%s\", Uri: \"%s\", Type: \"%s\"",
+              host.c_str(), uri.c_str(), type.c_str());
+    }
+
+    return callback->resource;
+}
+
+struct SignInCallback {
+    int resultCode = 0;
+    bool timeout = true;
+    std::condition_variable condVar;
+    std::string sid;
+
+    static void call(weak_ptr<SignInCallback> wptr,
+                     const HeaderOptions&,
+                     const OCRepresentation& rep,
+                     const int resultCode) {
+        if (auto p = wptr.lock()) {
+            p->resultCode = resultCode;
+            p->timeout = false;
+            p->sid = rep.getValueToString("sid");
+            p->condVar.notify_all();
+        }
+    }
+};
+
+struct SignUpCallback {
+    int resultCode = 0;
+    bool timeout = true;
+    std::condition_variable condVar;
+
+    std::string uid;
+    std::string sid;
+    std::string accessToken;
+
+    static void call(weak_ptr<SignUpCallback> wptr,
+                     const HeaderOptions&,
+                     const OCRepresentation& rep,
+                     const int resultCode) {
+        if (auto p = wptr.lock()) {
+            p->resultCode = resultCode;
+            if (resultCode == 4) {
+                p->uid = rep.getValueToString("uid");
+                p->sid = rep.getValueToString("sid");
+                p->accessToken = rep.getValueToString("accesstoken");
+            }
+            p->timeout = false;
+            p->condVar.notify_all();
+        }
+    }
+};
+
+void IoTivity_impl::signUp(const std::string& host, const std::string& auth_provider, const std::string& access_token)
+{
+    FN_VISIT
+    if (host.empty() || auth_provider.empty() || access_token.empty()) {
+        throw std::invalid_argument("Wrong signUp credentials");
+    }
+
+    OCAccountManager::Ptr accountMgr = OCPlatform::constructAccountManagerObject(host, CT_ADAPTER_TCP);
+
+    if (!accountMgr) {
+        throw IoTInternalError("Can not create account manager", EC_IOTIVITY_ERROR);
+    }
+
+    std::unique_lock<std::mutex> lock(instance_mutex);
+
+    signed_in = false;
+
+    shared_ptr<SignUpCallback> signUpCb = make_shared<SignUpCallback>();
+
+    guardErrorCode(accountMgr->signUp(
+                       auth_provider,
+                       access_token,
+                       std::bind(SignUpCallback::call, weak_ptr<SignUpCallback>(signUpCb), PH::_1, PH::_2, PH::_3)), SIGNUP);
+
+
+    signUpCb->condVar.wait_for(lock, std::chrono::seconds(DEFAULT_TIMEOUT));
+    guardTimeout(signUpCb->timeout, SIGNUP);
+    guardPostErrorCode(signUpCb->resultCode, SIGNUP);
+
+    cloud_host = host;
+    cloud_uid = signUpCb->uid;
+    cloud_sid = signUpCb->sid;
+    cloud_access_token = signUpCb->accessToken;
+    account_mgr = accountMgr;
+
+    lock.unlock();
+    signIn();
+}
+
+void IoTivity_impl::signIn(const std::string& host, const std::string& uid, const std::string& access_token)
+{
+    cloud_host = host;
+    cloud_uid = uid;
+    cloud_access_token = access_token;
+    if (!account_mgr) {
+        account_mgr = OCPlatform::constructAccountManagerObject(host, CT_ADAPTER_TCP);
+    }
+    signIn();
+}
+
+void IoTivity_impl::signIn()
+{
+    FN_VISIT
+    if (!account_mgr) {
+        throw IoTInternalError("No account manager", EC_IOTIVITY_ERROR);
+    }
+
+    std::unique_lock<std::mutex> lock(instance_mutex);
+
+    shared_ptr<SignInCallback> signInCb = make_shared<SignInCallback>();
+
+    guardErrorCode(account_mgr->signIn(
+                       cloud_uid,
+                       cloud_access_token,
+                       std::bind(SignInCallback::call, weak_ptr<SignInCallback>(signInCb), PH::_1, PH::_2, PH::_3)), SIGNIN);
+
+    signInCb->condVar.wait_for(lock, std::chrono::seconds(DEFAULT_TIMEOUT));
+    guardTimeout(signInCb->timeout, SIGNIN);
+    guardPostErrorCode(signInCb->resultCode, SIGNIN);
+
+    if (cloud_sid.empty()) {
+        cloud_sid = signInCb->sid;
+    }
+    signed_in = true;
+    connected = true;
+
+    mq_handler = std::make_shared<MqClient>(cloud_host);
+}
+
+void IoTivity_impl::signOut()
+{
+    FN_VISIT
+    if (!signed_in) {
+        return;
+    }
+    signed_in = false;
+
+    if (cloud_host.empty() || cloud_access_token.empty()) {
+        LOG_W(TAG, "SignOut without SignIn");
+        return;
+    }
+
+    if (!account_mgr) {
+        throw IoTInternalError("No account manager", EC_IOTIVITY_ERROR);
+    }
+
+    std::mutex mtx;
+    std::unique_lock<std::mutex> lock(mtx);
+
+    shared_ptr<SignInCallback> signOutCb = make_shared<SignInCallback>();
+
+    guardErrorCode(account_mgr->signOut(
+                       cloud_access_token,
+                       std::bind(SignInCallback::call, weak_ptr<SignInCallback>(signOutCb), PH::_1, PH::_2, PH::_3)), SIGNOUT);
+
+    signOutCb->condVar.wait_for(lock, std::chrono::seconds(DEFAULT_TIMEOUT));
+    guardTimeout(signOutCb->timeout, SIGNOUT);
+
+    // No need to throw OC_STACK_UNAUTHORIZED_REQ error
+    if (signOutCb->resultCode != OC_STACK_UNAUTHORIZED_REQ) {
+        guardPostErrorCode(signOutCb->resultCode, SIGNOUT);
+    }
+}
+
+void IoTivity_impl::deleteFromAccount()
+{
+    FN_VISIT
+    if (!signed_in) {
+        return;
+    }
+    signed_in = false;
+
+    if (cloud_host.empty() || cloud_access_token.empty()) {
+        LOG_W(TAG, "SignOut without SignIn");
+        return;
+    }
+
+    if (!account_mgr) {
+        throw IoTInternalError("No account manager", EC_IOTIVITY_ERROR);
+    }
+
+    auto deleteMutex = std::make_shared<std::mutex>();
+    weak_ptr<std::mutex> deleteMutexWptr(deleteMutex);
+    std::unique_lock<std::mutex> lock(*deleteMutex);
+    std::condition_variable cv;
+    bool called = false;
+    int code = OC_STACK_ERROR;
+
+    auto deleteCallback = [deleteMutexWptr, &cv, &called, &code](const HeaderOptions&, const int ecode) {
+        if (auto mtx = deleteMutexWptr.lock()) {
+            called = true;
+            code = ecode;
+            cv.notify_all();
+        }
+    };
+
+    account_mgr->deleteDevice(cloud_access_token, getDeviceID(), deleteCallback);
+
+    cv.wait_for(lock, std::chrono::seconds(DEFAULT_TIMEOUT), [&called] { return called; });
+
+    if (!called || code > OC_STACK_RESOURCE_CHANGED) {
+        throw IoTInternalError("Failed to delete device from account", EC_IOTIVITY_ERROR);
+    }
+}
+
+/*
+void IoTivity::devicePresenceHandle(
+    const HeaderOptions& hOptions,
+    const OCRepresentation& rep,
+    const int eCode,
+    const int seqN)
+{
+    FN_VISIT
+
+    std::string state{"off"};
+    std::string di;
+    rep.getValue("state", state);
+
+    if (rep.getValue("di", di))
+    {
+        bool isOn = state == "on";
+
+        if ((bool)presence_hook)
+        {
+            presence_hook(di, isOn);
+        }
+    }
+}
+*/
+
+//void IoTivity_impl::setDevicePresenceHook(PresenceHook&& hook)
+//{
+//    presence_hook = hook;
+//}
+
+//void IoTivity_impl::removeDevicePresenceHook()
+//{
+//    presence_hook = PresenceHook{};
+//}
+
+bool IoTivity_impl::isSignedIn()
+{
+    return signed_in;
+}
+
+const string& IoTivity_impl::getDeviceID()
+{
+    if (device_id.empty()) {
+        OCUUIdentity deviceId;
+        if (OC_STACK_OK == OC::OCPlatform::getDeviceId(&deviceId)) {
+            unsigned char* id = deviceId.id;
+            ostringstream os;
+            os << hex << setfill('0');
+            os << setw(2) << (unsigned)id[0];
+            os << setw(2) << (unsigned)id[1];
+            os << setw(2) << (unsigned)id[2];
+            os << setw(2) << (unsigned)id[3] << '-';
+
+            os << setw(2) << (unsigned)id[4];
+            os << setw(2) << (unsigned)id[5] << '-';
+
+            os << setw(2) << (unsigned)id[6];
+            os << setw(2) << (unsigned)id[7] << '-';
+
+            os << setw(2) << (unsigned)id[8];
+            os << setw(2) << (unsigned)id[9] << '-';
+
+            os << setw(2) << (unsigned)id[10];
+            os << setw(2) << (unsigned)id[11];
+            os << setw(2) << (unsigned)id[12];
+            os << setw(2) << (unsigned)id[13];
+            os << setw(2) << (unsigned)id[14];
+            os << setw(2) << (unsigned)id[15];
+            device_id = os.str();
+        }
+    }
+
+    return device_id;
+
+}
+
+void IoTivity_impl::publishResources(OC::ResourceHandles& handles)
+{
+    ResourcePublishCallback::Sptr callback = std::make_shared<ResourcePublishCallback>();
+    auto res = RDClient::Instance().publishResourceToRD(cloud_host, CT_ADAPTER_TCP, handles, bind_callback(callback, PH::_1,
+               PH::_2));
+
+    if (res != OC_STACK_OK) {
+        throw IoTInternalError("Failed to publish resources", res);
+    }
+
+    bool ok = callback->wait();
+
+    if (!ok || callback->errorCode > OC_STACK_RESOURCE_CHANGED) {
+        throw IoTInternalError("Failed to publish resources", callback->errorCode);
+    }
+}
+
+void IoTivity_impl::unPublishResources(OC::ResourceHandles& handles)
+{
+    ResourcePublishCallback::Sptr callback = std::make_shared<ResourcePublishCallback>();
+    auto res = RDClient::Instance().deleteResourceFromRD(cloud_host, CT_ADAPTER_TCP, handles, bind_callback(callback,
+               OCRepresentation{}, PH::_1));
+
+    if (res != OC_STACK_OK) {
+        throw IoTInternalError("Failed to unpublish resources", res);
+    }
+
+    bool ok = callback->wait();
+
+    if (!ok || callback->errorCode > OC_STACK_RESOURCE_CHANGED) {
+        throw IoTInternalError("Failed to unpublish resources", callback->errorCode);
+    }
+}
+
+void IoTivity_impl::unPublishAllResources()
+{
+    OC::ResourceHandles handles;
+    RDClient::Instance().deleteResourceFromRD(cloud_host, CT_ADAPTER_TCP, handles, [](int) {});
+}
+
+}
diff --git a/device_core/mock/audit-trail-mock.h b/device_core/mock/audit-trail-mock.h
new file mode 100644 (file)
index 0000000..82c27a3
--- /dev/null
@@ -0,0 +1,32 @@
+#ifndef AUDITTRAILMOCK_H
+#define AUDITTRAILMOCK_H
+
+#include <gmock/gmock.h>
+#include "audit-trail-stub.h"
+
+class AuditTrailMock: public IAuditTrail
+{
+public:
+    MOCK_METHOD1(audit_trail_create, int(audit_trail_h *handle));
+    MOCK_METHOD0(audit_trail_destroy, int());
+    MOCK_METHOD2(audit_trail_foreach_dac, int(audit_trail_string_cb callback, void *user_data));
+    MOCK_METHOD0(audit_trail_clear_dac, int());
+    MOCK_METHOD3(audit_trail_add_dac_cb, int(audit_trail_string_cb callback, void* user_data, int* id));
+    MOCK_METHOD1(audit_trail_remove_dac_cb, int(int id));
+    MOCK_METHOD1(audit_trail_enable_dac, int(bool en));
+    MOCK_METHOD1(audit_trail_is_enabled_dac, int(bool *en));
+    MOCK_METHOD2(audit_trail_foreach_mac, int(audit_trail_string_cb callback, void *user_data));
+    MOCK_METHOD0(audit_trail_clear_mac, int());
+    MOCK_METHOD3(audit_trail_add_mac_cb, int(audit_trail_string_cb callback, void* user_data, int* id));
+    MOCK_METHOD1(audit_trail_remove_mac_cb, int(int id));
+    MOCK_METHOD1(audit_trail_enable_mac, int(bool en));
+    MOCK_METHOD1(audit_trail_is_enabled_mac, int(bool *en));
+    MOCK_METHOD2(audit_trail_foreach_syscall, int(audit_trail_string_cb callback, void *user_data));
+    MOCK_METHOD0(audit_trail_clear_syscall, int());
+    MOCK_METHOD3(audit_trail_add_syscall_cb, int(audit_trail_string_cb callback, void* user_data, int* id));
+    MOCK_METHOD1(audit_trail_remove_syscall_cb, int(int id));
+    MOCK_METHOD1(audit_trail_enable_syscall, int(bool en));
+    MOCK_METHOD1(audit_trail_is_enabled_syscall, int(bool *en));
+};
+
+#endif // AUDITTRAILMOCK_H
diff --git a/device_core/mock/audit-trail-stub.cpp b/device_core/mock/audit-trail-stub.cpp
new file mode 100644 (file)
index 0000000..f217f41
--- /dev/null
@@ -0,0 +1,152 @@
+#include "mock/audit-trail.h"
+#include "mock/dac.h"
+#include "mock/mac.h"
+#include "mock/syscall.h"
+#include "mock/audit-trail-stub.h"
+
+static AuditTrailDefaultImpl atrail;
+static IAuditTrail* p_atrail = &atrail;
+
+void audit_trail_set_implementation(IAuditTrail* impl)
+{
+    p_atrail = impl;
+}
+
+int audit_trail_create(audit_trail_h* handle)
+{
+    int ret = p_atrail->audit_trail_create(handle);
+    *handle = p_atrail;
+    return ret;
+}
+
+int audit_trail_destroy(audit_trail_h handle)
+{
+    IAuditTrail* p = reinterpret_cast<IAuditTrail*>(handle);
+    return p->audit_trail_destroy();
+}
+
+int audit_trail_foreach_dac(audit_trail_h handle, audit_trail_string_cb callback, void* user_data)
+{
+    IAuditTrail* p = reinterpret_cast<IAuditTrail*>(handle);
+    return p->audit_trail_foreach_dac(callback, user_data);
+}
+
+
+int audit_trail_clear_dac(audit_trail_h handle)
+{
+    IAuditTrail* p = reinterpret_cast<IAuditTrail*>(handle);
+    return p->audit_trail_clear_dac();
+}
+
+
+int audit_trail_add_dac_cb(audit_trail_h handle, audit_trail_string_cb callback, void* user_data, int* id)
+{
+    IAuditTrail* p = reinterpret_cast<IAuditTrail*>(handle);
+    return p->audit_trail_add_dac_cb(callback, user_data, id);
+}
+
+
+int audit_trail_remove_dac_cb(audit_trail_h handle, int id)
+{
+    IAuditTrail* p = reinterpret_cast<IAuditTrail*>(handle);
+    return p->audit_trail_remove_dac_cb(id);
+}
+
+
+int audit_trail_enable_dac(audit_trail_h handle, bool en)
+{
+    IAuditTrail* p = reinterpret_cast<IAuditTrail*>(handle);
+    return p->audit_trail_enable_dac(en);
+}
+
+
+int audit_trail_is_enabled_dac(audit_trail_h handle, bool* en)
+{
+    IAuditTrail* p = reinterpret_cast<IAuditTrail*>(handle);
+    return p->audit_trail_is_enabled_dac(en);
+}
+
+
+int audit_trail_foreach_mac(audit_trail_h handle, audit_trail_string_cb callback, void* user_data)
+{
+    IAuditTrail* p = reinterpret_cast<IAuditTrail*>(handle);
+    return p->audit_trail_foreach_mac(callback, user_data);
+}
+
+
+int audit_trail_clear_mac(audit_trail_h handle)
+{
+    IAuditTrail* p = reinterpret_cast<IAuditTrail*>(handle);
+    return p->audit_trail_clear_mac();
+}
+
+
+int audit_trail_add_mac_cb(audit_trail_h handle, audit_trail_string_cb callback, void* user_data, int* id)
+{
+    IAuditTrail* p = reinterpret_cast<IAuditTrail*>(handle);
+    return p->audit_trail_add_mac_cb(callback, user_data, id);
+}
+
+
+int audit_trail_remove_mac_cb(audit_trail_h handle, int id)
+{
+    IAuditTrail* p = reinterpret_cast<IAuditTrail*>(handle);
+    return p->audit_trail_remove_mac_cb(id);
+}
+
+
+int audit_trail_enable_mac(audit_trail_h handle, bool en)
+{
+    IAuditTrail* p = reinterpret_cast<IAuditTrail*>(handle);
+    return p->audit_trail_enable_mac(en);
+}
+
+
+int audit_trail_is_enabled_mac(audit_trail_h handle, bool* en)
+{
+    IAuditTrail* p = reinterpret_cast<IAuditTrail*>(handle);
+    return p->audit_trail_is_enabled_mac(en);
+}
+
+
+int audit_trail_foreach_syscall(audit_trail_h handle, audit_trail_string_cb callback, void* user_data)
+{
+    IAuditTrail* p = reinterpret_cast<IAuditTrail*>(handle);
+    return p->audit_trail_foreach_syscall(callback, user_data);
+}
+
+
+int audit_trail_clear_syscall(audit_trail_h handle)
+{
+    IAuditTrail* p = reinterpret_cast<IAuditTrail*>(handle);
+    return p->audit_trail_clear_syscall();
+}
+
+
+int audit_trail_add_syscall_cb(audit_trail_h handle, audit_trail_string_cb callback, void* user_data, int* id)
+{
+    IAuditTrail* p = reinterpret_cast<IAuditTrail*>(handle);
+    return p->audit_trail_add_syscall_cb(callback, user_data, id);
+}
+
+
+int audit_trail_remove_syscall_cb(audit_trail_h handle, int id)
+{
+    IAuditTrail* p = reinterpret_cast<IAuditTrail*>(handle);
+    return p->audit_trail_remove_syscall_cb(id);
+}
+
+
+int audit_trail_enable_syscall(audit_trail_h handle, bool en)
+{
+    IAuditTrail* p = reinterpret_cast<IAuditTrail*>(handle);
+    return p->audit_trail_enable_syscall(en);
+}
+
+
+int audit_trail_is_enabled_syscall(audit_trail_h handle, bool* en)
+{
+    IAuditTrail* p = reinterpret_cast<IAuditTrail*>(handle);
+    return p->audit_trail_is_enabled_syscall(en);
+}
+
diff --git a/device_core/mock/audit-trail-stub.h b/device_core/mock/audit-trail-stub.h
new file mode 100644 (file)
index 0000000..723d5d8
--- /dev/null
@@ -0,0 +1,125 @@
+#ifndef AUDITTRAILSTUB_H
+#define AUDITTRAILSTUB_H
+
+
+#include "mock/dac.h"
+#include "mock/mac.h"
+#include "mock/syscall.h"
+
+class IAuditTrail
+{
+public:
+    virtual int audit_trail_create(audit_trail_h *handle) = 0;
+    virtual int audit_trail_destroy() = 0;
+    virtual int audit_trail_foreach_dac(audit_trail_string_cb callback, void *user_data) = 0;
+    virtual int audit_trail_clear_dac() = 0;
+    virtual int audit_trail_add_dac_cb(audit_trail_string_cb callback, void* user_data, int* id) = 0;
+    virtual int audit_trail_remove_dac_cb(int id) = 0;
+    virtual int audit_trail_enable_dac(bool en) = 0;
+    virtual int audit_trail_is_enabled_dac(bool *en) = 0;
+    virtual int audit_trail_foreach_mac(audit_trail_string_cb callback, void *user_data) = 0;
+    virtual int audit_trail_clear_mac() = 0;
+    virtual int audit_trail_add_mac_cb(audit_trail_string_cb callback, void* user_data, int* id) = 0;
+    virtual int audit_trail_remove_mac_cb(int id) = 0;
+    virtual int audit_trail_enable_mac(bool en) = 0;
+    virtual int audit_trail_is_enabled_mac(bool *en) = 0;
+    virtual int audit_trail_foreach_syscall(audit_trail_string_cb callback, void *user_data) = 0;
+    virtual int audit_trail_clear_syscall() = 0;
+    virtual int audit_trail_add_syscall_cb(audit_trail_string_cb callback, void* user_data, int* id) = 0;
+    virtual int audit_trail_remove_syscall_cb(int id) = 0;
+    virtual int audit_trail_enable_syscall(bool en) = 0;
+    virtual int audit_trail_is_enabled_syscall(bool *en) = 0;
+};
+
+void audit_trail_set_implementation(IAuditTrail* impl);
+
+class AuditTrailDefaultImpl: public IAuditTrail
+{
+public:
+    int audit_trail_create(audit_trail_h *handle) override
+    {
+        *handle = this;
+        return 0;
+    }
+    int audit_trail_destroy() override
+    {
+        return 0;
+    }
+    int audit_trail_foreach_dac(audit_trail_string_cb callback, void *user_data) override
+    {
+        return 0;
+    }
+    int audit_trail_clear_dac() override
+    {
+        return 0;
+    }
+    int audit_trail_add_dac_cb(audit_trail_string_cb callback, void* user_data, int* id) override
+    {
+        return 0;
+    }
+    int audit_trail_remove_dac_cb(int id) override
+    {
+        return 0;
+    }
+    int audit_trail_enable_dac(bool en) override
+    {
+        return 0;
+    }
+    int audit_trail_is_enabled_dac(bool *en) override
+    {
+        *en = true;
+        return 0;
+    }
+    int audit_trail_foreach_mac(audit_trail_string_cb callback, void *user_data) override
+    {
+        return 0;
+    }
+    int audit_trail_clear_mac() override
+    {
+        return 0;
+    }
+    int audit_trail_add_mac_cb(audit_trail_string_cb callback, void* user_data, int* id) override
+    {
+        return 0;
+    }
+    int audit_trail_remove_mac_cb(int id) override
+    {
+        return 0;
+    }
+    int audit_trail_enable_mac(bool en) override
+    {
+        return 0;
+    }
+    int audit_trail_is_enabled_mac(bool *en) override
+    {
+        *en = true;
+        return 0;
+    }
+    int audit_trail_foreach_syscall(audit_trail_string_cb callback, void *user_data) override
+    {
+        return 0;
+    }
+    int audit_trail_clear_syscall() override
+    {
+        return 0;
+    }
+    int audit_trail_add_syscall_cb(audit_trail_string_cb callback, void* user_data, int* id) override
+    {
+        return 0;
+    }
+    int audit_trail_remove_syscall_cb(int id) override
+    {
+        return 0;
+    }
+    int audit_trail_enable_syscall(bool en) override
+    {
+        return 0;
+    }
+    int audit_trail_is_enabled_syscall(bool *en) override
+    {
+        *en = true;
+        return 0;
+    }
+};
+
+#endif // AUDITTRAILSTUB_H
diff --git a/device_core/mock/audit-trail.h b/device_core/mock/audit-trail.h
new file mode 100644 (file)
index 0000000..46fd8bd
--- /dev/null
@@ -0,0 +1,85 @@
+/*
+ *  Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+
+#ifndef __CAPI_AUDIT_TRAIL_AUDIT_TRAIL_H__
+#define __CAPI_AUDIT_TRAIL_AUDIT_TRAIL_H__
+
+#include "common.h"
+
+/**
+ * @file audit-trail.h
+ * @brief This file provides APIs to get a handle of audit-trail
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * @brief       The audit-trail handle
+ * @details     The audit-trail  handle is an abstraction of the logical
+ *              connection between the audit-trail manager and it's client.
+ *              The audit-trail handle must be created by using
+ *              audit_trail_create() before attempting to use almost any of
+ *              the audit-trail related APIs, and it should be freed when interaction
+ *              with the audit-trail manager is no longer required.
+ *              To release the handle, use audit_trail_destroy().
+ * @since_tizen 5.0
+ * @see         audit_trail_create()
+ * @see         audit_trail_destroy()
+ */
+typedef void* audit_trail_h;
+
+/**
+ * @brief       Creates the audit-trail handle.
+ * @details     This API creates audit-trail handle required to the audit-trail
+ *              related APIs.
+ *              This API is also used to verify whether caller is authorized
+ *              or not.
+ * @since_tizen 5.0
+ * @param[out]  handle The audit-trail handle
+ * @return      #AUDIT_TRAIL_ERROR_NONE on success, otherwise a negative value
+ * @retval      #AUDIT_TRAIL_ERROR_NONE Successful
+ * @retval      #AUDIT_TRAIL_ERROR_CONNECTION_REFUSED Connection refused
+ * @retval      #AUDIT_TRAIL_ERROR_TIMED_OUT Time out
+ * @see         audit_trail_destroy()
+ * @see         get_last_result()
+ */
+AUDIT_TRAIL_API int audit_trail_create(audit_trail_h *handle);
+
+/**
+ * @brief       Releases the audit-trail handle.
+ * @details     This API must be called if interaction with the audit-trail API
+ *              is no longer required.
+ * @since_tizen 5.0
+ * @param[in]   handle The audit-trail handle
+ * @return      #AUDIT_TRAIL_ERROR_NONE on success, otherwise a negative value
+ * @retval      #AUDIT_TRAIL_ERROR_NONE Successful
+ * @retval      #AUDIT_TRAIL_ERROR_INVALID_PARAMETER Invalid parameter
+ * @pre         The handle must be created by audit_trail_create()
+ * @see         audit_trail_create()
+ */
+AUDIT_TRAIL_API int audit_trail_destroy(audit_trail_h handle);
+
+/**
+ * @}
+ */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __CAPI_AUDIT_TRAIL_AUDIT_TRAIL_H__ */
diff --git a/device_core/mock/common.h b/device_core/mock/common.h
new file mode 100644 (file)
index 0000000..d9b9bd1
--- /dev/null
@@ -0,0 +1,76 @@
+/*
+ *  Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+
+#ifndef __CAPI_AUDIT_TRAIL_COMMON_H__
+#define __CAPI_AUDIT_TRAIL_COMMON_H__
+
+#ifndef AUDIT_TRAIL_API
+#define AUDIT_TRAIL_API
+#endif // API
+
+#ifndef TRUE
+#define TRUE    1
+#endif
+
+#ifndef FALSE
+#define FALSE   0
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * @addtogroup  CAPI_AUDIT_TRAIL_MODULE
+ * @{
+ */
+
+/**
+ * @brief       Enumeration of device encryption API errors
+ * @since_tizen 3.0
+ */
+typedef enum {
+    AUDIT_TRAIL_ERROR_NONE = 0,
+    AUDIT_TRAIL_ERROR_INVALID_PARAMETER,
+    AUDIT_TRAIL_ERROR_CONNECTION_REFUSED,
+    AUDIT_TRAIL_ERROR_TIMED_OUT,
+    AUDIT_TRAIL_ERROR_PERMISSION_DENIED,
+    AUDIT_TRAIL_ERROR_NOT_SUPPORTED,
+    AUDIT_TRAIL_ERROR_OUT_OF_MEMORY,
+    AUDIT_TRAIL_ERROR_NOT_PERMITTED,
+    AUDIT_TRAIL_ERROR_NO_DATA
+} audit_trail_error_type_e;
+
+/**
+ * @brief       Called to get all strings in an array
+ * @since_tizen 5.0
+ * @param[in]   log Each string in an array
+ * @param[in]   user_data The user data passed from the function
+ * @see         audit_trail_add_log_cb
+ * @see         audit_trail_remove_log_cb
+ * @see         audit_trail_foreach_smack
+ */
+typedef void (*audit_trail_string_cb)(const char* log, void* user_data);
+
+/**
+ * @}
+ */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __CAPI_AUDIT_TRAIL_COMMON_H__ */
diff --git a/device_core/mock/dac.h b/device_core/mock/dac.h
new file mode 100644 (file)
index 0000000..c59f26d
--- /dev/null
@@ -0,0 +1,156 @@
+/*
+ *  Copyright (c) 2017 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+
+#ifndef __CAPI_AUDIT_TRAIL_DAC_H__
+#define __CAPI_AUDIT_TRAIL_DAC_H__
+
+#include "audit-trail.h"
+
+/**
+ * @file dac.h
+ * @brief This file provides APIs to get DAC(Discretionary Access Control) logs
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * @brief       Retrieves all DAC logs that occured in system.
+ * @details     This API calls audit_trail_string_cb() once for each DAC
+ *              (Discretionary Access Control) logs collected by audit-trail
+ *              when DAC auditing is enabled.
+ * @since_tizen 5.0
+ * @param[in]   handle The audit-trail handle
+ * @param[in]   callback The iteration callback function
+ * @param[in]   user_data The user data passed to the callback function
+ * @return      #AUDIT_TRAIL_ERROR_NONE on success, otherwise a negative value
+ * @retval      #AUDIT_TRAIL_ERROR_NONE Successful
+ * @retval      #AUDIT_TRAIL_ERROR_TIMED_OUT Time out
+ * @retval      #AUDIT_TRAIL_ERROR_INVALID_PARAMETER Invalid parameter
+ * @pre         The handle must be created by audit_trail_create().
+ * @see         audit_trail_create()
+ * @see         audit_trail_destroy()
+ * @see         audit_trail_enable_dac()
+ */
+AUDIT_TRAIL_API int audit_trail_foreach_dac(audit_trail_h handle, audit_trail_string_cb callback, void *user_data);
+
+/**
+ * @brief       Clears all DAC logs saved in audit-trail.
+ * @details     This API removes all DAC(Discretionary Access Control) logs
+ *              collected by audit-trail.
+ * @since_tizen 5.0
+ * @param[in]   handle The audit-trail handle
+ * @return      #AUDIT_TRAIL_ERROR_NONE on success, otherwise a negative value
+ * @retval      #AUDIT_TRAIL_ERROR_NONE Successful
+ * @retval      #AUDIT_TRAIL_ERROR_TIMED_OUT Time out
+ * @retval      #AUDIT_TRAIL_ERROR_INVALID_PARAMETER Invalid parameter
+ * @pre         The handle must be created by audit_trail_create().
+ * @see         audit_trail_create()
+ * @see         audit_trail_destroy()
+ * @see         audit_trail_foreach_dac()
+ */
+AUDIT_TRAIL_API int audit_trail_clear_dac(audit_trail_h handle);
+
+/**
+ * @brief       Adds a DAC log callback.
+ * @details     This API can be used to receive DAC(Discretionary Access
+ *              Control) logs of system. The callback specified to this
+ *              function is automatically called when a new log occurs.
+ * @since_tizen 5.0
+ * @param[in]   context The audit_trail handle
+ * @param[in]   callback The callback to get DAC(Discretionary Access Control) logs
+ * @param[in]   user_data The user data passed to the callback function
+ * @param[out]  id Callback identifier
+ * @return      #AUDIT_TRAIL_ERROR_NONE on success, otherwise a negative value
+ * @retval      #AUDIT_TRAIL_ERROR_NONE Successful
+ * @retval      #AUDIT_TRAIL_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval      #AUDIT_TRAIL_ERROR_TIMED_OUT Time out
+ * @pre         The handle must be created by audit_trail_create().
+ * @pre         DAC auditing must be enabled by audit_trail_enable_dac().
+ * @see         audit_trail_create()
+ * @see         audit_trail_destroy()
+ * @see         audit_trail_enable_dac()
+ * @see         audit_trail_remove_dac_cb()
+ */
+AUDIT_TRAIL_API int audit_trail_add_dac_cb(audit_trail_h handle,
+                                                       audit_trail_string_cb callback, void* user_data,
+                                                       int* id);
+
+/**
+ * @brief       Removes the DAC log callback.
+ * @details     This API can be used to remove the DAC(Discretionary Access
+ *              Control) logs callback.
+ * @since_tizen 5.0
+ * @param[in]   context The audit trail handle
+ * @param[in]   id Callback identifier
+ * @return      #AUDIT_TRAIL_ERROR_NONE on success, otherwise a negative value
+ * @retval      #AUDIT_TRAIL_ERROR_NONE Successful
+ * @retval      #AUDIT_TRAIL_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval      #AUDIT_TRAIL_ERROR_TIMED_OUT Time out
+ * @pre         The context must be created by audit_trail_create().
+ * @see         audit_trail_create()
+ * @see         audit_trail_destroy()
+ * @see         audit_trail_add_dac_cb()
+ */
+AUDIT_TRAIL_API int audit_trail_remove_dac_cb(audit_trail_h handle, int id);
+
+/**
+ * @brief       Enables DAC auditing.
+ * @details     This API can be used to enable to collect the DAC(Discretionary
+ *              Access Control) logs. Any DAC log will not be collected
+ *              until auditing is enabled
+ * @since_tizen 5.0
+ * @param[in]   handle The audit-trail handle
+ * @param[in]   en True enables DAC auditing, Otherwise disables
+ * @return      #AUDIT_TRAIL_ERROR_NONE on success, otherwise a negative value
+ * @retval      #AUDIT_TRAIL_ERROR_NONE Successful
+ * @retval      #AUDIT_TRAIL_ERROR_TIMED_OUT Time out
+ * @retval      #AUDIT_TRAIL_ERROR_INVALID_PARAMETER Invalid parameter
+ * @pre         The handle must be created by audit_trail_create().
+ * @see         audit_trail_create()
+ * @see         audit_trail_destroy()
+ * @see         audit_trail_foreach_dac()
+ * @see         audit_trail_add_dac_cb()
+ */
+AUDIT_TRAIL_API int audit_trail_enable_dac(audit_trail_h handle, bool en);
+
+/**
+ * @brief       Retrieves if DAC auditing is enabled.
+ * @details     This API can be used to know if DAC(Discretionary Access
+ *              Control) auditing is enabled now.
+ * @since_tizen 5.0
+ * @param[in]   handle The audit-trail handle
+ * @param[out]  en If true, DAC auditing was enabled, Otherwise disabled
+ * @return      #AUDIT_TRAIL_ERROR_NONE on success, otherwise a negative value
+ * @retval      #AUDIT_TRAIL_ERROR_NONE Successful
+ * @retval      #AUDIT_TRAIL_ERROR_TIMED_OUT Time out
+ * @retval      #AUDIT_TRAIL_ERROR_INVALID_PARAMETER Invalid parameter
+ * @pre         The handle must be created by audit_trail_create().
+ * @see         audit_trail_create()
+ * @see         audit_trail_destroy()
+ */
+AUDIT_TRAIL_API int audit_trail_is_enabled_dac(audit_trail_h handle, bool *en);
+
+/**
+ * @}
+ */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __CAPI_AUDIT_TRAIL_DAC_H__ */
diff --git a/device_core/mock/device-policy-manager-mock.h b/device_core/mock/device-policy-manager-mock.h
new file mode 100644 (file)
index 0000000..76d6dac
--- /dev/null
@@ -0,0 +1,65 @@
+#ifndef DEVICEPOLICYMANAGERMOCK_H
+#define DEVICEPOLICYMANAGERMOCK_H
+
+#include <gmock/gmock.h>
+#include "mock/device-policy-manager.h"
+
+class DPMMock: public DPMInterface
+{
+public:
+    MOCK_METHOD0(dpm_manager_create, device_policy_manager_h());
+    MOCK_METHOD0(dpm_manager_destroy, void());
+
+    MOCK_METHOD1(dpm_application_install_package, int(const char* app_name));
+    MOCK_METHOD1(dpm_application_uninstall_package, int(const char* app_name));
+
+    MOCK_METHOD0(dpm_security_lockout_screen, int());
+
+    MOCK_METHOD1(dpm_restriction_set_camera_state, int(int state));
+    MOCK_METHOD1(dpm_restriction_set_microphone_state, int(int state));
+    MOCK_METHOD1(dpm_restriction_set_location_state, int(int state));
+    MOCK_METHOD1(dpm_restriction_set_external_storage_state, int(int state));
+    MOCK_METHOD1(dpm_restriction_set_clipboard_state, int(int state));
+    MOCK_METHOD1(dpm_restriction_set_usb_debugging_state, int(int state));
+    MOCK_METHOD1(dpm_restriction_set_wifi_state, int(int state));
+    MOCK_METHOD1(dpm_restriction_set_wifi_hotspot_state, int(int state));
+    MOCK_METHOD1(dpm_restriction_set_bluetooth_tethering_state, int(int state));
+    MOCK_METHOD1(dpm_restriction_set_usb_tethering_state, int(int state));
+    MOCK_METHOD1(dpm_restriction_set_bluetooth_mode_change_state, int(int state));
+    MOCK_METHOD1(dpm_restriction_set_bluetooth_desktop_connectivity_state, int(int state));
+    MOCK_METHOD1(dpm_restriction_set_bluetooth_pairing_state, int(int state));
+    MOCK_METHOD1(dpm_restriction_set_popimap_email_state, int(int state));
+    MOCK_METHOD1(dpm_restriction_set_browser_state, int(int state));
+    MOCK_METHOD1(dpm_bluetooth_set_device_restriction, int(int state));
+    MOCK_METHOD1(dpm_bluetooth_set_uuid_restriction, int(int state));
+    MOCK_METHOD1(dpm_security_set_internal_storage_encryption, int(int state));
+    MOCK_METHOD1(dpm_security_set_external_storage_encryption, int(int state));
+    MOCK_METHOD1(dpm_wifi_set_profile_change_restriction, int(int state));
+    MOCK_METHOD1(dpm_wifi_set_network_access_restriction, int(int state));
+
+    MOCK_METHOD1(dpm_bluetooth_add_device_to_blacklist, int(const char* item));
+    MOCK_METHOD1(dpm_bluetooth_remove_device_from_blacklist, int(const char* item));
+    MOCK_METHOD1(dpm_bluetooth_add_uuid_to_blacklist, int(const char* item));
+    MOCK_METHOD1(dpm_bluetooth_remove_uuid_from_blacklist, int(const char* item));
+    MOCK_METHOD1(dpm_wifi_add_ssid_to_blocklist, int(const char* item));
+    MOCK_METHOD1(dpm_wifi_remove_ssid_from_blocklist, int(const char* item));
+
+    MOCK_METHOD2(dpm_security_wipe_data, int(int state, const char* item));
+    MOCK_METHOD2(dpm_restriction_set_messaging_state, int(int state, const char* item));
+    MOCK_METHOD2(dpm_application_add_privilege_to_blacklist, int(int state, const char* item));
+    MOCK_METHOD2(dpm_application_remove_privilege_from_blacklist, int(int state, const char* item));
+    MOCK_METHOD2(dpm_application_set_mode_restriction, int(int state, const char* item));
+    MOCK_METHOD2(dpm_application_unset_mode_restriction, int(int state, const char* item));
+
+    MOCK_METHOD1(dpm_firewall_apply_deny_rules, int(const char* rules));
+    MOCK_METHOD0(dpm_firewall_flush_deny_rules, int());
+
+    MOCK_METHOD1(dpm_restriction_set_usb_client_state, int(int allow));
+    MOCK_METHOD1(dpm_restriction_get_usb_client_state, int(int* is_allowed));
+    MOCK_METHOD1(dpm_restriction_set_sound_state, int(int allow));
+    MOCK_METHOD1(dpm_restriction_get_sound_state, int(int* is_allowed));
+    MOCK_METHOD1(dpm_restriction_set_tuner_state, int(int allow));
+    MOCK_METHOD1(dpm_restriction_get_tuner_state, int(int* is_allowed));
+};
+
+#endif // DEVICEPOLICYMANAGERMOCK_H
diff --git a/device_core/mock/device-policy-manager.cpp b/device_core/mock/device-policy-manager.cpp
new file mode 100644 (file)
index 0000000..558e20a
--- /dev/null
@@ -0,0 +1,255 @@
+#include <cassert>
+#include "mock/device-policy-manager.h"
+
+#define TAG "nmdaemon"
+
+namespace
+{
+
+static DPMInterface_impl_default default_dpm_impl;
+static DPMInterface* dpm_impl = &default_dpm_impl;
+}
+
+void dpm_set_custom_implementation(DPMInterface* dpm)
+{
+    dpm_impl = dpm;
+}
+
+device_policy_manager_h dpm_manager_create()
+{
+    assert(dpm_impl != nullptr);
+    return dpm_impl->dpm_manager_create();
+}
+
+void dpm_manager_destroy(device_policy_manager_h handle)
+{
+    assert(handle != nullptr);
+    handle->dpm_manager_destroy();
+}
+
+int dpm_application_install_package(device_policy_manager_h handle, const char* package_name)
+{
+    assert(handle != nullptr);
+    return handle->dpm_application_install_package(package_name);
+}
+
+int dpm_application_uninstall_package(device_policy_manager_h handle, const char* package_name)
+{
+    assert(handle != nullptr);
+    return handle->dpm_application_uninstall_package(package_name);
+}
+
+int dpm_security_lockout_screen(device_policy_manager_h handle)
+{
+    assert(handle != nullptr);
+    return handle->dpm_security_lockout_screen();
+}
+
+int dpm_restriction_set_camera_state(device_policy_manager_h handle, int state)
+{
+    assert(handle != nullptr);
+    return handle->dpm_restriction_set_camera_state(state);
+}
+int dpm_restriction_set_microphone_state(device_policy_manager_h handle, int state)
+{
+    assert(handle != nullptr);
+    return handle->dpm_restriction_set_microphone_state(state);
+}
+int dpm_restriction_set_location_state(device_policy_manager_h handle, int state)
+{
+    assert(handle != nullptr);
+    return handle->dpm_restriction_set_location_state(state);
+}
+int dpm_restriction_set_external_storage_state(device_policy_manager_h handle, int state)
+{
+    assert(handle != nullptr);
+    return handle->dpm_restriction_set_external_storage_state(state);
+}
+int dpm_restriction_set_clipboard_state(device_policy_manager_h handle, int state)
+{
+    assert(handle != nullptr);
+    return handle->dpm_restriction_set_clipboard_state(state);
+}
+int dpm_restriction_set_usb_debugging_state(device_policy_manager_h handle, int state)
+{
+    assert(handle != nullptr);
+    return handle->dpm_restriction_set_usb_debugging_state(state);
+}
+int dpm_restriction_set_wifi_state(device_policy_manager_h handle, int state)
+{
+    assert(handle != nullptr);
+    return handle->dpm_restriction_set_wifi_state(state);
+}
+int dpm_restriction_set_wifi_hotspot_state(device_policy_manager_h handle, int state)
+{
+    assert(handle != nullptr);
+    return handle->dpm_restriction_set_wifi_hotspot_state(state);
+}
+int dpm_restriction_set_bluetooth_tethering_state(device_policy_manager_h handle, int state)
+{
+    assert(handle != nullptr);
+    return handle->dpm_restriction_set_bluetooth_tethering_state(state);
+}
+int dpm_restriction_set_usb_tethering_state(device_policy_manager_h handle, int state)
+{
+    assert(handle != nullptr);
+    return handle->dpm_restriction_set_usb_tethering_state(state);
+}
+int dpm_restriction_set_bluetooth_mode_change_state(device_policy_manager_h handle, int state)
+{
+    assert(handle != nullptr);
+    return handle->dpm_restriction_set_bluetooth_mode_change_state(state);
+}
+int dpm_restriction_set_bluetooth_desktop_connectivity_state(device_policy_manager_h handle, int state)
+{
+    assert(handle != nullptr);
+    return handle->dpm_restriction_set_bluetooth_desktop_connectivity_state(state);
+}
+int dpm_restriction_set_bluetooth_pairing_state(device_policy_manager_h handle, int state)
+{
+    assert(handle != nullptr);
+    return handle->dpm_restriction_set_bluetooth_pairing_state(state);
+}
+int dpm_restriction_set_popimap_email_state(device_policy_manager_h handle, int state)
+{
+    assert(handle != nullptr);
+    return handle->dpm_restriction_set_popimap_email_state(state);
+}
+int dpm_restriction_set_browser_state(device_policy_manager_h handle, int state)
+{
+    assert(handle != nullptr);
+    return handle->dpm_restriction_set_browser_state(state);
+}
+int dpm_bluetooth_set_device_restriction(device_policy_manager_h handle, int state)
+{
+    assert(handle != nullptr);
+    return handle->dpm_bluetooth_set_device_restriction(state);
+}
+int dpm_bluetooth_set_uuid_restriction(device_policy_manager_h handle, int state)
+{
+    assert(handle != nullptr);
+    return handle->dpm_bluetooth_set_uuid_restriction(state);
+}
+int dpm_security_set_internal_storage_encryption(device_policy_manager_h handle, int state)
+{
+    assert(handle != nullptr);
+    return handle->dpm_security_set_internal_storage_encryption(state);
+}
+int dpm_security_set_external_storage_encryption(device_policy_manager_h handle, int state)
+{
+    assert(handle != nullptr);
+    return handle->dpm_security_set_external_storage_encryption(state);
+}
+int dpm_wifi_set_profile_change_restriction(device_policy_manager_h handle, int state)
+{
+    assert(handle != nullptr);
+    return handle->dpm_wifi_set_profile_change_restriction(state);
+}
+int dpm_wifi_set_network_access_restriction(device_policy_manager_h handle, int state)
+{
+    assert(handle != nullptr);
+    return handle->dpm_wifi_set_network_access_restriction(state);
+}
+
+int dpm_bluetooth_add_device_to_blacklist(device_policy_manager_h handle, const char* item)
+{
+    assert(handle != nullptr);
+    return handle->dpm_bluetooth_add_device_to_blacklist(item);
+}
+int dpm_bluetooth_remove_device_from_blacklist(device_policy_manager_h handle, const char* item)
+{
+    assert(handle != nullptr);
+    return handle->dpm_bluetooth_remove_device_from_blacklist(item);
+}
+int dpm_bluetooth_add_uuid_to_blacklist(device_policy_manager_h handle, const char* item)
+{
+    assert(handle != nullptr);
+    return handle->dpm_bluetooth_add_uuid_to_blacklist(item);
+}
+int dpm_bluetooth_remove_uuid_from_blacklist(device_policy_manager_h handle, const char* item)
+{
+    assert(handle != nullptr);
+    return handle->dpm_bluetooth_remove_uuid_from_blacklist(item);
+}
+int dpm_wifi_add_ssid_to_blocklist(device_policy_manager_h handle, const char* item)
+{
+    assert(handle != nullptr);
+    return handle->dpm_wifi_add_ssid_to_blocklist(item);
+}
+int dpm_wifi_remove_ssid_from_blocklist(device_policy_manager_h handle, const char* item)
+{
+    assert(handle != nullptr);
+    return handle->dpm_wifi_remove_ssid_from_blocklist(item);
+}
+
+int dpm_security_wipe_data(device_policy_manager_h handle, int state, const char* item)
+{
+    assert(handle != nullptr);
+    return handle->dpm_security_wipe_data(state, item);
+}
+int dpm_restriction_set_messaging_state(device_policy_manager_h handle, int state, const char* item)
+{
+    assert(handle != nullptr);
+    return handle->dpm_restriction_set_messaging_state(state, item);
+}
+int dpm_application_add_privilege_to_blacklist(device_policy_manager_h handle, int state, const char* item)
+{
+    assert(handle != nullptr);
+    return handle->dpm_application_add_privilege_to_blacklist(state, item);
+}
+int dpm_application_remove_privilege_from_blacklist(device_policy_manager_h handle, int state, const char* item)
+{
+    assert(handle != nullptr);
+    return handle->dpm_application_remove_privilege_from_blacklist(state, item);
+}
+int dpm_application_set_mode_restriction(device_policy_manager_h handle, int state, const char* item)
+{
+    assert(handle != nullptr);
+    return handle->dpm_application_set_mode_restriction(state, item);
+}
+int dpm_application_unset_mode_restriction(device_policy_manager_h handle, int state, const char* item)
+{
+    assert(handle != nullptr);
+    return handle->dpm_application_unset_mode_restriction(state, item);
+}
+int dpm_firewall_apply_deny_rules(device_policy_manager_h handle, const char* rules)
+{
+    assert(handle != nullptr);
+    return handle->dpm_firewall_apply_deny_rules(rules);
+}
+int dpm_firewall_flush_deny_rules(device_policy_manager_h handle)
+{
+    assert(handle != nullptr);
+    return handle->dpm_firewall_flush_deny_rules();
+}
+
+int dpm_restriction_set_usb_client_state(device_policy_manager_h handle, int allow)
+{
+    assert(handle != nullptr);
+    return handle->dpm_restriction_set_usb_client_state(allow);
+}
+int dpm_restriction_get_usb_client_state(device_policy_manager_h handle, int* is_allowed)
+{
+    assert(handle != nullptr);
+    return handle->dpm_restriction_get_usb_client_state(is_allowed);
+}
+int dpm_restriction_set_sound_state(device_policy_manager_h handle, int allow)
+{
+    assert(handle != nullptr);
+    return handle->dpm_restriction_set_sound_state(allow);
+}
+int dpm_restriction_get_sound_state(device_policy_manager_h handle, int* is_allowed)
+{
+    assert(handle != nullptr);
+    return handle->dpm_restriction_get_sound_state(is_allowed);
+}
+int dpm_restriction_set_tuner_state(device_policy_manager_h handle, int allow)
+{
+    assert(handle != nullptr);
+    return handle->dpm_restriction_set_tuner_state(allow);
+}
+int dpm_restriction_get_tuner_state(device_policy_manager_h handle, int* is_allowed)
+{
+    assert(handle != nullptr);
+    return handle->dpm_restriction_get_tuner_state(is_allowed);
+}
diff --git a/device_core/mock/device-policy-manager.h b/device_core/mock/device-policy-manager.h
new file mode 100644 (file)
index 0000000..0b614a8
--- /dev/null
@@ -0,0 +1,335 @@
+#ifndef DEVICE_POLICY_MANAGER_H
+#define DEVICE_POLICY_MANAGER_H
+
+#include <cassert>
+
+/**
+ * @brief The DPMInterface class represents supported DPM features
+ */
+class DPMInterface
+{
+public:
+    virtual ~DPMInterface()
+    {
+    }
+
+    virtual DPMInterface* dpm_manager_create()
+    {
+        return this;
+    }
+
+    virtual void dpm_manager_destroy() = 0;
+
+    virtual int dpm_application_install_package(const char* app_name) = 0;
+    virtual int dpm_application_uninstall_package(const char* app_name) = 0;
+
+    virtual int dpm_security_lockout_screen() = 0;
+
+    virtual int dpm_restriction_set_camera_state(int) = 0;
+    virtual int dpm_restriction_set_microphone_state(int) = 0;
+    virtual int dpm_restriction_set_location_state(int) = 0;
+    virtual int dpm_restriction_set_external_storage_state(int) = 0;
+    virtual int dpm_restriction_set_clipboard_state(int) = 0;
+    virtual int dpm_restriction_set_usb_debugging_state(int) = 0;
+    virtual int dpm_restriction_set_wifi_state(int) = 0;
+    virtual int dpm_restriction_set_wifi_hotspot_state(int) = 0;
+    virtual int dpm_restriction_set_bluetooth_tethering_state(int) = 0;
+    virtual int dpm_restriction_set_usb_tethering_state(int) = 0;
+    virtual int dpm_restriction_set_bluetooth_mode_change_state(int) = 0;
+    virtual int dpm_restriction_set_bluetooth_desktop_connectivity_state(int) = 0;
+    virtual int dpm_restriction_set_bluetooth_pairing_state(int) = 0;
+    virtual int dpm_restriction_set_popimap_email_state(int) = 0;
+    virtual int dpm_restriction_set_browser_state(int) = 0;
+    virtual int dpm_bluetooth_set_device_restriction(int) = 0;
+    virtual int dpm_bluetooth_set_uuid_restriction(int) = 0;
+    virtual int dpm_security_set_internal_storage_encryption(int) = 0;
+    virtual int dpm_security_set_external_storage_encryption(int) = 0;
+    virtual int dpm_wifi_set_profile_change_restriction(int) = 0;
+    virtual int dpm_wifi_set_network_access_restriction(int) = 0;
+
+    virtual int dpm_bluetooth_add_device_to_blacklist(const char*) = 0;
+    virtual int dpm_bluetooth_remove_device_from_blacklist(const char*) = 0;
+    virtual int dpm_bluetooth_add_uuid_to_blacklist(const char*) = 0;
+    virtual int dpm_bluetooth_remove_uuid_from_blacklist(const char*) = 0;
+    virtual int dpm_wifi_add_ssid_to_blocklist(const char*) = 0;
+    virtual int dpm_wifi_remove_ssid_from_blocklist(const char*) = 0;
+
+    virtual int dpm_security_wipe_data(int, const char*) = 0;
+    virtual int dpm_restriction_set_messaging_state(int, const char*) = 0;
+    virtual int dpm_application_add_privilege_to_blacklist(int, const char*) = 0;
+    virtual int dpm_application_remove_privilege_from_blacklist(int, const char*) = 0;
+    virtual int dpm_application_set_mode_restriction(int, const char*) = 0;
+    virtual int dpm_application_unset_mode_restriction(int, const char*) = 0;
+    virtual int dpm_firewall_apply_deny_rules(const char* rules) = 0;
+    virtual int dpm_firewall_flush_deny_rules() = 0;
+
+    virtual int dpm_restriction_set_usb_client_state(int allow) = 0;
+    virtual int dpm_restriction_get_usb_client_state(int* is_allowed) = 0;
+    virtual int dpm_restriction_set_sound_state(int allow) = 0;
+    virtual int dpm_restriction_get_sound_state(int* is_allowed) = 0;
+    virtual int dpm_restriction_set_tuner_state(int allow) = 0;
+    virtual int dpm_restriction_get_tuner_state(int* is_allowed) = 0;
+};
+
+/**
+ * @brief The DPMInterface_impl_default class - default dpm implementation for ubuntu
+ */
+class DPMInterface_impl_default: public DPMInterface
+{
+public:
+    int dpm_application_install_package(const char* app_name) override
+    {
+        return 0;
+    }
+
+    int dpm_application_uninstall_package(const char* app_name) override
+    {
+        return 0;
+    }
+
+    void dpm_manager_destroy() override
+    {
+    }
+
+    int dpm_security_lockout_screen() override
+    {
+        return 0;
+    }
+
+    int dpm_restriction_set_camera_state(int) override
+    {
+        return 0;
+    }
+    int dpm_restriction_set_microphone_state(int) override
+    {
+        return 0;
+    }
+    int dpm_restriction_set_location_state(int) override
+    {
+        return 0;
+    }
+    int dpm_restriction_set_external_storage_state(int) override
+    {
+        return 0;
+    }
+    int dpm_restriction_set_clipboard_state(int) override
+    {
+        return 0;
+    }
+    int dpm_restriction_set_usb_debugging_state(int) override
+    {
+        return 0;
+    }
+    int dpm_restriction_set_wifi_state(int) override
+    {
+        return 0;
+    }
+    int dpm_restriction_set_wifi_hotspot_state(int) override
+    {
+        return 0;
+    }
+    int dpm_restriction_set_bluetooth_tethering_state(int) override
+    {
+        return 0;
+    }
+    int dpm_restriction_set_usb_tethering_state(int) override
+    {
+        return 0;
+    }
+    int dpm_restriction_set_bluetooth_mode_change_state(int) override
+    {
+        return 0;
+    }
+    int dpm_restriction_set_bluetooth_desktop_connectivity_state(int) override
+    {
+        return 0;
+    }
+    int dpm_restriction_set_bluetooth_pairing_state(int) override
+    {
+        return 0;
+    }
+    int dpm_restriction_set_popimap_email_state(int) override
+    {
+        return 0;
+    }
+    int dpm_restriction_set_browser_state(int) override
+    {
+        return 0;
+    }
+    int dpm_bluetooth_set_device_restriction(int) override
+    {
+        return 0;
+    }
+    int dpm_bluetooth_set_uuid_restriction(int) override
+    {
+        return 0;
+    }
+    int dpm_security_set_internal_storage_encryption(int) override
+    {
+        return 0;
+    }
+    int dpm_security_set_external_storage_encryption(int) override
+    {
+        return 0;
+    }
+    int dpm_wifi_set_profile_change_restriction(int) override
+    {
+        return 0;
+    }
+    int dpm_wifi_set_network_access_restriction(int) override
+    {
+        return 0;
+    }
+
+    int dpm_bluetooth_add_device_to_blacklist(const char*) override
+    {
+        return 0;
+    }
+    int dpm_bluetooth_remove_device_from_blacklist(const char*) override
+    {
+        return 0;
+    }
+    int dpm_bluetooth_add_uuid_to_blacklist(const char*) override
+    {
+        return 0;
+    }
+    int dpm_bluetooth_remove_uuid_from_blacklist(const char*) override
+    {
+        return 0;
+    }
+    int dpm_wifi_add_ssid_to_blocklist(const char*) override
+    {
+        return 0;
+    }
+    int dpm_wifi_remove_ssid_from_blocklist(const char*) override
+    {
+        return 0;
+    }
+
+    int dpm_security_wipe_data(int, const char*) override
+    {
+        return 0;
+    }
+    int dpm_restriction_set_messaging_state(int, const char*) override
+    {
+        return 0;
+    }
+    int dpm_application_add_privilege_to_blacklist(int, const char*) override
+    {
+        return 0;
+    }
+    int dpm_application_remove_privilege_from_blacklist(int, const char*) override
+    {
+        return 0;
+    }
+    int dpm_application_set_mode_restriction(int, const char*) override
+    {
+        return 0;
+    }
+    int dpm_application_unset_mode_restriction(int, const char*) override
+    {
+        return 0;
+    }
+    int dpm_firewall_apply_deny_rules(const char* rules) override
+    {
+        return 0;
+    }
+    int dpm_firewall_flush_deny_rules() override
+    {
+        return 0;
+    }
+    int dpm_restriction_set_usb_client_state(int allow) override
+    {
+        return 0;
+    }
+    int dpm_restriction_get_usb_client_state(int* is_allowed) override
+    {
+        return 0;
+    }
+    int dpm_restriction_set_sound_state(int allow) override
+    {
+        return 0;
+    }
+    int dpm_restriction_get_sound_state(int* is_allowed) override
+    {
+        return 0;
+    }
+    int dpm_restriction_set_tuner_state(int allow) override
+    {
+        return 0;
+    }
+    int dpm_restriction_get_tuner_state(int* is_allowed) override
+    {
+        return 0;
+    }
+};
+
+typedef DPMInterface* device_policy_manager_h;
+
+/**
+ * @brief Set custom DPM implementation to change DPM functionality. Can be used for testing.
+ * @param dpm [in] pointer to the object implementing DPMInterface.
+ */
+void dpm_set_custom_implementation(DPMInterface* dpm);
+
+extern "C"
+{
+
+    device_policy_manager_h dpm_manager_create();
+
+    void dpm_manager_destroy(device_policy_manager_h handle);
+
+    int dpm_application_install_package(device_policy_manager_h handle, const char* package_name);
+
+    int dpm_application_uninstall_package(device_policy_manager_h handle, const char* package_name);
+
+    int dpm_security_lockout_screen(device_policy_manager_h);
+
+    int dpm_restriction_set_camera_state(device_policy_manager_h, int);
+    int dpm_restriction_set_microphone_state(device_policy_manager_h, int);
+    int dpm_restriction_set_location_state(device_policy_manager_h, int);
+    int dpm_restriction_set_external_storage_state(device_policy_manager_h, int);
+    int dpm_restriction_set_clipboard_state(device_policy_manager_h, int);
+    int dpm_restriction_set_usb_debugging_state(device_policy_manager_h, int);
+    int dpm_restriction_set_wifi_state(device_policy_manager_h, int);
+    int dpm_restriction_set_wifi_hotspot_state(device_policy_manager_h, int);
+    int dpm_restriction_set_bluetooth_tethering_state(device_policy_manager_h, int);
+    int dpm_restriction_set_usb_tethering_state(device_policy_manager_h, int);
+    int dpm_restriction_set_bluetooth_mode_change_state(device_policy_manager_h, int);
+    int dpm_restriction_set_bluetooth_desktop_connectivity_state(device_policy_manager_h, int);
+    int dpm_restriction_set_bluetooth_pairing_state(device_policy_manager_h, int);
+    int dpm_restriction_set_popimap_email_state(device_policy_manager_h, int);
+    int dpm_restriction_set_browser_state(device_policy_manager_h, int);
+    int dpm_bluetooth_set_device_restriction(device_policy_manager_h, int);
+    int dpm_bluetooth_set_uuid_restriction(device_policy_manager_h, int);
+    int dpm_security_set_internal_storage_encryption(device_policy_manager_h, int);
+    int dpm_security_set_external_storage_encryption(device_policy_manager_h, int);
+    int dpm_wifi_set_profile_change_restriction(device_policy_manager_h, int);
+    int dpm_wifi_set_network_access_restriction(device_policy_manager_h, int);
+
+    int dpm_bluetooth_add_device_to_blacklist(device_policy_manager_h, const char*);
+    int dpm_bluetooth_remove_device_from_blacklist(device_policy_manager_h, const char*);
+    int dpm_bluetooth_add_uuid_to_blacklist(device_policy_manager_h, const char*);
+    int dpm_bluetooth_remove_uuid_from_blacklist(device_policy_manager_h, const char*);
+    int dpm_wifi_add_ssid_to_blocklist(device_policy_manager_h, const char*);
+    int dpm_wifi_remove_ssid_from_blocklist(device_policy_manager_h, const char*);
+
+    int dpm_security_wipe_data(device_policy_manager_h, int, const char*);
+    int dpm_restriction_set_messaging_state(device_policy_manager_h, int, const char*);
+    int dpm_application_add_privilege_to_blacklist(device_policy_manager_h, int, const char*);
+    int dpm_application_remove_privilege_from_blacklist(device_policy_manager_h, int, const char*);
+    int dpm_application_set_mode_restriction(device_policy_manager_h, int, const char*);
+    int dpm_application_unset_mode_restriction(device_policy_manager_h, int, const char*);
+    int dpm_firewall_apply_deny_rules(device_policy_manager_h handle, const char* rules);
+    int dpm_firewall_flush_deny_rules(device_policy_manager_h handle);
+
+    int dpm_restriction_set_usb_client_state(device_policy_manager_h handle, int allow);
+    int dpm_restriction_get_usb_client_state(device_policy_manager_h handle, int* is_allowed);
+    int dpm_restriction_set_sound_state(device_policy_manager_h handle, int allow);
+    int dpm_restriction_get_sound_state(device_policy_manager_h handle, int* is_allowed);
+    int dpm_restriction_set_tuner_state(device_policy_manager_h handle, int allow);
+    int dpm_restriction_get_tuner_state(device_policy_manager_h handle, int* is_allowed);
+
+}
+
+#endif // DEVICE_POLICY_MANAGER_H
diff --git a/device_core/mock/iot_policy_enforce_mock.h b/device_core/mock/iot_policy_enforce_mock.h
new file mode 100644 (file)
index 0000000..a0c3131
--- /dev/null
@@ -0,0 +1,16 @@
+#ifndef IOT_POLICY_ENFORCE_MOCK_H
+#define IOT_POLICY_ENFORCE_MOCK_H
+
+#include "iot_policy_enforce.h"
+/**
+ * @brief The IPolicyGroupEnforceMock class used as mock for policy group
+ */
+class IPolicyGroupEnforceMock: public iot::core::IPolicyGroupEnforce
+{
+public:
+    MOCK_METHOD0(Init, bool());
+    MOCK_METHOD0(Deinit, void());
+    MOCK_METHOD1(ParseGroup, bool(Json::Value& policy));
+};
+
+#endif // IOT_POLICY_ENFORCE_MOCK_H
diff --git a/device_core/mock/iotdevice_mock.h b/device_core/mock/iotdevice_mock.h
new file mode 100644 (file)
index 0000000..8683760
--- /dev/null
@@ -0,0 +1,25 @@
+#ifndef IOTDEVICE_MOCK_H
+#define IOTDEVICE_MOCK_H
+
+#include "iotdevice.h"
+
+class IoTDeviceMock: public NetworkManager::IoTDevice
+{
+public:
+    MOCK_CONST_METHOD0(getUUID, const std::string&());
+    MOCK_CONST_METHOD0(getName, const std::string&());
+    MOCK_CONST_METHOD0(getModel, const std::string&());
+    MOCK_CONST_METHOD0(getType, const std::string&());
+    MOCK_CONST_METHOD0(getHost, const std::string&());
+    MOCK_CONST_METHOD0(getParent, const std::string&());
+    MOCK_CONST_METHOD0(isOnline, bool());
+    MOCK_CONST_METHOD0(isCloudAccessibility, bool());
+    MOCK_METHOD3(setCloudProperties, void(const std::string& host, const std::string& provider, const std::string& token));
+    MOCK_METHOD2(setWiFiProperties, void(const std::string& wifi_sid, const std::string& wifi_pass));
+    MOCK_METHOD0(unOwnDevice, void());
+    MOCK_METHOD1(setState, void(bool state));
+    MOCK_METHOD1(activate, void(std::shared_ptr<OC::OCResource>));
+    MOCK_METHOD0(deactivate, void());
+};
+
+#endif // IOTDEVICE_MOCK_H
diff --git a/device_core/mock/iotivity_mock.h b/device_core/mock/iotivity_mock.h
new file mode 100644 (file)
index 0000000..b755a7d
--- /dev/null
@@ -0,0 +1,37 @@
+#ifndef IOTIVITY_MOCK_H
+#define IOTIVITY_MOCK_H
+
+#include "iotivity.h"
+#include "gmock/gmock.h"
+
+class IoTivityMock: public NetworkManager::IoTivity
+{
+public:
+    MOCK_METHOD0(isSignedIn, bool());
+    MOCK_METHOD0(isConnected, bool());
+    MOCK_METHOD1(setConnected, void(bool state));
+//    MOCK_METHOD1(setDevicePresenceHook, void(NetworkManager::PresenceHook&& hook));
+//    MOCK_METHOD0(removeDevicePresenceHook, void());
+    MOCK_METHOD3(signUp, void(const std::string& host, const std::string& auth_provider, const std::string& access_token));
+    MOCK_METHOD0(signIn, void());
+    MOCK_METHOD3(signIn, void(const std::string& host, const std::string& uid, const std::string& access_token));
+    MOCK_METHOD0(signOut, void());
+    MOCK_METHOD0(deleteFromAccount, void());
+    MOCK_METHOD3(registerDeviceInfo, void(const std::string& name, const std::string& model, const std::string& type));
+    MOCK_METHOD3(findDevices, std::vector<NetworkManager::IoTDevicePtr>(bool cloud, OCConnectivityType con_type, const std::string& uri));
+    MOCK_METHOD4(findResource, std::shared_ptr<OC::OCResource>(bool cloud, const std::string& type, const std::string& uri, OCConnectivityType con_type));
+    MOCK_METHOD4(findResourceList, std::vector<std::shared_ptr<OC::OCResource>>(bool cloud, const std::string& type, const std::string& uri, OCConnectivityType con_type));
+    MOCK_METHOD4(findResource, std::shared_ptr<OC::OCResource>(const std::string& host, const std::string& type, const std::string& uri, OCConnectivityType con_type));
+    MOCK_METHOD4(findResource, std::shared_ptr<OC::OCResource>(const std::string& host, const std::string& type, const std::string& uri, const std::string& sid));
+    MOCK_METHOD0(getDeviceID, const std::string&());
+    MOCK_METHOD1(publishResources, void(OC::ResourceHandles& handles));
+    MOCK_METHOD1(unPublishResources, void(OC::ResourceHandles& handles));
+    MOCK_METHOD0(unPublishAllResources, void());
+    MOCK_METHOD0(host, const std::string&());
+    MOCK_METHOD0(cloudId, const std::string&());
+    MOCK_METHOD0(getCloudAuthId, const std::string&());
+    MOCK_METHOD0(getCloudAccessToken, const std::string&());
+    MOCK_METHOD0(getMqHandler, NetworkManager::IMqClient*());
+};
+
+#endif // IOTIVITY_MOCK_H
diff --git a/device_core/mock/mac.h b/device_core/mock/mac.h
new file mode 100644 (file)
index 0000000..fa69ca5
--- /dev/null
@@ -0,0 +1,155 @@
+/*
+ *  Copyright (c) 2017 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+
+#ifndef __CAPI_AUDIT_TRAIL_MAC_H__
+#define __CAPI_AUDIT_TRAIL_MAC_H__
+
+#include "audit-trail.h"
+
+/**
+ * @file mac.h
+ * @brief This file provides APIs to get MAC(Mandatory Access Control) logs
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * @brief       Retrieves all MAC logs that occured in system.
+ * @details     This API calls audit_trail_string_cb() once for each MAC
+ *              (Mandatory Access Control) logs collected by audit-trail
+ *              when MAC auditing is enabled.
+ * @since_tizen 5.0
+ * @param[in]   handle The audit-trail handle
+ * @param[in]   callback The iteration callback function
+ * @param[in]   user_data The user data passed to the callback function
+ * @return      #AUDIT_TRAIL_ERROR_NONE on success, otherwise a negative value
+ * @retval      #AUDIT_TRAIL_ERROR_NONE Successful
+ * @retval      #AUDIT_TRAIL_ERROR_TIMED_OUT Time out
+ * @retval      #AUDIT_TRAIL_ERROR_INVALID_PARAMETER Invalid parameter
+ * @pre         The handle must be created by audit_trail_create().
+ * @see         audit_trail_create()
+ * @see         audit_trail_destroy()
+ * @see         audit_trail_enable_mac()
+ */
+AUDIT_TRAIL_API int audit_trail_foreach_mac(audit_trail_h handle, audit_trail_string_cb callback, void *user_data);
+
+/**
+ * @brief       Clears all MAC logs saved in audit-trail.
+ * @details     This API removes all MAC(Mandatory Access Control) logs
+ *              collected by audit-trail.
+ * @since_tizen 5.0
+ * @param[in]   handle The audit-trail handle
+ * @return      #AUDIT_TRAIL_ERROR_NONE on success, otherwise a negative value
+ * @retval      #AUDIT_TRAIL_ERROR_NONE Successful
+ * @retval      #AUDIT_TRAIL_ERROR_TIMED_OUT Time out
+ * @retval      #AUDIT_TRAIL_ERROR_INVALID_PARAMETER Invalid parameter
+ * @pre         The handle must be created by audit_trail_create().
+ * @see         audit_trail_create()
+ * @see         audit_trail_destroy()
+ * @see         audit_trail_foreach_mac()
+ */
+AUDIT_TRAIL_API int audit_trail_clear_mac(audit_trail_h handle);
+
+/**
+ * @brief       Adds a MAC log callback.
+ * @details     This API can be used to receive MAC(Mandatory Access Control)
+ *              logs of system. The callback specified to this function is
+ *              automatically called when a new log occurs.
+ * @since_tizen 5.0
+ * @param[in]   context The audit_trail handle
+ * @param[in]   callback The callback to get MAC(Mandatory Access Control) logs
+ * @param[in]   user_data The user data passed to the callback function
+ * @param[out]  id Callback identifier
+ * @return      #AUDIT_TRAIL_ERROR_NONE on success, otherwise a negative value
+ * @retval      #AUDIT_TRAIL_ERROR_NONE Successful
+ * @retval      #AUDIT_TRAIL_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval      #AUDIT_TRAIL_ERROR_TIMED_OUT Time out
+ * @pre         The handle must be created by audit_trail_create().
+ * @pre         MAC auditing must be enabled by audit_trail_enable_mac().
+ * @see         audit_trail_create()
+ * @see         audit_trail_destroy()
+ * @see         audit_trail_remove_mac_cb()
+ */
+AUDIT_TRAIL_API int audit_trail_add_mac_cb(audit_trail_h handle,
+                                                       audit_trail_string_cb callback, void* user_data,
+                                                       int* id);
+
+/**
+ * @brief       Removes the MAC log callback.
+ * @details     This API can be used to remove the MAC(Mandatory Access
+ *              Control) logs callback.
+ * @since_tizen 5.0
+ * @param[in]   context The audit trail handle
+ * @param[in]   id Callback identifier
+ * @return      #AUDIT_TRAIL_ERROR_NONE on success, otherwise a negative value
+ * @retval      #AUDIT_TRAIL_ERROR_NONE Successful
+ * @retval      #AUDIT_TRAIL_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval      #AUDIT_TRAIL_ERROR_TIMED_OUT Time out
+ * @pre         The context must be created by audit_trail_create().
+ * @see         audit_trail_create()
+ * @see         audit_trail_destroy()
+ * @see         audit_trail_add_mac_cb()
+ */
+AUDIT_TRAIL_API int audit_trail_remove_mac_cb(audit_trail_h handle, int id);
+
+/**
+ * @brief       Enables MAC auditing.
+ * @details     This API can be used to enable to collect the MAC(Mandatory
+ *              Access Control) logs. Any MAC log will not be collected
+ *              until auditing is enabled
+ * @since_tizen 5.0
+ * @param[in]   handle The audit-trail handle
+ * @param[in]   en True enables MAC auditing, Otherwise disables
+ * @return      #AUDIT_TRAIL_ERROR_NONE on success, otherwise a negative value
+ * @retval      #AUDIT_TRAIL_ERROR_NONE Successful
+ * @retval      #AUDIT_TRAIL_ERROR_TIMED_OUT Time out
+ * @retval      #AUDIT_TRAIL_ERROR_INVALID_PARAMETER Invalid parameter
+ * @pre         The handle must be created by audit_trail_create().
+ * @see         audit_trail_create()
+ * @see         audit_trail_destroy()
+ * @see         audit_trail_mac_syscall()
+ * @see         audit_trail_add_mac_cb()
+ */
+AUDIT_TRAIL_API int audit_trail_enable_mac(audit_trail_h handle, bool en);
+
+/**
+ * @brief       Retrieves if MAC auditing is enabled.
+ * @details     This API can be used to know if MAC(Mandatory Access Control)
+ *               auditing is enabled now.
+ * @since_tizen 5.0
+ * @param[in]   handle The audit-trail handle
+ * @param[out]  en If true, MAC auditing was enabled, Otherwise disabled
+ * @return      #AUDIT_TRAIL_ERROR_NONE on success, otherwise a negative value
+ * @retval      #AUDIT_TRAIL_ERROR_NONE Successful
+ * @retval      #AUDIT_TRAIL_ERROR_TIMED_OUT Time out
+ * @retval      #AUDIT_TRAIL_ERROR_INVALID_PARAMETER Invalid parameter
+ * @pre         The handle must be created by audit_trail_create().
+ * @see         audit_trail_create()
+ * @see         audit_trail_destroy()
+ */
+AUDIT_TRAIL_API int audit_trail_is_enabled_mac(audit_trail_h handle, bool *en);
+
+/**
+ * @}
+ */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __CAPI_AUDIT_TRAIL_MAC_H__ */
diff --git a/device_core/mock/mqclient_mock.h b/device_core/mock/mqclient_mock.h
new file mode 100644 (file)
index 0000000..74a6dcb
--- /dev/null
@@ -0,0 +1,15 @@
+#ifndef MQCLIENT_MOCK_H
+#define MQCLIENT_MOCK_H
+
+#include <gmock/gmock.h>
+#include "imqclient.h"
+
+class MqClientMock: public NetworkManager::IMqClient
+{
+public:
+    MOCK_METHOD2(publish, void(const std::string& subTopic, const OC::OCRepresentation& rep));
+    MOCK_METHOD2(subscribe, void(const std::string& subTopic, OC::ObserveCallback subscribeCB));
+    MOCK_METHOD1(unsubscribe, void(const std::string& subTopic));
+};
+
+#endif // MQCLIENT_MOCK_H
diff --git a/device_core/mock/syscall.h b/device_core/mock/syscall.h
new file mode 100644 (file)
index 0000000..7a33062
--- /dev/null
@@ -0,0 +1,154 @@
+/*
+ *  Copyright (c) 2075 Samsung Electronics Co., Ltd All Rights Reserved
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License
+ */
+
+#ifndef __CAPI_AUDIT_TRAIL_SYSTEM_CALL_H__
+#define __CAPI_AUDIT_TRAIL_SYSTEM_CALL_H__
+
+#include "audit-trail.h"
+
+/**
+ * @file syscall.h
+ * @brief This file provides APIs to get system call logs
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * @brief       Retrieves all system call logs that occured in system.
+ * @details     This API calls audit_trail_strimg_cb() once for each system call
+ *              logs collected by audit-trail when system call auditing is enabled.
+ * @since_tizen 5.0
+ * @param[in]   handle The audit-trail handle
+ * @param[in]   callback The iteration callback function
+ * @param[in]   user_data The user data passed to the callback function
+ * @return      #AUDIT_TRAIL_ERROR_NONE on success, otherwise a negative value
+ * @retval      #AUDIT_TRAIL_ERROR_NONE Successful
+ * @retval      #AUDIT_TRAIL_ERROR_TIMED_OUT Time out
+ * @retval      #AUDIT_TRAIL_ERROR_INVALID_PARAMETER Invalid parameter
+ * @pre         The handle must be created by audit_trail_create().
+ * @see         audit_trail_create()
+ * @see         audit_trail_destroy()
+ * @see         audit_trail_enable_syscall()
+ */
+AUDIT_TRAIL_API int audit_trail_foreach_syscall(audit_trail_h handle, audit_trail_string_cb callback, void *user_data);
+
+/**
+ * @brief       Clears all system call logs saved in audit-trail.
+ * @details     This API removes all system call logs
+ *              collected by audit-trail.
+ * @since_tizen 5.0
+ * @param[in]   handle The audit-trail handle
+ * @return      #AUDIT_TRAIL_ERROR_NONE on success, otherwise a negative value
+ * @retval      #AUDIT_TRAIL_ERROR_NONE Successful
+ * @retval      #AUDIT_TRAIL_ERROR_TIMED_OUT Time out
+ * @retval      #AUDIT_TRAIL_ERROR_INVALID_PARAMETER Invalid parameter
+ * @pre         The handle must be created by audit_trail_create().
+ * @see         audit_trail_create()
+ * @see         audit_trail_destroy()
+ * @see         audit_trail_foreach_syscall()
+ */
+AUDIT_TRAIL_API int audit_trail_clear_syscall(audit_trail_h handle);
+
+/**
+ * @brief       Adds a system call log callback.
+ * @details     This API can be used to receive system call logs of system.
+ *              The callback specified to this function is automatically called
+ *              when a new log occurs.
+ * @since_tizen 5.0
+ * @param[in]   context The audit_trail handle
+ * @param[in]   callback The callback to get system call logs
+ * @param[in]   user_data The user data passed to the callback function
+ * @param[out]  id Callback identifier
+ * @return      #AUDIT_TRAIL_ERROR_NONE on success, otherwise a negative value
+ * @retval      #AUDIT_TRAIL_ERROR_NONE Successful
+ * @retval      #AUDIT_TRAIL_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval      #AUDIT_TRAIL_ERROR_TIMED_OUT Time out
+ * @pre         The handle must be created by audit_trail_create().
+ * @pre         System call auditing must be enabled by
+ *              audit_trail_enable_syscall().
+ * @see         audit_trail_create()
+ * @see         audit_trail_destroy()
+ * @see         audit_trail_enable_syscall()
+ * @see         audit_trail_remove_syscall_cb()
+ */
+AUDIT_TRAIL_API int audit_trail_add_syscall_cb(audit_trail_h handle,
+                                                       audit_trail_string_cb callback, void* user_data,
+                                                       int* id);
+
+/**
+ * @brief       Removes the system call log callback.
+ * @details     This API can be used to remove the system call logs callback.
+ * @since_tizen 5.0
+ * @param[in]   context The audit trail handle
+ * @param[in]   id Callback identifier
+ * @return      #AUDIT_TRAIL_ERROR_NONE on success, otherwise a negative value
+ * @retval      #AUDIT_TRAIL_ERROR_NONE Successful
+ * @retval      #AUDIT_TRAIL_ERROR_INVALID_PARAMETER Invalid parameter
+ * @retval      #AUDIT_TRAIL_ERROR_TIMED_OUT Time out
+ * @pre         The context must be created by audit_trail_create().
+ * @see         audit_trail_create()
+ * @see         audit_trail_destroy()
+ * @see         audit_trail_add_syscall_cb()
+ */
+AUDIT_TRAIL_API int audit_trail_remove_syscall_cb(audit_trail_h handle, int id);
+
+/**
+ * @brief       Enables system call auditing.
+ * @details     This API can be used to enable to collect the system call logs.
+ *              Any system call log will not be collected until auditing is
+ *              enabled
+ * @since_tizen 5.0
+ * @param[in]   handle The audit-trail handle
+ * @param[in]   en True enables system call auditing, Otherwise disables
+ * @return      #AUDIT_TRAIL_ERROR_NONE on success, otherwise a negative value
+ * @retval      #AUDIT_TRAIL_ERROR_NONE Successful
+ * @retval      #AUDIT_TRAIL_ERROR_TIMED_OUT Time out
+ * @retval      #AUDIT_TRAIL_ERROR_INVALID_PARAMETER Invalid parameter
+ * @pre         The handle must be created by audit_trail_create().
+ * @see         audit_trail_create()
+ * @see         audit_trail_destroy()
+ * @see         audit_trail_foreach_syscall()
+ * @see         audit_trail_add_syscall_cb()
+ */
+AUDIT_TRAIL_API int audit_trail_enable_syscall(audit_trail_h handle, bool en);
+
+/**
+ * @brief       Retrieves if system call auditing is enabled.
+ * @details     This API can be used to know if system call auditing is
+ *              enabled now.
+ * @since_tizen 5.0
+ * @param[in]   handle The audit-trail handle
+ * @param[out]  en If true, system call auditing was enabled, Otherwise disabled
+ * @return      #AUDIT_TRAIL_ERROR_NONE on success, otherwise a negative value
+ * @retval      #AUDIT_TRAIL_ERROR_NONE Successful
+ * @retval      #AUDIT_TRAIL_ERROR_TIMED_OUT Time out
+ * @retval      #AUDIT_TRAIL_ERROR_INVALID_PARAMETER Invalid parameter
+ * @pre         The handle must be created by audit_trail_create().
+ * @see         audit_trail_create()
+ * @see         audit_trail_destroy()
+ */
+AUDIT_TRAIL_API int audit_trail_is_enabled_syscall(audit_trail_h handle, bool *en);
+/**
+ * @}
+ */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __CAPI_AUDIT_TRAIL_SYSTEM_CALL_H__ */
index c16668b..0c149b4 100644 (file)
@@ -5,6 +5,7 @@ string(REPLACE " " "_" ProjectId ${ProjectId})
 project(${ProjectId} C CXX)
 
 include_directories(
+       ../.
        ../ctrl_app_lib/inc
        ../iotivity_lib/inc
        ../agent_lib/inc
@@ -15,8 +16,15 @@ include_directories(
 file(GLOB DPM_SOURCES dpm/*.cpp)
 file(GLOB NMDAEMON_SOURCES *.cpp)
 if("${FLAVOR}" STREQUAL "UBUNTU")
-        list(REMOVE_ITEM NMDAEMON_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/audit_trail_client.cpp)
-        list(REMOVE_ITEM NMDAEMON_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/report_service.cpp)
+               include_directories(../mock)
+#        list(REMOVE_ITEM NMDAEMON_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/audit_trail_client.cpp)
+               file(GLOB DPM_MOCK ../mock/*.cpp)
+               list(APPEND NMDAEMON_SOURCES ${DPM_MOCK})
+else()
+       FOREACH(flag ${pkgs_CFLAGS})
+               SET(EXTRA_CFLAGS "${EXTRA_CFLAGS} ${flag}")
+       ENDFOREACH(flag)
+
 endif()
 
 SET (SOURCES
index 9a749c3..24acc3f 100644 (file)
@@ -8,7 +8,9 @@
 #include <cassert>
 #include <algorithm>
 
-#ifndef __BUILD_UBUNTU__
+#if defined(__BUILD_UBUNTU__) || defined(__MOCK_THIRDPARTY__)
+#include "mock/device-policy-manager.h"
+#else
 #include <dpm/device-policy-manager.h>
 #include <dpm/application.h>
 #endif
@@ -23,7 +25,6 @@ namespace NMD
 
 int ApplicationService::install(const std::string& package_path_name)
 {
-#ifndef __BUILD_UBUNTU__
     int res = -1;
     device_policy_manager_h handle = dpm_manager_create();
     if (handle) {
@@ -31,26 +32,19 @@ int ApplicationService::install(const std::string& package_path_name)
         dpm_manager_destroy(handle);
     }
     return res;
-#else
-    return 0;
-#endif
 }
 
 int ApplicationService::uninstall(const std::string& package_name)
 {
-#ifndef __BUILD_UBUNTU__
     int res = -1;
     device_policy_manager_h handle = dpm_manager_create();
-    LOG_D(TAG, "DPM handle = 0x%08x", int(handle));
+
     if (handle) {
         res = dpm_application_uninstall_package(handle, package_name.c_str());
         LOG_D(TAG, "dpm_application_uninstall_package returned %d", res);
         dpm_manager_destroy(handle);
     }
     return res;
-#else
-    return 0;
-#endif
 }
 
 std::string ApplicationService::find_package_by_app_name(const std::string& app_name)
index c257211..9ff484f 100644 (file)
@@ -3,12 +3,17 @@
 
 #include <string>
 #include <memory>
-
+#if defined(__BUILD_UBUNTU__) || defined(__MOCK_THIRDPARTY__)
+#include <mock/dac.h>
+#include <mock/mac.h>
+#include <mock/syscall.h>
+#include <mock/audit-trail.h>
+#else
 #include <audit-trail/dac.h>
 #include <audit-trail/mac.h>
 #include <audit-trail/syscall.h>
 #include <audit-trail/audit-trail.h>
-
+#endif
 #include "proxythread.h"
 #include "reporthandler.h"
 #include "utils.h"
index 48db6fe..c480122 100644 (file)
@@ -36,7 +36,6 @@ public:
                    ThreadBase* main_thread);
 
     bool process(const OC::OCRepresentation& command) override;
-private:
 
     bool unOwnCommand(const OC::OCRepresentation& command);
 
@@ -44,6 +43,8 @@ private:
 
     void unOwnTask();
 
+private:
+
     NetworkManager::IoTivity* m_iotivity;
     std::shared_ptr<HubResource> m_hub;
     std::shared_ptr<ReportHandler> m_report_handler;
index 0e82a5e..387970c 100644 (file)
@@ -9,7 +9,9 @@
 #include <pwd.h>
 #include <sys/reboot.h>
 
-#ifndef __BUILD_UBUNTU__
+#if defined(__BUILD_UBUNTU__) || defined(__MOCK_THIRDPARTY__)
+#include "mock/device-policy-manager.h"
+#else
 #include <dpm/device-policy-manager.h>
 #include <dpm/bluetooth.h>
 #include <dpm/wifi.h>
 using namespace dpm_api;
 using namespace std;
 
-#ifndef __BUILD_UBUNTU__
 typedef device_policy_manager_h dpmh;
-#else
-typedef void* dpmh;
-#endif
 
 typedef function<int(dpmh)>  ApiNone;
 typedef function<int(dpmh, int)>  ApiInt;
@@ -44,7 +42,7 @@ int dpm_device_power_off(dpmh)
     return reboot(RB_POWER_OFF);
 }
 
-#ifdef __BUILD_UBUNTU__
+#if defined(__BUILD_UBUNTU__) || defined(__MOCK_THIRDPARTY__)
 
 enum {
     DPM_ERROR_NONE,
@@ -58,163 +56,9 @@ enum {
     DPM_ERROR_NO_DATA,
 };
 
-dpmh dpm_manager_create()
-{
-    return dpmh(1);
-}
-
-void dpm_manager_destroy(dpmh) {}
-
-int dpm_security_lockout_screen(dpmh)
-{
-    return 0;
-}
-
-int dpm_restriction_set_camera_state(dpmh, int)
-{
-    return 0;
-}
-int dpm_restriction_set_microphone_state(dpmh, int)
-{
-    return 0;
-}
-int dpm_restriction_set_location_state(dpmh, int)
-{
-    return 0;
-}
-int dpm_restriction_set_external_storage_state(dpmh, int)
-{
-    return 0;
-}
-int dpm_restriction_set_clipboard_state(dpmh, int)
-{
-    return 0;
-}
-int dpm_restriction_set_usb_debugging_state(dpmh, int)
-{
-    return 0;
-}
-int dpm_restriction_set_wifi_state(dpmh, int)
-{
-    return 0;
-}
-int dpm_restriction_set_wifi_hotspot_state(dpmh, int)
-{
-    return 0;
-}
-int dpm_restriction_set_bluetooth_tethering_state(dpmh, int)
-{
-    return 0;
-}
-int dpm_restriction_set_usb_tethering_state(dpmh, int)
-{
-    return 0;
-}
-int dpm_restriction_set_bluetooth_mode_change_state(dpmh, int)
-{
-    return 0;
-}
-int dpm_restriction_set_bluetooth_desktop_connectivity_state(dpmh, int)
-{
-    return 0;
-}
-int dpm_restriction_set_bluetooth_pairing_state(dpmh, int)
-{
-    return 0;
-}
-int dpm_restriction_set_popimap_email_state(dpmh, int)
-{
-    return 0;
-}
-int dpm_restriction_set_browser_state(dpmh, int)
-{
-    return 0;
-}
-int dpm_bluetooth_set_device_restriction(dpmh, int)
-{
-    return 0;
-}
-int dpm_bluetooth_set_uuid_restriction(dpmh, int)
-{
-    return 0;
-}
-int dpm_security_set_internal_storage_encryption(dpmh, int)
-{
-    return 0;
-}
-int dpm_security_set_external_storage_encryption(dpmh, int)
-{
-    return 0;
-}
-int dpm_wifi_set_profile_change_restriction(dpmh, int)
-{
-    return 0;
-}
-int dpm_wifi_set_network_access_restriction(dpmh, int)
-{
-    return 0;
-}
-
-int dpm_bluetooth_add_device_to_blacklist(dpmh, const char*)
-{
-    return 0;
-}
-int dpm_bluetooth_remove_device_from_blacklist(dpmh, const char*)
-{
-    return 0;
-}
-int dpm_bluetooth_add_uuid_to_blacklist(dpmh, const char*)
-{
-    return 0;
-}
-int dpm_bluetooth_remove_uuid_from_blacklist(dpmh, const char*)
-{
-    return 0;
-}
-int dpm_wifi_add_ssid_to_blocklist(dpmh, const char*)
-{
-    return 0;
-}
-int dpm_wifi_remove_ssid_from_blocklist(dpmh, const char*)
-{
-    return 0;
-}
-
-int dpm_security_wipe_data(dpmh, int, const char*)
-{
-    return 0;
-}
-int dpm_restriction_set_messaging_state(dpmh, int, const char*)
-{
-    return 0;
-}
-int dpm_application_add_privilege_to_blacklist(dpmh, int, const char*)
-{
-    return 0;
-}
-int dpm_application_remove_privilege_from_blacklist(dpmh, int, const char*)
-{
-    return 0;
-}
-int dpm_application_set_mode_restriction(dpmh, int, const char*)
-{
-    return 0;
-}
-int dpm_application_unset_mode_restriction(dpmh, int, const char*)
-{
-    return 0;
-}
-int dpm_firewall_apply_deny_rules(dpmh handle, const char* rules)
-{
-    return 0;
-}
-int dpm_firewall_flush_deny_rules(dpmh handle)
-{
-    return 0;
-}
 #endif
 
-#ifndef DPM_BUILD_TV
+#if !defined(DPM_BUILD_TV) && !defined(__BUILD_UBUNTU__) && !defined(__MOCK_THIRDPARTY__)
 int dpm_restriction_set_usb_client_state(dpmh handle, int allow)
 {
     return 0;
@@ -402,7 +246,11 @@ dpm_api::error_code Mapper::apply(const std::string& name, const int param, cons
     uid_t owner;
 
     try {
+#ifndef __BUILD_UBUNTU__
         owner = getUidByName("owner");
+#else
+        owner = root;
+#endif
     } catch (std::runtime_error& e) {
         LOG_E(TAG, "getUidByName(): %s", e.what());
         return NO_DATA;
index cf69902..384d67b 100644 (file)
@@ -27,7 +27,7 @@ const std::string HubResource::HUB_RESORCE_TYPE{"device.hub"};
 
 HubResource::HubResource(
     IoTivity* iotivity,
-    std::shared_ptr<ProxyThread> proxy_thread,
+    ProxyThread* proxy_thread,
     const std::string& _devices_file_path_name
 )
     : NetworkManager::IotResourceServer(HUB_RESOURCE_URI, HUB_RESORCE_TYPE)
index 466f454..b21c838 100644 (file)
@@ -33,7 +33,7 @@ public:
      */
     HubResource(
         NetworkManager::IoTivity* iotivity,
-        std::shared_ptr<ProxyThread> proxy_thread,
+        ProxyThread* proxy_thread,
         const std::string& devices_file_path_name
     );
 
@@ -81,6 +81,18 @@ public:
         return m_enabled;
     }
 
+    /**
+     * @brief Performs device pairing
+     * @param id [in] device uuid
+     */
+    void ownDevice(const std::string& id);
+
+    /**
+     * @brief Performs device unpairing
+     * @param id [in] device uuid
+     */
+    void unownDevice(const std::string& id);
+
     OCEntityHandlerResult getHandler(const OC::OCRepresentation& representation, const OC::QueryParamsMap& params,
                                      OC::OCRepresentation& response_body) override;
 
@@ -100,18 +112,6 @@ private:
     void findUnOwnedDevices();
 
     /**
-     * @brief Performs device pairing
-     * @param id [in] device uuid
-     */
-    void ownDevice(const std::string& id);
-
-    /**
-     * @brief Performs device unpairing
-     * @param id [in] device uuid
-     */
-    void unownDevice(const std::string& id);
-
-    /**
      * @brief Store information about owned devices to cache file
      */
     void saveOwnedDevicesInfo();
@@ -133,7 +133,7 @@ private:
 
     std::string m_devices_file_path_name;
     NetworkManager::IoTivity* m_iotivity;
-    std::shared_ptr<ProxyThread> m_proxy_thread;
+    ProxyThread* m_proxy_thread;
     NetworkManager::IoTDevicesMap m_owned_devices;
     NetworkManager::IoTDevicesMap m_unowned_devices;
     std::mutex m_mutex;
index 1f26436..ff7808a 100644 (file)
@@ -161,6 +161,7 @@ void kill_handler(int _sig)
 {
     write_log(TAG "should stopped\n");
     g_running = false;
+    threads_done();
 }
 
 bool threads_init(void)
index e94e0b6..ff3fe45 100644 (file)
@@ -121,11 +121,11 @@ void MainThread::routine()
         }
 
         if (with_cloud) {
-            report_handler = ReportHandlerFactory::createWithMQ();
-            policy_handler = PolicyHandlerFactory::createWithMQ();
+            report_handler = ReportHandlerFactory::createWithMQ(iotivity);
+            policy_handler = PolicyHandlerFactory::createWithMQ(iotivity);
         } else {
-            report_handler = ReportHandlerFactory::createWithResource(config.ssid);
-            policy_handler = PolicyHandlerFactory::createWithResource(config.ssid);
+            report_handler = ReportHandlerFactory::createWithResource(iotivity, config.ssid);
+            policy_handler = PolicyHandlerFactory::createWithResource(iotivity, config.ssid);
         }
 
         while (!policy_handler->init()) {
@@ -137,7 +137,7 @@ void MainThread::routine()
         proxy_thread->start();
 
         if (g_working_mode == WorkingMode::Hub) {
-            hub = std::make_shared<HubResource>(iotivity, proxy_thread, hub_file_path_name);
+            hub = std::make_shared<HubResource>(iotivity, proxy_thread.get(), hub_file_path_name);
 
             rhandles.push_back(hub->getHandle());
 
index 50f66bd..44e49b1 100644 (file)
 using namespace OC;
 using namespace NMD;
 
+PolicyHandler::PolicyHandler(NetworkManager::IoTivity* iotivity): iotivity(iotivity), disabled(false)
+{
+}
+
 void PolicyHandler::enforceCallback(const std::string& agentId, const std::string& jsonData)
 {
     LOG_D(TAG, "Enfore request from agent: %s\n%s", agentId.c_str(), jsonData.c_str());
     OCRepresentation rep;
     rep.setValue("policy", jsonData);
-    const std::string& device_id = NetworkManager::IoTivity::getInstance()->getDeviceID();
+    const std::string& device_id = iotivity->getDeviceID();
     QueryParamsMap query{{"did", device_id}, {"agent", agentId}};
     pass(rep, query);
 }
@@ -29,7 +33,7 @@ void PolicyHandler::observeCallback(const HeaderOptions& head_options, const OCR
         std::string did = rep.getValue<std::string>("duid");
         std::string parentUuid = rep.getValue<std::string>("parentUuid");
         LOG_D(TAG, "[Recieved Policy for %s]: %s", did.c_str(), policy.c_str());
-        const std::string& device_id = NetworkManager::IoTivity::getInstance()->getDeviceID();
+        const std::string& device_id = iotivity->getDeviceID();
 
         if (did == device_id) {
             LOG_D(TAG, "Policy for this device");
index 3a3027a..a130c6d 100644 (file)
@@ -2,7 +2,7 @@
 #define POLICYHANDLER_H
 
 #include <functional>
-#include <OCApi.h>
+#include "iotivity.h"
 
 class PolicyHandler
 {
@@ -13,6 +13,8 @@ public:
     typedef std::function<void(const OC::HeaderOptions&, const OC::OCRepresentation&, const int&, const int&)>
     ObserverCallback;
 
+    PolicyHandler(NetworkManager::IoTivity* iotivity);
+
     /**
      * @brief setObserver set proxy observe callback
      * @param handler
@@ -25,7 +27,6 @@ public:
      * @brief clearObserver delete proxy observe callback
      */
     void clearObserver() {
-//        callback = ObserverCallback{};
     }
 
     /**
@@ -68,9 +69,9 @@ public:
     virtual ~PolicyHandler() {};
 
 protected:
-
+    NetworkManager::IoTivity* iotivity;
     ObserverCallback callback;
-    bool disabled = false;
+    bool disabled;
 };
 
 #endif // POLICYHANDLER_H
index 1fda599..0db7536 100644 (file)
@@ -2,12 +2,12 @@
 #include "policyhandlerres.h"
 #include "policyhandlermq.h"
 
-std::shared_ptr<PolicyHandler> PolicyHandlerFactory::createWithResource(const std::string& sid)
+std::shared_ptr<PolicyHandler> PolicyHandlerFactory::createWithResource(NetworkManager::IoTivity* iotivity, const std::string& sid)
 {
-    return std::make_shared<PolicyHandlerRes>(sid);
+    return std::make_shared<PolicyHandlerRes>(iotivity, sid);
 }
 
-std::shared_ptr<PolicyHandler> PolicyHandlerFactory::createWithMQ()
+std::shared_ptr<PolicyHandler> PolicyHandlerFactory::createWithMQ(NetworkManager::IoTivity* iotivity)
 {
-    return std::make_shared<PolicyHandlerMQ>();
+    return std::make_shared<PolicyHandlerMQ>(iotivity);
 }
index 60cbacc..50025e2 100644 (file)
@@ -11,13 +11,13 @@ public:
      * @param sid [in] optional server id (with id used for primitive devices)
      * @return handler shared pointer
      */
-    static std::shared_ptr<PolicyHandler> createWithResource(const std::string& sid = "");
+    static std::shared_ptr<PolicyHandler> createWithResource(NetworkManager::IoTivity* iotivity, const std::string& sid = "");
 
     /**
      * @brief createWithMQ creates PolicyHandler using Message Queue layer for communication
      * @return handler shared pointer
      */
-    static std::shared_ptr<PolicyHandler> createWithMQ();
+    static std::shared_ptr<PolicyHandler> createWithMQ(NetworkManager::IoTivity* iotivity);
 };
 
 #endif // POLICYHANDLERFACTORY_H
index f96bc37..3746250 100644 (file)
@@ -8,7 +8,8 @@
 namespace PH = std::placeholders;
 const std::string PolicyHandlerMQ::POLICY_TOPIC{"/srv/policy"};
 
-PolicyHandlerMQ::PolicyHandlerMQ()
+PolicyHandlerMQ::PolicyHandlerMQ(NetworkManager::IoTivity* iotivity):
+    PolicyHandler(iotivity)
 {
 
 }
@@ -38,12 +39,11 @@ void PolicyHandlerMQ::pass(const OC::OCRepresentation& rep, const OC::QueryParam
         msg.setValue("agent", it->second);
     }
 
-    NetworkManager::IoTivity::getInstance()->getMqHandler()->publish(POLICY_TOPIC, rep);
+    iotivity->getMqHandler()->publish(POLICY_TOPIC, rep);
 }
 
 bool PolicyHandlerMQ::init()
 {
-    auto iotivity = NetworkManager::IoTivity::getInstance();
     auto handler = iotivity->getMqHandler();
     std::string topic = "/" + iotivity->getCloudAuthId() + "/policy";
     handler->subscribe(topic, std::bind(&PolicyHandler::observeCallback, this, PH::_1, PH::_2, PH::_3, PH::_4));
index 6dcb0e6..152ce18 100644 (file)
@@ -8,7 +8,7 @@ class PolicyHandlerMQ : public PolicyHandler
 public:
     static const std::string POLICY_TOPIC;
 
-    PolicyHandlerMQ();
+    PolicyHandlerMQ(NetworkManager::IoTivity* iotivity);
 
     /**
      * @brief pass sends policy to security server
index a5f4091..067cafc 100644 (file)
@@ -14,8 +14,8 @@ using namespace OC;
 using namespace NetworkManager;
 namespace PH = std::placeholders;
 
-PolicyHandlerRes::PolicyHandlerRes(const std::string& server_id)
-    : sid(server_id)
+PolicyHandlerRes::PolicyHandlerRes(NetworkManager::IoTivity* iotivity, const std::string& server_id)
+    : PolicyHandler(iotivity), sid(server_id)
 {
 }
 
index 0cf9341..618e257 100644 (file)
@@ -11,7 +11,7 @@ public:
      * @brief PolicyHandler constructor
      * @param iotivity [in] pointer to iotivity instance
      */
-    PolicyHandlerRes(const std::string& server_id = "");
+    PolicyHandlerRes(NetworkManager::IoTivity* iotivity, const std::string& server_id = "");
 
     /**
      * @brief pass sends policy to security server
index 2514c7e..1fa14cf 100644 (file)
@@ -16,8 +16,13 @@ public:
 
     template<typename Func, typename... Args>
     void addDefferedTask(Func&& func, Args&& ... args) {
+        addTask(std::async(std::launch::deferred, std::forward<Func>(func), std::forward<Args>(args)...));
+    }
+
+    void addTask(std::future<void>&& task)
+    {
         std::unique_lock<std::mutex> lock{mtx};
-        deferred.push(std::async(std::launch::deferred, std::forward<Func>(func), std::forward<Args>(args)...));
+        deferred.push(std::move(task));
         notice.notify_one();
     }
 
@@ -56,7 +61,7 @@ public:
         }
     }
 
-private:
+protected:
     std::queue<std::future<void>> deferred;
     std::mutex mtx;
     std::condition_variable notice;
index cff8312..5e2eb7a 100644 (file)
@@ -12,9 +12,9 @@ namespace
 const std::string REPORT_RESOURCE_TYPE{"core.security"};
 }
 
-ReportHandlerRes::ReportHandlerRes(const std::string& server_id) : server_id(server_id)
+ReportHandlerRes::ReportHandlerRes(NetworkManager::IoTivity* iotivity, const std::string& server_id)
+    : iotivity(iotivity), server_id(server_id)
 {
-    iotivity = NetworkManager::IoTivity::getInstance();
 }
 
 void ReportHandlerRes::pass(const OC::OCRepresentation& rep, const OC::QueryParamsMap& params)
index aad5938..ae0ea3e 100644 (file)
@@ -12,7 +12,7 @@ public:
      * @brief ReportHandlerRes constructor
      * @param iotivity pointer to IoTivity instance
      */
-    ReportHandlerRes(const std::string& server_id = "");
+    ReportHandlerRes(NetworkManager::IoTivity* iotivity, const std::string& server_id = "");
 
     void pass(const OC::OCRepresentation& rep, const OC::QueryParamsMap& params) override;
 
index 87796bc..ae6752b 100644 (file)
@@ -3,12 +3,12 @@
 #include "reporthandlermq.h"
 #include "reporthandlerfactory.h"
 
-std::shared_ptr<ReportHandler> ReportHandlerFactory::createWithResource(const std::string& sid)
+std::shared_ptr<ReportHandler> ReportHandlerFactory::createWithResource(NetworkManager::IoTivity* iotivity, const std::string& sid)
 {
-    return std::make_shared<ReportHandlerRes>(sid);
+    return std::make_shared<ReportHandlerRes>(iotivity, sid);
 }
 
-std::shared_ptr<ReportHandler> ReportHandlerFactory::createWithMQ()
+std::shared_ptr<ReportHandler> ReportHandlerFactory::createWithMQ(NetworkManager::IoTivity* iotivity)
 {
-    return std::make_shared<ReportHandlerMQ>();
+    return std::make_shared<ReportHandlerMQ>(iotivity);
 }
index ff4fad8..2cf99b7 100644 (file)
@@ -3,6 +3,7 @@
 
 #include <memory>
 
+#include "iotivity.h"
 #include "reporthandler.h"
 
 class ReportHandlerFactory
@@ -13,13 +14,14 @@ public:
      * @param sid [in] optional server id (with id used for primitive devices)
      * @return handler shared pointer
      */
-    static std::shared_ptr<ReportHandler> createWithResource(const std::string& sid = "");
+    static std::shared_ptr<ReportHandler> createWithResource(NetworkManager::IoTivity* iotivity, const std::string& sid = "");
 
     /**
      * @brief createWithMQ creates ReportHandler using Message Queue layer for communication
+     * @param iotivity [in] pointer to the IoTivity instance
      * @return handler shared pointer
      */
-    static std::shared_ptr<ReportHandler> createWithMQ();
+    static std::shared_ptr<ReportHandler> createWithMQ(NetworkManager::IoTivity* iotivity);
 };
 
 #endif // __REPORT_HANDLER_FACTORY_H__
index c8b2c70..b2e8519 100644 (file)
@@ -8,11 +8,16 @@ namespace
 const std::string POST_REPORT_MQ{"/srv/report"};
 }
 
+ReportHandlerMQ::ReportHandlerMQ(NetworkManager::IoTivity* iotivity)
+    : iotivity(iotivity)
+{
+}
+
 void ReportHandlerMQ::pass(const OC::OCRepresentation& rep, const OC::QueryParamsMap& /*params*/)
 {
     if (disabled) {
         return;
     }
 
-    NetworkManager::IoTivity::getInstance()->getMqHandler()->publish(POST_REPORT_MQ, rep);
+    iotivity->getMqHandler()->publish(POST_REPORT_MQ, rep);
 }
index 2b0ac96..93f490f 100644 (file)
@@ -8,6 +8,7 @@
 class ReportHandlerMQ: public ReportHandler
 {
 public:
+    ReportHandlerMQ(NetworkManager::IoTivity* iotivity);
     void pass(const OC::OCRepresentation& rep, const OC::QueryParamsMap& params) override;
 
 private:
index f76d3d5..dc11a67 100644 (file)
@@ -42,7 +42,7 @@ BuildRequires: python-xml
 %define _conf_file nmlib.conf
 
 %if ("%{GTEST_TYPE}" == "mock")
-%define _gtest_lib gmock
+%define _gtest_lib gmock_main
 %else
 %define _gtest_lib gtest
 %endif
index c839ceb..43aaba4 100644 (file)
@@ -76,7 +76,7 @@ function getBuildConfigs {
                0) PROFILE_NAME=tm2_tizen4 ; TARGET_ARCH=aarch64 ; GTEST_TYPE="main" ; KNOWN_DEVICES=() ; DPM_TYPE="MOBILE" ;;
                1) PROFILE_NAME=tm1_tizen4 ; TARGET_ARCH=armv7l ; GTEST_TYPE="main" ; KNOWN_DEVICES=( ${RASPBERRY_PI_S[@]} ) ; DPM_TYPE="MOBILE" ;;
                2) PROFILE_NAME=kantm_tizen3 ; TARGET_ARCH=armv7l ; GTEST_TYPE="mock" ; KNOWN_DEVICES=( ${KANTM_TV_S[@]} ) ; DPM_TYPE="TV" ;;
-               3) PROFILE_NAME=kantm_tizen4 ; TARGET_ARCH=armv7l ; GTEST_TYPE="main" ; KNOWN_DEVICES=( ${KANTM_TV_S[@]} ) ; DPM_TYPE="TV" ;;
+               3) PROFILE_NAME=kantm_tizen4 ; TARGET_ARCH=armv7l ; GTEST_TYPE="mock" ; KNOWN_DEVICES=( ${KANTM_TV_S[@]} ) ; DPM_TYPE="TV" ;;
                *) echo -e "${RED}error: unknown DEVICE number${NC}"; exit 1 ;;
        esac
        PROFILE=profile.${PROFILE_NAME}
index d33109e..9dc282a 100644 (file)
@@ -2,6 +2,9 @@ get_filename_component(ProjectId ${CMAKE_CURRENT_SOURCE_DIR} NAME)
 string(REPLACE " " "_" ProjectId ${ProjectId})
 project(${ProjectId})
 
+add_definitions(-D__MOCK_THIRDPARTY__)
+SET (CMAKE_BUILD_TYPE TEST)
+
 include_directories (
        ../ctrl_app_lib/inc
        ../iotivity_lib/inc
@@ -10,30 +13,26 @@ include_directories (
        ../agent_lib/rmi/inc
 
        ../nmdaemon
+       ../nmdaemon/dpm
+
+       ../.
 )
 
+include_directories(BEFORE ../mock)
+
 FILE(GLOB SRCS *.cpp
-       ../nmdaemon/agentpolicyservice.cpp
-       ../nmdaemon/device_list.cpp
-       ../nmdaemon/utils.cpp
-       ../nmdaemon/dpm/dpm_api_mapper.cpp
-       ../nmdaemon/control_resource.cpp
-       ../nmdaemon/report_stub.cpp
-       ../nmdaemon/hub_resource.cpp
-       ../nmdaemon/registration_mq.cpp
-       ../nmdaemon/thread_base.cpp
-       ../nmdaemon/commandhandler.cpp
-       ../nmdaemon/application_service.cpp
-        ../nmdaemon/report_service.cpp
+       ../nmdaemon/*.cpp
+       ../nmdaemon/dpm/*.cpp
+       ../iotivity_lib/src/*.cpp
+       ../ctrl_app_lib/src/*.cpp
+       ../mock/*.cpp
        )
 
-add_executable (${PROJECT_NAME} ${SRCS})
+FILE(GLOB NMDAEMON_MAIN ../nmdaemon/main.cpp)
 
-if ("${FLAVOR}" STREQUAL "UBUNTU")
-       set (DPM_LIB "")
-else()
-       set (DPM_LIB dpm)
-endif()
+list(REMOVE_ITEM SRCS ${NMDAEMON_MAIN})
+
+add_executable (${PROJECT_NAME} ${SRCS})
 
 if ("${FLAVOR}" STREQUAL "UBUNTU")
        set (LINK_DLOG "")
@@ -47,8 +46,6 @@ set (TEST_LINK_LIBRARIES ${GTEST_LIB}
        ${AGENT_LIB_PROJECT_NAME}
        jsoncpp
        boost_system boost_thread boost_serialization
-       ${DPM_LIB}
-       ${CTRL_APP_LIB_PROJECT_NAME}
        ${LINK_DLOG}
        curl
 )
index 8deece8..9d49584 100644 (file)
@@ -53,34 +53,3 @@ public:
 };
 
 }
-
-int child_process_routine()
-{
-    IoTivity* iotivity;
-    const std::string saved_devices_path{"/tmp/temp_devices_cache_78234.dat"};
-
-    try {
-        iotivity = IoTivity::getInstance();
-        std::ofstream file{saved_devices_path};
-        boost::archive::text_oarchive archive{file};
-        int cnt = sizeof(test_devices) / sizeof(TestDeviceInfo);
-        archive << cnt;
-
-        for (const auto& i : test_devices) {
-            archive << i.uuid << i.name << i.model << i.type;
-        }
-
-        HubResource hub_resource(iotivity, std::shared_ptr<ProxyThread> {}, saved_devices_path);
-
-        HandlerMock hm;
-
-        ControlResource res(&hm);
-    } catch (std::exception& e) {
-        std::cout << "Exception: " << e.what() << std::endl;
-        return -1;
-    }
-
-    std::this_thread::sleep_for(std::chrono::seconds(300));
-
-    return 0;
-}
index 9acec1a..31da000 100644 (file)
@@ -20,6 +20,7 @@
 #include <gtest/gtest.h>
 
 #include "iotivity.h"
+#include "nmexceptions.h"
 
 #include "easysetup_server.h"
 #include "iot_resource.h"
@@ -41,7 +42,7 @@ class Test_IoT_Fixture: public ::testing::Test
 {
 public:
     void SetUp() override {
-        IoTivity::cleanUp();
+        IoTivity::getInstance()->signOut();
         ASSERT_EQ(EC_OK, NM_init(&ctx));
         sleep(1);
 
diff --git a/device_core/utest/test_agentpolicyservice.cpp b/device_core/utest/test_agentpolicyservice.cpp
new file mode 100644 (file)
index 0000000..790d0d2
--- /dev/null
@@ -0,0 +1,71 @@
+#include <gtest/gtest.h>
+#include <gmock/gmock.h>
+#include "agentpolicyservice.h"
+#include <future>
+
+using namespace NMD;
+using ::testing::Return;
+using ::testing::StrEq;
+
+/**
+ * @brief The Mocking class used as EnforcePolicyHandler mock
+ */
+class EnforcePolicyHandlerMock
+{
+public:
+    MOCK_METHOD2(Call, void(const std::string& agentId, const std::string& jsonData));
+};
+
+/**
+ * Test enforcePolicy and getServicePid methods of AgentPolicyService class
+ * 1. Create mocks and initialize call expectations
+ * 2. Create AgentPolicyService object
+ * 3. Call enforcePolicy method
+ * 4. Call getServicePid method
+ */
+TEST(Test_AgentPolicyService, test_enforce)
+{
+    EnforcePolicyHandlerMock handler;
+    try {
+        auto handlerFunc = [&handler](const std::string& agentId, const std::string& jsonData) {
+            handler.Call(agentId, jsonData);
+        };
+        EXPECT_CALL(handler, Call(StrEq("123"), StrEq("[]")));
+
+        AgentPolicyService service(handlerFunc);
+        EXPECT_EQ(0, service.enforcePolicy("123", "[]"));
+        EXPECT_GT(service.getServicePid(), 0);
+    } catch (std::exception& e) {
+        FAIL() << "Exception: " << e.what();
+    }
+}
+
+/**
+ * Test enforcePolicy method of AgentPolicyService class doesn't throws if handler not set
+ * 1. Create AgentPolicyService object
+ * 3. Call enforcePolicy method
+ */
+TEST(Test_AgentPolicyService, test_enforce_with_empty_handler)
+{
+    try {
+        AgentPolicyService service;
+        EXPECT_EQ(0, service.enforcePolicy("123", "[]"));
+    } catch (std::exception& e) {
+        FAIL() << "Exception: " << e.what();
+    }
+}
+
+/**
+ * Test for stop method of AgentPolicyService class
+ * 1. Create AgentPolicyService object
+ * 3. Call "stop" method
+ */
+TEST(Test_AgentPolicyService, test_stop)
+{
+    try {
+        AgentPolicyService service;
+        service.stop();
+    } catch (std::exception& e) {
+        FAIL() << "Exception: " << e.what();
+    }
+}
index 9acdce6..a49c3ae 100644 (file)
@@ -2,22 +2,48 @@
 #include <string>
 #include <gtest/gtest.h>
 #include <gmock/gmock.h>
-#include <unistd.h>
-#include <thread>
-#include <chrono>
+#include <stdexcept>
 #include "iotivity.h"
+#include "securitycontext.h"
+#include "ctrl_app_support.h"
 
 std::string cloud_host{"coap+tcp://106.125.46.139:5683"};
+std::string TEST_DSM_SERVER_URL = "http://106.125.46.139:8080/dsm/restapi/";
 std::string TEST_ACCOUNT_LOGIN{"admin@samsung.com"};
 std::string TEST_ACCOUNT_PASSWORD{"111111"};
 
+namespace
+{
+
+static std::string getNextArg(int &pos, int argc, char** argv)
+{
+    if (++pos >= argc) {
+        throw std::logic_error("Wrong arguments number");
+    }
+
+    return argv[pos];
+}
+
+}
+
 int main(int argc, char** argv)
 {
     NetworkManager::IoTivity::setPersistentStoragePath("/tmp/temporary_persitent_storage.dat");
+    setCloudHost("coap+tcp://106.125.46.139", 5683);
+    setDSMURI(TEST_DSM_SERVER_URL);
 
     try {
-        if (argc > 1 && argv[1][0] != '-') {
-            cloud_host = std::string{"coap+tcp://"} + argv[1] + std::string{":5683"};
+        for (int i = 0; i < argc; i++) {
+            if (argv[i] == std::string{"-a"}) {
+                std::string addr = getNextArg(i, argc, argv);
+                setCloudHost(addr, 5683);
+                cloud_host = getCloudHost();
+
+                TEST_DSM_SERVER_URL = std::string{"http://"} + addr + std::string{":8080/dsm/restapi/"};
+                setDSMURI(TEST_DSM_SERVER_URL);
+
+                setINIFilePath("");
+            }
         }
         ::testing::InitGoogleTest(&argc, argv);
         return RUN_ALL_TESTS();
diff --git a/device_core/utest/test_application_service.cpp b/device_core/utest/test_application_service.cpp
new file mode 100644 (file)
index 0000000..c611f28
--- /dev/null
@@ -0,0 +1,45 @@
+#include <gtest/gtest.h>
+#include "device-policy-manager-mock.h"
+#include "application_service.h"
+
+using ::testing::Return;
+using ::testing::StrEq;
+
+namespace
+{
+
+const std::string PACKAGE_NAME{"test-package"};
+const std::string KNOWN_PROCESS_NAME{"utest"};
+const std::string UNKNOWN_PROCESS_NAME{"unknown-process-bla-bla"};
+const int DPM_RET_VALUE = 55;
+
+}
+
+TEST(test_ApplicationService, test_install)
+{
+    DPMMock dpm;
+    dpm_set_custom_implementation(&dpm);
+
+    EXPECT_CALL(dpm, dpm_manager_create())
+            .WillOnce(Return(nullptr))
+            .WillOnce(Return(&dpm));
+
+    EXPECT_CALL(dpm, dpm_application_install_package(StrEq(PACKAGE_NAME.c_str()))).WillOnce(Return(55));
+
+    EXPECT_CALL(dpm, dpm_manager_destroy()).Times(1);
+
+    EXPECT_EQ(-1, NMD::ApplicationService::install(PACKAGE_NAME));
+    EXPECT_EQ(DPM_RET_VALUE, NMD::ApplicationService::install(PACKAGE_NAME));
+}
+
+TEST(test_ApplicationService, test_get_process_id_by_name)
+{
+    EXPECT_GE(NMD::ApplicationService::get_process_id_by_name(KNOWN_PROCESS_NAME), 0);
+    EXPECT_EQ(-1, NMD::ApplicationService::get_process_id_by_name(UNKNOWN_PROCESS_NAME));
+}
+
+TEST(test_ApplicationService, test_find_package_by_app_name)
+{
+    std::string empty;
+    EXPECT_EQ(empty, NMD::ApplicationService::find_package_by_app_name(KNOWN_PROCESS_NAME));
+}
diff --git a/device_core/utest/test_audit_trail_client.cpp b/device_core/utest/test_audit_trail_client.cpp
new file mode 100644 (file)
index 0000000..9627c9c
--- /dev/null
@@ -0,0 +1,197 @@
+#include "audit_trail_client.h"
+#include "audit-trail-mock.h"
+
+using namespace NMD;
+using ::testing::Return;
+using ::testing::_;
+using ::testing::DoAll;
+using ::testing::SaveArg;
+using ::testing::SetArgPointee;
+using ::testing::Invoke;
+using ::testing::InvokeArgument;
+using ::testing::Eq;
+using ::testing::WithArgs;
+
+typedef void (*LogCallback)(const char* log, void* user_data);
+
+namespace
+{
+const std::string DEVICE_ID{"this-device-id"};
+const std::string REPORT{"report log"};
+}
+
+/**
+ * @brief The Mock class used for ReportHandler class mocking
+ */
+class ReportHandlerMock: public ReportHandler
+{
+public:
+    MOCK_METHOD2(pass, void(const OC::OCRepresentation& rep, const OC::QueryParamsMap& params));
+};
+
+/**
+ * @brief Adapter used to invoke callback with predefined report log
+ * @param cb [in] callback to invoke
+ * @param user_data [in] user specific data supplied to callback
+ */
+void InvokeCallbackWithReportAdapter(LogCallback cb, void* user_data)
+{
+    cb(REPORT.c_str(), user_data);
+}
+
+/**
+ * @brief TEST for DAC auditing usecase
+ * 1. Create objects and mocks
+ * 2. Run start DAC auditing
+ * 3. Simulate callback invocation
+ * 4. Stop DAC auditing
+ * 5. Check expectations
+ */
+TEST(Test_AuditTrailClient, dac_auditing)
+{
+    auto proxy_thread = std::make_shared<ProxyThread>();
+    ReportHandlerMock report_handler;
+    AuditTrailMock atrail;
+    audit_trail_set_implementation(&atrail);
+    const int DAC_CB_ID = 1;
+    OC::QueryParamsMap qp;
+
+    {
+        ::testing::InSequence dummy;
+        EXPECT_CALL(atrail, audit_trail_create(_)).WillOnce(Return(AUDIT_TRAIL_ERROR_NONE));
+        EXPECT_CALL(atrail, audit_trail_enable_dac(true)).WillOnce(Return(AUDIT_TRAIL_ERROR_NONE));
+        EXPECT_CALL(atrail, audit_trail_add_dac_cb(_, _, _))
+                .WillOnce(DoAll(
+                              SetArgPointee<2>(DAC_CB_ID),
+                              WithArgs<0,1>(Invoke(InvokeCallbackWithReportAdapter)),
+                              Return(AUDIT_TRAIL_ERROR_NONE)));
+        EXPECT_CALL(atrail, audit_trail_remove_dac_cb(Eq(DAC_CB_ID))).WillOnce(Return(AUDIT_TRAIL_ERROR_NONE));
+        EXPECT_CALL(atrail, audit_trail_destroy()).WillOnce(Return(AUDIT_TRAIL_ERROR_NONE));
+    }
+
+    EXPECT_CALL(report_handler, pass(_, Eq(qp))).Times(1);
+
+    AuditTrailClient aclient(
+            DEVICE_ID,
+            proxy_thread,
+            std::shared_ptr<ReportHandler>(&report_handler, [](ReportHandler*){}),
+            WorkingMode::Standard);
+
+    proxy_thread->start();
+    EXPECT_TRUE(aclient.start_dac_auditing());
+    EXPECT_NO_THROW(aclient.stop_dac_auditing());
+    proxy_thread->stop();
+    proxy_thread->join();
+}
+
+/**
+ * @brief TEST for MAC auditing usecase
+ * 1. Create objects and mocks
+ * 2. Run start MAC auditing
+ * 3. Simulate callback invocation
+ * 4. Stop MAC auditing
+ * 5. Check expectations
+ */
+TEST(Test_AuditTrailClient, mac_auditing)
+{
+    auto proxy_thread = std::make_shared<ProxyThread>();
+    ReportHandlerMock report_handler;
+    AuditTrailMock atrail;
+    audit_trail_set_implementation(&atrail);
+    const int MAC_CB_ID = 2;
+    OC::QueryParamsMap qp;
+
+    {
+        ::testing::InSequence dummy;
+        EXPECT_CALL(atrail, audit_trail_create(_)).WillOnce(Return(AUDIT_TRAIL_ERROR_NONE));
+        EXPECT_CALL(atrail, audit_trail_enable_mac(true)).WillOnce(Return(AUDIT_TRAIL_ERROR_NONE));
+        EXPECT_CALL(atrail, audit_trail_add_mac_cb(_, _, _))
+                .WillOnce(DoAll(
+                              SetArgPointee<2>(MAC_CB_ID),
+                              WithArgs<0,1>(Invoke(InvokeCallbackWithReportAdapter)),
+                              Return(AUDIT_TRAIL_ERROR_NONE)));
+        EXPECT_CALL(atrail, audit_trail_remove_mac_cb(Eq(MAC_CB_ID))).WillOnce(Return(AUDIT_TRAIL_ERROR_NONE));
+        EXPECT_CALL(atrail, audit_trail_destroy()).WillOnce(Return(AUDIT_TRAIL_ERROR_NONE));
+    }
+
+    EXPECT_CALL(report_handler, pass(_, Eq(qp))).Times(1);
+
+    AuditTrailClient aclient(
+            DEVICE_ID,
+            proxy_thread,
+            std::shared_ptr<ReportHandler>(&report_handler, [](ReportHandler*){}),
+            WorkingMode::Standard);
+
+    proxy_thread->start();
+    EXPECT_TRUE(aclient.start_mac_auditing());
+    EXPECT_NO_THROW(aclient.stop_mac_auditing());
+    proxy_thread->stop();
+    proxy_thread->join();
+}
+
+/**
+ * @brief TEST for syscall auditing usecase
+ * 1. Create objects and mocks
+ * 2. Run start syscall auditing
+ * 3. Simulate callback invocation
+ * 4. Stop syscall auditing
+ * 5. Check expectations
+ */
+TEST(Test_AuditTrailClient, syscall_auditing)
+{
+    auto proxy_thread = std::make_shared<ProxyThread>();
+    ReportHandlerMock report_handler;
+    AuditTrailMock atrail;
+    audit_trail_set_implementation(&atrail);
+    const int SYSCALL_CB_ID = 3;
+    OC::QueryParamsMap qp;
+
+    {
+        ::testing::InSequence dummy;
+        EXPECT_CALL(atrail, audit_trail_create(_)).WillOnce(Return(AUDIT_TRAIL_ERROR_NONE));
+        EXPECT_CALL(atrail, audit_trail_enable_syscall(true)).WillOnce(Return(AUDIT_TRAIL_ERROR_NONE));
+        EXPECT_CALL(atrail, audit_trail_add_syscall_cb(_, _, _))
+                .WillOnce(DoAll(
+                              SetArgPointee<2>(SYSCALL_CB_ID),
+                              WithArgs<0,1>(Invoke(InvokeCallbackWithReportAdapter)),
+                              Return(AUDIT_TRAIL_ERROR_NONE)));
+        EXPECT_CALL(atrail, audit_trail_remove_syscall_cb(Eq(SYSCALL_CB_ID))).WillOnce(Return(AUDIT_TRAIL_ERROR_NONE));
+        EXPECT_CALL(atrail, audit_trail_destroy()).WillOnce(Return(AUDIT_TRAIL_ERROR_NONE));
+    }
+
+    EXPECT_CALL(report_handler, pass(_, Eq(qp))).Times(1);
+
+    AuditTrailClient aclient(
+            DEVICE_ID,
+            proxy_thread,
+            std::shared_ptr<ReportHandler>(&report_handler, [](ReportHandler*){}),
+            WorkingMode::Standard);
+
+    proxy_thread->start();
+    EXPECT_TRUE(aclient.start_syscall_auditing());
+    EXPECT_NO_THROW(aclient.stop_syscall_auditing());
+    proxy_thread->stop();
+    proxy_thread->join();
+}
+
+/**
+ * @brief TEST for AuditTrailClient when audit_trail_create fails
+ * 1. Create objects and mocks
+ * 2. Create AuditTrailClient
+ * 3. Expect it fails with exception
+ */
+TEST(Test_AuditTrailClient, audit_trail_create_fails)
+{
+    auto proxy_thread = std::make_shared<ProxyThread>();
+    ReportHandlerMock report_handler;
+    AuditTrailMock atrail;
+    audit_trail_set_implementation(&atrail);
+
+    EXPECT_CALL(atrail, audit_trail_create(_)).WillOnce(Return(AUDIT_TRAIL_ERROR_CONNECTION_REFUSED));
+
+    EXPECT_ANY_THROW(AuditTrailClient aclient(
+            DEVICE_ID,
+            proxy_thread,
+            std::shared_ptr<ReportHandler>(&report_handler, [](ReportHandler*){}),
+            WorkingMode::Standard));
+}
diff --git a/device_core/utest/test_audit_trail_stub.cpp b/device_core/utest/test_audit_trail_stub.cpp
new file mode 100644 (file)
index 0000000..99c121a
--- /dev/null
@@ -0,0 +1,62 @@
+#include "audit-trail-stub.h"
+#include "audit-trail-mock.h"
+
+using ::testing::Return;
+
+void testCb(const char* log, void* user_data)
+{
+}
+
+TEST(AuditTrailStub, test_all)
+{
+    AuditTrailMock mock;
+    audit_trail_set_implementation(&mock);
+    int user_data = 3;
+    int id;
+    bool enable;
+
+    audit_trail_h handle;
+    const int RESULT_CODE = 1234;
+
+    EXPECT_CALL(mock, audit_trail_create(&handle)).WillOnce(Return(RESULT_CODE));
+    EXPECT_CALL(mock, audit_trail_destroy()).WillOnce(Return(RESULT_CODE));
+    EXPECT_CALL(mock, audit_trail_foreach_dac(testCb, &user_data)).WillOnce(Return(RESULT_CODE));
+    EXPECT_CALL(mock, audit_trail_clear_dac()).WillOnce(Return(RESULT_CODE));
+    EXPECT_CALL(mock, audit_trail_add_dac_cb(testCb, &user_data, &id)).WillOnce(Return(RESULT_CODE));
+    EXPECT_CALL(mock, audit_trail_remove_dac_cb(id)).WillOnce(Return(RESULT_CODE));
+    EXPECT_CALL(mock, audit_trail_enable_dac(enable)).WillOnce(Return(RESULT_CODE));
+    EXPECT_CALL(mock, audit_trail_is_enabled_dac(&enable)).WillOnce(Return(RESULT_CODE));
+    EXPECT_CALL(mock, audit_trail_foreach_mac(testCb, &user_data)).WillOnce(Return(RESULT_CODE));
+    EXPECT_CALL(mock, audit_trail_clear_mac()).WillOnce(Return(RESULT_CODE));
+    EXPECT_CALL(mock, audit_trail_add_mac_cb(testCb, &user_data, &id)).WillOnce(Return(RESULT_CODE));
+    EXPECT_CALL(mock, audit_trail_remove_mac_cb(id)).WillOnce(Return(RESULT_CODE));
+    EXPECT_CALL(mock, audit_trail_enable_mac(enable)).WillOnce(Return(RESULT_CODE));
+    EXPECT_CALL(mock, audit_trail_is_enabled_mac(&enable)).WillOnce(Return(RESULT_CODE));
+    EXPECT_CALL(mock, audit_trail_foreach_syscall(testCb, &user_data)).WillOnce(Return(RESULT_CODE));
+    EXPECT_CALL(mock, audit_trail_clear_syscall()).WillOnce(Return(RESULT_CODE));
+    EXPECT_CALL(mock, audit_trail_add_syscall_cb(testCb, &user_data, &id)).WillOnce(Return(RESULT_CODE));
+    EXPECT_CALL(mock, audit_trail_remove_syscall_cb(id)).WillOnce(Return(RESULT_CODE));
+    EXPECT_CALL(mock, audit_trail_enable_syscall(enable)).WillOnce(Return(RESULT_CODE));
+    EXPECT_CALL(mock, audit_trail_is_enabled_syscall(&enable)).WillOnce(Return(RESULT_CODE));
+
+    EXPECT_EQ(RESULT_CODE, audit_trail_create(&handle));
+    EXPECT_EQ(RESULT_CODE, audit_trail_destroy(handle));
+    EXPECT_EQ(RESULT_CODE, audit_trail_foreach_dac(handle, testCb, &user_data));
+    EXPECT_EQ(RESULT_CODE, audit_trail_clear_dac(handle));
+    EXPECT_EQ(RESULT_CODE, audit_trail_add_dac_cb(handle, testCb, &user_data, &id));
+    EXPECT_EQ(RESULT_CODE, audit_trail_remove_dac_cb(handle, id));
+    EXPECT_EQ(RESULT_CODE, audit_trail_enable_dac(handle, enable));
+    EXPECT_EQ(RESULT_CODE, audit_trail_is_enabled_dac(handle, &enable));
+    EXPECT_EQ(RESULT_CODE, audit_trail_foreach_mac(handle, testCb, &user_data));
+    EXPECT_EQ(RESULT_CODE, audit_trail_clear_mac(handle));
+    EXPECT_EQ(RESULT_CODE, audit_trail_add_mac_cb(handle, testCb, &user_data, &id));
+    EXPECT_EQ(RESULT_CODE, audit_trail_remove_mac_cb(handle, id));
+    EXPECT_EQ(RESULT_CODE, audit_trail_enable_mac(handle, enable));
+    EXPECT_EQ(RESULT_CODE, audit_trail_is_enabled_mac(handle, &enable));
+    EXPECT_EQ(RESULT_CODE, audit_trail_foreach_syscall(handle, testCb, &user_data));
+    EXPECT_EQ(RESULT_CODE, audit_trail_clear_syscall(handle));
+    EXPECT_EQ(RESULT_CODE, audit_trail_add_syscall_cb(handle, testCb, &user_data, &id));
+    EXPECT_EQ(RESULT_CODE, audit_trail_remove_syscall_cb(handle, id));
+    EXPECT_EQ(RESULT_CODE, audit_trail_enable_syscall(handle, enable));
+    EXPECT_EQ(RESULT_CODE, audit_trail_is_enabled_syscall(handle, &enable));
+}
index 58378e9..b62f8b9 100644 (file)
@@ -8,17 +8,27 @@
 #include "device_commands.h"
 #include "securitycontext.h"
 #include "ctrl_app_support.h"
+#include "iotivity_mock.h"
+#include "mqclient_mock.h"
+#include "device-policy-manager-mock.h"
 
 using namespace NetworkManager;
 using namespace NMD;
+using ::testing::ReturnRef;
 using ::testing::Return;
 using ::testing::StrEq;
+using ::testing::Eq;
 
-extern std::string cloud_host;
-extern std::string TEST_ACCOUNT_LOGIN;
-extern std::string TEST_ACCOUNT_PASSWORD;
+namespace
+{
+const std::string PACKAGE_TO_UNINSTALL{"smack_test"};
+const std::string UNREG_TOPIC{"/srv/unreg"};
+const std::string ACTION_UNREGISTER{"unregister"};
+const std::string DEVICE_ID{"this-device-id"};
+const std::string OTHER_DEVICE_ID{"unknown-device-id"};
+}
 
-class ReportHandlerMock: public ReportHandler
+class ReportHandlerStub: public ReportHandler
 {
 public:
     void pass(const OC::OCRepresentation& rep, const OC::QueryParamsMap& params) override {
@@ -29,30 +39,18 @@ public:
 class PolicyHandlerMock : public PolicyHandler
 {
 public:
-    virtual void pass(const OC::OCRepresentation& rep, const OC::QueryParamsMap& params) {
+    PolicyHandlerMock(): PolicyHandler(nullptr)
+    {
 
     }
 
-    virtual bool init() {
-        return true;
-    }
-};
+    virtual void pass(const OC::OCRepresentation& rep, const OC::QueryParamsMap& params) {
 
-class Test_commandhandler_fixture : public ::testing::Test
-{
-public:
-    void SetUp() {
-        IoTivity::cleanUp();
-        ASSERT_EQ(EC_OK, NM_init(&ctx));
-        ASSERT_EQ(EC_OK, NM_signIn(ctx, TEST_ACCOUNT_LOGIN.c_str(), TEST_ACCOUNT_PASSWORD.c_str()));
     }
 
-    void TearDown() {
-        ASSERT_NO_THROW(NM_signOut(ctx));
-        ASSERT_NO_THROW(NM_cleanup(&ctx));
+    virtual bool init() {
+        return true;
     }
-
-    NM_hContext ctx;
 };
 
 class MainThreadMock : public ThreadBase
@@ -64,126 +62,144 @@ public:
 /**
  * Test CommandHandler class UNOWN command for standard working mode
  */
-TEST_F(Test_commandhandler_fixture, test_unOwnTask_standard)
+TEST(Test_commandhandler, test_unOwnTask_standard)
 {
     MainThreadMock main_thread;
-
-    EXPECT_CALL(main_thread, stop())
-    .Times(1);
+    IoTivityMock iot;
+    MqClientMock mqclient;
+    OC::OCRepresentation unreg_repr;
+    unreg_repr.setValue("duid", DEVICE_ID);
+    unreg_repr.setValue("action", ACTION_UNREGISTER);
+
+    EXPECT_CALL(main_thread, stop()).Times(1);
+    EXPECT_CALL(iot, getDeviceID()).WillRepeatedly(ReturnRef(DEVICE_ID));
+    EXPECT_CALL(iot, getMqHandler()).WillOnce(Return(&mqclient));
+    EXPECT_CALL(iot, deleteFromAccount()).Times(1);
+    EXPECT_CALL(mqclient, publish(StrEq(UNREG_TOPIC), Eq(unreg_repr))).Times(1);
 
     try {
-        IoTivity* iot = ctx->instance;
-        EXPECT_TRUE(iot->isSignedIn());
         std::shared_ptr<ProxyThread> proxy = std::make_shared<ProxyThread>();
         std::shared_ptr<HubResource> hub  = nullptr;
-        std::shared_ptr<ReportHandler> rh = std::make_shared<ReportHandlerMock>();
+        std::shared_ptr<ReportHandler> rh = std::make_shared<ReportHandlerStub>();
         std::shared_ptr<PolicyHandler> ph = std::make_shared<PolicyHandlerMock>();
 
         proxy->start();
 
-        CommandHandler handler(iot, hub, rh, ph, proxy, WorkingMode::Standard, &main_thread);
+        CommandHandler handler(&iot, hub, rh, ph, proxy, WorkingMode::Standard, &main_thread);
 
         OC::OCRepresentation rep;
         rep.setValue("command", int(DeviceCommands::UNOWN));
-        handler.process(rep);
+        EXPECT_TRUE(handler.process(rep));
         proxy->stop();
         proxy->join();
-        sleep(1);
     } catch (std::exception& e) {
         FAIL() << "Exception: " << e.what();
     }
 }
 
-/**
- * Test CommandHandler class UNOWN command for primitive working mode
- */
-TEST_F(Test_commandhandler_fixture, test_unOwnTask_primitive)
+TEST(Test_commandhandler, test_uninstallTask)
 {
-    MainThreadMock main_thread;
+    IoTivityMock iot;
+    DPMMock dpm;
+    dpm_set_custom_implementation(&dpm);
 
-    EXPECT_CALL(main_thread, stop())
-    .Times(1);
+    EXPECT_CALL(iot, getDeviceID()).WillRepeatedly(ReturnRef(DEVICE_ID));
+    EXPECT_CALL(dpm, dpm_manager_create()).WillOnce(Return(&dpm));
+    EXPECT_CALL(dpm, dpm_application_uninstall_package(StrEq(PACKAGE_TO_UNINSTALL.c_str()))).WillOnce(Return(0));
+    EXPECT_CALL(dpm, dpm_manager_destroy()).Times(1);
 
     try {
-        IoTivity* iot = ctx->instance;
-        EXPECT_TRUE(iot->isSignedIn());
         std::shared_ptr<ProxyThread> proxy = std::make_shared<ProxyThread>();
-        std::shared_ptr<HubResource> hub  = nullptr;
-        std::shared_ptr<ReportHandler> rh = std::make_shared<ReportHandlerMock>();
+        std::shared_ptr<HubResource> hub  = std::make_shared<HubResource>(&iot, proxy.get(), std::string{""});
+        std::shared_ptr<ReportHandler> rh = std::make_shared<ReportHandlerStub>();
         std::shared_ptr<PolicyHandler> ph = std::make_shared<PolicyHandlerMock>();
+        ThreadBase mt;
 
-        proxy->start();
-        CommandHandler handler(iot, hub, rh, ph, proxy, WorkingMode::Primitive, &main_thread);
+        CommandHandler handler(&iot, hub, rh, ph, proxy, WorkingMode::Standard, &mt);
 
         OC::OCRepresentation rep;
-        rep.setValue("command", int(DeviceCommands::UNOWN));
-        handler.process(rep);
-        proxy->stop();
-        proxy->join();
+        rep.setValue("command", int(DeviceCommands::UNINSTALL));
+        rep.setValue("duid", DEVICE_ID);
+        rep.setValue("name", PACKAGE_TO_UNINSTALL);
+        EXPECT_TRUE(handler.process(rep));
     } catch (std::exception& e) {
         FAIL() << "Exception: " << e.what();
     }
 }
 
-/**
- * Test CommandHandler class UNOWN command for hub working mode
- */
-TEST_F(Test_commandhandler_fixture, test_unOwnTask_hub)
+TEST(Test_commandhandler, test_uninstall_wrong_params)
 {
-    MainThreadMock main_thread;
+    IoTivityMock iot;
 
-    EXPECT_CALL(main_thread, stop())
-    .Times(1);
+    EXPECT_CALL(iot, getDeviceID()).WillRepeatedly(ReturnRef(DEVICE_ID));
 
     try {
-        IoTivity* iot = ctx->instance;
-        EXPECT_TRUE(iot->isSignedIn());
         std::shared_ptr<ProxyThread> proxy = std::make_shared<ProxyThread>();
-        std::shared_ptr<HubResource> hub  = std::make_shared<HubResource>(iot, proxy, std::string{""});
-        std::shared_ptr<ReportHandler> rh = std::make_shared<ReportHandlerMock>();
+        std::shared_ptr<HubResource> hub  = std::make_shared<HubResource>(&iot, proxy.get(), std::string{""});
+        std::shared_ptr<ReportHandler> rh = std::make_shared<ReportHandlerStub>();
         std::shared_ptr<PolicyHandler> ph = std::make_shared<PolicyHandlerMock>();
+        ThreadBase mt;
 
-        proxy->start();
-
-        CommandHandler handler(iot, hub, rh, ph, proxy, WorkingMode::Hub, &main_thread);
+        CommandHandler handler(&iot, hub, rh, ph, proxy, WorkingMode::Standard, &mt);
 
         OC::OCRepresentation rep;
-        rep.setValue("command", int(DeviceCommands::UNOWN));
-        handler.process(rep);
-        proxy->stop();
-        proxy->join();
+        rep.setValue("command", int(DeviceCommands::UNINSTALL));
+        rep.setValue("duid", DEVICE_ID);
+        EXPECT_FALSE(handler.process(rep));
+
+        rep.setValue("duid", OTHER_DEVICE_ID);
+        rep.setValue("name", PACKAGE_TO_UNINSTALL);
+        EXPECT_FALSE(handler.process(rep));
     } catch (std::exception& e) {
         FAIL() << "Exception: " << e.what();
     }
 }
 
-namespace
+TEST(Test_commandhandler, test_uninstallTask_dpm_failure)
 {
-const std::string test_executable{"smack_test"};
-const std::string test_rpm_query_stub_path{"/tmp/test_rpm_query_stub.txt"};
-const std::string test_executable_package_name = test_executable + ".1.2.3.4.rpm";
-}
+    IoTivityMock iot;
+    DPMMock dpm;
+    dpm_set_custom_implementation(&dpm);
+
+    EXPECT_CALL(iot, getDeviceID()).WillRepeatedly(ReturnRef(DEVICE_ID));
+    EXPECT_CALL(dpm, dpm_manager_create()).WillOnce(Return(nullptr));
 
-TEST(Test_commandhandler, test_uninstallTask)
-{
     try {
-        IoTivity::cleanUp();
-        IoTivity* iot = IoTivity::getInstance();
         std::shared_ptr<ProxyThread> proxy = std::make_shared<ProxyThread>();
-        std::shared_ptr<HubResource> hub  = std::make_shared<HubResource>(iot, proxy, std::string{""});
-        std::shared_ptr<ReportHandler> rh = std::make_shared<ReportHandlerMock>();
+        std::shared_ptr<HubResource> hub  = std::make_shared<HubResource>(&iot, proxy.get(), std::string{""});
+        std::shared_ptr<ReportHandler> rh = std::make_shared<ReportHandlerStub>();
         std::shared_ptr<PolicyHandler> ph = std::make_shared<PolicyHandlerMock>();
         ThreadBase mt;
 
-        CommandHandler handler(iot, hub, rh, ph, proxy, WorkingMode::Standard, &mt);
+        CommandHandler handler(&iot, hub, rh, ph, proxy, WorkingMode::Standard, &mt);
 
         OC::OCRepresentation rep;
         rep.setValue("command", int(DeviceCommands::UNINSTALL));
-        rep.setValue("pid", std::string{"1234"});
-        rep.setValue("name", test_executable);
-        handler.process(rep);
+        rep.setValue("duid", DEVICE_ID);
+        rep.setValue("name", PACKAGE_TO_UNINSTALL);
+        EXPECT_FALSE(handler.process(rep));
     } catch (std::exception& e) {
         FAIL() << "Exception: " << e.what();
     }
 }
 
+
+TEST(Test_commandhandler, test_unsupported_command)
+{
+    try {
+        IoTivityMock iot;
+        std::shared_ptr<ProxyThread> proxy = std::make_shared<ProxyThread>();
+        std::shared_ptr<HubResource> hub  = std::make_shared<HubResource>(&iot, proxy.get(), std::string{""});
+        std::shared_ptr<ReportHandler> rh = std::make_shared<ReportHandlerStub>();
+        std::shared_ptr<PolicyHandler> ph = std::make_shared<PolicyHandlerMock>();
+        ThreadBase mt;
+
+        CommandHandler handler(&iot, hub, rh, ph, proxy, WorkingMode::Standard, &mt);
+
+        OC::OCRepresentation rep;
+        rep.setValue("command", int(DeviceCommands::UNINSTALL) + 100000);
+        EXPECT_FALSE(handler.process(rep));
+    } catch (std::exception& e) {
+        FAIL() << "Exception: " << e.what();
+    }
+}
diff --git a/device_core/utest/test_hubclient.cpp b/device_core/utest/test_hubclient.cpp
new file mode 100644 (file)
index 0000000..1f9ae42
--- /dev/null
@@ -0,0 +1,40 @@
+#include <gtest/gtest.h>
+#include <OCApi.h>
+#include <OCPlatform.h>
+#include "hub_client.h"
+
+using namespace OC;
+using namespace NetworkManager;
+
+namespace
+{
+const std::string RESOURCE_HOST{"coap://192.168.1.2:5000"};
+const std::string RESOURCE_URI{"/resource"};
+const std::string RESOURCE_TYPE{"oic.fake"};
+}
+
+TEST(Test_HubClient, construction)
+{
+    OCResource::Ptr resource = OCPlatform::constructResourceObject(
+                RESOURCE_HOST,
+                RESOURCE_URI,
+                CT_DEFAULT,
+                true,
+                {RESOURCE_TYPE},
+                {DEFAULT_INTERFACE});
+
+    HubClient hub_null(nullptr);
+    EXPECT_TRUE(!hub_null);
+
+    HubClient hub(resource);
+    EXPECT_FALSE(!hub);
+    HubClient hub_copy(hub);
+    EXPECT_FALSE(!hub_copy);
+
+    EXPECT_EQ(RESOURCE_HOST, hub.host());
+    EXPECT_EQ("", hub.getUUID());
+
+    IoTDevicesMap devs;
+    EXPECT_ANY_THROW(hub.getOwnedDevices(devs));
+    EXPECT_ANY_THROW(hub.getUnownedDevices(devs));
+}
index 7ef4997..edb8049 100644 (file)
 #include <OCPlatform.h>
 #include <iostream>
 #include <gmock/gmock.h>
+#include <fstream>
+#include <boost/archive/text_oarchive.hpp>
+#include <unistd.h>
+#include <jsoncpp/json/reader.h>
 #include "hub_resource.h"
 #include "iotivity.h"
+#include "iotivity_mock.h"
+#include "mqclient_mock.h"
+#include "proxythread.h"
+#include "iotdevice_mock.h"
+#include "registration_mq.h"
 
 using namespace NMD;
 using namespace OC;
 using namespace NetworkManager;
+using ::testing::Eq;
+using ::testing::StrEq;
+using ::testing::Return;
+using ::testing::ReturnRef;
 
+namespace
+{
+    const std::string test_hub_devices_file{"/tmp/test_hub_devices_file.dat"};
+
+    struct Device
+    {
+        std::string UUID;
+        std::string Name;
+        std::string Model;
+        std::string Type;
+    };
+
+    const Device devices[] = {
+        {
+            "11111111-1111-1111-1111-111111111111",
+            "device#1",
+            "model#1",
+            "type#1"
+        },
+        {
+            "22222222-2222-2222-2222-222222222222",
+            "device#2",
+            "model#2",
+            "type#2"
+        },
+        {
+            "33333333-3333-3333-3333-333333333333",
+            "device#3",
+            "model#3",
+            "type#3"
+        },
+    };
+
+    /**
+     * @brief Mocking class for ProxyThread
+     */
+    class ProxyThreadMock: public ProxyThread
+    {
+    public:
+        size_t tasksSize()
+        {
+            return deferred.size();
+        }
+    };
+}
+
+/**
+ * @brief GTest fixture
+ */
+class TestHubResource: public ::testing::Test
+{
+public:
+    static void SetUpTestCase()
+    {
+        std::ofstream file{test_hub_devices_file};
+
+        do {
+            boost::archive::text_oarchive oa{file};
+
+            int cnt = sizeof(devices) / sizeof(devices[0]);
+            oa << cnt;
+            for (const auto& i : devices) {
+                oa << i.UUID << i.Name << i.Model << i.Type;
+            }
+        } while (0);
+
+        file.close();
+    }
+
+    static void TearDownTestCase()
+    {
+        ::remove(test_hub_devices_file.c_str());
+    }
+};
+
+
+/**
+ * @brief test for postHandler method of HubResource
+ * 1. post own request with correct parameters
+ * 2. check OK returned and deffered task created
+ * 3. post requests with incorrect parameters and check that OC_EH_BAD_REQ is returned
+ * 4. post unown request with correct parameters
+ * 5. check OK returned and deffered task created
+ */
+TEST_F(TestHubResource, test_postHandler)
+{
+    try {
+
+        IoTivity* iot = IoTivity::getInstance();
+        ProxyThreadMock pt;
+        HubResource hub(iot, &pt, test_hub_devices_file);
+
+        EXPECT_EQ(0, pt.tasksSize());
+
+        OC::QueryParamsMap params1 = {{"uid", devices[0].UUID},{"state", "own"}};
+        OC::OCRepresentation rep;
+        EXPECT_EQ(OC_EH_OK, hub.postHandler(rep, params1, rep));
+        EXPECT_EQ(1, pt.tasksSize());
+
+        OC::QueryParamsMap wrong_state_params1 = {{"uid", "11111111-1111-1111-1111-111111111111"},{"state", "wrong"}};
+        OC::QueryParamsMap wrong_state_params2 = {{"state", "own"}};
+        EXPECT_EQ(OC_EH_BAD_REQ, hub.postHandler(rep, wrong_state_params1, rep));
+        EXPECT_EQ(OC_EH_BAD_REQ, hub.postHandler(rep, wrong_state_params2, rep));
+
+        EXPECT_EQ(1, pt.tasksSize());
+
+        OC::QueryParamsMap params2 = {{"uid", devices[1].UUID},{"state", "unown"}};
+        EXPECT_EQ(OC_EH_OK, hub.postHandler(rep, params2, rep));
+        EXPECT_EQ(2, pt.tasksSize());
+
+    } catch (std::exception& e) {
+        FAIL() << "Exception: " << e.what();
+    }
+}
 
-TEST(test_HubResource, test_all)
+/**
+ * @brief test for isOwned method of HubResource
+ * 1. check return value is true for owned device
+ * 2. check return value is false for unknown device
+ */
+TEST_F(TestHubResource, test_isOwned)
 {
     try {
+
         IoTivity* iot = IoTivity::getInstance();
+        ProxyThreadMock pt;
+        HubResource hub(iot, &pt, test_hub_devices_file);
+
+        EXPECT_TRUE(hub.isOwned(devices[1].UUID));
+        EXPECT_FALSE(hub.isOwned("aaaaaaaa-1111-1111-1111-111111111122"));
+
     } catch (std::exception& e) {
         FAIL() << "Exception: " << e.what();
     }
 }
+
+/**
+ * @brief test for isEnabled and setEnabled methods of HubResource
+ * 1. Create objects
+ * 2. Check enabled by default is true
+ * 3. Disable the Hub and check it's disabled
+ * 4. Enable the Hub and check it's enabled
+ */
+TEST_F(TestHubResource, test_enabled)
+{
+    try {
+
+        IoTivity* iot = IoTivity::getInstance();
+        ProxyThreadMock pt;
+        HubResource hub(iot, &pt, test_hub_devices_file);
+
+        EXPECT_TRUE(hub.isEnabled());
+        hub.setEnabled(false);
+        EXPECT_FALSE(hub.isEnabled());
+        hub.setEnabled(true);
+        EXPECT_TRUE(hub.isEnabled());
+
+    } catch (std::exception& e) {
+        FAIL() << "Exception: " << e.what();
+    }
+}
+
+TEST_F(TestHubResource, test_getHandler)
+{
+    try {
+
+        IoTivity* iot = IoTivity::getInstance();
+        ProxyThreadMock pt;
+        HubResource hub(iot, &pt, test_hub_devices_file);
+
+        EXPECT_EQ(0, pt.tasksSize());
+
+        OC::QueryParamsMap params_owned = {{"intention", "owned"}};
+        OC::QueryParamsMap params_unowned = {{"intention", "unowned"}};
+
+        OC::OCRepresentation rep;
+        EXPECT_EQ(OC_EH_BAD_REQ, hub.getHandler(rep, {}, rep));
+
+        OC::OCRepresentation rep_unowned;
+        EXPECT_EQ(OC_EH_OK, hub.getHandler(rep, params_unowned, rep_unowned));
+
+        EXPECT_EQ("[]", rep_unowned.getValue<std::string>("devices"));
+
+        OC::OCRepresentation rep_owned;
+        EXPECT_EQ(OC_EH_OK, hub.getHandler(rep, params_owned, rep_owned));
+
+        Json::Reader reader;
+        Json::Value root;
+        reader.parse(rep_owned.getValue<std::string>("devices"), root);
+
+        EXPECT_EQ(sizeof(devices)/sizeof(devices[0]), (size_t)root.size());
+
+        for (Json::ArrayIndex i = 0; i < root.size(); i++) {
+            auto dev = root[i];
+            std::string did = dev["did"].asString();
+            std::string name = dev["name"].asString();
+            std::string model = dev["model"].asString();
+            std::string type = dev["type"].asString();
+            EXPECT_NO_THROW(dev["state"].asBool());
+
+            unsigned j = 0;
+            for (; j < (sizeof(devices)/sizeof(devices[0])); j++) {
+                if (did == devices[j].UUID) {
+                    EXPECT_EQ(name, devices[j].Name);
+                    EXPECT_EQ(model, devices[j].Model);
+                    EXPECT_EQ(type, devices[j].Type);
+                    break;
+                }
+            }
+            EXPECT_NE(j, (sizeof(devices)/sizeof(devices[0])));
+        }
+
+    } catch (std::exception& e) {
+        FAIL() << "Exception: " << e.what();
+    }
+}
+
+
+TEST_F(TestHubResource, test_findDevices)
+{
+    const std::string unowned_device_1_id{"first-unknown-device"};
+    const std::string unowned_device_1_name{"first-unknown-name"};
+    const std::string unowned_device_1_model{"first-unknown-model"};
+    const std::string unowned_device_1_type{"first-unknown-type"};
+    const std::string unowned_device_2_id{"second-unknown-device"};
+    const std::string this_device_id{"this-device-id"};
+    const std::string cloud_auth_id{"Cloud auth id"};
+    const std::string reg_topic{"/srv/reg"};
+    const std::string unreg_topic{"/srv/unreg"};
+    const std::string action_unreg{"unregister"};
+    IoTivityMock iotivity;
+    MqClientMock mqclient;
+    ProxyThreadMock pt;
+    IoTDeviceMock unowned_dev_1;
+    IoTDeviceMock unowned_dev_2;
+
+    auto fake_deleter = [](IoTDevice*){};
+
+    std::vector<std::shared_ptr<IoTDevice>>
+    owned_devices{{&unowned_dev_1, fake_deleter}, {&unowned_dev_2, fake_deleter}};
+
+    // IoTivityMock iotivity call expectations
+    EXPECT_CALL(iotivity, findResourceList(false, StrEq("oic.wk.d"), StrEq("/oic/res?rt=oic.wk.d"), CT_DEFAULT))
+            .WillOnce(Return(std::vector<std::shared_ptr<OC::OCResource>>{}));
+    EXPECT_CALL(iotivity, findDevices(false, CT_DEFAULT, StrEq("/oic/res?rt=" OC_RSRVD_ES_RES_TYPE_EASYSETUP)))
+            .WillOnce(Return(owned_devices));
+    EXPECT_CALL(iotivity, getDeviceID())
+            .WillRepeatedly(ReturnRef(this_device_id));
+    EXPECT_CALL(iotivity, getMqHandler()).WillRepeatedly(Return(&mqclient));
+    EXPECT_CALL(iotivity, getCloudAuthId()).WillRepeatedly(ReturnRef(cloud_auth_id));
+
+    // IoTDeviceMock unowned_dev_1 call expectations
+    EXPECT_CALL(unowned_dev_1, getUUID()).WillRepeatedly(ReturnRef(unowned_device_1_id));
+    EXPECT_CALL(unowned_dev_1, getName()).WillRepeatedly(ReturnRef(unowned_device_1_name));
+    EXPECT_CALL(unowned_dev_1, getModel()).WillRepeatedly(ReturnRef(unowned_device_1_model));
+    EXPECT_CALL(unowned_dev_1, getType()).WillRepeatedly(ReturnRef(unowned_device_1_type));
+    EXPECT_CALL(unowned_dev_1, isCloudAccessibility()).WillOnce(Return(false));
+    EXPECT_CALL(unowned_dev_1, setWiFiProperties(StrEq(this_device_id), StrEq("Iotivity_PWD"))).Times(1);
+    EXPECT_CALL(unowned_dev_1, unOwnDevice()).Times(1);
+
+    // IoTDeviceMock unowned_dev_2 call expectations
+    EXPECT_CALL(unowned_dev_2, getUUID()).WillRepeatedly(ReturnRef(unowned_device_2_id));
+    EXPECT_CALL(unowned_dev_2, isCloudAccessibility()).WillOnce(Return(true));
+
+    // MqClientMock mqclient call expectations
+    OC::OCRepresentation reg_representation;
+    reg_representation.setValue("duid", unowned_device_1_id);
+    reg_representation.setValue("uuid", cloud_auth_id);
+    reg_representation.setValue("parentUuid", this_device_id);
+    reg_representation.setValue("name", unowned_device_1_name);
+    reg_representation.setValue("model", unowned_device_1_model);
+    reg_representation.setValue("type", unowned_device_1_type);
+    EXPECT_CALL(mqclient, publish(StrEq(reg_topic), Eq(reg_representation))).Times(1);
+    OC::OCRepresentation unreg_representation;
+    unreg_representation.setValue("duid", unowned_device_1_id);
+    unreg_representation.setValue("action", action_unreg);
+    EXPECT_CALL(mqclient, publish(StrEq(unreg_topic), Eq(unreg_representation))).Times(1);
+
+    try {
+        HubResource hub(&iotivity, &pt, test_hub_devices_file);
+        hub.findDevices();
+        hub.ownDevice(unowned_device_1_id);
+        hub.ownDevice(unowned_device_2_id);
+        hub.unownDevice(unowned_device_1_id);
+    } catch (std::exception& e) {
+        FAIL() << "Exception: " << e.what();
+    }
+}
+
index f4488fe..3e90912 100644 (file)
@@ -29,7 +29,7 @@ class IoTDevManagerTest: public ::testing::Test
 {
 public:
     void SetUp() override {
-        IoTivity::cleanUp();
+        IoTivity::getInstance()->signOut();
         ASSERT_EQ(EC_OK, NM_init(&ctx));
 
         std::string login(TEST_ACCOUNT_LOGIN);
@@ -69,7 +69,7 @@ class IoTDevManagerTestWithReg: public ::testing::Test
 public:
     static void SetUpTestCase() {
         try {
-            IoTivity::cleanUp();
+            IoTivity::getInstance()->signOut();
             ASSERT_EQ(EC_OK, NM_init(&ctx));
 
             std::string login(TEST_ACCOUNT_LOGIN);
@@ -131,7 +131,7 @@ class IoTDevManagerWithOwned: public ::testing::Test
 {
 public:
     static void SetUpTestCase() {
-        IoTivity::cleanUp();
+        IoTivity::getInstance()->signOut();
         ASSERT_EQ(EC_OK, NM_init(&ctx));
 
         std::string login(TEST_ACCOUNT_LOGIN);
@@ -278,111 +278,6 @@ TEST_F(IoTDevManagerTest, device_discovery_ex)
 }
 
 /**
- * Test checks hub use case for owned primitive devices discovery
- * 1. Search for hub resource
- * 2. Obtain list of owned primitive devices
- */
-TEST_F(IoTDevManagerTest, DISABLED_hub_owned_discovery)
-{
-    try {
-        // Hub server resource defined in local_test_resource.cpp
-        // and starting in child process see test_all.cpp (fork)
-        auto hub_client = std::make_shared<HubClient>("");
-
-        ASSERT_TRUE(hub_client && hub_client->operator bool());
-
-        IoTDevicesMap dev_map;
-        hub_client->getOwnedDevices(dev_map);
-
-        for (auto dev : dev_map) {
-            std::cout << "Owned Device [" << dev.second->getUUID() << "]" << std::endl
-                      << "\tname: " << dev.second->getName() << std::endl
-                      << "\tmodel: " << dev.second->getModel() << std::endl
-                      << "\ttype: " << dev.second->getType() << std::endl
-                      << "\tstate: " << (dev.second->isOnline() ? "online" : "offline") << std::endl << std::endl;
-        }
-    } catch (std::exception& e) {
-        FAIL() << e.what();
-    }
-}
-
-/**
- * Test checks hub use case for unowned devices discovery
- * 1. Search for hub resource
- * 2. Obtain list of unowned primitive devices
- */
-TEST_F(IoTDevManagerTest, DISABLED_hub_unowned_discovery)
-{
-    try {
-        auto hub_client = std::make_shared<HubClient>("");
-
-        ASSERT_TRUE(hub_client && hub_client->operator bool());
-
-        IoTDevicesMap dev_map;
-        hub_client->getUnownedDevices(dev_map);
-
-        for (auto dev : dev_map) {
-            std::cout << "Unowned Device [" << dev.second->getUUID() << "]" << std::endl
-                      << "\tname: " << dev.second->getName() << std::endl
-                      << "\tmodel: " << dev.second->getModel() << std::endl
-                      << "\ttype: " << dev.second->getType() << std::endl
-                      << "\tstate: " << (dev.second->isOnline() ? "online" : "offline") << std::endl << std::endl;
-
-        }
-    } catch (std::exception& e) {
-        FAIL() << e.what();
-    }
-}
-
-/**
- * Test checks hub use case for unowned devices owning
- * 1. Search for hub resource
- * 2. Obtain list of unowned primitive devices
- * 3. Own all found devices
- */
-TEST_F(IoTDevManagerTest, DISABLED_hub_own_all_unowned)
-{
-    auto hub_client = std::make_shared<HubClient>(cloud_host);
-    ASSERT_TRUE(hub_client && hub_client->operator bool());
-
-    try {
-        IoTDevicesMap dev_map;
-        hub_client->getUnownedDevices(dev_map);
-        for (auto dev : dev_map) {
-            std::cout << "Unowned Device [" << dev.second->getUUID() << "]" << std::endl
-                      << "\tname: " << dev.second->getName() << std::endl;
-            hub_client->ownDevice(dev.second->getUUID());
-        }
-    } catch (std::exception& e) {
-        FAIL() << e.what();
-    }
-}
-
-/**
- * Test checks hub use case for owned devices unowning
- * 1. Search for hub resource
- * 2. Try to receive list of primitive devices
- */
-TEST_F(IoTDevManagerTest, DISABLED_hub_unown_all_owned)
-{
-    auto hub_client = std::make_shared<HubClient>(cloud_host);
-    ASSERT_TRUE(!!hub_client);
-
-    try {
-        IoTDevicesMap dev_map;
-        hub_client->getOwnedDevices(dev_map);
-        for (auto dev : dev_map) {
-            std::cout << "Unown Device [" << dev.second->getUUID() << "]" << std::endl
-                      << "\tname: " << dev.second->getName() << std::endl;
-
-            hub_client->unOwnDevice(dev.second->getUUID());
-        }
-    } catch (std::exception& e) {
-        FAIL() << e.what();
-    }
-}
-
-/**
  * Part of device_discovery test for owning
  */
 TEST_F(IoTDevManagerTest, DISABLED_own_device)
@@ -625,3 +520,19 @@ TEST_F(IoTDevManagerWithOwned, agentsListTest)
     Json::Reader reader;
     ASSERT_TRUE(reader.parse(agents_list, root));
 }
+
+#include "iotutils.h"
+
+void presenceCallback(const OC::HeaderOptions&, const OC::OCRepresentation& rep, const int a, const int b)
+{
+    std::cout << "Presence [" << a << ", " << b << "]:" << std::endl;
+    NetworkManager::printRepresentation(rep);
+    std::cout << std::endl;
+}
+
+TEST_F(IoTDevManagerTest, device_presence_example)
+{
+    OC::OCPlatform::OCPresenceHandle presenceHandle;
+    OC::OCPlatform::subscribeDevicePresence(presenceHandle, cloud_host, {}, CT_DEFAULT, presenceCallback);
+    std::this_thread::sleep_for(std::chrono::seconds(3));
+}
index 152a793..e98f971 100644 (file)
@@ -16,7 +16,6 @@
 
 #include "iotivity.h"
 #include "iot_resource.h"
-#include "nmexceptions.h"
 #include "securitycontext.h"
 #include "utils.h"
 #include "report_stub.h"
@@ -33,7 +32,7 @@ class TestIotNotification: public ::testing::Test
 {
 public:
     void SetUp() override {
-        IoTivity::cleanUp();
+        IoTivity::getInstance()->signOut();
         ASSERT_EQ(EC_OK, NM_init(&ctx));
         ASSERT_EQ(EC_OK, NM_signIn(ctx, TEST_ACCOUNT_LOGIN.c_str(), TEST_ACCOUNT_PASSWORD.c_str()));
         iot = ctx->instance;
@@ -96,16 +95,3 @@ TEST_F(TestIotNotification, correct)
     ASSERT_TRUE(userDataCheck.firstCallbackFired);
     ASSERT_TRUE(userDataCheck.lastCallbackFired);
 }
-
-static void notification2Cb(NM_NotificationData data, void* inUserData)
-{
-    UserData* userData = (UserData*)inUserData;
-    if (data.callbackState == FIRST_CALLBACK) {
-        userData->firstCallbackFired = true;
-    }
-    if (data.callbackState != FIRST_CALLBACK) {
-        userData->lastCallbackFired = true;
-    }
-
-    userData->notificationCV.notify_all();
-}
diff --git a/device_core/utest/test_iot_policy_enforce.cpp b/device_core/utest/test_iot_policy_enforce.cpp
new file mode 100644 (file)
index 0000000..2f803dd
--- /dev/null
@@ -0,0 +1,133 @@
+#include <gmock/gmock.h>
+#include <stdexcept>
+#include "iot_policy_enforce_mock.h"
+
+using namespace iot::core;
+using ::testing::Return;
+using ::testing::Throw;
+
+namespace
+{
+
+const std::string EMPTY;
+const std::string ILLFORMED_JSON{"asdfasdf"};
+const std::string EMPTY_GROUP_NAME_JSON{R"-([{"group":""}])-"};
+const std::string UNKNOWN_GROUP_NAME_JSON{R"-([{"group":"some-unknown-group-name"}])-"};
+const std::string MOCK_POLICY_NAME{"mock"};
+const std::string MOCK_POLICY_EMPTY_JSON{"[{\"group\":\"" + MOCK_POLICY_NAME + "\",\"policies\":\"\"}]"};
+const std::string MOCK_POLICY_JSON{"[{\"group\":\"" + MOCK_POLICY_NAME + "\",\"policies\":\"[]\"}]"};
+
+}
+
+TEST(Test_PolicyEnforce, ParsePolicy_errors_and_init_failed)
+{
+    IPolicyGroupEnforceMock policy_mock;
+    PolicyEnforce::GetInstance().RegisterGroup(&policy_mock, MOCK_POLICY_NAME);
+
+    EXPECT_CALL(policy_mock, Init()).WillOnce(Return(false));
+
+    auto& pe = PolicyEnforce::GetInstance();
+    EXPECT_EQ(PolicyEnforce::Result::ERROR_PARSING, pe.ParsePolicy(EMPTY));
+    EXPECT_EQ(PolicyEnforce::Result::ERROR_PARSING, pe.ParsePolicy(ILLFORMED_JSON));
+    EXPECT_EQ(PolicyEnforce::Result::ERROR_PARSING, pe.ParsePolicy(EMPTY_GROUP_NAME_JSON));
+    EXPECT_EQ(PolicyEnforce::Result::SUCCESS, pe.ParsePolicy(UNKNOWN_GROUP_NAME_JSON));
+    // Simulate "fail to initialize group"
+    EXPECT_EQ(PolicyEnforce::Result::ERROR_GROUP, pe.ParsePolicy(MOCK_POLICY_JSON));
+}
+
+TEST(Test_PolicyEnforce, ParsePolicy_parsing_error)
+{
+    IPolicyGroupEnforceMock policy_mock;
+    PolicyEnforce::GetInstance().RegisterGroup(&policy_mock, MOCK_POLICY_NAME);
+
+    EXPECT_CALL(policy_mock, Init()).WillOnce(Return(true));
+    // Simulate parsing failure
+    EXPECT_CALL(policy_mock, ParseGroup(::testing::_)).WillOnce(Return(false));
+    EXPECT_CALL(policy_mock, Deinit()).Times(1);
+
+    auto& pe = PolicyEnforce::GetInstance();
+    // Simulate "fail to initialize group"
+    EXPECT_EQ(PolicyEnforce::Result::ERROR_GROUP, pe.ParsePolicy(MOCK_POLICY_JSON));
+}
+
+TEST(Test_PolicyEnforce, ParsePolicy_throw)
+{
+    IPolicyGroupEnforceMock policy_mock;
+    PolicyEnforce::GetInstance().RegisterGroup(&policy_mock, MOCK_POLICY_NAME);
+
+    EXPECT_CALL(policy_mock, Init()).WillOnce(Return(true));
+    // Simulate parsing failure
+    EXPECT_CALL(policy_mock, ParseGroup(::testing::_)).WillOnce(Throw(std::logic_error("")));
+
+    auto& pe = PolicyEnforce::GetInstance();
+    // Simulate throwing exception on parsing
+    EXPECT_EQ(PolicyEnforce::Result::ERROR_PARSING, pe.ParsePolicy(MOCK_POLICY_JSON));
+}
+
+//27           1 : PolicyEnforce::PolicyEnforce()
+//28           1 :     : m_policyGroups()
+//29             : {
+//30           1 : }
+//31             :
+//32             : PolicyEnforce::Result
+//33           1 : PolicyEnforce::ParsePolicy(const std::string& jsonString)
+//34             : {
+//35           1 :     LOG_D(TAG, "PolicyEnforce::ParsePolicy");
+//36           1 :     Result result = Result::SUCCESS;
+//37             :
+//38             :     try {
+//39           1 :         if (jsonString.empty()) {
+//40           0 :             return Result::ERROR_PARSING; //TODO
+//41             :         }
+//42             :
+//43           2 :         Json::Value policyGroupList;
+//44           2 :         Json::Reader reader;
+//45             :
+//46           1 :         bool parsingSuccessful = reader.parse(jsonString.c_str(), policyGroupList);
+//47             :
+//48           1 :         if (!parsingSuccessful || policyGroupList.empty()) {
+//49           0 :             return Result::ERROR_PARSING; //TODO
+//50             :         }
+//51             :
+//52           2 :         for (auto& node : policyGroupList) {
+//53           2 :             std::string groupName = node.get("group", "").asString();
+//54             :
+//55           1 :             if (groupName.empty()) {
+//56           0 :                 LOG_E(TAG, "No group node in class");
+//57           0 :                 return Result::ERROR_PARSING;
+//58             :             }
+//59             :
+//60           1 :             PolicyGroupMap::iterator it = m_policyGroups.find(groupName);
+//61             :
+//62           1 :             if (it == m_policyGroups.end()) {
+//63             :                 //FIXME Set error if error was occured
+//64           0 :                 continue; //TODO
+//65             :             }
+//66             :
+//67           1 :             IPolicyGroupEnforce& groupEnforce = *(it->second);
+//68             :
+//69           1 :             if (!groupEnforce.Init(/*m_context*/)) {
+//70           0 :                 result = Result::ERROR_GROUP;
+//71           0 :                 continue; //TODO
+//72             :             }
+//73             :
+//74           2 :             Json::Value policiesList = node.get("policies", "");
+//75             :
+//76           1 :             if (policiesList.empty()) {
+//77           0 :                 LOG_E(TAG, "No group node in class");
+//78           0 :                 return Result::ERROR_PARSING;
+//79             :             }
+//80             :
+//81           1 :             if (!groupEnforce.ParseGroup(policiesList)) {
+//82           0 :                 LOG_E(TAG, "Failed to apply policy group: %s", groupName.c_str());
+//83           0 :                 result = Result::ERROR_GROUP;
+//84             :             }
+//85             :
+//86           1 :             groupEnforce.Deinit();
+//87             :         }
+//88           0 :     } catch (std::exception& e) {
+//89           0 :         LOG_E(TAG, "Failed to apply policy, exception: %s", e.what());
+//90           0 :         LOG_E(TAG, "Policy which caused this exception: %s", jsonString.c_str());
+//91           0 :         result = Result::ERROR_PARSING;
+//92             :     }
+//93             :
diff --git a/device_core/utest/test_iot_tvext_policy_enforce.cpp b/device_core/utest/test_iot_tvext_policy_enforce.cpp
new file mode 100644 (file)
index 0000000..8ba534f
--- /dev/null
@@ -0,0 +1,45 @@
+#include "device-policy-manager-mock.h"
+#include "iot_tvext_enforce.h"
+#include <jsoncpp/json/reader.h>
+
+using namespace iot::core;
+using ::testing::_;
+using ::testing::Return;
+
+namespace
+{
+const std::string policy = R"-([{"name":"sound","state":1,"items":[]},
+                           {"name":"bluetooth","state":1,"items":[]},
+                           {"name":"wifi","state":0,"items":[]},
+                           {"name":"usb","state":0,"items":[]},
+                           {"name":"dtv-tunner","state":1,"items":[]},
+                           {"name":"iptables","state":1,"items":["127.0.0.0/24|UDP|10-1024","1.1.1.1|TCP|80,443","8.8.8.8"]}])-";
+}
+
+TEST(test_TvExtPolicyEnforce, test_ParseGroup)
+{
+    DPMMock dpm;
+    dpm_set_custom_implementation(&dpm);
+
+    TvExtPolicyEnforce tvep(PolicyEnforce::GetInstance());
+
+    EXPECT_CALL(dpm, dpm_manager_create()).WillOnce(Return(&dpm));
+
+    EXPECT_CALL(dpm, dpm_restriction_set_sound_state(1)).WillOnce(Return(0));
+
+    EXPECT_CALL(dpm, dpm_restriction_set_bluetooth_mode_change_state(1)).WillOnce(Return(0));
+    EXPECT_CALL(dpm, dpm_restriction_set_wifi_state(0)).WillOnce(Return(0));
+    EXPECT_CALL(dpm, dpm_restriction_set_usb_client_state(0)).WillOnce(Return(0));
+    EXPECT_CALL(dpm, dpm_restriction_set_tuner_state(1)).WillOnce(Return(0));
+    EXPECT_CALL(dpm, dpm_manager_destroy()).Times(1);
+    EXPECT_CALL(dpm, dpm_firewall_flush_deny_rules()).WillOnce(Return(0));
+    EXPECT_CALL(dpm, dpm_firewall_apply_deny_rules(_)).Times(3).WillRepeatedly(Return(0));
+
+    EXPECT_TRUE(tvep.Init());
+    Json::Value root;
+    Json::Reader reader;
+    ASSERT_TRUE(reader.parse(policy, root));
+    EXPECT_TRUE(tvep.ParseGroup(root));
+
+    EXPECT_NO_THROW(tvep.Deinit());
+}
diff --git a/device_core/utest/test_iotchilddevice_impl.cpp b/device_core/utest/test_iotchilddevice_impl.cpp
new file mode 100644 (file)
index 0000000..f4846ff
--- /dev/null
@@ -0,0 +1,44 @@
+#include <gtest/gtest.h>
+#include "iotchilddevice_impl.h"
+
+using namespace OC;
+using namespace NetworkManager;
+
+namespace
+{
+const std::string HUB_RESOURCE_HOST{"coap://192.168.1.2:5000"};
+const std::string HUB_RESOURCE_URI{"/resource"};
+const std::string HUB_RESOURCE_TYPE{"oic.fake"};
+const std::string CDEVICE_UUID{"child-device-uuid"};
+const std::string CDEVICE_NAME{"child-device-name"};
+const std::string CDEVICE_MODEL{"child-device-model"};
+const std::string CDEVICE_TYPE{"child-device-type"};
+}
+
+TEST(Test_IoTChildDevice_impl, construction_and_getters)
+{
+    OCResource::Ptr resource = OCPlatform::constructResourceObject(
+                HUB_RESOURCE_HOST,
+                HUB_RESOURCE_URI,
+                CT_DEFAULT,
+                true,
+                {HUB_RESOURCE_TYPE},
+                {DEFAULT_INTERFACE});
+
+    std::shared_ptr<HubClient> hub = std::make_shared<HubClient>(resource);
+
+    IoTChildDevice_impl child_device(hub, CDEVICE_UUID, CDEVICE_NAME, CDEVICE_MODEL, CDEVICE_TYPE, true);
+    EXPECT_EQ(CDEVICE_UUID, child_device.getUUID());
+    EXPECT_EQ(CDEVICE_NAME, child_device.getName());
+    EXPECT_EQ(CDEVICE_MODEL, child_device.getModel());
+    EXPECT_EQ(CDEVICE_TYPE, child_device.getType());
+    EXPECT_TRUE(child_device.isOnline());
+    EXPECT_EQ(HUB_RESOURCE_HOST, child_device.getHost());
+    EXPECT_EQ("", child_device.getParent());
+    EXPECT_FALSE(child_device.isCloudAccessibility());
+    child_device.setState(false);
+    EXPECT_FALSE(child_device.isOnline());
+    EXPECT_NO_THROW(child_device.setWiFiProperties(CDEVICE_UUID, CDEVICE_NAME));
+}
+
+
index a8f5df8..9894cc2 100644 (file)
@@ -35,7 +35,7 @@ class TestIotMQ: public ::testing::Test
 {
 public:
     void SetUp() override {
-        IoTivity::cleanUp();
+        IoTivity::getInstance()->signOut();
         ASSERT_EQ(EC_OK, NM_init(&ctx));
         ASSERT_EQ(EC_OK, NM_signIn(ctx, TEST_ACCOUNT_LOGIN.c_str(), TEST_ACCOUNT_PASSWORD.c_str()));
         iot = ctx->instance;
diff --git a/device_core/utest/test_policyhandler.cpp b/device_core/utest/test_policyhandler.cpp
new file mode 100644 (file)
index 0000000..653cf2b
--- /dev/null
@@ -0,0 +1,187 @@
+#include <gtest/gtest.h>
+#include <gmock/gmock.h>
+#include <jsoncpp/json/reader.h>
+#include "iotivity_mock.h"
+#include "mqclient_mock.h"
+#include "policyhandler.h"
+#include "policyhandlermq.h"
+#include "iot_policy_enforce_mock.h"
+
+using namespace NetworkManager;
+
+using ::testing::Return;
+using ::testing::ReturnRef;
+using ::testing::StrEq;
+using ::testing::Eq;
+
+/**
+ * @brief TEST usecase for policy dispatching to the server
+ * 1. Create objects and mocks
+ * 2. Call enforceCallback
+ * 3. Check expectations
+ */
+TEST(Test_PolicyHandler, test_enforceCallback)
+{
+    IoTivityMock iotivity;
+    MqClientMock mqclient;
+    const std::string auth_id = "1234";
+    const std::string topic = "/" + auth_id+ "/policy";
+    const std::string agentId = "11222123451345";
+    const std::string jsonData = "{\"policies\":[{\"group\":\"some-group\"}]}";
+    const std::string device_id = "this-device-id";
+    OC::OCRepresentation test_rep;
+    test_rep.setValue("policy", jsonData);
+    test_rep.setValue("duid", device_id);
+    test_rep.setValue("agent", agentId);
+
+    EXPECT_CALL(iotivity, getMqHandler()).WillRepeatedly(Return(&mqclient));
+    EXPECT_CALL(iotivity, getCloudAuthId()).WillOnce(ReturnRef(auth_id));
+    EXPECT_CALL(mqclient, subscribe(StrEq(topic), ::testing::_));
+    EXPECT_CALL(iotivity, getDeviceID()).WillOnce(ReturnRef(device_id));
+    EXPECT_CALL(mqclient, publish(StrEq(PolicyHandlerMQ::POLICY_TOPIC), Eq(test_rep))).Times(1);
+
+    try {
+        PolicyHandlerMQ phmq(&iotivity);
+        EXPECT_TRUE(phmq.init());
+        phmq.enforceCallback(agentId, jsonData);
+    } catch (std::exception& e) {
+        FAIL() << "Exception: " << e.what();
+    }
+}
+
+/**
+ * @brief TEST usecase for receiveing from server for this device
+ * 1. Create objects and mocks
+ * 2. Register IPolicyGroupEnforceMock as policy processor
+ * 3. Call observeCallback
+ * 4. Check expectations
+ */
+TEST(Test_PolicyHandler, test_observeCallback)
+{
+    IPolicyGroupEnforceMock policyMock;
+    iot::core::PolicyEnforce::GetInstance().RegisterGroup(&policyMock, "fake-policy-group");
+    IoTivityMock iotivity;
+    const std::string device_id = "this-device-id";
+    const std::string policy = R"-([{"name":"sound","state":1,"items":[]},{"name":"bluetooth","state":1,"items":[]},{"name":"wifi","state":0,"items":[]},{"name":"usb","state":0,"items":[]},{"name":"dtv-tunner","state":1,"items":[]},{"name":"iptables","state":1,"items":["127.0.0.0/24|UDP|10-1024","1.1.1.1|TCP|80,443","8.8.8.8"]}])-";
+    const std::string policy_package = "[{\"group\":\"fake-policy-group\",\"policies\":" + policy + "}]";
+    OC::OCRepresentation test_rep;
+    test_rep.setValue("policy", policy_package);
+    test_rep.setValue("duid", device_id);
+    OC::HeaderOptions head_options;
+    Json::Value root;
+    Json::Reader reader;
+    reader.parse(policy, root);
+
+    EXPECT_CALL(iotivity, getDeviceID()).WillRepeatedly(ReturnRef(device_id));
+
+    ::testing::InSequence dummy;
+    EXPECT_CALL(policyMock, Init()).WillOnce(Return(true));
+    EXPECT_CALL(policyMock, ParseGroup(Eq(root))).WillOnce(Return(true));
+    EXPECT_CALL(policyMock, Deinit()).Times(1);
+
+    try {
+        PolicyHandlerMQ phmq(&iotivity);
+        phmq.observeCallback(head_options, test_rep, OC_STACK_OK, 1);
+    } catch (std::exception& e) {
+        FAIL() << "Exception: " << e.what();
+    }
+}
+
+/**
+ * @brief The ICallback struct is interface used to mock callback
+ */
+struct ICallback
+{
+    virtual void call(const OC::HeaderOptions& head_options, const OC::OCRepresentation& rep, const int& ecode,
+                 const int& seq_number) = 0;
+};
+
+/**
+ * @brief The CallbackMock struct callback mock
+ */
+struct CallbackMock: public ICallback
+{
+    MOCK_METHOD4(call, void(const OC::HeaderOptions& head_options, const OC::OCRepresentation& rep, const int& ecode,
+                                 const int& seq_number));
+};
+
+/**
+ * @brief TEST usecase for receiving policy from server for child device
+ * 1. Create objects and mocks
+ * 2. Set callback for proxying requests to chil devices
+ * 3. Call observeCallback
+ * 4. Check expectations
+ */
+TEST(Test_PolicyHandler, test_observeCallback_for_child)
+{
+    CallbackMock callbackMock;
+    IoTivityMock iotivity;
+    const std::string device_id = "this-device-id";
+    const std::string child_device_id = "child-device-id";
+    const std::string policy = R"-([{"name":"sound","state":1,"items":[]},{"name":"bluetooth","state":1,"items":[]},{"name":"wifi","state":0,"items":[]},{"name":"usb","state":0,"items":[]},{"name":"dtv-tunner","state":1,"items":[]},{"name":"iptables","state":1,"items":["127.0.0.0/24|UDP|10-1024","1.1.1.1|TCP|80,443","8.8.8.8"]}])-";
+    const std::string policy_package = "[{\"group\":\"fake-policy-group\",\"policies\":" + policy + "}]";
+    OC::OCRepresentation test_rep;
+    test_rep.setValue("policy", policy_package);
+    test_rep.setValue("duid", child_device_id);
+    test_rep.setValue("parentUuid", device_id);
+    OC::HeaderOptions head_options;
+    Json::Value root;
+    Json::Reader reader;
+    reader.parse(policy, root);
+
+    EXPECT_CALL(iotivity, getDeviceID()).WillRepeatedly(ReturnRef(device_id));
+
+    EXPECT_CALL(callbackMock, call(::testing::_, Eq(test_rep), OC_STACK_OK, 1)).Times(1);
+
+    auto callLambda = [&callbackMock](const OC::HeaderOptions& head_options, const OC::OCRepresentation& rep, const int& ecode,
+            const int& seq_number)
+    {
+        callbackMock.call(head_options, rep, ecode, seq_number);
+    };
+
+    try {
+        PolicyHandlerMQ phmq(&iotivity);
+        phmq.setObserver(callLambda);
+        phmq.observeCallback(head_options, test_rep, OC_STACK_OK, 1);
+    } catch (std::exception& e) {
+        FAIL() << "Exception: " << e.what();
+    }
+}
+
+
+class PolicyHandlerSimpleMock: public PolicyHandler
+{
+public:
+    PolicyHandlerSimpleMock(): PolicyHandler(nullptr)
+    {
+    }
+
+    void pass(const OC::OCRepresentation& rep, const OC::QueryParamsMap& params) override
+    {
+    }
+
+    bool init() override
+    {
+        return true;
+    }
+
+    bool isDisabled()
+    {
+        return disabled;
+    }
+};
+
+/**
+ * @brief TEST for "disable" method PolicyHandler class
+ * 1. Check that initially is enabled
+ * 2. Disable
+ * 3. Check that object became disabled
+ */
+TEST(Test_PolicyHandler, test_disable)
+{
+    PolicyHandlerSimpleMock mock;
+    EXPECT_FALSE(mock.isDisabled());
+    mock.disable();
+    EXPECT_TRUE(mock.isDisabled());
+}
+
index 4cd3258..dee92aa 100644 (file)
@@ -1,6 +1,7 @@
 #include <string>
 #include <iostream>
 #include <gtest/gtest.h>
+#include <stdexcept>
 #include "proxythread.h"
 
 using namespace std;
@@ -27,4 +28,30 @@ TEST(test_proxythread, test_ProxyThread)
     }
 }
 
+TEST(test_proxythread, test_exceptions)
+{
+    try {
+        ProxyThread proxy;
+        proxy.start();
+
+        int result = 0;
+
+        proxy.addDefferedTask([&result] {
+            result = 42;
+            throw(std::logic_error(""));
+        });
+
+        proxy.addDefferedTask([] {
+            throw(1);
+        });
+
+        proxy.stop();
+        proxy.join();
+
+        ASSERT_EQ(42, result);
+    } catch (std::exception& e) {
+        FAIL() << "Exception: " << e.what();
+    }
+}
+
 
diff --git a/device_core/utest/test_reporthandler.cpp b/device_core/utest/test_reporthandler.cpp
new file mode 100644 (file)
index 0000000..64855f8
--- /dev/null
@@ -0,0 +1,31 @@
+#include <gtest/gtest.h>
+#include "reporthandler.h"
+
+
+
+class ReportHandlerTester: public ReportHandler
+{
+public:
+    bool isDisabled()
+    {
+        return disabled;
+    }
+
+    void pass(const OC::OCRepresentation&, const OC::QueryParamsMap&) override
+    {
+    }
+};
+
+/**
+ * @brief TEST for ReportHandler disable method
+ * 1. Check that object is enabled by default
+ * 2. Disable
+ * 3. Check that object is disabled
+ */
+TEST(TestReportHandler, test_disable)
+{
+    ReportHandlerTester rht;
+    EXPECT_FALSE(rht.isDisabled());
+    rht.disable();
+    EXPECT_TRUE(rht.isDisabled());
+}
diff --git a/device_core/utest/test_reporthandlermq.cpp b/device_core/utest/test_reporthandlermq.cpp
new file mode 100644 (file)
index 0000000..666db01
--- /dev/null
@@ -0,0 +1,44 @@
+#include <gtest/gtest.h>
+#include <gmock/gmock.h>
+#include <jsoncpp/json/reader.h>
+#include "iotivity_mock.h"
+#include "mqclient_mock.h"
+#include "reporthandlermq.h"
+
+
+using ::testing::Return;
+using ::testing::StrEq;
+using ::testing::Eq;
+
+/**
+ * @brief TEST usecase for policy dispatching to the server
+ * 1. Create objects and mocks
+ * 2. Call ReportHandlerMQ::pass
+ * 3. Check that publish method of MqClient is called
+ * 4. Disable handler
+ * 5. Call ReportHandlerMQ::pass
+ * 6. Check that publish method of MqClient is NOT called
+ */
+TEST(Test_ReportHandlerMQ, test_pass)
+{
+    IoTivityMock iotivity;
+    MqClientMock mqclient;
+    const std::string topic = "/srv/report";
+    const std::string report = "report data";
+    OC::OCRepresentation test_rep;
+    test_rep.setValue("report", report);
+
+    EXPECT_CALL(iotivity, getMqHandler()).WillOnce(Return(&mqclient));
+    EXPECT_CALL(mqclient, publish(StrEq(topic), Eq(test_rep))).Times(1);
+
+    try {
+        ReportHandlerMQ handler(&iotivity);
+
+        handler.pass(test_rep, OC::QueryParamsMap{});
+        handler.disable();
+        handler.pass(test_rep, OC::QueryParamsMap{});
+
+    } catch (std::exception& e) {
+        FAIL() << "Exception: " << e.what();
+    }
+}
index 6f0c84d..c117cce 100644 (file)
@@ -15,7 +15,7 @@ using namespace NetworkManager;
 extern std::string cloud_host;
 extern std::string TEST_ACCOUNT_LOGIN;
 extern std::string TEST_ACCOUNT_PASSWORD;
-const std::string TEST_DSM_SERVER_URL = "http://106.125.46.139:8080/dsm/restapi/";
+extern std::string TEST_DSM_SERVER_URL;
 
 #define TAG "Tests"
 
@@ -107,7 +107,7 @@ TEST(Test_REST, test_policyUseCase)
         std::string code = service.getAuthCode(TEST_ACCOUNT_LOGIN, TEST_ACCOUNT_PASSWORD);
         ASSERT_FALSE(code.empty());
         std::cout << "Received code: " << code << std::endl;
-        NetworkManager::IoTivity::cleanUp();
+        NetworkManager::IoTivity::getInstance()->signOut();
         auto iotivity = NetworkManager::IoTivity::getInstance();
         iotivity->signUp(cloud_host, NetworkManager::IoTivity::DEFAULT_PROVIDER, code);
 
diff --git a/device_core/utest/test_threadbase.cpp b/device_core/utest/test_threadbase.cpp
new file mode 100644 (file)
index 0000000..390e56c
--- /dev/null
@@ -0,0 +1,63 @@
+#include <gtest/gtest.h>
+#include "thread_base.h"
+#include <chrono>
+
+namespace
+{
+static const int SLEEP_DELAY_MS = 50;
+
+/**
+ * @brief The ThreadBaseTester class used to test ThreadBase class
+ */
+class ThreadBaseTester: public NMD::ThreadBase
+{
+public:
+    void routine() override
+    {
+        routine_called_atleast_once = true;
+        while(m_running) {
+            std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_DELAY_MS));
+        }
+
+        routine_exited = true;
+    }
+
+    bool isRunning() const
+    {
+        return m_running;
+    }
+
+    bool routine_called_atleast_once = false;
+
+    bool routine_exited = false;
+};
+}
+
+/**
+ * @brief TEST default usecase for objects of the classes derived from the ThreadBase
+ * 1. Create thread
+ * 2. Checking that thread is not running after creation
+ * 3. Start thread
+ * 4. Checking that thread is been running
+ * 5. Stop thread and join it
+ * 6. Checking that thread is stoped
+ */
+TEST(Test_ThreadBase, test_default_sequence)
+{
+    ThreadBaseTester t;
+    EXPECT_FALSE(t.isRunning());
+    EXPECT_FALSE(t.routine_called_atleast_once);
+    EXPECT_FALSE(t.routine_exited);
+    t.start();
+    // Give chance to run to the spawned thread
+    std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_DELAY_MS));
+    EXPECT_TRUE(t.isRunning());
+    EXPECT_TRUE(t.routine_called_atleast_once);
+    EXPECT_FALSE(t.routine_exited);
+    t.stop();
+    EXPECT_NO_THROW(t.join());
+
+    EXPECT_FALSE(t.isRunning());
+    EXPECT_TRUE(t.routine_exited);
+}
+
diff --git a/device_core/utest/test_ubuntu_dpm.cpp b/device_core/utest/test_ubuntu_dpm.cpp
new file mode 100644 (file)
index 0000000..56bc8a2
--- /dev/null
@@ -0,0 +1,57 @@
+#include <gtest/gtest.h>
+#include "mock/device-policy-manager.h"
+
+
+TEST(Test_ubuntu_dpm_stub, test_all_methods)
+{
+    DPMInterface_impl_default dpm;
+
+    dpm_set_custom_implementation(&dpm);
+    device_policy_manager_h handle = dpm_manager_create();
+    ASSERT_EQ((device_policy_manager_h)&dpm, handle);
+
+    ASSERT_EQ(0, dpm_application_install_package(handle, nullptr));
+
+    ASSERT_EQ(0, dpm_application_uninstall_package(handle, nullptr));
+
+    ASSERT_EQ(0, dpm_security_lockout_screen(handle));
+
+    ASSERT_EQ(0, dpm_restriction_set_camera_state(handle, 0));
+    ASSERT_EQ(0, dpm_restriction_set_microphone_state(handle, 0));
+    ASSERT_EQ(0, dpm_restriction_set_location_state(handle, 0));
+    ASSERT_EQ(0, dpm_restriction_set_external_storage_state(handle, 0));
+    ASSERT_EQ(0, dpm_restriction_set_clipboard_state(handle, 0));
+    ASSERT_EQ(0, dpm_restriction_set_usb_debugging_state(handle, 0));
+    ASSERT_EQ(0, dpm_restriction_set_wifi_state(handle, 0));
+    ASSERT_EQ(0, dpm_restriction_set_wifi_hotspot_state(handle, 0));
+    ASSERT_EQ(0, dpm_restriction_set_bluetooth_tethering_state(handle, 0));
+    ASSERT_EQ(0, dpm_restriction_set_usb_tethering_state(handle, 0));
+    ASSERT_EQ(0, dpm_restriction_set_bluetooth_mode_change_state(handle, 0));
+    ASSERT_EQ(0, dpm_restriction_set_bluetooth_desktop_connectivity_state(handle, 0));
+    ASSERT_EQ(0, dpm_restriction_set_bluetooth_pairing_state(handle, 0));
+    ASSERT_EQ(0, dpm_restriction_set_popimap_email_state(handle, 0));
+    ASSERT_EQ(0, dpm_restriction_set_browser_state(handle, 0));
+    ASSERT_EQ(0, dpm_bluetooth_set_device_restriction(handle, 0));
+    ASSERT_EQ(0, dpm_bluetooth_set_uuid_restriction(handle, 0));
+    ASSERT_EQ(0, dpm_security_set_internal_storage_encryption(handle, 0));
+    ASSERT_EQ(0, dpm_security_set_external_storage_encryption(handle, 0));
+    ASSERT_EQ(0, dpm_wifi_set_profile_change_restriction(handle, 0));
+    ASSERT_EQ(0, dpm_wifi_set_network_access_restriction(handle, 0));
+
+    ASSERT_EQ(0, dpm_bluetooth_add_device_to_blacklist(handle, nullptr));
+    ASSERT_EQ(0, dpm_bluetooth_remove_device_from_blacklist(handle, nullptr));
+    ASSERT_EQ(0, dpm_bluetooth_add_uuid_to_blacklist(handle, nullptr));
+    ASSERT_EQ(0, dpm_bluetooth_remove_uuid_from_blacklist(handle, nullptr));
+    ASSERT_EQ(0, dpm_wifi_add_ssid_to_blocklist(handle, nullptr));
+    ASSERT_EQ(0, dpm_wifi_remove_ssid_from_blocklist(handle, nullptr));
+
+    ASSERT_EQ(0, dpm_security_wipe_data(handle, 0, nullptr));
+    ASSERT_EQ(0, dpm_restriction_set_messaging_state(handle, 0, nullptr));
+    ASSERT_EQ(0, dpm_application_add_privilege_to_blacklist(handle, 0, nullptr));
+    ASSERT_EQ(0, dpm_application_remove_privilege_from_blacklist(handle, 0, nullptr));
+    ASSERT_EQ(0, dpm_application_set_mode_restriction(handle, 0, nullptr));
+    ASSERT_EQ(0, dpm_application_unset_mode_restriction(handle, 0, nullptr));
+    ASSERT_EQ(0, dpm_firewall_apply_deny_rules(handle, nullptr));
+    ASSERT_EQ(0, dpm_firewall_flush_deny_rules(handle));
+    ASSERT_NO_THROW(dpm_manager_destroy(handle));
+}
diff --git a/device_core/utest/tests_stub.cpp b/device_core/utest/tests_stub.cpp
new file mode 100644 (file)
index 0000000..680924d
--- /dev/null
@@ -0,0 +1,14 @@
+#include <string>
+#include <systemd/sd-daemon.h>
+
+static std::string g_device_name = "Generic device";
+static std::string g_device_model = "Model 1";
+static std::string g_device_type = "iotdevice";
+
+bool volatile g_running = true;
+
+int sd_notify(int unset_environment, const char *state)
+{
+    return 0;
+}
+