replace : iotivity -> iotivity-sec
[platform/upstream/iotivity.git] / resource / csdk / security / provisioning / sample / sampleserver_randompin.cpp
index bd9560f..0f750a0 100644 (file)
 ///////////////////////////////////////////////////////////////////////
 //NOTE :  This sample server is generated based on ocserverbasicops.cpp
 ///////////////////////////////////////////////////////////////////////
+#include "iotivity_config.h"
 #include <stdio.h>
 #include <string.h>
 #include <stdlib.h>
+#ifdef HAVE_UNISTD_H
 #include <unistd.h>
+#endif
+#ifdef HAVE_TIME_H
+#include <time.h>
+#endif
 #include <signal.h>
-#include <pthread.h>
 #include "ocstack.h"
-#include "logger.h"
 #include "ocpayload.h"
 #include "pinoxmcommon.h"
 
+#ifdef HAVE_WINDOWS_H
+#include <windows.h>
+/** @todo stop-gap for naming issue. Windows.h does not like us to use ERROR */
+#ifdef ERROR
+#undef ERROR
+#endif //ERROR
+#endif //HAVE_WINDOWS_H
+#include "platform_features.h"
+#include "logger.h"
+
 #define TAG "SAMPLE_RANDOMPIN"
 
 int gQuitFlag = 0;
@@ -54,7 +68,7 @@ char *gResourceUri= (char *)"/a/led";
 //Secure Virtual Resource database for Iotivity Server
 //It contains Server's Identity and the PSK credentials
 //of other devices which the server trusts
