IP address plumbing changes to support IPv6
[platform/upstream/iotivity.git] / resource / csdk / stack / samples / linux / secure / occlientbasicops.cpp
index 8059bc3..ebc65a7 100644 (file)
 #include "ocstack.h"
 #include "logger.h"
 #include "occlientbasicops.h"
+#include "cJSON.h"
+#include "common.h"
 
 #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 std::string coapServerIP = "255.255.255.255";
-static std::string coapServerPort = "5683";
-static std::string coapServerResource = "/a/led";
+
+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;
+
+
+//Secure Virtual Resource database for Iotivity Client application
+//It contains Client's Identity and the PSK credentials
+//of other devices which the client trusts
+static char CRED_FILE[] = "oic_svr_db_client.json";
+
 
 int gQuitFlag = 0;
 
@@ -65,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)
     {
@@ -119,23 +133,6 @@ OCStackApplicationResult getReqCB(void* ctx, OCDoHandle handle, OCClientResponse
         OC_LOG_V(INFO, TAG, "JSON = %s =============> Get Response",
                 clientResponse->resJSONPayload);
     }
-    if(clientResponse->rcvdVendorSpecificHeaderOptions &&
-            clientResponse->numRcvdVendorSpecificHeaderOptions)
-    {
-        OC_LOG (INFO, TAG, "Received vendor specific options");
-        uint8_t i = 0;
-        OCHeaderOption * rcvdOptions = clientResponse->rcvdVendorSpecificHeaderOptions;
-        for( i = 0; i < clientResponse->numRcvdVendorSpecificHeaderOptions; i++)
-        {
-            if(((OCHeaderOption)rcvdOptions[i]).protocolID == OC_COAP_ID)
-            {
-                OC_LOG_V(INFO, TAG, "Received option with OC_COAP_ID and ID %u with",
-                        ((OCHeaderOption)rcvdOptions[i]).optionID );
-                OC_LOG_BUFFER(INFO, TAG, ((OCHeaderOption)rcvdOptions[i]).optionData,
-                        ((OCHeaderOption)rcvdOptions[i]).optionLength);
-            }
-        }
-    }
     return OC_STACK_DELETE_TRANSACTION;
 }
 
@@ -143,38 +140,32 @@ 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);
 
-        parseClientResponse(clientResponse);
+        ocConnType = clientResponse->connType;
 
-        switch(TEST_CASE)
+        if (parseClientResponse(clientResponse) != -1)
         {
-            case TEST_NON_CON_OP:
-                InitGetRequest(OC_LOW_QOS);
-                InitPutRequest();
-                //InitPostRequest(OC_LOW_QOS);
-                break;
-            case TEST_CON_OP:
-                InitGetRequest(OC_HIGH_QOS);
-                InitPutRequest();
-                //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;
+            }
         }
     }
 
@@ -182,12 +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 << "coaps://" << coapServerIP << ":" << "5684" << coapServerResource;
-    return (InvokeOCDoResource(query, OC_REST_PUT, OC_LOW_QOS, putReqCB, NULL, 0));
+    query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
+        << ":" << 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)
@@ -195,7 +188,8 @@ int InitPostRequest(OCQualityOfService qos)
     OCStackResult result;
     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
     std::ostringstream query;
-    query << "coaps://" << coapServerIP << ":" << "5684" << coapServerResource;
+    query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
+        << ":" << coapServerPort << coapServerResource;
 
     // First POST operation (to create an LED instance)
     result = InvokeOCDoResource(query, OC_REST_POST,
@@ -226,7 +220,8 @@ int InitGetRequest(OCQualityOfService qos)
 {
     OC_LOG_V(INFO, TAG, "\n\nExecuting %s", __func__);
     std::ostringstream query;
-    query << "coaps://" << coapServerIP << ":" << "5684" << coapServerResource;
+    query << (coapSecureResource ? "coaps://" : "coap://") << coapServerIP
+        << ":" << coapServerPort << coapServerResource;
 
     return (InvokeOCDoResource(query, OC_REST_GET, (qos == OC_HIGH_QOS)?
             OC_HIGH_QOS:OC_LOW_QOS, getReqCB, NULL, 0));
@@ -235,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");
@@ -258,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;
 
@@ -290,18 +314,17 @@ 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;
@@ -324,7 +347,6 @@ int main(int argc, char* argv[])
         }
 
         nanosleep(&timeout, NULL);
-        //sleep(2);
     }
     OC_LOG(INFO, TAG, "Exiting occlient main loop...");
 
@@ -336,39 +358,97 @@ 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();
 }
 
-std::string getQueryStrForGetPut(OCClientResponse * clientResponse)
+int parseClientResponse(OCClientResponse * clientResponse)
 {
-    return "/a/led";
-}
+    int port = -1;
+    cJSON * root = NULL;
+    cJSON * oc = NULL;
+
+    // Initialize all global variables
+    coapServerResource.clear();
+    coapServerPort.clear();
+    coapServerIP.clear();
+    coapSecureResource = 0;
+
+    root = cJSON_Parse((char *)(clientResponse->resJSONPayload));
+    if (!root)
+    {
+        return -1;
+    }
 
-void parseClientResponse(OCClientResponse * clientResponse)
-{
-    coapServerIP = getIPAddrTBServer(clientResponse);
-    coapServerPort = getPortTBServer(clientResponse);
-    coapServerResource = getQueryStrForGetPut(clientResponse);
+    oc = cJSON_GetObjectItem(root,"oic");
+    if (!oc)
+    {
+        return -1;
+    }
+
+    if (oc->type == cJSON_Array)
+    {
+        int numRsrcs =  cJSON_GetArraySize(oc);
+        for(int i = 0; i < numRsrcs; i++)
+        {
+            cJSON * resource = cJSON_GetArrayItem(oc, i);
+            if (cJSON_GetObjectItem(resource, "href"))
+            {
+                coapServerResource.assign(cJSON_GetObjectItem(resource, "href")->valuestring);
+            }
+            else
+            {
+                coapServerResource = "";
+            }
+            OC_LOG_V(INFO, TAG, "Uri -- %s", coapServerResource.c_str());
+
+            cJSON * prop = cJSON_GetObjectItem(resource,"prop");
+            if (prop)
+            {
+                cJSON * policy = cJSON_GetObjectItem(prop,"p");
+                if (policy)
+                {
+                    // 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"))
+                    {
+                        if ((cJSON_GetObjectItem(policy, "sec")->valueint) == 1)
+                        {
+                            coapSecureResource = 1;
+                        }
+                    }
+                    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();
+                    }
+                }
+            }
+
+            // If we discovered a secure resource, exit from here
+            if (coapSecureResource)
+            {
+                break;
+            }
+        }
+    }
+    cJSON_Delete(root);
+
+    coapServerIP = clientResponse->devAddr.addr;
+    if (port == -1)
+    {
+        coapServerPort = getPortTBServer(clientResponse);
+        OC_LOG_V(INFO, TAG, "Hosting Server Port -- %s", coapServerPort.c_str());
+    }
+    return 0;
 }
+