Split cloudClient to Client & Server part
authorAndrii Shtompel <a.shtompel@samsung.com>
Wed, 14 Sep 2016 14:33:37 +0000 (23:33 +0900)
committerRandeep Singh <randeep.s@samsung.com>
Fri, 30 Sep 2016 09:17:06 +0000 (09:17 +0000)
1) Server part creates LED resource
2) Only Client part supports d2d requests

[Patch #2] Fix minor logic error during last cherry-pick

Change-Id: I335f7556a1ef247526886175ebcf400cd9e19b99
Signed-off-by: Andrii Shtompel <a.shtompel@samsung.com>
Reviewed-on: https://gerrit.iotivity.org/gerrit/12057
Tested-by: jenkins-iotivity <jenkins-iotivity@opendaylight.org>
Reviewed-by: dongik Lee <dongik.lee@samsung.com>
Reviewed-by: Randeep Singh <randeep.s@samsung.com>
resource/csdk/security/provisioning/sample/SConscript
resource/csdk/security/provisioning/sample/cloud/cloudCommon.c [new file with mode: 0644]
resource/csdk/security/provisioning/sample/cloud/cloudCommon.h
resource/csdk/security/provisioning/sample/cloud/cloudResource.c [new file with mode: 0644]
resource/csdk/security/provisioning/sample/cloud/cloudResource.h [new file with mode: 0644]
resource/csdk/security/provisioning/sample/cloud/cloudWrapper.c
resource/csdk/security/provisioning/sample/cloud/cloudWrapper.h
resource/csdk/security/provisioning/sample/cloudClient.c
resource/csdk/security/provisioning/sample/cloudServer.c [new file with mode: 0644]

index fc7005e..da600ae 100644 (file)
@@ -102,12 +102,13 @@ provisioningclient = provisioning_env.Program('provisioningclient', 'provisionin
 sampleserver_justworks = provisioning_env.Program('sampleserver_justworks', 'sampleserver_justworks.cpp')
 sampleserver_randompin = provisioning_env.Program('sampleserver_randompin', 'sampleserver_randompin.cpp')
 if provisioning_env.get('WITH_TCP') == True:
-    cloudClient_src = [
-        'cloudClient.c',
+    cloud_src = [
         'cloud/cloudAuth.c',
+        'cloud/cloudCommon.c',
         'cloud/cloudWrapper.c',
         'cloud/cloudDiscovery.c']
-    cloudClient = provisioning_env.Program('cloudClient', cloudClient_src)
+    cloudClient = provisioning_env.Program('cloudClient', cloud_src + ['cloudClient.c'])
+    cloudServer = provisioning_env.Program('cloudServer', cloud_src + ['cloudServer.c', 'cloud/cloudResource.c'])
 
 src_dir = provisioning_env.get('SRC_DIR')
 sec_provisioning_src_dir = src_dir + '/resource/csdk/security/provisioning/sample/'
@@ -127,7 +128,7 @@ if provisioning_env.get('WITH_TCP') == True:
                                         sec_provisioning_src_dir + 'cloud.dat')
     rootcert = provisioning_env.Install(sec_provisioning_build_dir,
                                         sec_provisioning_src_dir + 'rootca.crt')
-    Alias("cloud", [clouddat, rootcert, cloudClient])
+    Alias("cloud", [clouddat, rootcert, cloudClient, cloudServer])
     provisioning_env.AppendTarget("cloud")
 
 Alias("samples", [provisioningclient, sampleserver_justworks, sampleserver_randompin, clientdat, justworksdat, randompindat, randompin_with_emptyuuid_dat])
diff --git a/resource/csdk/security/provisioning/sample/cloud/cloudCommon.c b/resource/csdk/security/provisioning/sample/cloud/cloudCommon.c
new file mode 100644 (file)
index 0000000..acf96ac
--- /dev/null
@@ -0,0 +1,541 @@
+//******************************************************************
+//
+// Copyright 2016 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 <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+#include "ocstack.h"
+#include "logger.h"
+#include "camutex.h"
+#include "cathreadpool.h"
+#include "ocpayload.h"
+#include "payload_logging.h"
+#include "ocprovisioningmanager.h"
+
+#include "utils.h"
+#include "cloudAuth.h"
+#include "cloudCommon.h"
+#include "cloudWrapper.h"
+#include "cloudDiscovery.h"
+
+#ifdef __unix__
+#include <unistd.h> //for unlink
+#endif
+
+#define TAG "cloudCommon"
+
+#define DEFAULT_HOST            "10.113.68.85"//"127.0.0.1"
+#define DEFAULT_PORT            OC_MULTICAST_PORT
+#define DEFAULT_AUTH_PROVIDER   "github"
+#define DEFAULT_DB_FILE         "./cloud.dat"
+#define DEFAULT_RESPONSE_WAIT_TIME (10 * 1000000) //10s
+
+#define GITHUB_AUTH_LINK        "https://github.com/login?return_to=%2Flogin%2Foauth%2Fauthorize%3Fclient_id%3Dea9c18f540323b0213d0%26redirect_uri%3Dhttp%253A%252F%252Fwww.example.com%252Foauth_callback%252F"
+
+#define CLIENT_ONLY(mode)       if (OC_SERVER == mode) { wrongRequest(); break; }
+
+static bool fExit = false;
+
+static ca_thread_pool_t g_threadPoolHandle = NULL;
+static OCDevAddr endPoint;
+static char token[1024] = "";
+static char authProvider[1024] = DEFAULT_AUTH_PROVIDER;
+static char *fname = DEFAULT_DB_FILE;
+static uint64_t timeout;
+static uint16_t g_credId = 0;
+
+static ca_cond cond;
+static ca_mutex mutex;
+
+typedef enum {
+    SIGN_UP       = 1,
+    SIGN_IN       = 2,
+    SIGN_OUT      = 3,
+
+    HOST          = 4,
+    PORT          = 5,
+    DB_FILE       = 6,
+    AUTH_PROVIDER = 7,
+    USE_RSA = 8,
+    SAVE_TRUST_CERT = 9,
+    USE_SECURE_CONN = 10,
+
+    DISCOVERY     = 13,
+    GET           = 14,
+    PUT           = 15,
+    POST          = 16,
+
+    CSR_SIGN      = 19,
+
+    CRL_GET       = 20,
+    CRL_POST      = 21,
+
+    ACL_ID_CREATE = 30,
+    ACL_ID_GET_BY_DEVICE = 31,
+    ACL_ID_DELETE = 32,
+
+    ACL_INDIVIDUAL_GET_INFO = 40,
+    ACL_INDIVIDUAL_UPDATE_ACE = 41,
+    ACL_INDIVIDUAL_DELETE = 42,
+
+    ACL_GROUP_CREATE = 50,
+    ACL_GROUP_FIND   = 51,
+    ACL_GROUP_JOIN   = 52,
+    ACL_GROUP_OBSERVE= 53,
+    ACL_GROUP_DELETE = 54,
+
+    ACL_GROUP_SHARE_DEVICE  = 60,
+    ACL_GROUP_DELETE_DEVICE  = 61,
+    ACL_GROUP_GET_INFO  = 62,
+
+    ACL_POLICY_CHECK_REQUEST = 70,
+
+    ACL_GROUP_INVITE_USER = 80,
+    ACL_GROUP_GET_INVITE  = 81,
+    ACL_GROUP_DELETE_INVITE  = 82,
+    ACL_GROUP_CANCEL_INVITE  = 83,
+
+    EXIT          = 99
+}CloudRequest;
+
+static void printMenu(OCMode mode)
+{
+    char *title = "Client";
+    if (OC_SERVER == mode)
+    {
+        title = "Server";
+    }
+    printf("************************************************************\n");
+    printf("****************** Cloud %s Requests *******************\n", title);
+    printf("************************************************************\n");
+    printf("** AUTHORIZATION\n");
+    printf("** %d - Sign Up request\n", SIGN_UP);
+    printf("** %d - Sign In request\n", SIGN_IN);
+    printf("** %d - Sign Out request\n", SIGN_OUT);
+
+    printf("** SETTINGS \n");
+    printf("** %d - Change default host\n", HOST);
+    printf("** %d - Change default port\n", PORT);
+    printf("** %d - Change default database filename\n", DB_FILE);
+    printf("** %d - Change default auth provider\n", AUTH_PROVIDER);
+    printf("** %d - Change TLS cipher suite to RSA\n", USE_RSA);
+    printf("** %d - Save Trust Cert. Chain into Cred of SVR\n", SAVE_TRUST_CERT);
+    printf("** %d - Change Protocol type (CoAP/CoAPs)\n", USE_SECURE_CONN);
+
+    if (OC_CLIENT == mode)
+    {
+        printf("** DISCOVERY\n");
+        printf("** %d - Start Discovery\n", DISCOVERY);
+        printf("** %d - Get Request\n", GET);
+        printf("** %d - Put Request\n", PUT);
+        printf("** %d - Post Request\n", POST);
+    }
+
+    printf("** CERTIFICATE REQUEST\n");
+    printf("** %d - Certificate Request\n", CSR_SIGN);
+
+    printf("** CRL\n");
+    printf("** %d - CRL GET Request\n", CRL_GET);
+    printf("** %d - CRL POST Request\n", CRL_POST);
+
+    printf("** ACL MANAGER\n");
+    printf("** %d - ACL id create Request\n", ACL_ID_CREATE);
+    printf("** %d - ACL id retrieve by device Request\n", ACL_ID_GET_BY_DEVICE);
+    printf("** %d - ACL id delete Request\n", ACL_ID_DELETE);
+
+    printf("** ACL INDIVIDUAL\n");
+    printf("** %d - ACL individual get info Request\n", ACL_INDIVIDUAL_GET_INFO);
+    printf("** %d - ACL individual update ACE Request\n", ACL_INDIVIDUAL_UPDATE_ACE);
+    printf("** %d - ACL individual delete Request\n", ACL_INDIVIDUAL_DELETE);
+
+    printf("** ACL GROUP MANAGER\n");
+    printf("** %d - ACL Create Group Request\n", ACL_GROUP_CREATE);
+    printf("** %d - ACL Find Group Request\n", ACL_GROUP_FIND);
+    printf("** %d - ACL Join to invited Group Request\n", ACL_GROUP_JOIN);
+    printf("** %d - ACL Observe Group Request\n", ACL_GROUP_OBSERVE);
+    printf("** %d - ACL Delete Group Request\n", ACL_GROUP_DELETE);
+
+    printf("** ACL INDIVIDUAL GROUP\n");
+    printf("** %d - ACL Share device into Group Request\n", ACL_GROUP_SHARE_DEVICE);
+    printf("** %d - ACL Delete device from Group Request\n", ACL_GROUP_DELETE_DEVICE);
+    printf("** %d - ACL Get Group Info Request\n", ACL_GROUP_GET_INFO);
+
+    printf("** ACL POLICY ENFORCEMENT\n");
+    printf("** %d - ACL Check Permissions Request\n", ACL_POLICY_CHECK_REQUEST);
+
+    printf("** ACL MEMBER INVITATION\n");
+    printf("** %d - ACL Invite user to group Request\n", ACL_GROUP_INVITE_USER);
+    printf("** %d - ACL Retrieve invitation Request\n", ACL_GROUP_GET_INVITE);
+    printf("** %d - ACL Delete invitation Request\n", ACL_GROUP_DELETE_INVITE);
+    printf("** %d - ACL Cancel invitation Request\n", ACL_GROUP_CANCEL_INVITE);
+
+    printf("** EXIT\n");
+    printf("** %d - Exit cloud %s\n\n", EXIT, title);
+    printf("************************************************************\n");
+
+    printf(">> Enter Menu number:\n");
+}
+
+void unlockMenu(void *data)
+{
+    OICFree(data);
+
+    if (!fExit)
+    {
+        ca_mutex_lock(mutex);
+        ca_cond_signal(cond);
+        ca_mutex_unlock(mutex);
+    }
+}
+
+/**
+ * This is default callback to all requests
+ * Used to sync with main menu
+ *
+ * @param[in] ctx          context
+ * @param[in] result       result
+ * @param[in] data         data
+ */
+static void handleCB(void* ctx, OCStackResult result, void* data)
+{
+    OC_UNUSED(ctx);
+    OC_UNUSED(data);
+
+    OIC_LOG_V(INFO, TAG, "%s: Received result = %d", __func__, result);
+
+    unlockMenu(NULL);
+}
+
+static OCStackResult saveTrustCert(void)
+{
+    OCStackResult res = OC_STACK_ERROR;
+    OIC_LOG(INFO, TAG, "Save Trust Cert. Chain into Cred of SVR");
+
+    ByteArray trustCertChainArray = {0, 0};
+    const char *filename = "rootca.crt";
+
+    if (!readFile(filename, (OCByteString *)&trustCertChainArray))
+    {
+        OIC_LOG_V(ERROR, TAG, "Can't read %s file", filename);
+        return OC_STACK_ERROR;
+    }
+    OIC_LOG_BUFFER(DEBUG, TAG, trustCertChainArray.data, trustCertChainArray.len);
+
+    res = OCSaveTrustCertChain(trustCertChainArray.data, trustCertChainArray.len, OIC_ENCODING_PEM,&g_credId);
+
+    if(OC_STACK_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "OCSaveTrustCertChainBin API error");
+        return res;
+    }
+    OIC_LOG_V(INFO, TAG, "CredId of Saved Trust Cert. Chain into Cred of SVR : %d.\n", g_credId);
+
+    return res;
+}
+
+static void wrongRequest()
+{
+    printf(">> Entered Wrong Menu Number. Please Enter Again\n\n");
+}
+
+static void userRequests(void *data)
+{
+    if (NULL == data)
+    {
+        OIC_LOG(ERROR, TAG, "Received NULL data");
+        return;
+    }
+
+    OCMode mode = *(OCMode*)data;
+
+    memset(&endPoint, 0, sizeof(endPoint));
+    strncpy(endPoint.addr, DEFAULT_HOST, sizeof(endPoint.addr));
+    endPoint.port = DEFAULT_PORT;
+
+    mutex = ca_mutex_new();
+    cond = ca_cond_new();
+
+    while (false == fExit)
+    {
+        OCStackResult res = OC_STACK_ERROR;
+        timeout = DEFAULT_RESPONSE_WAIT_TIME;
+        //startup report
+        printf("-----------------------------------------------------------\n");
+        printf("Connecting to: %s:%d\n", endPoint.addr, endPoint.port);
+        printf("via auth provider: %s\n", authProvider);
+        printf("srv file: %s\n", fname);
+        printf("CoAP prefix: %s\n", DEFAULT_PREFIX);
+        printf("-----------------------------------------------------------\n");
+
+        printMenu(mode);
+
+        int request = 0;
+        scanf("%d", &request);
+
+        switch (request)
+        {
+        case SIGN_UP:
+            if (0 == strncmp(authProvider, DEFAULT_AUTH_PROVIDER, sizeof(authProvider)))
+            {
+                printf("Paste to browser %s and get auth code\n", GITHUB_AUTH_LINK);
+            }
+            readString(token, sizeof(token), "auth token", "check link above");
+            res = CloudSignUp(&endPoint, authProvider, token);
+            break;
+        case SIGN_IN:
+            res = CloudSignIn(&endPoint);
+            break;
+        case SIGN_OUT:
+            res = CloudSignOut(&endPoint);
+            break;
+        case HOST:
+            readString(endPoint.addr, sizeof(endPoint.addr), "host ip address", DEFAULT_HOST);
+            break;
+        case PORT:
+        {
+            char example[8];
+            snprintf(example, sizeof(example), "%d", DEFAULT_PORT);
+            int tmp = 0;
+            readInteger(&tmp, "port number", example);
+            endPoint.port = tmp;
+        }
+        break;
+        case CRL_GET:
+            res = OCWrapperGetCRL(&endPoint, handleCB);
+            break;
+        case CRL_POST:
+            res = OCWrapperPostCRL(&endPoint, handleCB);
+            break;
+        case ACL_GROUP_CREATE:
+            res = OCWrapperAclCreateGroup(&endPoint, handleCB);
+            break;
+        case ACL_GROUP_FIND:
+            res = OCWrapperAclFindMyGroup(&endPoint, handleCB);
+            break;
+        case ACL_GROUP_DELETE:
+            res = OCWrapperAclDeleteGroup(&endPoint, handleCB);
+            break;
+        case ACL_GROUP_JOIN:
+            res = OCWrapperAclJoinToInvitedGroup(&endPoint, handleCB);
+            break;
+        case ACL_GROUP_OBSERVE:
+            res = OCWrapperAclObserveGroup(&endPoint, handleCB);
+            break;
+        case ACL_GROUP_SHARE_DEVICE:
+            res = OCWrapperAclShareDeviceIntoGroup(&endPoint, handleCB);
+            break;
+        case ACL_GROUP_DELETE_DEVICE:
+            res = OCWrapperAclDeleteDeviceFromGroup(&endPoint, handleCB);
+            break;
+        case ACL_GROUP_GET_INFO:
+            res = OCWrapperAclGroupGetInfo(&endPoint, handleCB);
+            break;
+        case ACL_GROUP_INVITE_USER:
+            res = OCWrapperAclInviteUser(&endPoint, handleCB);
+            break;
+        case ACL_GROUP_GET_INVITE:
+            res = OCWrapperAclGetInvitation(&endPoint, handleCB);
+            break;
+        case ACL_GROUP_DELETE_INVITE:
+            res = OCWrapperAclDeleteInvitation(&endPoint, handleCB);
+            break;
+        case ACL_GROUP_CANCEL_INVITE:
+            res = OCWrapperAclCancelInvitation(&endPoint, handleCB);
+            break;
+        case ACL_POLICY_CHECK_REQUEST:
+            res = OCWrapperAclPolicyCheck(&endPoint, handleCB);
+            break;
+        case ACL_ID_GET_BY_DEVICE:
+            res = OCWrapperAclIdGetByDevice(&endPoint, handleCB);
+            break;
+        case ACL_ID_CREATE:
+            res = OCWrapperAclIdCreate(&endPoint, handleCB);
+            break;
+        case ACL_ID_DELETE:
+            res = OCWrapperAclIdDelete(&endPoint, handleCB);
+            break;
+        case ACL_INDIVIDUAL_GET_INFO:
+            res = OCWrapperAclIndividualGetInfo(&endPoint, handleCB);
+            break;
+        case ACL_INDIVIDUAL_UPDATE_ACE:
+            res = OCWrapperAclIndividualUpdateAce(&endPoint, handleCB);
+            break;
+        case ACL_INDIVIDUAL_DELETE:
+            res = OCWrapperAclIndividualDelete(&endPoint, handleCB);
+            break;
+        case CSR_SIGN:
+            res = OCWrapperCertificateIssueRequest(&endPoint, handleCB);
+            break;
+        case DISCOVERY:
+            CLIENT_ONLY(mode);
+            res = InitDiscovery();
+            break;
+        case GET:
+            CLIENT_ONLY(mode);
+            res = InitRequest(OC_REST_GET);
+            break;
+        case PUT:
+            CLIENT_ONLY(mode);
+            res= InitRequest(OC_REST_PUT);
+            break;
+        case POST:
+            CLIENT_ONLY(mode);
+            res= InitRequest(OC_REST_POST);
+            break;
+        case USE_RSA:
+            CASelectCipherSuite(0x35, CA_ADAPTER_TCP);
+            break;
+        case SAVE_TRUST_CERT:
+            saveTrustCert();
+            break;
+        case USE_SECURE_CONN:
+        {
+            int tmp = 0;
+            readInteger(&tmp, "CoAP protocol type", "0 - non-secure, 1 - secure");
+            setCoapPrefix(0 == tmp ? false : true);
+        }
+            break;
+        case EXIT:
+            ca_mutex_free(mutex);
+            ca_cond_free(cond);
+            fExit = true;
+            break;
+        default:
+            wrongRequest();
+            break;
+        }
+
+        //if requests were sent then wait response
+        if (res == OC_STACK_OK)
+        {
+            ca_mutex_lock(mutex);
+            ca_cond_wait_for(cond, mutex, timeout);
+            ca_mutex_unlock(mutex);
+        }
+    }
+}
+
+FILE* server_fopen(const char *path, const char *mode)
+{
+    OC_UNUSED(path);
+    return fopen(fname, mode);
+}
+
+/**
+ * Check file accessibility
+ *
+ * @param[in] name        file path
+ * @return true           if check was successful
+ */
+static bool checkConfig(const char *name)
+{
+    FILE* file = fopen(name, "rb");
+
+    if (file)
+    {
+        fclose(file);
+        return true;
+    }
+    return false;
+}
+
+static void printUsage(char *name)
+{
+    printf("Wrong arguments count!\n");
+    printf("Usage : %s <database_filename>\n", name);
+    printf("Examples : 1) %s 2) %s cloud.dat\n", name, name);
+}
+
+bool parseCommandLineArguments(int argc, char *argv[])
+{
+    bool result = true;
+    if (2 == argc)
+    {
+        fname = argv[1];
+
+        if (!checkConfig(fname))
+        {
+            OIC_LOG_V(ERROR, TAG, "Can't open database file %s, exit!", fname);
+            result = false;
+        }
+    }
+    else if (argc > 2)
+    {
+        printUsage(argv[0]);
+        result = false;
+    }
+    return result;
+}
+
+OCStackResult initPersistentStorage()
+{
+    //Initialize Persistent Storage for SVR database
+    static OCPersistentStorage ps = {server_fopen, fread, fwrite, fclose, unlink};
+
+    return OCRegisterPersistentStorageHandler(&ps);
+}
+
+OCStackResult startRequestsThread(OCMode *mode)
+{
+    CAResult_t res = ca_thread_pool_init(1, &g_threadPoolHandle);
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "thread pool initialize error.");
+        return res;
+    }
+
+    res = ca_thread_pool_add_task(g_threadPoolHandle, userRequests, mode);
+    if (CA_STATUS_OK != res)
+    {
+        OIC_LOG(ERROR, TAG, "thread pool add task error.");
+        ca_thread_pool_free(g_threadPoolHandle);
+    }
+    return res;
+}
+
+OCStackResult initProcess(OCMode mode)
+{
+    return OCInit(NULL, 0, mode);
+}
+
+void startProcess()
+{
+    while(false == fExit)
+    {
+        if (OCProcess() != OC_STACK_OK)
+        {
+            OIC_LOG(ERROR, TAG,"OCProcess process error, exit\n");
+            break;
+        }
+    }
+
+    if (OCStop() != OC_STACK_OK)
+    {
+        OIC_LOG(ERROR, TAG, "OCStop process error\n");
+    }
+}
+
+void freeThreadResources()
+{
+    if (g_threadPoolHandle)
+    {
+        ca_thread_pool_free(g_threadPoolHandle);
+    }
+}
index 1f617bc..928943d 100644 (file)
 #ifndef CLOUD_COMMON_H
 #define CLOUD_COMMON_H
 