-static char CRED_FILE[] = "oic_svr_db_server_randompin.json";
+static char CRED_FILE[] = "oic_svr_db_server_randompin.dat";
 
 /* Function that creates a new LED resource by calling the
  * OCCreateResource() method.
@@ -128,12 +142,49 @@ const char *getResult(OCStackResult result) {
     }
 }
 
+#ifdef MULTIPLE_OWNER
+
+#include <assert.h>
+#include <thread>
+#include <chrono>
+
+static bool volatile g_LoopFlag;
+static std::thread* oc_process_thread;
+
+static void oc_process_loop()
+{
+    while(g_LoopFlag)
+    {
+        if (OCProcess() != OC_STACK_OK)
+        {
+            OIC_LOG(ERROR, TAG, "OCStack process error");
+            g_LoopFlag = false;
+            break;
+        }
+        std::this_thread::sleep_for(std::chrono::milliseconds(100));
+    }
+}
+
+static void StartOCProcessThread()
+{
+    g_LoopFlag = true;
+    oc_process_thread = new std::thread(oc_process_loop);
+}
+
+static void StopOCProcessThread()
+{
+    assert(oc_process_thread->joinable() == true);
+    g_LoopFlag = false;
+    oc_process_thread->join();
+}
+#endif //MULTIPLE_OWNER
+
 OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
 {
     OCRepPayload* payload = OCRepPayloadCreate();
     if(!payload)
     {
-        OC_LOG(ERROR, TAG, PCF("Failed to allocate Payload"));
+        OIC_LOG(ERROR, TAG, "Failed to allocate Payload");
         return NULL;
     }
 
@@ -149,7 +200,7 @@ OCRepPayload* constructResponse (OCEntityHandlerRequest *ehRequest)
 {
     if(ehRequest->payload && ehRequest->payload->type != PAYLOAD_TYPE_REPRESENTATION)
     {
-        OC_LOG(ERROR, TAG, PCF("Incoming payload not a representation"));
+        OIC_LOG(ERROR, TAG, "Incoming payload not a representation");
         return NULL;
     }
 
@@ -259,11 +310,11 @@ OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
 
             if (0 == createLEDResource (newLedUri, &gLedInstance[gCurrLedInstance], false, 0))
             {
-                OC_LOG (INFO, TAG, "Created new LED instance");
+                OIC_LOG (INFO, TAG, "Created new LED instance");
                 gLedInstance[gCurrLedInstance].state = 0;
                 gLedInstance[gCurrLedInstance].power = 0;
                 gCurrLedInstance++;
-                strncpy ((char *)response->resourceUri, newLedUri, MAX_URI_LENGTH);
+                strncpy ((char *)response->resourceUri, newLedUri, sizeof(response->resourceUri));
                 ehResult = OC_EH_RESOURCE_CREATED;
             }
         }
@@ -298,7 +349,7 @@ OCEntityHandlerResult ProcessPostRequest (OCEntityHandlerRequest *ehRequest,
     }
     else
     {
-        OC_LOG_V (INFO, TAG, "Payload was NULL");
+        OIC_LOG_V (INFO, TAG, "Payload was NULL");
         ehResult = OC_EH_ERROR;
     }
 
@@ -310,7 +361,7 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
         OCEntityHandlerRequest *entityHandlerRequest,
         void* callbackParam)
 {
-    OC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
+    OIC_LOG_V (INFO, TAG, "Inside entity handler - flags: 0x%x", flag);
     (void)callbackParam;
     OCEntityHandlerResult ehResult = OC_EH_ERROR;
 
@@ -320,7 +371,7 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
     // Validate pointer
     if (!entityHandlerRequest)
     {
-        OC_LOG (ERROR, TAG, "Invalid request pointer");
+        OIC_LOG (ERROR, TAG, "Invalid request pointer");
         return OC_EH_ERROR;
     }
 
@@ -328,27 +379,27 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
 
     if (flag & OC_REQUEST_FLAG)
     {
-        OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
+        OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
         if (entityHandlerRequest)
         {
             if (OC_REST_GET == entityHandlerRequest->method)
             {
-                OC_LOG (INFO, TAG, "Received OC_REST_GET from client");
+                OIC_LOG (INFO, TAG, "Received OC_REST_GET from client");
                 ehResult = ProcessGetRequest (entityHandlerRequest, &payload);
             }
             else if (OC_REST_PUT == entityHandlerRequest->method)
             {
-                OC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
+                OIC_LOG (INFO, TAG, "Received OC_REST_PUT from client");
                 ehResult = ProcessPutRequest (entityHandlerRequest, &payload);
             }
             else if (OC_REST_POST == entityHandlerRequest->method)
             {
-                OC_LOG (INFO, TAG, "Received OC_REST_POST from client");
+                OIC_LOG (INFO, TAG, "Received OC_REST_POST from client");
                 ehResult = ProcessPostRequest (entityHandlerRequest, &response, &payload);
             }
             else
             {
-                OC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
+                OIC_LOG_V (INFO, TAG, "Received unsupported method %d from client",
                         entityHandlerRequest->method);
                 ehResult = OC_EH_ERROR;
             }
@@ -370,7 +421,7 @@ OCEntityHandlerCb (OCEntityHandlerFlag flag,
                 // Send the response
                 if (OCDoResponse(&response) != OC_STACK_OK)
                 {
-                    OC_LOG(ERROR, TAG, "Error sending response");
+                    OIC_LOG(ERROR, TAG, "Error sending response");
                     ehResult = OC_EH_ERROR;
                 }
             }
@@ -400,28 +451,33 @@ void GeneratePinCB(char* pin, size_t pinSize)
 {
     if(NULL == pin || pinSize <= 0)
     {
-        OC_LOG(INFO, TAG, "Invalid PIN");
+        OIC_LOG(INFO, TAG, "Invalid PIN");
         return;
     }
 
-    OC_LOG(INFO, TAG, "============================");
-    OC_LOG_V(INFO, TAG, "    PIN CODE : %s", pin);
-    OC_LOG(INFO, TAG, "============================");
+    OIC_LOG(INFO, TAG, "============================");
+    OIC_LOG_V(INFO, TAG, "    PIN CODE : %s", pin);
+    OIC_LOG(INFO, TAG, "============================");
 }
 
-int main()
+void ClosePinDisplayCB(void)
 {
-    struct timespec timeout;
+    OIC_LOG(INFO, TAG, "============================");
+    OIC_LOG(INFO, TAG, "    PIN DISPLAY CLOSED.");
+    OIC_LOG(INFO, TAG, "============================");
+}
 
-    OC_LOG(DEBUG, TAG, "OCServer is starting...");
+int main()
+{
+    OIC_LOG(DEBUG, TAG, "OCServer is starting...");
 
     // Initialize Persistent Storage for SVR database
-    OCPersistentStorage ps = {server_fopen, fread, fwrite, fclose, unlink};
+    OCPersistentStorage ps = {server_fopen, fread, fwrite, fclose, unlink, NULL, NULL};
     OCRegisterPersistentStorageHandler(&ps);
 
     if (OCInit(NULL, 0, OC_SERVER) != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack init error");
+        OIC_LOG(ERROR, TAG, "OCStack init error");
         return 0;
     }
 
@@ -429,34 +485,76 @@ int main()
      * If server supported random pin based ownership transfer,
      * callback of print PIN should be registered before runing server.
      */
