Merge branch '1.3-rel' (5fdb8a1) 33/22733/9
authorPhilippe Coval <philippe.coval@osg.samsung.com>
Fri, 17 Nov 2017 00:19:39 +0000 (01:19 +0100)
committerPhil Coval <philippe.coval@osg.samsung.com>
Fri, 17 Nov 2017 21:58:11 +0000 (21:58 +0000)
Change-Id: I3040a9e4ab81d6b4485bcb390a643955719ab8f5
Bug: https://jira.iotivity.org/browse/IOT-2453
Signed-off-by: Philippe Coval <philippe.coval@osg.samsung.com>
38 files changed:
resource/csdk/connectivity/src/camessagehandler.c
resource/csdk/resource-directory/src/rd_server.c
resource/csdk/security/include/experimental/doxmresource.h
resource/csdk/security/include/internal/credresource.h
resource/csdk/security/include/internal/pstatresource.h
resource/csdk/security/src/credresource.c
resource/csdk/security/src/doxmresource.c
resource/csdk/security/src/pkix_interface.c
resource/csdk/security/src/pstatresource.c
resource/csdk/security/src/rolesresource.c
resource/csdk/security/src/secureresourcemanager.c
resource/csdk/security/tool/json2cbor.c
resource/csdk/stack/include/experimental/payload_logging.h
resource/provisioning/unittests/OCProvisioningTest.cpp
service/easy-setup/enrollee/src/resourcehandler.c
service/notification/src/provider/NSProviderSubscription.c
service/notification/src/provider/NSProviderTopic.c
service/resource-encapsulation/examples/linux/NestedAttributesServer.cpp
service/resource-encapsulation/src/common/expiryTimer/src/ExpiryTimer.cpp
service/resource-encapsulation/src/common/expiryTimer/src/ExpiryTimerImpl.cpp
service/resource-encapsulation/src/common/primitiveResource/include/AssertUtils.h
service/resource-encapsulation/src/common/primitiveResource/include/PrimitiveResourceImpl.h
service/resource-encapsulation/src/common/primitiveResource/include/ResourceAttributesConverter.h
service/resource-encapsulation/src/common/primitiveResource/src/RCSResourceAttributes.cpp
service/resource-encapsulation/src/common/primitiveResource/unittests/PrimitiveResourceTest.cpp
service/resource-encapsulation/src/common/utils/include/UnitTestHelper.h
service/resource-encapsulation/src/resourceBroker/src/DevicePresence.cpp
service/resource-encapsulation/src/resourceBroker/src/ResourceBroker.cpp
service/resource-encapsulation/src/resourceBroker/src/ResourcePresence.cpp
service/resource-encapsulation/src/resourceBroker/unittest/ResourcePresenceUnitTest.cpp
service/resource-encapsulation/src/resourceClient/RCSDiscoveryManager.cpp
service/resource-encapsulation/src/resourceClient/RCSDiscoveryManagerImpl.cpp
service/resource-encapsulation/src/resourceClient/RCSRemoteResourceObject.cpp
service/resource-encapsulation/src/serverBuilder/src/InterfaceHandler.cpp
service/resource-encapsulation/src/serverBuilder/src/RCSRequest.cpp
service/resource-encapsulation/src/serverBuilder/src/RCSResourceObject.cpp
service/resource-encapsulation/src/serverBuilder/src/RCSSeparateResponse.cpp
service/resource-encapsulation/src/serverBuilder/unittests/RCSResourceObjectTest.cpp

index 69e569a..fd25d85 100644 (file)
@@ -1494,11 +1494,11 @@ static void CALogPDUInfo(const CAData_t *data, const coap_pdu_t *pdu)
     OIC_LOG(DEBUG, ANALYZER_TAG, "CoAP Header (+ 0xFF)");
     OIC_LOG_BUFFER(DEBUG, ANALYZER_TAG,  (const uint8_t *) pdu->transport_hdr,
                    pdu->length - payloadLen);
-    OIC_LOG_V(DEBUG, ANALYZER_TAG, "CoAP Header size = [%lu]", pdu->length - payloadLen);
+    OIC_LOG_V(DEBUG, ANALYZER_TAG, "CoAP Header size = [%" PRIuPTR "]", (size_t) pdu->length - payloadLen);
 
     OIC_LOG_V(DEBUG, ANALYZER_TAG, "CoAP Payload");
     //OIC_LOG_BUFFER(DEBUG, ANALYZER_TAG, pdu->data, payloadLen);
-    OIC_LOG_V(DEBUG, ANALYZER_TAG, "CoAP Payload Size = [%lu]", payloadLen);
+    OIC_LOG_V(DEBUG, ANALYZER_TAG, "CoAP Payload Size = [%" PRIuPTR "]", payloadLen);
     OIC_LOG(DEBUG, ANALYZER_TAG, "=================================================");
     OIC_TRACE_END();
 }
index 7546989..5f3e26b 100644 (file)
@@ -187,9 +187,13 @@ static OCEntityHandlerResult handlePublishRequest(const OCEntityHandlerRequest *
     }
 
     // Send Response
-    if (OC_STACK_OK != sendResponse(ehRequest, resPayload, ehResult))
+    if (OC_EH_OK == ehResult)
     {
-        OIC_LOG(ERROR, TAG, "Sending response failed.");
+        if (OC_STACK_OK != sendResponse(ehRequest, resPayload, ehResult))
+        {
+            OIC_LOG(ERROR, TAG, "Sending response failed.");
+            ehResult = OC_EH_ERROR;
+        }
     }
 
     if (OC_EH_OK == ehResult)