+#include "octypes.h"
+
+/**
+ * Used parse command line arguments
+ * Interpret given argument as database filename and check that given file exists
+ *
+ * @param[in] argc  count of command line parameters
+ * @param[in] argv  command line parameters
+ * @return  bool true if parameters are correct, false otherwise
+ */
+bool parseCommandLineArguments(int argc, char *argv[]);
+
+/**
+ * This function initializes persistent storage
+ * It uses database filename from global variable
+ *
+ * @return  OCStackResult application result
+ */
+OCStackResult initPersistentStorage();
+
+/**
+ * Used to display Main Menu and send requests
+ *
+ * @param[in] mode  OC_CLIENT/OC_SERVER mode
+ * @return  OCStackResult application result
+ */
+OCStackResult startRequestsThread(OCMode *mode);
+
+/**
+ * This function initialize main process
+ *
+ * @param[in] mode  in which mode process starts (client/server/both/gateway)
+ * @return  OCStackResult application result
+ */
+OCStackResult initProcess(OCMode mode);
+
+/**
+ * This function starts main process which responds to any requests
+ */
+void startProcess();
+
+/**
+ * This function frees thread pool data
+ */
+void freeThreadResources();
+
 /**
- * Used to sync with main menu
+ * Used to sync with Main Menu
  * Create this function to have proper API for delete callbacks
  *
  * @param[in] data         data
diff --git a/resource/csdk/security/provisioning/sample/cloud/cloudResource.c b/resource/csdk/security/provisioning/sample/cloud/cloudResource.c
new file mode 100644 (file)
index 0000000..4c1fcb2
--- /dev/null
@@ -0,0 +1,244 @@
+#include <string.h>
+#include "cloudCommon.h"
+#include "ocstack.h"
+#include "logger.h"
+#include "ocpayload.h"
+
+#include "cloudResource.h"
+
+#define TAG "cloudResource"
+
+LEDResource LED;
+char *gResourceUri = (char *)"/a/led";
+
+// This variable determines instance number of the LED resource.
+// Used by POST method to create a new instance of LED resource.
+static int gCurrLedInstance = 0;
+#define SAMPLE_MAX_NUM_POST_INSTANCE  2
+static LEDResource gLedInstance[SAMPLE_MAX_NUM_POST_INSTANCE];
+
+static OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
+{
+    OCRepPayload* payload = OCRepPayloadCreate();
+    if(!payload)
+    {
+        OIC_LOG(ERROR, TAG, "Failed to allocate Payload");
+        return NULL;
+    }
+
+    OCRepPayloadSetUri(payload, uri);
+    OCRepPayloadSetPropBool(payload, "state", state);
+    OCRepPayloadSetPropInt(payload, "power", power);
+
+    return payload;
+}
+
+static OCEntityHandlerResult ProcessRequest (OCEntityHandlerRequest *request,
+        OCRepPayload **payload)
+{
+    if(!request || !request->payload || request->payload->type != PAYLOAD_TYPE_REPRESENTATION)
+    {
+        OIC_LOG(ERROR, TAG, "Incoming payload not a representation");
+        return OC_EH_ERROR;
+    }
+
+    LEDResource *currLEDResource = &LED;
+
+    if (request->resource == gLedInstance[0].handle)
+    {
+        currLEDResource = &gLedInstance[0];
+        gResourceUri = (char *) "/a/led/0";
+    }
+    else if (request->resource == gLedInstance[1].handle)
+    {
+        currLEDResource = &gLedInstance[1];
+        gResourceUri = (char *) "/a/led/1";
+    }
+
+    if(OC_REST_PUT == request->method)
+    {
+        OCRepPayload* input = (OCRepPayload*)request->payload;
+        // Get pointer to query
+        int64_t pow;
+        if(OCRepPayloadGetPropInt(input, "power", &pow))
+        {
+            currLEDResource->power =pow;
+        }
+
+        bool state;
+        if(OCRepPayloadGetPropBool(input, "state", &state))
+        {
+            currLEDResource->state = state;
+        }
+    }
+
+    *payload = getPayload(gResourceUri, currLEDResource->power, currLEDResource->state);
+
+    return OC_EH_OK;
+}
+
+static OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *request,
+        char *resourceUri, OCRepPayload **payload)
+{
+    OCRepPayload *answer = NULL;
+    OCEntityHandlerResult result = OC_EH_OK;
+
+    /*
+     * The entity handler determines how to process a POST request.
+     * Per the REST paradigm, POST can also be used to update representation of existing
+     * resource or create a new resource.
+     * In the sample below, if the POST is for /a/led then a new instance of the LED
+     * resource is created with default representation (if representation is included in
+     * POST payload it can be used as initial values) as long as the instance is
+     * lesser than max new instance count. Once max instance count is reached, POST on
+     * /a/led updated the representation of /a/led (just like PUT)
+     */
+
+    if (request->resource == LED.handle)
+    {
+        if (gCurrLedInstance < SAMPLE_MAX_NUM_POST_INSTANCE)
+        {
+            // Create new LED instance
+            char uri[15] = "/a/led/";
+            int length = strlen(uri);
+            snprintf (uri + length, sizeof(uri) - length, "%d", gCurrLedInstance);
+
+            answer = OCRepPayloadCreate();
+            if (!answer)
+            {
+                OIC_LOG(ERROR, TAG, "Failed to allocate Payload");
+                return OC_EH_ERROR;
+            }
+
+            OCRepPayloadSetUri(answer, gResourceUri);
+            OCRepPayloadSetPropString(answer, "createduri", uri);
+
+            gLedInstance[gCurrLedInstance].power = 0;
+            gLedInstance[gCurrLedInstance].state = false;
+
+            if (OC_STACK_OK == createLEDResource(uri, &gLedInstance[gCurrLedInstance]))
+            {
+                OIC_LOG (INFO, TAG, "Created new LED instance");
+                gLedInstance[gCurrLedInstance].state = false;
+                gLedInstance[gCurrLedInstance].power = 0;
+                gCurrLedInstance++;
+                strncpy(resourceUri, uri, MAX_URI_LENGTH);
+                result = OC_EH_RESOURCE_CREATED;
+            }
+        }
+        else
+        {
+            result = ProcessRequest(request, &answer);
+        }
+    }
+    else
+    {
+        for (int i = 0; i < SAMPLE_MAX_NUM_POST_INSTANCE; i++)
+        {
+            if (request->resource == gLedInstance[i].handle)
+            {
+                result = ProcessRequest(request, &answer);
+                break;
+            }
+        }
+    }
+
+    if (answer)
+    {
+        *payload = answer;
+        result = OC_EH_OK;
+    }
+    else
+    {
+        OIC_LOG_V (INFO, TAG, "Payload was NULL");
+        result = OC_EH_ERROR;
+    }
+
+    return result;
+}
+
+static OCEntityHandlerResult
+OCLedHandler (OCEntityHandlerFlag flag,
+        OCEntityHandlerRequest *request,
+        void *params)
+{
+    OC_UNUSED(params);
+    OIC_LOG_V (INFO, TAG, "%s IN - flags: 0x%x", __func__, flag);
+
+    OCEntityHandlerResult result = OC_EH_ERROR;
+    char resourceUri[MAX_URI_LENGTH] = "";
+
+    if (!request)
+    {
+        OIC_LOG (ERROR, TAG, "Invalid request pointer");
+        return result;
+    }
+
+    OCRepPayload* payload = NULL;
+
+    if (flag & OC_REQUEST_FLAG)
+    {
+        OIC_LOG_V(INFO, TAG, "Received %d request method from client", request->method);
+
+        switch (request->method)
+        {
+            case OC_REST_GET:
+                result = ProcessRequest(request, &payload);
+                break;
+            case OC_REST_PUT:
+                result = ProcessRequest(request, &payload);
+                break;
+            case OC_REST_POST:
+                result = ProcessPostRequest(request, resourceUri, &payload);
+                break;
+            default:
+                OIC_LOG_V (ERROR, TAG, "Method %d doesn't supported!", request->method);
+                break;
+        }
+
+        if (result == OC_EH_OK)
+        {
+            // Format the response.  Note this requires some info about the request
+            OCEntityHandlerResponse response;
+            memset(&response, 0, sizeof(OCEntityHandlerResponse));
+
+            response.requestHandle = request->requestHandle;
+            response.resourceHandle = request->resource;
+            response.ehResult = result;
+            response.payload = (OCPayload*)payload;
+            response.numSendVendorSpecificHeaderOptions = 0;
+            // Indicate that response is NOT in a persistent buffer
+            response.persistentBufferFlag = 0;
+            if (resourceUri[0])
+            {
+                memcpy(response.resourceUri, resourceUri, sizeof(resourceUri));
+            }
+
+            // Send the response
+            if (OCDoResponse(&response) != OC_STACK_OK)
+            {
+                OIC_LOG(ERROR, TAG, "Error sending response");
+                result = OC_EH_ERROR;
+            }
+        }
+    }
+    OCRepPayloadDestroy(payload);
+    return result;
+}
+
+OCStackResult createLEDResource (char *uri, LEDResource *resource)
+{
+    if (!uri || !resource)
+    {
+        OIC_LOG(ERROR, TAG, "Resource URI and LED cannot be NULL");
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    return OCCreateResource(&resource->handle,
+            "core.led",
+            OC_RSRVD_INTERFACE_DEFAULT,
+            uri,
+            OCLedHandler,
+            NULL,
+            OC_DISCOVERABLE | OC_OBSERVABLE | OC_SECURE);
+}
diff --git a/resource/csdk/security/provisioning/sample/cloud/cloudResource.h b/resource/csdk/security/provisioning/sample/cloud/cloudResource.h
new file mode 100644 (file)
index 0000000..777c0ca
--- /dev/null
@@ -0,0 +1,38 @@
+/* *****************************************************************
+ *
+ * Copyright 2016 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.
+ *
+ * *****************************************************************/
+#ifndef CLOUD_RESOURCE_H
+#define CLOUD_RESOURCE_H
+
+typedef struct LEDRESOURCE{
+    OCResourceHandle handle;
+    bool state;
+    int power;
+} LEDResource;
+
+/**
+ * Creates resource with all required request handlers
+ *
+ * @param[in] uri          resource uri
+ * @param[in] resource     resource
+  * @return  OCStackResult application result
+ */
+OCStackResult createLEDResource (char *uri, LEDResource *resource);
+
+#endif // CLOUD_RESOURCE_H
index 60b9d86..50f32ec 100644 (file)
@@ -160,19 +160,12 @@ static void readOptionalStringArray(stringArray_t *list, int length, const char*
     }
 }
 
