[RE] Added Secure Resource Linux Sample Apps to the RE Layer
authorJay Sharma <jay.sharma@samsung.com>
Fri, 4 Dec 2015 13:42:04 +0000 (19:12 +0530)
committerMadan Lanka <lanka.madan@samsung.com>
Mon, 7 Dec 2015 06:15:33 +0000 (06:15 +0000)
- Added API to RCSResourceObject to support OC_SECURE property for
  resource creation.
- Added Secure Resource Linux Applications.

Change-Id: I97fb97387c1c03c44a6a5ff123729107bd28681d
Signed-off-by: Jay Sharma <jay.sharma@samsung.com>
Reviewed-on: https://gerrit.iotivity.org/gerrit/4399
Tested-by: jenkins-iotivity <jenkins-iotivity@opendaylight.org>
Reviewed-by: Madan Lanka <lanka.madan@samsung.com>
service/resource-encapsulation/examples/linux/SConscript
service/resource-encapsulation/examples/linux/secureResourceExample/README [new file with mode: 0644]
service/resource-encapsulation/examples/linux/secureResourceExample/SConscript [new file with mode: 0644]
service/resource-encapsulation/examples/linux/secureResourceExample/SampleAuthorizedClient.cpp [new file with mode: 0644]
service/resource-encapsulation/examples/linux/secureResourceExample/SampleSecureServer.cpp [new file with mode: 0644]
service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_client.json [new file with mode: 0644]
service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_server.json [new file with mode: 0644]
service/resource-encapsulation/include/RCSResourceObject.h
service/resource-encapsulation/src/serverBuilder/src/RCSResourceObject.cpp

index 12fa444..e6d52bc 100644 (file)
@@ -32,11 +32,11 @@ sample_env = lib_env.Clone()
 sample_env.AppendUnique(CXXFLAGS = ['-Wall', '-std=c++0x'])
 sample_env.AppendUnique(LIBS = [
     'rcs_common',
-    'oc', 
-    'octbstack', 
-    'oc_logger', 
-    'connectivity_abstraction', 
-    'coap', 
+    'oc',
+    'octbstack',
+    'oc_logger',
+    'connectivity_abstraction',
+    'coap',
     'pthread'
     ])
 sample_env.AppendUnique(CPPPATH = ['../../include'])