@@ -262,6 +266,7 @@ static OCEntityHandlerResult handleDeleteRequest(const OCEntityHandlerRequest *e
         if (!key || !value)
         {
             OIC_LOG_V(ERROR, TAG, "Invalid query parameter!");
+            ehResult = OC_EH_BAD_REQ;
             goto exit;
         }
         else if (0 == strncasecmp(key, OC_RSRVD_DEVICE_ID, sizeof(OC_RSRVD_DEVICE_ID) - 1))
@@ -276,6 +281,7 @@ static OCEntityHandlerResult handleDeleteRequest(const OCEntityHandlerRequest *e
             if (0 == matchedItems)
             {
                 OIC_LOG_V(ERROR, TAG, "Invalid ins query parameter: %s", value);
+                ehResult = OC_EH_BAD_REQ;
                 goto exit;
             }
 
@@ -287,6 +293,7 @@ static OCEntityHandlerResult handleDeleteRequest(const OCEntityHandlerRequest *e
     if (!di && !nIns)
     {
         OIC_LOG_V(ERROR, TAG, "Missing required query parameters!");
+        ehResult = OC_EH_BAD_REQ;
         goto exit;
     }
 
@@ -296,6 +303,15 @@ static OCEntityHandlerResult handleDeleteRequest(const OCEntityHandlerRequest *e
         ehResult = OC_EH_OK;
     }
 
+    if (OC_EH_OK == ehResult)
+    {
+        if (OC_STACK_OK != sendResponse(ehRequest, NULL, ehResult))
+        {
+            OIC_LOG(ERROR, TAG, "Sending response failed.");
+            ehResult = OC_EH_ERROR;
+        }
+    }
+
     if (OC_EH_OK == ehResult)
     {
         OCResourceHandle handle = OCGetResourceHandleAtUri(OC_RSRVD_WELL_KNOWN_URI);
@@ -310,10 +326,6 @@ static OCEntityHandlerResult handleDeleteRequest(const OCEntityHandlerRequest *e
 exit:
     OICFree(ins);
     OICFree(queryDup);
-    if (OC_STACK_OK != sendResponse(ehRequest, NULL, ehResult))
-    {
-        OIC_LOG(ERROR, TAG, "Sending response failed.");
-    }
     return ehResult;
 }
 
index cf96385..504e194 100644 (file)
@@ -238,12 +238,6 @@ void DeleteDoxmBinData(OicSecDoxm_t* doxm);
  */
 bool AreDoxmBinPropertyValuesEqual(OicSecDoxm_t* doxm1, OicSecDoxm_t* doxm2);
 
-/**
- * Function to restore doxm resurce to initial status.
- * This function will use in case of error while ownership transfer
- */
-void RestoreDoxmToInitState();
-
 #if defined(__WITH_DTLS__) && defined(MULTIPLE_OWNER)
 /**
  * Callback function to handle MOT DTLS handshake result.
index b2bb3e9..47354be 100644 (file)
@@ -72,7 +72,8 @@ OicSecCred_t* GetCredEntryByCredId(const uint16_t credId);
 
 /**
  * This function converts credential data into CBOR format.
- * Caller needs to invoke 'free' when done using returned string.
+ * Caller needs to invoke 'OICFree' when done using returned string.
+ * Wrapper over the CredToCBORPayloadWithRowner.
  *
  * @param cred is the pointer to instance of OicSecCred_t structure.
  * @param cborPayload is the CBOR converted value.
@@ -84,6 +85,22 @@ OicSecCred_t* GetCredEntryByCredId(const uint16_t credId);
 OCStackResult CredToCBORPayload(const OicSecCred_t* cred, uint8_t **cborPayload,
                                 size_t *cborSize, int secureFlag);
 
+/**
+ * This function converts credential data into CBOR format.
+ * Caller needs to invoke 'OICFree' when done using returned string.
+ *
+ * @param cred is the pointer to instance of OicSecCred_t structure.
+ * @param rownerId resource owner's UUID
+ * @param cborPayload is the CBOR converted value.
+ * @param cborSize is the size of the CBOR.
+ * @param secureFlag shows fill or not private key.
+ *
+ * @return ::OC_STACK_OK if conversion is successful, else ::OC_STACK_ERROR if unsuccessful.
+ */
+
+OCStackResult CredToCBORPayloadWithRowner(const OicSecCred_t *credS, const OicUuid_t *rownerId, uint8_t **cborPayload,
+                                size_t *cborSize, int secureFlag);
+
 #ifdef MULTIPLE_OWNER
 /**
  * Function to check the credential access of SubOwner
@@ -241,12 +258,18 @@ OCStackResult GetAllRoleCerts(RoleCertChain_t** roleCerts);
  */
 void GetPemOwnCert(ByteArray_t * crt, const char * usage);
 /**
- * Used by mbedTLS to retrieve owm private key
+ * Used by mbedTLS to retrieve own private key
  *
  * @param[out] key key to be filled.
  * @param[in] usage credential usage string.
  */
 void GetDerKey(ByteArray_t * key, const char * usage);
+/**
+ * Used by mbedTLS to retrieve own primary cert private key
+ *
+ * @param[out] key key to be filled.
+ */
+void GetPrimaryCertKey(ByteArray_t * key);
 /**
  * Used by CA to retrieve credential types
  *
index 5d54032..ed78e91 100644 (file)
@@ -113,12 +113,6 @@ OCStackResult CBORPayloadToPstat(const uint8_t *cborPayload, const size_t cborSi
  */
 void DeletePstatBinData(OicSecPstat_t* pstat);
 
-/**
- * Function to restore pstat resurce to initial status.
- * This function will use in case of error while ownership transfer
- */
-void RestorePstatToInitState();
-
 /**
  * Get the pstat.rowneruuid value for this device.
  *
index a81189d..8ae68a0 100644 (file)
@@ -657,7 +657,7 @@ static void logCredMetadata()
 #endif
 }
 
-OCStackResult CredToCBORPayload(const OicSecCred_t *credS, uint8_t **cborPayload,
+OCStackResult CredToCBORPayloadWithRowner(const OicSecCred_t *credS, const OicUuid_t *rownerId, uint8_t **cborPayload,
                                 size_t *cborSize, int secureFlag)
 {
     OIC_LOG_V(DEBUG, TAG, "IN %s:", __func__);
@@ -892,7 +892,7 @@ OCStackResult CredToCBORPayload(const OicSecCred_t *credS, uint8_t **cborPayload
         cborEncoderResult = cbor_encode_text_string(&credRootMap, OIC_JSON_ROWNERID_NAME,
             strlen(OIC_JSON_ROWNERID_NAME));
         VERIFY_CBOR_SUCCESS_OR_OUT_OF_MEMORY(TAG, cborEncoderResult, "Failed Adding rownerid Name.");
-        ret = ConvertUuidToStr(&gRownerId, &rowner);
+        ret = ConvertUuidToStr(rownerId, &rowner);
         VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
         cborEncoderResult = cbor_encode_text_string(&credRootMap, rowner, strlen(rowner));
         VERIFY_CBOR_SUCCESS_OR_OUT_OF_MEMORY(TAG, cborEncoderResult, "Failed Addding rownerid Value.");
@@ -973,6 +973,13 @@ exit:
     return ret;
 }
 
+OCStackResult CredToCBORPayload(const OicSecCred_t *credS, uint8_t **cborPayload,
+                                size_t *cborSize, int secureFlag)
+{
+    return CredToCBORPayloadWithRowner(credS, &gRownerId, cborPayload, cborSize, secureFlag);
+}
+
+
 OCStackResult CBORPayloadToCred(const uint8_t *cborPayload, size_t size,
                                 OicSecCred_t **secCred, OicUuid_t **rownerid)
 {
@@ -1464,7 +1471,7 @@ static bool UpdatePersistentStorage(const OicSecCred_t *cred)
         OIC_LOG_V(DEBUG, TAG, "cred size: %zu", size);
 
         int secureFlag = 0;
-        OCStackResult res = CredToCBORPayload(cred, &payload, &size, secureFlag);
+        OCStackResult res = CredToCBORPayloadWithRowner(cred, &gRownerId, &payload, &size, secureFlag);
 #ifdef HAVE_WINDOWS_H
         /* On Windows, keep the credential resource encrypted on disk to protect symmetric and private keys. Only the
          * current user on this system will be able to decrypt it later, to help prevent credential theft.
@@ -2123,7 +2130,7 @@ exit:
 #endif // __WITH_DTLS__ or __WITH_TLS__
 
 
-static OCEntityHandlerResult HandleNewCredential(OCEntityHandlerRequest *ehRequest, OicSecCred_t *cred, uint16_t previousMsgId)
+static OCEntityHandlerResult HandleNewCredential(OCEntityHandlerRequest *ehRequest, OicSecCred_t *cred)
 {
     OCEntityHandlerResult ret = OC_EH_INTERNAL_SERVER_ERROR;
 
@@ -2230,34 +2237,6 @@ static OCEntityHandlerResult HandleNewCredential(OCEntityHandlerRequest *ehReque
                 break;
             }
         }
-
-        if(OC_EH_CHANGED != ret)
-        {
-            /*
-                * If some error is occured while ownership transfer,
-                * ownership transfer related resource should be revert back to initial status.
-                */
-            const OicSecDoxm_t *ownershipDoxm =  GetDoxmResourceData();
-            if(ownershipDoxm)
-            {
-                if(!ownershipDoxm->owned)
-                {
-                    OIC_LOG(WARNING, TAG, "The operation failed during handle DOXM request");
-
-                    if((OC_ADAPTER_IP == ehRequest->devAddr.adapter && previousMsgId != ehRequest->messageID)
-                        || OC_ADAPTER_TCP == ehRequest->devAddr.adapter)
-                    {
-                        RestoreDoxmToInitState();
-                        RestorePstatToInitState();
-                        OIC_LOG(WARNING, TAG, "DOXM will be reverted.");
-                    }
-                }
-            }
-            else
-            {
-                OIC_LOG(ERROR, TAG, "Invalid DOXM resource");
-            }
-        }
     }
 #ifdef MULTIPLE_OWNER
     // In case SubOwner Credential
@@ -2349,7 +2328,6 @@ static OCEntityHandlerResult HandleNewCredential(OCEntityHandlerRequest *ehReque
         * list and updating svr database.
         */
     ret = (OC_STACK_OK == AddCredential(cred))? OC_EH_CHANGED : OC_EH_ERROR;
-    OC_UNUSED(previousMsgId);
     OC_UNUSED(ehRequest);
 #endif//__WITH_DTLS__ or __WITH_TLS__
 
@@ -2362,7 +2340,6 @@ static OCEntityHandlerResult HandlePostRequest(OCEntityHandlerRequest* ehRequest
     OIC_LOG(DEBUG, TAG, "HandleCREDPostRequest IN");
 
     OicSecDostype_t dos;
-    static uint16_t previousMsgId = 0;
     // Get binary representation of cbor
     OicSecCred_t *cred = NULL;
     OicUuid_t     *rownerId = NULL;
@@ -2389,7 +2366,7 @@ static OCEntityHandlerResult HandlePostRequest(OCEntityHandlerRequest* ehRequest
 
         LL_FOREACH_SAFE(cred, newCred, newCredTemp)
         {
-            ret = HandleNewCredential(ehRequest, newCred, previousMsgId);
+            ret = HandleNewCredential(ehRequest, newCred);
 
             if (OC_EH_CHANGED != ret)
             {
@@ -2427,13 +2404,6 @@ exit:
             DeleteCredList(cred);
         }
     }
-    else
-    {
-        if (OC_ADAPTER_IP == ehRequest->devAddr.adapter)
-        {
-            previousMsgId = ehRequest->messageID++;
-        }
-    }
 
     // Send response to request originator
     ret = ((SendSRMResponse(ehRequest, ret, NULL, 0)) == OC_STACK_OK) ?
@@ -2460,7 +2430,7 @@ static OCEntityHandlerResult HandleGetRequest (const OCEntityHandlerRequest * eh
     // This added '256' is arbitrary value that is added to cover the name of the resource, map addition and ending
     size = GetCredKeyDataSize(cred);
     size += (256 * OicSecCredCount(cred));
-    OCStackResult res = CredToCBORPayload(cred, &payload, &size, secureFlag);
+    OCStackResult res = CredToCBORPayloadWithRowner(cred, &gRownerId, &payload, &size, secureFlag);
 
     // A device should always have a default cred. Therefore, payload should never be NULL.
     OCEntityHandlerResult ehRet = (res == OC_STACK_OK) ? OC_EH_OK : OC_EH_ERROR;
@@ -3714,6 +3684,91 @@ void GetDerKey(ByteArray_t * key, const char * usage)
     OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
 }
 
+void GetPrimaryCertKey(ByteArray_t * key)
+{
+    OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
+
+    VERIFY_NOT_NULL(TAG, key, ERROR);
+    
+    key->len = 0;
+    OicSecCred_t * temp = NULL;
+
+    LL_FOREACH(gCred, temp)
+    {
+        size_t length = temp->privateData.len;
+
+        if ((SIGNED_ASYMMETRIC_KEY == temp->credType || ASYMMETRIC_KEY == temp->credType) &&
+            (0 < length) &&
+            (NULL != temp->credUsage) &&
+            (0 == strcmp(temp->credUsage, PRIMARY_CERT)))
+        {
+            switch (temp->privateData.encoding)
+            {
+                case OIC_ENCODING_PEM:
+                case OIC_ENCODING_DER:
+                case OIC_ENCODING_RAW:
+                {
+                    bool addNull = false;
+                    uint8_t *data = temp->privateData.data;
+
+                    if ((OIC_ENCODING_PEM == temp->privateData.encoding) &&
+                        (0 != data[length - 1]))
+                    {
+                        /* mbedtls_pk_parse_key needs null terminator to determine the PEM key format */
+                        OIC_LOG_V(DEBUG, TAG, "%s: adding null terminator to key", __func__);
+                        addNull = true;
+                        data = OICCalloc(length + 1, sizeof(*data));
+                    }
+                    else
+                    {
+                        data = OICCalloc(length, sizeof(*data));
+                    }
+
+                    if (NULL == data)
+                    {
+                        key->data = NULL;
+                        OIC_LOG(ERROR, TAG, "Failed to allocate memory");
+                        return;
+                    }
+
+                    memcpy(data, temp->privateData.data, length);
+
+                    if (addNull)
+                    {
+                        data[length] = 0;
+                        length++;
+                    }
+
+                    key->data = data;
+                    key->len = length;
+
+                    OIC_LOG(DEBUG, TAG, "Key for PRIMARY_CERT found");
+                    break;
+                }
+
+                default:
+                {
+                    OIC_LOG_V(WARNING, TAG, "Key for PRIMARY_CERT found, but it has an unknown encoding (%d)", temp->privateData.encoding);
+                    break;
+                }
+            }
+
+            if (0 != key->len)
+            {
+                break;
+            }
+        }
+    }
+
+    if(0 == key->len)
+    {
+        OIC_LOG(WARNING, TAG, "Key for PRIMARY_CERT not found");
+    }
+
+exit:
+    OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
+}
+
 void InitCipherSuiteListInternal(bool * list, const char * usage, const char *deviceId)
 {
     OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
index 5995391..59b967a 100644 (file)
@@ -1334,14 +1334,12 @@ OCEntityHandlerResult HandleDoxmPostRequestUpdatePS(bool fACE)
     }
 }
 
-OCEntityHandlerResult StartOTMJustWorks(OCEntityHandlerRequest *ehRequest,
-        bool isDuplicatedMsg)
+OCEntityHandlerResult StartOTMJustWorks(OCEntityHandlerRequest *ehRequest)
 {
     OIC_LOG_V(DEBUG, TAG, "%s: IN", __func__);
     OCEntityHandlerResult ehRet = OC_EH_OK;
 
 #if !(defined(__WITH_DTLS__) || defined(__WITH_TLS__))
-    OC_UNUSED(isDuplicatedMsg);
     OC_UNUSED(ehRequest);
 #endif // not __WITH_DTLS__ and not __WITH_TLS__
 
@@ -1357,20 +1355,11 @@ OCEntityHandlerResult StartOTMJustWorks(OCEntityHandlerRequest *ehRequest,
 #endif // __WITH_DTLS__ or __WITH_TLS__
         goto exit;
     }
-    // else if /doxm.devowneruuid != Nil UUID, disable Anon CipherSuite
     else
     {
 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
-        // Disable anonymous ECDH cipher since OTM is underway
-        RegisterOTMSslHandshakeCallback(NULL);
-        CAResult_t caRes = CA_STATUS_OK;
-        caRes = CAEnableAnonECDHCipherSuite(false);
-        VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
-        OIC_LOG_V(INFO, TAG, "%s: ECDH_ANON CipherSuite is DISABLED", __func__);
-
         //In case of Mutual Verified Just-Works, verify mutualVerifNum
-        if (OIC_MV_JUST_WORKS == gDoxm->oxmSel && false == gDoxm->owned &&
-            false == isDuplicatedMsg)
+        if (OIC_MV_JUST_WORKS == gDoxm->oxmSel && false == gDoxm->owned)
         {
             uint8_t preMutualVerifNum[OWNER_PSK_LENGTH_128] = {0};
             uint8_t mutualVerifNum[MUTUAL_VERIF_NUM_LEN] = {0};
@@ -1424,14 +1413,12 @@ exit:
 }
 
 OCEntityHandlerResult HandleDoxmPostRequestRandomPin(OicSecDoxm_t *newDoxm,
-        OCEntityHandlerRequest *ehRequest,
-        bool isDuplicatedMsg)
+        OCEntityHandlerRequest *ehRequest)
 {
     OIC_LOG_V(DEBUG, TAG, "%s: IN", __func__);
     OCEntityHandlerResult ehRet = OC_EH_OK;
 
 #if !(defined(__WITH_DTLS__) || defined(__WITH_TLS__))
-    OC_UNUSED(isDuplicatedMsg);
     OC_UNUSED(ehRequest);
 #endif // not __WITH_DTLS__ and not __WITH_TLS__
 
@@ -1453,28 +1440,25 @@ OCEntityHandlerResult HandleDoxmPostRequestRandomPin(OicSecDoxm_t *newDoxm,
                                     (CATransportAdapter_t)ehRequest->devAddr.adapter);
         VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
 
-        if (!isDuplicatedMsg)
+        char ranPin[OXM_RANDOM_PIN_MAX_SIZE + 1] = {0};
+        if (OC_STACK_OK == GeneratePin(ranPin, sizeof(ranPin)))
         {
-            char ranPin[OXM_RANDOM_PIN_MAX_SIZE + 1] = {0};
-            if (OC_STACK_OK == GeneratePin(ranPin, sizeof(ranPin)))
-            {
-                //Set the device id to derive temporal PSK
-                SetUuidForPinBasedOxm(&gDoxm->deviceID);
-
-                /**
-                 * Since PSK will be used directly by DTLS layer while PIN based ownership transfer,
-                 * Credential should not be saved into SVR.
-                 * For this reason, use a temporary get_psk_info callback to random PIN OxM.
-                 */
-                caRes = CAregisterPskCredentialsHandler(GetDtlsPskForRandomPinOxm);
-                VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
-                ehRet = OC_EH_OK;
-            }
-            else
-            {
-                OIC_LOG(ERROR, TAG, "Failed to generate random PIN");
-                ehRet = OC_EH_ERROR;
-            }
+            //Set the device id to derive temporal PSK
+            SetUuidForPinBasedOxm(&gDoxm->deviceID);
+
+            /**
+             * Since PSK will be used directly by DTLS layer while PIN based ownership transfer,
+             * Credential should not be saved into SVR.
+             * For this reason, use a temporary get_psk_info callback to random PIN OxM.
+             */
+            caRes = CAregisterPskCredentialsHandler(GetDtlsPskForRandomPinOxm);
+            VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
+            ehRet = OC_EH_OK;
+        }
+        else
+        {
+            OIC_LOG(ERROR, TAG, "Failed to generate random PIN");
+            ehRet = OC_EH_ERROR;
         }
 #endif // __WITH_DTLS__ or __WITH_TLS__
     }
@@ -1485,10 +1469,8 @@ OCEntityHandlerResult HandleDoxmPostRequestRandomPin(OicSecDoxm_t *newDoxm,
         memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
 
         // In case of random-pin based OTM, close the PIN display if callback is registered.
-        if (!isDuplicatedMsg)
-        {
-            ClosePinDisplay();
-        }
+        ClosePinDisplay();
+
     }
 #endif // __WITH_DTLS__ or __WITH_TLS__
     goto exit;
@@ -1499,16 +1481,14 @@ exit:
 
 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
 OCEntityHandlerResult HandleDoxmPostRequestMfg(OicSecDoxm_t *newDoxm,
-        OCEntityHandlerRequest *ehRequest,
-        bool isDuplicatedMsg)
+        OCEntityHandlerRequest *ehRequest)
 {
     OIC_LOG_V(DEBUG, TAG, "%s: IN", __func__);
     OCEntityHandlerResult ehRet = OC_EH_OK;
 
-
         //In case of Confirm Manufacturer Cert, get user confirmation
         if (OIC_CON_MFG_CERT == newDoxm->oxmSel && false == newDoxm->owned &&
-            false == isDuplicatedMsg && !IsNilUuid(&newDoxm->owner))
+            !IsNilUuid(&newDoxm->owner))
         {
             if (OC_STACK_OK != VerifyOwnershipTransfer(NULL, USER_CONFIRM))
             {
@@ -1546,8 +1526,7 @@ exit:
 
 // Do OTM specific initiation steps
 OCEntityHandlerResult StartOwnershipTransfer(OicSecDoxm_t *newDoxm,
-        OCEntityHandlerRequest *ehRequest,
-        bool isDuplicatedMsg)
+        OCEntityHandlerRequest *ehRequest)
 {
     OIC_LOG_V(DEBUG, TAG, "%s: IN", __func__);
     OCEntityHandlerResult ehRet = OC_EH_OK;
@@ -1556,15 +1535,15 @@ OCEntityHandlerResult StartOwnershipTransfer(OicSecDoxm_t *newDoxm,
     {
         case OIC_JUST_WORKS:
         case OIC_MV_JUST_WORKS:
-            ehRet = StartOTMJustWorks(ehRequest, isDuplicatedMsg);
+            ehRet = StartOTMJustWorks(ehRequest);
             break;
         case OIC_RANDOM_DEVICE_PIN:
-            ehRet = HandleDoxmPostRequestRandomPin(newDoxm, ehRequest, isDuplicatedMsg);
+            ehRet = HandleDoxmPostRequestRandomPin(newDoxm, ehRequest);
             break;
 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
         case OIC_MANUFACTURER_CERTIFICATE:
         case OIC_CON_MFG_CERT:
-            ehRet = HandleDoxmPostRequestMfg(newDoxm, ehRequest, isDuplicatedMsg);
+            ehRet = HandleDoxmPostRequestMfg(newDoxm, ehRequest);
             break;
 #endif // __WITH_DTLS__ or __WITH_TLS__
         default:
@@ -1580,8 +1559,6 @@ static OCEntityHandlerResult HandleDoxmPostRequest(OCEntityHandlerRequest *ehReq
 {
     OIC_LOG_V(DEBUG, TAG, "%s: IN", __func__);
     OCEntityHandlerResult ehRet = OC_EH_INTERNAL_SERVER_ERROR;
-    static uint16_t previousMsgId = 0;
-    bool isDuplicatedMsg = false;
     bool fACE = false;
     OicSecDoxm_t *newDoxm = NULL;
     bool roParsed = false;
@@ -1619,17 +1596,6 @@ static OCEntityHandlerResult HandleDoxmPostRequest(OCEntityHandlerRequest *ehReq
         goto exit;
     }
 
-    /*
-     * message ID is supported for CoAP over UDP only according to RFC 7252
-     * So we should check message ID to prevent duplicate request handling in case of OC_ADAPTER_IP.
-     * In case of other transport adapter, duplicate message check is not required.
-     */
-    if (OC_ADAPTER_IP == ehRequest->devAddr.adapter &&
-        previousMsgId == ehRequest->messageID)
-    {
-        isDuplicatedMsg = true;
-    }
-
     // Validate newDoxm->oxmsel first
     if (false == ValidateOxmsel(gDoxm->oxm, gDoxm->oxmLen, &newDoxm->oxmSel))
     {
@@ -1648,12 +1614,12 @@ static OCEntityHandlerResult HandleDoxmPostRequest(OCEntityHandlerRequest *ehReq
         goto exit;
     }
 
-    // If oxmsel was in Update payload, and the device is not owned,
-    // do the OTM-specific aspect of owner-transfer
-    if (oxmselParsed && (false == gDoxm->owned))
+    // If oxmsel was in Update payload, and the device is in RFOTM,
+    // start the OTM-specific aspect of owner-transfer.
+    if (oxmselParsed && (DOS_RFOTM == dos.state))
     {
-        OIC_LOG_V(INFO, TAG, "%s: Device not owned and oxmsel Updated... starting OTM!", __func__);
-        ehRet = StartOwnershipTransfer(newDoxm, ehRequest, isDuplicatedMsg);
+        OIC_LOG_V(INFO, TAG, "%s: Device in RFOTM, and oxmsel Updated... starting OTM!", __func__);
+        ehRet = StartOwnershipTransfer(newDoxm, ehRequest);
         VERIFY_SUCCESS(TAG, OC_EH_OK == ehRet, ERROR);
     }
 
@@ -1676,29 +1642,6 @@ static OCEntityHandlerResult HandleDoxmPostRequest(OCEntityHandlerRequest *ehReq
     ehRet = HandleDoxmPostRequestUpdatePS(fACE);
 
 exit:
-    if (OC_EH_OK != ehRet)
-    {
-        // If some error is occured during Update handler,
-        // revert /doxm and /pstat back to initial status.
-
-        if (gDoxm)
-        {
-            if (!isDuplicatedMsg)
-            {
-                RestoreDoxmToInitState();
-                RestorePstatToInitState();
-                OIC_LOG(WARNING, TAG, "DOXM will be reverted.");
-            }
-        }
-        else
-        {
-            OIC_LOG(ERROR, TAG, "Invalid DOXM resource.");
-        }
-    }
-    else
-    {
-        previousMsgId = ehRequest->messageID;
-    }
 
     //Send payload to request originator
     ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
@@ -2270,28 +2213,6 @@ exit:
 
 #endif //MULTIPLE_OWNER
 
-/**
- * Function to restore doxm resurce to initial status.
- * This function will use in case of error while ownership transfer
- */
-void RestoreDoxmToInitState()
-{
-    if(gDoxm)
-    {
-        OIC_LOG(INFO, TAG, "DOXM resource will revert back to initial status.");
-
-        OicUuid_t emptyUuid = {.id={0}};
-        memcpy(&(gDoxm->owner), &emptyUuid, sizeof(OicUuid_t));
-        gDoxm->owned = false;
-        gDoxm->oxmSel = OIC_JUST_WORKS;
-
-        if(!UpdatePersistentStorage(gDoxm))
-        {
-            OIC_LOG(ERROR, TAG, "Failed to revert DOXM in persistent storage");
-        }
-    }
-}
-
 OCStackResult SetDoxmSelfOwnership(const OicUuid_t* newROwner)
 {
     OCStackResult ret = OC_STACK_ERROR;
index 06d6ed6..874d105 100644 (file)
@@ -42,7 +42,7 @@ void GetPkixInfo(PkiInfo_t * inf)
         OIC_LOG_V(WARNING, TAG, "%s: empty certificate", __func__);
     }
 
-    GetDerKey(&inf->key, PRIMARY_CERT);
+    GetPrimaryCertKey(&inf->key);
     if (inf->key.len == 0)
     {
         OIC_LOG_V(WARNING, TAG, "%s: empty key", __func__);
index 9c66fe5..6b39e6d 100644 (file)
@@ -788,8 +788,6 @@ static OCEntityHandlerResult HandlePstatPostRequest(OCEntityHandlerRequest *ehRe
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
     OIC_LOG(INFO, TAG, "HandlePstatPostRequest  processing POST request");
     OicSecPstat_t *pstat = NULL;
-    static uint16_t previousMsgId = 0;
-    bool isDuplicatedMsg = false;
 
     if (ehRequest->payload && NULL != gPstat)
     {
@@ -805,17 +803,6 @@ static OCEntityHandlerResult HandlePstatPostRequest(OCEntityHandlerRequest *ehRe
         // if CBOR parsing OK
         if (OC_STACK_OK == ret)
         {
-            /*
-             * message ID is supported for CoAP over UDP only according to RFC 7252
-             * So we should check message ID to prevent duplicate request handling in case of OC_ADAPTER_IP.
-             * In case of other transport adapter, duplicate message check is not required.
-             */
-            if (OC_ADAPTER_IP == ehRequest->devAddr.adapter &&
-                 previousMsgId == ehRequest->messageID)
-            {
-                isDuplicatedMsg = true;
-            }
-
             if (true == roParsed)
             {
                     OIC_LOG(ERROR, TAG, "Not acceptable request because of read-only properties");
@@ -905,42 +892,7 @@ static OCEntityHandlerResult HandlePstatPostRequest(OCEntityHandlerRequest *ehRe
         }
     }
 
-    exit:
-
-    // TODO [IOT-1796] This is another place error code returns need to be
-    // cleaned up.
-    if (OC_EH_OK != ehRet)
-    {
-        /*
-         * If some error is occured while ownership transfer,
-         * ownership transfer related resource should be revert back to initial status.
-         */
-        OIC_LOG(WARNING, TAG, "The operation failed during handle pstat POST request");
-        const OicSecDoxm_t* doxm = GetDoxmResourceData();
-        if (doxm)
-        {
-            if (!doxm->owned)
-            {
-                if (!isDuplicatedMsg)
-                {
-                    OIC_LOG(WARNING, TAG, "DOXM and PSTAT will be reverted.");
-                    RestoreDoxmToInitState();
-                    RestorePstatToInitState();
-                }
-            }
-        }
-        else
-        {
-           OIC_LOG(ERROR, TAG, "Invalid DOXM resource.");
-        }
-    }
-    else
-    {
-        if (ehRequest->devAddr.adapter == OC_ADAPTER_IP)
-        {
-            previousMsgId = ehRequest->messageID;
-        }
-    }
+exit:
 
     // Send response payload to request originator
     ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
@@ -1067,34 +1019,6 @@ OCStackResult DeInitPstatResource()
     return OCDeleteResource(gPstatHandle);
 }
 
-/**
- * Function to restore pstat resurce to initial status.
- * This function will use in case of error while ownership transfer
- */
-void RestorePstatToInitState()
-{
-    if(gPstat)
-    {
-        OIC_LOG(INFO, TAG, "PSTAT resource will revert back to initial status.");
-        gPstat->dos.state = DOS_RFOTM;
-        gPstat->dos.pending = false;
-        gPstat->cm = (OicSecDpm_t)(gPstat->cm | TAKE_OWNER);
-        OIC_LOG_V(INFO, TAG, "%s setting gPstat->tm = %u",
-            __func__, (OicSecDpm_t)(gPstat->tm & (~TAKE_OWNER)));
-        gPstat->tm = (OicSecDpm_t)(gPstat->tm & (~TAKE_OWNER));
-        gPstat->om = SINGLE_SERVICE_CLIENT_DRIVEN;
-        if(gPstat->sm && 0 < gPstat->smLen)
-        {
-            gPstat->sm[0] = SINGLE_SERVICE_CLIENT_DRIVEN;
-        }
-
-        if (!UpdatePersistentStorage(gPstat))
-        {
-            OIC_LOG(ERROR, TAG, "Failed to revert PSTAT in persistent storage");
-        }
-    }
-}
-
 OCStackResult GetPstatRownerId(OicUuid_t *rowneruuid)
 {
     if (gPstat && rowneruuid)
index b95ada4..a6db8a3 100644 (file)
@@ -716,7 +716,7 @@ OCStackResult CBORPayloadToRoles(const uint8_t *cborPayload, size_t size, RoleCe
                                 /* Only SIGNED_ASYMMETRIC_KEY is supported. */
                                 if (SIGNED_ASYMMETRIC_KEY != (OicSecCredType_t)credType)
                                 {
-                                    OIC_LOG_V(ERROR, TAG, "Unsupported role credential type: %lu", credType);
+                                    OIC_LOG_V(ERROR, TAG, "Unsupported role credential type: %" PRIu64 , credType);
                                     goto exit;
                                 }
                             }
index e67922c..21eef1f 100644 (file)
@@ -312,6 +312,25 @@ void SRMRequestHandler(const CAEndpoint_t *endPoint, const CARequestInfo_t *requ
     // Set secure channel boolean.
     ctx->secureChannel = isRequestOverSecureChannel(ctx);
 
+#if defined( __WITH_TLS__) || defined(__WITH_DTLS__)
+
+    // [IOT-2858]
+    // If request is over Secure Channel but requester ID is Nil UUID
+    // it means that this request arrived over DTLS established via anon
+    // cipher suite.  This may be an opportunity to disable anon cipher
+    // suite, but for now, just log the event.
+#ifndef NDEBUG
+    if (SUBJECT_ID_TYPE_UUID == ctx->subjectIdType)
+    {
+        if (ctx->secureChannel &&
+            IsNilUuid(&(ctx->subjectUuid)))
+        {
+            OIC_LOG_V(INFO, TAG, "%s: request received over Secure Channel from Nil UUID client.", __func__);
+        }
+    }
+#endif // NDEBUG
+#endif // DTLS
+
     // Set resource URI and type.
     SetResourceUriAndType(ctx);
 
index 28a1672..67624c7 100644 (file)
@@ -54,7 +54,7 @@ static OicSecDoxm_t *JSONToDoxmBin(const char *jsonStr);
 static OicSecAcl_t *JSONToAclBin(OicSecAclVersion_t *aclVersion,
                                  const char *jsonStr);
 static OicSecAmacl_t *JSONToAmaclBin(const char *jsonStr);
-static OicSecCred_t *JSONToCredBin(const char *jsonStr);
+static OicSecCred_t *JSONToCredBinWithRowner(const char *jsonStr,OicUuid_t *rownerId);
 static OCDeviceProperties *JSONToDPBin(const char *jsonStr);
 
 static size_t GetJSONFileSize(const char *jsonFileName)
@@ -419,7 +419,8 @@ static OCStackResult ConvertOCJSONStringToCBORFile(const char *jsonStr, const ch
     int secureFlag = 0;
     if (NULL != value)
     {
-        OicSecCred_t *cred = JSONToCredBin(jsonStr);
+        OicUuid_t rownerId;
+        OicSecCred_t *cred = JSONToCredBinWithRowner(jsonStr,&rownerId);
         VERIFY_NOT_NULL(TAG, cred, FATAL);
         // The source code line below is just a workaround for IOT-2407.
         // It should be deleted when IOT-2407 gets fixed. There is no clear
@@ -427,7 +428,7 @@ static OCStackResult ConvertOCJSONStringToCBORFile(const char *jsonStr, const ch
         // CredToCBORPayload happens to work better when initializing
         // credCborSize this way.
         credCborSize = strlen(jsonStr);
-        ret = CredToCBORPayload(cred, &credCbor, &credCborSize, secureFlag);
+        ret = CredToCBORPayloadWithRowner(cred, &rownerId,&credCbor, &credCborSize, secureFlag);
         if (OC_STACK_OK != ret)
         {
             OIC_LOG (ERROR, TAG, "Failed converting Cred to Cbor Payload");
@@ -1165,7 +1166,7 @@ static OicEncodingType_t GetEncodingTypeFromStr(const char *encodingType)
     return OIC_ENCODING_RAW;
 }
 
-OicSecCred_t *JSONToCredBin(const char *jsonStr)
+static OicSecCred_t *JSONToCredBinWithRowner(const char *jsonStr,OicUuid_t *rownerId)
 {
     if (NULL == jsonStr)
     {
@@ -1357,13 +1358,13 @@ OicSecCred_t *JSONToCredBin(const char *jsonStr)
     }
 
     // rownerid
-/*    cJSON *jsonCredObj = cJSON_GetObjectItem(jsonCredMap, OIC_JSON_ROWNERID_NAME);
+    cJSON *jsonCredObj = cJSON_GetObjectItem(jsonCredMap, OIC_JSON_ROWNERID_NAME);
     VERIFY_NOT_NULL(TAG, jsonCredObj, ERROR);
     VERIFY_SUCCESS(TAG, cJSON_String == jsonCredObj->type, ERROR);
-    ret = ConvertStrToUuid(jsonCredObj->valuestring, &headCred->rownerID);
+    ret = ConvertStrToUuid(jsonCredObj->valuestring, rownerId);
     VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
     ret = OC_STACK_OK;
-*/
+
 exit:
     cJSON_Delete(jsonRoot);
     if (OC_STACK_OK != ret)
index 4456bfc..5027d47 100644 (file)
@@ -64,7 +64,7 @@ INLINE_API void OCPayloadLogRepValues(LogLevel level, OCRepPayloadValue* val)
                 OIC_LOG_V(level, PL_TAG, "\t\t%s: NULL", val->name);
                 break;
             case OCREP_PROP_INT:
-                OIC_LOG_V(level, PL_TAG, "\t\t%s(int):%zd", val->name, val->i);
+                OIC_LOG_V(level, PL_TAG, "\t\t%s(int):%" PRId64, val->name, val->i);
                 break;
             case OCREP_PROP_DOUBLE:
                 OIC_LOG_V(level, PL_TAG, "\t\t%s(double):%f", val->name, val->d);
@@ -96,7 +96,7 @@ INLINE_API void OCPayloadLogRepValues(LogLevel level, OCRepPayloadValue* val)
                         OIC_LOG(level, PL_TAG, "\t\t Values:");
                         for (size_t i = 0; i < val->arr.dimensions[0]; i++)
                         {
-                            OIC_LOG_V(level, PL_TAG, "\t\t\t %zd", val->arr.iArray[i]);
+                            OIC_LOG_V(level, PL_TAG, "\t\t\t %" PRId64, val->arr.iArray[i]);
                         }
                         break;
                     case OCREP_PROP_DOUBLE:
index c9a58f0..529c8b8 100644 (file)
@@ -30,6 +30,7 @@
 #include "provisioningdatabasemanager.h"
 
 #define TIMEOUT 5
+#define DB_FILE "./dbPath.tmp"
 
 namespace OCProvisioningTest
 {
@@ -50,7 +51,7 @@ namespace OCProvisioningTest
 
     TEST(ProvisionInitTest, TestValidPath)
     {
-        std::string dbPath("./dbPath.tmp");
+        std::string dbPath(DB_FILE);
         EXPECT_EQ(OC_STACK_OK, OCSecure::provisionInit(dbPath));
         EXPECT_EQ(OC_STACK_OK, OCSecure::provisionClose());
     }
@@ -185,7 +186,7 @@ namespace OCProvisioningTest
 
     TEST(DeviceInfoTest, DevInfoFromNetwork)
     {
-        std::string dbPath("./dbPath");
+        std::string dbPath(DB_FILE);
         EXPECT_EQ(OC_STACK_OK, OCSecure::provisionInit(dbPath));
         DeviceList_t owned, unowned;
         EXPECT_EQ(OC_STACK_OK, OCSecure::getDevInfoFromNetwork(TIMEOUT,
index d92992d..54b75f2 100644 (file)
@@ -386,38 +386,33 @@ OCEntityHandlerResult updateEasySetupResource(OCEntityHandlerRequest* ehRequest,
             while(children)
             {
                 char* uri = children->uri;
-                if(NULL == uri)
+                if (NULL == uri)
                 {
-                    OIC_LOG(DEBUG, ES_RH_TAG,
-                        "No URI found in request, applying same request to all links in collection");
-
-                    ///TODO: Need to check if "input" should be passed, or the value of property OC_RSRVD_REPRESENTATION.
-                    updateEasySetupConnectProperty(input);
-                    updateWiFiConfResource(input);
-                    updateCoapCloudConfResource(input);
-                    updateDevConfResource(input);
-
-                    // As the request is applied to children already, no need to check next child.
-                    break;
+                    OIC_LOG(DEBUG, ES_RH_TAG, "No URI found in request");
+                }
+                else
+                {
+                    OIC_LOG_V(DEBUG, ES_RH_TAG, "Request URI [%s]", uri);
                 }
-
-                OIC_LOG_V(DEBUG, ES_RH_TAG, "uri [%s]", uri);
 
                 OCRepPayload *repPayload = NULL;
                 OCRepPayloadGetPropObject(children, OC_RSRVD_REPRESENTATION, &repPayload);
-
-                if(NULL == repPayload)
+                if (NULL == repPayload)
                 {
                     OIC_LOG(ERROR, ES_RH_TAG, "repPayload is null!");
                     children = children->next;
                     continue;
                 }
 
-                if (0 == strcmp(uri, OC_RSRVD_ES_URI_EASYSETUP))
+                // If uri is NULL, rep is applied to all resources in collection;
+                // otherwise its applied to specific target resources.
+                if (NULL == uri || 0 == strlen(uri) || 0 == strcmp(uri, OC_RSRVD_ES_URI_EASYSETUP))
                 {
                     updateEasySetupConnectProperty(repPayload);
                 }
-                else if (0 == strcmp(uri, OC_RSRVD_ES_URI_WIFICONF))
+
+                if (NULL == uri || 0 == strlen(uri)
+                    || 0 == strcmp(uri, OC_RSRVD_ES_URI_WIFICONF))
                 {
                     if (updateWiFiConfResource(repPayload) != OC_EH_OK)
                     {
@@ -427,11 +422,15 @@ OCEntityHandlerResult updateEasySetupResource(OCEntityHandlerRequest* ehRequest,
                         hasError = true;
                     }
                 }
-                else if (0 == strcmp(uri, OC_RSRVD_ES_URI_COAPCLOUDCONF))
+
+                if (NULL == uri ||  0 == strlen(uri)
+                    || 0 == strcmp(uri, OC_RSRVD_ES_URI_COAPCLOUDCONF))
                 {
                     updateCoapCloudConfResource(repPayload);
                 }
-                else if (0 == strcmp(uri, OC_RSRVD_ES_URI_DEVCONF))
+
+                if (NULL == uri ||  0 == strlen(uri)
+                    || 0 == strcmp(uri, OC_RSRVD_ES_URI_DEVCONF))
                 {
                     updateDevConfResource(repPayload);
                 }
index 80267f7..c2df9b1 100644 (file)
@@ -331,7 +331,6 @@ void NSProviderMQSubscription(NSMQTopicAddress * topicAddr)
     OCCallbackData cbdata = { NULL, NULL, NULL };\r
     cbdata.cb = NSProviderGetMQResponseCB;\r
     cbdata.context = OICStrdup(topicName);\r
-\r
     char requestUri[100] = "coap+tcp://";\r
 \r
     NS_LOG_V(DEBUG, "requestUri1 = %s", requestUri);\r
index 2b9a55b..e8931d7 100644 (file)
@@ -312,8 +312,14 @@ NSResult NSSendTopicList(OCEntityHandlerRequest * entityHandlerRequest)
             topics = next;
         }
 
-        OCRepPayloadSetPropObjectArrayAsOwner(payload, NS_ATTRIBUTE_TOPIC_LIST,
-                    payloadTopicArray, dimensions);
+        OCRepPayloadSetPropObjectArray(payload, NS_ATTRIBUTE_TOPIC_LIST,
+                (const OCRepPayload**) (payloadTopicArray), dimensions);
+        for (int i = 0; i < (int) dimensionSize; ++i)
+        {
+            OCRepPayloadDestroy(payloadTopicArray[i]);
+        }
+        NSOICFree(payloadTopicArray);
+
     }
     else
     {
index 005e0a5..b85ea15 100644 (file)
@@ -324,10 +324,6 @@ int main(void)
     {
         std::cout << "main exception  : " << e.what() << std::endl;
     }
-    catch (...)
-    {
-        std::cout << "main exception  : unknown" << std::endl;
-    }
 
     std::cout << "Stopping the server" << std::endl;
 }
index a3758c6..5e24060 100644 (file)
@@ -46,7 +46,10 @@ namespace OIC
             auto task = ExpiryTimerImpl::getInstance()->post(milliSec, std::move(cb));
             m_tasks[task->getId()] = task;
 
-            if (m_tasks.size() == m_nextSweep) sweep();
+            if (m_tasks.size() == m_nextSweep)
+            {
+                sweep();
+            }
 
             return task->getId();
         }
@@ -55,12 +58,18 @@ namespace OIC
         {
             auto it = m_tasks.find(id);
 
-            if (it == m_tasks.end()) return false;
+            if (it == m_tasks.end())
+            {
+                return false;
+            }
 
             auto task = it->second;
             m_tasks.erase(it);
 
-            if (task->isExecuted()) return false;
+            if (task->isExecuted())
+            {
+                return false;
+            }
 
             return ExpiryTimerImpl::getInstance()->cancel(id);
         }
index c79d1e6..183868e 100644 (file)
@@ -78,7 +78,10 @@ namespace OIC
 
         bool ExpiryTimerImpl::cancel(Id id)
         {
-            if (id == INVALID_ID) return false;
+            if (id == INVALID_ID)
+            {
+                return false;
+            }
 
             std::lock_guard< std::mutex > lock{ m_mutex };
 
@@ -136,7 +139,10 @@ namespace OIC
         {
             for (const auto& info : m_tasks)
             {
-                if (info.second->getId() == id) return true;
+                if (info.second->getId() == id)
+                {
+                    return true;
+                }
             }
             return false;
         }
@@ -156,7 +162,10 @@ namespace OIC
 
         void ExpiryTimerImpl::executeExpired()
         {
-            if (m_tasks.empty()) return;
+            if (m_tasks.empty())
+            {
+                return;
+            }
 
             auto now = std::chrono::system_clock::now().time_since_epoch();
 
@@ -179,7 +188,10 @@ namespace OIC
 
         void ExpiryTimerImpl::run()
         {
-            auto hasTaskOrStop = [this](){ return !m_tasks.empty() || m_stop; };
+            auto hasTaskOrStop = [this]()
+            {
+                return !m_tasks.empty() || m_stop;
+            };
 
             std::unique_lock< std::mutex > lock{ m_mutex };
 
@@ -187,7 +199,10 @@ namespace OIC
             {
                 m_cond.wait(lock, hasTaskOrStop);
 
-                if (m_stop) break;
+                if (m_stop)
+                {
+                    break;
+                }
 
                 m_cond.wait_for(lock, remainingTimeForNext());
 
@@ -204,7 +219,10 @@ namespace OIC
 
         void TimerTask::execute()
         {
-            if (isExecuted()) return;
+            if (isExecuted())
+            {
+                return;
+            }
 
             ExpiryTimerImpl::Id id { m_id };
             m_id = INVALID_ID;
index f556f39..6265dad 100644 (file)
@@ -122,7 +122,10 @@ namespace OIC
         {
             for (auto r : allowed)
             {
-                if (actual == r) return;
+                if (actual == r)
+                {
+                    return;
+                }
             }
 
             throw RCSPlatformException(actual);
@@ -147,7 +150,10 @@ namespace OIC
         invokeOCFuncWithResultExpect(std::initializer_list<OCStackResult> allowed,
                 FUNC&& fn, PARAMS&& ...params)
         {
-            if (Detail::TerminationChecker::isInTermination()) return;
+            if (Detail::TerminationChecker::isInTermination())
+            {
+                return;
+            }
 
             try
             {
@@ -165,7 +171,10 @@ namespace OIC
                 OCStackResult >::type
         invokeOCFunc(FUNC&& fn, PARAMS&& ...params)
         {
-            if (Detail::TerminationChecker::isInTermination()) return;
+            if (Detail::TerminationChecker::isInTermination())
+            {
+                return;
+            }
 
             try
             {
@@ -182,7 +191,10 @@ namespace OIC
                         Detail::NotOCStackResult >::type
         invokeOCFunc(FUNC* fn, PARAMS&& ...params)
         {
-            if (Detail::TerminationChecker::isInTermination()) return;
+            if (Detail::TerminationChecker::isInTermination())
+            {
+                return;
+            }
 
             try
             {
@@ -201,8 +213,10 @@ namespace OIC
                 decltype((obj->*fn)(std::forward< PARAMS >(params)...)), OCStackResult>::
                 type
         {
-            if (Detail::TerminationChecker::isInTermination()) return;
-
+            if (Detail::TerminationChecker::isInTermination())
+            {
+                return;
+            }
             try
             {
                 expectOCStackResultOK(obj->*fn(std::forward< PARAMS >(params)...));
@@ -221,7 +235,10 @@ namespace OIC
                     Detail::NotOCStackResult>::
                     type
         {
-            if (Detail::TerminationChecker::isInTermination()) return;
+            if (Detail::TerminationChecker::isInTermination())
+            {
+                return;
+            }
 
             try
             {
@@ -240,7 +257,10 @@ namespace OIC
                     decltype((obj.get()->*fn)(std::forward< PARAMS >(params)...)), OCStackResult>::
                     type
         {
-            if (Detail::TerminationChecker::isInTermination()) return;
+            if (Detail::TerminationChecker::isInTermination())
+            {
+                return;
+            }
 
             try
             {
@@ -260,7 +280,10 @@ namespace OIC
                    Detail::NotOCStackResult>::
                    type
         {
-            if (Detail::TerminationChecker::isInTermination()) return { };
+            if (Detail::TerminationChecker::isInTermination())
+            {
+                return { };
+            }
 
             try
             {
index 778a62a..bc13112 100644 (file)
@@ -50,7 +50,10 @@ namespace OIC
             {
                 auto checkedRes = resource.lock();
 
-                if (!checkedRes) return;
+                if (!checkedRes)
+                {
+                    return;
+                }
 
                 cb(std::forward< ARGS >(args)...);
             }
index 10f59e0..0fb93ef 100644 (file)
@@ -114,7 +114,8 @@ namespace OIC
                 void insertItem(Detail::Int2Type< DEPTH >,
                         const OC::OCRepresentation::AttributeItem& item)
                 {
-                    switch (item.base_type()) {
+                    switch (item.base_type())
+                    {
                         case OC::AttributeType::Null:
                             return putValue(item.attrname(), nullptr);
 
index ab01604..6666bce 100644 (file)
@@ -63,7 +63,10 @@ namespace
             m_stream << "[";
             for (auto it = v.begin(); it != v.end(); ++it)
             {
-                if (it != v.begin()) m_stream << ", ";
+                if (it != v.begin())
+                {
+                    m_stream << ", ";
+                }
                 (*this)(*it);
             }
             m_stream << "]";
@@ -97,13 +100,17 @@ namespace
             m_stream << "{";
             for (auto it = attrs.begin(); it != attrs.end(); ++it)
             {
-                if (it != attrs.begin()) m_stream << ", ";
+                if (it != attrs.begin())
+                {
+                    m_stream << ", ";
+                }
                 m_stream << "\"" << it->key() << "\" : " << it->value().toString();
             }
             m_stream << "}";
         }
 
-        std::string get() const {
+        std::string get() const
+        {
             return m_stream.str();
         }
 
@@ -456,6 +463,11 @@ namespace OIC
 
         auto RCSResourceAttributes::iterator::operator=(const iterator& rhs) -> iterator&
         {
+            // If it is same object skip assignment
+            if (this == &rhs)
+            {
+                return *this;
+            }
             m_cur = rhs.m_cur;
             return *this;
         }
@@ -524,6 +536,11 @@ namespace OIC
         auto RCSResourceAttributes::const_iterator::operator=(
                 const const_iterator& rhs) -> const_iterator&
         {
+            // If it is same object skip assignment
+            if (this == &rhs)
+            {
+                return *this;
+            }
             m_cur = rhs.m_cur;
             return *this;
         }
index 5a69004..9b81373 100644 (file)
@@ -66,7 +66,8 @@ public:
     FakeOCResource* fakeResource;
 
 protected:
-    void SetUp() {
+    void SetUp()
+    {
         TestWithMock::SetUp();
 
         fakeResource = mocks.Mock< FakeOCResource >();
index 3a9e490..14bfca2 100644 (file)
@@ -32,7 +32,8 @@ public:
 protected:
     virtual ~TestWithMock() noexcept(noexcept(std::declval<Test>().~Test())) {}
 
-    virtual void TearDown() {
+    virtual void TearDown()
+    {
         try
         {
             mocks.VerifyAll();
index 7ebdf3f..cdab171 100644 (file)
@@ -45,7 +45,8 @@ namespace OIC
                 try
                 {
                     presenceSubscriber.unsubscribe();
-                } catch (std::exception & e)
+                }
+                catch (std::exception & e)
                 {
                     OIC_LOG_V(DEBUG,BROKER_TAG,"unsubscribed presence : %s", e.what());
                 }
@@ -66,10 +67,11 @@ namespace OIC
                 OIC_LOG_V(DEBUG, BROKER_TAG, "subscribe Presence");
                 presenceSubscriber
                 = PresenceSubscriber(address, BROKER_TRANSPORT, pSubscribeRequestCB);
-            } catch(RCSPlatformException &e)
+            }
+            catch(RCSPlatformException &e)
             {
                 OIC_LOG_V(DEBUG, BROKER_TAG,
-                        "exception in subscribe Presence %s", e.getReason().c_str());
+                "exception in subscribe Presence %s", e.getReason().c_str());
                 throw;
             }
             presenceTimerHandle
index 970db5f..f858017 100644 (file)
@@ -82,7 +82,8 @@ namespace OIC
                     OIC_LOG_V(DEBUG, BROKER_TAG, "create the ResourcePresence.");
                     presenceItem.reset(new ResourcePresence());
                     presenceItem->initializeResourcePresence(pResource);
-                }catch(RCSPlatformException &e)
+                }
+                catch(RCSPlatformException &e)
                 {
                     throw FailedSubscribePresenceException(e.getReasonCode());
                 }
index c5aba84..da2889c 100644 (file)
@@ -158,7 +158,8 @@ namespace OIC
             return (requesterList!=nullptr)?requesterList->empty():true;
         }
 
-        int ResourcePresence::requesterListSize() const {
+        int ResourcePresence::requesterListSize() const
+        {
             OIC_LOG_V(DEBUG,BROKER_TAG,"requesterListSize().\n");
             return (requesterList!=nullptr)?requesterList->size():0;
         }
index 7dd9927..1147c63 100644 (file)
@@ -117,7 +117,6 @@ TEST_F(ResourcePresenceTest,addBrokerRequester_ReturnNormalValueIfNormalParams)
     id = 1;
     instance->addBrokerRequester(id,cb);
     EXPECT_FALSE(instance->isEmptyRequester());
-
 }
 
 TEST_F(ResourcePresenceTest,removeBrokerRequester_NormalHandlingIfNormalId)
index a44f5d0..9edb290 100644 (file)
@@ -38,7 +38,9 @@ namespace OIC
         void RCSDiscoveryManager::DiscoveryTask::cancel()
         {
             if (isCanceled())
+            {
                 return;
+            }
 
             RCSDiscoveryManagerImpl::getInstance()->cancel(m_id);
             m_id = RCSDiscoveryManagerImpl::INVALID_ID;
index 7db2529..aa60a5e 100644 (file)
@@ -35,9 +35,12 @@ namespace
         return resource->getSid() + resource->getUri();
     }
 
-    void validateTypes(const std::vector< std::string >& resourceTypes) {
-        if (resourceTypes.size() == 1) return;
-
+    void validateTypes(const std::vector< std::string >& resourceTypes)
+    {
+        if (resourceTypes.size() == 1)
+        {
+            return;
+        }
         for (const auto& type : resourceTypes)
         {
             if (type == OIC::Service::RCSDiscoveryManagerImpl::ALL_RESOURCE_TYPE)
@@ -79,9 +82,14 @@ namespace OIC
                 std::lock_guard < std::mutex > lock(m_mutex);
                 auto it = m_discoveryMap.find(discoveryId);
 
-                if (it == m_discoveryMap.end()) return;
-                if (it->second.isKnownResource(resource)) return;
-
+                if (it == m_discoveryMap.end())
+                {
+                    return;
+                }
+                if (it->second.isKnownResource(resource))
+                {
+                    return;
+                }
                 it->second.addKnownResource(resource);
             }
 
@@ -149,7 +157,10 @@ namespace OIC
         void RCSDiscoveryManagerImpl::onPresence(OCStackResult result, const unsigned int /*seq*/,
                 const std::string& address)
         {
-            if (result != OC_STACK_OK && result != OC_STACK_RESOURCE_CREATED) return;
+            if (result != OC_STACK_OK && result != OC_STACK_RESOURCE_CREATED)
+            {
+                return;
+            }
 
             std::lock_guard < std::mutex > lock(m_mutex);
             for (const auto& it : m_discoveryMap)
index 8f1818e..223b06d 100644 (file)
@@ -179,12 +179,13 @@ namespace OIC
         RCSRemoteResourceObject::~RCSRemoteResourceObject()
         {
             SCOPE_LOG_F(DEBUG, TAG);
-
-            try{
+            try
+            {
                 stopCaching();
                 stopMonitoring();
             }
-            catch(std::exception &e){
+            catch(std::exception &e)
+            {
                 OIC_LOG_V(ERROR, TAG, "%s", e.what());
             }
         }
index bf59e69..7a52f8f 100644 (file)
@@ -153,10 +153,16 @@ namespace OIC
                 const std::string& defaultInterfaceName)
         {
             auto it = g_defaultHandlers.find(interfaceName);
-            if (it != g_defaultHandlers.end()) return it->second;
+            if (it != g_defaultHandlers.end())
+            {
+                return it->second;
+            }
 
             it = g_defaultHandlers.find(defaultInterfaceName);
-            if (it != g_defaultHandlers.end()) return it->second;
+            if (it != g_defaultHandlers.end())
+            {
+                return it->second;
+            }
 
             return g_defaultHandlers.find(OIC::Service::BASELINE_INTERFACE)->second;
         }
index 6efc456..8175f9a 100644 (file)
@@ -67,8 +67,10 @@ namespace OIC
 
             auto it = params.find(OC::Key::INTERFACESKEY);
 
-            if (it == params.end()) return "";
-
+            if (it == params.end())
+            {
+                return "";
+            }
             return it->second;
         }
 
index 027d493..0a22b84 100644 (file)
@@ -123,7 +123,10 @@ namespace
 
     void insertValue(std::vector<std::string>& container, std::string value)
     {
-        if (value.empty()) return;
+            if (value.empty())
+            {
+                return;
+            }
 
         if (std::find(container.begin(), container.end(), value) == container.end())
         {
@@ -233,12 +236,14 @@ namespace OIC
                     handle, m_uri, m_types[0], m_interfaces[0], entityHandler, m_properties);
 
             std::for_each(m_interfaces.begin() + 1, m_interfaces.end(),
-                    [&handle](const std::string& interfaceName){
+                    [&handle](const std::string& interfaceName)
+            {
                 invokeOCFunc(OC::OCPlatform::bindInterfaceToResource, handle, interfaceName);
             });
 
             std::for_each(m_types.begin() + 1, m_types.end(),
-                    [&handle](const std::string& typeName){
+                    [&handle](const std::string& typeName)
+            {
                 invokeOCFunc(OC::OCPlatform::bindTypeToResource, handle, typeName);
             });
 
@@ -319,7 +324,10 @@ namespace OIC
                 m_resourceAttributes[std::forward< K >(key)] = std::forward< V >(value);
             }
 
-            if (needToNotify) autoNotify(valueUpdated);
+            if (needToNotify)
+            {
+                autoNotify(valueUpdated);
+            }
         }
         void RCSResourceObject::setAttribute(const std::string& key,
                 const RCSResourceAttributes::Value& value)
@@ -366,7 +374,10 @@ namespace OIC
                 }
             }
 
-            if (needToNotify) autoNotify(true);
+            if (needToNotify)
+            {
+                autoNotify(true);
+            }
 
             return erased;
         }
@@ -573,9 +584,16 @@ namespace OIC
         void RCSResourceObject::autoNotify(
                         bool isAttributesChanged, AutoNotifyPolicy autoNotifyPolicy) const
         {
-            if(autoNotifyPolicy == AutoNotifyPolicy::NEVER) return;
+            if(autoNotifyPolicy == AutoNotifyPolicy::NEVER)
+            {
+                return;
+            }
+
             if(autoNotifyPolicy == AutoNotifyPolicy::UPDATED &&
-                    isAttributesChanged == false) return;
+                    isAttributesChanged == false)
+            {
+                return;
+            }
 
             notify();
         }
@@ -586,7 +604,10 @@ namespace OIC
         {
             auto resource = weakRes.lock();
 
-            if (!resource) return OC_EH_ERROR;
+            if (!resource)
+            {
+                return OC_EH_ERROR;
+            }
 
             OIC_LOG(WARNING, LOG_TAG_RE, "entityHandler");
             if (!request)
@@ -655,7 +676,10 @@ namespace OIC
 
             auto response = invokeHandler(attrs, request, m_getRequestHandler);
 
-            if (response.isSeparate()) return OC_EH_SLOW;
+            if (response.isSeparate())
+            {
+                return OC_EH_SLOW;
+            }
 
             return sendResponse(request, response,
                          findInterfaceHandler(request.getInterface()).getGetResponseBuilder());
@@ -707,7 +731,10 @@ namespace OIC
 
             auto response = invokeHandler(attrs, request, m_setRequestHandler);
 
-            if (response.isSeparate()) return OC_EH_SLOW;
+            if (response.isSeparate())
+            {
+                return OC_EH_SLOW;
+            }
 
             autoNotify(applyAcceptanceMethod(response, attrs), m_autoNotifyPolicy);
 
@@ -730,7 +757,10 @@ namespace OIC
         {
             auto it = m_interfaceHandlers.find(interfaceName);
 
-            if (it != m_interfaceHandlers.end()) return it->second;
+            if (it != m_interfaceHandlers.end())
+            {
+                return it->second;
+            }
 
             assert(m_interfaceHandlers.find(m_defaultInterface) != m_interfaceHandlers.end());
 
@@ -798,7 +828,10 @@ namespace OIC
 
         RCSResourceObject::LockGuard::~LockGuard() noexcept(false)
         {
-            if (!std::uncaught_exception() && m_autoNotifyFunc) m_autoNotifyFunc();
+            if (!std::uncaught_exception() && m_autoNotifyFunc)
+            {
+                m_autoNotifyFunc();
+            }
 
             if (m_isOwningLock)
             {
index 8a9e1c0..9ed0c73 100644 (file)
@@ -73,7 +73,10 @@ namespace OIC
                 throw RCSBadRequestException{ "ResourceObject is unspecified(or destroyed)!" };\r
             }\r
 \r
-            if (m_done) throw RCSBadRequestException{ "The response is already set!" };\r
+            if (m_done)\r
+            {\r
+                throw RCSBadRequestException{ "The response is already set!" };\r
+            }\r
 \r
             auto ocRequest = m_request.getOCRequest();\r
             auto response = std::make_shared< OC::OCResourceResponse >();\r
index ad33726..1202c54 100644 (file)
@@ -175,7 +175,8 @@ protected:
                         .Return(OC_STACK_OK);
     }
 
-    virtual void initResourceObject() {
+    virtual void initResourceObject()
+    {
         server->setAutoNotifyPolicy(RCSResourceObject::AutoNotifyPolicy::NEVER);
     }
 };
@@ -280,7 +281,8 @@ protected:
                         .Return(OC_STACK_OK);
     }
 
-    virtual void initResourceObject() {
+    virtual void initResourceObject()
+    {
         // intended blank
     }
 };
@@ -878,7 +880,10 @@ TEST_F(ResourceObjectSynchronizationTest, MultipleAccessToServerResourceWithRequ
             for (int i=0; i<10000; ++i)
 #endif
             {
-                if (i % 5 == 0) handler(createRequest(OC_REST_OBSERVE));
+                if (i % 5 == 0)
+                {
+                    handler(createRequest(OC_REST_OBSERVE));
+                }
                 handler(createRequest((i & 1) ? OC_REST_GET : OC_REST_POST));
             }
         }