-/**
- * Copies whole binary file to crl variable
- *
- * @param[in] list           array of strings structure
- * @param[out] crl           byte array to fill
- * @return                   negative error code
- * */
-static int ReadFile(const char *name, OCByteString *crl)
+bool readFile(const char *name, OCByteString *out)
 {
     FILE *file = NULL;
     int length = 0;
     uint8_t *buffer = NULL;
-    int result = 1;
+    bool result = false;
 
     //Open file
     file = fopen(name, "rb");
@@ -183,8 +176,7 @@ static int ReadFile(const char *name, OCByteString *crl)
     }
 
     //Get file length
-    result = fseek(file, 0, SEEK_END);
-    if (result)
+    if (fseek(file, 0, SEEK_END))
     {
         OIC_LOG(ERROR, TAG, "Failed to SEEK_END");
         goto exit;
@@ -197,8 +189,7 @@ static int ReadFile(const char *name, OCByteString *crl)
         goto exit;
     }
 
-    result = fseek(file, 0, SEEK_SET);
-    if (result)
+    if (fseek(file, 0, SEEK_SET))
     {
         OIC_LOG(ERROR, TAG, "Failed to SEEK_SET");
         goto exit;
@@ -220,13 +211,13 @@ static int ReadFile(const char *name, OCByteString *crl)
         goto exit;
     }
 