-    SetGeneratePinCB(&GeneratePinCB);
+    SetGeneratePinCB(GeneratePinCB);
+
+    /**
+     * If ther server supports random pin based OTM,
+     * the callback to close PIN display can be registered.
+     * This callback will be invoked when random PIN based OTM is done.
+     */
+    SetClosePinDisplayCB(ClosePinDisplayCB);
+
+    /**
+     * Random PIN generation policy can be changed through SetRandomPinPolicy() API.
+     * first param : byte length of random PIN ( 4 <= first param <= 32)
+     * second param : PIN type (This is bitmask)
+     */
+    if(OC_STACK_OK != SetRandomPinPolicy(8, NUM_PIN))
+    {
+        OIC_LOG(ERROR, TAG, "Failed to setting PIN policy");
+        return 0;
+    }
 
     /*
      * Declare and create the example resource: LED
      */
     createLEDResource(gResourceUri, &LED, false, 0);
 
+    // Break from loop with Ctrl-C
+    OIC_LOG(INFO, TAG, "Entering ocserver main loop...");
+    signal(SIGINT, handleSigInt);
+
+#ifdef MULTIPLE_OWNER
+    StartOCProcessThread();
+
+    while(!gQuitFlag)
+    {
+        printf("Press 'G' to generate random PIN...\n");
+        printf("Press 'E' to exit...\n");
+        char in = getchar();
+        if('G' == in || 'g' == in)
+        {
+            char ranPin[OXM_RANDOM_PIN_MAX_SIZE + 1] = {0};
+            GeneratePin(ranPin, sizeof(ranPin));
+        }
+        if('E' == in || 'e' == in)
+        {
+            break;
+        }
+    }
+
+    StopOCProcessThread();
+#else
+    struct timespec timeout;
     timeout.tv_sec  = 0;
     timeout.tv_nsec = 100000000L;
 
-    // Break from loop with Ctrl-C
-    OC_LOG(INFO, TAG, "Entering ocserver main loop...");
-    signal(SIGINT, handleSigInt);
     while (!gQuitFlag)
     {
         if (OCProcess() != OC_STACK_OK)
         {
-            OC_LOG(ERROR, TAG, "OCStack process error");
+            OIC_LOG(ERROR, TAG, "OCStack process error");
             return 0;
         }
         nanosleep(&timeout, NULL);
     }
+#endif //MULTIPLE_OWNER
 
-    OC_LOG(INFO, TAG, "Exiting ocserver main loop...");
+    OIC_LOG(INFO, TAG, "Exiting ocserver main loop...");
 
     if (OCStop() != OC_STACK_OK)
     {
-        OC_LOG(ERROR, TAG, "OCStack process error");
+        OIC_LOG(ERROR, TAG, "OCStack process error");
     }
 
     return 0;
@@ -466,7 +564,7 @@ int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState,
 {
     if (!uri)
     {
-        OC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
+        OIC_LOG(ERROR, TAG, "Resource URI cannot be NULL");
         return -1;
     }
 
@@ -479,7 +577,7 @@ int createLEDResource (char *uri, LEDResource *ledResource, bool resourceState,
             OCEntityHandlerCb,
             NULL,
             OC_DISCOVERABLE|OC_OBSERVABLE | OC_SECURE);
-    OC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));
+    OIC_LOG_V(INFO, TAG, "Created LED resource with result: %s", getResult(res));
 
     return 0;
 }