From 8c2a147814d2fee647dd3583f6d8eb8e82853630 Mon Sep 17 00:00:00 2001 From: Lomtev Dmytro Date: Tue, 5 Sep 2017 10:53:06 +0300 Subject: [PATCH] Server stub (secserver) removed from repository. --- device_core/secserver/CMakeLists.txt | 21 -- device_core/secserver/accessor.h | 25 -- device_core/secserver/agent.cpp | 86 ------- device_core/secserver/agent.h | 44 ---- device_core/secserver/macro.h | 20 -- device_core/secserver/notification_resource.cpp | 148 ------------ device_core/secserver/notification_resource.h | 78 ------- device_core/secserver/policy.cpp | 132 ----------- device_core/secserver/policy.h | 59 ----- device_core/secserver/policy_resource.cpp | 298 ------------------------ device_core/secserver/policy_resource.h | 69 ------ device_core/secserver/report.cpp | 163 ------------- device_core/secserver/report.h | 82 ------- device_core/secserver/report_resource.cpp | 270 --------------------- device_core/secserver/report_resource.h | 71 ------ device_core/secserver/secserver.cpp | 257 -------------------- device_core/secserver/selectquery.h | 61 ----- device_core/secserver/sqlitedb.cpp | 46 ---- device_core/secserver/sqlitedb.h | 26 --- 19 files changed, 1956 deletions(-) delete mode 100644 device_core/secserver/CMakeLists.txt delete mode 100644 device_core/secserver/accessor.h delete mode 100644 device_core/secserver/agent.cpp delete mode 100644 device_core/secserver/agent.h delete mode 100644 device_core/secserver/macro.h delete mode 100644 device_core/secserver/notification_resource.cpp delete mode 100644 device_core/secserver/notification_resource.h delete mode 100644 device_core/secserver/policy.cpp delete mode 100644 device_core/secserver/policy.h delete mode 100644 device_core/secserver/policy_resource.cpp delete mode 100644 device_core/secserver/policy_resource.h delete mode 100644 device_core/secserver/report.cpp delete mode 100644 device_core/secserver/report.h delete mode 100644 device_core/secserver/report_resource.cpp delete mode 100644 device_core/secserver/report_resource.h delete mode 100644 device_core/secserver/secserver.cpp delete mode 100644 device_core/secserver/selectquery.h delete mode 100644 device_core/secserver/sqlitedb.cpp delete mode 100644 device_core/secserver/sqlitedb.h diff --git a/device_core/secserver/CMakeLists.txt b/device_core/secserver/CMakeLists.txt deleted file mode 100644 index 50ebc32..0000000 --- a/device_core/secserver/CMakeLists.txt +++ /dev/null @@ -1,21 +0,0 @@ -get_filename_component(ProjectId ${CMAKE_CURRENT_SOURCE_DIR} NAME) -project(${ProjectId}) - -set(app ${ProjectId}) -file(GLOB SRCS *.cpp) - -pkg_check_modules(REQUIRED sqlite3 jsoncpp) - -include_directories( - ../iotivity_lib/inc - ../ctrl_app_lib/inc -) - -add_executable(${app} ${SRCS}) -target_link_libraries(${app} - ${IOTIVITY_LIB_PROJECT_NAME} - sqlite3 - jsoncpp -) - -install(TARGETS ${app} DESTINATION ${TESTS_DIR}) diff --git a/device_core/secserver/accessor.h b/device_core/secserver/accessor.h deleted file mode 100644 index 67b1758..0000000 --- a/device_core/secserver/accessor.h +++ /dev/null @@ -1,25 +0,0 @@ -#ifndef ACCESSOR_H -#define ACCESSOR_H - -#include -#include - -template -inline void convert(T& out, const char* in, std::true_type) -{ -out = std::stoi(in); -} - -template -inline void convert(T& out, const char* in, std::false_type) -{ - out = in; -} - -template -inline void convert(T& out, const char* in) -{ - convert(out, in, typename std::is_integral::type()); -} - -#endif // ACCESSOR_H diff --git a/device_core/secserver/agent.cpp b/device_core/secserver/agent.cpp deleted file mode 100644 index 8c0e12b..0000000 --- a/device_core/secserver/agent.cpp +++ /dev/null @@ -1,86 +0,0 @@ -#include "agent.h" -#include -#include "accessor.h" -#include - -using namespace std; - -const string Agent::TABLE_NAME{STRINGIZE(Agent) "s"}; - -Agent::Agent(const std::string& id, const std::string& name): id(-1), agent_id(id), name(name), modified(false) -{ - -} - -Agent::Agent(): id(-1), agent_id(""), name(""), modified(false) -{ - -} - -void Agent::registerModel() -{ - ostringstream os; - - os << "CREATE TABLE IF NOT EXISTS " << TABLE_NAME - << " (id INTEGER PRIMARY KEY AUTOINCREMENT," - << "agent_id CHAR(36) NOT NULL," - << "name TEXT);"; - SQLiteDB::inst().exec(os.str(), &selecter, nullptr); -} - -void Agent::save() -{ - if (id == -1) { - ostringstream os; - os << "INSERT INTO " << TABLE_NAME << " (agent_id,name) " - << "VALUES ('" << agent_id << "', '" << name << "');"; - SQLiteDB::inst().exec(os.str(), &selecter, nullptr); - id = SQLiteDB::inst().last_row_id(); - } else if (modified) { - ostringstream os; - os << "UPDATE " << TABLE_NAME << " set agent_id = '" << agent_id - << "', name = '" << name - << "' WHERE id=" << id << ";"; - SQLiteDB::inst().exec(os.str(), &selecter, nullptr); - } - modified = false; -} - -int Agent::selecter(void* data, int argc, char** argv, char** col_name) -{ - if (data == nullptr) { - return 0; - } - vector* v = reinterpret_cast*>(data); - - if (argc != 3) { - throw logic_error("Wrong \"Agents\" table format"); - } - - string id, name; - Agent a; - - for (int i = 0; i < argc; i++) { - - const char* arg = argv[i] == nullptr ? "" : argv[i]; - - if (a.id_name == col_name[i]) { - convert(a.id, arg); - } else if (a.agent_id_name == col_name[i]) { - convert(a.agent_id, arg); - } else if (a.name_name == col_name[i]) { - convert(a.name, arg); - } - } - - v->push_back(a); - - return 0; -} - - -SelectQuery Agent::get() -{ - SelectQuery q(&selecter); - return q; -} diff --git a/device_core/secserver/agent.h b/device_core/secserver/agent.h deleted file mode 100644 index 13fa28b..0000000 --- a/device_core/secserver/agent.h +++ /dev/null @@ -1,44 +0,0 @@ -#ifndef AGENT_H -#define AGENT_H - -#include "macro.h" -#include "sqlitedb.h" -#include "selectquery.h" - - -class Agent -{ -public: - static const std::string TABLE_NAME; - - Agent(); - Agent(const std::string& id, const std::string& name); - - static void registerModel(); - - static SelectQuery get(); - - const std::string& getId() - { - return agent_id; - } - - const std::string& getName() - { - return name; - } - - void save(); -private: - static int selecter(void* data, int argc, char** argv, char** col_name); - - TABLE_FIELD((long long) id); - - TABLE_FIELD((std::string) agent_id); - - TABLE_FIELD((std::string) name); - - bool modified; -}; - -#endif // AGENT_H diff --git a/device_core/secserver/macro.h b/device_core/secserver/macro.h deleted file mode 100644 index 415ea01..0000000 --- a/device_core/secserver/macro.h +++ /dev/null @@ -1,20 +0,0 @@ -#ifndef MACRO_H -#define MACRO_H - -#define STRINGIZE(x) STRINGIZE2(x) -#define STRINGIZE2(x) #x - -#define REM(x) x -#define EAT(...) -#define PAIR(...) REM __VA_ARGS__ -#define ADD_COMMA(...) (__VA_ARGS__), -#define TYPE_OF_I1(...) TYPE_OF_I2(__VA_ARGS__) -#define TYPE_OF_I2(x, ...) REM x -#define TYPE_OF(x) TYPE_OF_I1(ADD_COMMA x,) -#define ADD_NAME_I(x) x##_name -#define ADD_NAME(x) ADD_NAME_I(x) - -#define TABLE_FIELD(x) PAIR(x);\ -const std::string ADD_NAME(EAT x) = STRINGIZE(EAT x) - -#endif // MACRO_H diff --git a/device_core/secserver/notification_resource.cpp b/device_core/secserver/notification_resource.cpp deleted file mode 100644 index 26c10ee..0000000 --- a/device_core/secserver/notification_resource.cpp +++ /dev/null @@ -1,148 +0,0 @@ -#include "iotivity.h" -#include "securitycontext.h" -#include "notification_resource.h" - -namespace PH = std::placeholders; - -const std::string NotificationResource::RESOURCE_DEFAULT_TITLE = "Title"; -const std::string NotificationResource::RESOURCE_DEFAULT_MESSAGE = "Empty notification"; - -NotificationResource::NotificationResource(): - NotificationResource(true) -{ -} - -NotificationResource::NotificationResource(bool isSecured): - mCode(0), - mTime(std::time(nullptr)), - mTitle(RESOURCE_DEFAULT_TITLE), - mMessage(RESOURCE_DEFAULT_MESSAGE), - mUri(NetworkManager::NOTIFICATION_URI), - mResourceHandle(nullptr), - mIsSecured(isSecured) -{ -} - -void NotificationResource::registerResource() -{ - - EntityHandler resourceCallback = std::bind(&NotificationResource::entityHandler, this, PH::_1); - - // This will internally create and register the resource. - OCStackResult result = OCPlatform::registerResource( - mResourceHandle, - mUri, - NetworkManager::NOTIFICATION_TYPE, - DEFAULT_INTERFACE, - resourceCallback, - OC_DISCOVERABLE | OC_OBSERVABLE | (mIsSecured ? OC_SECURE : 0) - ); - - if (OC_STACK_OK != result) { - cout << "Resource creation was unsuccessful\n"; - } else { - cout << "Notification resource created.\n"; - } -} - -OCResourceHandle NotificationResource::getHandle() -{ - return mResourceHandle; -} - -OCRepresentation NotificationResource::getRepr() -{ - OCRepresentation mRepr; - mRepr.setUri(mUri); - mRepr.setValue("code", mCode); - mRepr.setValue("title", mTitle); - mRepr.setValue("message", mMessage); - mRepr.setValue("time", (int) mTime); - return mRepr; -} - -void NotificationResource::set(int code, std::string title, std::string message) -{ - mTime = std::time(nullptr); - mCode = code; - mMessage = message; - mTitle = title; -} - -void NotificationResource::get(int& code, std::string& title, std::string& message, std::time_t& time) -{ - code = mCode; - title = mTitle; - message = mMessage; - time = mTime; -} - - -//ObservationIds NotificationResource::getObserversList() -//{ -// return mObserversList; -//} - -inline std::shared_ptr -constructRequest(std::shared_ptr request, OCRepresentation rep) -{ - shared_ptr pResponse = make_shared(); - pResponse->setRequestHandle(request->getRequestHandle()); - pResponse->setResourceHandle(request->getResourceHandle()); - pResponse->setResponseResult(OC_EH_OK); - pResponse->setResourceRepresentation(rep, DEFAULT_INTERFACE); - return pResponse; -} - -OCEntityHandlerResult NotificationResource::entityHandler(std::shared_ptr request) -{ - OCEntityHandlerResult ehResult = OC_EH_ERROR; - if (!request) { - std::cout << "Request invalid" << std::endl; - return ehResult; - } - - std::cout << "Handling request from client:\n"; - - // Get the request type and request flag - std::string requestType = request->getRequestType(); - int requestFlag = request->getRequestHandlerFlag(); - - QueryParamsMap queries = request->getQueryParameters(); - - if (requestFlag & RequestHandlerFlag::RequestFlag && requestType == "GET") { - if (OC_STACK_OK == OCPlatform::sendResponse(constructRequest(request, getRepr()))) { - ehResult = OC_EH_OK; - } - } - - if (requestFlag & RequestHandlerFlag::ObserverFlag) { - ObservationInfo observationInfo = request->getObservationInfo(); - - if (ObserveAction::ObserveRegister == observationInfo.action) { - mObserversList.push_back(observationInfo.obsId); - - std::cout << "Client " - << "[" << observationInfo.address - << "]:" << observationInfo.port - << " was registered to observe " - << request->getResourceUri() << "\n"; - } - // Have no idea how to get this flag - ObserveUnregister - else if (ObserveAction::ObserveUnregister == observationInfo.action) { - mObserversList.erase(std::remove( - mObserversList.begin(), - mObserversList.end(), - observationInfo.obsId), - mObserversList.end()); - } - ehResult = OC_EH_OK; - } - - return ehResult; -} - -OCStackResult NotificationResource::notifyAll() -{ - return OCPlatform::notifyAllObservers(mResourceHandle); -} diff --git a/device_core/secserver/notification_resource.h b/device_core/secserver/notification_resource.h deleted file mode 100644 index c40bad0..0000000 --- a/device_core/secserver/notification_resource.h +++ /dev/null @@ -1,78 +0,0 @@ -#ifndef ALERTRESOURCE_H -#define ALERTRESOURCE_H - -#include "OCPlatform.h" - -using namespace OC; -using namespace std; - -/** - * Class that represents /secserver/notification resource. - */ -class NotificationResource -{ -public: - -private: - static const std::string RESOURCE_DEFAULT_TITLE; - static const std::string RESOURCE_DEFAULT_MESSAGE; - - int mCode; - std::time_t mTime; - std::string mTitle; - std::string mMessage; - std::string mUri; - - OCResourceHandle mResourceHandle; - ObservationIds mObserversList; - bool mIsSecured; - -public: - /** - * Constructor - * - * @param dbHandler database object for authentication - */ - NotificationResource(); - - /** - * Constructor - * - * @param dbHandler database object for authentication - * @param isSecure flag indicates that resource is secured - */ - NotificationResource(bool isSecure); - - /** - * Register resource to make IOTivity clients to find it - */ - void registerResource(); - - /** - * Getter for resource mResourceHandle - * - * @return mResourceHandle object - */ - OCResourceHandle getHandle(); - - /** - * Gets the updated representation. - * - * @return representation object - */ - OCRepresentation getRepr(); - - /** - * Updates internal fields of resource. - */ - void set(int code, std::string title, std::string message); - - void get(int& code, std::string& title, std::string& message, std::time_t& time); - - OCStackResult notifyAll(); - -private: - OCEntityHandlerResult entityHandler(std::shared_ptr request); -}; - -#endif // ALERTRESOURCE_H diff --git a/device_core/secserver/policy.cpp b/device_core/secserver/policy.cpp deleted file mode 100644 index 6762f71..0000000 --- a/device_core/secserver/policy.cpp +++ /dev/null @@ -1,132 +0,0 @@ -#include "sqlitedb.h" -#include "policy.h" -#include "macro.h" -#include - -using namespace std; - -Policy::Policy() - : pk(-1) - , did("") - , agent("") - , policy("") - , modified(false) -{ - -} - -Policy::Policy(const string& id, const string& agent, const string& policy) - : pk(-1) - , did(id) - , agent(agent) - , policy(policy) - , modified(false) -{ - -} - -void Policy::registerModel() -{ - ostringstream os; - os << "CREATE TABLE IF NOT EXISTS " << Policy::TABLE_NAME - << "(id INTEGER PRIMARY KEY AUTOINCREMENT," - << "did CHAR(36) NOT NULL," - << "agent CHAR(36)," - << "policy TEXT NOT NULL);"; - SQLiteDB::inst().exec(os.str(), &selecter, nullptr); -} - -void Policy::save() -{ - if (pk == -1) { - ostringstream os; - os << "INSERT INTO " << TABLE_NAME << " (did,agent,policy) " - << "VALUES ('" << did << "', '" << agent << "', '" << policy << "');"; - SQLiteDB::inst().exec(os.str(), &selecter, nullptr); - pk = SQLiteDB::inst().last_row_id(); - } else if (modified) { - ostringstream os; - os << "UPDATE " << TABLE_NAME << " set did = '" << did - << "', agent = '" << agent - << "', policy = '" << policy - << "' WHERE id=" << pk << ";"; - SQLiteDB::inst().exec(os.str(), &selecter, nullptr); - } - modified = false; -} - -SelectQuery Policy::get() -{ - SelectQuery q(&selecter); - return q; -} - -void Policy::setDid(const string& new_id) -{ - if (did != new_id) { - did = new_id; - modified = true; - } -} - -void Policy::setAgent(const string& new_agent) -{ - if (agent != new_agent) { - agent = new_agent; - modified = true; - } -} - -void Policy::setPolicy(const string& new_policy) -{ - if (policy != new_policy) { - policy = new_policy; - modified = true; - } -} - -int Policy::selecter(void* data, int argc, char** argv, char** col_name) -{ - if (data == nullptr) { - return 0; - } - vector* v = reinterpret_cast*>(data); - - if (argc != 4) { - throw logic_error("Wrong \"Policy\" table format"); - } - - Policy r; - - for (int i = 0; i < argc; i++) { - - const char* arg = argv[i] == nullptr ? "" : argv[i]; - - if (r.pk_name == col_name[i]) { - r.pk = stol(arg); - } else if (r.did_name == col_name[i]) { - r.did = arg; - } else if (r.agent_name == col_name[i]) { - r.agent = arg; - } else if (r.policy_name == col_name[i]) { - r.policy = arg; - } else { - throw logic_error(string{"Unknown column name: "} + col_name[i]); - } - } - - v->push_back(r); - - return 0; -} - -const string Policy::TABLE_NAME{STRINGIZE(Policy) "s"}; - -ostream& operator << (ostream& os, const Policy& r) -{ - os << "[Policy]" << endl - << "\tdid: " << r.did << endl - << "\tagent: " << r.agent << endl - << "\tpolicy: " << r.policy; - return os; -} diff --git a/device_core/secserver/policy.h b/device_core/secserver/policy.h deleted file mode 100644 index 83a315f..0000000 --- a/device_core/secserver/policy.h +++ /dev/null @@ -1,59 +0,0 @@ -#ifndef POLICY_H -#define POLICY_H - -#include "selectquery.h" - -class Policy -{ -public: - static const std::string TABLE_NAME; - - Policy(); - - Policy(const std::string& id, const std::string& agent, const std::string& policy); - - static void registerModel(); - - void save(); - - static SelectQuery get(); - - void setDid(const std::string& new_id); - - void setAgent(const std::string& new_id); - - void setPolicy(const std::string& new_name); - - const std::string& getDid() const - { - return did; - } - - const std::string& getAgent() const - { - return agent; - } - - const std::string& getPolicy() const - { - return policy; - } - - friend std::ostream& operator << (std::ostream&, const Policy&); - -private: - static int selecter(void* data, int argc, char** argv, char** col_name); - - long long pk; - std::string did; - std::string agent; - std::string policy; - bool modified; - - const std::string pk_name{"id"}; - const std::string did_name{"did"}; - const std::string agent_name{"agent"}; - const std::string policy_name{"policy"}; -}; - -#endif // POLICY_H diff --git a/device_core/secserver/policy_resource.cpp b/device_core/secserver/policy_resource.cpp deleted file mode 100644 index 7589574..0000000 --- a/device_core/secserver/policy_resource.cpp +++ /dev/null @@ -1,298 +0,0 @@ -/** - * @brief Server policy reasource - * @date Created 19.05.2017 - * @author Created 2017 in Samsung Ukraine R&D Center (SURC) under a contract - * between LLC "Samsung Electronics Ukraine Company" (Kiev, Ukraine) - * and "Samsung Electronics Co", Ltd (Seoul, Republic of Korea). - * Copyright: (c) Samsung Electronics Co, Ltd 2017. All rights reserved. - * @author Mail to: Dmytro Lomtev, d.lomtev@samsung.com - */ - -#include -#include -#include -#include "OCPlatform.h" -#include "OCApi.h" -#include "policy_resource.h" -#include "sqlitedb.h" -#include "policy.h" -#include -#include -#include -#include "agent.h" - -using namespace OC; -using namespace std; -namespace PH = std::placeholders; - - -PolicyResource::PolicyResource() - : policy_uri("/a/policy"), resource_handle(nullptr) -{ - policy_rep.setValue("policy", ""); - Policy::registerModel(); - Agent::registerModel(); - Agent ms{"3574462a-7efa-9449-4d9f-488734c79c0a", "Microsoft agent"}; - ms.save(); - Agent sm{"b4298b09-123d-d76f-cf23-9015f54fddd7", "Samsung agent"}; - sm.save(); - Agent ibm{"7e24e062-36d6-df90-f10b-99e3f7151fc6", "IBM agent"}; - ibm.save(); - Policy p("0627b5e6-4519-42e1-bef1-55ee794de75c", "123", "bla-bla-bla policy!!!"); - p.save(); - Policy p2("db6d4ec3-ff0f-4f5b-915c-03762f6fd931", "", "policy for test device"); - p2.save(); -} - -void PolicyResource::registerResource() -{ - string resourceTypeName = "core.policy"; - - uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE; - - EntityHandler cb = std::bind(&PolicyResource::entityHandler, this, PH::_1); - - OCStackResult result = OCPlatform::registerResource( - resource_handle, policy_uri, resourceTypeName, - DEFAULT_INTERFACE, cb, resourceProperty); - - if (OC_STACK_OK != result) { - cout << "Policy resource creation was unsuccessful\n"; - } else { - cout << "Policy resource created\n"; - } -} - -OCResourceHandle PolicyResource::getHandle() -{ - return resource_handle; -} - -OCRepresentation PolicyResource::get(const std::string& agent, const std::string& policy) -{ - policy_rep.setValue("agent", agent); - policy_rep.setValue("policy", policy); - return policy_rep; -} - -OCRepresentation PolicyResource::get(const QueryParamsMap& params) -{ - cout << "IN > PolicyResource::get(const QueryParamsMap& params)" << endl; - std::string agent_id{"user"}; - std::string policy; - - std::cout << "Policy query parameters:" << std::endl; - for (auto q : params) { - std::cout << q.first << ": " << q.second << std::endl; - } - - - auto it = params.find("agent"); - - if (it != params.cend()) { - agent_id = it->second; - } - - if (agent_id == "list") { - auto agents = Agent::get().all(); - - Json::Value root; - - for (auto agent : agents) { - Json::Value jagent; - jagent["name"] = agent.getName(); - jagent["id"] = agent.getId(); - root.append(jagent); - } - policy = root.toStyledString(); - } else { - auto query = Policy::get(); - - auto it = params.find("did"); - - if (it != params.cend()) { - query.filter("did", it->second); - } - - query.filter("agent", agent_id); - - auto records = query.all(); - - if (!records.empty()) { - agent_id = records[0].getAgent(); - policy = records[0].getPolicy(); - std::cout << "Get: policy found: " << records[0] << std::endl; - } else { - std::cout << "Get: policy not found" << std::endl; - // Create default - if (agent_id == "user") { - policy = "[{\"group\":\"tv-extension\",\"policies\":[{\"name\":\"usb\",\"state\":1,\"items\":[]},{\"name\":\"screen-capture\",\"state\":1,\"items\":[]},{\"name\":\"bluetooth\",\"state\":1,\"items\":[]},{\"name\":\"iptables\",\"state\":0,\"items\":[\"127.0.0.0/24|UDP|10-1024\",\"1.1.1.1|TCP|80,443\"]}]}]"; - } else if (agent_id == "3574462a-7efa-9449-4d9f-488734c79c0a") { - policy = "[{\"group\":\"tv-extension\",\"policies\":[{\"name\":\"usb\",\"state\":1,\"items\":[]},{\"name\":\"screen-capture\",\"state\":1,\"items\":[]},{\"name\":\"bluetooth\",\"state\":1,\"items\":[]},{\"name\":\"iptables\",\"state\":0,\"items\":[\"8.8.8.8\"]}]}]"; - } else { - policy = "[{\"group\":\"tv-extension\",\"policies\":[{\"name\":\"usb\",\"state\":1,\"items\":[]},{\"name\":\"screen-capture\",\"state\":1,\"items\":[]},{\"name\":\"bluetooth\",\"state\":1,\"items\":[]},{\"name\":\"iptables\",\"state\":0,\"items\":[]}]}]"; - } - } - } - - policy_rep.setValue("agent", agent_id); - policy_rep.setValue("policy", policy); - return policy_rep; -} - -OCEntityHandlerResult PolicyResource::entityHandler(std::shared_ptr request) -{ - OCEntityHandlerResult ehResult = OC_EH_ERROR; - - try { - - if (request) { - std::string requestType = request->getRequestType(); - int requestFlag = request->getRequestHandlerFlag(); - QueryParamsMap queries = request->getQueryParameters(); - std::string& did = queries["did"]; - std::string& route = queries["route"]; - std::string& agent_id = queries["agent"]; - if (agent_id.empty()) { - agent_id = "user"; - } - - std::cout << "Policy request: " << requestType << std::endl; - std::cout << "\t\tdid: " << did << std::endl; - std::cout << "\t\troute : " << route << std::endl; - std::cout << "\t\tagent: " << agent_id << std::endl; - - if (requestFlag & RequestHandlerFlag::RequestFlag) { - - auto pResponse = make_shared(); - pResponse->setRequestHandle(request->getRequestHandle()); - pResponse->setResourceHandle(request->getResourceHandle()); - - if (requestType == "GET") { - pResponse->setResponseResult(OC_EH_OK); - pResponse->setResourceRepresentation(get(queries)); - if (OC_STACK_OK == OCPlatform::sendResponse(pResponse)) { - ehResult = OC_EH_OK; - } - - } else if (requestType == "PUT") { - - if (OC_STACK_OK == OCPlatform::sendResponse(pResponse)) { - ehResult = OC_EH_OK; - } - } else if (requestType == "POST") { - const auto& rep = request->getResourceRepresentation(); - std::string policy_enforcement; - - int rcode = 400; - - if (!did.empty() && rep.getValue("policy", policy_enforcement)) { - rcode = 200; - Json::Value root; - Json::Reader reader; - - std::cout << "[Policy] by " << agent_id << std::endl << policy_enforcement << std::endl; - - if (!reader.parse(policy_enforcement, root)) { - std::cout << "[ERROR] Wrong policy format" << std::endl; - rcode = 400; - } else { - if (!agent_id.empty() && agent_id != "list" && agent_id != "user") { - auto agents_v = Agent::get().filter("agent_id", agent_id).all(); - if (agents_v.empty()) { - if (OC_STACK_OK == OCPlatform::sendResponse(pResponse)) { - ehResult = OC_EH_OK; - } - - std::cout << "[ERROR] Agent: " << agent_id << " not found" << std::endl; - - return ehResult; - } - } - - auto policies = Policy::get().filter("did", did).filter("agent", agent_id).all(); - - if (policies.empty()) { - std::cout << "Policy for new device " << did << std::endl; - Policy p(did, agent_id, policy_enforcement); - p.save(); - } else { - std::cout << "Update policy for device " << did << std::endl; - policies[0].setPolicy(policy_enforcement); - policies[0].save(); - } - - unique_lock lock(obs_mutex); - - auto it = observers.find(route.empty() ? did : route); - - if (it != observers.end()) { - cout << "Found observer " << int(it->second) << endl; - ObservationIds obs; - obs.push_back(it->second); - - auto notify_response = make_shared(); - notify_response->setRequestHandle(request->getRequestHandle()); - notify_response->setResourceHandle(request->getResourceHandle()); - OCRepresentation rep; - rep.setValue("agent", agent_id); - rep.setValue("policy", policy_enforcement); - rep.setValue("did", did); - - notify_response->setResourceRepresentation(rep); - notify_response->setResponseResult(OC_EH_OK); - - OCPlatform::notifyListOfObservers(resource_handle, obs, notify_response); - } else { - cout << "Observer not found" << endl; - } - - pResponse->setResponseResult(OC_EH_OK); - } - } - - - if (OC_STACK_OK == OCPlatform::sendResponse(pResponse)) { - ehResult = OC_EH_OK; - } - } else if (requestType == "DELETE") { - } - } - - if (requestFlag & RequestHandlerFlag::ObserverFlag) { - ObservationInfo observationInfo = request->getObservationInfo(); - - unique_lock lock(obs_mutex); - - if (ObserveAction::ObserveRegister == observationInfo.action) { - observers[did] = observationInfo.obsId; - - std::cout << "Client " - << "[" << observationInfo.address - << "]:" << observationInfo.port - << "?di=" << did - << " was registered to observe " - << request->getResourceUri() << "\nOserve ID " << int(observationInfo.obsId) << endl; - } else if (ObserveAction::ObserveUnregister == observationInfo.action) { - cout << "Observe unregister request ID " << int(observationInfo.obsId) << endl; - auto it = observers.find(did); - - if (it != observers.end()) { - cout << "Observer found. Unregister" << endl; - observers.erase(it); - } else { - cout << "Observer not found." << endl; - } - } - ehResult = OC_EH_OK; - } - } else { - std::cout << "Invalid request" << std::endl; - } - } catch (std::exception& e) { - std::cout << "entityHandler exception: " << e.what() << std::endl; - ehResult = OC_EH_ERROR; - } - - return ehResult; -} diff --git a/device_core/secserver/policy_resource.h b/device_core/secserver/policy_resource.h deleted file mode 100644 index 65620c7..0000000 --- a/device_core/secserver/policy_resource.h +++ /dev/null @@ -1,69 +0,0 @@ -#ifndef POLICYRESOURCE_H -#define POLICYRESOURCE_H -/** - * @brief Server policy reasource - * @date Created 19.05.2017 - * @author Created 2017 in Samsung Ukraine R&D Center (SURC) under a contract - * between LLC "Samsung Electronics Ukraine Company" (Kiev, Ukraine) - * and "Samsung Electronics Co", Ltd (Seoul, Republic of Korea). - * Copyright: (c) Samsung Electronics Co, Ltd 2017. All rights reserved. - * @author Mail to: Dmytro Lomtev, d.lomtev@samsung.com - */ - -#include "OCPlatform.h" -#include "OCApi.h" -#include -#include -#include - - -using namespace OC; - -class PolicyResource -{ -private: - std::string policy_uri; - OCResourceHandle resource_handle; - OCRepresentation policy_rep; - std::map observers; - std::mutex obs_mutex; - -public: - /** - * Constructor - */ - PolicyResource(); - - /** - * Register resource to make IOTivity clients to find it - */ - void registerResource(); - - /** - * Getter for resource handle - * - * @return OCResourceHandle object (used to publish resource on IoT cloud) - */ - OCResourceHandle getHandle(); - - /** - * Gets the updated representation. - * - * @return representation object - */ - OCRepresentation get(const std::string& agent, const std::string& policy); - - /** - * Gets the representation. - * - * @param params [in] Specific request parameters - * @return representation object - */ - OCRepresentation get(const QueryParamsMap& params); - -private: - OCEntityHandlerResult entityHandler(std::shared_ptr request); -}; - - -#endif // POLICYRESOURCE_H diff --git a/device_core/secserver/report.cpp b/device_core/secserver/report.cpp deleted file mode 100644 index 80206b1..0000000 --- a/device_core/secserver/report.cpp +++ /dev/null @@ -1,163 +0,0 @@ -#include "sqlitedb.h" -#include "report.h" -#include "macro.h" -#include - -using namespace std; - -Report::Report() - : pk(-1) - , did("") - , name("") - , date("") - , data("") - , result(0) - , modified(false) -{ - -} - -Report::Report(const string& id, const string& name, const string& date, const string& report, int result) - : pk(-1) - , did(id) - , name(name) - , date(date) - , data(report) - , result(result) - , modified(false) -{ - -} - -void Report::registerModel() -{ - ostringstream os; - os << "CREATE TABLE IF NOT EXISTS " << Report::TABLE_NAME - << "(id INTEGER PRIMARY KEY AUTOINCREMENT," - << "did CHAR(36) NOT NULL," - << "name CHAR(32) NOT NULL," - << "date CHAR(32) NOT NULL," - << "data TEXT NOT NULL," - << "result INTEGER);"; - SQLiteDB::inst().exec(os.str(), &selecter, nullptr); -} - -void Report::save() -{ - if (pk == -1) { - ostringstream os; - os << "INSERT INTO " << TABLE_NAME << " (did,name,date,data,result) " - << "VALUES ('" << did << "', '" << name << "', '" << date << "', '" - << data << "', " << result << ");"; - SQLiteDB::inst().exec(os.str(), &selecter, nullptr); - pk = SQLiteDB::inst().last_row_id(); - } else if (modified) { - ostringstream os; - os << "UPDATE " << TABLE_NAME << " set did = '" << did - << "', name = '" << name - << "', date = '" << date - << "', data = '" << data - << "', result = " << result - << " WHERE id=" << pk << ";"; - SQLiteDB::inst().exec(os.str(), &selecter, nullptr); - } - modified = false; -} - -SelectQuery Report::get() -{ - SelectQuery q(&selecter); - return q; -} - -void Report::setDid(const string& new_id) -{ - if (did != new_id) { - did = new_id; - modified = true; - } -} - -void Report::setName(const string& new_name) -{ - if (name != new_name) { - name = new_name; - modified = true; - } -} - -void Report::setDate(const string& new_date) -{ - if (date != new_date) { - date = new_date; - modified = true; - } -} - -void Report::setData(const string& new_report) -{ - if (data != new_report) { - data = new_report; - modified = true; - } -} - -void Report::setResult(int new_result) -{ - if (result != new_result) { - result = new_result; - modified = true; - } -} - -int Report::selecter(void* data, int argc, char** argv, char** col_name) -{ - if (data == nullptr) { - return 0; - } - vector* v = reinterpret_cast*>(data); - - if (argc != 6) { - throw logic_error("Wrong \"Report\" table format"); - } - - Report r; - - for (int i = 0; i < argc; i++) { - - const char* arg = argv[i] == nullptr ? "" : argv[i]; - - if (r.pk_name == col_name[i]) { - r.pk = stol(arg); - } else if (r.did_name == col_name[i]) { - r.did = arg; - } else if (r.name_name == col_name[i]) { - r.name = arg; - } else if (r.date_name == col_name[i]) { - r.date = arg; - } else if (r.data_name == col_name[i]) { - r.data = arg; - } else if (r.result_name == col_name[i]) { - r.result = stoi(arg); - } else { - throw logic_error(string{"Unknown column name: "} + col_name[i]); - } - } - - v->push_back(r); - - return 0; -} - -const string Report::TABLE_NAME{STRINGIZE(Report) "s"}; - -ostream& operator << (ostream& os, const Report& r) -{ - os << "[Report]" << endl - << "\tdid: " << r.did << endl - << "\tname: " << r.name << endl - << "\tdate: " << r.date << endl - << "\tdata: " << r.data << endl - << "\tresult: " << r.result; - return os; -} diff --git a/device_core/secserver/report.h b/device_core/secserver/report.h deleted file mode 100644 index 66a3531..0000000 --- a/device_core/secserver/report.h +++ /dev/null @@ -1,82 +0,0 @@ -#ifndef REPORT_H -#define REPORT_H - -#include "selectquery.h" - -class Report -{ -public: - static const std::string TABLE_NAME; - - Report(); - - Report(const std::string& id, const std::string& name, const std::string& date, const std::string& data, int result); - - static void registerModel(); - - void save(); - - static SelectQuery get(); - - void detach() - { - pk = -1; - } - - void setDid(const std::string& new_id); - - void setName(const std::string& new_name); - - void setDate(const std::string& new_date); - - void setData(const std::string& new_data); - - void setResult(int new_result); - - const std::string& getDid() const - { - return did; - } - - const std::string& getName() const - { - return name; - } - - const std::string& getDate() const - { - return date; - } - - const std::string& getData() const - { - return data; - } - - int getResult() const - { - return result; - } - - friend std::ostream& operator << (std::ostream&, const Report&); - -private: - static int selecter(void* data, int argc, char** argv, char** col_name); - - long long pk; - std::string did; - std::string name; - std::string date; - std::string data; - int result; - bool modified; - - const std::string pk_name{"id"}; - const std::string did_name{"did"}; - const std::string name_name{"name"}; - const std::string date_name{"date"}; - const std::string data_name{"data"}; - const std::string result_name{"result"}; -}; - -#endif // REPORT_H diff --git a/device_core/secserver/report_resource.cpp b/device_core/secserver/report_resource.cpp deleted file mode 100644 index a25ae73..0000000 --- a/device_core/secserver/report_resource.cpp +++ /dev/null @@ -1,270 +0,0 @@ -/** - * @brief Server report reasource - * @date Created 17.05.2017 - * @author Created 2017 in Samsung Ukraine R&D Center (SURC) under a contract - * between LLC "Samsung Electronics Ukraine Company" (Kiev, Ukraine) - * and "Samsung Electronics Co", Ltd (Seoul, Republic of Korea). - * Copyright: (c) Samsung Electronics Co, Ltd 2017. All rights reserved. - * @author Mail to: Dmytro Lomtev, d.lomtev@samsung.com - */ - -#include -//#include -#include -#include -#include "OCPlatform.h" -#include "OCApi.h" -#include "report_resource.h" -#include "sqlitedb.h" -#include "report.h" -#include -#include -#include - -using namespace OC; -using namespace std; -namespace PH = std::placeholders; - -void sql_test() -{ - try { - Report::registerModel(); - Report r1{"9b5287b3-fe92-46fc-a924-488d2339c2ba", "sim", "17-05-2017 05:32:30", "Alert! Alles caput!", 3}; - Report r2{"11223344-fe92-46fc-a924-488d2339c2ba", "alert", "17-05-2017 05:32:30", "Deus vult", 77}; - Report r3{"00000000-fe92-46fc-a924-488d2339c2ba", "sim", "17-05-2017 05:32:30", "Spartaaaaa!", 0}; - r1.save(); - r2.save(); - r3.save(); - - auto v = Report::get().filter("name", "sim").all(); - - cout << "SELECT 1 returned " << v.size() << " records" << endl; - int i = 1; - - for (auto rec : v) { - cout << "#" << i++ << endl << rec << endl; - } - - v = Report::get().all(); - - cout << "SELECT 2 returned " << v.size() << " records" << endl; - i = 1; - - for (auto rec : v) { - cout << "#" << i++ << endl << rec << endl; - } - - v = Report::get().filter("did", "00000000-fe92-46fc-a924-488d2339c2ba").filter("name", "sim").filter("result", 0).all(); - - cout << "SELECT 3 returned " << v.size() << " records" << endl; - i = 1; - - for (auto rec : v) { - cout << "#" << i++ << endl << rec << endl; - } - } catch (exception& e) { - cout << "SQLite test Exception: " << e.what() << endl; - } -} - - -ReportResource::ReportResource() - : m_reportUri("/a/report"), m_resourceHandle(nullptr), m_notifResource(nullptr) -{ - m_reportRep.setValue("report", ""); - Report::registerModel(); - Report r1{"9b5287b3-fe92-46fc-a924-488d2339c2ba", "sim", "17-05-2017 05:32:30", "{\"message\":\"Alert! Alles caput!\"}", 3}; - Report r2{"11223344-fe92-46fc-a924-488d2339c2ba", "alert", "17-05-2017 05:32:30", "{\"message\":\"Deus vult\"}", 77}; - Report r3{"9b5287b3-fe92-46fc-a924-488d2339c2ba", "smart-security", "17-05-2017 05:32:30", "{\"message\":\"Spartaaaaa!\"}", 0}; - - r1.save(); - r2.save(); - r3.save(); - - r1.setDid("0627b5e6-4519-42e1-bef1-55ee794de75c"); - r2.setDid("0627b5e6-4519-42e1-bef1-55ee794de75c"); - r3.setDid("0627b5e6-4519-42e1-bef1-55ee794de75c"); - r1.detach(); - r2.detach(); - r3.detach(); - - r1.save(); - r2.save(); - r3.save(); -} - -void ReportResource::registerResource() -{ - string resourceTypeName = "core.security"; - - uint8_t resourceProperty = OC_DISCOVERABLE | OC_OBSERVABLE; - - EntityHandler cb = std::bind(&ReportResource::entityHandler, this, PH::_1); - - OCStackResult result = OCPlatform::registerResource( - m_resourceHandle, m_reportUri, resourceTypeName, - DEFAULT_INTERFACE, cb, resourceProperty); - - if (OC_STACK_OK != result) { - cout << "Security Resource creation was unsuccessful\n"; - } else { - cout << "Report resource created\n"; - } -} - -OCResourceHandle ReportResource::getHandle() -{ - return m_resourceHandle; -} - -Json::Value reportAsJson(const Report& r) -{ - Json::Value report; - report["did"] = r.getDid(); - report["name"] = r.getName(); - report["date"] = r.getDate(); - Json::Reader reader; - Json::Value data; - reader.parse(r.getData(), data); - report["data"] = data; - report["result"] = r.getResult(); - return report; -} - -OCRepresentation ReportResource::get() -{ - return get(QueryParamsMap{}); -} - -OCRepresentation ReportResource::get(const QueryParamsMap& params) -{ - cout << "IN > ReportResource::get(const QueryParamsMap& params)" << endl; - auto query = Report::get(); - - for (auto p : params) { - cout << p.first << ": " << p.second << endl; - query.filter(p.first, p.second); - } - - auto records = query.all(); - - Json::Value root; - - for (auto r : records) { - root.append(reportAsJson(r)); - } - - if (records.empty()) { - std::string rpt = "[]"; - m_reportRep.setValue("report", rpt); - } else { - m_reportRep.setValue("report", root.toStyledString()); - } - - return m_reportRep; -} - -OCEntityHandlerResult ReportResource::entityHandler(std::shared_ptr request) -{ - OCEntityHandlerResult ehResult = OC_EH_ERROR; - - if (request) { - std::string requestType = request->getRequestType(); - int requestFlag = request->getRequestHandlerFlag(); - - if (requestFlag & RequestHandlerFlag::RequestFlag) { - auto pResponse = make_shared(); - pResponse->setRequestHandle(request->getRequestHandle()); - pResponse->setResourceHandle(request->getResourceHandle()); - - if (requestType == "GET") { - QueryParamsMap queries = request->getQueryParameters(); - pResponse->setResponseResult(OC_EH_OK); - pResponse->setResourceRepresentation(get(queries)); - if (OC_STACK_OK == OCPlatform::sendResponse(pResponse)) { - ehResult = OC_EH_OK; - } - - } else if (requestType == "PUT") { - - if (OC_STACK_OK == OCPlatform::sendResponse(pResponse)) { - ehResult = OC_EH_OK; - } - } else if (requestType == "POST") { - const auto& rep = request->getResourceRepresentation(); - std::string new_report; - - int rcode = 400; - - if (rep.getValue("report", new_report)) { - rcode = 200; - Json::Value root; - Json::Reader reader; - - std::cout << "[Report]" << std::endl << new_report << std::endl; - - if (!reader.parse(new_report, root)) { - std::cout << "[ERROR] Wrong report format" << std::endl; - rcode = 400; - } else { - std::string did = root["did"].asString(); - std::string date = root["date"].asString(); - std::string name = root["name"].asString(); - int result = root["result"].asInt(); - Json::FastWriter writer; -// std::string data = root["data"].toStyledString(); - std::string data = writer.write(root["data"]); - - try { - auto reports = Report::get().filter("did", did).filter("name", name).all(); - - if (reports.empty()) { - Report r{did, name, date, data, result}; -// std::cout << "Report model: " << data << endl; - r.save(); - } else { - reports[0].setDate(date); - reports[0].setData(data); - reports[0].setResult(result); - reports[0].save(); - } - } catch (std::exception& e) { - std::cout << "DB save error: " << e.what() << std::endl; - } - - // Reaction on suspicious activity to check notification - try { - if (m_notifResource != nullptr && name.find("Suspicious") != std::string::npos) { - std::string dataMessage = root["data"]["message"].asString(); - m_notifResource->set(0, name, dataMessage); - m_notifResource->notifyAll(); - } - } catch (std::exception& e) { - std::cout << "Reaction on suspicious activity: " << e.what() << std::endl; - } - - pResponse->setResponseResult(OC_EH_OK); - } - - - } - - - - if (OC_STACK_OK == OCPlatform::sendResponse(pResponse)) { - ehResult = OC_EH_OK; - } - } else if (requestType == "DELETE") { - } - } - } else { - std::cout << "Invalid request" << std::endl; - } - - return ehResult; -} - -void ReportResource::setNotificationResource(NotificationResource* notifResource) -{ - m_notifResource = notifResource; -} diff --git a/device_core/secserver/report_resource.h b/device_core/secserver/report_resource.h deleted file mode 100644 index 4f7a9f2..0000000 --- a/device_core/secserver/report_resource.h +++ /dev/null @@ -1,71 +0,0 @@ -/** - * @brief Server report reasource - * @date Created 17.05.2017 - * @author Created 2017 in Samsung Ukraine R&D Center (SURC) under a contract - * between LLC "Samsung Electronics Ukraine Company" (Kiev, Ukraine) - * and "Samsung Electronics Co", Ltd (Seoul, Republic of Korea). - * Copyright: (c) Samsung Electronics Co, Ltd 2017. All rights reserved. - * @author Mail to: Dmytro Lomtev, d.lomtev@samsung.com - */ - -#include "OCPlatform.h" -#include "OCApi.h" -#include - -#include "notification_resource.h" - -using namespace OC; - -void sql_test(); - -class ReportResource -{ -private: - std::string m_reportUri; - OCResourceHandle m_resourceHandle; - OCRepresentation m_reportRep; - NotificationResource* m_notifResource; - -public: - /** - * Constructor - */ - ReportResource(); - - /** - * Register resource to make IOTivity clients to find it - */ - void registerResource(); - - /** - * Getter for resource handle - * - * @return OCResourceHandle object (used to publish resource on IoT cloud) - */ - OCResourceHandle getHandle(); - - /** - * Gets the updated representation. - * - * @return representation object - */ - OCRepresentation get(); - - /** - * Gets the representation. - * - * @param params [in] Specific request parameters - * @return representation object - */ - OCRepresentation get(const QueryParamsMap& params); - - /** - * @brief setNotificationResource method to set NotificationResource. - * Used to send notification then reports contain suspicious data. - * @param notifResource link to NotificationResource object - */ - void setNotificationResource(NotificationResource* notifResource); - -private: - OCEntityHandlerResult entityHandler(std::shared_ptr request); -}; diff --git a/device_core/secserver/secserver.cpp b/device_core/secserver/secserver.cpp deleted file mode 100644 index fc6550b..0000000 --- a/device_core/secserver/secserver.cpp +++ /dev/null @@ -1,257 +0,0 @@ -#include -#include -#include - -#include "RDClient.h" - -#include -#include -#include "iotivity.h" -#include "notification_resource.h" -#include "report_resource.h" -#include "policy_resource.h" - -#include "sqlitedb.h" -#include "report.h" -#include "policy.h" -#include "macro.h" -#include -#include -#include - -#include "mqclient.h" - -using namespace OC; -using namespace NetworkManager; -using namespace std; - -condition_variable g_callbackLock; -static string cloud_ip{"106.125.46.44"}; - -static string getPSPath() -{ - char SVR_DB_FILE_PATH[1000] = {0}; - ssize_t size = readlink("/proc/self/exe", SVR_DB_FILE_PATH, sizeof(SVR_DB_FILE_PATH)); - if (size == 0 || size == sizeof(SVR_DB_FILE_PATH)) { - throw runtime_error("readlink error"); - } - return string(SVR_DB_FILE_PATH) + "_ps.dat"; -} - -void inputNotificationData(int& notifCode, std::string& notifTitle, string& notifMessage, time_t& notifTime) -{ - std::cout << "\n\nPlease enter new notification [Current: " << notifCode - << " \"" << notifTitle << "\" " << " \"" << notifMessage << "\" " << notifTime << "]:\n"; - - string inputLine; - std::getline (std::cin, inputLine); - istringstream iss(inputLine); - - iss >> notifCode; - iss >> notifTitle; - iss >> notifMessage; -} - -void onPublish(const OCRepresentation&, const int& eCode) -{ - cout << "Publish resource response received, code: " << eCode << endl; - - g_callbackLock.notify_all(); -} - -inline void guardErrorCode(OCStackResult resultCode, std::string message) -{ - if (resultCode != OC_STACK_OK) { - throw runtime_error(message + " error:" + std::to_string(resultCode)); - } -} - - -void setDeviceInfo(std::string duid) -{ - OCDeviceInfo devInfoAirConditioner; - OCStringLL deviceType; - OCStringLL deviceModel; - - deviceType.value = (char*)"oic.d.secserver"; - deviceType.next = NULL; - - deviceModel.value = (char*)"1"; - deviceModel.next = NULL; - - std::string name = "secserver " + duid.substr(0, 8); - devInfoAirConditioner.deviceName = (char*)name.c_str(); - devInfoAirConditioner.types = &deviceType; - devInfoAirConditioner.specVersion = NULL; - devInfoAirConditioner.dataModelVersions = &deviceModel; - - guardErrorCode(OC::OCPlatform::registerDeviceInfo(devInfoAirConditioner), "registerDeviceInfo()"); -} - - -void subscribeCB(const HeaderOptions&, - const OCRepresentation& rep, const int eCode, const int sequenceNumber) -{ - try { - std::cout << "MQ recived new report" << std::endl; - if (eCode == OC_STACK_OK && sequenceNumber <= MAX_SEQUENCE_NUMBER) { - std::string new_report; - if (rep.getValue("report", new_report)) { - Json::Value root; - Json::Reader reader; - std::cout << "MQ [Report]" << std::endl << new_report << std::endl; - if (reader.parse(new_report, root)) { - std::string did = root["did"].asString(); - std::string date = root["date"].asString(); - std::string name = root["name"].asString(); - int result = root["result"].asInt(); - Json::FastWriter writer; - std::string data = writer.write(root["data"]); - - try { - auto reports = Report::get().filter("did", did).filter("name", name).all(); - if (reports.empty()) { - Report r{did, name, date, data, result}; - r.save(); - } else { - reports[0].setDate(date); - reports[0].setData(data); - reports[0].setResult(result); - reports[0].save(); - } - } catch (std::exception& e) { - std::cout << "DB save error: " << e.what() << std::endl; - } - } else { - std::cout << "[ERROR] Wrong report format" << std::endl; - } - - - } - } else { - if (eCode != OC_STACK_OK) { - exit(-1); - } - } - } catch (exception& e) { - cout << "Exception: " << e.what() << " in onObserve" << endl; - } -} - -void policyCB(const HeaderOptions&, - const OCRepresentation& rep, const int eCode, const int sequenceNumber) -{ - try { - std::cout << "MQ recived new policy" << std::endl; - if (eCode == OC_STACK_OK && sequenceNumber <= MAX_SEQUENCE_NUMBER) { - std::string did; - std::string policy; - if (rep.getValue("did", did) && rep.getValue("policy", policy)) { - try { - auto policies = Policy::get().filter("did", did).all(); - if (policies.empty()) { - Policy p{did, "", policy}; - p.save(); - } else { - policies[0].setAgent(""); - policies[0].setPolicy(policy); - policies[0].save(); - } - } catch (std::exception& e) { - std::cout << "DB save error: " << e.what() << std::endl; - } - } - } else { - if (eCode != OC_STACK_OK) { - exit(-1); - } - } - } catch (exception& e) { - cout << "Exception: " << e.what() << " in onObserve" << endl; - } -} - -static void mainLoop() -{ - std::string auth_provider("samsung"); - std::string access_token("AuthCode_A"); - std::string host("coap+tcp://" + cloud_ip + ":5683"); - - auto iot = IoTivity::getInstance(); -// iot->setPersistentStoragePath(getPSPath()); - iot->signUp(host, auth_provider, access_token); - std::string duid = iot->getDeviceID(); - cout << "secserver lounched: " << duid << endl << flush; - - mutex blocker; - unique_lock lock(blocker); - - ResourceHandles resourceHandles; - setDeviceInfo(duid); - guardErrorCode(RDClient::Instance().publishResourceToRD(host, OCConnectivityType::CT_ADAPTER_TCP, resourceHandles, - &onPublish), "Default publishResourceToRD()"); - g_callbackLock.wait(lock); - - cout << "Device info publish success" << endl << flush; - - bool isSecured = false; - NotificationResource notifResource(isSecured); - notifResource.registerResource(); - ReportResource reportResouce; - reportResouce.registerResource(); - reportResouce.setNotificationResource(¬ifResource); - - iot->getMqHandler()->subscribe("/srv/report", &subscribeCB); - cout << "Subscribed on topic \"/srv/report\"" << endl << flush; - iot->getMqHandler()->subscribe("/srv/policy", &policyCB); - cout << "Subscribed on topic \"/srv/policy\"" << endl << flush; - - PolicyResource policyResource; - policyResource.registerResource(); - - resourceHandles.push_back(notifResource.getHandle()); - resourceHandles.push_back(reportResouce.getHandle()); - resourceHandles.push_back(policyResource.getHandle()); - - guardErrorCode(RDClient::Instance().publishResourceToRD(host, OCConnectivityType::CT_ADAPTER_TCP, resourceHandles, - &onPublish), "Server resources publishResourceToRD()"); - g_callbackLock.wait(lock); - - MqClient mqHandler(host); - - cout << "Server resources publish success" << endl << flush; - - int notifCode; - string notifTitle; - string notifMessage; - time_t notifTime; - - while (true) { - notifResource.get(notifCode, notifTitle, notifMessage, notifTime); - inputNotificationData(notifCode, notifTitle, notifMessage, notifTime); - - cout << "Sending notification:" << notifCode << " " << notifMessage << "\n"; - - notifResource.set(notifCode, notifTitle, notifMessage); - - mqHandler.publish("/00000000-0000-0000-0000-000000000000/notification", notifResource.getRepr()); - } -} - -int main(int argc, char* argv[]) -{ - if (argc < 2) { - cout << "[WARNING] IoT Cloud IP not specified" << endl - << " - Running with default: " << cloud_ip << endl << endl; - } else { - cloud_ip = argv[1]; - } - - try { - mainLoop(); - } catch (OCException& e) { - std::cout << "OCException: " << e.what() << endl; - } - - return 0; -} diff --git a/device_core/secserver/selectquery.h b/device_core/secserver/selectquery.h deleted file mode 100644 index 91cbcee..0000000 --- a/device_core/secserver/selectquery.h +++ /dev/null @@ -1,61 +0,0 @@ -#ifndef SELECTQUERY_H -#define SELECTQUERY_H - -#include -#include -#include -#include - -template -class SelectQuery -{ -public: - SelectQuery(sqlite_exec_callback cb): callback(cb) {} - - template - SelectQuery& filter(const std::string& name, const R& value) - { - filter(name, value, std::is_integral()); - return *this; - } - - std::vector all() - { - std::vector v; - std::ostringstream os; - os << "SELECT * FROM " << T::TABLE_NAME; - - if (!filters.empty()) { - auto it = filters.cbegin(); - os << " WHERE " << *it; - - while (++it != filters.cend()) { - os << " AND " << *it; - } - } - - os << ';'; - - SQLiteDB::inst().exec(os.str(), callback, &v); - return v; - } - -private: - template - void filter(const std::string& name, const R& value, std::true_type) - { - filters.emplace_back(name + " = " + std::to_string(value)); - } - - template - void filter(const std::string& name, const R& value, std::false_type) - { - filters.emplace_back(name + " = '" + std::string{value} + "'"); - } - - - sqlite_exec_callback callback; - std::vector filters; -}; - -#endif // SELECTQUERY_H diff --git a/device_core/secserver/sqlitedb.cpp b/device_core/secserver/sqlitedb.cpp deleted file mode 100644 index 8b0d829..0000000 --- a/device_core/secserver/sqlitedb.cpp +++ /dev/null @@ -1,46 +0,0 @@ -#include "sqlitedb.h" -#include -#include - -using namespace std; - -SQLiteDB::~SQLiteDB() -{ - sqlite3_close(db); -} - -void SQLiteDB::exec(const string& SQL, sqlite_exec_callback cb, void* data) -{ - char* error_msg; - int ecode = sqlite3_exec(db, SQL.c_str(), cb, data, &error_msg); - - if (ecode != SQLITE_OK) { - string serr{error_msg}; - sqlite3_free(error_msg); - throw runtime_error(serr.c_str()); - } -} - -SQLiteDB& SQLiteDB::inst() -{ - if (instance.db == nullptr) { - int ecode = sqlite3_open(":memory:", &instance.db); - if (ecode != SQLITE_OK) { - throw runtime_error("Can not create memory data base"); - } - } - - return instance; -} - -long long SQLiteDB::last_row_id() -{ - return sqlite3_last_insert_rowid(db); -} - -SQLiteDB::SQLiteDB() : db(nullptr) -{ - -} - -SQLiteDB SQLiteDB::instance; diff --git a/device_core/secserver/sqlitedb.h b/device_core/secserver/sqlitedb.h deleted file mode 100644 index d02f86b..0000000 --- a/device_core/secserver/sqlitedb.h +++ /dev/null @@ -1,26 +0,0 @@ -#ifndef SQLITEDB_H -#define SQLITEDB_H - -#include - -typedef int (*sqlite_exec_callback)(void* user_data, int argc, char** argv, char** col_name); -struct sqlite3; - -class SQLiteDB -{ -public: - ~SQLiteDB(); - - void exec(const std::string& SQL, sqlite_exec_callback cb, void* data); - - static SQLiteDB& inst(); - - long long last_row_id(); - -private: - SQLiteDB(); - sqlite3* db; - static SQLiteDB instance; -}; - -#endif // SQLITEDB_H -- 2.7.4