-    crl->bytes = buffer;
-    crl->len   = length;
+    out->bytes = buffer;
+    out->len   = length;
 
-    result = 0;
+    result = true;
 exit:
     fclose(file);
-    return 0;
+    return result;
 }
 
 /**
@@ -294,7 +285,7 @@ OCStackResult OCWrapperPostCRL(const OCDevAddr *endPoint, OCCloudResponseCB call
         readString(filename, sizeof(filename),
                    "filename from which binary Crl in DER format will be read", "crl");
 
-        if (ReadFile(filename, &crlData))
+        if (!readFile(filename, &crlData))
         {
             printf("Can't read crl from file %s\n", filename);
             goto exit;
index a8f3116..a40a815 100644 (file)
@@ -239,5 +239,13 @@ void readString(char* item, int length, const char* description, const char* exa
  */
 void readInteger(int* item, const char* description, const char* example);
 
+/**
+ * Copies whole binary file to out variable
+ *
+ * @param[in] list           array of strings structure
+ * @param[out] out           byte array to fill
+ * @return                   negative error code
+ * */
+int readFile(const char *name, OCByteString *out);
 
 #endif //OC_CLOUD_WRAPPER_H
index 7659eca..78bf8a4 100644 (file)
-//******************************************************************
-//
-// Copyright 2016 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 <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#include "ocstack.h"
+#include "cloudCommon.h"
 #include "logger.h"
