IP address plumbing changes to support IPv6
[platform/upstream/iotivity.git] / resource / csdk / stack / samples / linux / secure / occlientbasicops.cpp
index e4125d2..ebc65a7 100644 (file)
 #define TAG "occlientbasicops"
 static int UNICAST_DISCOVERY = 0;
 static int TEST_CASE = 0;
-static const char * TEST_APP_UNICAST_DISCOVERY_QUERY = "coap://0.0.0.0:5683/oc/core";
-static std::string putPayload = "{\"state\":\"off\",\"power\":10}";
+
+static int IPV4_ADDR_SIZE = 16;
+static char UNICAST_DISCOVERY_QUERY[] = "coap://%s:6298/oic/res";
+static char MULTICAST_DISCOVERY_QUERY[] = "/oic/res";
+
+static std::string putPayload = "{\"oic\":[{\"rep\":{\"state\":\"off\",\"power\":10}}]}";
 static std::string coapServerIP;
 static std::string coapServerPort;
 static std::string coapServerResource;
 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;
@@ -74,15 +80,14 @@ OCStackResult InvokeOCDoResource(std::ostringstream &query,
 {
     OCStackResult ret;
     OCCallbackData cbData;
-    OCDoHandle handle;
 
     cbData.cb = cb;
     cbData.context = NULL;
     cbData.cd = NULL;
 
-    ret = OCDoResource(&handle, method, query.str().c_str(), 0,
+    ret = OCDoResource(NULL, method, query.str().c_str(), 0,
             (method == OC_REST_PUT || method == OC_REST_POST) ? putPayload.c_str() : NULL,
-            qos, &cbData, options, numOptions);
+            ocConnType, qos, &cbData, options, numOptions);
 
     if (ret != OC_STACK_OK)
     {
@@ -135,23 +140,16 @@ 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);
+                "Device =============> Discovered %s @ %s:%d",
+                clientResponse->resJSONPayload, clientResponse->devAddr.addr, clientResponse->devAddr.port);
+
+        ocConnType = clientResponse->connType;
 
         if (parseClientResponse(clientResponse) != -1)
         {
@@ -159,12 +157,12 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
             {
                 case TEST_NON_CON_OP:
                     InitGetRequest(OC_LOW_QOS);
-                    InitPutRequest();
+                    InitPutRequest(OC_LOW_QOS);
                     //InitPostRequest(OC_LOW_QOS);
                     break;
                 case TEST_CON_OP:
                     InitGetRequest(OC_HIGH_QOS);
-                    InitPutRequest();
+                    InitPutRequest(OC_HIGH_QOS);
                     //InitPostRequest(OC_HIGH_QOS);
                     break;
             }
@@ -175,13 +173,14 @@ OCStackApplicationResult discoveryReqCB(void* ctx, OCDoHandle handle,
 
 }
 
-int InitPutRequest()
+int InitPutRequest(OCQualityOfService qos)
 {
     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
     std::ostringstream query;
     query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
-        << ":" << coapServerPort << coapServerResource;
-    return (InvokeOCDoResource(query, OC_REST_PUT, OC_LOW_QOS, putReqCB, NULL, 0));
+        << ":" << coapServerPort  << coapServerResource;
+    return (InvokeOCDoResource(query, OC_REST_PUT,
+            ((qos == OC_HIGH_QOS) ? OC_HIGH_QOS: OC_LOW_QOS), putReqCB, NULL, 0));
 }
 
 int InitPostRequest(OCQualityOfService qos)
@@ -231,22 +230,49 @@ int InitGetRequest(OCQualityOfService qos)
 int InitDiscovery()
 {
     OCStackResult ret;
+    OCMethod method;
     OCCallbackData cbData;
-    OCDoHandle handle;
-    /* Start a discovery query*/
-    char szQueryUri[64] = { 0 };
+    char szQueryUri[MAX_URI_LENGTH] = { 0 };
+    OCConnectivityType discoveryReqConnType;
+
     if (UNICAST_DISCOVERY)
     {
-        strcpy(szQueryUri, TEST_APP_UNICAST_DISCOVERY_QUERY);
+        char ipv4addr[IPV4_ADDR_SIZE];
+        printf("Enter IPv4 address of the Server hosting secure resource (Ex: 11.12.13.14)\n");
+        if (fgets(ipv4addr, IPV4_ADDR_SIZE, stdin))
+        {
+            //Strip newline char from ipv4addr
+            StripNewLineChar(ipv4addr);
+            snprintf(szQueryUri, sizeof(szQueryUri), UNICAST_DISCOVERY_QUERY, ipv4addr);
+        }
+        else
+        {
+            OC_LOG(ERROR, TAG, "!! Bad input for IPV4 address. !!");
+            return OC_STACK_INVALID_PARAM;
+        }
+        discoveryReqConnType = CT_ADAPTER_IP;
+        method = OC_REST_GET;
     }
     else
     {
-        strcpy(szQueryUri, OC_WELL_KNOWN_QUERY);
+        //Send discovery request on Wifi and Ethernet interface
+        discoveryReqConnType = CT_DEFAULT;
+        strcpy(szQueryUri, MULTICAST_DISCOVERY_QUERY);
+        method = OC_REST_DISCOVER;
     }
+
     cbData.cb = discoveryReqCB;
     cbData.context = NULL;
     cbData.cd = NULL;
-    ret = OCDoResource(&handle, OC_REST_GET, szQueryUri, 0, 0, OC_LOW_QOS, &cbData, NULL, 0);
+
+    /* Start a discovery query*/
+    OC_LOG_V(INFO, TAG, "Initiating %s Resource Discovery : %s\n",
+        (UNICAST_DISCOVERY) ? "Unicast" : "Multicast",
+        szQueryUri);
+
+    ret = OCDoResource(NULL, method, szQueryUri, 0, 0,
+            discoveryReqConnType, OC_LOW_QOS,
+            &cbData, NULL, 0);
     if (ret != OC_STACK_OK)
     {
         OC_LOG(ERROR, TAG, "OCStack resource error");
@@ -254,12 +280,14 @@ 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[])
 {
-    uint8_t addr[20] = {0};
-    uint8_t* paddr = NULL;
-    uint16_t port = USE_RANDOM_PORT;
-    uint8_t ifname[] = "eth0";
     int opt;
     struct timespec timeout;
 
@@ -286,33 +314,22 @@ int main(int argc, char* argv[])
         return -1;
     }
 
-
-    /*Get Ip address on defined interface and initialize coap on it with random port number
-     * this port number will be used as a source port in all coap communications*/
-    if ( OCGetInterfaceAddress(ifname, sizeof(ifname), AF_INET, addr,
-                sizeof(addr)) == ERR_SUCCESS)
-    {
-        OC_LOG_V(INFO, TAG, "Starting occlient on address %s",addr);
-        paddr = addr;
-    }
+    // 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);
 
     /* Initialize OCStack*/
-    if (OCInit((char *) paddr, port, OC_CLIENT) != OC_STACK_OK)
+    if (OCInit(NULL, 0, OC_CLIENT_SERVER) != OC_STACK_OK)
     {
         OC_LOG(ERROR, TAG, "OCStack init error");
         return 0;
     }
 
-    /*
-     * Read DTLS PSK credentials from persistent storage and
-     * set in the OC stack.
-     */
-    if (SetCredentials(CRED_FILE) != OC_STACK_OK)
-    {
-        OC_LOG(ERROR, TAG, "SetCredentials failed");
-        return 0;
-    }
-
     InitDiscovery();
 
     timeout.tv_sec  = 0;
@@ -341,28 +358,11 @@ 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();
 }
 
@@ -384,7 +384,7 @@ int parseClientResponse(OCClientResponse * clientResponse)
         return -1;
     }
 
-    oc = cJSON_GetObjectItem(root,"oc");
+    oc = cJSON_GetObjectItem(root,"oic");
     if (!oc)
     {
         return -1;
@@ -392,9 +392,10 @@ int parseClientResponse(OCClientResponse * clientResponse)
 
     if (oc->type == cJSON_Array)
     {
-        if (cJSON_GetArraySize(oc) > 0)
+        int numRsrcs =  cJSON_GetArraySize(oc);
+        for(int i = 0; i < numRsrcs; i++)
         {
-            cJSON * resource = cJSON_GetArrayItem(oc, 0);
+            cJSON * resource = cJSON_GetArrayItem(oc, i);
             if (cJSON_GetObjectItem(resource, "href"))
             {
                 coapServerResource.assign(cJSON_GetObjectItem(resource, "href")->valuestring);
@@ -408,31 +409,41 @@ int parseClientResponse(OCClientResponse * clientResponse)
             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"))
+                cJSON * policy = cJSON_GetObjectItem(prop,"p");
+                if (policy)
                 {
-                    if ((cJSON_GetObjectItem(prop, "sec")->valueint) == 1)
+                    // 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(policy, "sec"))
                     {
-                        coapSecureResource = 1;
+                        if ((cJSON_GetObjectItem(policy, "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");
+                    if (cJSON_GetObjectItem(policy, "port"))
+                    {
+                        port = cJSON_GetObjectItem(policy, "port")->valueint;
+                        OC_LOG_V(INFO, TAG, "Hosting Server Port (embedded inside JSON) -- %u", port);
 
-                    std::ostringstream ss;
-                    ss << port;
-                    coapServerPort = ss.str();
+                        std::ostringstream ss;
+                        ss << port;
+                        coapServerPort = ss.str();
+                    }
                 }
             }
+
+            // If we discovered a secure resource, exit from here
+            if (coapSecureResource)
+            {
+                break;
+            }
         }
     }
     cJSON_Delete(root);
 
-    coapServerIP = getIPAddrTBServer(clientResponse);
+    coapServerIP = clientResponse->devAddr.addr;
     if (port == -1)
     {
         coapServerPort = getPortTBServer(clientResponse);
@@ -440,3 +451,4 @@ int parseClientResponse(OCClientResponse * clientResponse)
     }
     return 0;
 }
+