Imported Upstream version 0.9.2
[platform/upstream/iotivity.git] / resource / csdk / stack / samples / linux / secure / occlientbasicops.cpp
index 5f8d7b6..dd84fc3 100644 (file)
 #include "ocstack.h"
 #include "logger.h"
 #include "occlientbasicops.h"
-#include "cJSON.h"
+#include "ocpayload.h"
 #include "common.h"
 
 #define TAG "occlientbasicops"
 static int UNICAST_DISCOVERY = 0;
 static int TEST_CASE = 0;
+static int CONN_TYPE = 0;
 
-static int IPV4_ADDR_SIZE = 16;
-static char UNICAST_DISCOVERY_QUERY[] = "coap://%s:6298/oc/core";
-static char MULTICAST_DISCOVERY_QUERY[] = "/oc/core";
+static int IPV4_ADDR_SIZE = 24;
+static char UNICAST_DISCOVERY_QUERY[] = "coap://%s/oic/res";
+static char MULTICAST_DISCOVERY_QUERY[] = "/oic/res";
+OCConnectivityType discoveryReqConnType = CT_ADAPTER_IP;
 
-static std::string putPayload = "{\"state\":\"off\",\"power\":10}";
 static std::string coapServerIP;
 static std::string coapServerPort;
 static std::string coapServerResource;
@@ -47,10 +48,10 @@ static int coapSecureResource;
 static OCConnectivityType ocConnType;
 
 
-//File containing Client's Identity and the PSK credentials
+//Secure Virtual Resource database for Iotivity Client application
+//It contains Client's Identity and the PSK credentials
 //of other devices which the client trusts
-//This can be generated using 'gen_sec_bin' application
-static char CRED_FILE[] = "client_cred.bin";
+static char CRED_FILE[] = "oic_svr_db_client.json";
 
 
 int gQuitFlag = 0;
@@ -64,14 +65,32 @@ void handleSigInt(int signum)
     }
 }
 