@@ -70,3 +70,9 @@ nestedAttributesServer = server_env.Program('nestedAttributesServer', 'NestedAtt
 
 server_env.InstallTarget(sampleResourceServer, 'sampleResourceServer')
 server_env.InstallTarget(nestedAttributesServer, 'nestedAttributesServer')
+
+######################################################################
+# ##### Build the RE Secure Resource Example #####
+######################################################################
+if env.get('SECURED') == '1':
+       SConscript('secureResourceExample/SConscript')
diff --git a/service/resource-encapsulation/examples/linux/secureResourceExample/README b/service/resource-encapsulation/examples/linux/secureResourceExample/README
new file mode 100644 (file)
index 0000000..d1401a6
--- /dev/null
@@ -0,0 +1,75 @@
+### Build Instruction ###
+
+1) build Iotivity code for linux platform
+
+   $ scons SECURED=1
+
+NOTE:
+   To build in debug mode
+   $ scons SECURED=1 RELEASE=0
+
+### Sample Apps Running Instructions ###
+
+1) Change directory to:
+
+   ~/iotivity/out/linux/{TARGET_ARCH}/{MODE}/service/resource-encapsulation/examples/linux/secureResourceExample
+
+   {TARGET_ARCH} is your machine Architecture. For Example : x86
+   {MODE} is build mode i.e. RELEASE mode or DEBUG mode.
+
+2) Set the Library Path
+
+   $ export LD_LIBRARY_PATH=../../../../../../{MODE}
+
+3) Run the sample Resource Server -> ./sampleSecureServer
+   Follow the instructions on the screen to create a secure resource.
+
+4) Open a new terminal and repeat the step (1) & (2).
+
+5) Run the Sample client -> ./sampleAutorizedClient
+   Follow the instructions on the screen to test the client functionalities.
+
+### Varification of Secure Resource ###
+
+In order to verify the resource that you created is secure or not
+you can run the other client app to access the secure resource:
+
+1) Open the new terminal goto : ~/iotivity/out/linux/{TARGET_ARCH}/{MODE}/service/resource-encapsulation/examples/linux
+
+2) Set the Library Path
+
+   $ export LD_LIBRARY_PATH=../../../../../{MODE}
+
+3) Run the sample Resource Client -> ./sampleResourceClient
+
+4) Perform the discovery for Light Resource.
+
+5) Once you discovery of Light resource done. select the option provided in the app.
+
+   For example : startMonitoring , If you select the option you will see on the server side
+   i.e. secure resource No request has came & client side no response. Because the sample that we ran is not the authorized client.
+   It doesn't have the credentials to access the resource.
+
+### About the Sample Applications ###
+
+1) In the main function of both the Client and Server samples, we are passing the json files to the OCPersistentStorage
+   Structure and same OCPersistentStorage's reference passing as the last parameter to "PlatformConfig" API.
+
+   oic_svr_db_client --> In Client Sample
+   oic_svr_db_server --> In server sample
+
+2) Additionally, on server-side while creating a Secure resource we have spcified the OC_SECURE as the
+   resource property flag.
+
+3) After Platform configuration and Resource creation, it is the Security manager module (~/iotivity/resource/csdk/security)
+   who decides whether to accept/reject the request as per the json file passed for platform configuration.
+
+4) Json files contains the static values. It means server contains the entry for the client in the ACL List, credentials and
+   other fields and client has the same subject id, credentials etc. for the server as it is there in the server Json file.
+
+5) The same json files can be used for the different client and server samples. Sample Applications is just to show that at
+   the RE layer we can have the Secure resource like we have at the CSDK and RI layer. in real scenerios
+   this json files will be populated with the mechanisms provided by the Security module of Iotivity stack.
+   (~/iotivity/resource/csdk/security).
+
+NOTE : More information about "Iotivity Security mechanism" can be found at : https://wiki.iotivity.org/iotivity_security
diff --git a/service/resource-encapsulation/examples/linux/secureResourceExample/SConscript b/service/resource-encapsulation/examples/linux/secureResourceExample/SConscript
new file mode 100644 (file)
index 0000000..3ad2106
--- /dev/null
@@ -0,0 +1,76 @@
+#******************************************************************
+#
+# Copyright 2015 Samsung Electronics 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.
+#
+#-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+##
+# linux RE Secure sample apps  build script (Secure Server &  Client)
+##
+Import('env')
+
+# Add third party libraries
+lib_env = env.Clone()
+SConscript(env.get('SRC_DIR') + '/service/third_party_libs.scons', 'lib_env')
+
+sample_env = lib_env.Clone()
+
+sample_env.AppendUnique(CXXFLAGS = ['-Wall', '-std=c++0x'])
+sample_env.AppendUnique(LIBS = [
+    'rcs_common',
+    'oc',
+    'octbstack',
+    'oc_logger',
+    'connectivity_abstraction',
+    'coap',
+    'pthread',
+    'tinydtls'
+    ])
+sample_env.AppendUnique(CPPPATH = ['../../../include'])
+
+if 'rt' in sample_env.get('LIBS'):
+    sample_env.Append(LIBS = ['rt'])
+
+######################################################################
+# ##### Authorized Client #####
+######################################################################
+client_env = sample_env.Clone()
+client_env.AppendUnique(LIBS = 'rcs_client')
+
+sampleAuthorizedClient = client_env.Program('sampleAuthorizedClient', 'SampleAuthorizedClient.cpp')
+client_env.InstallTarget(sampleAuthorizedClient, 'sampleAuthorizedClient')
+
+######################################################################
+# ##### Secure Server #####
+######################################################################
+server_env = sample_env.Clone()
+server_env.AppendUnique(LIBS = 'rcs_server')
+
+sampleSecureServer = server_env.Program('sampleSecureServer', 'SampleSecureServer.cpp')
+server_env.InstallTarget(sampleSecureServer, 'sampleSecureServer')
+
+######################################################################
+# ##### Copy the client & Server credentials files to build directory #####
+######################################################################
+
+src_dir = sample_env.get('SRC_DIR')
+svr_db_src_dir = src_dir + '/service/resource-encapsulation/examples/linux/secureResourceExample/'
+svr_db_build_dir = env.get('BUILD_DIR') +'/service/resource-encapsulation/examples/linux/secureResourceExample/'
+sample_env.Alias("install", sample_env.Install( svr_db_build_dir,
+                svr_db_src_dir + 'oic_svr_db_client.json'))
+sample_env.Alias("install", sample_env.Install( svr_db_build_dir,
+                svr_db_src_dir + 'oic_svr_db_server.json'))
diff --git a/service/resource-encapsulation/examples/linux/secureResourceExample/SampleAuthorizedClient.cpp b/service/resource-encapsulation/examples/linux/secureResourceExample/SampleAuthorizedClient.cpp
new file mode 100644 (file)
index 0000000..5b53677
--- /dev/null
@@ -0,0 +1,361 @@
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#include <iostream>
+
+#include "RCSDiscoveryManager.h"
+#include "RCSRemoteResourceObject.h"
+#include "RCSResourceAttributes.h"
+#include "RCSAddress.h"
+
+#include "OCPlatform.h"
+
+#define DECLARE_MENU(FUNC, ...) { #FUNC, FUNC }
+
+using namespace OC;
+using namespace OIC::Service;
+
+struct CloseApp {};
+
+struct MenuItem
+{
+    private:
+        typedef void(*Handler)();
+
+    public:
+        const std::string title;
+        const Handler handler;
+};
+
+typedef void(*Runner)();
+
+constexpr int RESOURCE_TEMP = 1;
+constexpr int RESOURCE_LIGHT = 2;
+
+const std::string RESOURCE_TYPE_LIGHT = "oic.r.light";
+
+RCSRemoteResourceObject::Ptr g_selectedResource;
+std::vector<RCSRemoteResourceObject::Ptr> g_discoveredResources;
+
+std::string g_attrKey;
+Runner g_currentRun;
+
+std::ostream &operator<<(std::ostream &os, const RCSRemoteResourceObject::Ptr &object)
+{
+    return os << "\turi : " << object->getUri() << std::endl <<
+           "\thost address : " << object->getAddress();
+}
+
+std::ostream &operator<<(std::ostream &os, const MenuItem &item)
+{
+    return os << item.title;
+}
+
+void onSelected(const RCSRemoteResourceObject::Ptr &object)
+{
+    g_selectedResource = object;
+}
+
+void onSelected(const MenuItem &item)
+{
+    std::cout << item.title << " start.." << std::endl;
+    item.handler();
+}
+
+int processUserInput(int min = std::numeric_limits<int>::min(),
+                     int max = std::numeric_limits<int>::max())
+{
+    assert(min <= max);
+
+    int input;
+
+    std::cin >> input;
+    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
+
+    if (!std::cin.fail() && min <= input && input <= max) return input;
+
+    std::cin.clear();
+    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
+
+    throw std::runtime_error("Invalid Input, please try again");
+}
+
+template<typename D>
+void displayItem(int width, int index, const D &data)
+{
+    std::cout.width(width);
+    std::cout << std::right << index << ". ";
+    std::cout << data << std::endl;
+}
+
+template<typename T>
+void displayItems(const std::vector<T> &items)
+{
+    std::cout << std::endl;
+
+    const auto width = (items.size() + 1) / 10 + 1;
+
+    for (size_t i = 0; i < items.size(); ++i)
+    {
+        displayItem(width, i + 1, items[i]);
+    }
+    displayItem(width, items.size() + 1, "quit");
+}
+
+template<typename T>
+void selectItem(const std::vector<T> &items)
+{
+    int selected = processUserInput(1, items.size() + 1) - 1;
+
+    if (selected == static_cast<int>(items.size())) throw CloseApp();
+
+    onSelected(items[selected]);
+}
+
+template<typename T>
+void handleItems(const std::vector<T> &items)
+{
+    displayItems(items);
+    selectItem(items);
+}
+
+void printAttribute(const std::string &key, const RCSResourceAttributes::Value &value)
+{
+    std::cout << "\tkey : " << key << std::endl
+              << "\tvalue : " << value.toString() << std::endl;
+}
+
+void printAttributes(const RCSResourceAttributes &attributes)
+{
+    if (attributes.empty())
+    {
+        std::cout << "\tattributes is empty" << std::endl;
+    }
+
+    for (const auto &attr : attributes)
+    {
+        printAttribute(attr.key(), attr.value());
+    }
+}
+
+void onResourceStateChanged(ResourceState resourceState)
+{
+    std::cout << "onResourceStateChanged callback" << std::endl;
+
+    switch (resourceState)
+    {
+        case ResourceState::NONE:
+            std::cout << "\tState changed to : NOT_MONITORING" << std::endl;
+            break;
+
+        case ResourceState::ALIVE:
+            std::cout << "\tState changed to : ALIVE" << std::endl;
+            break;
+
+        case ResourceState::REQUESTED:
+            std::cout << "\tState changed to : REQUESTED" << std::endl;
+            break;
+
+        case ResourceState::LOST_SIGNAL:
+            std::cout << "\tState changed to : LOST_SIGNAL" << std::endl;
+            break;
+
+        case ResourceState::DESTROYED:
+            std::cout << "\tState changed to : DESTROYED" << std::endl;
+            break;
+    }
+}
+
+void onRemoteAttributesReceived(const RCSResourceAttributes &attributes, int)
+{
+    std::cout << "onRemoteAttributesReceived callback" << std::endl;
+    printAttributes(attributes);
+}
+
+void startMonitoring()
+{
+    if (g_selectedResource->isMonitoring())
+    {
+        std::cout << "\tAlready Started..." << std::endl;
+        return;
+    }
+
+    g_selectedResource->startMonitoring(&onResourceStateChanged);
+    std::cout << "\tMonitoring Started..." << std::endl;
+}
+
+void stopMonitoring()
+{
+    if (!g_selectedResource->isMonitoring())
+    {
+        std::cout << "\tMonitoring not started..." << std::endl;
+        return;
+    }
+
+    g_selectedResource->stopMonitoring();
+    std::cout << "\tMonitoring stopped..." << std::endl;
+}
+
+void getRemoteAttributes()
+{
+    g_selectedResource->getRemoteAttributes(onRemoteAttributesReceived);
+}
+
+void setRemoteAttributes()
+{
+    std::string key;
+
+    std::cout << "\tEnter the Key you want to set : ";
+    std::cin >> key;
+
+    std::cout << "\tEnter the value(INT) you want to set :";
+    RCSResourceAttributes attrs;
+    attrs[key] = processUserInput();
+
+    g_selectedResource->setRemoteAttributes(attrs, onRemoteAttributesReceived);
+}
+
+RCSAddress inputAddress()
+{
+    std::cout << "========================================================";
+    std::cout << "==================" << std::endl;
+    std::cout << "Please enter the address for Unicast Discovery or press enter for multicast" <<
+              std::endl;
+    std::cout << "========================================================";
+    std::cout << "==================" << std::endl;
+
+    std::string address;
+
+    if (std::cin.peek() != '\n') std::cin >> address;
+
+    return address.empty() ? RCSAddress::multicast() : RCSAddress::unicast(address);
+}
+
+void printDiscoveryInProgress()
+{
+    std::cout << "Discovery in progress, press '1' to stop." << std::endl;
+}
+
+void discoverResource()
+{
+    auto onResourceDiscovered = [](
+                                    const RCSRemoteResourceObject::Ptr & discoveredResource)
+    {
+        std::cout << "onResourceDiscovered callback :: " << std::endl;
+
+        std::cout << "\t uri : " << discoveredResource->getUri() << std::endl;
+        std::cout << "\t host address : " << discoveredResource->getAddress() << std::endl;
+
+        g_discoveredResources.push_back(discoveredResource);
+
+        printDiscoveryInProgress();
+    };
+
+    auto resourceType = RESOURCE_TYPE_LIGHT;
+    auto address = inputAddress();
+
+    printDiscoveryInProgress();
+
+    auto discoveryTask = RCSDiscoveryManager::getInstance()->discoverResourceByType(address,
+                         resourceType, onResourceDiscovered);
+
+    while (processUserInput() != 1);
+
+    discoveryTask->cancel();
+}
+
+void runResourceControl()
+{
+    static std::vector<MenuItem> resourceMenuItems
+    {
+        DECLARE_MENU(startMonitoring),
+        DECLARE_MENU(stopMonitoring),
+        DECLARE_MENU(getRemoteAttributes),
+        DECLARE_MENU(setRemoteAttributes),
+    };
+
+    handleItems(resourceMenuItems);
+}
+
+void runResourceSelection()
+{
+    handleItems(g_discoveredResources);
+    g_currentRun = runResourceControl;
+}
+
+void runDiscovery()
+{
+    static std::vector<MenuItem> discoveryMenuItems
+    {
+        DECLARE_MENU(discoverResource),
+    };
+
+    handleItems(discoveryMenuItems);
+
+    if (g_discoveredResources.empty()) throw std::runtime_error("No resource found!");
+
+    g_currentRun = runResourceSelection;
+}
+
+static FILE *client_open(const char * /*path*/, const char *mode)
+{
+    return fopen("./oic_svr_db_client.json", mode);
+}
+
+int main()
+{
+
+    OCPersistentStorage ps {client_open, fread, fwrite, fclose, unlink };
+
+    PlatformConfig cfg
+    {
+        OC::ServiceType::InProc, OC::ModeType::Both, "0.0.0.0", 0,
+        OC::QualityOfService::LowQos, &ps
+    };
+
+    OCPlatform::Configure(cfg);
+
+    g_currentRun = runDiscovery;
+
+    while (true)
+    {
+        try
+        {
+            g_currentRun();
+        }
+        catch (const std::exception &e)
+        {
+            std::cout << e.what() << std::endl;
+        }
+        catch (const CloseApp &)
+        {
+            break;
+        }
+    }
+
+    if ((g_selectedResource) && (g_selectedResource->isMonitoring()))
+    {
+        g_selectedResource->stopMonitoring();
+    }
+
+    std::cout << "Stopping the client" << std::endl;
+
+    return 0;
+}
diff --git a/service/resource-encapsulation/examples/linux/secureResourceExample/SampleSecureServer.cpp b/service/resource-encapsulation/examples/linux/secureResourceExample/SampleSecureServer.cpp
new file mode 100644 (file)
index 0000000..5d5a345
--- /dev/null
@@ -0,0 +1,251 @@
+/******************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ ******************************************************************/
+
+#include "RCSResourceObject.h"
+#include "OCPlatform.h"
+
+using namespace OC::OCPlatform;
+using namespace OIC::Service;
+
+struct CloseApp {};
+
+constexpr int RESOURCE_LIGHT = 1;
+
+constexpr int DEFALUT_SERVER = 1;
+constexpr int CUSTOM_SERVER = 2;
+
+constexpr int INCREASE = 1;
+constexpr int DECREASE = 2;
+
+typedef void (*DisplayControlMenuFunc)();
+typedef std::function<void()> Run;
+
+Run g_currentRun;
+bool g_isPresenceStarted = false;
+
+RCSResourceObject::Ptr g_resource;
+
+int processUserInput(int min, int max)
+{
+    assert(min <= max);
+
+    int input;
+
+    std::cin >> input;
+
+    if (!std::cin.fail())
+    {
+        if (input == max + 1) throw CloseApp();
+        if (min <= input) return input;
+    }
+
+    std::cin.clear();
+    std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
+
+    throw std::runtime_error("Invalid Input, please try again");
+}
+
+void displayControlLightMenu()
+{
+    std::cout << "========================================================\n";
+    std::cout << INCREASE << ". Increase Brightness by 1 stage            \n";
+    std::cout << DECREASE << ". Decrease Brightness by 1 stage            \n";
+    std::cout << DECREASE + 1 << ". Quit                                  \n";
+    std::cout << "========================================================\n";
+}
+
+void printAttributes(const RCSResourceAttributes &attrs)
+{
+    for (const auto &attr : attrs)
+    {
+        std::cout << "\tkey : " << attr.key() << "\n\tvalue : "
+                  << attr.value().toString() << std::endl;
+    }
+}
+
+RCSGetResponse requestHandlerForGet(const RCSRequest &, RCSResourceAttributes &attrs)
+{
+    std::cout << "Received a Get request from Client" << std::endl;
+    printAttributes(attrs);
+
+    {
+        RCSResourceObject::LockGuard lock(g_resource);
+        std::cout << "\nSending response to Client : " << std::endl;
+        printAttributes(g_resource->getAttributes());
+    }
+
+    return RCSGetResponse::defaultAction();
+}
+
+RCSSetResponse requestHandlerForSet(const RCSRequest &, RCSResourceAttributes &attrs)
+{
+    std::cout << "Received a Set request from Client" << std::endl;
+    printAttributes(attrs);
+
+    return RCSSetResponse::defaultAction();
+}
+
+void initServer(const std::string &resourceUri, const std::string &resourceType,
+                const std::string &attrKey)
+{
+
+    g_resource = RCSResourceObject::Builder(resourceUri, resourceType, "oic.if.baseline").
+                 setDiscoverable(true).setObservable(true).setSecureFlag(true).build();
+
+    g_resource->setAutoNotifyPolicy(RCSResourceObject::AutoNotifyPolicy::UPDATED);
+    g_resource->setSetRequestHandlerPolicy(RCSResourceObject::SetRequestHandlerPolicy::NEVER);
+    g_resource->setAttribute(attrKey, 0);
+}
+
+void updateAttribute(const std::string &attrKey, int control)
+{
+    const int diff = control == INCREASE ? 1 : - 1;
+
+    {
+        RCSResourceObject::LockGuard lock(g_resource);
+        auto &attrs = g_resource->getAttributes();
+        attrs[attrKey] = attrs[attrKey].get<int>() + diff;
+    }
+
+    if (control == INCREASE)
+    {
+        std::cout << attrKey << " increased." << std::endl;
+    }
+    else
+    {
+        std::cout << attrKey << " decreased." << std::endl;
+    }
+    std::cout << "\nCurrent " << attrKey << ": "
+              << g_resource->getAttributeValue(attrKey).get<int>() << std::endl;
+}
+
+void runResourceControl(DisplayControlMenuFunc displayMenuFunc, const std::string &attrKey)
+{
+    displayMenuFunc();
+    updateAttribute(attrKey, processUserInput(INCREASE, DECREASE));
+}
+
+void runResourceTypeSelection(int resourceMode)
+{
+    std::cout << "========================================================\n";
+    std::cout << RESOURCE_LIGHT << ". Create a Secure Light Resource                              \n";
+    std::cout << RESOURCE_LIGHT + 1 << ". Quit                            \n";
+    std::cout << "========================================================\n";
+
+    int resourceType = processUserInput(RESOURCE_LIGHT, RESOURCE_LIGHT);
+    DisplayControlMenuFunc displayMenuFunc;
+    std::string attrKey;
+
+    switch (resourceType)
+    {
+        case RESOURCE_LIGHT:
+            attrKey = "Brightness";
+            initServer("/a/light", "oic.r.light", attrKey);
+
+            displayMenuFunc = displayControlLightMenu;
+            break;
+    }
+
+    if (resourceMode == CUSTOM_SERVER)
+    {
+        g_resource->setGetRequestHandler(requestHandlerForGet);
+        g_resource->setSetRequestHandler(requestHandlerForSet);
+    }
+
+    g_currentRun = std::bind(runResourceControl, displayMenuFunc, std::move(attrKey));
+}
+
+void runResourceModeSelection()
+{
+    std::cout << "========================================================          \n";
+    std::cout << DEFALUT_SERVER << ". Creation of Secure Resource Without Handlers  \n";
+    std::cout << CUSTOM_SERVER << ". Creation of Secure Resource With Set and Get Handlers \n";
+    std::cout << CUSTOM_SERVER + 1 << ". Quit                                       \n";
+    std::cout << "========================================================          \n";
+
+    g_currentRun = std::bind(runResourceTypeSelection,
+                             processUserInput(DEFALUT_SERVER, CUSTOM_SERVER));
+}
+
+void runPresenceSelection()
+{
+    constexpr int PRESENCE_ON = 1;
+    constexpr int PRESENCE_OFF = 2;
+
+    std::cout << "========================================================\n";
+    std::cout << PRESENCE_ON << ". Presence On                            \n";
+    std::cout << PRESENCE_OFF << ". Presence Off                          \n";
+    std::cout << PRESENCE_OFF + 1 << ". Quit                              \n";
+    std::cout << "========================================================\n";
+
+    if (processUserInput(PRESENCE_ON, PRESENCE_OFF) == PRESENCE_ON)
+    {
+        g_isPresenceStarted = true;
+        startPresence(3);
+    }
+
+    g_currentRun = runResourceModeSelection;
+}
+
+static FILE *client_open(const char * /*path*/, const char *mode)
+{
+    return fopen("./oic_svr_db_server.json", mode);
+}
+
+int main(void)
+{
+    OCPersistentStorage ps {client_open, fread, fwrite, fclose, unlink };
+
+    OC::PlatformConfig cfg
+    {
+        OC::ServiceType::InProc, OC::ModeType::Server, "0.0.0.0", 0,
+        OC::QualityOfService::LowQos, &ps
+    };
+
+    OC::OCPlatform::Configure(cfg);
+
+    g_currentRun = runPresenceSelection;
+
+    while (true)
+    {
+        try
+        {
+            g_currentRun();
+        }
+        catch (const std::exception &e)
+        {
+            std::cout << e.what() << std::endl;
+        }
+        catch (const CloseApp &)
+        {
+            break;
+        }
+    }
+    std::cout << "Stopping the server" << std::endl;
+
+    g_resource.reset();
+
+    if (g_isPresenceStarted)
+    {
+        stopPresence();
+    }
+
+}
+
diff --git a/service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_client.json b/service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_client.json
new file mode 100644 (file)
index 0000000..c16acb8
--- /dev/null
@@ -0,0 +1,50 @@
+{
+    "acl": [
+        {
+            "sub": "Kg==",
+            "rsrc": [
+                "/oic/res",
+                "/oic/d",
+                "/oic/p",
+                "/oic/res/types/d",
+                "/oic/ad",
+                "/oic/sec/acl"
+                       ],
+                       "perms": 2,
+                       "ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
+               },
+        {
+            "sub": "Kg==",
+            "rsrc": [
+                "/oic/sec/doxm",
+                "/oic/sec/pstat"
+             ],
+             "perms": 2,
+             "ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
+        }
+       ],
+       "pstat":        {
+               "isop": true,
+               "deviceid":     "ZGV2aWNlaWQAAAAAABhanw==",
+               "ch": 0,
+               "cm":   0,
+               "tm":   0,
+               "om":   3,
+               "sm":   [3]
+       },
+       "doxm": {
+               "oxm":  [0],
+               "oxmsel": 0,
+               "sct": 1,
+               "owned": true,
+               "deviceid":     "MjIyMjIyMjIyMjIyMjIyMg==",
+               "ownr": "MjIyMjIyMjIyMjIyMjIyMg=="
+       },
+    "cred":    [{
+               "credid": 1,
+               "sub": "MTExMTExMTExMTExMTExMQ==",
+               "credtyp": 1,
+               "pvdata": "QUFBQUFBQUFBQUFBQUFBQQ==",
+        "ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
+       }]
+}
diff --git a/service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_server.json b/service/resource-encapsulation/examples/linux/secureResourceExample/oic_svr_db_server.json
new file mode 100644 (file)
index 0000000..b6bb1eb
--- /dev/null
@@ -0,0 +1,56 @@
+{
+    "acl": [
+        {
+            "sub": "Kg==",
+            "rsrc": [
+                "/oic/res",
+                "/oic/d",
+                "/oic/p",
+                "/oic/res/types/d",
+                "/oic/ad",
+                "/oic/sec/acl"
+                       ],
+                       "perms": 2,
+                       "ownrs" : ["MTExMTExMTExMTExMTExMQ=="]
+               },
+        {
+            "sub": "Kg==",
+            "rsrc": [
+                "/oic/sec/doxm",
+                "/oic/sec/pstat"
+             ],
+             "perms": 2,
+             "ownrs" : ["MTExMTExMTExMTExMTExMQ=="]
+        },
+        {
+            "sub": "Kg==",
+            "rsrc": ["/a/light"],
+            "perms": 6,
+            "ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
+        }
+       ],
+       "pstat":        {
+               "isop": true,
+               "deviceid":     "ZGV2aWNlaWQAAAAAABhanw==",
+               "ch": 0,
+               "cm":   0,
+               "tm":   0,
+               "om":   3,
+               "sm":   [3]
+       },
+       "doxm": {
+               "oxm":  [0],
+               "oxmsel": 0,
+               "sct": 1,
+               "owned": true,
+               "deviceid":     "MTExMTExMTExMTExMTExMQ==",
+               "ownr": "MjIyMjIyMjIyMjIyMjIyMg=="
+       },
+    "cred":    [{
+               "credid": 1,
+               "sub": "MjIyMjIyMjIyMjIyMjIyMg==",
+               "credtyp": 1,
+               "pvdata": "QUFBQUFBQUFBQUFBQUFBQQ==",
+        "ownrs" : ["MjIyMjIyMjIyMjIyMjIyMg=="]
+       }]
+}
index d062b3a..93eb4c7 100644 (file)
@@ -158,6 +158,14 @@ namespace OIC
                         Builder& setObservable(bool observable);
 
                         /**
+                         * Sets whether the resource should be secure or not.
+                         *
+                         * @param secureFlag whether to be secure or not.
+                         *
+                         */
+                        Builder& setSecureFlag(bool secureFlag);
+
+                        /**
                          * Sets attributes for the resource.
                          *
                          * @param attributes attributes to set
index 04b9717..c68b357 100644 (file)
@@ -154,6 +154,12 @@ namespace OIC
             return *this;
         }
 
+        RCSResourceObject::Builder& RCSResourceObject::Builder::setSecureFlag(
+            bool secureFlag)
+        {
+            m_properties = ::makePropertyFlags(m_properties, OC_SECURE, secureFlag);
+            return *this;
+        }
         RCSResourceObject::Builder& RCSResourceObject::Builder::setAttributes(
                 const RCSResourceAttributes& attrs)
         {