-#include "camutex.h"
-#include "cathreadpool.h"
-#include "ocpayload.h"
-#include "payload_logging.h"
-#include "ocprovisioningmanager.h"
-
-#include "utils.h"
-#include "cloudAuth.h"
-#include "cloudWrapper.h"
-#include "cloudDiscovery.h"
-
-#ifdef __unix__
-#include <unistd.h> //for unlink
-#endif
 
 #define TAG "cloudClient"
 
-#define DEFAULT_HOST            "10.113.68.85"//"127.0.0.1"
-#define DEFAULT_PORT            OC_MULTICAST_PORT
-#define DEFAULT_DEVICEID        "6A757374-776F-726B-4465-765575696430"
-#define DEFAULT_USERID          "6A757374-776F-726B-4465-765575696430"
-#define DEFAULT_AUTH_PROVIDER   "github"
-#define DEFAULT_DB_FILE         "./cloud.dat"
-#define DEFAULT_RESPONSE_WAIT_TIME (10 * 1000000) //10s
-
-#define GITHUB_AUTH_LINK        "https://github.com/login?return_to=%2Flogin%2Foauth%2Fauthorize%3Fclient_id%3Dea9c18f540323b0213d0%26redirect_uri%3Dhttp%253A%252F%252Fwww.example.com%252Foauth_callback%252F"
-
-static bool fExit = false;
-
-static OCDevAddr endPoint;
-static char token[1024];
-static char authProvider[1024];
-static char *fname = DEFAULT_DB_FILE;
-static uint64_t timeout;
-static uint16_t g_credId = 0;
-
-ca_cond cond;
-ca_mutex mutex;
-
-typedef enum {
-    SIGN_UP       = 1,
-    SIGN_IN       = 2,
-    SIGN_OUT      = 3,
-
-    HOST          = 4,
-    PORT          = 5,
-    DB_FILE       = 6,
-    AUTH_PROVIDER = 7,
-    USE_RSA = 8,
-    SAVE_TRUST_CERT = 9,
-    USE_SECURE_CONN = 10,
-
-    DISCOVERY     = 13,
-    GET           = 14,
-    PUT           = 15,
-    POST          = 16,
-
-    CSR_SIGN      = 19,
-
-    CRL_GET       = 20,
-    CRL_POST      = 21,
-
-    ACL_ID_CREATE = 30,
-    ACL_ID_GET_BY_DEVICE = 31,
-    ACL_ID_DELETE = 32,
-
-    ACL_INDIVIDUAL_GET_INFO = 40,
-    ACL_INDIVIDUAL_UPDATE_ACE = 41,
-    ACL_INDIVIDUAL_DELETE = 42,
-
-    ACL_GROUP_CREATE = 50,
-    ACL_GROUP_FIND   = 51,
-    ACL_GROUP_JOIN   = 52,
-    ACL_GROUP_OBSERVE= 53,
-    ACL_GROUP_DELETE = 54,
-
-    ACL_GROUP_SHARE_DEVICE  = 60,
-    ACL_GROUP_DELETE_DEVICE  = 61,
-    ACL_GROUP_GET_INFO  = 62,
-
-    ACL_POLICY_CHECK_REQUEST = 70,
-
-    ACL_GROUP_INVITE_USER = 80,
-    ACL_GROUP_GET_INVITE  = 81,
-    ACL_GROUP_DELETE_INVITE  = 82,
-    ACL_GROUP_CANCEL_INVITE  = 83,
-
-    EXIT          = 99
-}CloudRequest;
-
-void printMenu()
-{
-    printf("************************************************************\n");
-    printf("****************** Cloud Client Requests *******************\n");
-    printf("************************************************************\n");
-    printf("** AUTHORIZATION\n");
-    printf("** %d - Sign Up request\n", SIGN_UP);
-    printf("** %d - Sign In request\n", SIGN_IN);
-    printf("** %d - Sign Out request\n", SIGN_OUT);
-
-    printf("** SETTINGS \n");
-    printf("** %d - Change default host\n", HOST);
-    printf("** %d - Change default port\n", PORT);
-    printf("** %d - Change default database filename\n", DB_FILE);
-    printf("** %d - Change default auth provider\n", AUTH_PROVIDER);
-    printf("** %d - Change TLS cipher suite to RSA\n", USE_RSA);
-    printf("** %d - Save Trust Cert. Chain into Cred of SVR\n", SAVE_TRUST_CERT);
-    printf("** %d - Change Protocol type (CoAP/CoAPs)\n", USE_SECURE_CONN);
-
-    printf("** DISCOVERY\n");
-    printf("** %d - Start Discovery\n", DISCOVERY);
-    printf("** %d - Get Request\n", GET);
-    printf("** %d - Put Request\n", PUT);
-    printf("** %d - Post Request\n", POST);
-
-    printf("** CERTIFICATE REQUEST\n");
-    printf("** %d - Certificate Request\n", CSR_SIGN);
-
-    printf("** CRL\n");
-    printf("** %d - CRL GET Request\n", CRL_GET);
-    printf("** %d - CRL POST Request\n", CRL_POST);
-
-    printf("** ACL MANAGER\n");
-    printf("** %d - ACL id create Request\n", ACL_ID_CREATE);
-    printf("** %d - ACL id retrieve by device Request\n", ACL_ID_GET_BY_DEVICE);
-    printf("** %d - ACL id delete Request\n", ACL_ID_DELETE);
-
-    printf("** ACL INDIVIDUAL\n");
-    printf("** %d - ACL individual get info Request\n", ACL_INDIVIDUAL_GET_INFO);
-    printf("** %d - ACL individual update ACE Request\n", ACL_INDIVIDUAL_UPDATE_ACE);
-    printf("** %d - ACL individual delete Request\n", ACL_INDIVIDUAL_DELETE);
-
-    printf("** ACL GROUP MANAGER\n");
-    printf("** %d - ACL Create Group Request\n", ACL_GROUP_CREATE);
-    printf("** %d - ACL Find Group Request\n", ACL_GROUP_FIND);
-    printf("** %d - ACL Join to invited Group Request\n", ACL_GROUP_JOIN);
-    printf("** %d - ACL Observe Group Request\n", ACL_GROUP_OBSERVE);
-    printf("** %d - ACL Delete Group Request\n", ACL_GROUP_DELETE);
-
-    printf("** ACL INDIVIDUAL GROUP\n");
-    printf("** %d - ACL Share device into Group Request\n", ACL_GROUP_SHARE_DEVICE);
-    printf("** %d - ACL Delete device from Group Request\n", ACL_GROUP_DELETE_DEVICE);
-    printf("** %d - ACL Get Group Info Request\n", ACL_GROUP_GET_INFO);
-
-    printf("** ACL POLICY ENFORCEMENT\n");
-    printf("** %d - ACL Check Permissions Request\n", ACL_POLICY_CHECK_REQUEST);
-
-    printf("** ACL MEMBER INVITATION\n");
-    printf("** %d - ACL Invite user to group Request\n", ACL_GROUP_INVITE_USER);
-    printf("** %d - ACL Retrieve invitation Request\n", ACL_GROUP_GET_INVITE);
-    printf("** %d - ACL Delete invitation Request\n", ACL_GROUP_DELETE_INVITE);
-    printf("** %d - ACL Cancel invitation Request\n", ACL_GROUP_CANCEL_INVITE);
-
-    printf("** EXIT\n");
-    printf("** %d - Exit cloud client\n\n", EXIT);
-    printf("************************************************************\n");
-
-    printf(">> Enter Menu number:\n");
-}
-
-void unlockMenu(void *data)
-{
-    OICFree(data);
-
-    ca_mutex_lock(mutex);
-    ca_cond_signal(cond);
-    ca_mutex_unlock(mutex);
-}
-
-/**
- * This is default callback to all requests
- * Used to sync with main menu
- *
- * @param[in] ctx          context
- * @param[in] result       result
- * @param[in] data         data
- */
-static void handleCB(void* ctx, OCStackResult result, void* data)
-{
-    OC_UNUSED(ctx);
-    OC_UNUSED(data);
-
-    OIC_LOG_V(INFO, TAG, "%s: Received result = %d", __func__, result);
-
-    unlockMenu(NULL);
-}
-
-static int saveTrustCert(void)
-{
-    OCStackResult res = OC_STACK_ERROR;
-    OIC_LOG(INFO, TAG, "Save Trust Cert. Chain into Cred of SVR");
-
-    ByteArray trustCertChainArray = {0, 0};
-
-    FILE *fp = fopen("rootca.crt", "rb+");
-
-    if (fp)
-    {
-        size_t fsize;
-        if (fseeko(fp, 0, SEEK_END) == 0 && (fsize = ftello(fp)))
-        {
-            trustCertChainArray.data = OICCalloc(1, fsize);
-            trustCertChainArray.len = fsize;
-            if (NULL == trustCertChainArray.data)
-            {
-                OIC_LOG(ERROR,TAG,"OICCalloc");
-                fclose(fp);
-                return res;
-            }
-            rewind(fp);
-            fsize = fread(trustCertChainArray.data, 1, fsize, fp);
-            fclose(fp);
-        }
-    }
-    OIC_LOG_BUFFER(DEBUG, TAG, trustCertChainArray.data, trustCertChainArray.len);
-
-    res = OCSaveTrustCertChain(trustCertChainArray.data, trustCertChainArray.len, OIC_ENCODING_PEM,&g_credId);
-
-    if(OC_STACK_OK != res)
-    {
-        OIC_LOG(ERROR, TAG, "OCSaveTrustCertChainBin API error");
-        return res;
-    }
-    OIC_LOG_V(INFO, TAG, "CredId of Saved Trust Cert. Chain into Cred of SVR : %d.\n", g_credId);
-
-    return res;
-}
-
-static void userRequests()
-{
-    //defaults
-    memset(token, 0, sizeof(token));
-    memset(authProvider, 0, sizeof(authProvider));
-    strncpy(authProvider, DEFAULT_AUTH_PROVIDER, sizeof(authProvider));
-    memset(&endPoint, 0, sizeof(endPoint));
-    strncpy(endPoint.addr, DEFAULT_HOST, sizeof(endPoint.addr));
-    endPoint.port = DEFAULT_PORT;
-
-    mutex = ca_mutex_new();
-    cond = ca_cond_new();
-
-    while (false == fExit)
-    {
-        OCStackResult res = OC_STACK_ERROR;
-        timeout = DEFAULT_RESPONSE_WAIT_TIME;
-        //startup report
-        printf("-----------------------------------------------------------\n");
-        printf("Connecting to: %s:%d\n", endPoint.addr, endPoint.port);
-        printf("via auth provider: %s\n", authProvider);
-        printf("srv file: %s\n", fname);
-        printf("CoAP prefix: %s\n", DEFAULT_PREFIX);
-        printf("-----------------------------------------------------------\n");
-
-        printMenu();
-
-        int request = 0;
-        scanf("%d", &request);
-
-        switch (request)
-        {
-        case SIGN_UP:
-            if (0 == strncmp(authProvider, DEFAULT_AUTH_PROVIDER, sizeof(authProvider)))
-            {
-                printf("Paste to browser %s and get auth code\n", GITHUB_AUTH_LINK);
-            }
-            readString(token, sizeof(token), "auth token", "check link above");
-            res = CloudSignUp(&endPoint, authProvider, token);
-            break;
-        case SIGN_IN:
-            res = CloudSignIn(&endPoint);
-            break;
-        case SIGN_OUT:
-            res = CloudSignOut(&endPoint);
-            break;
-        case HOST:
-            readString(endPoint.addr, sizeof(endPoint.addr), "host ip address", DEFAULT_HOST);
-            break;
-        case PORT:
-        {
-            char example[8];
-            snprintf(example, sizeof(example), "%d", DEFAULT_PORT);
-            int tmp = 0;
-            readInteger(&tmp, "port number", example);
-            endPoint.port = tmp;
-        }
-        break;
-        case CRL_GET:
-            res = OCWrapperGetCRL(&endPoint, handleCB);
-            break;
-        case CRL_POST:
-            res = OCWrapperPostCRL(&endPoint, handleCB);
-            break;
-        case ACL_GROUP_CREATE:
-            res = OCWrapperAclCreateGroup(&endPoint, handleCB);
-            break;
-        case ACL_GROUP_FIND:
-            res = OCWrapperAclFindMyGroup(&endPoint, handleCB);
-            break;
-        case ACL_GROUP_DELETE:
-            res = OCWrapperAclDeleteGroup(&endPoint, handleCB);
-            break;
-        case ACL_GROUP_JOIN:
-            res = OCWrapperAclJoinToInvitedGroup(&endPoint, handleCB);
-            break;
-        case ACL_GROUP_OBSERVE:
-            res = OCWrapperAclObserveGroup(&endPoint, handleCB);
-            break;
-        case ACL_GROUP_SHARE_DEVICE:
-            res = OCWrapperAclShareDeviceIntoGroup(&endPoint, handleCB);
-            break;
-        case ACL_GROUP_DELETE_DEVICE:
-            res = OCWrapperAclDeleteDeviceFromGroup(&endPoint, handleCB);
-            break;
-        case ACL_GROUP_GET_INFO:
-            res = OCWrapperAclGroupGetInfo(&endPoint, handleCB);
-            break;
-        case ACL_GROUP_INVITE_USER:
-            res = OCWrapperAclInviteUser(&endPoint, handleCB);
-            break;
-        case ACL_GROUP_GET_INVITE:
-            res = OCWrapperAclGetInvitation(&endPoint, handleCB);
-            break;
-        case ACL_GROUP_DELETE_INVITE:
-            res = OCWrapperAclDeleteInvitation(&endPoint, handleCB);
-            break;
-        case ACL_GROUP_CANCEL_INVITE:
-            res = OCWrapperAclCancelInvitation(&endPoint, handleCB);
-            break;
-        case ACL_POLICY_CHECK_REQUEST:
-            res = OCWrapperAclPolicyCheck(&endPoint, handleCB);
-            break;
-        case ACL_ID_GET_BY_DEVICE:
-            res = OCWrapperAclIdGetByDevice(&endPoint, handleCB);
-            break;
-        case ACL_ID_CREATE:
-            res = OCWrapperAclIdCreate(&endPoint, handleCB);
-            break;
-        case ACL_ID_DELETE:
-            res = OCWrapperAclIdDelete(&endPoint, handleCB);
-            break;
-        case ACL_INDIVIDUAL_GET_INFO:
-            res = OCWrapperAclIndividualGetInfo(&endPoint, handleCB);
-            break;
-        case ACL_INDIVIDUAL_UPDATE_ACE:
-            res = OCWrapperAclIndividualUpdateAce(&endPoint, handleCB);
-            break;
-        case ACL_INDIVIDUAL_DELETE:
-            res = OCWrapperAclIndividualDelete(&endPoint, handleCB);
-            break;
-        case CSR_SIGN:
-            res = OCWrapperCertificateIssueRequest(&endPoint, handleCB);
-            break;
-        case DISCOVERY:
-            res = InitDiscovery();
-            break;
-        case GET:
-            res = InitRequest(OC_REST_GET);
-            break;
-        case PUT:
-            res= InitRequest(OC_REST_PUT);
-            break;
-        case POST:
-            res= InitRequest(OC_REST_POST);
-            break;
-        case USE_RSA:
-            CASelectCipherSuite(0x35, CA_ADAPTER_TCP);
-            break;
-        case SAVE_TRUST_CERT:
-            saveTrustCert();
-            break;
-        case USE_SECURE_CONN:
-        {
-            int tmp = 0;
-            readInteger(&tmp, "CoAP protocol type", "0 - non-secure, 1 - secure");
-            setCoapPrefix(0 == tmp ? false : true);
-        }
-            break;
-        case EXIT:
-            ca_mutex_free(mutex);
-            ca_cond_free(cond);
-            fExit = true;
-            break;
-        default:
-            printf(">> Entered Wrong Menu Number. Please Enter Again\n\n");
-            break;
-        }
-
-        //if requests were sent then wait response
-        if (res == OC_STACK_OK)
-        {
-            ca_mutex_lock(mutex);
-            ca_cond_wait_for(cond, mutex, timeout);
-            ca_mutex_unlock(mutex);
-        }
-    }
-}
-
-FILE* server_fopen(const char *path, const char *mode)
-{
-    OC_UNUSED(path);
-    return fopen(fname, mode);
-}
-
-/**
- * Check file accessibility
- *
- * @param[in] name        file path
- * @return true           if check was successful
- */
-static bool checkConfig(const char *name)
-{
-    FILE* file = fopen(name, "rb");
-
-    if (file)
-    {
-        fclose(file);
-        return true;
-    }
-    return false;
-}
-
-static void printUsage(char *name)
-{
-    printf("Wrong arguments count!\n");
-    printf("Usage : %s <database_filename>\n", name);
-    printf("Examples : 1) %s 2) %s cloud.dat\n", name, name);
-}
-
-//==============================================================
 int main(int argc, char *argv[])
 {
-    OC_UNUSED(argc);
-    OC_UNUSED(argv);
-
-    if (2 == argc)
+    if (!parseCommandLineArguments(argc, argv))
     {
-        fname = argv[1];
-
-        if (!checkConfig(fname))
-        {
-            OIC_LOG_V(ERROR, TAG, "Can't open database file %s, exit!", fname);
-            return -1;
-        }
+        return -1;
     }
-    else if (argc > 2)
-    {
-        printUsage(argv[0]);
-    }
-
-    //Initialize Persistent Storage for SVR database
-    OCPersistentStorage ps = {server_fopen, fread, fwrite, fclose, unlink};
 
-    OCRegisterPersistentStorageHandler(&ps);
-
-    OCMode stackMode = OC_CLIENT_SERVER;
-    if (OCInit(NULL, 0, stackMode) != OC_STACK_OK)
+    if (OC_STACK_OK != initPersistentStorage())
     {
-        OIC_LOG(ERROR, TAG, "OCStack init error, exit\n");
-        return 1;
+        return -2;
     }
 
-    ca_thread_pool_t g_threadPoolHandle = NULL;
-    CAResult_t res = ca_thread_pool_init(1, &g_threadPoolHandle);
-    if (CA_STATUS_OK != res)
+    if (OC_STACK_OK != initProcess(OC_CLIENT_SERVER))
     {
-        OIC_LOG(ERROR, TAG, "thread pool initialize error.");
-        return res;
+        OIC_LOG(ERROR, TAG, "initProcess error, exit\n");
+        return -3;
     }
 
-    res = ca_thread_pool_add_task(g_threadPoolHandle, userRequests, NULL);
-    if (CA_STATUS_OK != res)
+    OCMode mode = OC_CLIENT;
+    if (OC_STACK_OK != startRequestsThread(&mode))
     {
-        OIC_LOG(ERROR, TAG, "thread pool add task error.");
-        goto error;
+        return -4;
     }
 
-    while(false == fExit)
-    {
-        if (OCProcess() != OC_STACK_OK)
-        {
-            OIC_LOG(ERROR, TAG,"OCProcess process error, exit\n");
-            return 2;
-        }
-    }
+    startProcess();
 
-    if (OCStop() != OC_STACK_OK)
-    {
-        OIC_LOG(ERROR, TAG, "OCStop process error\n");
-    }
-
-    error:
-    if (g_threadPoolHandle)
-    {
-        ca_thread_pool_free(g_threadPoolHandle);
-    }
+    freeThreadResources();
 
     return 0;
 }