+OCPayload* putPayload()
+{
+    OCRepPayload* payload = OCRepPayloadCreate();
+
+    if(!payload)
+    {
+        std::cout << "Failed to create put payload object"<<std::endl;
+        std::exit(1);
+    }
+
+    OCRepPayloadSetPropInt(payload, "power", 15);
+    OCRepPayloadSetPropBool(payload, "state", true);
+
+    return (OCPayload*) payload;
+}
+
 static void PrintUsage()
 {
-    OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3>");
+    OC_LOG(INFO, TAG, "Usage : occlient -u <0|1> -t <1|2|3> -c <0|1>");
     OC_LOG(INFO, TAG, "-u <0|1> : Perform multicast/unicast discovery of resources");
     OC_LOG(INFO, TAG, "-t 1 : Discover Resources");
     OC_LOG(INFO, TAG, "-t 2 : Discover Resources and"
             " Initiate Nonconfirmable Get/Put/Post Requests");
     OC_LOG(INFO, TAG, "-t 3 : Discover Resources and Initiate Confirmable Get/Put/Post Requests");
+    OC_LOG(INFO, TAG, "-c 0 : Default auto-selection");
+    OC_LOG(INFO, TAG, "-c 1 : IPv4 Connectivity Type");
 }
 
 OCStackResult InvokeOCDoResource(std::ostringstream &query,
@@ -86,7 +105,7 @@ OCStackResult InvokeOCDoResource(std::ostringstream &query,
     cbData.cd = NULL;
 
     ret = OCDoResource(NULL, method, query.str().c_str(), 0,
-            (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload.c_str() : NULL,
+            (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload() : NULL,
             ocConnType, qos, &cbData, options, numOptions);
 
     if (ret != OC_STACK_OK)
@@ -104,7 +123,8 @@ OCStackApplicationResult putReqCB(void* ctx, OCDoHandle handle, OCClientResponse
     if(clientResponse)
     {
         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
-        OC_LOG_V(INFO, TAG, "JSON = %s =============> Put Response", clientResponse->resJSONPayload);
+        OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
+        OC_LOG(INFO, TAG, PCF("=============> Put Response"));
     }
     return OC_STACK_DELETE_TRANSACTION;
 }
@@ -116,8 +136,8 @@ OCStackApplicationResult postReqCB(void *ctx, OCDoHandle handle, OCClientRespons
     if(clientResponse)
     {
         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
-        OC_LOG_V(INFO, TAG, "JSON = %s =============> Post Response",
-                clientResponse->resJSONPayload);
+        OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
+        OC_LOG(INFO, TAG, PCF("=============> Post Response"));
     }
     return OC_STACK_DELETE_TRANSACTION;
 }
@@ -130,8 +150,8 @@ OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse
     {
         OC_LOG_V(INFO, TAG, "StackResult: %s",  getResult(clientResponse->result));
         OC_LOG_V(INFO, TAG, "SEQUENCE NUMBER: %d", clientResponse->sequenceNumber);
-        OC_LOG_V(INFO, TAG, "JSON = %s =============> Get Response",
-                clientResponse->resJSONPayload);
+        OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
+        OC_LOG(INFO, TAG, PCF("=============> Get Response"));
     }
     return OC_STACK_DELETE_TRANSACTION;
 }
@@ -140,40 +160,37 @@ OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse
 OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
         OCClientResponse * clientResponse)
 {
-    uint8_t remoteIpAddr[4];
-    uint16_t remotePortNu;
-
     OC_LOG(INFO, TAG, "Callback Context for DISCOVER query recvd successfully");
 
     if (clientResponse)
     {
         OC_LOG_V(INFO, TAG, "StackResult: %s", getResult(clientResponse->result));
-
-        OCDevAddrToIPv4Addr((OCDevAddr *) clientResponse->addr, remoteIpAddr,
-                remoteIpAddr + 1, remoteIpAddr + 2, remoteIpAddr + 3);
-        OCDevAddrToPort((OCDevAddr *) clientResponse->addr, &remotePortNu);
-
         OC_LOG_V(INFO, TAG,
-                "Device =============> Discovered %s @ %d.%d.%d.%d:%d",
-                clientResponse->resJSONPayload, remoteIpAddr[0], remoteIpAddr[1],
-                remoteIpAddr[2], remoteIpAddr[3], remotePortNu);
-
-        ocConnType = clientResponse->connType;
+                "Device =============> Discovered @ %s:%d",
+                clientResponse->devAddr.addr,
+                clientResponse->devAddr.port);
 
-        if (parseClientResponse(clientResponse) != -1)
+        if (clientResponse->result == OC_STACK_OK)
         {
-            switch(TEST_CASE)
+            OC_LOG_PAYLOAD(INFO, TAG, clientResponse->payload);
+
+            ocConnType = clientResponse->connType;
+
+            if (parseClientResponse(clientResponse) != -1)
             {
-                case TEST_NON_CON_OP:
-                    InitGetRequest(OC_LOW_QOS);
-                    InitPutRequest(OC_LOW_QOS);
-                    //InitPostRequest(OC_LOW_QOS);
-                    break;
-                case TEST_CON_OP:
-                    InitGetRequest(OC_HIGH_QOS);
-                    InitPutRequest(OC_HIGH_QOS);
-                    //InitPostRequest(OC_HIGH_QOS);
-                    break;
+                switch(TEST_CASE)
+                {
+                    case TEST_NON_CON_OP:
+                        InitGetRequest(OC_LOW_QOS);
+                        InitPutRequest(OC_LOW_QOS);
+                        //InitPostRequest(OC_LOW_QOS);
+                        break;
+                    case TEST_CON_OP:
+                        InitGetRequest(OC_HIGH_QOS);
+                        InitPutRequest(OC_HIGH_QOS);
+                        //InitPostRequest(OC_HIGH_QOS);
+                        break;
+                }
             }
         }
     }
@@ -239,14 +256,15 @@ int InitGetRequest(OCQualityOfService qos)
 int InitDiscovery()
 {
     OCStackResult ret;
+    OCMethod method;
     OCCallbackData cbData;
     char szQueryUri[MAX_URI_LENGTH] = { 0 };
-    OCConnectivityType discoveryReqConnType;
 
     if (UNICAST_DISCOVERY)
     {
         char ipv4addr[IPV4_ADDR_SIZE];
-        printf("Enter IPv4 address of the Server hosting secure resource (Ex: 11.12.13.14)\n");
+        OC_LOG(INFO, TAG, "Enter IPv4 address:port of the Server hosting secure resource"\
+                "(Ex: 11.12.13.14:1234)\n");
         if (fgets(ipv4addr, IPV4_ADDR_SIZE, stdin))
         {
             //Strip newline char from ipv4addr
@@ -258,13 +276,14 @@ int InitDiscovery()
             OC_LOG(ERROR, TAG, "!! Bad input for IPV4 address. !!");
             return OC_STACK_INVALID_PARAM;
         }
-        discoveryReqConnType = OC_IPV4;
+        method = OC_REST_GET;
     }
     else
     {
         //Send discovery request on Wifi and Ethernet interface
-        discoveryReqConnType = OC_ALL;
+        discoveryReqConnType = CT_DEFAULT;
         strcpy(szQueryUri, MULTICAST_DISCOVERY_QUERY);
+        method = OC_REST_DISCOVER;
     }
 
     cbData.cb = discoveryReqCB;
@@ -276,7 +295,7 @@ int InitDiscovery()
         (UNICAST_DISCOVERY) ? "Unicast" : "Multicast",
         szQueryUri);
 
-    ret = OCDoResource(NULL, OC_REST_GET, szQueryUri, 0, 0,
+    ret = OCDoResource(NULL, method, szQueryUri, 0, 0,
             discoveryReqConnType, OC_LOW_QOS,
             &cbData, NULL, 0);
     if (ret != OC_STACK_OK)
@@ -286,12 +305,18 @@ int InitDiscovery()
     return ret;
 }
 
+FILE* client_fopen(const char *path, const char *mode)
+{
+    (void)path;
+    return fopen(CRED_FILE, mode);
+}
+
 int main(int argc, char* argv[])
 {
     int opt;
     struct timespec timeout;
 
-    while ((opt = getopt(argc, argv, "u:t:")) != -1)
+    while ((opt = getopt(argc, argv, "u:t:c:")) != -1)
     {
         switch(opt)
         {
@@ -301,6 +326,9 @@ int main(int argc, char* argv[])
             case 't':
                 TEST_CASE = atoi(optarg);
                 break;
+            case 'c':
+                CONN_TYPE = atoi(optarg);
+                break;
             default:
                 PrintUsage();
                 return -1;
@@ -308,26 +336,38 @@ int main(int argc, char* argv[])
     }
 
     if ((UNICAST_DISCOVERY != 0 && UNICAST_DISCOVERY != 1) ||
-            (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS) )
+            (TEST_CASE < TEST_DISCOVER_REQ || TEST_CASE >= MAX_TESTS)||
+            (CONN_TYPE < CT_ADAPTER_DEFAULT || CONN_TYPE >= MAX_CT))
     {
         PrintUsage();
         return -1;
     }
 
-    /* Initialize OCStack*/
-    if (OCInit(NULL, 0, OC_CLIENT) != OC_STACK_OK)
+
+    if(CONN_TYPE == CT_ADAPTER_DEFAULT || CONN_TYPE ==  CT_IP)
     {
-        OC_LOG(ERROR, TAG, "OCStack init error");
-        return 0;
+        discoveryReqConnType = CT_DEFAULT;
     }
+    else
+    {
+        OC_LOG(INFO, TAG, "Using Default Connectivity type");
+        PrintUsage();
+    }
+
+
+    // Initialize Persistent Storage for SVR database
+    OCPersistentStorage ps = {};
+    ps.open = client_fopen;
+    ps.read = fread;
+    ps.write = fwrite;
+    ps.close = fclose;
+    ps.unlink = unlink;
+    OCRegisterPersistentStorageHandler(&ps);
 
-    /*
-     * Read DTLS PSK credentials from persistent storage and
-     * set in the OC stack.
-     */
-    if (SetCredentials(CRED_FILE) != OC_STACK_OK)
+    /* Initialize OCStack*/
+    if (OCInit(NULL, 0, OC_CLIENT_SERVER) != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "SetCredentials failed");
+        OC_LOG(ERROR, TAG, "OCStack init error");
         return 0;
     }
 
@@ -359,36 +399,17 @@ int main(int argc, char* argv[])
     return 0;
 }
 
-std::string getIPAddrTBServer(OCClientResponse * clientResponse)
-{
-    if(!clientResponse) return "";
-    if(!clientResponse->addr) return "";
-    uint8_t a, b, c, d = 0;
-    if(0 != OCDevAddrToIPv4Addr(clientResponse->addr, &a, &b, &c, &d) ) return "";
-
-    char ipaddr[16] = {'\0'};
-    // ostringstream not working correctly here, hence snprintf
-    snprintf(ipaddr,  sizeof(ipaddr), "%d.%d.%d.%d", a,b,c,d);
-    return std::string (ipaddr);
-}
-
-
 std::string getPortTBServer(OCClientResponse * clientResponse)
 {
     if(!clientResponse) return "";
-    if(!clientResponse->addr) return "";
-    uint16_t p = 0;
-    if(0 != OCDevAddrToPort(clientResponse->addr, &p) ) return "";
     std::ostringstream ss;
-    ss << p;
+    ss << clientResponse->devAddr.port;
     return ss.str();
 }
 
 int parseClientResponse(OCClientResponse * clientResponse)
 {
-    int port = -1;
-    cJSON * root = NULL;
-    cJSON * oc = NULL;
+    OCResourcePayload* res = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
 
     // Initialize all global variables
     coapServerResource.clear();
@@ -396,66 +417,40 @@ int parseClientResponse(OCClientResponse * clientResponse)
     coapServerIP.clear();
     coapSecureResource = 0;
 
-    root = cJSON_Parse((char *)(clientResponse->resJSONPayload));
-    if (!root)
+    while(res)
     {
-        return -1;
-    }
+        coapServerResource.assign(res->uri);
+        OC_LOG_V(INFO, TAG, "Uri -- %s", coapServerResource.c_str());
 
-    oc = cJSON_GetObjectItem(root,"oc");
-    if (!oc)
-    {
-        return -1;
-    }
-
-    if (oc->type == cJSON_Array)
-    {
-        if (cJSON_GetArraySize(oc) > 0)
+        if(res->secure)
         {
-            cJSON * resource = cJSON_GetArrayItem(oc, 0);
-            if (cJSON_GetObjectItem(resource, "href"))
-            {
-                coapServerResource.assign(cJSON_GetObjectItem(resource, "href")->valuestring);
-            }
-            else
-            {
-                coapServerResource = "";
-            }
-            OC_LOG_V(INFO, TAG, "Uri -- %s", coapServerResource.c_str());
+            coapSecureResource = 1;
+        }
 
-            cJSON * prop = cJSON_GetObjectItem(resource,"prop");
-            if (prop)
-            {
-                // If this is a secure resource, the info about the port at which the
-                // resource is hosted on server is embedded inside discovery JSON response
-                if (cJSON_GetObjectItem(prop, "sec"))
-                {
-                    if ((cJSON_GetObjectItem(prop, "sec")->valueint) == 1)
-                    {
-                        coapSecureResource = 1;
-                    }
-                }
-                OC_LOG_V(INFO, TAG, "Secure -- %s", coapSecureResource == 1 ? "YES" : "NO");
-                if (cJSON_GetObjectItem(prop, "port"))
-                {
-                    port = cJSON_GetObjectItem(prop, "port")->valueint;
-                    OC_LOG_V(INFO, TAG, "Hosting Server Port (embedded inside JSON) -- %u", port);
+        OC_LOG_V(INFO, TAG, "Secure -- %s", coapSecureResource == 1 ? "YES" : "NO");
 
-                    std::ostringstream ss;
-                    ss << port;
-                    coapServerPort = ss.str();
-                }
-            }
+        std::ostringstream ss;
+        ss << res->port;
+        coapServerPort = ss.str();
+        std::cout<<"PORT: "<<coapServerPort;
+
+        // If we discovered a secure resource, exit from here
+        if (coapSecureResource)
+        {
+            break;
         }
+
+        res = res->next;
     }
-    cJSON_Delete(root);
 
-    coapServerIP = getIPAddrTBServer(clientResponse);
-    if (port == -1)
+    coapServerIP = clientResponse->devAddr.addr;
+
+    if(coapServerPort.length() == 0 || coapServerPort == "0")
     {
         coapServerPort = getPortTBServer(clientResponse);
         OC_LOG_V(INFO, TAG, "Hosting Server Port -- %s", coapServerPort.c_str());
     }
+
     return 0;
 }