diff --git a/resource/csdk/security/provisioning/sample/cloudServer.c b/resource/csdk/security/provisioning/sample/cloudServer.c
new file mode 100644 (file)
index 0000000..c120a76
--- /dev/null
@@ -0,0 +1,49 @@
+#include "cloudCommon.h"
+#include "logger.h"
+#include "cloudResource.h"
+
+#define TAG "cloudServer"
+
+extern LEDResource LED;
+extern char *gResourceUri;
+
+int main(int argc, char *argv[])
+{
+    if (!parseCommandLineArguments(argc, argv))
+    {
+        return -1;
+    }
+
+    if (OC_STACK_OK != initPersistentStorage())
+    {
+        return -2;
+    }
+
+    if (OC_STACK_OK != initProcess(OC_CLIENT_SERVER))
+    {
+        OIC_LOG(ERROR, TAG, "initProcess error, exit\n");
+        return -3;
+    }
+
+    LED.state = false;
+    LED.power = 0;
+    /*
+     * Declare and create the example resource: LED
+     */
+    if (OC_STACK_OK != createLEDResource(gResourceUri, &LED))
+    {
+        return -4;
+    }
+
+    OCMode mode = OC_SERVER;
+    if (OC_STACK_OK != startRequestsThread(&mode))
+    {
+        return -5;
+    }
+
+    startProcess();
+
+    freeThreadResources();
+
+    return 0;
+}