Security CBOR conversion
authorSahil Bansal <sahil.bansal@samsung.com>
Sat, 19 Mar 2016 11:19:23 +0000 (16:49 +0530)
committerRandeep Singh <randeep.s@samsung.com>
Sat, 19 Mar 2016 13:44:04 +0000 (13:44 +0000)
 - all security resources converted to CBOR format
 - added .dat files for samples
 - modified psinterface to handle pconf resource
 - modified json2cbor tool to handle private data in cred
 - Added dat file for c++ PT
 - Corrected Unit Test case
 - Code change as per review comments
 - Resolved SVACE issues

Change-Id: Idadfe37c07f44bfaf1c7929c772f99e2163f7e2f
Signed-off-by: Ashwini Kumar <k.ashwini@samsung.com>
Signed-off-by: Sandeep Sharma <sandeep.s9@samsung.com>
Signed-off-by: saurabh.s9 <saurabh.s9@samsung.com>
Signed-off-by: Sahil Bansal <sahil.bansal@samsung.com>
Reviewed-on: https://gerrit.iotivity.org/gerrit/6079
Tested-by: jenkins-iotivity <jenkins-iotivity@opendaylight.org>
Reviewed-by: Randeep Singh <randeep.s@samsung.com>
112 files changed:
resource/csdk/security/SConscript
resource/csdk/security/include/base64.h
resource/csdk/security/include/internal/aclresource.h
resource/csdk/security/include/internal/amaclresource.h
resource/csdk/security/include/internal/amsmgr.h
resource/csdk/security/include/internal/credresource.h
resource/csdk/security/include/internal/crlresource.h
resource/csdk/security/include/internal/doxmresource.h
resource/csdk/security/include/internal/dpairingresource.h
resource/csdk/security/include/internal/pconfresource.h
resource/csdk/security/include/internal/policyengine.h
resource/csdk/security/include/internal/psinterface.h
resource/csdk/security/include/internal/pstatresource.h
resource/csdk/security/include/internal/resourcemanager.h
resource/csdk/security/include/internal/secureresourcemanager.h
resource/csdk/security/include/internal/security_internals.h [new file with mode: 0644]
resource/csdk/security/include/internal/srmresourcestrings.h
resource/csdk/security/include/internal/svcresource.h
resource/csdk/security/include/pbkdf2.h
resource/csdk/security/include/pinoxmcommon.h
resource/csdk/security/include/securevirtualresourcetypes.h
resource/csdk/security/include/srmutility.h
resource/csdk/security/provisioning/ck_manager/sample/Door_sample.cpp
resource/csdk/security/provisioning/ck_manager/sample/Light_sample.cpp
resource/csdk/security/provisioning/ck_manager/sample/SConscript
resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_door.dat [new file with mode: 0644]
resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_door.json
resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_light.dat [new file with mode: 0644]
resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_light.json
resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_pt.dat [new file with mode: 0644]
resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_pt.json
resource/csdk/security/provisioning/ck_manager/sample/provisioningclient.c
resource/csdk/security/provisioning/ck_manager/unittest/SConscript
resource/csdk/security/provisioning/ck_manager/unittest/pki_test.cpp
resource/csdk/security/provisioning/ck_manager/unittest/test_data/CKMInfo.dat [new file with mode: 0644]
resource/csdk/security/provisioning/include/internal/ownershiptransfermanager.h
resource/csdk/security/provisioning/include/oxm/oxmjustworks.h
resource/csdk/security/provisioning/include/oxm/oxmrandompin.h
resource/csdk/security/provisioning/sample/SConscript
resource/csdk/security/provisioning/sample/oic_svr_db_client.dat [new file with mode: 0644]
resource/csdk/security/provisioning/sample/oic_svr_db_client.json
resource/csdk/security/provisioning/sample/oic_svr_db_prov_tool.dat [new file with mode: 0644]
resource/csdk/security/provisioning/sample/oic_svr_db_server_justworks.dat [new file with mode: 0644]
resource/csdk/security/provisioning/sample/oic_svr_db_server_justworks.json
resource/csdk/security/provisioning/sample/oic_svr_db_server_randompin.dat [new file with mode: 0644]
resource/csdk/security/provisioning/sample/oic_svr_db_server_randompin.json
resource/csdk/security/provisioning/sample/oic_svr_db_unowned_server.dat [new file with mode: 0644]
resource/csdk/security/provisioning/sample/provisioningclient.c
resource/csdk/security/provisioning/sample/sampleserver_justworks.cpp
resource/csdk/security/provisioning/sample/sampleserver_randompin.cpp
resource/csdk/security/provisioning/src/credentialgenerator.c
resource/csdk/security/provisioning/src/ownershiptransfermanager.c
resource/csdk/security/provisioning/src/oxmjustworks.c
resource/csdk/security/provisioning/src/oxmrandompin.c
resource/csdk/security/provisioning/src/pmutility.c
resource/csdk/security/provisioning/src/secureresourceprovider.c
resource/csdk/security/provisioning/unittest/otmunittest.cpp
resource/csdk/security/src/aclresource.c
resource/csdk/security/src/amaclresource.c
resource/csdk/security/src/amsmgr.c
resource/csdk/security/src/base64.c
resource/csdk/security/src/credresource.c
resource/csdk/security/src/crlresource.c
resource/csdk/security/src/directpairing.c
resource/csdk/security/src/doxmresource.c
resource/csdk/security/src/dpairingresource.c [changed mode: 0644->0755]
resource/csdk/security/src/oxmpincommon.c
resource/csdk/security/src/pbkdf2.c
resource/csdk/security/src/pconfresource.c
resource/csdk/security/src/policyengine.c
resource/csdk/security/src/psinterface.c
resource/csdk/security/src/pstatresource.c
resource/csdk/security/src/resourcemanager.c
resource/csdk/security/src/secureresourcemanager.c
resource/csdk/security/src/srmresourcestrings.c
resource/csdk/security/src/srmutility.c
resource/csdk/security/src/svcresource.c
resource/csdk/security/tool/SConscript [new file with mode: 0644]
resource/csdk/security/tool/json2cbor.c [new file with mode: 0644]
resource/csdk/security/unittest/SConscript
resource/csdk/security/unittest/aclresourcetest.cpp
resource/csdk/security/unittest/amaclresourcetest.cpp [new file with mode: 0644]
resource/csdk/security/unittest/credentialresource.cpp
resource/csdk/security/unittest/doxmresource.cpp
resource/csdk/security/unittest/oic_svr_db.dat [new file with mode: 0644]
resource/csdk/security/unittest/oic_unittest.dat [new file with mode: 0644]
resource/csdk/security/unittest/oic_unittest_acl1.dat [new file with mode: 0644]
resource/csdk/security/unittest/oic_unittest_acl1.json
resource/csdk/security/unittest/oic_unittest_default_acl.dat [new file with mode: 0644]
resource/csdk/security/unittest/pstatresource.cpp
resource/csdk/security/unittest/srmtestcommon.cpp
resource/csdk/security/unittest/srmtestcommon.h
resource/csdk/security/unittest/svcresourcetest.cpp
resource/csdk/stack/include/ocpayload.h
resource/csdk/stack/include/octypes.h
resource/csdk/stack/samples/linux/secure/SConscript
resource/csdk/stack/samples/linux/secure/ocamsservice.cpp
resource/csdk/stack/samples/linux/secure/occlientbasicops.cpp
resource/csdk/stack/samples/linux/secure/occlientdirectpairing.cpp
resource/csdk/stack/samples/linux/secure/ocserverbasicops.cpp
resource/csdk/stack/samples/linux/secure/oic_amss_db.dat [new file with mode: 0644]
resource/csdk/stack/samples/linux/secure/oic_svr_db_client.dat [new file with mode: 0644]
resource/csdk/stack/samples/linux/secure/oic_svr_db_client_directpairing.dat [new file with mode: 0644]
resource/csdk/stack/samples/linux/secure/oic_svr_db_client_directpairing.json
resource/csdk/stack/samples/linux/secure/oic_svr_db_server.dat [new file with mode: 0644]
resource/csdk/stack/samples/linux/secure/oic_svr_db_server_justworks.dat [new file with mode: 0644]
resource/csdk/stack/src/ocpayload.c
resource/csdk/stack/src/ocpayloadconvert.c
resource/csdk/stack/src/ocpayloadparse.c
resource/provisioning/examples/SConscript
resource/provisioning/examples/oic_svr_db_client.dat [new file with mode: 0644]
resource/provisioning/examples/provisioningclient.cpp

index f2aed83..f5d2616 100644 (file)
@@ -146,3 +146,5 @@ libocsrm_env.InstallTarget(libocsrm, 'libocsrm')
 if target_os in ['linux', 'android', 'tizen'] and env.get('SECURED') == '1':
        SConscript('provisioning/SConscript')
 
+if target_os in ['linux'] and env.get('SECURED') == '1':
+       SConscript('tool/SConscript')
index 4d5837d..a983f1e 100644 (file)
@@ -1,22 +1,22 @@
- /******************************************************************
-  *
-  * Copyright 2015 Samsung Electronics All Rights Reserved.
-  *
-  *
-  *
-  * Licensed under the Apache License, Version 2.0 (the "License");
-  * you may not use this file except in compliance with the License.
-  * You may obtain a copy of the License at
-  *
-  *     http://www.apache.org/licenses/LICENSE-2.0
-  *
-  * Unless required by applicable law or agreed to in writing, software
-  * distributed under the License is distributed on an "AS IS" BASIS,
-  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-  * See the License for the specific language governing permissions and
-  * limitations under the License.
-  *
-  ******************************************************************/
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #ifndef _IOTVT_B64_H_
 #define _IOTVT_B64_H_
@@ -41,27 +41,27 @@ extern "C" {
 #define B64DECODE_OUT_SAFESIZE(x) (((x)*3)/4)
 
 /**
- * Result code of base64 functions
+ * Result code of base64 functions.
  */
-typedef enum {
+typedef enum
+{
     B64_OK = 0,
     B64_INVALID_PARAM,
     B64_OUTPUT_BUFFER_TOO_SMALL,
     B64_ERROR
-}B64Result;
+} B64Result;
 
 /**
  * Encode the plain message in base64.
  *
- * @param[in] in  Plain message
- * @param[in] inLen  Byte length of 'in'
- * @param[in,out] outBuf Output buffer
- *                Base64 encoded message will be written into 'outBuf'
- *                NOTE : This method adds a NULL to the string configuration
- * @param[in] outBufSize Size of output buffer
- * @param[out] outLen  Byte length of encoded message
+ * @param in is the plain message to be converted.
+ * @param inLen is the byte length of plain message.
+ * @param outBuf is the output buffer containing Base64 encoded message.
+ * @note outBuf adds a NULL to the string configuration.
+ * @param outBufSize is the size of output buffer.
+ * @param outLen is the byte length of encoded message.
  *
- * @return  B64_OK for Success, otherwise some error value
+ * @return ::B64_OK for Success, otherwise some error value.
  */
 B64Result b64Encode(const uint8_t* in, const size_t inLen,
                char* outBuf, const size_t outBufSize, uint32_t *outLen);
@@ -69,14 +69,14 @@ B64Result b64Encode(const uint8_t* in, const size_t inLen,
 /**
  * Decode the encoded message in base64.
  *
- * @param[in] in  Base64 encoded message
- * @param[in] inLen  Byte lenth of 'in'
- * @param[in, out] outBuf  Output buffer
- *                 Base64 decoded message will be written into 'outBuf'
- * @param[in] outBufSize Size of output buffer
- * @param[out] outLen  Byte length of decoded message
+ * @param in is the Base64 encoded message to be converted.
+ * @param inLen is the byte length of the encoded message.
+ * @param outBuf is the output buffer containing decoded message.
+ * @note outBuf adds a NULL to the string configuration.
+ * @param outBufSize is the size of output buffer.
+ * @param outLen is the byte length of decoded message.
  *
- * @return  B64_OK for Success, otherwise some error value
+ * @return ::B64_OK for Success, otherwise some error value.
  */
 B64Result b64Decode(const char* in, const size_t inLen,
                uint8_t* outBuf, size_t outBufSize, uint32_t *outLen);
index ccd97ef..ac4d543 100644 (file)
@@ -28,16 +28,15 @@ extern "C" {
 /**
  * Initialize ACL resource by loading data from persistent storage.
  *
- * @retval  OC_STACK_OK for Success, otherwise some error value
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
 OCStackResult InitACLResource();
 
 /**
  * Perform cleanup for ACL resources.
  *
- * @retval  none
  */
-void DeInitACLResource();
+OCStackResult DeInitACLResource();
 
 /**
  * This method is used by PolicyEngine to retrieve ACL for a Subject.
@@ -46,38 +45,39 @@ void DeInitACLResource();
  * @param savePtr is used internally by @ref GetACLResourceData to maintain index between
  *                successive calls for same subjectId.
  *
- * @retval  reference to @ref OicSecAcl_t if ACL is found, else NULL
+ * @note On the first call to @ref GetACLResourceData, savePtr should point to NULL.
  *
- * @note On the first call to @ref GetACLResourceData, savePtr should point to NULL
+ * @return reference to @ref OicSecAcl_t if ACL is found, else NULL.
  */
 const OicSecAcl_t* GetACLResourceData(const OicUuid_t* subjectId, OicSecAcl_t **savePtr);
 
 /**
- * This function converts ACL data into JSON format.
- * Caller needs to invoke 'free' when done using
- * returned string.
- * @param acl  instance of OicSecAcl_t structure.
+ * This function converts ACL data into CBOR format.
  *
- * @retval  pointer to ACL in json format.
+ * @param acl instance of @ref OicSecAcl_t structure.
+ * @param outPayload is the pointer to allocated memory for cbor payload.
+ * @param size of the cbor payload.
+ *
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
-char* BinToAclJSON(const OicSecAcl_t * acl);
-
+OCStackResult AclToCBORPayload(const OicSecAcl_t * acl, uint8_t **outPayload, size_t *size);
 
 /**
  * This function deletes ACL data.
  *
- * @param acl  instance of OicSecAcl_t structure.
+ * @param acl instance of @ref OicSecAcl_t structure to be deleted.
  */
 void DeleteACLList(OicSecAcl_t* acl);
 
-
 /**
  * This function installs a new ACL.
- * @param newJsonStr JSON string representing a new ACL.
  *
- * @retval  OC_STACK_OK for Success, otherwise some error value
+ * @param payload cbor value representing a new ACL.
+ * @param size of the cbor payload.
+ *
+ * @return ::OC_STACK_OK for Success, otherwise some error value
  */
-OCStackResult InstallNewACL(const char* newJsonStr);
+OCStackResult InstallNewACL(const uint8_t* payload, const size_t size);
 
 /**
  * This function updates default ACL which is required for ownership transfer.
index 9c37a0e..e3dc1fa 100644 (file)
@@ -36,14 +36,12 @@ extern "C" {
 /**
  * Initialize Amacl resource by loading data from persistent storage.
  *
- * @retval  OC_STACK_OK for Success, otherwise some error value
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
 OCStackResult InitAmaclResource();
 
 /**
  * Perform cleanup for Amacl resources.
- *
- * @retval  none
  */
 void DeInitAmaclResource();
 
@@ -52,30 +50,31 @@ void DeInitAmaclResource();
  * If the Amacl is found for the given resource then populate the parameter
  * amsId with Amacl resource amss id.
  *
- * @param resource  resource for which AMS service is required.
- * @param amsId     ID of the ams service for the given resource
- *
- * @retval
- *  OC_STACK_OK     If Amacl found for the resource
- *  OC_STACK_ERROR  If no Amacl found for the resource
+ * @param resource for which AMS service is required.
+ * @param amsId of the ams service for the given resource.
  *
+ * @return ::OC_STACK_OK, if Amacl is found for the resource, else ::OC_STACK_ERROR,
+ *  if no Amacl found for the resource.
  */
 OCStackResult AmaclGetAmsDeviceId(const char *resource, OicUuid_t *amsId);
 
 /**
- * This function converts Amacl data into JSON format.
- * Caller needs to invoke 'free' when done using
- * returned string.
- * @param Amacl  instance of OicSecAmacl_t structure.
+ * This function converts Amacl data into CBOR format.
+ * Caller needs to invoke 'free' when done using returned string.
+ *
+ * @param amacl instance of @ref OicSecAmacl_t structure.
+ * @param cborPayload is the converted cbor value of @ref OicSecAmacl_t structure.
+ * @param cborSize is the size of the cbor payload. This value is the size of the
+ * cborPayload. It should not be NON-NULL value.
  *
- * @retval  pointer to Amacl in json format.
+ * @return ::OC_STACK_OK for Success. ::OC_STACK_INVALID in case of invalid parameters.
+ * ::OC_STACK_ERROR in case of error in converting to cbor.
  */
-char* BinToAmaclJSON(const OicSecAmacl_t * amacl);
+OCStackResult AmaclToCBORPayload(const OicSecAmacl_t *amacl, uint8_t **cborPayload,
+                                 size_t *cborSize);
 
 #ifdef __cplusplus
 }
 #endif
 
 #endif //IOTVT_SRM_AMACLR_H
-
-
index d9d74b5..e07b442 100644 (file)
 #ifndef IOTVT_SRM_AMSMGR_H
 #define IOTVT_SRM_AMSMGR_H
 
+#include <stdlib.h>
+#include <stdint.h>
+
 #include "ocstack.h"
 #include "logger.h"
 #include "policyengine.h"
 #include "securevirtualresourcetypes.h"
 #include "cainterface.h"
-#include <stdlib.h>
-#include <stdint.h>
 
 typedef struct PEContext PEContext_t;
 /**
- * @brief   The AMS context..
+ * The AMS context.
  */
 typedef struct AmsMgrContext
 {
@@ -40,103 +41,95 @@ typedef struct AmsMgrContext
     CARequestInfo_t     *requestInfo;
 } AmsMgrContext_t;
 
-
 /**
- * @brief This method updates AmsMgr context's endpoint & requestInfo
+ * This method updates AmsMgr context's endpoint & requestInfo.
  *
- * @param context          Policy engine context.
- * @param endpoint         CA Endpoint info of the requester
- * @param requestInfo      CA RequestInfo of the requester
+ * @param context is the policy engine context.
+ * @param endpoint is the CA Endpoint info of the requester.
+ * @param requestInfo is the CA RequestInfo of the requester.
+ *
+ * @return ::OC_STACK_OK if successful, else other value in case of error.
  */
-OCStackResult UpdateAmsMgrContext(PEContext_t *context, const CAEndpoint_t *endpoint,
-                       const CARequestInfo_t *requestInfo);
+OCStackResult UpdateAmsMgrContext(PEContext_t *context,
+                                  const CAEndpoint_t *endpoint,
+                                  const CARequestInfo_t *requestInfo);
 
 /**
- *
  * This method is called by PolicyEngine to Discover AMS service.
  * It sends muticast discovery request such as
  * /oic/sec/doxm?deviceid="AMSSrvcDeviceID" to discover AMS service
- * with deviceId="AMSSrvcDeviceID"
- *
- * @param context   Policy engine context.
+ * with deviceId="AMSSrvcDeviceID".
  *
- * @retval
- *  OC_STACK_OK     If able to successfully send multicast discovery request.
- *  OC_STACK_ERROR  If unable to successfully send multicast discovery request due to error.
+ * @param context is the policy engine context.
  *
+ * @return ::OC_STACK_OK,If able to successfully send multicast discovery request.
+ * else ::OC_STACK_ERROR, If unable to successfully send multicast discovery request
+ * due to error.
  */
 OCStackResult DiscoverAmsService(PEContext_t *context);
 
-
 /**
- *
  * This method sends unicast request to retrieve the secured port info of the
  * discovered AMS service. It sends unicast discovery request such as
- * /oic/res?rt="oic.sec.doxm" to the discovered AMS service
+ * /oic/res?rt="oic.sec.doxm" to the discovered AMS service.
  *
- * @param context   Policy engine context.
- *
- * @retval
- *  OC_STACK_OK     If able to successfully send unicast discovery request
- *  OC_STACK_ERROR  If unable to successfully send unicast discovery request due to error
+ * @param context is the policy engine context.
  *
+ * @return ::OC_STACK_OK,If able to successfully send unicast discovery request.
+ * else ::OC_STACK_ERROR, If unable to successfully send unicast discovery request
+ * due to error.
  */
-OCStackResult SendUnicastSecurePortDiscovery(PEContext_t *context,OCDevAddr *devAddr,
-                                      OCConnectivityType connType);
-
+OCStackResult SendUnicastSecurePortDiscovery(PEContext_t *context,
+                                             OCDevAddr *devAddr,
+                                             OCConnectivityType connType);
 
 /**
- *
  * This method sends unicast request to AMS service to get ACL for
  * the Subject and/or Resource. It sends unicast request such as
  * /oic/sec/acl?sub="subjectId";rsrc="/a/led" to get the ACL for
- * the subject & resource
+ * the subject & resource.
  *
- * @param context   Policy engine context.
+ * @param context is the policy engine context.
  *
- * @retval
- *  OC_STACK_OK     If able to successfully send unicast ACL request
- *  OC_STACK_ERROR  If unable to successfully send unicast ACL request due to error
+ * @return ::OC_STACK_OK, If able to successfully send unicast ACL request.
+ * ::OC_STACK_ERROR, If unable to successfully send unicast ACL request due to error.
  *
  */
-OCStackResult SendAclReq(PEContext_t *context, OCDevAddr *devAddr, OCConnectivityType connType,
-        uint16_t securedPort);
-
+OCStackResult SendAclReq(PEContext_t *context,
+                         OCDevAddr *devAddr,
+                         OCConnectivityType connType,
+                         uint16_t securedPort);
 
 /*
- * Cleanup CARequestInfo_t object
- * @param requestInfo        pointer to RequestInfo_t object
+ * Cleanup CARequestInfo_t object.
+ *
+ * @param requestInfo is the pointer to @ref CARequestInfo_t.
  */
 void FreeCARequestInfo(CARequestInfo_t *requestInfo);
 
-
 /*
  * This method is used by Policy engine to checks Amacl resource.
  * If Amacl is found then it fills up context->amsMgrContext->amsDeviceId
  * with amsID of the Amacl else leaves it empty.
  *
- * @param context   Policy engine context.
+ * @param context is the policy engine context.
  *
- * @return          true if AMacl for the resource is found
- *                  false if AMacl for the resource is not found
+ * @return true, if Amacl for the resource is found. false, if Amacl for the
+ * resource is not found
  */
 bool FoundAmaclForRequest(PEContext_t *context);
 
-
 /*
- * This method is used by Policy engine to process AMS request
- *
- * @param context   Policy engine context.
+ * This method is used by Policy engine to process AMS request.
  *
+ * @param context is the policy engine context.
  */
 void ProcessAMSRequest(PEContext_t *context);
 
-
 /*
- * This method is used by Policy engine to free AMS context requestInfo
- *
- * @param requestInfo   pointer to CARequestInfo_t.
+ * This method is used by Policy engine to free AMS context requestInfo/
  *
+ * @param requestInfo is the pointer to @ref CARequestInfo_t.
  */
 void FreeCARequestInfo(CARequestInfo_t *requestInfo);
 
index 74ea373..1d7e2d4 100644 (file)
@@ -32,45 +32,42 @@ extern "C" {
 /**
  * Initialize credential resource by loading data from persistent storage.
  *
- * @retval
- *     OC_STACK_OK    - no errors
- *     OC_STACK_ERROR - stack process error
+ * @return ::OC_STACK_OK, if initialization is successful, else ::OC_STACK_ERROR if
+ * initialization fails.
  */
 OCStackResult InitCredResource();
 
 /**
  * Perform cleanup for credential resources.
  *
- * @retval
- *     OC_STACK_OK              - no errors
- *     OC_STACK_ERROR           - stack process error
- *     OC_STACK_NO_RESOURCE     - resource not found
- *     OC_STACK_INVALID_PARAM   - invalid param
+ * @return ::OC_STACK_OK, if no errors. ::OC_STACK_ERROR, if stack process error.
+ * ::OC_STACK_NO_RESOURCE, if resource not found.
+ * ::OC_STACK_INVALID_PARAM, if invalid param.
  */
 OCStackResult DeInitCredResource();
 
 /**
- * This method is used by tinydtls/SRM to retrieve credential for given Subject.
+ * This method is used by tinydtls/SRM to retrieve credential for given subject.
  *
- * @param subject - subject for which credential is required.
+ * @param subjectId for which credential is required.
  *
- * @retval
- *     reference to OicSecCred_t - if credential is found
- *     NULL                      - if credential not found
+ * @return reference to @ref OicSecCred_t, if credential is found, else NULL, if credential
+ * not found.
  */
 const OicSecCred_t* GetCredResourceData(const OicUuid_t* subjectId);
 
 /**
- * This function converts credential data into JSON format.
- * Caller needs to invoke 'free' when done using
- * returned string.
- * @param cred  pointer to instance of OicSecCred_t structure.
- *
- * @retval
- *      pointer to JSON credential representation - if credential for subjectId found
- *      NULL                                      - if credential for subjectId not found
+ * This function converts credential data into CBOR format.
+ * Caller needs to invoke 'free' when done using returned string.
+ *
+ * @param cred is the pointer to instance of OicSecCred_t structure.
+ * @param cborPayload is the CBOR converted value.
+ * @param cborSize is the size of the CBOR.
+ *
+ * @return ::OC_STACK_OK if conversion is successful, else ::OC_STACK_ERROR if unsuccessful.
  */
-char* BinToCredJSON(const OicSecCred_t* cred);
+OCStackResult CredToCBORPayload(const OicSecCred_t* cred, uint8_t **cborPayload,
+                                size_t *cborSize);
 
 /**
  * This function generates the bin credential data.
@@ -82,53 +79,42 @@ char* BinToCredJSON(const OicSecCred_t* cred);
  * @param ownersLen length of owners array
  * @param owners array of owners.
  *
- * @retval
- *      pointer to instance of OicSecCred_t  - success
- *      NULL                                 - error
+ * @return pointer to instance of @ref OicSecCred_t if successful. else NULL in case of error.
+
  */
 OicSecCred_t * GenerateCredential(const OicUuid_t* subject, OicSecCredType_t credType,
-                     const char * publicData, const char * privateData, size_t ownersLen,
-                     const OicUuid_t * owners);
+                     const OicSecCert_t * publicData, const OicSecKey_t * privateData,
+                     size_t ownersLen, const OicUuid_t * owners);
 
 /**
  * This function adds the new cred to the credential list.
  *
- * @param cred pointer to new credential.
+ * @param cred is the pointer to new credential.
  *
- * @retval
- *      OC_STACK_OK     - cred not NULL and persistent storage gets updated
- *      OC_STACK_ERROR  - cred is NULL or fails to update persistent storage
+ * @return ::OC_STACK_OK, cred not NULL and persistent storage gets updated.
+ * ::OC_STACK_ERROR, cred is NULL or fails to update persistent storage.
  */
 OCStackResult AddCredential(OicSecCred_t * cred);
 
 /**
  * Function to remove the credential from SVR DB.
  *
- * @param credId Credential ID to be deleted.
+ * @param credId is the Credential ID to be deleted.
  *
- * @return OC_STACK_OK for success and errorcode otherwise.
+ * @return ::OC_STACK_OK for success, or errorcode otherwise.
  */
-OCStackResult RemoveCredential(const OicUuid_t* credId);
-
-/**
- * Remove all credential data on credential resource and persistent storage
- *
- * @retval
- *     OC_STACK_OK              - no errors
- *     OC_STACK_ERROR           - stack process error
- */
-OCStackResult RemoveAllCredentials(void);
+OCStackResult RemoveCredential(const OicUuid_t *credId);
 
 #if defined(__WITH_DTLS__)
 /**
  * This internal callback is used by lower stack (i.e. CA layer) to
  * retrieve PSK credentials from RI security layer.
  *
- * @param[in]  type type of PSK data required by CA layer during DTLS handshake.
- * @param[in]  desc Additional request information.
- * @param[in]  desc_len The actual length of desc.
- * @param[out] result  Must be filled with the requested information.
- * @param[in]  result_length  Maximum size of @p result.
+ * @param type of PSK data required by CA layer during DTLS handshake.
+ * @param desc Additional request information.
+ * @param desc_len is the actual length of desc.
+ * @param result  is must be filled with the requested information.
+ * @param result_length is the maximum size of @p result.
  *
  * @return The number of bytes written to @p result or a value
  *         less than zero on error.
@@ -138,21 +124,22 @@ int32_t GetDtlsPskCredentials( CADtlsPskCredType_t type,
               unsigned char *result, size_t result_length);
 
 /**
- * Add temporal PSK to PIN based OxM
+ * Add temporal PSK to PIN based OxM.
  *
- * @param[in] tmpSubject UUID of target device
- * @param[in] credType Type of credential to be added
- * @param[in] pin numeric characters
- * @param[in] pinSize length of 'pin'
- * @param[in] ownersLen Number of owners
- * @param[in] owners Array of owners
- * @param[out] tmpCredSubject Generated credential's subject.
+ * @param tmpSubject is the UUID of target device
+ * @param credType is the type of credential to be added
+ * @param pin is the numeric characters
+ * @param pinSize is the length of 'pin'
+ * @param ownersLen is the number of owners
+ * @param owners is the array of owners
+ * @param tmpCredSubject is the generated credential's subject.
  *
- * @return OC_STACK_OK for success and errorcode otherwise.
+ * @return ::OC_STACK_OK for success or else errorcode.
  */
 OCStackResult AddTmpPskWithPIN(const OicUuid_t* tmpSubject, OicSecCredType_t credType,
                             const char * pin, size_t pinSize,
-                            size_t ownersLen, const OicUuid_t * owners, OicUuid_t* tmpCredSubject);
+                            size_t ownersLen, const OicUuid_t * owners,
+                            OicUuid_t* tmpCredSubject);
 
 #endif /* __WITH_DTLS__ */
 
@@ -160,18 +147,17 @@ OCStackResult AddTmpPskWithPIN(const OicUuid_t* tmpSubject, OicSecCredType_t cre
 /**
  * This function is used toretrieve certificate credentials from RI security layer.
  *
- * @param credInfo
- *     binary structure containing certificate credentials
+ * @param credInfo is the binary structure containing certificate credentials
  *
- * @retval 0  on scuccess
+ * @return 0 on success.
  */
 int GetDtlsX509Credentials(CADtlsX509Creds_t *credInfo);
 #endif /*__WITH_X509__*/
 
 /**
- * Function to deallocate allocated memory to OicSecCred_t
+ * Function to deallocate allocated memory to OicSecCred_t.
  *
- * @param cred pointer to cred type
+ * @param cred pointer to cred type.
  *
  */
 void DeleteCredList(OicSecCred_t* cred);
@@ -181,5 +167,3 @@ void DeleteCredList(OicSecCred_t* cred);
 #endif
 
 #endif //IOTVT_SRM_CREDR_H
-
-
index 75178d8..454bec7 100644 (file)
@@ -29,43 +29,62 @@ extern "C" {
 #endif
 
 /**
- * This function stores CRL in SRM
- * @param crl - CRL
+ * This function stores CRL in SRM.
  *
- * @returns OC_STACK_OK for Success, otherwise some error value
+ * @param crl to be stored in SRM.
+ *
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
 OCStackResult UpdateCRLResource(const OicSecCrl_t *crl);
 
 /**
- * This function get encoded with base64 CRL from SRM
+ * This function get encoded with base64 CRL from SRM.
+ *
+ * @note Caller responsible for resulting string memory (use OICFree to remove it).
  *
- * @returns encoded CRL with base64 format. NULL if error occured (e.g. CRL did not set)
- * @note Caller responsible for resulting string memory (use OICFree to remove it)
+ * @return NULL if error occured (e.g. CRL did not set).
  */
-char* GetBase64CRL();
+uint8_t* GetCrl();
+
 /**
- * This function get encoded with DER CRL from SRM
+ * This function get encoded with DER CRL from SRM.
  *
- * @returns encoded CRL with DER format. array len is 0 if error occured (e.g. CRL did not set)
+ * @return encoded CRL with DER format. array len is 0 if error occured (e.g. CRL did not set).
  */
 void  GetDerCrl(ByteArray crlArray);
 
 /**
- * This function get CRL from SRM
+ * This function converts CRL to CBOR
  *
- * @param crl [out] - pointer to buffer that contains crl. Shoul be not NULL. Buffer
+ * @param crl is a pointer to buffer that contains crl. Shoul be not NULL. Buffer
  * will be allocated by the function and content of *crl will be ignored.
- * @param outlen [out] - pointer to length of the CRL buffer. Shoul be not NULL.
+ * @param payload is the converted cbor value.
+ * @param size is a pointer to length of the CRL buffer. Should be not NULL.
+ *
+ * @note Caller responsible for crl buffer memory (use OICFree to free it).
  *
- * @returns OC_STACK_OK if success and errorcode otherwise.
- * @note Caller responsible for crl buffer memory (use OICFree to free it)
+ * @return ::OC_STACK_OK if success, otherwise some error value.
  */
-OicSecCrl_t * JSONToCrlBin(const char * jsonStr);
+OCStackResult CrlToCBORPayload(const OicSecCrl_t *crl, uint8_t **payload, size_t *size);
 
 /**
- * Initialize CLR resource by loading data from persistent storage.
+ * This function converts CBOR to CRL
  *
- * @returns OC_STACK_OK for Success, otherwise some error value
+ * will be allocated by the function and content of *crl will be ignored.
+ * @param cborPayload is the cbor vlaue
+ * @param size is a pointer to length of the CRL buffer. Should be not NULL.
+ * @param crl is a pointer to buffer that contains crl. Shoul be not NULL. Buffer
+ *
+ * @note Caller responsible for crl buffer memory (use OICFree to free it).
+ *
+ * @return ::OC_STACK_OK if success, otherwise some error value.
+ */
+OCStackResult CBORPayloadToCrl(const uint8_t *cborPayload, const size_t size,
+                               OicSecCrl_t **secCrl);
+/**
+ * Initialize CRL resource by loading data from persistent storage.
+ *
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
 OCStackResult InitCRLResource();
 
@@ -74,15 +93,15 @@ OCStackResult InitCRLResource();
  */
 void DeInitCRLResource();
 
+/**
+ * Get an instance of CRL resource.
+ *
+ * @return reference to the @ref OicSecCrl_t, holding reference to CRL resource.
+ */
 OicSecCrl_t *GetCRLResource();
 
-OCEntityHandlerResult CRLEntityHandler(OCEntityHandlerFlag flag,
-                                        OCEntityHandlerRequest * ehRequest,
-                                        void* callbackParameter);
 #ifdef __cplusplus
 }
 #endif
 
 #endif //IOTVT_SRM_CRLR_H
-
-
index 237da64..e9ce684 100644 (file)
@@ -30,67 +30,71 @@ extern "C" {
 /**
  * Initialize DOXM resource by loading data from persistent storage.
  *
- * @retval  OC_STACK_OK for Success, otherwise some error value
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
 OCStackResult InitDoxmResource();
 
 /**
  * Perform cleanup for DOXM resources.
  *
- * @retval  OC_STACK_OK for Success, otherwise some error value
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
 OCStackResult DeInitDoxmResource();
 
 /**
  * This method is used by SRM to retrieve DOXM resource data..
  *
- * @retval  reference to @ref OicSecDoxm_t, binary format of Doxm resource data
+ * @return reference to @ref OicSecDoxm_t, binary format of Doxm resource data.
  */
 const OicSecDoxm_t* GetDoxmResourceData();
 
 /**
- * This method converts JSON DOXM into binary DOXM.
- * The JSON DOXM can be from persistent database or
+ * This method converts CBOR DOXM into binary DOXM.
+ * The CBOR DOXM can be from persistent database or
  * or received as PUT/POST request.
  *
- * @param[in] jsonStr  doxm data in json string.
- * @return pointer to OicSecDoxm_t.
+ * @param cborPayload is a doxm data in cbor.
+ * @note Caller needs to invoke OCFree after done using the return pointer.
+ * @param doxm is the pointer to @ref OicSecDoxm_t.
+ * @param size of the cborPayload. In case value is 0, CBOR_SIZE value is assigned.
  *
- * @note Caller needs to invoke OCFree after done
- *       using the return pointer
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
-OicSecDoxm_t * JSONToDoxmBin(const char * jsonStr);
+OCStackResult CBORPayloadToDoxm(const uint8_t *cborPayload, size_t size,
+                                OicSecDoxm_t **doxm);
 
 /**
- * This method converts DOXM data into JSON format.
+ * This method converts DOXM data into CBOR format.
  * Caller needs to invoke 'free' when finished done using
- * return string
+ * return string.
  *
- * @param[in] doxm  Pointer to OicSecDoxm_t.
- * @return pointer to json string.
+ * @param doxm Pointer to @ref OicSecDoxm_t.
+ * @note Caller needs to invoke OCFree after done using the return pointer.
+ * @param cborPayload is the payload of the cbor.
+ * @param cborSize is the size of the cbor payload. Passed parameter should not be NULL.
  *
- * @note Caller needs to invoke OCFree after done
- *       using the return pointer
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
-char * BinToDoxmJSON(const OicSecDoxm_t * doxm);
+OCStackResult DoxmToCBORPayload(const OicSecDoxm_t * doxm, uint8_t **cborPayload,
+                                size_t *cborSize);
 
 /**
  * This method returns the SRM device ID for this device.
  *
- * @retval  OC_STACK_OK for Success, otherwise some error value
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
 OCStackResult GetDoxmDeviceID(OicUuid_t *deviceID);
 
 /**
- * @brief Gets the OicUuid_t value for the owner of this device.
+ * Gets the OicUuid_t value for the owner of this device.
  *
- * @return OC_STACK_OK if devOwner is a valid UUID, otherwise OC_STACK_ERROR.
+ * @return ::OC_STACK_OK if devOwner is a valid UUID, otherwise ::OC_STACK_ERROR.
  */
 OCStackResult GetDoxmDevOwnerId(OicUuid_t *devOwner);
 
 /** This function deallocates the memory for OicSecDoxm_t .
  *
- * @param[in] doxm  Pointer to OicSecDoxm_t.
+ * @param doxm is the pointer to @ref OicSecDoxm_t.
  */
 void DeleteDoxmBinData(OicSecDoxm_t* doxm);
 
@@ -105,5 +109,3 @@ void RestoreDoxmToInitState();
 #endif
 
 #endif //IOTVT_SRM_DOXMR_H
-
-
index dbb5ce9..1d2d363 100644 (file)
@@ -42,30 +42,33 @@ OCStackResult InitDpairingResource();
 OCStackResult DeInitDpairingResource();\r
 \r
 /**\r
- * This method converts JSON DPAIRING into binary DPAIRING.\r
- * The JSON DPAIRING can be from persistent database or\r
+ * This method converts CBOR DPAIRING into binary DPAIRING.\r
+ * The CBOR DPAIRING can be from persistent database or\r
  * or received as POST request.\r
  *\r
- * @param[in] jsonStr  pconf data in json string.\r
- * @return pointer to OicSecDpairing_t.\r
+ * @param cborPayload pconf data in cbor format.\r
+ * @param size size of the cbor payload\r
+ * @param secDpair binary Dpairing resource\r
+ * @return OC_STACK_OK for Success, otherwise some error value.\r
  *\r
- * @note Caller needs to invoke OCFree after done\r
+ * @note Caller needs to invoke OICFree after done\r
  *       using the return pointer\r
  */\r
-OicSecDpairing_t * JSONToDpairingBin(const char * jsonStr);\r
+OCStackResult CBORPayloadToDpair(const uint8_t *cborPayload, size_t size,\r
+        OicSecDpairing_t **secDpair);\r
 \r
 /**\r
- * This method converts DPAIRING data into JSON format.\r
- * Caller needs to invoke 'free' when finished done using\r
- * return string\r
+ * This method converts DPAIRING data into CBOR format.\r
  *\r
- * @param[in] dpair  Pointer to OicSecDpairing_t.\r
- * @return pointer to json string.\r
+ * @param dpair  Pointer to OicSecDpairing_t.\r
+ * @param payload CBOR format converted from binary dpairing\r
+ * @param size Size of the coverted payload\r
+ * @return OC_STACK_OK for Success, otherwise some error value.\r
  *\r
- * @note Caller needs to invoke OCFree after done\r
+ * @note Caller needs to invoke OICFree after done\r
  *       using the return pointer\r
  */\r
-char * BinToDpairingJSON(const OicSecDpairing_t * dpair);\r
+OCStackResult DpairingToCBORPayload(const OicSecDpairing_t *dpair, uint8_t **payload, size_t *size);\r
 \r
 /** This function deallocates the memory for OicSecPconf_t .\r
  *\r
index 70366ac..b48bd1e 100644 (file)
@@ -49,30 +49,34 @@ OCStackResult DeInitPconfResource();
 const OicSecPconf_t* GetPconfResourceData();\r
 \r
 /**\r
- * This method converts JSON PCONF into binary PCONF.\r
+ * This method converts CBOR PCONF into binary PCONF.\r
  * The JSON PCONF can be from persistent database or\r
  * or received as PUT request.\r
  *\r
- * @param[in] jsonStr  pconf data in json string.\r
- * @return pointer to OicSecPconf_t.\r
+ * @param cborPayload  pconf data in cbor format.\r
+ * @param size cbor payload size\r
+ * @param secPconf converted pconf\r
+ * @return OC_STACK_OK for success.\r
  *\r
  * @note Caller needs to invoke OCFree after done\r
  *       using the return pointer\r
  */\r
-OicSecPconf_t * JSONToPconfBin(const char * jsonStr);\r
+OCStackResult CBORPayloadToPconf(const uint8_t *cborPayload, size_t size, OicSecPconf_t **secPconf);\r
 \r
 /**\r
- * This method converts PCONF data into JSON format.\r
+ * This method converts PCONF data into CBOR format.\r
  * Caller needs to invoke 'free' when finished done using\r
  * return string\r
  *\r
- * @param[in] pconf  Pointer to OicSecPconf_t.\r
- * @return pointer to json string.\r
+ * @param pconf  Pointer to OicSecPconf_t.\r
+ * @param payload pconf converted in cbor format\r
+ * @param size size of the converted payload\r
+ * @return OC_STACK_OK for success.\r
  *\r
  * @note Caller needs to invoke OCFree after done\r
  *       using the return pointer\r
  */\r
-char * BinToPconfJSON(const OicSecPconf_t * pconf);\r
+OCStackResult PconfToCBORPayload(const OicSecPconf_t *pconf,uint8_t **payload,size_t *size);\r
 \r
 /**\r
  * This method might be used to add a paired device id after direct-pairing process complete.\r
index ba40d68..72aa01c 100644 (file)
@@ -31,7 +31,6 @@
 
 typedef struct AmsMgrContext AmsMgrContext_t;
 
-
 typedef enum PEState
 {
     STOPPED = 0,              //Policy engine state machine is not running
@@ -40,7 +39,6 @@ typedef enum PEState
     BUSY                      //Can't process new request as processing other requests
 } PEState_t;
 
-
 typedef struct PEContext
 {
     PEState_t   state;
@@ -56,13 +54,12 @@ typedef struct PEContext
 /**
  * Check whether a request should be allowed.
  *
- * @param   context     Pointer to Policy Engine context to use.
- * @param   subjectId   Pointer to Id of the requesting entity.
- * @param   resource    Pointer to URI of Resource being requested.
- * @param   permission  Requested permission.
+ * @param context is the pointer to Policy Engine context to use.
+ * @param subjectId is the pointer to Id of the requesting entity.
+ * @param resource is the pointer to URI of Resource being requested.
+ * @param permission is the requested permission.
  *
- * @return  ACCESS_GRANTED if request should go through,
- *          otherwise some flavor of ACCESS_DENIED
+ * @return ::ACCESS_GRANTED if request should go through, otherwise some flavor of ACCESS_DENIED.
  */
 SRMAccessResponse_t CheckPermission(
     PEContext_t     *context,
@@ -74,33 +71,35 @@ SRMAccessResponse_t CheckPermission(
  * Initialize the Policy Engine. Call this before calling CheckPermission().
  * TODO Eventually this and DeInit() need to be called from a new
  *      "SRMInit(SRMContext_t *)" function, TBD after BeachHead.
- * @param   context     Pointer to Policy Engine context to initialize.
- * @return  OC_STACK_OK for Success, otherwise some error value
+ * @param context is the pointer to Policy Engine context to initialize.
+ *
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
 OCStackResult InitPolicyEngine(PEContext_t *context);
 
 /**
  * De-Initialize the Policy Engine. Call this before exiting to allow Policy
  * Engine to do cleanup on context.
- * @param   context     Pointer to Policy Engine context to de-initialize.
- * @return  none
+ *
+ * @param context is the pointer to Policy Engine context to de-initialize.
  */
 void DeInitPolicyEngine(PEContext_t *context);
 
 /**
- * Return the uint16_t CRUDN permission corresponding to passed CAMethod_t.
+ * Get CRUDN permission for a method.
+ *
+ * @param method is CRUDN permission being seeked.
+ *
+ * @return the uint16_t CRUDN permission .
  */
 uint16_t GetPermissionFromCAMethod_t(const CAMethod_t method);
 
-
 /*
  * This method reset Policy Engine context to default state and update
  * it's state to @param state.
  *
- * @param context  Policy engine context.
- * @param state    Set Policy engine state to this.
- *
- * @return         none
+ * @param context is the policy engine context.
+ * @param state set Policy engine state to this.
  */
 void SetPolicyEngineState(PEContext_t *context, const PEState_t state);
 
index b48c674..34a7822 100644 (file)
@@ -21,6 +21,8 @@
 #ifndef IOTVT_SRM_PSI_H
 #define IOTVT_SRM_PSI_H
 
+#include "cJSON.h"
+
 /**
  * Reads the Secure Virtual Database from PS into dynamically allocated
  * memory buffer.
@@ -28,7 +30,7 @@
  * @note Caller of this method MUST use OCFree() method to release memory
  *       referenced by return value.
  *
- * @retval  reference to memory buffer containing SVR database.
+ * @return char * reference to memory buffer containing SVR database.
  */
 char * GetSVRDatabase();
 
@@ -39,8 +41,34 @@ char * GetSVRDatabase();
  * @param rsrcName string denoting the SVR name ("acl", "cred", "pstat" etc).
  * @param jsonObj JSON object containing the SVR contents.
  *
- * @retval  OC_STACK_OK for Success, otherwise some error value
+ * @return ::OC_STACK_OK for Success, otherwise some error value
  */
 OCStackResult UpdateSVRDatabase(const char* rsrcName, cJSON* jsonObj);
 
+/**
+ * Reads the Secure Virtual Database from PS
+ *
+ * @note Caller of this method MUST use OCFree() method to release memory
+ *       referenced by return value.
+ *
+ * @param rsrcName is the name of the field for which file content are read.
+                   if the value is NULL it will send the content of the whole file.
+ * @param data is the pointer to the file contents read from the database.
+ * @param size is the size to the file contents read.
+ *
+ * @return ::OC_STACK_OK for Success, otherwise some error value
+ */
+OCStackResult GetSecureVirtualDatabaseFromPS(const char *rsrcName, uint8_t **data, size_t *size);
+
+/**
+ * This method converts updates the persistent storage.
+ *
+ * @param rsrcName is the name of the secure resource that will be updated.
+ * @param cborPayload is the pointer holding cbor payload.
+ * @param cborPayload is the size of the cbor payload.
+ *
+ * @return ::OC_STACK_OK for Success, otherwise some error value
+ */
+OCStackResult UpdateSecureResourceInPS(const char* rsrcName, uint8_t* cborPayload, size_t size);
+
 #endif //IOTVT_SRM_PSI_H
index 3134788..facab4e 100644 (file)
@@ -28,36 +28,45 @@ extern "C" {
 /**
  * Initialize Pstat resource by loading data from persistent storage.
  *
- * @retval  OC_STACK_OK for Success, otherwise some error value
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
 OCStackResult InitPstatResource();
 
 /**
  * Perform cleanup for Pstat resources.
  *
- * @retval  OC_STACK_OK for Success, otherwise some error value
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
 OCStackResult DeInitPstatResource();
 
 /**
- * This method converts JSON PSTAT into binary PSTAT.
+ * This method converts PSTAT into the cbor payload.
  *
- * @param[in] jsonStr  pstat data in json string.
- * @return pointer to OicSecPstat_t.
+ * @param pstat pointer to the initialized pstat structure.
+ * @param cborPayload pointer to pstat cbor payload.
+ * @param size of the cbor payload converted. It is 0 in case of error,
+ * else a positive value if succcessful.
+ *
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
-OicSecPstat_t * JSONToPstatBin(const char * jsonStr);
+ OCStackResult PstatToCBORPayload(const OicSecPstat_t *pstat, uint8_t **cborPayload,
+                                  size_t *cborSize);
 
 /**
- * This method converts pstat data into JSON format.
+ * This method converts cbor into PSTAT data.
  *
- * @param[in] pstat  pstat data in binary format.
- * @return pointer to pstat json string.
+ * @param cborPayload is the pstat data in cbor format.
+ * @param size of the cborPayload. In case 0 is provided it assigns CBOR_SIZE (255) value.
+ * @param pstat pointer to @ref OicSecPstat_t.
+  *
+  * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
-char * BinToPstatJSON(const OicSecPstat_t * pstat);
+ OCStackResult CBORPayloadToPstat(const uint8_t *cborPayload, const size_t cborSize,
+                                  OicSecPstat_t **pstat);
 
 /** This function deallocates the memory for OicSecPstat_t.
  *
- * @param[in] pstat  Pointer to OicSecPstat_t.
+ * @param pstat is the pointer to @ref OicSecPstat_t.
  */
 void DeletePstatBinData(OicSecPstat_t* pstat);
 
@@ -72,5 +81,3 @@ void RestorePstatToInitState();
 #endif
 
 #endif //IOTVT_SRM_PSTATR_H
-
-
index 3e946f5..0bcb606 100644 (file)
 /**
  * Initialize all secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
  *
- * @retval  OC_STACK_OK for Success, otherwise some error value
+ * @return ::OC_STACK_OK for Success, otherwise some error value
  */
 OCStackResult InitSecureResources();
 
 /**
  * Perform cleanup for secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
  *
- * @retval  OC_STACK_OK for Success, otherwise some error value
+ * @return ::OC_STACK_OK for Success, otherwise some error value
  */
 OCStackResult DestroySecureResources();
 
@@ -44,13 +44,12 @@ OCStackResult DestroySecureResources();
  *
  * @param ehRequest pointer to entity handler request data structure.
  * @param ehRet result code from entity handler.
- * @param rspPayload response payload in JSON.
+ * @param cborPayload response payload.
  *
- * @retval  OC_STACK_OK for Success, otherwise some error value
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
-OCStackResult SendSRMResponse(const OCEntityHandlerRequest *ehRequest,
-        OCEntityHandlerResult ehRet, const char *rspPayload);
+OCStackResult SendSRMCBORResponse(const OCEntityHandlerRequest *ehRequest,
+        OCEntityHandlerResult ehRet, uint8_t *cborPayload, size_t size);
 
 #endif //IOTVT_SRM_RM_H
 
-
index eb2643b..51f6a3f 100644 (file)
@@ -28,85 +28,85 @@ extern "C" {
 #endif
 
 /**
- * @brief   Register Persistent storage callback.
- * @param   persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
- * @return
- *     OC_STACK_OK    - No errors; Success
- *     OC_STACK_INVALID_PARAM - Invalid parameter
+ * Register Persistent storage callback.
+ *
+ * @param  persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
+ *
+ * @return ::OC_STACK_OK  is no errors and successful. ::OC_STACK_INVALID_PARAM for invalid parameter.
  */
 OCStackResult SRMRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler);
 
 /**
- * @brief   Get Persistent storage handler pointer.
- * @return
- *     The pointer to Persistent Storage callback handler
+ * Get Persistent storage handler pointer.
+ *
+ * @return The pointer to Persistent Storage callback handler.
  */
 OCPersistentStorage* SRMGetPersistentStorageHandler();
 
 /**
- * @brief   Register request and response callbacks.
- *          Requests and responses are delivered in these callbacks.
- * @param   reqHandler   [IN] Request handler callback ( for GET,PUT ..etc)
- * @param   respHandler  [IN] Response handler callback.
- * @param   errHandler   [IN] Error handler callback.
- * @return
- *     OC_STACK_OK    - No errors; Success
- *     OC_STACK_INVALID_PARAM - Invalid parameter
+ * Register request and response callbacks. Requests and responses are delivered in these callbacks.
+ *
+ * @param reqHandler Request handler callback ( for GET,PUT ..etc)
+ * @param respHandler Response handler callback.
+ * @param errHandler Error handler callback.
+ *
+ * @return ::OC_STACK_OK  is no errors and successful. ::OC_STACK_INVALID_PARAM for invalid parameter.
  */
 OCStackResult SRMRegisterHandler(CARequestCallback reqHandler,
                                  CAResponseCallback respHandler,
                                  CAErrorCallback errHandler);
 
 /**
- * @brief   Initialize all secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
- * @return  OC_STACK_OK for Success, otherwise some error value
+ * Initialize all secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
+ * @return  ::OC_STACK_OK for Success, otherwise some error value.
  */
 OCStackResult SRMInitSecureResources();
 
 /**
- * @brief   Perform cleanup for secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
- * @return  none
+ * Perform cleanup for secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
  */
 void SRMDeInitSecureResources();
 
 /**
- * @brief   Initialize Policy Engine context.
- * @return  OC_STACK_OK for Success, otherwise some error value.
+ * Initialize Policy Engine context.
+ *
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
 OCStackResult SRMInitPolicyEngine();
 
 /**
- * @brief   Cleanup Policy Engine context.
- * @return  none
+ * Cleanup Policy Engine context.
  */
 void SRMDeInitPolicyEngine();
 
 /**
- * @brief   Provisioning API response callback.
- * @param object[IN]       endpoint instance.
- * @param responseInfo[IN] instance of CAResponseInfo_t structure.
+ * Provisioning API response callback.
+ *
+ * @param object endpoint instance.
+ * @param responseInfo instance of CAResponseInfo_t structure.
+ *
  * @return true if received response is for provisioning API false otherwise.
  */
 typedef bool (*SPResponseCallback) (const CAEndpoint_t *object,
                                     const CAResponseInfo_t *responseInfo);
 
 /**
- * @brief function to register provisoning API's response callback.
+ * Function to register provisoning API's response callback.
+ *
  * @param respHandler response handler callback.
  */
 void SRMRegisterProvisioningResponseHandler(SPResponseCallback respHandler);
 
 /**
- * @brief   Check the security resource URI.
- * @param   uri [IN] Pointers to security resource URI.
- * @return  true if the URI is one of security resources, otherwise false.
+ * Check the security resource URI.
+ * @param uri Pointers to security resource URI.
+ * @return true if the URI is one of security resources, otherwise false.
  */
 bool SRMIsSecurityResourceURI(const char* uri);
 
 /**
- * @brief   Sends Response
- * @param   resposeVal       SRMAccessResponse_t value
- * @return  NONE
+ * Sends Response
+ * @param resposeVal Response @ref SRMAccessResponse_t value.
  */
 void SRMSendResponse(SRMAccessResponse_t responseVal);
 
diff --git a/resource/csdk/security/include/internal/security_internals.h b/resource/csdk/security/include/internal/security_internals.h
new file mode 100644 (file)
index 0000000..ba41586
--- /dev/null
@@ -0,0 +1,116 @@
+#ifndef IOTVT_SRM_SECURITY_INTERNALS_H
+#define IOTVT_SRM_SECURITY_INTERNALS_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+OicSecAcl_t* CBORPayloadToAcl(const uint8_t *payload, const size_t size);
+
+void DeleteACLList(OicSecAcl_t* acl);
+
+/**
+ * This internal method is to retrieve the default ACL.
+ * If SVR database in persistent storage got corrupted or
+ * is not available for some reason, a default ACL is created
+ * which allows user to initiate ACL provisioning again.
+ */
+OCStackResult  GetDefaultACL(OicSecAcl_t** defaultAcl);
+
+/**
+ * This internal method is the entity handler for ACL resources and
+ * will handle REST request (GET/PUT/POST/DEL) for them.
+ */
+OCEntityHandlerResult ACLEntityHandler(OCEntityHandlerFlag flag,
+            OCEntityHandlerRequest * ehRequest, void* callbackParameter);
+
+OCStackResult SetDefaultACL(OicSecAcl_t *acl);
+
+/**
+ * Converts CBOR payload to SVC.
+ *
+ * @param cborPayload is the svc payload cbor value that neds to be converted.
+ * @param cborSize of the cborPayload. In case size is not known, it is 0.
+ * @param svc is the value that is initialized. It is NULL in case of error.
+ *
+ * @return ::OC_STACK_OK in case successful. ::OC_STACK_INVALID_PARAM if one of
+ * the passed parameter is NULL. ::OC_STACK_ERROR in case of error.
+ */
+OCStackResult CBORPayloadToSVC(const uint8_t *cborPayload, size_t size, OicSecSvc_t **svc);
+
+/**
+ * Deletes the passed initialized reference to @ref OicSecSvc_t.
+ *
+ * @param svc is the reference to be deleted.
+ */
+void DeleteSVCList(OicSecSvc_t* svc);
+
+/**
+ * Create PSTAT resource after default PSTAT initialization is done.
+ */
+OCStackResult CreatePstatResource();
+
+/**
+ * This internal method is the entity handler for PSTAT resources and
+ * will handle REST request (GET/PUT/POST/DEL) for them.
+ */
+OCEntityHandlerResult PstatEntityHandler(OCEntityHandlerFlag flag,
+                                         OCEntityHandlerRequest * ehRequest);
+
+/**
+ * Converts CBOR payload to AMACL.
+ *
+ * @param cborPayload is the amacl payload cbor value that neds to be converted.
+ * @param cborSize of the cborPayload. In case size is not known, it is 0.
+ * It should be NON-NULL.
+ * @param amacl is the value that is initialized. It is NULL in case of error.
+ */
+OCStackResult CBORPayloadToAmacl(const uint8_t *cborPayload, size_t cborSize,
+                                 OicSecAmacl_t **amacl);
+
+void DeleteAmaclList(OicSecAmacl_t *amacl);
+
+/**
+ * This internal method is the entity handler for Cred resources
+ * to handle REST request (PUT/POST/DEL)
+ */
+OCEntityHandlerResult CredEntityHandler(OCEntityHandlerFlag flag,
+                                        OCEntityHandlerRequest * ehRequest,
+                                        void* callbackParameter);
+
+/**
+ * This internal method is used to create '/oic/sec/Cred' resource.
+ */
+OCStackResult CreateCredResource();
+
+/**
+ * This function converts from CBOR format into credential structure .
+ * Caller needs to invoke 'free' for allocated structure.
+ *
+ * @param cborPayload is the CBOR value that is assigned to the structure.
+ * @param size is the size of the CBOR.
+ * @param secCred is the pointer to instance of @ref OicSecCred_t structure that will be allocated.
+ * If it fails it will return NULL.
+ *
+ * @return ::OC_STACK_OK if conversion is successful, else ::OC_STACK_ERROR if unsuccessful.
+ */
+OCStackResult CBORPayloadToCred(const uint8_t *cborPayload, size_t size,
+                                OicSecCred_t **secCred);
+
+/**
+ * This internal method is used to create '/oic/sec/doxm' resource.
+ */
+OCStackResult CreateDoxmResource();
+
+/**
+ * This internal method is the entity handler for DOXM resources.
+ */
+OCEntityHandlerResult DoxmEntityHandler(OCEntityHandlerFlag flag,
+                                        OCEntityHandlerRequest * ehRequest,
+                                        void* callbackParam);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif //IOTVT_SRM_SECURITY_INTERNALS_H
index 568bfa4..a7a2df1 100644 (file)
@@ -24,6 +24,7 @@
 #include "securevirtualresourcetypes.h"
 
 extern const char * SVR_DB_FILE_NAME;
+extern const char * SVR_DB_DAT_FILE_NAME;
 extern const char * OIC_MI_DEF;
 
 //AMACL
@@ -112,6 +113,7 @@ extern const char * OIC_JSON_SPM_NAME;
 extern const char * OIC_JSON_PDEVICE_ID_NAME;
 
 extern OicUuid_t WILDCARD_SUBJECT_ID;
+extern OicUuid_t WILDCARD_SUBJECT_B64_ID;
 extern size_t WILDCARD_SUBJECT_ID_LEN;
 extern const char * WILDCARD_RESOURCE_URI;
 
index 9db42c5..ce759f8 100644 (file)
@@ -28,31 +28,33 @@ extern "C" {
 /**
  * Initialize SVC resource by loading data from persistent storage.
  *
- * @retval  OC_STACK_OK for Success, otherwise some error value
+ * @return ::OC_STACK_OK for Success, otherwise some error value.
  */
 OCStackResult InitSVCResource();
 
 /**
  * Perform cleanup for SVC resources.
- *
- * @retval  none
  */
 void DeInitSVCResource();
 
 /**
- * This function converts SVC data into JSON format.
- * Caller needs to invoke 'free' when done using
- * returned string.
- * @param svc  instance of OicSecSvc_t structure.
+ * This function converts SVC data into CBOR format.
+ * Caller needs to invoke 'free' when done using returned string.
+ *
+ * @param svc is the instance of @ref OicSecSvc_t structure. In case of NULL it
+ * will return ::OC_STACK_INVALID_PARAM.
+ * @param cborPayload is the converted cbor value of SVC structure.
+ * @param cborSize is the size of the cbor payload. This value is the size of the
+ * cborPayload. It should not be NON-NULL value.
  *
- * @retval  pointer to SVC in json format.
+ * @return ::OC_STACK_OK for Success. ::OC_STACK_INVALID in case of invalid parameters.
+ * ::OC_STACK_ERROR in case of error in converting to cbor.
  */
-char* BinToSvcJSON(const OicSecSvc_t * svc);
+ OCStackResult SVCToCBORPayload(const OicSecSvc_t *svc, uint8_t **cborPayload,
+                                size_t *cborSize);
 
 #ifdef __cplusplus
 }
 #endif
 
 #endif //IOTVT_SRM_SVCR_H
-
-
index ff2e3e5..2957db8 100644 (file)
@@ -1,22 +1,22 @@
-/*****************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * *****************************************************************/
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #ifndef _PBKDF2_H
 #define _PBKDF2_H
@@ -39,14 +39,14 @@ extern "C"
  * Function to derive cryptographic key from the password. (RFC 2898)
  * In this implementation, HMAC with SHA2 is considered as a pseudorandom function
  *
- * @param[in] passwd is the master password from which a derived key is generated.
- * @param[in] pLen is the byte size of the passwd.
- * @param[in] salt is a cryptographic salt.
- * @param[in] saltlen is the byte size of the salt.
- * @param[in] iteration is the number of iterations desired.
- * @param[in] keyLen is the desired byte size of the derived key. (should be the same as
+ * @param passwd is the master password from which a derived key is generated.
+ * @param pLen is the byte size of the passwd.
+ * @param salt is a cryptographic salt.
+ * @param saltlen is the byte size of the salt.
+ * @param iteration is the number of iterations desired.
+ * @param keyLen is the desired byte size of the derived key. (should be the same as
  *       derivedKey size)
- * @param[out] derivedKey is the generated derived key
+ * @param derivedKey is the generated derived key
  *
  * @return  0 on success
  */
index de15015..67f07ac 100644 (file)
@@ -1,22 +1,22 @@
-/*****************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * *****************************************************************/
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #ifndef PIN_CALLBACK_DEF_H_
 #define PIN_CALLBACK_DEF_H_
 #define OXM_RANDOM_PIN_SIZE 8
 
 /**
- * Function pointer to print pin code
+ * Function pointer to print pin code.
  */
 typedef void (*GeneratePinCallback)(char* pinData, size_t pinSize);
 
 /**
- * Function pointer to input pin code
+ * Function pointer to input pin code.
  */
 typedef void (*InputPinCallback)(char* pinBuf, size_t bufSize);
 
 /**
- * Function to setting generate PIN callback from user
+ * Function to setting generate PIN callback from user.
  *
- * @param[in] pinCB implementation of generate PIN callback
+ * @param pinCB implementation of generate PIN callback.
  */
 void SetGeneratePinCB(GeneratePinCallback pinCB);
 
 /**
- * Function to setting input PIN callback from user
+ * Function to setting input PIN callback from user.
  *
- * @param[in] pinCB implementation of input PIN callback
+ * @param pinCB implementation of input PIN callback.
  */
 void SetInputPinCB(InputPinCallback pinCB);
 
@@ -58,18 +58,20 @@ void SetInputPinCB(InputPinCallback pinCB);
  * Function to generate random PIN.
  * This function will send generated PIN to user via callback.
  *
- * @param[in,out] pinBuffer   Buffer to store the generated PIN data.
- * @param[in] bufferSize   Size of buffer
- * @return OC_STACK_SUCCESS in case of success and other value otherwise.
+ * @param pinBuffer is the reference to the buffer to store the generated PIN data.
+ * @param bufferSize is the size of buffer.
+ *
+ * @return ::OC_STACK_SUCCESS in case of success or other value in case of error.
  */
 OCStackResult GeneratePin(char* pinBuffer, size_t bufferSize);
 
 /**
- * Function to input PIN callback via input callback
+ * Function to input PIN callback via input callback.
+ *
+ * @param[in,out] pinBuffer is the reference to the buffer to store the inputed PIN data.
+ * @param[in] bufferSize is the size of buffer.
  *
- * @param[in,out] pinBuffer Buffer to store the inputed PIN data.
- * @param[in] bufferSize Size of buffer
- * @return OC_STACK_SUCCESS in case of success and other value otherwise.
+ * @return ::OC_STACK_SUCCESS in case of success or other value in ccase of error.
  */
 OCStackResult InputPin(char* pinBuffer, size_t bufferSize);
 
index d8f7048..d16a1e8 100644 (file)
@@ -52,8 +52,8 @@ extern "C" {
 #endif
 
 /**
- * @brief   Values used to create bit-maskable enums for single-value
- *          response with embedded code.
+ * Values used to create bit-maskable enums for single-value response with
+ * embedded code.
  */
 #define ACCESS_GRANTED_DEF            (1 << 0)
 #define ACCESS_DENIED_DEF             (1 << 1)
@@ -189,8 +189,8 @@ typedef enum OSCTBitmask
 } OSCTBitmask_t;
 
 /**
- * @brief   /oic/sec/credtype (Credential Type) data type.
- *          Derived from OIC Security Spec /oic/sec/cred; see Spec for details.
+ * /oic/sec/credtype (Credential Type) data type.
+ * Derived from OIC Security Spec /oic/sec/cred; see Spec for details.
  *              0:  no security mode
  *              1:  symmetric pair-wise key
  *              2:  symmetric group key
@@ -245,7 +245,7 @@ typedef enum
     OIC_OXM_COUNT
 }OicSecOxm_t;
 
-typedef struct OicSecJwk OicSecJwk_t;
+typedef struct OicSecKey OicSecKey_t;
 
 typedef struct OicSecPstat OicSecPstat_t;
 
@@ -262,10 +262,13 @@ typedef struct OicUuid OicUuid_t; //TODO is UUID type defined elsewhere?
 
 #ifdef __WITH_X509__
 typedef struct OicSecCrl OicSecCrl_t;
+typedef ByteArray OicSecCert_t;
+#else
+typedef void OicSecCert_t;
 #endif /* __WITH_X509__ */
 
 /**
- * @brief   /oic/uuid (Universal Unique Identifier) data type.
+ * /oic/uuid (Universal Unique Identifier) data type.
  */
 #define UUID_LENGTH 128/8 // 128-bit GUID length
 //TODO: Confirm the length and type of ROLEID.
@@ -281,18 +284,19 @@ struct OicUuid
 };
 
 /**
- * @brief   /oic/sec/jwk (JSON Web Key) data type.
- *          See JSON Web Key (JWK)  draft-ietf-jose-json-web-key-41
+ * /oic/sec/jwk (JSON Web Key) data type.
+ * See JSON Web Key (JWK)  draft-ietf-jose-json-web-key-41
  */
 #define JWK_LENGTH 256/8 // 256 bit key length
-struct OicSecJwk
+struct OicSecKey
 {
-    char                *data;
+    uint8_t                *data;
+    size_t                  len;
 };
 
 /**
- * @brief   /oic/sec/acl (Access Control List) data type.
- *          Derived from OIC Security Spec; see Spec for details.
+ * /oic/sec/acl (Access Control List) data type.
+ * Derived from OIC Security Spec; see Spec for details.
  */
 struct OicSecAcl
 {
@@ -316,9 +320,8 @@ struct OicSecAcl
 };
 
 /**
- * @brief   /oic/sec/amacl (Access Manager Service Accesss Control List)
- *          data type.
- *          Derived from OIC Security Spec; see Spec for details.
+ * /oic/sec/amacl (Access Manager Service Accesss Control List) data type.
+ * Derived from OIC Security Spec; see Spec for details.
  */
 struct OicSecAmacl
 {
@@ -337,8 +340,8 @@ struct OicSecAmacl
 };
 
 /**
- * @brief   /oic/sec/cred (Credential) data type.
- *          Derived from OIC Security Spec; see Spec for details.
+ * /oic/sec/cred (Credential) data type.
+ * Derived from OIC Security Spec; see Spec for details.
  */
 struct OicSecCred
 {
@@ -350,8 +353,10 @@ struct OicSecCred
     //size_t              roleIdsLen;     // the number of elts in RoleIds
     //OicSecRole_t        *roleIds;       // 2:R:M:N:oic.sec.role
     OicSecCredType_t    credType;       // 3:R:S:Y:oic.sec.credtype
-    OicSecJwk_t         publicData;     // 5:R:S:N:oic.sec.jwk
-    OicSecJwk_t         privateData;    // 6:R:S:N:oic.sec.jwk
+#ifdef __WITH_X509__
+    OicSecCert_t        publicData;     // chain of certificates
+#endif /* __WITH_X509__ */
+    OicSecKey_t         privateData;    // 6:R:S:N:oic.sec.key
     char                *period;        // 7:R:S:N:String
     size_t              ownersLen;      // the number of elts in Owners
     OicUuid_t           *owners;        // 8:R:M:Y:oic.uuid
@@ -363,8 +368,8 @@ struct OicSecCred
 };
 
 /**
- * @brief   /oic/sec/doxm (Device Owner Transfer Methods) data type
- *          Derived from OIC Security Spec; see Spec for details.
+ * /oic/sec/doxm (Device Owner Transfer Methods) data type
+ * Derived from OIC Security Spec; see Spec for details.
  */
 struct OicSecDoxm
 {
@@ -379,17 +384,17 @@ struct OicSecDoxm
     //TODO: Need more clarification on deviceIDFormat field type.
     //OicSecDvcIdFrmt_t   deviceIDFormat; // 5:R:S:Y:UINT8
     OicUuid_t           deviceID;       // 6:R:S:Y:oic.uuid
-    bool                   dpc;             // 7:R:S:Y:Boolean
-    OicUuid_t           owner;         // 7:R:S:Y:oic.uuid
+    bool                dpc;             // 7:R:S:Y:Boolean
+    OicUuid_t           owner;         // 8:R:S:Y:oic.uuid
     // NOTE: we are using UUID for Owner instead of Svc type for mid-April
     // SRM version only; this will change to Svc type for full implementation.
-    //OicSecSvc_t       devOwner;        // 7:R:S:Y:oic.sec.svc
-    //OicSecSvc_t       rOwner;        // 8:R:S:Y:oic.sec.svc
+    //OicSecSvc_t       devOwner;        // 9:R:S:Y:oic.sec.svc
+    //OicSecSvc_t       rOwner;        // 10:R:S:Y:oic.sec.svc
     //TODO change Owner type to oic.sec.svc
 };
 
 /**
- * @brief   /oic/sec/pstat (Provisioning Status) data type.
+ * /oic/sec/pstat (Provisioning Status) data type.
  * NOTE: this struct is ahead of Spec v0.95 in definition to include Sm.
  * TODO: change comment when reconciled to Spec v0.96.
  */
@@ -409,8 +414,8 @@ struct OicSecPstat
 };
 
 /**
- * @brief   /oic/sec/role (Role) data type.
- *          Derived from OIC Security Spec; see Spec for details.
+ * /oic/sec/role (Role) data type.
+ * Derived from OIC Security Spec; see Spec for details.
  */
 struct OicSecRole
 {
@@ -420,8 +425,8 @@ struct OicSecRole
 };
 
 /**
- * @brief   /oic/sec/sacl (Signed Access Control List) data type.
- *          Derived from OIC Security Spec; see Spec for details.
+ * /oic/sec/sacl (Signed Access Control List) data type.
+ * Derived from OIC Security Spec; see Spec for details.
  */
 struct OicSecSacl
 {
@@ -430,8 +435,8 @@ struct OicSecSacl
 };
 
 /**
- * @brief   /oic/sec/svc (Service requiring a secure connection) data type.
- *          Derived from OIC Security Spec; see Spec for details.
+ * /oic/sec/svc (Service requiring a secure connection) data type.
+ * Derived from OIC Security Spec; see Spec for details.
  */
 struct OicSecSvc
 {
@@ -483,7 +488,7 @@ typedef PRMBitmask_t OicSecPrm_t;
 
 struct OicPin
 {
-    uint8_t             val[DP_PIN_LENGTH+1];
+    uint8_t             val[DP_PIN_LENGTH];
 };
 
 /**
index 80548f0..029a41b 100644 (file)
@@ -33,86 +33,76 @@ extern "C"
 }
 #endif
 
-
 #ifdef __cplusplus
 extern "C" {
 #endif // __cplusplus
 
-
 typedef struct OicParseQueryIter OicParseQueryIter_t;
 
 /**
- * @brief   OicRestQueryIter data structure is used for book-keeping
- *          sub-REST query's attribute's and value's, starting location &
- *          length between calls to GetNextQuery(). This struct needs
- *          to be first initialized with ParseQueryIterInit().
+ * OicRestQueryIter data structure is used for book-keeping
+ * sub-REST query's attribute's and value's, starting location &
+ * length between calls to GetNextQuery(). This struct needs
+ * to be first initialized with ParseQueryIterInit().
  *
  */
 struct OicParseQueryIter
 {
-    unsigned char * attrPos;    /**<stating location of attribute */
-    size_t attrLen;             /**<length of the attribute */
-    unsigned char * valPos;     /**<starting location of value*/
-    size_t valLen;              /**<length of the value*/
-    coap_parse_iterator_t pi;   /**<coap struct for tokenizing the query*/
+    unsigned char * attrPos;    /**< stating location of attribute. */
+    size_t attrLen;             /**< length of the attribute. */
+    unsigned char * valPos;     /**< starting location of value. */
+    size_t valLen;              /**< length of the value. */
+    coap_parse_iterator_t pi;   /**< coap struct for tokenizing the query.*/
 };
 
 /**
- * @def VERIFY_SUCCESS
- * @brief Macro to verify success of operation.
+ * Macro to verify success of operation.
  * eg: VERIFY_SUCCESS(TAG, OC_STACK_OK == foo(), ERROR);
  * @note Invoking function must define "exit:" label for goto functionality to work correctly.
- *
  */
 #define VERIFY_SUCCESS(tag, op, logLevel) do{ if (!(op)) \
             {OIC_LOG((logLevel), tag, #op " failed!!"); goto exit; } }while(0)
 
 /**
- * @def VERIFY_NON_NULL
- * @brief Macro to verify argument is not equal to NULL.
+ * Macro to verify argument is not equal to NULL.
  * eg: VERIFY_NON_NULL(TAG, ptrData, ERROR);
  * @note Invoking function must define "exit:" label for goto functionality to work correctly.
- *
  */
 #define VERIFY_NON_NULL(tag, arg, logLevel) do{ if (NULL == (arg)) \
             { OIC_LOG((logLevel), tag, #arg " is NULL"); goto exit; } }while(0)
 
 /**
- * This method initializes the OicParseQueryIter_t struct
- *
- *@param query     - REST query, to be parsed
- *@param parseIter - OicParseQueryIter_t struct, to be initialized
+ * This method initializes the @ref OicParseQueryIter_t struct.
  *
+ * @param query is the REST query, to be parsed.
+ * @param parseIter is the @ref OicParseQueryIter_t struct, to be initialized based on the query.
  */
-void ParseQueryIterInit(unsigned char * query, OicParseQueryIter_t * parseIter);
-
+void ParseQueryIterInit(const unsigned char * query, OicParseQueryIter_t * parseIter);
 
 /**
- * This method fills the OicParseQueryIter_t struct with next REST query's
- * attribute's and value's information
+ * This method fills the @ref OicParseQueryIter_t struct with next REST query's
+ * attribute's and value's information.
  *
- *@param parseIter - OicParseQueryIter_t struct, has next query's attribute's & value's info
+ * @param parseIter is the @ref OicParseQueryIter_t struct, has next query's attribute's
+ *  & value's info.
  *
- * @retval
- *     OicParseQueryIter_t *  - has parsed query info
- *     NULL                   - has no query to parse
+ * @return reference to the @ref OicParseQueryIter_t if it has parsed query info, else
+ * NULL if it has no query to parse.
  */
 OicParseQueryIter_t * GetNextQuery(OicParseQueryIter_t * parseIter);
 
-
-
 /**
- * This method acts as a helper funtion for JSON unmarshalling by various SVR's.
+ * This method acts as a helper function for JSON unmarshalling by various SVR's.
  *
- * @param jsonRoot  - root JSON node containing the OicUuid array
- * @param arrayItem - name of the JSON OicUuid array item
- * @param numUuids  - pointer to the number of OicUuid's available in JSON array
- * @param uuids     - pointer to the array of OicUuid's
+ * @param jsonRoot point to the root JSON node containing the OicUuid array.
+ * @param arrayItem is the name of the JSON OicUuid array item.
+ * @param numUuids is the pointer to the number of OicUuid's available in JSON array.
+ * @param uuids is the pointer to the array of OicUuid's.
  *
  * @return ::OC_STACK_OK on success, some other value upon failure.
  */
-OCStackResult AddUuidArray(cJSON* jsonRoot, const char* arrayItem,
-                           size_t *numUuids, OicUuid_t** uuids );
+OCStackResult AddUuidArray(const cJSON* jsonRoot, const char* arrayItem,
+                           size_t *numUuids, OicUuid_t** uuids);
 
 /**
  * Function to getting string of ownership transfer method
index 9425b5f..d75863d 100755 (executable)
@@ -59,7 +59,7 @@ static std::string address;
 
 static int coapSecureResource;
 
-static const char CRED_FILE[] = "oic_svr_db_door.json";
+static const char CRED_FILE[] = "oic_svr_db_door.dat";
 
 CAEndpoint_t endpoint = {CA_DEFAULT_ADAPTER, CA_DEFAULT_FLAGS, 0, {0}, 0};
 
index bed8d16..11c7991 100755 (executable)
@@ -42,7 +42,7 @@ const char *gResourceUri = (char *)"/a/light";
 //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_light.json";
+static char CRED_FILE[] = "oic_svr_db_light.dat";
 
 
 //Structure to represent a light resource  and its attributes
index b368fe3..d41b38b 100644 (file)
@@ -88,4 +88,10 @@ provisioning_env.Alias("install", provisioning_env.Install( sec_provisioning_bui
 provisioning_env.Alias("install", provisioning_env.Install( sec_provisioning_build_dir,
        sec_provisioning_src_dir + 'oic_svr_db_door.json'))
 provisioning_env.Alias("install", provisioning_env.Install( sec_provisioning_build_dir,
+       sec_provisioning_src_dir + 'oic_svr_db_pt.dat'))
+provisioning_env.Alias("install", provisioning_env.Install( sec_provisioning_build_dir,
+       sec_provisioning_src_dir + 'oic_svr_db_light.dat'))
+provisioning_env.Alias("install", provisioning_env.Install( sec_provisioning_build_dir,
+       sec_provisioning_src_dir + 'oic_svr_db_door.dat'))
+provisioning_env.Alias("install", provisioning_env.Install( sec_provisioning_build_dir,
        sec_provisioning_src_dir + 'README.txt'))
diff --git a/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_door.dat b/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_door.dat
new file mode 100644 (file)
index 0000000..e6ddaa8
Binary files /dev/null and b/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_door.dat differ
index 8bcb39f..05cc4b0 100644 (file)
@@ -31,7 +31,7 @@
        "pstat":        {
                "isop": false,
                "deviceid":     "ZG9vckRldmljZVVVSUQwMA==",
-               "commithash": 0,
+               "ch": 0,
                "cm":   0,
                "tm":   0,
                "om":   3,
@@ -42,6 +42,7 @@
                "oxmsel": 0,
                "sct": 1,
                "owned": false,
-               "deviceid":     "ZG9vckRldmljZVVVSUQwMA=="
+               "deviceid":     "ZG9vckRldmljZVVVSUQwMA==",
+               "dpc": true
        }
 }
diff --git a/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_light.dat b/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_light.dat
new file mode 100644 (file)
index 0000000..0f4653a
Binary files /dev/null and b/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_light.dat differ
index 048384b..5ec466b 100644 (file)
@@ -31,7 +31,7 @@
        "pstat":        {
                "isop": false,
                "deviceid":     "bGlnaHREZXZpY2VVVUlEMA==",
-               "commithash": 0,
+               "ch": 0,
                "cm":   0,
                "tm":   0,
                "om":   3,
@@ -42,6 +42,7 @@
                "oxmsel": 0,
                "sct": 1,
                "owned": false,
-               "deviceid":     "bGlnaHREZXZpY2VVVUlEMA=="
+               "deviceid":     "bGlnaHREZXZpY2VVVUlEMA==",
+               "dpc": true
        }
 }
diff --git a/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_pt.dat b/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_pt.dat
new file mode 100644 (file)
index 0000000..42622ee
Binary files /dev/null and b/resource/csdk/security/provisioning/ck_manager/sample/oic_svr_db_pt.dat differ
index dd5dec4..d05736c 100644 (file)
@@ -39,6 +39,7 @@
                "sct": 1,
                "owned": true,
                "deviceid":     "YWRtaW5EZXZpY2VVVUlEMA==",
-               "ownr": "YWRtaW5EZXZpY2VVVUlEMA=="
+               "ownr": "YWRtaW5EZXZpY2VVVUlEMA==",
+               "dpc": true
        }
 }
index 67ae5ae..4b2f0c2 100644 (file)
@@ -50,7 +50,7 @@
 
 static OicSecAcl_t        *gAcl = NULL;
 static OicSecCrl_t        *gCrl = NULL;
-static char PROV_TOOL_DB_FILE[] = "oic_svr_db_pt.json";
+static char PROV_TOOL_DB_FILE[] = "oic_svr_db_pt.dat";
 static const char* PRVN_DB_FILE_NAME = "oic_prvn_mng.db";
 static int gOwnershipState = 0;
 
index f92fcdf..6218806 100644 (file)
@@ -82,7 +82,7 @@ pki_test_env.Alias("install",env.Install( unittest_build_dir, [ unittest_src_dir
                                                                unittest_src_dir + 'capub.der',
                                                                unittest_src_dir + 'cert_chain.dat',
                                                                unittest_src_dir + 'chain.der',
-                                                               unittest_src_dir + 'CKMInfo.json' ]))
+                                                               unittest_src_dir + 'CKMInfo.dat' ]))
 
 env.AppendTarget('test')
 if env.get('TEST') == '1':
index a2ceb10..e224b42 100644 (file)
@@ -43,7 +43,7 @@
 #define READ_WRITE_BLOCK_N 1ul
 #define N_LENGTH_BYTES 3
 
-const char *CKMI_JSON_FILE_NAME = "CKMInfo.json";
+const char *CKMI_PS_FILE_NAME = "CKMInfo.dat";
 
 #define CRL_DEFAULT_CRL_ID           1
 #define CRL_DEFAULT_THIS_UPDATE     "150101000000Z"
@@ -57,7 +57,7 @@ OCPersistentStorage ps = { NULL, NULL, NULL, NULL, NULL};
 
 FILE* ckm_fopen(const char * /*path*/, const char *mode)
 {
-    return fopen(CKMI_JSON_FILE_NAME, mode);
+    return fopen(CKMI_PS_FILE_NAME, mode);
 }
 
 void SetPersistentHandler(OCPersistentStorage *ps)
@@ -977,7 +977,7 @@ TEST_F(PKITest, CRLSetGet)
     defaultCrl->ThisUpdate.len = strlen(CRL_DEFAULT_THIS_UPDATE);
     EXPECT_EQ(OC_STACK_OK, UpdateCRLResource(defaultCrl));
 
-    EXPECT_NE((void *)NULL, GetBase64CRL());
+    EXPECT_NE((void *)NULL, GetCrl());
     OICFree(defaultCrl);
 
 
diff --git a/resource/csdk/security/provisioning/ck_manager/unittest/test_data/CKMInfo.dat b/resource/csdk/security/provisioning/ck_manager/unittest/test_data/CKMInfo.dat
new file mode 100644 (file)
index 0000000..0f1ecf1
Binary files /dev/null and b/resource/csdk/security/provisioning/ck_manager/unittest/test_data/CKMInfo.dat differ
index bf7deed..546bb28 100644 (file)
@@ -75,17 +75,19 @@ typedef OCStackResult (*OTMCreateSecureSession)(OTMContext_t* otmCtx);
 /*\r
  * Callback for creating CoAP payload.\r
  */\r
-typedef char* (*OTMCreatePayloadCallback)(OTMContext_t* otmCtx);\r
+typedef OCStackResult (*OTMCreatePayloadCallback)(OTMContext_t* otmCtx, uint8_t **payload,\r
+                                                  size_t *size);\r
 \r
 /**\r
  * Required callback for performing ownership transfer\r
  */\r
-typedef struct OTMCallbackData{\r
+typedef struct OTMCallbackData\r
+{\r
     OTMLoadSecret loadSecretCB;\r
     OTMCreateSecureSession createSecureSessionCB;\r
     OTMCreatePayloadCallback createSelectOxmPayloadCB;\r
     OTMCreatePayloadCallback createOwnerTransferPayloadCB;\r
-}OTMCallbackData_t;\r
+} OTMCallbackData_t;\r
 \r
 /**\r
  * Set the callbacks for ownership transfer\r
index 190b55d..0b9f81e 100644 (file)
@@ -1,22 +1,22 @@
-/*****************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * *****************************************************************/
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #ifndef OXM_JUST_WORKS_H_
 #define OXM_JUST_WORKS_H_
@@ -35,35 +35,45 @@ extern "C" {
 
 /**
  * In case of just works OxM, no need to implement.
+ *
+ * @return ::OC_STACK_SUCCESS in case of success and other value otherwise.
  */
 OCStackResult LoadSecretJustWorksCallback(OTMContext_t* UNUSED_PARAM);
 
 /**
  * To establish a secure channel with anonymous cipher suite
  *
- * @param[in] selectedDeviceInfo Selected device infomation
- * @return OC_STACK_SUCCESS in case of success and other value otherwise.
+ * @param otmCtx Context of OTM, It includes current device information.
+ *
+ * @return ::OC_STACK_SUCCESS in case of success and other value otherwise.
  */
 OCStackResult CreateSecureSessionJustWorksCallback(OTMContext_t* otmCtx);
 
 /**
  * Generate payload for select OxM request.
  *
- * @param[in] selectedDeviceInfo Selected device infomation
- * @return DOXM JSON payload including the selected OxM.
- *         NOTE : Returned memory should be deallocated by caller.
+ * @param otmCtx Context of OTM, It includes current device information.
+ * @param cborPayload is the DOXM CBOR payload including the selected OxM.
+ * @note Returned memory should be deallocated by caller.
+ * @param cborSize is the size of the cborPayload.
+ *
+ * @return ::OC_STACK_SUCCESS in case of success and other value otherwise.
  */
-char* CreateJustWorksSelectOxmPayload(OTMContext_t* otmCtx);
+OCStackResult CreateJustWorksSelectOxmPayload(OTMContext_t *otmCtx, uint8_t **cborPayload,
+                                             size_t *cborSize);
 
 /**
  * Generate payload for owner transfer request.
  *
- * @param[in] selectedDeviceInfo Selected device infomation
- * @return DOXM JSON payload including the owner information.
- *         NOTE : Returned memory should be deallocated by caller.
+ * @param otmCtx Context of OTM, It includes current device information.
+ * @param cborPayload is the DOXM CBOR payload including the owner information.
+ * @note Returned memory should be deallocated by caller.
+ * @param cborSize is the size of the cborPayload.
+ *
+ * @return ::OC_STACK_SUCCESS in case of success and other value otherwise.
  */
-char* CreateJustWorksOwnerTransferPayload(OTMContext_t* otmCtx);
-
+OCStackResult CreateJustWorksOwnerTransferPayload(OTMContext_t *otmCtx, uint8_t **cborPayload,
+                                                  size_t *cborSize);
 #ifdef __cplusplus
 }
 #endif
index b458ef3..ae7b110 100644 (file)
@@ -1,22 +1,22 @@
-/*****************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * *****************************************************************/
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #ifndef OXM_RANDOM_PIN_H_
 #define OXM_RANDOM_PIN_H_
@@ -34,36 +34,46 @@ extern "C" {
 /**
  * Callback implementation to input the PIN code from user.
  *
- * @otmCtx  Context of OTM, It includes current device infomation.
- * @return OC_STACK_SUCCESS in case of success and other value otherwise.
+ * @param otmCtx Context of OTM, It includes current device information.
+ *
+ * @return ::OC_STACK_SUCCESS in case of success and other value otherwise.
  */
-OCStackResult InputPinCodeCallback(OTMContext_totmCtx);
+OCStackResult InputPinCodeCallback(OTMContext_t *otmCtx);
 
 /**
- * Callback implemenration to establish a secure channel with PSK cipher suite
+ * Callback implemenration to establish a secure channel with PSK cipher suite.
+ *
+ * @param otmCtx Context of OTM, It includes current device information.
  *
- * @param[in] selectedDeviceInfo Selected device infomation
- * @return OC_STACK_SUCCESS in case of success and other value otherwise.
+ * @return ::OC_STACK_SUCCESS in case of success and other value otherwise.
  */
 OCStackResult CreateSecureSessionRandomPinCallback(OTMContext_t *otmCtx);
 
 /**
  * Generate payload for select OxM request.
  *
- * @param[in] selectedDeviceInfo Selected device infomation
- * @return DOXM JSON payload including the selected OxM.
- *         NOTE : Returned memory should be deallocated by caller.
+ * @param otmCtx Context of OTM, It includes current device information.
+ * @param cborPaylaod is the DOXM CBOR payload including the selected OxM.
+ * @note Returned memory should be deallocated by caller.
+ * @param cborSize is the size of the cborPayload.
+ *
+ * @return ::OC_STACK_SUCCESS in case of success and other value otherwise.
  */
-char* CreatePinBasedSelectOxmPayload(OTMContext_t* otmCtx);
+OCStackResult CreatePinBasedSelectOxmPayload(OTMContext_t *otmCtx, uint8_t **cborPayload,
+                                             size_t *cborSize);
 
 /**
  * Generate payload for owner transfer request.
  *
- * @param[in] selectedDeviceInfo Selected device infomation
- * @return DOXM JSON payload including the owner information.
- *         NOTE : Returned memory should be deallocated by caller.
+ * @param otmCtx Context of OTM, It includes current device information.
+ * @param cborPaylaod is the DOXM CBOR payload including the owner information.
+ * @note Returned memory should be deallocated by caller.
+ * @param cborSize is the size of the cborPayload.
+ *
+ * @return ::OC_STACK_SUCCESS in case of success and other value otherwise.
  */
-char* CreatePinBasedOwnerTransferPayload(OTMContext_t* otmCtx);
+OCStackResult CreatePinBasedOwnerTransferPayload(OTMContext_t *otmCtx, uint8_t **cborPayload,
+                                                 size_t *cborSize);
 
 #ifdef __cplusplus
 }
index f65169c..1f811cf 100644 (file)
@@ -23,8 +23,6 @@ Import('env')
 
 provisioning_env = env.Clone()
 
-target_os = env.get('TARGET_OS')
-
 ######################################################################
 # Build flags
 ######################################################################
@@ -53,7 +51,7 @@ provisioning_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread', '-f
 provisioning_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
 provisioning_env.AppendUnique(LIBS = ['-lpthread','-ldl'])
 provisioning_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
-provisioning_env.PrependUnique(LIBS = ['ocpmapi', 'm', 'octbstack', 'ocsrm', 'connectivity_abstraction', 'coap'])
+provisioning_env.PrependUnique(LIBS = ['ocpmapi','oc', 'oc_logger', 'ocsrm','m', 'octbstack', 'connectivity_abstraction', 'coap'])
 
 if env.get('SECURED') == '1':
     provisioning_env.AppendUnique(LIBS = ['tinydtls'])
@@ -62,26 +60,28 @@ if env.get('DTLS_WITH_X509') == '1':
        provisioning_env.AppendUnique(LIBS = ['asn1'])
 provisioning_env.ParseConfig('pkg-config --libs glib-2.0');
 
+provisioning_env.AppendUnique(CPPDEFINES = ['TB_LOG'])
+
 ######################################################################
 # Source files and Targets
 ######################################################################
 
-src_dir = provisioning_env.get('SRC_DIR')
-sec_provisioning_src_dir = src_dir + '/resource/csdk/security/provisioning/sample/'
-sec_provisioning_build_dir = env.get('BUILD_DIR') +'/resource/csdk/security/provisioning/sample/'
-
 provisioningclient = provisioning_env.Program('provisioningclient', 'provisioningclient.c')
 sampleserver_justworks = provisioning_env.Program('sampleserver_justworks', 'sampleserver_justworks.cpp')
 sampleserver_randompin = provisioning_env.Program('sampleserver_randompin', 'sampleserver_randompin.cpp')
 
-clientjson = provisioning_env.Install(sec_provisioning_build_dir,
-                                        sec_provisioning_src_dir + 'oic_svr_db_client.json')
-justworksjson = provisioning_env.Install(sec_provisioning_build_dir,
-                                    sec_provisioning_src_dir + 'oic_svr_db_server_justworks.json')
-randompinjson = provisioning_env.Install(sec_provisioning_build_dir,
-                                    sec_provisioning_src_dir+ 'oic_svr_db_server_randompin.json')
+src_dir = provisioning_env.get('SRC_DIR')
+sec_provisioning_src_dir = src_dir + '/resource/csdk/security/provisioning/sample/'
+sec_provisioning_build_dir = env.get('BUILD_DIR') +'/resource/csdk/security/provisioning/sample/'
+
+clientdat = provisioning_env.Install(sec_provisioning_build_dir,
+                                        sec_provisioning_src_dir + 'oic_svr_db_client.dat')
+justworksdat = provisioning_env.Install(sec_provisioning_build_dir,
+                                    sec_provisioning_src_dir + 'oic_svr_db_server_justworks.dat')
+randompindat = provisioning_env.Install(sec_provisioning_build_dir,
+                                    sec_provisioning_src_dir+ 'oic_svr_db_server_randompin.dat')
 
-Alias("samples", [provisioningclient, sampleserver_justworks, sampleserver_randompin, clientjson, justworksjson, randompinjson])
+Alias("samples", [provisioningclient, sampleserver_justworks, sampleserver_randompin, clientdat, justworksdat, randompindat])
 
 provisioning_env.AppendTarget('samples')
 
diff --git a/resource/csdk/security/provisioning/sample/oic_svr_db_client.dat b/resource/csdk/security/provisioning/sample/oic_svr_db_client.dat
new file mode 100644 (file)
index 0000000..6a39661
Binary files /dev/null and b/resource/csdk/security/provisioning/sample/oic_svr_db_client.dat differ
index 1219d6a..9e5fa3a 100644 (file)
@@ -38,6 +38,7 @@
                "sct": 1,
                "owned": true,
                "deviceid":     "YWRtaW5EZXZpY2VVVUlEMA==",
+        "dpc": false,
                "ownr": "YWRtaW5EZXZpY2VVVUlEMA=="
        }
 }
diff --git a/resource/csdk/security/provisioning/sample/oic_svr_db_prov_tool.dat b/resource/csdk/security/provisioning/sample/oic_svr_db_prov_tool.dat
new file mode 100644 (file)
index 0000000..a02c199
Binary files /dev/null and b/resource/csdk/security/provisioning/sample/oic_svr_db_prov_tool.dat differ
diff --git a/resource/csdk/security/provisioning/sample/oic_svr_db_server_justworks.dat b/resource/csdk/security/provisioning/sample/oic_svr_db_server_justworks.dat
new file mode 100644 (file)
index 0000000..552fdec
Binary files /dev/null and b/resource/csdk/security/provisioning/sample/oic_svr_db_server_justworks.dat differ
index 8dc08f6..abb850f 100755 (executable)
@@ -41,7 +41,7 @@
        "pstat":        {
                "isop": false,
                "deviceid":     "anVzdHdvcmtzRGV2VVVJRA==",
-               "commithash": 0,
+               "ch": 0,
                "cm":   0,
                "tm":   0,
                "om":   3,
diff --git a/resource/csdk/security/provisioning/sample/oic_svr_db_server_randompin.dat b/resource/csdk/security/provisioning/sample/oic_svr_db_server_randompin.dat
new file mode 100644 (file)
index 0000000..5e123bd
Binary files /dev/null and b/resource/csdk/security/provisioning/sample/oic_svr_db_server_randompin.dat differ
index 4caf960..181e105 100644 (file)
@@ -41,7 +41,7 @@
        "pstat":        {
                "isop": false,
                "deviceid":     "cmFuZG9tUGluRGV2VVVJRA==",
-               "commithash": 0,
+               "ch": 0,
                "cm":   0,
                "tm":   0,
                "om":   3,
diff --git a/resource/csdk/security/provisioning/sample/oic_svr_db_unowned_server.dat b/resource/csdk/security/provisioning/sample/oic_svr_db_unowned_server.dat
new file mode 100644 (file)
index 0000000..bb175dc
Binary files /dev/null and b/resource/csdk/security/provisioning/sample/oic_svr_db_unowned_server.dat differ
index 22f6894..85555ed 100644 (file)
@@ -60,7 +60,7 @@ extern "C"
 #define TAG "provisioningclient"
 
 static const char* ACL_PEMISN[5] = {"CREATE", "READ", "WRITE", "DELETE", "NOTIFY"};
-static const char* SVR_DB_FILE_NAME = "oic_svr_db_client.json";
+static const char* SVR_DB_FILE_NAME = "oic_svr_db_client.dat";
         // '_' for separaing from the same constant variable in |srmresourcestrings.c|
 static const char* PRVN_DB_FILE_NAME = "oic_prvn_mng.db";
 static const OicSecPrm_t  SUPPORTED_PRMS[1] =
index 03e741e..7047ae9 100644 (file)
@@ -53,7 +53,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_justworks.json";
+static char CRED_FILE[] = "oic_svr_db_server_justworks.dat";
 
 /* Function that creates a new LED resource by calling the
  * OCCreateResource() method.
index b60a34f..5ca0e7a 100644 (file)
@@ -54,7 +54,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.
index df7754b..456fc7c 100644 (file)
  * *****************************************************************/
 #include <string.h>
 #include "credentialgenerator.h"
+#include "base64.h"
 #include "oic_malloc.h"
 #include "oic_string.h"
-#include "logger.h"
+#include "ocpayload.h"
+#include "payload_logging.h"
 #include "credresource.h"
 #include "ocrandom.h"
-#include "base64.h"
+#include "srmutility.h"
 #include "stdbool.h"
 #include "securevirtualresourcetypes.h"
 #ifdef __WITH_X509__
 #include "ck_manager.h"
+//Certificate-related functions
+#define CERT_LEN_PREFIX (3)
+#define BYTE_SIZE (8) //bits
 
 #define CHAIN_LEN (2) //TODO: replace by external define or a runtime value
 #endif  //__WITH_X509__
 
 #define TAG "SRPAPI-CG"
 
-/**
- * @def PM_VERIFY_SUCCESS
- * @brief Macro to verify success of operation.
- *        eg: PM_VERIFY_SUCCESS(TAG, OC_STACK_OK == foo(), OC_STACK_ERROR, ERROR);
- * @note Invoking function must define "bail:" label for goto functionality to work correctly and
- *       must define "OCStackResult res" for setting error code.
- * */
-#define PM_VERIFY_SUCCESS(tag, op, errCode, logLevel) { if (!(op)) \
-                       {OIC_LOG((logLevel), tag, #op " failed!!"); res = errCode; goto bail;} }
-/**
- * @def PM_VERIFY_NON_NULL
- * @brief Macro to verify argument is not equal to NULL.
- *        eg: PM_VERIFY_NON_NULL(TAG, ptrData, ERROR);
- * @note Invoking function must define "bail:" label for goto functionality to work correctly.
- * */
-#define PM_VERIFY_NON_NULL(tag, arg, errCode, logLevel) { if (NULL == (arg)) \
-                   { OIC_LOG((logLevel), tag, #arg " is NULL"); res = errCode; goto bail;} }
-
 OCStackResult PMGeneratePairWiseCredentials(OicSecCredType_t type, size_t keySize,
-                                    const OicUuid_t *ptDeviceId,
-                                    const OicUuid_t *firstDeviceId, const OicUuid_t *secondDeviceId,
-                                    OicSecCred_t **firstCred, OicSecCred_t **secondCred)
+        const OicUuid_t *ptDeviceId, const OicUuid_t *firstDeviceId,
+        const OicUuid_t *secondDeviceId, OicSecCred_t **firstCred, OicSecCred_t **secondCred)
 {
-
     if (NULL == ptDeviceId || NULL == firstDeviceId || NULL != *firstCred || \
         NULL == secondDeviceId || NULL != *secondCred)
     {
@@ -71,42 +56,31 @@ OCStackResult PMGeneratePairWiseCredentials(OicSecCredType_t type, size_t keySiz
         return OC_STACK_INVALID_PARAM;
     }
     OCStackResult res = OC_STACK_ERROR;
-    uint8_t* privData = NULL;
-    char* base64Buff = NULL;
     OicSecCred_t *tempFirstCred = NULL;
     OicSecCred_t *tempSecondCred = NULL;
 
     size_t privDataKeySize = keySize;
 
-    privData = (uint8_t*) OICCalloc(privDataKeySize,sizeof(uint8_t));
-    PM_VERIFY_NON_NULL(TAG, privData, OC_STACK_NO_MEMORY, ERROR);
-
-    OCFillRandomMem(privData,privDataKeySize);
+    uint8_t *privData = (uint8_t *)OICCalloc(privDataKeySize, sizeof(uint8_t));
+    VERIFY_NON_NULL(TAG, privData, ERROR);
+    OicSecKey_t privKey = {privData, keySize};
 
-    uint32_t outLen = 0;
-
-    base64Buff = (char*) OICCalloc(B64ENCODE_OUT_SAFESIZE(privDataKeySize) + 1, sizeof(char));
-    PM_VERIFY_NON_NULL(TAG, base64Buff, OC_STACK_NO_MEMORY, ERROR);
-    int memReq = (B64ENCODE_OUT_SAFESIZE(privDataKeySize) + 1) * sizeof(char);
-    B64Result b64Ret = b64Encode(privData, privDataKeySize*sizeof(uint8_t), base64Buff,
-                                 memReq, &outLen);
-    PM_VERIFY_SUCCESS(TAG, B64_OK == b64Ret, OC_STACK_ERROR, ERROR);
+    OCFillRandomMem(privData, privDataKeySize);
 
     // TODO: currently owner array is 1. only provisioning tool's id.
-    tempFirstCred =  GenerateCredential(secondDeviceId, type, NULL, base64Buff, 1, ptDeviceId);
-    PM_VERIFY_NON_NULL(TAG, tempFirstCred, OC_STACK_ERROR, ERROR);
+    tempFirstCred =  GenerateCredential(secondDeviceId, type, NULL, &privKey, 1, ptDeviceId);
+    VERIFY_NON_NULL(TAG, tempFirstCred, ERROR);
 
     // TODO: currently owner array is 1. only provisioning tool's id.
-    tempSecondCred =  GenerateCredential(firstDeviceId, type, NULL, base64Buff, 1, ptDeviceId);
-    PM_VERIFY_NON_NULL(TAG, tempSecondCred, OC_STACK_ERROR, ERROR);
+    tempSecondCred =  GenerateCredential(firstDeviceId, type, NULL, &privKey, 1, ptDeviceId);
+    VERIFY_NON_NULL(TAG, tempSecondCred, ERROR);
 
     *firstCred = tempFirstCred;
     *secondCred = tempSecondCred;
     res = OC_STACK_OK;
 
-bail:
+exit:
     OICFree(privData);
-    OICFree(base64Buff);
 
     if(res != OC_STACK_OK)
     {
@@ -120,95 +94,27 @@ bail:
 }
 
 #ifdef __WITH_X509__
-/**
- * Function to compose JSON Web Key (JWK) string from a certificate and a public key.
- *
- * @param[in]  certificateChain    Array of Base64 encoded certificate strings.
- * @param[in]  chainLength         Number of the certificates in certificateChain.
- * @return     Valid JWK string on success, or NULL on fail.
- */
-static char *CreateCertificatePublicJWK(const char *const *certificateChain,
-                                        const size_t chainLength)
+static void writeCertPrefix(uint8_t *prefix, uint32_t certLen)
 {
-    if (NULL == certificateChain || chainLength == 0)
-    {
-        OIC_LOG(ERROR, TAG, "Error CreateCertificatePublicJWK: Invalid params");
-        return NULL;
-    }
-
-    size_t certChainSize = 0;
-    for (size_t i = 0; i < chainLength; ++i)
-    {
-        if (NULL != certificateChain[i])
-        {
-            certChainSize += strlen(certificateChain[i]);
-        }
-        else
-        {
-            OIC_LOG(ERROR, TAG, "Error CreateCertificatePublicJWK: Invalid params");
-            return NULL;
-        }
-
-    }
-    /* certificates in the json array taken in quotes and separated by a comma
-     * so we have to count the number of characters (number of commas and quotes) required
-     * for embedding certificates in the array depending on the number of certificates in chain
-     * each certificate except last embeded in  "\"%s\"," */
-    const int numCommasAndQuotes = chainLength * 3 - 1;
-    const char firstPart[] = "{\"kty\":\"EC\",\"crv\":\"P-256\",\"x5c\":[";
-    const char secondPart[] = "]}";
-    /* to calculate the size of JWK public part we need to add the value of first and  second parts,
-     * size of certificate chain, number of additional commas and quotes and 1 for string termination symbol */
-    size_t certPubJWKLen = strlen(firstPart) + strlen(secondPart)
-                                             + certChainSize + numCommasAndQuotes + 1;
-    char *certPubJWK = (char *)OICMalloc(certPubJWKLen);
-
-    if (NULL != certPubJWK)
+    for (size_t i = 0; i < CERT_LEN_PREFIX; ++i)
     {
-        OICStrcpy(certPubJWK, certPubJWKLen, firstPart);
-        size_t offset = strlen(firstPart);
-        for (size_t i = 0; i < chainLength; ++i)
-        {
-            offset += snprintf(certPubJWK + offset, certPubJWKLen - offset, "\"%s\",", certificateChain[i]);
-        }
-        snprintf(certPubJWK + offset - 1, certPubJWK - offset - 1, secondPart);
-    }
-    else
-    {
-        OIC_LOG(ERROR, TAG, "Error while memory allocation");
+        prefix[i] = (certLen >> (BYTE_SIZE * (CERT_LEN_PREFIX - 1 - i))) & 0xFF;
     }
-    return certPubJWK;
 }
 
-/**
- * Function to compose JWK string from a private key.
- *
- * @param[in]  privateKey    Base64 encoded private key.
- * @return     Valid JWK string on success, or NULL on fail.
- */
-static char *CreateCertificatePrivateJWK(const char *privateKey)
+static uint32_t appendCert2Chain(uint8_t *appendPoint, uint8_t *cert, size_t len)
 {
-    if (NULL == privateKey)
-    {
-        OIC_LOG(ERROR, TAG, "Error privateKey is NULL");
-        return NULL;
-    }
-    const char firstPart[] = "{\"kty\":\"EC\",\"crv\":\"P-256\",\"d\":\"";
-    const char secondPart[] = "\"}";
-    size_t len = strlen(firstPart) + strlen(secondPart) + strlen(privateKey) + 1;
-    char *certPrivJWK = (char *)OICMalloc(len);
+    uint32_t ret = 0;
+    VERIFY_NON_NULL(TAG, appendPoint, ERROR);
+    VERIFY_NON_NULL(TAG, cert, ERROR);
 
-    if (NULL != certPrivJWK)
-    {
-        snprintf(certPrivJWK, len, "%s%s%s", firstPart, privateKey, secondPart);
-    }
-    else
-    {
-        OIC_LOG(ERROR, TAG, "Error while memory allocation");
-    }
-    return certPrivJWK;
-}
+    memcpy(appendPoint + CERT_LEN_PREFIX, cert, len);
+    writeCertPrefix(appendPoint, len);
 
+    ret = len + CERT_LEN_PREFIX;
+exit:
+    return ret;
+}
 
 /**
  * Function to generate Base64 encoded credential data for device.
@@ -219,15 +125,15 @@ static char *CreateCertificatePrivateJWK(const char *privateKey)
  * @param[out]  privKey             Pointer to Base64 encoded private key.
  * @return  OC_STACK_OK on success
  */
-static OCStackResult GenerateCertificateAndKeys(const OicUuid_t * subject, char *** const certificateChain,
-        size_t * const chainLength, char ** const privKey)
+static OCStackResult GenerateCertificateAndKeys(const OicUuid_t * subject, OicSecCert_t * certificateChain,
+        OicSecKey_t * privKey)
 {
-    if (NULL == subject || NULL == certificateChain || NULL == chainLength || NULL == privKey)
+    if (NULL == subject || NULL == certificateChain || NULL == privKey)
     {
         return  OC_STACK_INVALID_PARAM;
     }
-    *certificateChain = NULL;
-    *privKey     = NULL;
+    certificateChain->data = NULL;
+    privKey->data = NULL;
 
     ByteArray pubKeyBA  = BYTE_ARRAY_INITIALIZER;
     ByteArray privKeyBA = BYTE_ARRAY_INITIALIZER;
@@ -262,84 +168,52 @@ static OCStackResult GenerateCertificateAndKeys(const OicUuid_t * subject, char
         return OC_STACK_ERROR;
     }
 
-    char privB64buf[B64ENCODE_OUT_SAFESIZE(PRIVATE_KEY_SIZE) + 1] = {0};
-    uint32_t privB64len = 0;
-    if (B64_OK != b64Encode(privKeyBA.data,  privKeyBA.len, privB64buf,
-                             B64ENCODE_OUT_SAFESIZE(PRIVATE_KEY_SIZE) + 1, &privB64len))
-    {
-        OIC_LOG(ERROR, TAG, "Error while encoding key");
-        return OC_STACK_ERROR;
-    }
-
-    if (PKI_SUCCESS != GetCAChain(chainLength , cert + 1))
+    uint8_t numCert = 0;
+    if (PKI_SUCCESS != GetCAChain(&numCert , cert + 1))
     {
         OIC_LOG(ERROR, TAG, "Error getting CA certificate chain.");
         return OC_STACK_ERROR;
     }
 
-    ++(*chainLength);
-    *certificateChain = (char **)OICMalloc(sizeof(char *) * (*chainLength));
-
-    OCStackResult ret = OC_STACK_NO_MEMORY;
-    if (NULL == *certificateChain)
-    {
-        goto memclean;
-    }
-
-
-    for (size_t i = 0; i < *chainLength; ++i)
+    numCert ++;
+    uint32_t len = 0;
+    for (size_t i = 0; i < numCert; ++i)
     {
-        (*certificateChain)[i] = NULL;
-
-        char certB64buf[B64ENCODE_OUT_SAFESIZE(ISSUER_MAX_CERT_SIZE) + 1] = {0};
-        uint32_t certB64len = 0;
-        if (B64_OK != b64Encode(cert[i].data, cert[i].len, certB64buf,
-                                B64ENCODE_OUT_SAFESIZE(ISSUER_MAX_CERT_SIZE) + 1, &certB64len))
+        certificateChain->data = (uint8_t *) OICRealloc(certificateChain->data, len + cert[i].len + CERT_LEN_PREFIX);
+        if (NULL == certificateChain->data)
         {
-            OIC_LOG(ERROR, TAG, "Error while encoding certificate");
-            ret = OC_STACK_ERROR;
-            goto memclean;
+            OIC_LOG(ERROR, TAG, "Error while memory allocation");
+            return OC_STACK_ERROR;
         }
 
-        (*certificateChain)[i] = (char *) OICMalloc(certB64len + 1);
-        if (NULL == (*certificateChain)[i])
+        uint32_t appendedLen = appendCert2Chain(certificateChain->data + len, cert[i].data,
+                                              cert[i].len);
+        //TODO function check len
+        if (0 == appendedLen)
         {
-            goto memclean;
+            OIC_LOG(ERROR, TAG, "Error while certifiacate chain creation.");
+            OICFree(certificateChain->data);
+            certificateChain->len = 0;
+            return OC_STACK_ERROR;
         }
-
-        memcpy((*certificateChain)[i], certB64buf, certB64len + 1);
+        len += appendedLen;
     }
-
-
-    *privKey     = (char *)OICMalloc(privB64len + 1);
-
-    if (NULL == *privKey)
+    certificateChain->len = len;
+    privKey->data = (uint8_t*) OICMalloc(PRIVATE_KEY_SIZE);
+    if (NULL == privKey->data)
     {
-memclean:
-        if (NULL != *certificateChain)
-        {
-            for (size_t i = 0; i < *chainLength; ++i)
-            {
-                OICFree((*certificateChain)[i]);
-            }
-        }
-        OICFree(*certificateChain);
-        *certificateChain = NULL;
-        *privKey     = NULL;
-        *chainLength = 0;
-        if (OC_STACK_NO_MEMORY == ret)
-        {
-            OIC_LOG(ERROR, TAG, "Error while memory allocation");
-        }
-        return ret;
+        OIC_LOG(ERROR, TAG, "Error while memory allocation");
+        OICFree(certificateChain->data);
+        certificateChain->len = 0;
+        privKey->len = 0;
+        return OC_STACK_ERROR;
     }
-
-    memcpy(*privKey, privB64buf, privB64len + 1);
+    memcpy(privKey->data, privKeyData, PRIVATE_KEY_SIZE);
+    privKey->len = PRIVATE_KEY_SIZE;
 
     return OC_STACK_OK;
 }
 
-
 OCStackResult PMGenerateCertificateCredentials(const OicUuid_t *ptDeviceId,
         const OicUuid_t *deviceId, OicSecCred_t **const cred)
 {
@@ -347,42 +221,16 @@ OCStackResult PMGenerateCertificateCredentials(const OicUuid_t *ptDeviceId,
     {
         return OC_STACK_INVALID_PARAM;
     }
-    char **certificateChain = NULL;
-    char *privKey = NULL;
-    size_t certChainLen = 0;
-    if (OC_STACK_OK != GenerateCertificateAndKeys(deviceId, &certificateChain,
-            &certChainLen, &privKey))
+    OicSecCert_t certificateChain;
+    OicSecKey_t privKey;
+    if (OC_STACK_OK != GenerateCertificateAndKeys(deviceId, &certificateChain, &privKey))
     {
         OIC_LOG(ERROR, TAG, "Error while generating credential data.");
         return OC_STACK_ERROR;
     }
 
-    char *publicJWK = CreateCertificatePublicJWK(certificateChain, certChainLen);
-    char *privateJWK = CreateCertificatePrivateJWK(privKey);
-    for (size_t i = 0; i < certChainLen; ++i)
-    {
-        OICFree(certificateChain[i]);
-    }
-    OICFree(certificateChain);
-    OICFree(privKey);
-    if (NULL == publicJWK || NULL == privateJWK)
-    {
-        OICFree(publicJWK);
-        OICFree(privateJWK);
-        OIC_LOG(ERROR, TAG, "Error while converting keys to JWK format.");
-        return OC_STACK_ERROR;
-    }
-
-    OicSecCred_t *tempCred =  GenerateCredential(deviceId, SIGNED_ASYMMETRIC_KEY, publicJWK,
-                              privateJWK, 1, ptDeviceId);
-    OICFree(publicJWK);
-    OICFree(privateJWK);
-    if (NULL == tempCred)
-    {
-        OIC_LOG(ERROR, TAG, "Error while generating credential.");
-        return OC_STACK_ERROR;
-    }
-    *cred = tempCred;
+    *cred = GenerateCredential(deviceId, SIGNED_ASYMMETRIC_KEY, &certificateChain,
+                              &privKey, 1, ptDeviceId);
     return OC_STACK_OK;
 }
 #endif // __WITH_X509__
index 486cf73..b797f98 100644 (file)
@@ -58,6 +58,8 @@
 #include "srmutility.h"
 #include "provisioningdatabasemanager.h"
 #include "oxmrandompin.h"
+#include "ocpayload.h"
+#include "payload_logging.h"
 
 #define TAG "OTM"
 
@@ -93,8 +95,7 @@ static OTMContext_t* g_otmCtx = NULL;
  * @return  OC_STACK_OK on success
  */
 static OCStackResult SelectProvisioningMethod(const OicSecOxm_t *supportedMethods,
-                                                            size_t numberOfMethods,
-                                                            OicSecOxm_t *selectedMethod)
+        size_t numberOfMethods, OicSecOxm_t *selectedMethod)
 {
     OIC_LOG(DEBUG, TAG, "IN SelectProvisioningMethod");
 
@@ -422,6 +423,7 @@ static OCStackResult SaveOwnerPSK(OCProvisionDev_t *selectedDeviceInfo)
     }
 
     uint8_t ownerPSK[OWNER_PSK_LENGTH_128] = {0};
+    OicSecKey_t ownerKey = {ownerPSK, OWNER_PSK_LENGTH_128};
 
     //Generating OwnerPSK
     CAResult_t pskRet = CAGenerateOwnerPSK(&endpoint,
@@ -437,16 +439,10 @@ static OCStackResult SaveOwnerPSK(OCProvisionDev_t *selectedDeviceInfo)
         OIC_LOG_BUFFER(INFO, TAG,ownerPSK, OWNER_PSK_LENGTH_128);
         //Generating new credential for provisioning tool
         size_t ownLen = 1;
-        uint32_t outLen = 0;
-
-        char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(ownerPSK)) + 1] = {};
-        B64Result b64Ret = b64Encode(ownerPSK, sizeof(ownerPSK), base64Buff, sizeof(base64Buff),
-                &outLen);
-        VERIFY_SUCCESS(TAG, B64_OK == b64Ret, ERROR);
 
         OicSecCred_t *cred = GenerateCredential(&selectedDeviceInfo->doxm->deviceID,
                 SYMMETRIC_PAIR_WISE_KEY, NULL,
-                base64Buff, ownLen, &ptDeviceID);
+                &ownerKey, ownLen, &ptDeviceID);
         VERIFY_NON_NULL(TAG, cred, ERROR);
 
         res = AddCredential(cred);
@@ -543,12 +539,14 @@ static OCStackApplicationResult ListMethodsHandler(void *ctx, OCDoHandle UNUSED,
             SetResult(otmCtx, OC_STACK_ERROR);
             return OC_STACK_DELETE_TRANSACTION;
         }
-
-        OicSecPstat_t* pstat = JSONToPstatBin(
-                ((OCSecurityPayload*)clientResponse->payload)->securityData);
-        if(NULL == pstat)
+        OicSecPstat_t* pstat = NULL;
+        OCStackResult result = CBORPayloadToPstat(
+                ((OCSecurityPayload*)clientResponse->payload)->securityData1,
+                ((OCSecurityPayload*)clientResponse->payload)->payloadSize,
+                &pstat);
+        if(NULL == pstat && result != OC_STACK_OK)
         {
-            OIC_LOG(ERROR, TAG, "Error while converting json to pstat bin");
+            OIC_LOG(ERROR, TAG, "Error while converting cbor to pstat.");
             SetResult(otmCtx, OC_STACK_ERROR);
             return OC_STACK_DELETE_TRANSACTION;
         }
@@ -910,8 +908,7 @@ static OCStackResult PutOwnerCredential(OTMContext_t* otmCtx)
 
     //Generate owner credential for new device
     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
-    OicSecCred_t* ownerCredential =
-        GetCredResourceData(&(deviceInfo->doxm->deviceID));
+    OicSecCred_t* ownerCredential = GetCredResourceData(&(deviceInfo->doxm->deviceID));
     if(!ownerCredential)
     {
         OIC_LOG(ERROR, TAG, "Can not find OwnerPSK.");
@@ -930,16 +927,20 @@ static OCStackResult PutOwnerCredential(OTMContext_t* otmCtx)
 
         //Fill private data as empty string
         newCredential.privateData.data = NULL;
+        newCredential.privateData.len = 0;
+#ifdef __WITH_X509__
+        newCredential.publicData.data = NULL;
+        newCredential.publicData.len = 0;
+#endif
 
         //Send owner credential to new device : PUT /oic/sec/cred [ owner credential ]
-        secPayload->securityData = BinToCredJSON(&newCredential);
-        if (NULL == secPayload->securityData)
+        if (OC_STACK_OK != CredToCBORPayload(&newCredential, &secPayload->securityData1, &secPayload->payloadSize))
         {
             OICFree(secPayload);
-            OIC_LOG(ERROR, TAG, "Error while converting bin to json");
+            OIC_LOG(ERROR, TAG, "Error while converting bin to cbor.");
             return OC_STACK_ERROR;
         }
-        OIC_LOG_V(DEBUG, TAG, "Payload : %s", secPayload->securityData);
+        OIC_LOG_V(DEBUG, TAG, "Payload : %s", secPayload->securityData1);
 
         OCCallbackData cbData;
         cbData.cb = &OwnerCredentialHandler;
@@ -994,11 +995,12 @@ static OCStackResult PutOwnerTransferModeToResource(OTMContext_t* otmCtx)
         return OC_STACK_NO_MEMORY;
     }
     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
-    secPayload->securityData = g_OTMDatas[selectedOxm].createSelectOxmPayloadCB(otmCtx);
-    if (NULL == secPayload->securityData)
+    OCStackResult res = g_OTMDatas[selectedOxm].createSelectOxmPayloadCB(otmCtx,
+            &secPayload->securityData1, &secPayload->payloadSize);
+    if (OC_STACK_OK != res && NULL == secPayload->securityData1)
     {
-        OICFree(secPayload);
-        OIC_LOG(ERROR, TAG, "Error while converting bin to json");
+        OCPayloadDestroy((OCPayload *)secPayload);
+        OIC_LOG(ERROR, TAG, "Error while converting bin to cbor");
         return OC_STACK_ERROR;
     }
 
@@ -1006,9 +1008,9 @@ static OCStackResult PutOwnerTransferModeToResource(OTMContext_t* otmCtx)
     cbData.cb = &OwnerTransferModeHandler;
     cbData.context = (void *)otmCtx;
     cbData.cd = NULL;
-    OCStackResult res = OCDoResource(NULL, OC_REST_PUT, query,
-                                     &deviceInfo->endpoint, (OCPayload*)secPayload,
-                                     deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
+    res = OCDoResource(NULL, OC_REST_PUT, query,
+                       &deviceInfo->endpoint, (OCPayload *)secPayload,
+                       deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
     if (res != OC_STACK_OK)
     {
         OIC_LOG(ERROR, TAG, "OCStack resource error");
@@ -1087,23 +1089,23 @@ static OCStackResult PutOwnerUuid(OTMContext_t* otmCtx)
         return OC_STACK_NO_MEMORY;
     }
     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
-    secPayload->securityData =
-        g_OTMDatas[deviceInfo->doxm->oxmSel].createOwnerTransferPayloadCB(otmCtx);
-    if (NULL == secPayload->securityData)
+    OCStackResult res =  g_OTMDatas[deviceInfo->doxm->oxmSel].createOwnerTransferPayloadCB(
+            otmCtx, &secPayload->securityData1, &secPayload->payloadSize);
+    if (NULL == secPayload->securityData1)
     {
-        OICFree(secPayload);
-        OIC_LOG(ERROR, TAG, "Error while converting doxm bin to json");
+        OCPayloadDestroy((OCPayload *)secPayload);
+        OIC_LOG(ERROR, TAG, "Error while converting doxm bin to cbor.");
         return OC_STACK_INVALID_PARAM;
     }
-    OIC_LOG_V(DEBUG, TAG, "Payload : %s", secPayload->securityData);
+    OIC_LOG_V(DEBUG, TAG, "Payload : %s", secPayload->securityData1);
 
     OCCallbackData cbData;
     cbData.cb = &OwnerUuidUpdateHandler;
     cbData.context = (void *)otmCtx;
     cbData.cd = NULL;
 
-    OCStackResult res = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload*)secPayload,
-                                     deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
+    res = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload *)secPayload,
+            deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
     if (res != OC_STACK_OK)
     {
         OIC_LOG(ERROR, TAG, "OCStack resource error");
@@ -1137,30 +1139,32 @@ static OCStackResult PutOwnershipInformation(OTMContext_t* otmCtx)
     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
 
     //OwnershipInformationHandler
-    OCSecurityPayloadsecPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
-    if(!secPayload)
+    OCSecurityPayload *secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
+    if (!secPayload)
     {
         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
         return OC_STACK_NO_MEMORY;
     }
 
     otmCtx->selectedDeviceInfo->doxm->owned = true;
-    secPayload->securityData = BinToDoxmJSON(otmCtx->selectedDeviceInfo->doxm);
-    if (NULL == secPayload->securityData)
+
+    secPayload->base.type = PAYLOAD_TYPE_SECURITY;
+    OCStackResult res = DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm,
+            &secPayload->securityData1, &secPayload->payloadSize);
+    if (OC_STACK_OK != res && NULL == secPayload->securityData1)
     {
-        OICFree(secPayload);
+        OCPayloadDestroy((OCPayload *)secPayload);
         OIC_LOG(ERROR, TAG, "Error while converting doxm bin to json");
         return OC_STACK_INVALID_PARAM;
     }
-    secPayload->base.type = PAYLOAD_TYPE_SECURITY;
 
     OCCallbackData cbData;
     cbData.cb = &OwnershipInformationHandler;
     cbData.context = (void *)otmCtx;
     cbData.cd = NULL;
 
-    OCStackResult res = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload*)secPayload,
-                                     deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
+    res = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload*)secPayload,
+                       deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
     if (res != OC_STACK_OK)
     {
         OIC_LOG(ERROR, TAG, "OCStack resource error");
@@ -1199,11 +1203,12 @@ static OCStackResult PutUpdateOperationMode(OTMContext_t* otmCtx)
         return OC_STACK_NO_MEMORY;
     }
     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
-    secPayload->securityData = BinToPstatJSON(deviceInfo->pstat);
-    if (NULL == secPayload->securityData)
+    OCStackResult res = PstatToCBORPayload(deviceInfo->pstat, &secPayload->securityData1,
+                                           &secPayload->payloadSize);
+   if (OC_STACK_OK != res)
     {
-        OICFree(secPayload);
-        OIC_LOG(ERROR, TAG, "Error while converting pstat bin to json");
+        OCPayloadDestroy((OCPayload *)secPayload);
+        OIC_LOG(ERROR, TAG, "Error while converting pstat to cbor.");
         return OC_STACK_INVALID_PARAM;
     }
 
@@ -1211,8 +1216,8 @@ static OCStackResult PutUpdateOperationMode(OTMContext_t* otmCtx)
     cbData.cb = &OperationModeUpdateHandler;
     cbData.context = (void *)otmCtx;
     cbData.cd = NULL;
-    OCStackResult res = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload*)secPayload,
-                                     deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
+    res = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload *)secPayload,
+                       deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
     if (res != OC_STACK_OK)
     {
         OIC_LOG(ERROR, TAG, "OCStack resource error");
@@ -1367,7 +1372,122 @@ error:
     OICFree(otmCtx->ctxResultArray);
     OICFree(otmCtx);
     return res;
+}
 
+/**
+ * Callback handler of SRPFinalizeProvisioning.
+ *
+ * @param[in] ctx             ctx value passed to callback from calling function.
+ * @param[in] UNUSED          handle to an invocation
+ * @param[in] clientResponse  Response from queries to remote servers.
+ * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
+ *          and OC_STACK_KEEP_TRANSACTION to keep it.
+ */
+static OCStackApplicationResult FinalizeProvisioningCB(void *ctx, OCDoHandle UNUSED,
+                                                       OCClientResponse *clientResponse)
+{
+    OIC_LOG_V(INFO, TAG, "IN FinalizeProvisioningCB.");
+
+    VERIFY_NON_NULL(TAG, clientResponse, ERROR);
+    VERIFY_NON_NULL(TAG, ctx, ERROR);
+
+    OTMContext_t* otmCtx = (OTMContext_t*)ctx;
+    (void)UNUSED;
+    if(OC_STACK_OK == clientResponse->result)
+    {
+        OCStackResult res = PDMAddDevice(&otmCtx->selectedDeviceInfo->doxm->deviceID);
+
+         if (OC_STACK_OK == res)
+         {
+                OIC_LOG_V(INFO, TAG, "Add device's UUID in PDM_DB");
+                SetResult(otmCtx, OC_STACK_OK);
+                return OC_STACK_DELETE_TRANSACTION;
+         }
+         else
+         {
+              OIC_LOG(ERROR, TAG, "Ownership transfer is complete but adding information to DB is failed.");
+         }
+    }
+exit:
+    return OC_STACK_DELETE_TRANSACTION;
+}
+
+/**
+ * Callback handler of default ACL provisioning.
+ *
+ * @param[in] ctx             ctx value passed to callback from calling function.
+ * @param[in] UNUSED          handle to an invocation
+ * @param[in] clientResponse  Response from queries to remote servers.
+ * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
+ *          and OC_STACK_KEEP_TRANSACTION to keep it.
+ */
+static OCStackApplicationResult ProvisionDefaultACLCB(void *ctx, OCDoHandle UNUSED,
+                                                       OCClientResponse *clientResponse)
+{
+    OIC_LOG_V(INFO, TAG, "IN ProvisionDefaultACLCB.");
+
+    VERIFY_NON_NULL(TAG, clientResponse, ERROR);
+    VERIFY_NON_NULL(TAG, ctx, ERROR);
+
+    OTMContext_t* otmCtx = (OTMContext_t*) ctx;
+    (void)UNUSED;
+
+    if (OC_STACK_RESOURCE_CREATED == clientResponse->result)
+    {
+        OIC_LOG_V(INFO, TAG, "Staring commit hash task.");
+        // TODO hash currently have fixed value 0.
+        uint16_t aclHash = 0;
+        otmCtx->selectedDeviceInfo->pstat->commitHash = aclHash;
+        otmCtx->selectedDeviceInfo->pstat->tm = NORMAL;
+        OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
+        if(!secPayload)
+        {
+            OIC_LOG(ERROR, TAG, "Failed to memory allocation");
+            return OC_STACK_NO_MEMORY;
+        }
+        secPayload->base.type = PAYLOAD_TYPE_SECURITY;
+        OCStackResult res = PstatToCBORPayload(otmCtx->selectedDeviceInfo->pstat,
+                &secPayload->securityData1, &secPayload->payloadSize);
+        if (OC_STACK_OK != res || NULL == secPayload->securityData1)
+        {
+            OICFree(secPayload);
+            SetResult(otmCtx, OC_STACK_INVALID_JSON);
+            return OC_STACK_DELETE_TRANSACTION;
+        }
+
+        char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
+        if(!PMGenerateQuery(true,
+                            otmCtx->selectedDeviceInfo->endpoint.addr,
+                            otmCtx->selectedDeviceInfo->securePort,
+                            otmCtx->selectedDeviceInfo->connType,
+                            query, sizeof(query), OIC_RSRC_PSTAT_URI))
+        {
+            OIC_LOG(ERROR, TAG, "ProvisionDefaultACLCB : Failed to generate query");
+            return OC_STACK_ERROR;
+        }
+        OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
+
+        OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
+        cbData.cb = &FinalizeProvisioningCB;
+        cbData.context = (void*)otmCtx;
+        cbData.cd = NULL;
+        OCStackResult ret = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload*)secPayload,
+                otmCtx->selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
+        OIC_LOG_V(INFO, TAG, "OCDoResource returned: %d",ret);
+        if (ret != OC_STACK_OK)
+        {
+            OIC_LOG(ERROR, TAG, "OCStack resource error");
+            SetResult(otmCtx, ret);
+        }
+    }
+    else
+    {
+        OIC_LOG_V(INFO, TAG, "Error occured in provisionDefaultACLCB :: %d\n",
+                            clientResponse->result);
+        SetResult(otmCtx, clientResponse->result);
+    }
+exit:
+    return OC_STACK_DELETE_TRANSACTION;
 }
 
 OCStackResult PutProvisioningStatus(OTMContext_t* otmCtx)
@@ -1389,21 +1509,21 @@ OCStackResult PutProvisioningStatus(OTMContext_t* otmCtx)
     otmCtx->selectedDeviceInfo->pstat->tm = NORMAL;
     otmCtx->selectedDeviceInfo->pstat->cm = PROVISION_ACLS | PROVISION_CREDENTIALS |
                                             SECURITY_MANAGEMENT_SERVICES | BOOTSTRAP_SERVICE;
-    OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
-    if(!secPayload)
+    OCSecurityPayload *secPayload = (OCSecurityPayload *)OICCalloc(1, sizeof(OCSecurityPayload));
+    if (!secPayload)
     {
         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
         return OC_STACK_NO_MEMORY;
     }
     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
-    secPayload->securityData = BinToPstatJSON(otmCtx->selectedDeviceInfo->pstat);
-    if (NULL == secPayload->securityData)
+    if (OC_STACK_OK != PstatToCBORPayload(otmCtx->selectedDeviceInfo->pstat,
+            &secPayload->securityData1, &secPayload->payloadSize))
     {
-        OICFree(secPayload);
+        OCPayloadDestroy((OCPayload *)secPayload);
         SetResult(otmCtx, OC_STACK_INVALID_JSON);
         return OC_STACK_INVALID_JSON;
     }
-    OIC_LOG_V(INFO, TAG, "Created payload for commit hash: %s",secPayload->securityData);
+    OIC_LOG_V(INFO, TAG, "Created payload for commit hash: %s",secPayload->securityData1);
 
     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
     if(!PMGenerateQuery(true,
@@ -1434,4 +1554,3 @@ OCStackResult PutProvisioningStatus(OTMContext_t* otmCtx)
 
     return ret;
 }
-
index ca65bdd..a0f1e96 100644 (file)
 
 #define TAG "OXM_JustWorks"
 
-char* CreateJustWorksSelectOxmPayload(OTMContext_t* otmCtx)
+OCStackResult CreateJustWorksSelectOxmPayload(OTMContext_t *otmCtx, uint8_t **payload, size_t *size)
 {
-    if(!otmCtx || !otmCtx->selectedDeviceInfo)
+    if (!otmCtx || !otmCtx->selectedDeviceInfo || !payload || *payload || !size)
     {
-        return NULL;
+        return OC_STACK_INVALID_PARAM;
     }
 
     otmCtx->selectedDeviceInfo->doxm->oxmSel = OIC_JUST_WORKS;
-    return BinToDoxmJSON(otmCtx->selectedDeviceInfo->doxm);
+    *payload = NULL;
+    *size = 0;
+
+    return DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm, payload, size);
 }
 
-char* CreateJustWorksOwnerTransferPayload(OTMContext_t* otmCtx)
+OCStackResult CreateJustWorksOwnerTransferPayload(OTMContext_t* otmCtx, uint8_t **payload, size_t *size)
 {
-    if(!otmCtx || !otmCtx->selectedDeviceInfo)
+    if (!otmCtx || !otmCtx->selectedDeviceInfo || !payload || *payload || !size)
     {
-        return NULL;
+        return OC_STACK_INVALID_PARAM;
     }
 
     OicUuid_t uuidPT = {.id={0}};
@@ -55,11 +58,14 @@ char* CreateJustWorksOwnerTransferPayload(OTMContext_t* otmCtx)
     if (OC_STACK_OK != GetDoxmDeviceID(&uuidPT))
     {
         OIC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
-        return NULL;
+        return OC_STACK_ERROR;
     }
     memcpy(otmCtx->selectedDeviceInfo->doxm->owner.id, uuidPT.id , UUID_LENGTH);
 
-    return BinToDoxmJSON(otmCtx->selectedDeviceInfo->doxm);
+    *payload = NULL;
+    *size = 0;
+
+    return DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm, payload, size);
 }
 
 OCStackResult LoadSecretJustWorksCallback(OTMContext_t* UNUSED_PARAM)
@@ -72,7 +78,7 @@ OCStackResult LoadSecretJustWorksCallback(OTMContext_t* UNUSED_PARAM)
 OCStackResult CreateSecureSessionJustWorksCallback(OTMContext_t* otmCtx)
 {
     OIC_LOG(INFO, TAG, "IN CreateSecureSessionJustWorksCallback");
-    if(!otmCtx || !otmCtx->selectedDeviceInfo)
+    if (!otmCtx || !otmCtx->selectedDeviceInfo)
     {
         return OC_STACK_INVALID_PARAM;
     }
@@ -102,13 +108,13 @@ OCStackResult CreateSecureSessionJustWorksCallback(OTMContext_t* otmCtx)
     }
     OIC_LOG(INFO, TAG, "TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256 cipher suite selected.");
 
-    OCProvisionDev_tselDevInfo = otmCtx->selectedDeviceInfo;
+    OCProvisionDev_t *selDevInfo = otmCtx->selectedDeviceInfo;
     CAEndpoint_t *endpoint = (CAEndpoint_t *)OICCalloc(1, sizeof (CAEndpoint_t));
     if(NULL == endpoint)
     {
         return OC_STACK_NO_MEMORY;
     }
-    memcpy(endpoint,&selDevInfo->endpoint,sizeof(CAEndpoint_t));
+    memcpy(endpoint, &selDevInfo->endpoint, sizeof(CAEndpoint_t));
     endpoint->port = selDevInfo->securePort;
 
     caresult = CAInitiateHandshake(endpoint);
index 138c274..4efc238 100644 (file)
 
 #define TAG "OXM_RandomPIN"
 
-char* CreatePinBasedSelectOxmPayload(OTMContext_t* otmCtx)
+OCStackResult CreatePinBasedSelectOxmPayload(OTMContext_t* otmCtx, uint8_t **payload, size_t *size)
 {
-    if(!otmCtx || !otmCtx->selectedDeviceInfo)
+    if(!otmCtx || !otmCtx->selectedDeviceInfo || !payload || *payload || !size)
     {
-        return NULL;
+        return OC_STACK_INVALID_PARAM;
     }
 
     otmCtx->selectedDeviceInfo->doxm->oxmSel = OIC_RANDOM_DEVICE_PIN;
 
-    return BinToDoxmJSON(otmCtx->selectedDeviceInfo->doxm);
+    return DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm, payload, size);
 }
 
-char* CreatePinBasedOwnerTransferPayload(OTMContext_t* otmCtx)
+OCStackResult CreatePinBasedOwnerTransferPayload(OTMContext_t* otmCtx, uint8_t **payload, size_t *size)
 {
-    if(!otmCtx || !otmCtx->selectedDeviceInfo)
+    if(!otmCtx || !otmCtx->selectedDeviceInfo || !payload || *payload || !size)
     {
-        return NULL;
+        return OC_STACK_INVALID_PARAM;
     }
 
     OicUuid_t uuidPT = {.id={0}};
+    *payload = NULL;
+    *size = 0;
 
     if (OC_STACK_OK != GetDoxmDeviceID(&uuidPT))
     {
         OIC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
-        return NULL;
+        return OC_STACK_ERROR;
     }
     memcpy(otmCtx->selectedDeviceInfo->doxm->owner.id, uuidPT.id , UUID_LENGTH);
 
-    return BinToDoxmJSON(otmCtx->selectedDeviceInfo->doxm);
+    return DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm, payload, size);
 }
 
-OCStackResult InputPinCodeCallback(OTMContext_totmCtx)
+OCStackResult InputPinCodeCallback(OTMContext_t *otmCtx)
 {
-    if(!otmCtx || !otmCtx->selectedDeviceInfo)
+    if (!otmCtx || !otmCtx->selectedDeviceInfo)
     {
         return OC_STACK_INVALID_PARAM;
     }
@@ -79,7 +81,7 @@ OCStackResult InputPinCodeCallback(OTMContext_t* otmCtx)
     uint8_t pinData[OXM_RANDOM_PIN_SIZE + 1];
 
     OCStackResult res = InputPin((char*)pinData, OXM_RANDOM_PIN_SIZE + 1);
-    if(OC_STACK_OK != res)
+    if (OC_STACK_OK != res)
     {
         OIC_LOG(ERROR, TAG, "Failed to input PIN");
         return res;
@@ -106,7 +108,7 @@ OCStackResult CreateSecureSessionRandomPinCallback(OTMContext_t* otmCtx)
 {
     OIC_LOG(INFO, TAG, "IN CreateSecureSessionRandomPinCallbak");
 
-    if(!otmCtx || !otmCtx->selectedDeviceInfo)
+    if (!otmCtx || !otmCtx->selectedDeviceInfo)
     {
         return OC_STACK_INVALID_PARAM;
     }
@@ -127,10 +129,9 @@ OCStackResult CreateSecureSessionRandomPinCallback(OTMContext_t* otmCtx)
     }
     OIC_LOG(INFO, TAG, "TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256 cipher suite selected.");
 
-
     OCProvisionDev_t* selDevInfo = otmCtx->selectedDeviceInfo;
     CAEndpoint_t *endpoint = (CAEndpoint_t *)OICCalloc(1, sizeof (CAEndpoint_t));
-    if(NULL == endpoint)
+    if (NULL == endpoint)
     {
         return OC_STACK_NO_MEMORY;
     }
@@ -148,4 +149,3 @@ OCStackResult CreateSecureSessionRandomPinCallback(OTMContext_t* otmCtx)
 
     return OC_STACK_OK;
 }
-
index 2e4158b..648ca05 100644 (file)
@@ -489,16 +489,19 @@ static OCStackApplicationResult DeviceDiscoveryHandler(void *ctx, OCDoHandle UNU
                 OIC_LOG(INFO, TAG, "Unknown payload type");
                 return OC_STACK_KEEP_TRANSACTION;
             }
-            OicSecDoxm_t *ptrDoxm = JSONToDoxmBin(
-                            ((OCSecurityPayload*)clientResponse->payload)->securityData);
-            if (NULL == ptrDoxm)
+
+            OicSecDoxm_t *ptrDoxm = NULL;
+            uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData1;
+            size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
+            OCStackResult res = CBORPayloadToDoxm(payload, size, &ptrDoxm);
+            if ((NULL == ptrDoxm) && (OC_STACK_OK != res))
             {
-                OIC_LOG(INFO, TAG, "Ignoring malformed JSON");
+                OIC_LOG(INFO, TAG, "Ignoring malformed CBOR");
                 return OC_STACK_KEEP_TRANSACTION;
             }
             else
             {
-                OIC_LOG(DEBUG, TAG, "Successfully converted doxm json to bin.");
+                OIC_LOG(DEBUG, TAG, "Successfully converted doxm cbor to bin.");
 
                 //If this is owend device discovery we have to filter out the responses.
                 DiscoveryInfo* pDInfo = (DiscoveryInfo*)ctx;
index d3056c0..ede10b2 100644 (file)
@@ -40,6 +40,7 @@
 #include "provisioningdatabasemanager.h"
 #include "base64.h"
 #include "utlist.h"
+#include "ocpayload.h"
 
 #ifdef __WITH_X509__
 #include "crlresource.h"
@@ -297,21 +298,21 @@ static OCStackResult provisionCredentials(const OicSecCred_t *cred,
         OCClientResponseHandler responseHandler)
 {
     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
-    if(!secPayload)
+    if (!secPayload)
     {
         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
         return OC_STACK_NO_MEMORY;
     }
     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
-    secPayload->securityData = BinToCredJSON(cred);
-    if(NULL == secPayload->securityData)
+    OCStackResult res = CredToCBORPayload(cred, &secPayload->securityData1, &secPayload->payloadSize);
+    if((OC_STACK_OK != res) && (NULL == secPayload->securityData1))
     {
-        OICFree(secPayload);
-        OIC_LOG(ERROR, TAG, "Failed to BinToCredJSON");
+        OCPayloadDestroy((OCPayload *)secPayload);
+        OIC_LOG(ERROR, TAG, "Failed to CredToCBORPayload");
         return OC_STACK_NO_MEMORY;
     }
 
-    OIC_LOG_V(INFO, TAG, "Credential for provisioning : %s",secPayload->securityData);
+    OIC_LOG_V(INFO, TAG, "Credential for provisioning : %s",secPayload->securityData1);
     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
     if(!PMGenerateQuery(true,
                         deviceInfo->endpoint.addr,
@@ -455,14 +456,14 @@ OCStackResult SRPProvisionCRL(void *ctx, const OCProvisionDev_t *selectedDeviceI
     }
 
     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
-    secPayload->securityData = BinToCrlJSON(crl);
-    if (NULL == secPayload->securityData)
+    OCStackResult res = CrlToCBORPayload(crl, &secPayload->securityData1, &secPayload->payloadSize);
+    if((OC_STACK_OK != res) && (NULL == secPayload->securityData1))
     {
         OICFree(secPayload);
         OIC_LOG(ERROR, TAG, "Failed to BinToCrlJSON");
         return OC_STACK_NO_MEMORY;
     }
-    OIC_LOG_V(INFO, TAG, "CRL : %s", secPayload->securityData);
+    OIC_LOG_V(INFO, TAG, "CRL : %s", secPayload->securityData1);
 
     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
     if(!PMGenerateQuery(true,
@@ -472,8 +473,7 @@ OCStackResult SRPProvisionCRL(void *ctx, const OCProvisionDev_t *selectedDeviceI
                         query, sizeof(query), OIC_RSRC_CRL_URI))
     {
         OIC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
-        OICFree(secPayload->securityData);
-        OICFree(secPayload);
+        OCPayloadDestroy((OCPayload *)secPayload);
         return OC_STACK_ERROR;
     }
     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
@@ -483,8 +483,7 @@ OCStackResult SRPProvisionCRL(void *ctx, const OCProvisionDev_t *selectedDeviceI
     CRLData_t *crlData = (CRLData_t *) OICCalloc(1, sizeof(CRLData_t));
     if (crlData == NULL)
     {
-        OICFree(secPayload->securityData);
-        OICFree(secPayload);
+        OCPayloadDestroy((OCPayload *)secPayload);
         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
         return OC_STACK_NO_MEMORY;
     }
@@ -497,8 +496,7 @@ OCStackResult SRPProvisionCRL(void *ctx, const OCProvisionDev_t *selectedDeviceI
     crlData->resArr = (OCProvisionResult_t*)OICCalloc(1, sizeof(OCProvisionResult_t));
     if (crlData->resArr == NULL)
     {
-        OICFree(secPayload->securityData);
-        OICFree(secPayload);
+        OCPayloadDestroy((OCPayload *)secPayload);
         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
         return OC_STACK_NO_MEMORY;
     }
@@ -541,16 +539,17 @@ static OCStackResult provisionCertCred(const OicSecCred_t *cred,
         return OC_STACK_NO_MEMORY;
     }
     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
-    secPayload->securityData = BinToCredJSON(cred);
+    OCStackResult res = CredToCBORPayload(cred, &secPayload->securityData1,
+        &secPayload->payloadSize);
 
-    if (NULL == secPayload->securityData)
+    if ((OC_STACK_OK != res) || (NULL == secPayload->securityData1))
     {
         OICFree(secPayload);
-        OIC_LOG(ERROR, TAG, "Failed to BinToCredJSON");
+        OIC_LOG(ERROR, TAG, "Failed to CredToCBORPayload");
         return OC_STACK_NO_MEMORY;
     }
 
-    OIC_LOG_V(INFO, TAG, "Credential for provisioning : %s",secPayload->securityData);
+    OIC_LOG_V(INFO, TAG, "Credential for provisioning : %s",secPayload->securityData1);
     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
     if(!PMGenerateQuery(true,
                         deviceInfo->endpoint.addr,
@@ -559,8 +558,7 @@ static OCStackResult provisionCertCred(const OicSecCred_t *cred,
                         query, sizeof(query), OIC_RSRC_CRED_URI))
     {
         OIC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
-        OICFree(secPayload->securityData);
-        OICFree(secPayload);
+        OCPayloadDestroy((OCPayload *)secPayload);
         return OC_STACK_ERROR;
     }
     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
@@ -848,15 +846,12 @@ OCStackResult SRPProvisionACL(void *ctx, const OCProvisionDev_t *selectedDeviceI
         return OC_STACK_NO_MEMORY;
     }
     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
-    secPayload->securityData = BinToAclJSON(acl);
-    if(NULL == secPayload->securityData)
+    if(OC_STACK_OK != AclToCBORPayload(acl, &secPayload->securityData1, &secPayload->payloadSize))
     {
-        OICFree(secPayload);
-        OIC_LOG(ERROR, TAG, "Failed to BinToAclJSON");
+        OCPayloadDestroy((OCPayload *)secPayload);
+        OIC_LOG(ERROR, TAG, "Failed to AclToCBORPayload");
         return OC_STACK_NO_MEMORY;
     }
-    OIC_LOG_V(INFO, TAG, "ACL : %s", secPayload->securityData);
-
     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
     if(!PMGenerateQuery(true,
                         selectedDeviceInfo->endpoint.addr,
@@ -874,8 +869,7 @@ OCStackResult SRPProvisionACL(void *ctx, const OCProvisionDev_t *selectedDeviceI
     ACLData_t *aclData = (ACLData_t *) OICCalloc(1, sizeof(ACLData_t));
     if (aclData == NULL)
     {
-        OICFree(secPayload->securityData);
-        OICFree(secPayload);
+        OCPayloadDestroy((OCPayload *)secPayload);
         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
         return OC_STACK_NO_MEMORY;
     }
@@ -889,8 +883,7 @@ OCStackResult SRPProvisionACL(void *ctx, const OCProvisionDev_t *selectedDeviceI
     if (aclData->resArr == NULL)
     {
         OICFree(aclData);
-        OICFree(secPayload->securityData);
-        OICFree(secPayload);
+        OCPayloadDestroy((OCPayload *)secPayload);
         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
         return OC_STACK_NO_MEMORY;
     }
@@ -917,8 +910,8 @@ OCStackResult SRPProvisionACL(void *ctx, const OCProvisionDev_t *selectedDeviceI
 static void registerResultForDirectPairingProvisioning(PconfData_t *pconfData,
                                              OCStackResult stackresult)
 {
-   OIC_LOG_V(INFO, TAG, "Inside registerResultForDirectPairingProvisioning pconfData->numOfResults is %d\n",
-                       pconfData->numOfResults);
+   OIC_LOG_V(INFO, TAG, "Inside registerResultForDirectPairingProvisioning "
+           "pconfData->numOfResults is %d\n", pconfData->numOfResults);
    memcpy(pconfData->resArr[(pconfData->numOfResults)].deviceId.id,
           pconfData->deviceInfo->doxm->deviceID.id, UUID_LENGTH);
    pconfData->resArr[(pconfData->numOfResults)].res = stackresult;
@@ -995,21 +988,22 @@ OCStackResult SRPProvisionDirectPairing(void *ctx, const OCProvisionDev_t *selec
         return OC_STACK_NO_MEMORY;
     }
     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
-    secPayload->securityData = BinToPconfJSON(pconf);
-    if(NULL == secPayload->securityData)
+
+    if (OC_STACK_OK != PconfToCBORPayload(pconf, &(secPayload->securityData1),
+                &(secPayload->payloadSize)))
     {
-        OICFree(secPayload);
-        OIC_LOG(ERROR, TAG, "Failed to BinToPconfJSON");
+        OCPayloadDestroy((OCPayload*)secPayload);
+        OIC_LOG(ERROR, TAG, "Failed to PconfToCborPayload");
         return OC_STACK_NO_MEMORY;
     }
-    OIC_LOG_V(INFO, TAG, "PCONF : %s", secPayload->securityData);
+    OIC_LOG_V(INFO, TAG, "PCONF : %s", secPayload->securityData1);
 
     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
     if(!PMGenerateQuery(true,
-                        selectedDeviceInfo->endpoint.addr,
-                        selectedDeviceInfo->securePort,
-                        selectedDeviceInfo->connType,
-                        query, sizeof(query), OIC_RSRC_PCONF_URI))
+                selectedDeviceInfo->endpoint.addr,
+                selectedDeviceInfo->securePort,
+                selectedDeviceInfo->connType,
+                query, sizeof(query), OIC_RSRC_PCONF_URI))
     {
         OIC_LOG(ERROR, TAG, "SRPProvisionDirectPairing : Failed to generate query");
         return OC_STACK_ERROR;
@@ -1021,8 +1015,7 @@ OCStackResult SRPProvisionDirectPairing(void *ctx, const OCProvisionDev_t *selec
     PconfData_t *pconfData = (PconfData_t *) OICCalloc(1, sizeof(PconfData_t));
     if (NULL == pconfData)
     {
-        OICFree(secPayload->securityData);
-        OICFree(secPayload);
+        OCPayloadDestroy((OCPayload*)secPayload);
         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
         return OC_STACK_NO_MEMORY;
     }
@@ -1036,8 +1029,7 @@ OCStackResult SRPProvisionDirectPairing(void *ctx, const OCProvisionDev_t *selec
     if (NULL == pconfData->resArr)
     {
         OICFree(pconfData);
-        OICFree(secPayload->securityData);
-        OICFree(secPayload);
+        OCPayloadDestroy((OCPayload*)secPayload);
         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
         return OC_STACK_NO_MEMORY;
     }
index 4e85e79..f0a0eab 100644 (file)
@@ -28,10 +28,10 @@ using namespace std;
 
 TEST(JustWorksOxMTest, NullParam)
 {
-
     OTMContext_t* otmCtx = NULL;
     OCStackResult res = OC_STACK_ERROR;
-    char* payloadRes;
+    uint8_t *payloadRes = NULL;
+    size_t size = 0;
 
     //LoadSecretJustWorksCallback always returns OC_STACK_OK.
     res = LoadSecretJustWorksCallback(otmCtx);
@@ -40,11 +40,11 @@ TEST(JustWorksOxMTest, NullParam)
     res = CreateSecureSessionJustWorksCallback(otmCtx);
     EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 
-    payloadRes = CreateJustWorksSelectOxmPayload(otmCtx);
-    EXPECT_TRUE(NULL == payloadRes);
+    res = CreateJustWorksSelectOxmPayload(otmCtx, &payloadRes, &size);
+    EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 
-    payloadRes = CreateJustWorksOwnerTransferPayload(otmCtx);
-    EXPECT_TRUE(NULL == payloadRes);
+    res = CreateJustWorksOwnerTransferPayload(otmCtx, &payloadRes, &size);
+    EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 
     OTMContext_t otmCtx2;
     otmCtx2.selectedDeviceInfo = NULL;
@@ -56,18 +56,19 @@ TEST(JustWorksOxMTest, NullParam)
     res = CreateSecureSessionJustWorksCallback(&otmCtx2);
     EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 
-    payloadRes = CreateJustWorksSelectOxmPayload(&otmCtx2);
-    EXPECT_TRUE(NULL == payloadRes);
+    res = CreateJustWorksSelectOxmPayload(&otmCtx2, &payloadRes, &size);
+    EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 
-    payloadRes = CreateJustWorksOwnerTransferPayload(&otmCtx2);
-    EXPECT_TRUE(NULL == payloadRes);
+    res = CreateJustWorksOwnerTransferPayload(&otmCtx2, &payloadRes, &size);
+    EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 }
 
 TEST(RandomPinOxMTest, NullParam)
 {
     OTMContext_t* otmCtx = NULL;
     OCStackResult res = OC_STACK_ERROR;
-    char* payloadRes;
+    uint8_t *payloadRes = NULL;
+    size_t size = 0;
 
     //LoadSecretJustWorksCallback always returns OC_STACK_OK.
     res = InputPinCodeCallback(otmCtx);
@@ -76,11 +77,11 @@ TEST(RandomPinOxMTest, NullParam)
     res = CreateSecureSessionRandomPinCallback(otmCtx);
     EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 
-    payloadRes = CreatePinBasedSelectOxmPayload(otmCtx);
-    EXPECT_TRUE(NULL == payloadRes);
+    res = CreatePinBasedSelectOxmPayload(otmCtx, &payloadRes, &size);
+    EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 
-    payloadRes = CreatePinBasedOwnerTransferPayload(otmCtx);
-    EXPECT_TRUE(NULL == payloadRes);
+    res = CreatePinBasedOwnerTransferPayload(otmCtx, &payloadRes, &size);
+    EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 
     OTMContext_t otmCtx2;
     otmCtx2.selectedDeviceInfo = NULL;
@@ -92,9 +93,9 @@ TEST(RandomPinOxMTest, NullParam)
     res = CreateSecureSessionRandomPinCallback(&otmCtx2);
     EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 
-    payloadRes = CreatePinBasedSelectOxmPayload(&otmCtx2);
-    EXPECT_TRUE(NULL == payloadRes);
+    res = CreatePinBasedSelectOxmPayload(&otmCtx2, &payloadRes, &size);
+    EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 
-    payloadRes = CreatePinBasedOwnerTransferPayload(&otmCtx2);
-    EXPECT_TRUE(NULL == payloadRes);
+    res = CreatePinBasedOwnerTransferPayload(&otmCtx2, &payloadRes, &size);
+    EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 }
index e142ca7..745c533 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#include <stdlib.h>
+#ifdef WITH_ARDUINO
 #include <string.h>
+#else
+#include <strings.h>
+#endif
+#include <stdlib.h>
+
 #include "ocstack.h"
-#include "logger.h"
+#include "ocserverrequest.h"
 #include "oic_malloc.h"
 #include "oic_string.h"
-#include "cJSON.h"
-#include "base64.h"
-#include "resourcemanager.h"
-#include "aclresource.h"
-#include "psinterface.h"
+#include "ocrandom.h"
+#include "ocpayload.h"
 #include "utlist.h"
+#include "payload_logging.h"
 #include "srmresourcestrings.h"
+#include "aclresource.h"
 #include "doxmresource.h"
+#include "resourcemanager.h"
 #include "srmutility.h"
-#include "ocserverrequest.h"
-#include <stdlib.h>
-#ifdef WITH_ARDUINO
-#include <string.h>
-#else
-#include <strings.h>
-#endif
+#include "psinterface.h"
+
+#include "security_internals.h"
 
 #define TAG  "SRM-ACL"
 #define NUMBER_OF_SEC_PROV_RSCS 4
 #define NUMBER_OF_DEFAULT_SEC_RSCS 2
 
-OicSecAcl_t               *gAcl = NULL;
-static OCResourceHandle    gAclHandle = NULL;
+// CborSize is the default cbor payload size being used.
+static uint64_t CborSize = 255;
+
+static OicSecAcl_t *gAcl = NULL;
+static OCResourceHandle gAclHandle = NULL;
 
 /**
  * This function frees OicSecAcl_t object's fields and object itself.
@@ -54,9 +58,9 @@ static OCResourceHandle    gAclHandle = NULL;
 static void FreeACE(OicSecAcl_t *ace)
 {
     size_t i;
-    if(NULL == ace)
+    if (NULL == ace)
     {
-        OIC_LOG (ERROR, TAG, "Invalid Parameter");
+        OIC_LOG(ERROR, TAG, "Invalid Parameter");
         return;
     }
 
@@ -68,9 +72,9 @@ static void FreeACE(OicSecAcl_t *ace)
     OICFree(ace->resources);
 
     //Clean Period
-    if(ace->periods)
+    if (ace->periods)
     {
-        for(i = 0; i < ace->prdRecrLen; i++)
+        for (i = 0; i < ace->prdRecrLen; i++)
         {
             OICFree(ace->periods[i]);
         }
@@ -78,9 +82,9 @@ static void FreeACE(OicSecAcl_t *ace)
     }
 
     //Clean Recurrence
-    if(ace->recurrences)
+    if (ace->recurrences)
     {
-        for(i = 0; i < ace->prdRecrLen; i++)
+        for (i = 0; i < ace->prdRecrLen; i++)
         {
             OICFree(ace->recurrences[i]);
         }
@@ -108,298 +112,371 @@ void DeleteACLList(OicSecAcl_t* acl)
     }
 }
 
-/*
- * This internal method converts ACL data into JSON format.
- *
- * Note: Caller needs to invoke 'free' when finished done using
- * return string.
- */
-char * BinToAclJSON(const OicSecAcl_t * acl)
+static size_t OicSecAclSize(const OicSecAcl_t *secAcl)
 {
-    cJSON *jsonRoot = NULL;
-    char *jsonStr = NULL;
-
-    if (acl)
+    if (!secAcl)
+    {
+        return 0;
+    }
+    OicSecAcl_t *acl = (OicSecAcl_t *)secAcl;
+    size_t size = 0;
+    while (acl)
     {
-        jsonRoot = cJSON_CreateObject();
-        VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+       size++;
+       acl = acl->next;
+    }
+    return size;
+}
 
-        cJSON *jsonAclArray = NULL;
-        cJSON_AddItemToObject (jsonRoot, OIC_JSON_ACL_NAME, jsonAclArray = cJSON_CreateArray());
-        VERIFY_NON_NULL(TAG, jsonAclArray, ERROR);
+OCStackResult AclToCBORPayload(const OicSecAcl_t *secAcl, uint8_t **payload, size_t *size)
+{
+    OCStackResult ret = OC_STACK_INVALID_PARAM;
+    int64_t cborEncoderResult = CborNoError;
+    uint8_t *outPayload = NULL;
+    size_t cborLen = *size;
+    *size = 0;
+    *payload = NULL;
+    OicSecAcl_t *acl = (OicSecAcl_t *)secAcl;
+    CborEncoder encoder = { {.ptr = NULL }, .end = 0 };
+    CborEncoder oicSecAclArray = { {.ptr = NULL }, .end = 0 };
+
+    VERIFY_NON_NULL(TAG, secAcl, ERROR);
+
+    if (cborLen == 0)
+    {
+        cborLen = CborSize;
+    }
 
-        while(acl)
-        {
-            char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};
-            uint32_t outLen = 0;
-            size_t inLen = 0;
-            B64Result b64Ret = B64_OK;
+    outPayload = (uint8_t *)OICCalloc(1, cborLen);
+    VERIFY_NON_NULL(TAG, outPayload, ERROR);
+    cbor_encoder_init(&encoder, outPayload, cborLen, 0);
 
-            cJSON *jsonAcl = cJSON_CreateObject();
+    // Create ACL Array
+    cborEncoderResult |= cbor_encoder_create_array(&encoder, &oicSecAclArray, OicSecAclSize(secAcl));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Creating ACL Array.");
 
-            // Subject -- Mandatory
-            outLen = 0;
-            if (memcmp(&(acl->subject), &WILDCARD_SUBJECT_ID, sizeof(OicUuid_t)) == 0)
-            {
-                inLen = WILDCARD_SUBJECT_ID_LEN;
-            }
-            else
-            {
-                inLen =  sizeof(OicUuid_t);
-            }
-            b64Ret = b64Encode(acl->subject.id, inLen, base64Buff,
-                sizeof(base64Buff), &outLen);
-            VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
-            cJSON_AddStringToObject(jsonAcl, OIC_JSON_SUBJECT_NAME, base64Buff );
-
-            // Resources -- Mandatory
-            cJSON *jsonRsrcArray = NULL;
-            cJSON_AddItemToObject (jsonAcl, OIC_JSON_RESOURCES_NAME, jsonRsrcArray = cJSON_CreateArray());
-            VERIFY_NON_NULL(TAG, jsonRsrcArray, ERROR);
+    while (acl)
+    {
+        CborEncoder oicSecAclMap = { {.ptr = NULL }, .end = 0, .added = 0, .flags = 0 };
+        // ACL Map size - Number of mandatory items
+        uint8_t aclMapSize = 4;
+        // Create ACL Map
+        if (acl->periods)
+        {
+            ++aclMapSize;
+        }
+        if (acl->recurrences)
+        {
+            ++aclMapSize;
+        }
+        cborEncoderResult |= cbor_encoder_create_map(&oicSecAclArray, &oicSecAclMap, aclMapSize);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Creating ACL Map");
+
+        // Subject -- Mandatory
+        cborEncoderResult |= cbor_encode_text_string(&oicSecAclMap, OIC_JSON_SUBJECT_NAME,
+            strlen(OIC_JSON_SUBJECT_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Subject Name Tag.");
+        size_t inLen = (memcmp(&(acl->subject), &WILDCARD_SUBJECT_ID, sizeof(OicUuid_t)) == 0) ?
+            WILDCARD_SUBJECT_ID_LEN : sizeof(OicUuid_t);
+        cborEncoderResult |= cbor_encode_byte_string(&oicSecAclMap, (uint8_t *)acl->subject.id, inLen);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding Subject Id Value.");
+
+        // Resources
+        {
+            CborEncoder resources;
+            cborEncoderResult |= cbor_encode_text_string(&oicSecAclMap, OIC_JSON_RESOURCES_NAME,
+                strlen(OIC_JSON_RESOURCES_NAME));
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Resource Name Tag.");
+            cborEncoderResult |= cbor_encoder_create_array(&oicSecAclMap, &resources, acl->resourcesLen);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Resource Name Array.");
             for (size_t i = 0; i < acl->resourcesLen; i++)
             {
-                cJSON_AddItemToArray (jsonRsrcArray, cJSON_CreateString(acl->resources[i]));
+                cborEncoderResult |= cbor_encode_text_string(&resources, acl->resources[i],
+                    strlen(acl->resources[i]));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Resource Name Array Value.");
             }
+            cborEncoderResult |= cbor_encoder_close_container(&oicSecAclMap, &resources);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Resource Name Array.");
+        }
 
-            // Permissions -- Mandatory
-            cJSON_AddNumberToObject (jsonAcl, OIC_JSON_PERMISSION_NAME, acl->permission);
+        // Permissions -- Mandatory
+        cborEncoderResult |= cbor_encode_text_string(&oicSecAclMap, OIC_JSON_PERMISSION_NAME,
+            strlen(OIC_JSON_PERMISSION_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Permission Name Tag.");
+        cborEncoderResult |= cbor_encode_int(&oicSecAclMap, acl->permission);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Permission Name Value.");
 
-            //Period & Recurrence -- Not Mandatory
-            if(0 != acl->prdRecrLen)
+        // Period -- Not Mandatory
+        if (acl->periods)
+        {
+            CborEncoder period;
+            cborEncoderResult |= cbor_encode_text_string(&oicSecAclMap, OIC_JSON_PERIODS_NAME,
+                strlen(OIC_JSON_PERIODS_NAME));
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Period Tag.");
+            cborEncoderResult |= cbor_encoder_create_array(&oicSecAclMap, &period, acl->prdRecrLen);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Period Array.");
+            for (size_t i = 0; i < acl->prdRecrLen; i++)
             {
-                cJSON *jsonPeriodArray = NULL;
-                cJSON_AddItemToObject (jsonAcl, OIC_JSON_PERIODS_NAME,
-                        jsonPeriodArray = cJSON_CreateArray());
-                VERIFY_NON_NULL(TAG, jsonPeriodArray, ERROR);
-                for (size_t i = 0; i < acl->prdRecrLen; i++)
-                {
-                    cJSON_AddItemToArray (jsonPeriodArray,
-                            cJSON_CreateString(acl->periods[i]));
-                }
+                cborEncoderResult |= cbor_encode_text_string(&period, acl->periods[i],
+                    strlen(acl->periods[i]));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Period Value in Array.");
             }
+            cborEncoderResult |= cbor_encoder_close_container(&oicSecAclMap, &period);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Period Array.");
+        }
 
-            //Recurrence -- Not Mandatory
-            if(0 != acl->prdRecrLen && acl->recurrences)
+        // Recurrence -- Not Mandatory
+        if (acl->recurrences)
+        {
+            CborEncoder recurrences;
+            cborEncoderResult |= cbor_encode_text_string(&oicSecAclMap, OIC_JSON_RECURRENCES_NAME,
+                strlen(OIC_JSON_RECURRENCES_NAME));
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Recurrence Tag.");
+            cborEncoderResult |= cbor_encoder_create_array(&oicSecAclMap, &recurrences, acl->prdRecrLen);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Recurrence Array.");
+
+            for (size_t i = 0; i < acl->prdRecrLen; i++)
             {
-                cJSON *jsonRecurArray  = NULL;
-                cJSON_AddItemToObject (jsonAcl, OIC_JSON_RECURRENCES_NAME,
-                        jsonRecurArray = cJSON_CreateArray());
-                VERIFY_NON_NULL(TAG, jsonRecurArray, ERROR);
-                for (size_t i = 0; i < acl->prdRecrLen; i++)
-                {
-                    cJSON_AddItemToArray (jsonRecurArray,
-                            cJSON_CreateString(acl->recurrences[i]));
-                }
+                cborEncoderResult |= cbor_encode_text_string(&recurrences, acl->recurrences[i],
+                    strlen(acl->recurrences[i]));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Recurrence Array Value.");
             }
+            cborEncoderResult |= cbor_encoder_close_container(&oicSecAclMap, &recurrences);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Recurrence Array");
+        }
 
-            // Owners -- Mandatory
-            cJSON *jsonOwnrArray = NULL;
-            cJSON_AddItemToObject (jsonAcl, OIC_JSON_OWNERS_NAME, jsonOwnrArray = cJSON_CreateArray());
-            VERIFY_NON_NULL(TAG, jsonOwnrArray, ERROR);
-            for (size_t i = 0; i < acl->ownersLen; i++)
-            {
-                outLen = 0;
-
-                b64Ret = b64Encode(acl->owners[i].id, sizeof(((OicUuid_t*)0)->id), base64Buff,
-                    sizeof(base64Buff), &outLen);
-                VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
+        cborEncoderResult |= cbor_encode_text_string(&oicSecAclMap, OIC_JSON_OWNERS_NAME,
+            strlen(OIC_JSON_OWNERS_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Name.");
+        CborEncoder owners;
+        cborEncoderResult |= cbor_encoder_create_array(&oicSecAclMap, &owners, acl->ownersLen);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Array.");
+        for (size_t i = 0; i < acl->ownersLen; i++)
+        {
+            cborEncoderResult |= cbor_encode_byte_string(&owners, (uint8_t *)acl->owners[i].id,
+                sizeof(acl->owners[i].id));
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Array Value.");
+        }
+        cborEncoderResult |= cbor_encoder_close_container(&oicSecAclMap, &owners);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Owner Array.");
 
-                cJSON_AddItemToArray (jsonOwnrArray, cJSON_CreateString(base64Buff));
-            }
+        cborEncoderResult |= cbor_encoder_close_container(&oicSecAclArray, &oicSecAclMap);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing ACL Map.");
 
-            // Attach current acl node to Acl Array
-            cJSON_AddItemToArray(jsonAclArray, jsonAcl);
-            acl = acl->next;
+        acl = acl->next;
+    }
+    cborEncoderResult |= cbor_encoder_close_container(&encoder, &oicSecAclArray);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing ACL Array.");
+    if (CborNoError == cborEncoderResult)
+    {
+        *size = encoder.ptr - outPayload;
+        *payload = outPayload;
+        ret = OC_STACK_OK;
+    }
+exit:
+    if (CborErrorOutOfMemory == cborEncoderResult)
+    {
+        // reallocate and try again!
+        OICFree(outPayload);
+        // Since the allocated initial memory failed, double the memory.
+        cborLen += encoder.ptr - encoder.end;
+        cborEncoderResult = CborNoError;
+        if (OC_STACK_OK == AclToCBORPayload(secAcl, &outPayload, &cborLen))
+        {
+            *size = cborLen;
+            *payload = outPayload;
+            ret = OC_STACK_OK;
         }
-
-        jsonStr = cJSON_PrintUnformatted(jsonRoot);
     }
 
-exit:
-    if (jsonRoot)
+    if (cborEncoderResult != CborNoError)
     {
-        cJSON_Delete(jsonRoot);
+        OICFree(outPayload);
+        outPayload = NULL;
+        *size = 0;
+        ret = OC_STACK_ERROR;
     }
-    return jsonStr;
+
+    return ret;
 }
 
-/*
- * This internal method converts JSON ACL into binary ACL.
- */
-OicSecAcl_t * JSONToAclBin(const char * jsonStr)
+// This function converts CBOR format to ACL data.
+// Caller needs to invoke 'free' when done using
+// note: This function is used in unit test hence not declared static,
+OicSecAcl_t* CBORPayloadToAcl(const uint8_t *cborPayload, const size_t size)
 {
-    OCStackResult ret = OC_STACK_ERROR;
-    OicSecAcl_t * headAcl = NULL;
-    OicSecAcl_t * prevAcl = NULL;
-    cJSON *jsonRoot = NULL;
-    cJSON *jsonAclArray = NULL;
+    if (NULL == cborPayload)
+    {
+        return NULL;
+    }
 
-    VERIFY_NON_NULL(TAG, jsonStr, ERROR);
+    CborValue aclCbor = { .parser = NULL };
+    CborParser parser = { .end = NULL };
+    CborError cborFindResult = CborNoError;
+    cbor_parser_init(cborPayload, size, 0, &parser, &aclCbor);
 
-    jsonRoot = cJSON_Parse(jsonStr);
-    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+    OicSecAcl_t *headAcl = NULL;
 
-    jsonAclArray = cJSON_GetObjectItem(jsonRoot, OIC_JSON_ACL_NAME);
-    VERIFY_NON_NULL(TAG, jsonAclArray, ERROR);
+    CborValue aclArray = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
+    cborFindResult = cbor_value_enter_container(&aclCbor, &aclArray);
+    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering ACL Array.");
 
-    if (cJSON_Array == jsonAclArray->type)
+    while (cbor_value_is_valid(&aclArray))
     {
-        int numAcl = cJSON_GetArraySize(jsonAclArray);
-        int idx = 0;
-
-        VERIFY_SUCCESS(TAG, numAcl > 0, INFO);
-        do
-        {
-            cJSON *jsonAcl = cJSON_GetArrayItem(jsonAclArray, idx);
-            VERIFY_NON_NULL(TAG, jsonAcl, ERROR);
+        CborValue aclMap = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
+        cborFindResult = cbor_value_enter_container(&aclArray, &aclMap);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering ACL Map.");
 
-            OicSecAcl_t *acl = (OicSecAcl_t*)OICCalloc(1, sizeof(OicSecAcl_t));
-            VERIFY_NON_NULL(TAG, acl, ERROR);
+        OicSecAcl_t *acl = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
+        VERIFY_NON_NULL(TAG, acl, ERROR);
 
-            headAcl = (headAcl) ? headAcl : acl;
-            if (prevAcl)
+        while (cbor_value_is_valid(&aclMap))
+        {
+            char* name = NULL;
+            size_t len = 0;
+            CborType type = cbor_value_get_type(&aclMap);
+            if (type == CborTextStringType)
             {
-                prevAcl->next = acl;
+                cborFindResult = cbor_value_dup_text_string(&aclMap, &name, &len, NULL);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Name in ACL Map.");
+                cborFindResult = cbor_value_advance(&aclMap);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Value in ACL Map.");
             }
-
-            size_t jsonObjLen = 0;
-            cJSON *jsonObj = NULL;
-
-            unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
-            uint32_t outLen = 0;
-            B64Result b64Ret = B64_OK;
-
-            // Subject -- Mandatory
-            jsonObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_SUBJECT_NAME);
-            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-            VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
-            outLen = 0;
-            b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff,
-                        sizeof(base64Buff), &outLen);
-            VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(acl->subject.id)), ERROR);
-            memcpy(acl->subject.id, base64Buff, outLen);
-
-            // Resources -- Mandatory
-            jsonObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_RESOURCES_NAME);
-            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-            VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
-
-            acl->resourcesLen = (size_t)cJSON_GetArraySize(jsonObj);
-            VERIFY_SUCCESS(TAG, acl->resourcesLen > 0, ERROR);
-            acl->resources = (char**)OICCalloc(acl->resourcesLen, sizeof(char*));
-            VERIFY_NON_NULL(TAG, (acl->resources), ERROR);
-
-            size_t idxx = 0;
-            do
+            if (name)
             {
-                cJSON *jsonRsrc = cJSON_GetArrayItem(jsonObj, idxx);
-                VERIFY_NON_NULL(TAG, jsonRsrc, ERROR);
-
-                jsonObjLen = strlen(jsonRsrc->valuestring) + 1;
-                acl->resources[idxx] = (char*)OICMalloc(jsonObjLen);
-                VERIFY_NON_NULL(TAG, (acl->resources[idxx]), ERROR);
-                OICStrcpy(acl->resources[idxx], jsonObjLen, jsonRsrc->valuestring);
-            } while ( ++idxx < acl->resourcesLen);
-
-            // Permissions -- Mandatory
-            jsonObj = cJSON_GetObjectItem(jsonAcl,
-                                OIC_JSON_PERMISSION_NAME);
-            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-            VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
-            acl->permission = jsonObj->valueint;
-
-            //Period -- Not Mandatory
-            cJSON *jsonPeriodObj = cJSON_GetObjectItem(jsonAcl,
-                    OIC_JSON_PERIODS_NAME);
-            if(jsonPeriodObj)
-            {
-                VERIFY_SUCCESS(TAG, cJSON_Array == jsonPeriodObj->type,
-                               ERROR);
-                acl->prdRecrLen = (size_t)cJSON_GetArraySize(jsonPeriodObj);
-                if(acl->prdRecrLen > 0)
+                // Subject -- Mandatory
+                if (strcmp(name, OIC_JSON_SUBJECT_NAME)  == 0)
                 {
-                    acl->periods = (char**)OICCalloc(acl->prdRecrLen,
-                                    sizeof(char*));
-                    VERIFY_NON_NULL(TAG, acl->periods, ERROR);
+                    uint8_t *subjectId = NULL;
+                    cborFindResult = cbor_value_dup_byte_string(&aclMap, &subjectId, &len, NULL);
+                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a Subject Name Value.");
+                    memcpy(acl->subject.id, subjectId, len);
+                    OICFree(subjectId);
+                }
 
-                    cJSON *jsonPeriod = NULL;
-                    for(size_t i = 0; i < acl->prdRecrLen; i++)
+                // Resources -- Mandatory
+                if (strcmp(name, OIC_JSON_RESOURCES_NAME) == 0)
+                {
+                    CborValue resources = { .parser = NULL };
+                    cborFindResult = cbor_value_get_array_length(&aclMap, &acl->resourcesLen);
+                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a Rec Array Len Value.");
+                    cborFindResult = cbor_value_enter_container(&aclMap, &resources);
+                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering a Rec Array.");
+
+                    acl->resources = (char **) OICMalloc(acl->resourcesLen * sizeof(char*));
+                    VERIFY_NON_NULL(TAG, acl->resources, ERROR);
+                    int i = 0;
+                    while (cbor_value_is_text_string(&resources))
                     {
-                        jsonPeriod = cJSON_GetArrayItem(jsonPeriodObj, i);
-                        VERIFY_NON_NULL(TAG, jsonPeriod, ERROR);
-
-                        jsonObjLen = strlen(jsonPeriod->valuestring) + 1;
-                        acl->periods[i] = (char*)OICMalloc(jsonObjLen);
-                        VERIFY_NON_NULL(TAG, acl->periods[i], ERROR);
-                        OICStrcpy(acl->periods[i], jsonObjLen,
-                                  jsonPeriod->valuestring);
+                        cborFindResult = cbor_value_dup_text_string(&resources, &acl->resources[i++],
+                            &len, NULL);
+                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a Rec Array Value.");
+                        cborFindResult = cbor_value_advance(&resources);
+                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a Rec Array Advance.");
                     }
                 }
-            }
 
-            //Recurrence -- Not mandatory
-            cJSON *jsonRecurObj = cJSON_GetObjectItem(jsonAcl,
-                                        OIC_JSON_RECURRENCES_NAME);
-            if(jsonRecurObj)
-            {
-                VERIFY_SUCCESS(TAG, cJSON_Array == jsonRecurObj->type,
-                               ERROR);
+                // Permissions -- Mandatory
+                if (strcmp(name, OIC_JSON_PERMISSION_NAME) == 0)
+                {
+                    cborFindResult = cbor_value_get_uint64(&aclMap, (uint64_t *) &acl->permission);
+                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a PERM Value.");
+                }
 
-                if(acl->prdRecrLen > 0)
+                // Period -- Not mandatory
+                if (strcmp(name, OIC_JSON_PERIODS_NAME) == 0)
                 {
-                    acl->recurrences = (char**)OICCalloc(acl->prdRecrLen,
-                                             sizeof(char*));
+                    CborValue period = { .parser = NULL };
+                    cborFindResult = cbor_value_get_array_length(&aclMap, &acl->prdRecrLen);
+                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a Period Array Len.");
+                    cborFindResult = cbor_value_enter_container(&aclMap, &period);
+                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a Period Array Map.");
+                    acl->periods = (char**)OICCalloc(acl->prdRecrLen, sizeof(char*));
+                    VERIFY_NON_NULL(TAG, acl->periods, ERROR);
+                    int i = 0;
+                    while (cbor_value_is_text_string(&period))
+                    {
+                        cborFindResult = cbor_value_dup_text_string(&period, &acl->periods[i++],
+                            &len, NULL);
+                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a Period Array Value.");
+                        cborFindResult = cbor_value_advance(&period);
+                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing a Period Array.");
+                    }
+                }
+
+                // Recurrence -- Not mandatory
+                if (strcmp(name, OIC_JSON_RECURRENCES_NAME) == 0)
+                {
+                    CborValue recurrences = { .parser = NULL };
+                    cborFindResult = cbor_value_enter_container(&aclMap, &recurrences);
+                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Adding Recurrence Array.");
+                    acl->recurrences = (char**)OICCalloc(acl->prdRecrLen, sizeof(char*));
                     VERIFY_NON_NULL(TAG, acl->recurrences, ERROR);
+                    int i = 0;
+                    while (cbor_value_is_text_string(&recurrences))
+                    {
+                        cborFindResult = cbor_value_dup_text_string(&recurrences,
+                            &acl->recurrences[i++], &len, NULL);
+                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Adding Recurrence Array Value.");
+                        cborFindResult = cbor_value_advance(&recurrences);
+                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Closing Recurrence Array.");
+                    }
+                }
 
-                    cJSON *jsonRecur = NULL;
-                    for(size_t i = 0; i < acl->prdRecrLen; i++)
+                // Owners -- Mandatory
+                if (strcmp(name, OIC_JSON_OWNERS_NAME) == 0)
+                {
+                    CborValue owners = { .parser = NULL };
+                    cborFindResult = cbor_value_get_array_length(&aclMap, &acl->ownersLen);
+                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Getting Owner Array Len.");
+                    cborFindResult = cbor_value_enter_container(&aclMap, &owners);
+                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering Owner Array.");
+                    int i = 0;
+                    acl->owners = (OicUuid_t *)OICMalloc(acl->ownersLen * sizeof(OicUuid_t));
+                    VERIFY_NON_NULL(TAG, acl->owners, ERROR);
+                    while (cbor_value_is_valid(&owners))
                     {
-                        jsonRecur = cJSON_GetArrayItem(jsonRecurObj, i);
-                        VERIFY_NON_NULL(TAG, jsonRecur, ERROR);
-                        jsonObjLen = strlen(jsonRecur->valuestring) + 1;
-                        acl->recurrences[i] = (char*)OICMalloc(jsonObjLen);
-                        VERIFY_NON_NULL(TAG, acl->recurrences[i], ERROR);
-                        OICStrcpy(acl->recurrences[i], jsonObjLen,
-                              jsonRecur->valuestring);
+                        uint8_t *owner = NULL;
+                        cborFindResult = cbor_value_dup_byte_string(&owners, &owner, &len, NULL);
+                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Adding Owner Array Value.");
+                        cborFindResult = cbor_value_advance(&owners);
+                        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Owners Array.");
+                        memcpy(acl->owners[i++].id, owner, len);
+                        OICFree(owner);
                     }
                 }
+                OICFree(name);
             }
-
-            // Owners -- Mandatory
-            jsonObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_OWNERS_NAME);
-            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-            VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
-
-            acl->ownersLen = (size_t)cJSON_GetArraySize(jsonObj);
-            VERIFY_SUCCESS(TAG, acl->ownersLen > 0, ERROR);
-            acl->owners = (OicUuid_t*)OICCalloc(acl->ownersLen, sizeof(OicUuid_t));
-            VERIFY_NON_NULL(TAG, (acl->owners), ERROR);
-
-            idxx = 0;
-            do
+            if (type != CborMapType && cbor_value_is_valid(&aclMap))
             {
-                cJSON *jsonOwnr = cJSON_GetArrayItem(jsonObj, idxx);
-                VERIFY_NON_NULL(TAG, jsonOwnr, ERROR);
-                VERIFY_SUCCESS(TAG, cJSON_String == jsonOwnr->type, ERROR);
-
-                outLen = 0;
-                b64Ret = b64Decode(jsonOwnr->valuestring, strlen(jsonOwnr->valuestring), base64Buff,
-                            sizeof(base64Buff), &outLen);
-
-                VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(acl->owners[idxx].id)),
-                                    ERROR);
-                memcpy(acl->owners[idxx].id, base64Buff, outLen);
-            } while ( ++idxx < acl->ownersLen);
+                cborFindResult = cbor_value_advance(&aclMap);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing the Array.");
+            }
+        }
 
-            prevAcl = acl;
-        } while( ++idx < numAcl);
+        acl->next = NULL;
+        if (headAcl == NULL)
+        {
+            headAcl = acl;
+        }
+        else
+        {
+            OicSecAcl_t *temp = headAcl;
+            while (temp->next)
+            {
+                temp = temp->next;
+            }
+            temp->next = acl;
+        }
+        if (cbor_value_is_valid(&aclArray))
+        {
+            cborFindResult = cbor_value_advance(&aclArray);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing ACL Array.");
+        }
     }
 
-    ret = OC_STACK_OK;
-
 exit:
-    cJSON_Delete(jsonRoot);
-    if (OC_STACK_OK != ret)
+    if (cborFindResult != CborNoError)
     {
         DeleteACLList(headAcl);
         headAcl = NULL;
@@ -407,37 +484,18 @@ exit:
     return headAcl;
 }
 
-static bool UpdatePersistentStorage(const OicSecAcl_t *acl)
-{
-    // Convert ACL data into JSON for update to persistent storage
-    char *jsonStr = BinToAclJSON(acl);
-    if (jsonStr)
-    {
-        cJSON *jsonAcl = cJSON_Parse(jsonStr);
-        OICFree(jsonStr);
-
-        if ((jsonAcl) && (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_ACL_NAME, jsonAcl)))
-        {
-            return true;
-        }
-        cJSON_Delete(jsonAcl);
-    }
-    return false;
-}
-
-/*
+/**
  * This method removes ACE for the subject and resource from the ACL
  *
- * @param subject  - subject of the ACE
- * @param resource - resource of the ACE
+ * @param subject of the ACE
+ * @param resource of the ACE
  *
  * @return
- *     OC_STACK_RESOURCE_DELETED on success
- *     OC_STACK_NO_RESOURC on failure to find the appropriate ACE
- *     OC_STACK_INVALID_PARAM on invalid parameter
+ *     ::OC_STACK_RESOURCE_DELETED on success
+ *     ::OC_STACK_NO_RESOURCE on failure to find the appropriate ACE
+ *     ::OC_STACK_INVALID_PARAM on invalid parameter
  */
-static OCStackResult RemoveACE(const OicUuid_t * subject,
-                               const char * resource)
+static OCStackResult RemoveACE(const OicUuid_t * subject, const char * resource)
 {
     OIC_LOG(DEBUG, TAG, "IN RemoveACE");
 
@@ -446,18 +504,18 @@ static OCStackResult RemoveACE(const OicUuid_t * subject,
     bool deleteFlag = false;
     OCStackResult ret = OC_STACK_NO_RESOURCE;
 
-    if(memcmp(subject->id, &WILDCARD_SUBJECT_ID, sizeof(subject->id)) == 0)
+    if (memcmp(subject->id, &WILDCARD_SUBJECT_ID, sizeof(subject->id)) == 0)
     {
-        OIC_LOG_V (ERROR, TAG, "%s received invalid parameter", __func__ );
+        OIC_LOG_V(ERROR, TAG, "%s received invalid parameter", __func__ );
         return  OC_STACK_INVALID_PARAM;
     }
 
     //If resource is NULL then delete all the ACE for the subject.
-    if(NULL == resource || resource[0] == '\0')
+    if (NULL == resource || resource[0] == '\0')
     {
         LL_FOREACH_SAFE(gAcl, acl, tempAcl)
         {
-            if(memcmp(acl->subject.id, subject->id, sizeof(subject->id)) == 0)
+            if (memcmp(acl->subject.id, subject->id, sizeof(subject->id)) == 0)
             {
                 LL_DELETE(gAcl, acl);
                 FreeACE(acl);
@@ -473,9 +531,9 @@ static OCStackResult RemoveACE(const OicUuid_t * subject,
         //the resource array
         LL_FOREACH_SAFE(gAcl, acl, tempAcl)
         {
-            if(memcmp(acl->subject.id, subject->id, sizeof(subject->id)) == 0)
+            if (memcmp(acl->subject.id, subject->id, sizeof(subject->id)) == 0)
             {
-                if(1 == acl->resourcesLen && strcmp(acl->resources[0],  resource) == 0)
+                if (1 == acl->resourcesLen && strcmp(acl->resources[0], resource) == 0)
                 {
                     LL_DELETE(gAcl, acl);
                     FreeACE(acl);
@@ -484,24 +542,24 @@ static OCStackResult RemoveACE(const OicUuid_t * subject,
                 }
                 else
                 {
-                    int resPos = -1;
+                    size_t resPos = -1;
                     size_t i;
-                    for(i = 0; i < acl->resourcesLen; i++)
+                    for (i = 0; i < acl->resourcesLen; i++)
                     {
-                        if(strcmp(acl->resources[i],  resource) == 0)
+                        if (strcmp(acl->resources[i], resource) == 0)
                         {
                             resPos = i;
                             break;
                         }
                     }
-                    if((0 <= resPos))
+                    if (0 <= (int) resPos)
                     {
                         OICFree(acl->resources[resPos]);
                         acl->resources[resPos] = NULL;
                         acl->resourcesLen -= 1;
-                        for(i = (size_t)resPos; i < acl->resourcesLen; i++)
+                        for (i = resPos; i < acl->resourcesLen; i++)
                         {
-                            acl->resources[i] = acl->resources[i+1];
+                            acl->resources[i] = acl->resources[i + 1];
                         }
                         deleteFlag = true;
                         break;
@@ -511,17 +569,31 @@ static OCStackResult RemoveACE(const OicUuid_t * subject,
         }
     }
 
-    if(deleteFlag)
+    if (deleteFlag)
     {
-        if(UpdatePersistentStorage(gAcl))
+        // In case of unit test do not update persistant storage.
+        if (memcmp(subject->id, &WILDCARD_SUBJECT_B64_ID, sizeof(subject->id)) == 0)
         {
             ret = OC_STACK_RESOURCE_DELETED;
         }
+        else
+        {
+            uint8_t *payload = NULL;
+            size_t size = 0;
+            if (OC_STACK_OK == AclToCBORPayload(gAcl, &payload, &size))
+            {
+                if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_ACL_NAME, payload, size))
+                {
+                    ret = OC_STACK_RESOURCE_DELETED;
+                }
+                OICFree(payload);
+            }
+        }
     }
     return ret;
 }
 
-/*
+/**
  * This method parses the query string received for REST requests and
  * retrieves the 'subject' field.
  *
@@ -532,33 +604,25 @@ static OCStackResult RemoveACE(const OicUuid_t * subject,
  */
 static bool GetSubjectFromQueryString(const char *query, OicUuid_t *subject)
 {
-    OicParseQueryIter_t parseIter = {.attrPos=NULL};
-
-    ParseQueryIterInit((unsigned char *)query, &parseIter);
+    OicParseQueryIter_t parseIter = { .attrPos = NULL };
 
+    ParseQueryIterInit((unsigned char *) query, &parseIter);
 
-    while(GetNextQuery(&parseIter))
+    while (GetNextQuery (&parseIter))
     {
-        if(strncasecmp((char *)parseIter.attrPos, OIC_JSON_SUBJECT_NAME, parseIter.attrLen) == 0)
+        if (strncasecmp((char *) parseIter.attrPos, OIC_JSON_SUBJECT_NAME, parseIter.attrLen) == 0)
         {
             VERIFY_SUCCESS(TAG, 0 != parseIter.valLen, ERROR);
-            unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
-            uint32_t outLen = 0;
-            B64Result b64Ret = B64_OK;
-            b64Ret = b64Decode((char *)parseIter.valPos, parseIter.valLen, base64Buff,
-                    sizeof(base64Buff), &outLen);
-            VERIFY_SUCCESS(TAG, (B64_OK == b64Ret && outLen <= sizeof(subject->id)), ERROR);
-            memcpy(subject->id, base64Buff, outLen);
-
+            memcpy(subject->id, parseIter.valPos, parseIter.valLen);
             return true;
         }
     }
 
 exit:
-   return false;
+    return false;
 }
 
-/*
+/**
  * This method parses the query string received for REST requests and
  * retrieves the 'resource' field.
  *
@@ -570,16 +634,17 @@ exit:
  */
 static bool GetResourceFromQueryString(const char *query, char *resource, size_t resourceSize)
 {
-    OicParseQueryIter_t parseIter = {.attrPos=NULL};
+    OicParseQueryIter_t parseIter = { .attrPos = NULL };
 
-    ParseQueryIterInit((unsigned char *)query, &parseIter);
+    ParseQueryIterInit((unsigned char *) query, &parseIter);
 
-    while(GetNextQuery(&parseIter))
+    while (GetNextQuery (&parseIter))
     {
-        if(strncasecmp((char *)parseIter.attrPos, OIC_JSON_RESOURCES_NAME, parseIter.attrLen) == 0)
+        if (strncasecmp((char *) parseIter.attrPos, OIC_JSON_RESOURCES_NAME, parseIter.attrLen)
+                == 0)
         {
             VERIFY_SUCCESS(TAG, 0 != parseIter.valLen, ERROR);
-            OICStrcpy(resource, resourceSize, (char *)parseIter.valPos);
+            OICStrcpy(resource, resourceSize, (char *) parseIter.valPos);
 
             return true;
         }
@@ -589,28 +654,26 @@ exit:
    return false;
 }
 
-
-
-static OCEntityHandlerResult HandleACLGetRequest (const OCEntityHandlerRequest * ehRequest)
+static OCEntityHandlerResult HandleACLGetRequest(const OCEntityHandlerRequest *ehRequest)
 {
-    OCEntityHandlerResult ehRet = OC_EH_ERROR;
-    char* jsonStr = NULL;
+    OIC_LOG(INFO, TAG, "HandleACLGetRequest processing the request");
+    uint8_t* payload = NULL;
+    size_t size = 0;
+    OCEntityHandlerResult ehRet;
 
     // Process the REST querystring parameters
-    if(ehRequest->query)
+    if (ehRequest->query)
     {
-        OIC_LOG (DEBUG, TAG, "HandleACLGetRequest processing query");
+        OIC_LOG(DEBUG, TAG, "HandleACLGetRequest processing query");
 
-        OicUuid_t subject = {.id={0}};
-        char resource[MAX_URI_LENGTH] = {0};
+        OicUuid_t subject = {.id= { 0 } };
+        char resource[MAX_URI_LENGTH] = { 0 };
 
         OicSecAcl_t *savePtr = NULL;
         const OicSecAcl_t *currentAce = NULL;
 
         // 'Subject' field is MUST for processing a querystring in REST request.
-        VERIFY_SUCCESS(TAG,
-                       true == GetSubjectFromQueryString(ehRequest->query, &subject),
-                       ERROR);
+        VERIFY_SUCCESS(TAG, true == GetSubjectFromQueryString(ehRequest->query, &subject), ERROR);
 
         GetResourceFromQueryString(ehRequest->query, resource, sizeof(resource));
 
@@ -619,7 +682,7 @@ static OCEntityHandlerResult HandleACLGetRequest (const OCEntityHandlerRequest *
          * Below code needs to be updated for scenarios when Subject have
          * multiple ACE's in ACL resource.
          */
-        while((currentAce = GetACLResourceData(&subject, &savePtr)))
+        while ((currentAce = GetACLResourceData(&subject, &savePtr)))
         {
             /*
              * If REST querystring contains a specific resource, we need
@@ -627,104 +690,123 @@ static OCEntityHandlerResult HandleACLGetRequest (const OCEntityHandlerRequest *
              */
             if (resource[0] != '\0')
             {
-                for(size_t n = 0; n < currentAce->resourcesLen; n++)
+                for (size_t n = 0; n < currentAce->resourcesLen; n++)
                 {
-                    if((currentAce->resources[n]) &&
-                            (0 == strcmp(resource, currentAce->resources[n]) ||
-                             0 == strcmp(WILDCARD_RESOURCE_URI, currentAce->resources[n])))
+                    if ((currentAce->resources[n])
+                            && (0 == strcmp(resource, currentAce->resources[n])
+                                    || 0 == strcmp(WILDCARD_RESOURCE_URI, currentAce->resources[n])))
                     {
-                        // Convert ACL data into JSON for transmission
-                        jsonStr = BinToAclJSON(currentAce);
+                        // Convert ACL data into CBOR format for transmission
+                        if (OC_STACK_OK != AclToCBORPayload(currentAce, &payload, &size))
+                        {
+                            ehRet = OC_EH_ERROR;
+                        }
                         goto exit;
                     }
                 }
             }
             else
             {
-                // Convert ACL data into JSON for transmission
-                jsonStr = BinToAclJSON(currentAce);
+                // Convert ACL data into CBOR format for transmission
+                if (OC_STACK_OK != AclToCBORPayload(currentAce, &payload, &size))
+                {
+                    ehRet = OC_EH_ERROR;
+                }
                 goto exit;
             }
         }
     }
     else
     {
-        // Convert ACL data into JSON for transmission
-        jsonStr = BinToAclJSON(gAcl);
+        // Convert ACL data into CBOR format for transmission.
+        if (OC_STACK_OK != AclToCBORPayload(gAcl, &payload, &size))
+        {
+            ehRet = OC_EH_ERROR;
+        }
     }
-
 exit:
-    ehRet = (jsonStr ? OC_EH_OK : OC_EH_ERROR);
+    // A device should always have a default acl. Therefore, payload should never be NULL.
+    ehRet = (payload ? OC_EH_OK : OC_EH_ERROR);
 
     // Send response payload to request originator
-    SendSRMResponse(ehRequest, ehRet, jsonStr);
-
-    OICFree(jsonStr);
+    SendSRMCBORResponse(ehRequest, ehRet, payload, size);
 
-    OIC_LOG_V (DEBUG, TAG, "%s RetVal %d", __func__ , ehRet);
+    OIC_LOG_V(DEBUG, TAG, "%s RetVal %d", __func__, ehRet);
     return ehRet;
 }
 
-static OCEntityHandlerResult HandleACLPostRequest (const OCEntityHandlerRequest * ehRequest)
+static OCEntityHandlerResult HandleACLPostRequest(const OCEntityHandlerRequest *ehRequest)
 {
+    OIC_LOG(INFO, TAG, "HandleACLPostRequest processing the request");
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
 
-    // Convert JSON ACL data into binary. This will also validate the ACL data received.
-    OicSecAcl_t* newAcl = JSONToAclBin(((OCSecurityPayload*)ehRequest->payload)->securityData);
-
-    if (newAcl)
+    // Convert CBOR into ACL data and update to SVR buffers. This will also validate the ACL data received.
+    uint8_t *payload = ((OCSecurityPayload *) ehRequest->payload)->securityData1;
+    size_t size = ((OCSecurityPayload *) ehRequest->payload)->payloadSize;
+    if (payload)
     {
-        // Append the new ACL to existing ACL
-        LL_APPEND(gAcl, newAcl);
-
-        if(UpdatePersistentStorage(gAcl))
+        OicSecAcl_t *newAcl = CBORPayloadToAcl(payload, size);
+        if (newAcl)
         {
-            ehRet = OC_EH_RESOURCE_CREATED;
+            // Append the new ACL to existing ACL
+            LL_APPEND(gAcl, newAcl);
+            size_t size = 0;
+            // In case of unit test do not update persistant storage.
+            if (memcmp(newAcl->subject.id, &WILDCARD_SUBJECT_ID, sizeof(newAcl->subject.id)) == 0
+                || memcmp(newAcl->subject.id, &WILDCARD_SUBJECT_B64_ID, sizeof(newAcl->subject.id)) == 0)
+            {
+                ehRet = OC_EH_RESOURCE_CREATED;
+            }
+            else
+            {
+                uint8_t *cborPayload = NULL;
+                if (OC_STACK_OK == AclToCBORPayload(gAcl, &cborPayload, &size))
+                {
+                    if (UpdateSecureResourceInPS(OIC_JSON_ACL_NAME, cborPayload, size) == OC_STACK_OK)
+                    {
+                        ehRet = OC_EH_RESOURCE_CREATED;
+                    }
+                    OICFree(cborPayload);
+                }
+            }
         }
     }
 
     // Send payload to request originator
-    SendSRMResponse(ehRequest, ehRet, NULL);
+    SendSRMCBORResponse(ehRequest, ehRet, NULL, 0);
 
-    OIC_LOG_V (DEBUG, TAG, "%s RetVal %d", __func__ , ehRet);
+    OIC_LOG_V(DEBUG, TAG, "%s RetVal %d", __func__, ehRet);
     return ehRet;
 }
 
 static OCEntityHandlerResult HandleACLDeleteRequest(const OCEntityHandlerRequest *ehRequest)
 {
-    OIC_LOG (DEBUG, TAG, "Processing ACLDeleteRequest");
+    OIC_LOG(DEBUG, TAG, "Processing ACLDeleteRequest");
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
-    OicUuid_t subject = {.id={0}};
-    char resource[MAX_URI_LENGTH] = {0};
+    OicUuid_t subject = { .id= { 0 } };
+    char resource[MAX_URI_LENGTH] = { 0 };
 
     VERIFY_NON_NULL(TAG, ehRequest->query, ERROR);
 
     // 'Subject' field is MUST for processing a querystring in REST request.
-    VERIFY_SUCCESS(TAG,
-            true == GetSubjectFromQueryString(ehRequest->query, &subject),
-            ERROR);
+    VERIFY_SUCCESS(TAG, true == GetSubjectFromQueryString(ehRequest->query, &subject), ERROR);
 
     GetResourceFromQueryString(ehRequest->query, resource, sizeof(resource));
 
-    if(OC_STACK_RESOURCE_DELETED == RemoveACE(&subject, resource))
+    if (OC_STACK_RESOURCE_DELETED == RemoveACE(&subject, resource))
     {
         ehRet = OC_EH_RESOURCE_DELETED;
     }
 
 exit:
     // Send payload to request originator
-    SendSRMResponse(ehRequest, ehRet, NULL);
+    SendSRMCBORResponse(ehRequest, ehRet, NULL, 0);
 
     return ehRet;
 }
 
-/*
- * This internal method is the entity handler for ACL resources and
- * will handle REST request (GET/PUT/POST/DEL) for them.
- */
-OCEntityHandlerResult ACLEntityHandler (OCEntityHandlerFlag flag,
-                                        OCEntityHandlerRequest * ehRequest,
-                                        void* callbackParameter)
+OCEntityHandlerResult ACLEntityHandler(OCEntityHandlerFlag flag, OCEntityHandlerRequest * ehRequest,
+        void* callbackParameter)
 {
     OIC_LOG(DEBUG, TAG, "Received request ACLEntityHandler");
     (void)callbackParameter;
@@ -738,7 +820,7 @@ OCEntityHandlerResult ACLEntityHandler (OCEntityHandlerFlag flag,
     if (flag & OC_REQUEST_FLAG)
     {
         // TODO :  Handle PUT method
-        OIC_LOG (DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
+        OIC_LOG(DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
         switch (ehRequest->method)
         {
             case OC_REST_GET:
@@ -755,17 +837,17 @@ OCEntityHandlerResult ACLEntityHandler (OCEntityHandlerFlag flag,
 
             default:
                 ehRet = OC_EH_ERROR;
-                SendSRMResponse(ehRequest, ehRet, NULL);
+                SendSRMCBORResponse(ehRequest, ehRet, NULL, 0);
         }
     }
 
     return ehRet;
 }
 
-/*
+/**
  * This internal method is used to create '/oic/sec/acl' resource.
  */
-OCStackResult CreateACLResource()
+static OCStackResult CreateACLResource()
 {
     OCStackResult ret;
 
@@ -779,23 +861,24 @@ OCStackResult CreateACLResource()
 
     if (OC_STACK_OK != ret)
     {
-        OIC_LOG (FATAL, TAG, "Unable to instantiate ACL resource");
+        OIC_LOG(FATAL, TAG, "Unable to instantiate ACL resource");
         DeInitACLResource();
     }
     return ret;
 }
 
-/*
- * This internal method is to retrieve the default ACL.
- * If SVR database in persistent storage got corrupted or
- * is not available for some reason, a default ACL is created
- * which allows user to initiate ACL provisioning again.
- */
-OCStackResult  GetDefaultACL(OicSecAcl_t** defaultAcl)
+// This function sets the default ACL and is defined for the unit test only.
+OCStackResult SetDefaultACL(OicSecAcl_t *acl)
+{
+    gAcl = acl;
+    return OC_STACK_OK;
+}
+
+OCStackResult GetDefaultACL(OicSecAcl_t** defaultAcl)
 {
     OCStackResult ret = OC_STACK_ERROR;
 
-    OicUuid_t ownerId = {.id = {0}};
+    OicUuid_t ownerId = { .id = { 0 } };
 
     /*
      * TODO In future, when new virtual resources will be added in OIC
@@ -822,22 +905,22 @@ OCStackResult  GetDefaultACL(OicSecAcl_t** defaultAcl)
         return OC_STACK_INVALID_PARAM;
     }
 
-    OicSecAcl_t *acl = (OicSecAcl_t *)OICCalloc(1, sizeof(OicSecAcl_t));
+    OicSecAcl_t *acl = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
     VERIFY_NON_NULL(TAG, acl, ERROR);
 
     // Subject -- Mandatory
     memcpy(&(acl->subject), &WILDCARD_SUBJECT_ID, sizeof(acl->subject));
 
     // Resources -- Mandatory
-    acl->resourcesLen = sizeof(rsrcs)/sizeof(rsrcs[0]);
+    acl->resourcesLen = sizeof(rsrcs) / sizeof(rsrcs[0]);
 
-    acl->resources = (char**)OICCalloc(acl->resourcesLen, sizeof(char*));
+    acl->resources = (char**) OICCalloc(acl->resourcesLen, sizeof(char*));
     VERIFY_NON_NULL(TAG, (acl->resources), ERROR);
 
-    for (size_t i = 0; i <  acl->resourcesLen; i++)
+    for (size_t i = 0; i < acl->resourcesLen; i++)
     {
         size_t len = strlen(rsrcs[i]) + 1;
-        acl->resources[i] = (char*)OICMalloc(len * sizeof(char));
+        acl->resources[i] = (char*) OICMalloc(len * sizeof(char));
         VERIFY_NON_NULL(TAG, (acl->resources[i]), ERROR);
         OICStrcpy(acl->resources[i], len, rsrcs[i]);
     }
@@ -848,11 +931,18 @@ OCStackResult  GetDefaultACL(OicSecAcl_t** defaultAcl)
     acl->recurrences = NULL;
 
     // Device ID is the owner of this default ACL
-    ret = GetDoxmDeviceID( &ownerId);
-    VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, FATAL);
-
+    if (GetDoxmResourceData() != NULL)
+    {
+        ret = GetDoxmDeviceID(&ownerId);
+        VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, FATAL);
+    }
+    else
+    {
+        OCRandomUuidResult rdm = OCGenerateUuid(ownerId.id);
+        VERIFY_SUCCESS(TAG, RAND_UUID_OK == rdm, FATAL);
+    }
     acl->ownersLen = 1;
-    acl->owners = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t));
+    acl->owners = (OicUuid_t*) OICMalloc(sizeof(OicUuid_t));
     VERIFY_NON_NULL(TAG, (acl->owners), ERROR);
     memcpy(acl->owners, &ownerId, sizeof(OicUuid_t));
 
@@ -872,30 +962,29 @@ exit:
     return ret;
 }
 
-/**
- * Initialize ACL resource by loading data from persistent storage.
- *
- * @retval  OC_STACK_OK for Success, otherwise some error value
- */
 OCStackResult InitACLResource()
 {
     OCStackResult ret = OC_STACK_ERROR;
 
-    // Read ACL resource from PS
-    char* jsonSVRDatabase = GetSVRDatabase();
-
-    if (jsonSVRDatabase)
+    uint8_t *data = NULL;
+    size_t size = 0;
+    ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_ACL_NAME, &data, &size);
+    // If database read failed
+    if (ret != OC_STACK_OK)
     {
-        // Convert JSON ACL into binary format
-        gAcl = JSONToAclBin(jsonSVRDatabase);
-        OICFree(jsonSVRDatabase);
+        OIC_LOG(DEBUG, TAG, "ReadSVDataFromPS failed");
+    }
+    if (data)
+    {
+        // Read ACL resource from PS
+        gAcl = CBORPayloadToAcl(data, size);
     }
     /*
      * If SVR database in persistent storage got corrupted or
      * is not available for some reason, a default ACL is created
      * which allows user to initiate ACL provisioning again.
      */
-    if (!jsonSVRDatabase || !gAcl)
+    if (!gAcl)
     {
         GetDefaultACL(&gAcl);
         // TODO Needs to update persistent storage
@@ -913,37 +1002,25 @@ exit:
     return ret;
 }
 
-/**
- * Perform cleanup for ACL resources.
- *
- * @retval  none
- */
-void DeInitACLResource()
+OCStackResult DeInitACLResource()
 {
-    OCDeleteResource(gAclHandle);
+    OCStackResult ret =  OCDeleteResource(gAclHandle);
     gAclHandle = NULL;
 
-    DeleteACLList(gAcl);
-    gAcl = NULL;
+    if (gAcl)
+    {
+        DeleteACLList(gAcl);
+        gAcl = NULL;
+    }
+    return ret;
 }
 
-/**
- * This method is used by PolicyEngine to retrieve ACL for a Subject.
- *
- * @param subjectId ID of the subject for which ACL is required.
- * @param savePtr is used internally by @ref GetACLResourceData to maintain index between
- *                successive calls for same subjectId.
- *
- * @retval  reference to @ref OicSecAcl_t if ACL is found, else NULL
- *
- * @note On the first call to @ref GetACLResourceData, savePtr should point to NULL
- */
 const OicSecAcl_t* GetACLResourceData(const OicUuid_t* subjectId, OicSecAcl_t **savePtr)
 {
     OicSecAcl_t *acl = NULL;
     OicSecAcl_t *begin = NULL;
 
-    if ( NULL == subjectId)
+    if (NULL == subjectId)
     {
         return NULL;
     }
@@ -987,31 +1064,36 @@ const OicSecAcl_t* GetACLResourceData(const OicUuid_t* subjectId, OicSecAcl_t **
     return NULL;
 }
 
-
-OCStackResult InstallNewACL(const char* newJsonStr)
+OCStackResult InstallNewACL(const uint8_t *cborPayload, const size_t size)
 {
     OCStackResult ret = OC_STACK_ERROR;
 
-    // Convert JSON ACL data into binary. This will also validate the ACL data received.
-    OicSecAcl_t* newAcl = JSONToAclBin(newJsonStr);
+    // Convert CBOR format to ACL data. This will also validate the ACL data received.
+    OicSecAcl_t* newAcl = CBORPayloadToAcl(cborPayload, size);
 
     if (newAcl)
     {
         // Append the new ACL to existing ACL
         LL_APPEND(gAcl, newAcl);
 
-        // Convert ACL data into JSON for update to persistent storage
-        char *jsonStr = BinToAclJSON(gAcl);
-        if (jsonStr)
+        // Update persistent storage only if it is not WILDCARD_SUBJECT_ID
+        if (memcmp(newAcl->subject.id, &WILDCARD_SUBJECT_ID, sizeof(newAcl->subject.id)) == 0
+            || memcmp(newAcl->subject.id, &WILDCARD_SUBJECT_B64_ID, sizeof(newAcl->subject.id)) == 0)
         {
-            cJSON *jsonAcl = cJSON_Parse(jsonStr);
-            OICFree(jsonStr);
-
-            if (jsonAcl)
+            ret = OC_STACK_OK;
+        }
+        else
+        {
+            size_t size = 0;
+            uint8_t *payload = NULL;
+            if (OC_STACK_OK == AclToCBORPayload(gAcl, &payload, &size))
             {
-                ret = UpdateSVRDatabase(OIC_JSON_ACL_NAME, jsonAcl);
+                if (UpdateSecureResourceInPS(OIC_JSON_ACL_NAME, payload, size) == OC_STACK_OK)
+                {
+                    ret = OC_STACK_OK;
+                }
+                OICFree(payload);
             }
-            cJSON_Delete(jsonAcl);
         }
     }
 
@@ -1021,7 +1103,7 @@ OCStackResult InstallNewACL(const char* newJsonStr)
 /**
  * This function generates default ACL for security resource in case of owned status.
  *
- * @retval Default ACL for security resource.
+ * @return Default ACL for security resource.
  */
 static OicSecAcl_t* GetSecDefaultACL()
 {
@@ -1129,27 +1211,20 @@ OCStackResult UpdateDefaultSecProvACL()
              *      resources :  '/oic/sec/doxm', '/oic/sec/pstat'
              *      permission : READ
              */
-            OicSecAcl_tnewDefaultAcl = GetSecDefaultACL();
-            if(newDefaultAcl)
+            OicSecAcl_t *newDefaultAcl = GetSecDefaultACL();
+            if (newDefaultAcl)
             {
                 LL_APPEND(gAcl, newDefaultAcl);
 
-                char *jsonStr = BinToAclJSON(gAcl);
-                if(jsonStr)
+                size_t size = 0;
+                uint8_t *payload = NULL;
+                if (OC_STACK_OK == AclToCBORPayload(gAcl, &payload, &size))
                 {
-                    cJSON *jsonAcl = cJSON_Parse(jsonStr);
-                    OICFree(jsonStr);
-
-                    //Update SVR DB
-                    if (jsonAcl)
+                    if (UpdateSecureResourceInPS(OIC_JSON_ACL_NAME, payload, size) == OC_STACK_OK)
                     {
-                        ret = UpdateSVRDatabase(OIC_JSON_ACL_NAME, jsonAcl);
-                        if(OC_STACK_OK != ret)
-                        {
-                            OIC_LOG(WARNING, TAG, "Failed to update SVR DB");
-                        }
+                        ret = OC_STACK_OK;
                     }
-                    cJSON_Delete(jsonAcl);
+                    OICFree(payload);
                 }
             }
         }
index 63aef6a..60c87f5 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-
 #include <stdlib.h>
 #include <string.h>
-#include "ocstack.h"
-#include "logger.h"
 #include "oic_malloc.h"
-#include "oic_string.h"
-#include "cJSON.h"
-#include "base64.h"
-#include "resourcemanager.h"
+#include "ocpayload.h"
+#include "payload_logging.h"
 #include "psinterface.h"
+#include "resourcemanager.h"
 #include "utlist.h"
 #include "srmresourcestrings.h"
-#include "amaclresource.h"
 #include "srmutility.h"
-#include <stdlib.h>
-#include <string.h>
+#include "amaclresource.h"
 
 #define TAG  "SRM-AMACL"
 
-OicSecAmacl_t *gAmacl = NULL;
+/** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
+ * The value of payload size is increased until reaching belox max cbor size. */
+static const uint8_t CBOR_SIZE = 255;
+
+/* Max cbor size payload. */
+static const uint16_t CBOR_MAX_SIZE = 4400;
+
+/** AMACL Map size - Number of mandatory items. */
+static const uint8_t AMACL_MAP_SIZE = 3;
+
+static OicSecAmacl_t *gAmacl = NULL;
 static OCResourceHandle gAmaclHandle = NULL;
 
 void DeleteAmaclList(OicSecAmacl_t* amacl)
@@ -69,193 +73,321 @@ void DeleteAmaclList(OicSecAmacl_t* amacl)
     }
 }
 
-/*
- * This internal method converts AMACL data into JSON format.
- *
- * Note: Caller needs to invoke 'free' when finished using the return string.
- */
-char * BinToAmaclJSON(const OicSecAmacl_t * amacl)
+static size_t OicSecAmaclCount(const OicSecAmacl_t *secAmacl)
 {
-    cJSON *jsonRoot = NULL;
-    char *jsonStr = NULL;
+    size_t size = 0;
+    for (const OicSecAmacl_t *amacl = secAmacl; amacl; amacl = amacl->next)
+    {
+        size++;
+    }
+    return size;
+}
 
-    if (amacl)
+OCStackResult AmaclToCBORPayload(const OicSecAmacl_t *amaclS, uint8_t **cborPayload,
+                                 size_t *cborSize)
+{
+    if (NULL == amaclS || NULL == cborPayload || NULL != *cborPayload || NULL == cborSize)
     {
-        jsonRoot = cJSON_CreateObject();
-        VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+        return OC_STACK_INVALID_PARAM;
+    }
 
-        cJSON *jsonAmaclArray = NULL;
-        cJSON_AddItemToObject (jsonRoot, OIC_JSON_AMACL_NAME, jsonAmaclArray = cJSON_CreateArray());
-        VERIFY_NON_NULL(TAG, jsonAmaclArray, ERROR);
+    OCStackResult ret = OC_STACK_ERROR;
+    size_t cborLen = *cborSize;
+    if (0 == cborLen)
+    {
+        cborLen = CBOR_SIZE;
+    }
 
-        while(amacl)
-        {
-            char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};
-            uint32_t outLen = 0;
-            B64Result b64Ret = B64_OK;
+    *cborSize = 0;
+    *cborPayload = NULL;
 
-            cJSON *jsonAmacl = cJSON_CreateObject();
+    CborEncoder encoder = { {.ptr = NULL }, .end = 0 };
+    CborEncoder amaclArray = { {.ptr = NULL }, .end = 0 };
+    int64_t cborEncoderResult = CborNoError;
 
-            // Resources -- Mandatory
-            cJSON *jsonRsrcArray = NULL;
-            cJSON_AddItemToObject(jsonAmacl, OIC_JSON_RESOURCES_NAME, jsonRsrcArray =
-                    cJSON_CreateArray());
-            VERIFY_NON_NULL(TAG, jsonRsrcArray, ERROR);
-            for (unsigned int i = 0; i < amacl->resourcesLen; i++)
-            {
-                cJSON_AddItemToArray(jsonRsrcArray, cJSON_CreateString(amacl->resources[i]));
-            }
+    const OicSecAmacl_t *amacl = amaclS;
+    uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
+    VERIFY_NON_NULL(TAG, outPayload, ERROR);
+    cbor_encoder_init(&encoder, outPayload, cborLen, 0);
 
-            // Amss -- Mandatory
-            cJSON *jsonAmsArray = NULL;
-            cJSON_AddItemToObject(jsonAmacl, OIC_JSON_AMSS_NAME, jsonAmsArray =
-                    cJSON_CreateArray());
-            VERIFY_NON_NULL(TAG, jsonAmsArray, ERROR);
-            for (unsigned int i = 0; i < amacl->amssLen; i++)
-            {
-                outLen = 0;
+    // Create AMACL Array
+    cborEncoderResult |= cbor_encoder_create_array(&encoder, &amaclArray, OicSecAmaclCount(amacl));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding AMACL Array.");
 
-                b64Ret = b64Encode(amacl->amss[i].id, sizeof(((OicUuid_t*) 0)->id), base64Buff,
-                        sizeof(base64Buff), &outLen);
-                VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
-
-                cJSON_AddItemToArray(jsonAmsArray, cJSON_CreateString(base64Buff));
-            }
+    while (amacl)
+    {
+        CborEncoder amaclMap = { {.ptr = NULL }, .end = 0 };
+        cborEncoderResult |= cbor_encoder_create_map(&amaclArray, &amaclMap, AMACL_MAP_SIZE);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding AMACL MAP.");
 
-            // Owners -- Mandatory
-            cJSON *jsonOwnrArray = NULL;
-            cJSON_AddItemToObject(jsonAmacl, OIC_JSON_OWNERS_NAME, jsonOwnrArray =
-                    cJSON_CreateArray());
-            VERIFY_NON_NULL(TAG, jsonOwnrArray, ERROR);
-            for (unsigned int i = 0; i < amacl->ownersLen; i++)
+        // Resources -- Mandatory
+        {
+            CborEncoder resources = { {.ptr = NULL }, .end = 0};
+            cborEncoderResult |= cbor_encode_text_string(&amaclMap, OIC_JSON_RESOURCES_NAME,
+                strlen(OIC_JSON_RESOURCES_NAME));
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding Resource Name Tag.");
+            cborEncoderResult |= cbor_encoder_create_array(&amaclMap, &resources, amacl->resourcesLen);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding Resource Name Array.");
+
+            for (size_t i = 0; i < amacl->resourcesLen; i++)
             {
-                outLen = 0;
-
-                b64Ret = b64Encode(amacl->owners[i].id, sizeof(((OicUuid_t*) 0)->id), base64Buff,
-                        sizeof(base64Buff), &outLen);
-                VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
+                cborEncoderResult |= cbor_encode_text_string(&resources, amacl->resources[i],
+                    strlen(amacl->resources[i]));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding Resource Name Value in Array.");
 
-                cJSON_AddItemToArray(jsonOwnrArray, cJSON_CreateString(base64Buff));
             }
-
-            // Attach current amacl node to Amacl Array
-            cJSON_AddItemToArray(jsonAmaclArray, jsonAmacl);
-            amacl = amacl->next;
+            cborEncoderResult |= cbor_encoder_close_container(&amaclMap, &resources);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Resource Name ");
         }
+        // Amss -- Mandatory
+        {
+            CborEncoder amss = { {.ptr = NULL }, .end = 0 };
+            cborEncoderResult |= cbor_encode_text_string(&amaclMap, OIC_JSON_AMSS_NAME,
+                strlen(OIC_JSON_AMSS_NAME));
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding AMSS Name Tag.");
+            cborEncoderResult |= cbor_encoder_create_array(&amaclMap, &amss, amacl->amssLen);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding AMSS Name Array.");
+            for (size_t i = 0; i < amacl->amssLen; i++)
+            {
+                cborEncoderResult |= cbor_encode_byte_string(&amss, amacl->amss[i].id,
+                    sizeof(amacl->amss[i].id));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding AMSS Name Value.");
+            }
+            cborEncoderResult |= cbor_encoder_close_container(&amaclMap, &amss);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing AMSS Array.");
+        }
+        // Owners -- Mandatory
+        {
+            cborEncoderResult |= cbor_encode_text_string(&amaclMap, OIC_JSON_OWNERS_NAME,
+                strlen(OIC_JSON_OWNERS_NAME));
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding Owners Array Tag.");
+            CborEncoder owners = { {.ptr = NULL }, .end = 0};
+            cborEncoderResult |= cbor_encoder_create_array(&amaclMap, &owners, amacl->ownersLen);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding Owners Array.");
+
+            for (size_t i = 0; i < amacl->ownersLen; i++)
+            {
+                cborEncoderResult |= cbor_encode_byte_string(&owners, (uint8_t *)amacl->owners[i].id,
+                    sizeof(amacl->owners[i].id));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding Owners Array Value.");
+            }
+            cborEncoderResult |= cbor_encoder_close_container(&amaclMap, &owners);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Owners Array.");
+        }
+        cborEncoderResult |= cbor_encoder_close_container(&amaclArray, &amaclMap);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing AMACL Map.");
 
-        jsonStr = cJSON_PrintUnformatted(jsonRoot);
+        amacl = amacl->next;
     }
+    cborEncoderResult |= cbor_encoder_close_container(&encoder, &amaclArray);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Amacl Array.");
 
-exit:
-    if (jsonRoot)
+    if (CborNoError == cborEncoderResult)
     {
-        cJSON_Delete(jsonRoot);
+        *cborPayload = outPayload;
+        *cborSize = encoder.ptr - outPayload;
+        ret = OC_STACK_OK;
     }
-    return jsonStr;
-}
 
+exit:
+    if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
+    {
+       // reallocate and try again!
+       OICFree(outPayload);
+       outPayload = NULL;
+       // Since the allocated initial memory failed, double the memory.
+       cborLen += encoder.ptr - encoder.end;
+       cborEncoderResult = CborNoError;
+       ret = AmaclToCBORPayload(amaclS, cborPayload, &cborLen);
+       if (OC_STACK_OK == ret)
+       {
+           *cborSize = cborLen;
+           ret = OC_STACK_OK;
+       }
+    }
 
+    if (CborNoError != cborEncoderResult)
+    {
+       OICFree(outPayload);
+       outPayload = NULL;
+       *cborSize = 0;
+       *cborPayload = NULL;
+       ret = OC_STACK_ERROR;
+    }
 
+    return ret;
+}
 
-/*
- * This internal method converts JSON AMACL into binary AMACL.
- */
-OicSecAmacl_t * JSONToAmaclBin(const char * jsonStr)
+OCStackResult CBORPayloadToAmacl(const uint8_t *cborPayload, size_t size,
+                                 OicSecAmacl_t **secAmacl)
 {
-    OCStackResult ret = OC_STACK_ERROR;
-    OicSecAmacl_t * headAmacl = NULL;
-    OicSecAmacl_t * prevAmacl = NULL;
-    cJSON *jsonRoot = NULL;
-    cJSON *jsonAmaclArray = NULL;
-
-    VERIFY_NON_NULL(TAG, jsonStr, ERROR);
+    if (NULL == cborPayload || NULL == secAmacl || NULL != *secAmacl)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
 
-    jsonRoot = cJSON_Parse(jsonStr);
-    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+    *secAmacl = NULL;
 
-    jsonAmaclArray = cJSON_GetObjectItem(jsonRoot, OIC_JSON_AMACL_NAME);
-    VERIFY_NON_NULL(TAG, jsonAmaclArray, INFO);
+    OCStackResult ret = OC_STACK_ERROR;
 
-    if (cJSON_Array == jsonAmaclArray->type)
+    CborValue amaclCbor = { .parser = NULL };
+    CborParser parser = { .end = NULL };
+    CborError cborFindResult = CborNoError;
+    int cborLen = size;
+    if (0 == size)
     {
-        int numAmacl = cJSON_GetArraySize(jsonAmaclArray);
-        int idx = 0;
+        cborLen = CBOR_SIZE;
+    }
+    cbor_parser_init(cborPayload, cborLen, 0, &parser, &amaclCbor);
 
-        VERIFY_SUCCESS(TAG, numAmacl > 0, INFO);
-        do
-        {
-            cJSON *jsonAmacl = cJSON_GetArrayItem(jsonAmaclArray, idx);
-            VERIFY_NON_NULL(TAG, jsonAmacl, ERROR);
+    OicSecAmacl_t *headAmacl = NULL;
 
-            OicSecAmacl_t *amacl = (OicSecAmacl_t*)OICCalloc(1, sizeof(OicSecAmacl_t));
-            VERIFY_NON_NULL(TAG, amacl, ERROR);
+    CborValue amaclArray = { .parser = NULL };
+    cborFindResult = cbor_value_enter_container(&amaclCbor, &amaclArray);
+    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering Amacl Array.");
 
-            headAmacl = (headAmacl) ? headAmacl : amacl;
-            if (prevAmacl)
-            {
-                prevAmacl->next = amacl;
-            }
+    while (cbor_value_is_valid(&amaclArray))
+    {
+        CborValue amaclMap = { .parser = NULL };
+        cborFindResult = cbor_value_enter_container(&amaclArray, &amaclMap);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering Amacl Map.");
 
-            size_t jsonObjLen = 0;
-            cJSON *jsonObj = NULL;
+        OicSecAmacl_t *amacl = (OicSecAmacl_t *) OICCalloc(1, sizeof(*amacl));
+        VERIFY_NON_NULL(TAG, amacl, ERROR);
 
-            // Resources -- Mandatory
-            jsonObj = cJSON_GetObjectItem(jsonAmacl, OIC_JSON_RESOURCES_NAME);
-            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-            VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
+        while (cbor_value_is_valid(&amaclMap))
+        {
+            char *name = NULL;
+            size_t len = 0;
+            cborFindResult = cbor_value_dup_text_string(&amaclMap, &name, &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering Amacl Name.");
+            cborFindResult = cbor_value_advance(&amaclMap);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering Amacl Advance.");
 
-            amacl->resourcesLen = (size_t)cJSON_GetArraySize(jsonObj);
-            VERIFY_SUCCESS(TAG, amacl->resourcesLen > 0, ERROR);
-            amacl->resources = (char**)OICCalloc(amacl->resourcesLen, sizeof(char*));
-            VERIFY_NON_NULL(TAG, (amacl->resources), ERROR);
+            CborType type = cbor_value_get_type(&amaclMap);
 
-            size_t idxx = 0;
-            do
+            // Resources -- Mandatory
+            if (0 == strcmp(OIC_JSON_RESOURCES_NAME, name))
             {
-                cJSON *jsonRsrc = cJSON_GetArrayItem(jsonObj, idxx);
-                VERIFY_NON_NULL(TAG, jsonRsrc, ERROR);
-
-                jsonObjLen = strlen(jsonRsrc->valuestring) + 1;
-                amacl->resources[idxx] = (char*)OICMalloc(jsonObjLen);
-                VERIFY_NON_NULL(TAG, (amacl->resources[idxx]), ERROR);
-                OICStrcpy(amacl->resources[idxx], jsonObjLen, jsonRsrc->valuestring);
-            } while ( ++idxx < amacl->resourcesLen);
+                CborValue resources = { .parser = NULL  };
+                cborFindResult = cbor_value_get_array_length(&amaclMap, &amacl->resourcesLen);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Resource Name Array Len.");
+
+                cborFindResult = cbor_value_enter_container(&amaclMap, &resources);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering Amacl Array.");
+
+                amacl->resources = (char **) OICCalloc(amacl->resourcesLen, sizeof(*amacl->resources));
+                VERIFY_NON_NULL(TAG, amacl->resources, ERROR);
+                int i = 0;
+                while (cbor_value_is_text_string(&resources))
+                {
+                    cborFindResult = cbor_value_dup_text_string(&resources, &amacl->resources[i++],
+                        &len, NULL);
+                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Resource Name Value.");
+                    cborFindResult = cbor_value_advance(&resources);
+                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Resource Name.");
+                }
+            }
 
             // Amss -- Mandatory
-            VERIFY_SUCCESS( TAG, OC_STACK_OK == AddUuidArray(jsonAmacl, OIC_JSON_AMSS_NAME,
-                               &(amacl->amssLen), &(amacl->amss)), ERROR);
+            if (0 == strcmp(OIC_JSON_AMSS_NAME, name))
+            {
+                CborValue amss = { .parser = NULL };
+                cborFindResult = cbor_value_get_array_length(&amaclMap, &amacl->amssLen);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering AMSS Name Array Len.");
+                cborFindResult = cbor_value_enter_container(&amaclMap, &amss);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering AMSS Name Container.");
+                int i = 0;
+                amacl->amss = (OicUuid_t *)OICCalloc(amacl->amssLen, sizeof(*amacl->amss));
+                VERIFY_NON_NULL(TAG, amacl->amss, ERROR);
+                while (cbor_value_is_valid(&amss))
+                {
+                    uint8_t *amssId = NULL;
+                    cborFindResult = cbor_value_dup_byte_string(&amss, &amssId, &len, NULL);
+                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Adding AMSS Id.");
+                    cborFindResult = cbor_value_advance(&amss);
+                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing AMSS.");
+                    memcpy(amacl->amss[i++].id, amssId, len);
+                    OICFree(amssId);
+                }
+            }
 
             // Owners -- Mandatory
-            VERIFY_SUCCESS( TAG, OC_STACK_OK == AddUuidArray(jsonAmacl, OIC_JSON_OWNERS_NAME,
-                               &(amacl->ownersLen), &(amacl->owners)), ERROR);
+            if (0 == strcmp(OIC_JSON_OWNERS_NAME, name))
+            {
+                CborValue owners = { .parser = NULL };
+                cborFindResult = cbor_value_get_array_length(&amaclMap, &amacl->ownersLen);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Adding Owner Name Len.");
+                cborFindResult = cbor_value_enter_container(&amaclMap, &owners);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Container Owner Array.");
+                int i = 0;
+                amacl->owners = (OicUuid_t *)OICCalloc(amacl->ownersLen, sizeof(*amacl->owners));
+                VERIFY_NON_NULL(TAG, amacl->owners, ERROR);
+                while (cbor_value_is_valid(&owners))
+                {
+                    uint8_t *owner = NULL;
+                    cborFindResult = cbor_value_dup_byte_string(&owners, &owner, &len, NULL);
+                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Adding Owners Array Value.");
+                    cborFindResult = cbor_value_advance(&owners);
+                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Owners Array");
+                    memcpy(amacl->owners[i++].id, owner, len);
+                    OICFree(owner);
+                }
+            }
+            if (CborMapType != type && cbor_value_is_valid(&amaclMap))
+            {
+                cborFindResult = cbor_value_advance(&amaclMap);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Amacl Map.");
+            }
+            OICFree(name);
+        }
 
-            prevAmacl = amacl;
-        } while( ++idx < numAmacl);
+        amacl->next = NULL;
+        if (NULL == headAmacl)
+        {
+            headAmacl = amacl;
+        }
+        else
+        {
+            OicSecAmacl_t *temp = headAmacl;
+            while (temp->next)
+            {
+                temp = temp->next;
+            }
+            temp->next = amacl;
+        }
+        if (cbor_value_is_valid(&amaclArray))
+        {
+            cborFindResult = cbor_value_advance(&amaclArray);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing AMACL Array.");
+        }
     }
-
+    *secAmacl = headAmacl;
     ret = OC_STACK_OK;
 
 exit:
-    cJSON_Delete(jsonRoot);
-    if (OC_STACK_OK != ret)
+    if (CborNoError != cborFindResult)
     {
         DeleteAmaclList(headAmacl);
         headAmacl = NULL;
+        ret = OC_STACK_ERROR;
     }
-    return headAmacl;
+    return ret;
 }
 
 static OCEntityHandlerResult HandleAmaclGetRequest (const OCEntityHandlerRequest * ehRequest)
 {
     // Convert Amacl data into JSON for transmission
-    char* jsonStr = BinToAmaclJSON(gAmacl);
+    size_t size = 0;
+    uint8_t *cborPayload = NULL;
+    OCStackResult res = AmaclToCBORPayload(gAmacl, &cborPayload, &size);
 
-    OCEntityHandlerResult ehRet = (jsonStr ? OC_EH_OK : OC_EH_ERROR);
+    OCEntityHandlerResult ehRet = (res == OC_STACK_OK) ? OC_EH_OK : OC_EH_ERROR;
 
     // Send response payload to request originator
-    SendSRMResponse(ehRequest, ehRet, jsonStr);
+    SendSRMCBORResponse(ehRequest, ehRet, cborPayload, size);
 
-    OICFree(jsonStr);
+    OICFree(cborPayload);
 
     OIC_LOG_V (DEBUG, TAG, "%s RetVal %d", __func__ , ehRet);
     return ehRet;
@@ -265,44 +397,45 @@ static OCEntityHandlerResult HandleAmaclPostRequest (const OCEntityHandlerReques
 {
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
 
-    // Convert JSON Amacl data into binary. This will also validate the Amacl data received.
-    OicSecAmacl_t* newAmacl = JSONToAmaclBin(((OCSecurityPayload*)ehRequest->payload)->securityData);
-
-    if (newAmacl)
+    // Convert CBOR Amacl data into binary. This will also validate the Amacl data received.
+    uint8_t *payload = ((OCSecurityPayload *) ehRequest->payload)->securityData1;
+    size_t size = ((OCSecurityPayload *) ehRequest->payload)->payloadSize;
+    if (payload)
     {
-        // Append the new Amacl to existing Amacl
-        LL_APPEND(gAmacl, newAmacl);
-
-        // Convert Amacl data into JSON for update to persistent storage
-        char *jsonStr = BinToAmaclJSON(gAmacl);
-        if (jsonStr)
+        OicSecAmacl_t *newAmacl = NULL;
+        OCStackResult res = CBORPayloadToAmacl(payload, size, &newAmacl);
+        if (newAmacl && OC_STACK_OK == res)
         {
-            cJSON *jsonAmacl = cJSON_Parse(jsonStr);
-            OICFree(jsonStr);
-
-            if ((jsonAmacl) &&
-                (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_AMACL_NAME, jsonAmacl)))
+            // Append the new Amacl to existing Amacl
+            LL_APPEND(gAmacl, newAmacl);
+            size_t size = 0;
+            // Convert Amacl data into JSON for update to persistent storage.
+            uint8_t *cborPayload = NULL;
+            res = AmaclToCBORPayload(gAmacl, &cborPayload, &size);
+            if (cborPayload && (OC_STACK_OK == res) &&
+                (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_AMACL_NAME, cborPayload, size)))
             {
                 ehRet = OC_EH_RESOURCE_CREATED;
             }
-            cJSON_Delete(jsonAmacl);
+            OICFree(cborPayload);
         }
+        OICFree(payload);
     }
 
     // Send payload to request originator
-    SendSRMResponse(ehRequest, ehRet, NULL);
+    SendSRMCBORResponse(ehRequest, ehRet, NULL, 0);
 
-    OIC_LOG_V (DEBUG, TAG, "%s RetVal %d", __func__ , ehRet);
+    OIC_LOG_V(DEBUG, TAG, "%s RetVal %d", __func__ , ehRet);
     return ehRet;
 }
 
-/*
+/**
  * This internal method is the entity handler for Amacl resources and
  * will handle REST request (GET/PUT/POST/DEL) for them.
  */
-OCEntityHandlerResult AmaclEntityHandler (OCEntityHandlerFlag flag,
-                                          OCEntityHandlerRequest * ehRequest,
-                                          void* callbackParameter)
+static OCEntityHandlerResult AmaclEntityHandler (OCEntityHandlerFlag flag,
+                                                 OCEntityHandlerRequest * ehRequest,
+                                                 void* callbackParameter)
 {
     (void) callbackParameter;
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
@@ -327,27 +460,25 @@ OCEntityHandlerResult AmaclEntityHandler (OCEntityHandlerFlag flag,
 
             default:
                 ehRet = OC_EH_ERROR;
-                SendSRMResponse(ehRequest, ehRet, NULL);
+                SendSRMCBORResponse(ehRequest, ehRet, NULL, 0);
         }
     }
 
     return ehRet;
 }
 
-/*
+/**
  * This internal method is used to create '/oic/sec/amacl' resource.
  */
-OCStackResult CreateAmaclResource()
+static OCStackResult CreateAmaclResource()
 {
-    OCStackResult ret;
-
-    ret = OCCreateResource(&gAmaclHandle,
-                           OIC_RSRC_TYPE_SEC_AMACL,
-                           OIC_MI_DEF,
-                           OIC_RSRC_AMACL_URI,
-                           AmaclEntityHandler,
-                           NULL,
-                           OC_OBSERVABLE);
+    OCStackResult ret = OCCreateResource(&gAmaclHandle,
+                                         OIC_RSRC_TYPE_SEC_AMACL,
+                                         OIC_MI_DEF,
+                                         OIC_RSRC_AMACL_URI,
+                                         AmaclEntityHandler,
+                                         NULL,
+                                         OC_OBSERVABLE);
 
     if (OC_STACK_OK != ret)
     {
@@ -357,23 +488,28 @@ OCStackResult CreateAmaclResource()
     return ret;
 }
 
-/**
- * Initialize Amacl resource by loading data from persistent storage.
- *
- * @retval  OC_STACK_OK for Success, otherwise some error value
- */
 OCStackResult InitAmaclResource()
 {
     OCStackResult ret = OC_STACK_ERROR;
 
-    // Read Amacl resource from PS
-    char* jsonSVRDatabase = GetSVRDatabase();
+    uint8_t *data = NULL;
+    size_t size = 0;
+    ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_AMACL_NAME, &data, &size);
 
-    if (jsonSVRDatabase)
+    // If database read failed
+    if (OC_STACK_OK != ret)
+    {
+        OIC_LOG(DEBUG, TAG, "ReadSVDataFromPS failed");
+    }
+    if (data)
     {
-        // Convert JSON Amacl into binary format
-        gAmacl = JSONToAmaclBin(jsonSVRDatabase);
-        OICFree(jsonSVRDatabase);
+        // Read AMACL resource from PS
+        ret = CBORPayloadToAmacl(data, size, &gAmacl);
+        if (OC_STACK_OK != ret)
+        {
+            OIC_LOG(DEBUG, TAG, "ReadAMACLresourcefromPS failed");
+        }
+        OICFree(data);
     }
 
     // Instantiate 'oic/sec/amacl' resource
@@ -386,11 +522,6 @@ OCStackResult InitAmaclResource()
     return ret;
 }
 
-/**
- * Perform cleanup for Amacl resources.
- *
- * @retval  none
- */
 void DeInitAmaclResource()
 {
     OCDeleteResource(gAmaclHandle);
@@ -400,7 +531,6 @@ void DeInitAmaclResource()
     gAmacl = NULL;
 }
 
-
 OCStackResult AmaclGetAmsDeviceId(const char *resource, OicUuid_t *amsDeviceId)
 {
     OicSecAmacl_t *amacl = NULL;
@@ -412,7 +542,7 @@ OCStackResult AmaclGetAmsDeviceId(const char *resource, OicUuid_t *amsDeviceId)
     {
         for(size_t i = 0; i < amacl->resourcesLen; i++)
         {
-            if (strncmp((amacl->resources[i]), resource, strlen(amacl->resources[i])) == 0)
+            if (0 == strncmp((amacl->resources[i]), resource, strlen(amacl->resources[i])))
             {
                 //Returning the ID of the first AMS service for the resource
                 memcpy(amsDeviceId, &amacl->amss[0], sizeof(*amsDeviceId));
index c9be755..8a65c0b 100644 (file)
@@ -18,6 +18,7 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+#include <string.h>
 #include "oic_malloc.h"
 #include "amsmgr.h"
 #include "resourcemanager.h"
 #include "policyengine.h"
 #include "oic_string.h"
 #include "caremotehandler.h"
-#include <string.h>
 
 #define TAG "SRM-AMSMGR"
 
-
  //Callback for AMS service multicast discovery request.
 static OCStackApplicationResult AmsMgrDiscoveryCallback(void *ctx, OCDoHandle handle,
                          OCClientResponse * clientResponse);
@@ -51,7 +50,6 @@ static OCStackApplicationResult SecurePortDiscoveryCallback(void *ctx, OCDoHandl
 static OCStackApplicationResult AmsMgrAclReqCallback(void *ctx, OCDoHandle handle,
     OCClientResponse * clientResponse);
 
-
 OCStackResult DiscoverAmsService(PEContext_t *context)
 {
     OIC_LOG(INFO, TAG, "IN DiscoverAmsService");
@@ -60,16 +58,11 @@ OCStackResult DiscoverAmsService(PEContext_t *context)
     const char DOXM_DEVICEID_QUERY_FMT[] = "%s?%s=%s";
     char uri[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {};
     OCCallbackData cbData = {.context=NULL};
-    char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};
-    uint32_t outLen = 0;
-    B64Result b64Ret;
 
     VERIFY_NON_NULL(TAG, context, ERROR);
-    b64Ret = b64Encode(context->amsMgrContext->amsDeviceId.id,
-          sizeof(context->amsMgrContext->amsDeviceId.id), base64Buff, sizeof(base64Buff), &outLen);
-    VERIFY_SUCCESS(TAG, B64_OK == b64Ret, ERROR);
     snprintf(uri, sizeof(uri), DOXM_DEVICEID_QUERY_FMT, OIC_RSRC_DOXM_URI,
-                                       OIC_JSON_DEVICE_ID_NAME, base64Buff);
+                                       OIC_JSON_DEVICE_ID_NAME,
+                                       context->amsMgrContext->amsDeviceId.id);
 
     cbData.cb = &AmsMgrDiscoveryCallback;
     cbData.context = (void*)context;
@@ -89,7 +82,6 @@ exit:
     return ret;
 }
 
-
 static OCStackApplicationResult AmsMgrDiscoveryCallback(void *ctx, OCDoHandle handle,
                          OCClientResponse * clientResponse)
 {
@@ -114,15 +106,17 @@ static OCStackApplicationResult AmsMgrDiscoveryCallback(void *ctx, OCDoHandle ha
     }
 
     OicSecDoxm_t *doxm = NULL;
+
     OIC_LOG_V(INFO, TAG, "Doxm DeviceId Discovery response = %s\n",
-          ((OCSecurityPayload*)clientResponse->payload)->securityData);
-    doxm = JSONToDoxmBin(((OCSecurityPayload*)clientResponse->payload)->securityData);
+          ((OCSecurityPayload*)clientResponse->payload)->securityData1);
+    uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData1;
+    size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
 
     //As doxm is NULL amsmgr can't test if response from trusted AMS service
     //so keep the transaction.
-    if(NULL == doxm)
+    if (OC_STACK_OK == CBORPayloadToDoxm(payload, size, &doxm))
     {
-        OIC_LOG_V(ERROR, TAG, "%s : Unable to convert JSON to Binary",__func__);
+        OIC_LOG_V(ERROR, TAG, "%s : Unable to convert CBOR to Binary",__func__);
         return OC_STACK_KEEP_TRANSACTION;
     }
 
@@ -138,7 +132,7 @@ static OCStackApplicationResult AmsMgrDiscoveryCallback(void *ctx, OCDoHandle ha
     {
         OIC_LOG(INFO, TAG, "AMS Manager Sending unicast discovery to get secured port info");
         //Sending Unicast discovery to get secure port information
-        if(OC_STACK_OK == SendUnicastSecurePortDiscovery(context, &clientResponse->devAddr,
+        if (OC_STACK_OK == SendUnicastSecurePortDiscovery(context, &clientResponse->devAddr,
                 clientResponse->connType))
         {
             context->retVal = ACCESS_WAITING_FOR_AMS;
@@ -150,7 +144,6 @@ static OCStackApplicationResult AmsMgrDiscoveryCallback(void *ctx, OCDoHandle ha
     return OC_STACK_DELETE_TRANSACTION;
 }
 
-
 OCStackResult SendUnicastSecurePortDiscovery(PEContext_t *context,OCDevAddr *devAddr,
                                       OCConnectivityType connType)
 {
@@ -198,7 +191,7 @@ static OCStackApplicationResult SecurePortDiscoveryCallback(void *ctx, OCDoHandl
         return OC_STACK_DELETE_TRANSACTION;
     }
 
-    OCResourcePayloadresPayload = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
+    OCResourcePayload *resPayload = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
 
     //Verifying if the ID of the sender is an AMS service that this device trusts.
     if(resPayload &&
@@ -228,7 +221,6 @@ static OCStackApplicationResult SecurePortDiscoveryCallback(void *ctx, OCDoHandl
     return OC_STACK_DELETE_TRANSACTION;
 }
 
-
 OCStackResult SendAclReq(PEContext_t *context, OCDevAddr *devAddr, OCConnectivityType connType,
         uint16_t securedPort)
 {
@@ -269,7 +261,6 @@ exit:
     return ret;
 }
 
-
 static OCStackApplicationResult AmsMgrAclReqCallback(void *ctx, OCDoHandle handle,
     OCClientResponse * clientResponse)
 {
@@ -305,8 +296,9 @@ static OCStackApplicationResult AmsMgrAclReqCallback(void *ctx, OCDoHandle handl
         memcmp(context->amsMgrContext->amsDeviceId.id, clientResponse->identity.id,
                        sizeof(context->amsMgrContext->amsDeviceId.id)) == 0)
     {
+        size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
         OCStackResult ret =
-                InstallNewACL(((OCSecurityPayload*)clientResponse->payload)->securityData);
+                InstallNewACL(((OCSecurityPayload*)clientResponse->payload)->securityData1, size);
         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
 
         OIC_LOG_V(INFO, TAG, "%s : Calling checkPermission", __func__);
@@ -325,7 +317,6 @@ exit:
     return OC_STACK_DELETE_TRANSACTION;
 }
 
-
 OCStackResult UpdateAmsMgrContext(PEContext_t *context, const CAEndpoint_t *endpoint,
                         const CARequestInfo_t *requestInfo)
 {
@@ -333,7 +324,7 @@ OCStackResult UpdateAmsMgrContext(PEContext_t *context, const CAEndpoint_t *endp
 
     //The AmsMgr context endpoint and requestInfo will be free from ,
     //AmsMgrAclReqCallback function
-    if(context->amsMgrContext->endpoint)
+    if (context->amsMgrContext->endpoint)
     {
         OICFree(context->amsMgrContext->endpoint);
         context->amsMgrContext->endpoint = NULL;
@@ -342,7 +333,7 @@ OCStackResult UpdateAmsMgrContext(PEContext_t *context, const CAEndpoint_t *endp
     VERIFY_NON_NULL(TAG, context->amsMgrContext->endpoint, ERROR);
     *context->amsMgrContext->endpoint = *endpoint;
 
-    if(context->amsMgrContext->requestInfo)
+    if (context->amsMgrContext->requestInfo)
     {
         FreeCARequestInfo(context->amsMgrContext->requestInfo);
         context->amsMgrContext->requestInfo = NULL;
@@ -356,7 +347,7 @@ exit:
 
 void FreeCARequestInfo(CARequestInfo_t *requestInfo)
 {
-    if(NULL == requestInfo)
+    if (NULL == requestInfo)
     {
         OIC_LOG_V(ERROR, TAG, "%s: Can't free memory. Received NULL requestInfo", __func__);
         return;
@@ -380,7 +371,7 @@ bool FoundAmaclForRequest(PEContext_t *context)
     memset(&context->amsMgrContext->amsDeviceId, 0, sizeof(context->amsMgrContext->amsDeviceId));
 
     //Call amacl resource function to get the AMS service deviceID for the resource
-    if(OC_STACK_OK == AmaclGetAmsDeviceId(context->resource, &context->amsMgrContext->amsDeviceId))
+    if (OC_STACK_OK == AmaclGetAmsDeviceId(context->resource, &context->amsMgrContext->amsDeviceId))
     {
         OIC_LOG_V(INFO, TAG, "%s:AMACL found for the requested resource %s",
                 __func__, context->resource);
@@ -397,12 +388,11 @@ bool FoundAmaclForRequest(PEContext_t *context)
      return ret;
 }
 
-
 void ProcessAMSRequest(PEContext_t *context)
 {
     OicUuid_t  emptyUuid = {.id={}};
     OIC_LOG_V(INFO, TAG, "Entering %s", __func__);
-    if(NULL != context)
+    if (NULL != context)
     {
         if((false == context->matchingAclFound) && (false == context->amsProcessing))
         {
index 2a1ac98..4c396f1 100644 (file)
@@ -1,38 +1,38 @@
-/******************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- ******************************************************************/
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #include "base64.h"
 
-/**< base character of Base64  */
+/** base character of Base64. */
 static const char g_b64TransTbl[] =
                 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdef"\
                 "ghijklmnopqrstuvwxyz0123456789+/";
 
 /**
- * base64 block encode function
+ * base64 block encode function.
  *
- * @param[in] in  octet stream, max 3 byte
- * @param[out] out  base64 encoded stream, 4 byte
- * @param[in] len  byte-length of in
+ * @param in is the octet stream, max 3 byte.
+ * @param out is the Base64 encoded stream, 4 byte.
+ * @param len is the  byte-length of octet stream.
  *
- * @return  B64_OK for Success, otherwise some error value
+ * @return ::B64_OK for Success, otherwise some error value.
  */
 static B64Result b64EncodeBlk(const uint8_t* in, char* out, uint32_t len)
 {
@@ -43,7 +43,7 @@ static B64Result b64EncodeBlk(const uint8_t* in, char* out, uint32_t len)
 
     out[0] = g_b64TransTbl[in[0] >> 2];
 
-    if(1 == len)
+    if (1 == len)
     {
         out[1] = g_b64TransTbl[((in[0] & 0x03) << 4)];
     }
@@ -52,7 +52,7 @@ static B64Result b64EncodeBlk(const uint8_t* in, char* out, uint32_t len)
         out[1] = g_b64TransTbl[((in[0] & 0x03) << 4) | ((in[1] & 0xf0) >> 4)];
     }
 
-    if(2 == len)
+    if (2 == len)
     {
         out[2] = g_b64TransTbl[((in[1] & 0x0f) << 2)];
     }
@@ -77,25 +77,9 @@ static B64Result b64EncodeBlk(const uint8_t* in, char* out, uint32_t len)
     return B64_OK;
 }
 
-/**
- * Encode the plain message in base64.
- *
- * @param[in] in  Plain message
- * @param[in] inLen  Byte length of 'in'
- * @param[in,out] outBuf Output buffer
- *                Base64 encoded message will be written into 'out'
- *                NOTE : This method adds a NULL to the string configuration
- * @param[in] outBufSize Size of output buffer
- * @param[out] outLen  Byte length of encoded message
- *
- * @return  B64_OK for Success, otherwise some error value
-*/
 B64Result b64Encode(const uint8_t* in, const size_t inLen,
                char* outBuf, const size_t outBufSize, uint32_t* outLen)
 {
-    size_t i;
-    size_t minBufSize;
-
     if (NULL == in || 0 == inLen || NULL ==  outBuf || NULL == outLen )
     {
         return B64_INVALID_PARAM;
@@ -104,12 +88,13 @@ B64Result b64Encode(const uint8_t* in, const size_t inLen,
     *outLen = ((inLen / 3) * 3 == inLen) ?
               ((inLen / 3) * 4) :
               (((inLen / 3) + 1) * 4);
-    minBufSize = (*outLen + 1);
-    if(outBufSize < minBufSize)
+    uint32_t minBufSize = (*outLen + 1);
+    if (outBufSize < minBufSize)
     {
         return B64_OUTPUT_BUFFER_TOO_SMALL;
     }
 
+    uint32_t i;
     for (i = 0; i < inLen / 3; i++)
     {
         if(B64_OK != b64EncodeBlk(in + i * 3, outBuf + i * 4, 3))
@@ -118,9 +103,9 @@ B64Result b64Encode(const uint8_t* in, const size_t inLen,
         }
     }
 
-    if (i * 3 != inLen)
+    if (((size_t)i * 3) != inLen)
     {
-        if(B64_OK != b64EncodeBlk(in + i * 3, outBuf + i * 4, inLen - i * 3))
+        if (B64_OK != b64EncodeBlk(in + i * 3, outBuf + i * 4, inLen - i * 3))
         {
             return B64_INVALID_PARAM;
         }
@@ -132,11 +117,11 @@ B64Result b64Encode(const uint8_t* in, const size_t inLen,
 }
 
 /**
- * Get decoded value
+ * Get decoded value.
  *
- * @param[in] c  Base64 encoded charactor
+ * @param c is the Base64 encoded character.
  *
- * @return decoded value, 6-bit
+ * @return decoded value, 6-bit.
  */
 static uint32_t b64GetVal(char c)
 {
@@ -169,23 +154,21 @@ static uint32_t b64GetVal(char c)
 }
 
 /**
- * base64 block decode function
+ * Base64 block decode function.
  *
- * @param[in] in  Base64 encoded stream, 4 bytes
- * @param[out] out  Octet stream, 3 bytes
+ * @param in is the Base64 encoded stream, 4 bytes.
+ * @param out is the Octet stream, 3 bytes.
  *
- * @return  B64_OK for Success, otherwise some error value
+ * @return ::B64_OK for Success, otherwise some error value.
  */
 static B64Result b64DecodeBlk(const char* in, uint8_t* out)
 {
-    uint32_t val;
-
-    if(NULL == in || NULL == out)
+    if (NULL == in || NULL == out)
     {
         return B64_INVALID_PARAM;
     }
 
-    val = (b64GetVal(in[0]) << 18) | (b64GetVal(in[1]) << 12) |
+    uint32_t val = (b64GetVal(in[0]) << 18) | (b64GetVal(in[1]) << 12) |
           (b64GetVal(in[2]) << 6) | (b64GetVal(in[3]));
 
     out[0] = (val >> 16) & 0xff;
@@ -202,47 +185,32 @@ static B64Result b64DecodeBlk(const char* in, uint8_t* out)
     return B64_OK;
 }
 
-/**
- * Decode the encoded message in base64.
- *
- * @param[in] in  Base64 encoded message
- * @param[in] inLen  Byte lenth of 'in'
- * @param[in, out] outBuf  Output buffer
- *                 Base64 decoded message will be written into 'out'
- * @param[in] outBufSize Size of output buffer
- * @param[out] outLen  Byte length of decoded message
- *
- * @return  B64_OK for Success, otherwise some error value
- */
 B64Result b64Decode(const char* in, const size_t inLen,
                uint8_t* outBuf, size_t outBufSize, uint32_t* outLen)
 {
-    uint32_t i;
-    uint32_t minBufSize;
-
     if (NULL == in || 0 == inLen || 0 != (inLen & 0x03) || NULL == outBuf || NULL == outLen)
     {
         return B64_INVALID_PARAM;
     }
 
     *outLen = (inLen / 4) * 3;
-    minBufSize = (inLen / 4) * 3;
-    if('=' == in[inLen - 1])
+    uint32_t minBufSize = (inLen / 4) * 3;
+    if ('=' == in[inLen - 1])
     {
         minBufSize--;
         (*outLen)--;
     }
-    if('=' == in[inLen - 2])
+    if ('=' == in[inLen - 2])
     {
         minBufSize--;
         (*outLen)--;
     }
-    if(outBufSize < minBufSize)
+    if (outBufSize < minBufSize)
     {
         return B64_OUTPUT_BUFFER_TOO_SMALL;
     }
 
-    for (i = 0; i < inLen / 4; i++)
+    for (uint32_t i = 0; i < inLen / 4; i++)
     {
         if(B64_OK != b64DecodeBlk(in + i * 4, outBuf + i * 3))
         {
index 54f17b4..76fbe19 100644 (file)
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #define __STDC_LIMIT_MACROS
+
+#include <stdlib.h>
+#ifdef WITH_ARDUINO
+#include <string.h>
+#else
+#include <strings.h>
+#endif
+#include <stdint.h>
+
+#include "cainterface.h"
+#include "payload_logging.h"
 #include "ocstack.h"
-#include "logger.h"
+#include "ocrandom.h"
+#include "base64.h"
+#include "ocserverrequest.h"
 #include "oic_malloc.h"
-#include "cJSON.h"
-#include "resourcemanager.h"
-#include "psinterface.h"
+#include "ocpayload.h"
 #include "utlist.h"
-#include "srmresourcestrings.h"
 #include "credresource.h"
-#include "ocrandom.h"
 #include "doxmresource.h"
-#include "base64.h"
-#include "srmutility.h"
-#include "cainterface.h"
-#include "pbkdf2.h"
-#include <stdlib.h>
+#include "pstatresource.h"
 #include "iotvticalendar.h"
-#include "ocserverrequest.h"
+#include "pbkdf2.h"
+#include "resourcemanager.h"
+#include "srmresourcestrings.h"
+#include "srmutility.h"
+#include "psinterface.h"
+#include "pinoxmcommon.h"
 
 #ifdef __WITH_DTLS__
 #include "global.h"
-#endif //__WITH_DTLS__
+#endif
 
-#ifdef WITH_ARDUINO
-#include <string.h>
+#define TAG  "SRM-CREDL"
+
+/** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
+ * The value of payload size is increased until reaching belox max cbor size. */
+#ifndef __WITH_X509__
+static const uint8_t CBOR_SIZE = 255;
 #else
-#include <strings.h>
+static const uint16_t CBOR_SIZE = 1024;
 #endif
-#include <stdint.h>
 
-#define TAG  "SRM-CREDL"
+/** Max cbor size payload. */
+static const uint16_t CBOR_MAX_SIZE = 4400;
 
+/** CRED Map size - Number of mandatory items. */
+static const uint8_t CRED_MAP_SIZE = 4;
 
 static OicSecCred_t        *gCred = NULL;
 static OCResourceHandle    gCredHandle = NULL;
@@ -62,7 +78,7 @@ static void FreeCred(OicSecCred_t *cred)
 {
     if(NULL == cred)
     {
-        OIC_LOG (ERROR, TAG, "Invalid Parameter");
+        OIC_LOG(ERROR, TAG, "Invalid Parameter");
         return;
     }
     //Note: Need further clarification on roleID data type
@@ -72,7 +88,9 @@ static void FreeCred(OicSecCred_t *cred)
 #endif
 
     //Clean PublicData
+#ifdef __WITH_X509__
     OICFree(cred->publicData.data);
+#endif
 
     //Clean PrivateData
     OICFree(cred->privateData.data);
@@ -100,347 +118,341 @@ void DeleteCredList(OicSecCred_t* cred)
     }
 }
 
-/**
- * This function converts credential data into JSON format.
- * Caller needs to invoke 'free' when done using
- * returned string.
- * @param cred  pointer to instance of OicSecCred_t structure.
- *
- * @retval
- *      pointer to JSON credential representation - if credential for subjectId found
- *      NULL                                      - if credential for subjectId not found
- */
-char * BinToCredJSON(const OicSecCred_t * cred)
+static size_t OicSecCredCount(const OicSecCred_t *secCred)
 {
-    cJSON *jsonRoot = NULL;
-    char *jsonStr = NULL;
-
-    if (cred)
+    size_t size = 0;
+    for (const OicSecCred_t *cred = secCred; cred; cred = cred->next)
     {
-        char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};
-        uint32_t outLen = 0;
-        B64Result b64Ret = B64_OK;
-
-        jsonRoot = cJSON_CreateObject();
-        VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+        size++;
+    }
+    return size;
+}
 
-        cJSON *jsonCredArray = NULL;
-        cJSON_AddItemToObject(jsonRoot, OIC_JSON_CRED_NAME,
-                jsonCredArray = cJSON_CreateArray());
-        VERIFY_NON_NULL(TAG, jsonCredArray, ERROR);
+OCStackResult CredToCBORPayload(const OicSecCred_t *credS, uint8_t **cborPayload,
+                                size_t *cborSize)
+{
+    if (NULL == credS || NULL == cborPayload || NULL != *cborPayload || NULL == cborSize)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+    OIC_LOG(DEBUG, TAG, "CredToCBORPayload IN");
+    OCStackResult ret = OC_STACK_ERROR;
+    size_t cborLen = *cborSize;
+    if (0 == cborLen)
+    {
+        cborLen = CBOR_SIZE;
+    }
 
-        while(cred)
-        {
-            cJSON *jsonCred = cJSON_CreateObject();
-            VERIFY_NON_NULL(TAG, jsonCred, ERROR);
+    *cborSize = 0;
+    *cborPayload = NULL;
 
-            //CredID -- Mandatory
-            cJSON_AddNumberToObject(jsonCred, OIC_JSON_CREDID_NAME, (int)cred->credId);
+    CborEncoder encoder = { {.ptr = NULL }, .end = 0 };
+    CborEncoder credArray = { {.ptr = NULL }, .end = 0 };
+    int64_t cborEncoderResult = CborNoError;
 
-            //Subject -- Mandatory
-            outLen = 0;
-            memset(base64Buff, 0, sizeof(base64Buff));
-            b64Ret = b64Encode(cred->subject.id, sizeof(cred->subject.id), base64Buff,
-                   sizeof(base64Buff), &outLen);
-            VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
-            cJSON_AddStringToObject(jsonCred, OIC_JSON_SUBJECT_NAME, base64Buff);
+    const OicSecCred_t *cred = credS;
+    uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
+    VERIFY_NON_NULL(TAG, outPayload, ERROR);
+    cbor_encoder_init(&encoder, outPayload, cborLen, 0);
 
-            //Note: Need further clarification on roleID data type
-#if 0
-            //RoleId -- Not Mandatory
-            if(cred->roleIdsLen > 0)
-            {
-                cJSON *jsonRoleIdsArray = NULL;
-                cJSON_AddItemToObject (jsonCred, OIC_JSON_ROLEIDS_NAME,
-                                         jsonRoleIdsArray = cJSON_CreateArray());
-                VERIFY_NON_NULL(TAG, jsonRoleIdsArray, ERROR);
-                for (size_t i = 0; i < cred->roleIdsLen; i++)
-                {
-                    cJSON_AddItemToArray (jsonRoleIdsArray,
-                            cJSON_CreateString((char *)cred->roleIds[i].id));
-                }
-            }
-#endif
+    // Create CRED Array
+    cborEncoderResult |= cbor_encoder_create_array(&encoder, &credArray, OicSecCredCount(cred));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding0 Cred Array.");
 
-            //CredType -- Mandatory
-            cJSON_AddNumberToObject(jsonCred, OIC_JSON_CREDTYPE_NAME,(int)cred->credType);
+    while (cred)
+    {
+        CborEncoder credMap = { {.ptr = NULL }, .end = 0, .added = 0, .flags = 0 };
+        size_t mapSize = CRED_MAP_SIZE;
+        if (cred->period)
+        {
+            mapSize++;
+        }
+#ifdef __WITH_X509__
+        if (cred->publicData.data)
+        {
+            mapSize++;
+        }
+#endif /* __WITH_X509__ */
+        if (cred->privateData.data)
+        {
+            mapSize++;
+        }
+        cborEncoderResult |= cbor_encoder_create_map(&credArray, &credMap, mapSize);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Map");
+
+        //CredID -- Mandatory
+        cborEncoderResult |= cbor_encode_text_string(&credMap, OIC_JSON_CREDID_NAME,
+            strlen(OIC_JSON_CREDID_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Id Tag. ");
+        cborEncoderResult |= cbor_encode_int(&credMap, cred->credId);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Id Value.");
+
+        //Subject -- Mandatory
+        cborEncoderResult |= cbor_encode_text_string(&credMap, OIC_JSON_SUBJECT_NAME,
+            strlen(OIC_JSON_SUBJECT_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Subject Tag.");
+        cborEncoderResult |= cbor_encode_byte_string(&credMap, cred->subject.id,
+            sizeof(cred->subject.id));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Subject Value.");
+
+        //CredType -- Mandatory
+        cborEncoderResult |= cbor_encode_text_string(&credMap, OIC_JSON_CREDTYPE_NAME,
+            strlen(OIC_JSON_CREDTYPE_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Tag.");
+        cborEncoderResult |= cbor_encode_int(&credMap, cred->credType);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Value.");
 
 #ifdef __WITH_X509__
-            //PublicData -- Not Mandatory
-            if(cred->publicData.data)
-            {
-                if (SIGNED_ASYMMETRIC_KEY == cred->credType)
-                {
-                    cJSON_AddItemToObject(jsonCred, OIC_JSON_PUBLICDATA_NAME,
-                                          cJSON_Parse(cred->publicData.data));
-                }
-                else
-                {
-                cJSON_AddStringToObject(jsonCred, OIC_JSON_PUBLICDATA_NAME, cred->publicData.data);
-                }
-            }
+        //PublicData -- Not Mandatory
+        if (cred->publicData.data)
+        {
+            cborEncoderResult |= cbor_encode_text_string(&credMap,
+                OIC_JSON_PUBLICDATA_NAME, strlen(OIC_JSON_PUBLICDATA_NAME));
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Public Data Tag.");
+            cborEncoderResult |= cbor_encode_byte_string(&credMap, cred->publicData.data,
+                    cred->publicData.len);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Public Tag Value.");
+        }
 #endif /*__WITH_X509__*/
-            //PrivateData -- Not Mandatory
-            if(cred->privateData.data)
-            {
-#ifdef __WITH_X509__
-                if (SIGNED_ASYMMETRIC_KEY == cred->credType)
-                {
-                    cJSON_AddItemToObject(jsonCred, OIC_JSON_PRIVATEDATA_NAME,
-                                          cJSON_Parse(cred->privateData.data));
-                }
-                else
-                {
-                    cJSON_AddStringToObject(jsonCred, OIC_JSON_PRIVATEDATA_NAME, cred->privateData.data);
-                }
-#else
-                cJSON_AddStringToObject(jsonCred, OIC_JSON_PRIVATEDATA_NAME, cred->privateData.data);
-#endif
-            }
+        //PrivateData -- Not Mandatory
+        if(cred->privateData.data)
+        {
+            cborEncoderResult |= cbor_encode_text_string(&credMap,
+                OIC_JSON_PRIVATEDATA_NAME, strlen(OIC_JSON_PRIVATEDATA_NAME));
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Private Data Tag");
+            cborEncoderResult |= cbor_encode_byte_string(&credMap, cred->privateData.data,
+                cred->privateData.len);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Private Data Value.");
+        }
 
-            //Period -- Not Mandatory
-            if(cred->period)
-            {
-                cJSON_AddStringToObject(jsonCred, OIC_JSON_PERIOD_NAME,
-                                        cred->period);
-            }
+        //Period -- Not Mandatory
+        if(cred->period)
+        {
+            cborEncoderResult |= cbor_encode_text_string(&credMap, OIC_JSON_PERIOD_NAME,
+                strlen(OIC_JSON_PERIOD_NAME));
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Period Name Tag.");
+            cborEncoderResult |= cbor_encode_text_string(&credMap, cred->period,
+                strlen(cred->period));
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Period Name Value.");
+        }
 
-            //Owners -- Mandatory
-            cJSON *jsonOwnrArray = NULL;
-            cJSON_AddItemToObject (jsonCred, OIC_JSON_OWNERS_NAME,
-                                             jsonOwnrArray = cJSON_CreateArray());
-            VERIFY_NON_NULL(TAG, jsonOwnrArray, ERROR);
+        //Owners -- Mandatory
+        {
+            cborEncoderResult |= cbor_encode_text_string(&credMap, OIC_JSON_OWNERS_NAME,
+                strlen(OIC_JSON_OWNERS_NAME));
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owners Name Tag.");
+            CborEncoder owners = { {.ptr = NULL }, .end = 0 };
+            cborEncoderResult |= cbor_encoder_create_array(&credMap, &owners, cred->ownersLen);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owners Name Array.");
             for (size_t i = 0; i < cred->ownersLen; i++)
             {
-                outLen = 0;
-                memset(base64Buff, 0, sizeof(base64Buff));
-                b64Ret = b64Encode(cred->owners[i].id, sizeof(cred->owners[i].id),
-                        base64Buff, sizeof(base64Buff), &outLen);
-                VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
-                cJSON_AddItemToArray (jsonOwnrArray,
-                                       cJSON_CreateString((char *)(base64Buff)));
+                cborEncoderResult |= cbor_encode_byte_string(&owners, (uint8_t *)cred->owners[i].id,
+                    sizeof(cred->owners[i].id));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owners Array Value.");
             }
-
-            /* Attach current cred node to cred Array */
-            cJSON_AddItemToArray(jsonCredArray, jsonCred);
-            cred = cred->next;
+            cborEncoderResult |= cbor_encoder_close_container(&credMap, &owners);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Owners Name Array.");
         }
+        cborEncoderResult |= cbor_encoder_close_container(&credArray, &credMap);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Cred Map.");
 
-        jsonStr = cJSON_PrintUnformatted(jsonRoot);
-    }
+        cred = cred->next;
+   }
+   cborEncoderResult |= cbor_encoder_close_container(&encoder, &credArray);
+   VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Cred Array.");
 
+   if (CborNoError == cborEncoderResult)
+   {
+       *cborPayload = outPayload;
+       *cborSize = encoder.ptr - outPayload;
+        ret = OC_STACK_OK;
+    }
+    OIC_LOG(DEBUG, TAG, "CredToCBORPayload OUT");
 exit:
-    if (jsonRoot)
+    if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
     {
-        cJSON_Delete(jsonRoot);
+       // reallocate and try again!
+       OICFree(outPayload);
+       outPayload = NULL;
+       // Since the allocated initial memory failed, double the memory.
+       cborLen += encoder.ptr - encoder.end;
+       cborEncoderResult = CborNoError;
+       ret = CredToCBORPayload(credS, cborPayload, &cborLen);
+       if (OC_STACK_OK == ret)
+       {
+           *cborSize = cborLen;
+        }
     }
-    return jsonStr;
+
+    if (CborNoError != cborEncoderResult)
+    {
+       OICFree(outPayload);
+       outPayload = NULL;
+       *cborSize = 0;
+       *cborPayload = NULL;
+       ret = OC_STACK_ERROR;
+    }
+
+    return ret;
 }
 
-/*
- * This internal method converts JSON cred into binary cred.
- */
-OicSecCred_t * JSONToCredBin(const char * jsonStr)
+OCStackResult CBORPayloadToCred(const uint8_t *cborPayload, size_t size,
+                                OicSecCred_t **secCred)
 {
-    OCStackResult ret = OC_STACK_ERROR;
-    OicSecCred_t * headCred = NULL;
-    OicSecCred_t * prevCred = NULL;
-    cJSON *jsonCredArray = NULL;
+    if (NULL == cborPayload || NULL == secCred || NULL != *secCred)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+    OIC_LOG(DEBUG, TAG, "CBORPayloadToCred IN");
 
-    cJSON *jsonRoot = cJSON_Parse(jsonStr);
-    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+    *secCred = NULL;
 
-    jsonCredArray = cJSON_GetObjectItem(jsonRoot, OIC_JSON_CRED_NAME);
-    VERIFY_NON_NULL(TAG, jsonCredArray, ERROR);
-    if (cJSON_Array == jsonCredArray->type)
-    {
-        int numCred = cJSON_GetArraySize(jsonCredArray);
-        int idx = 0;
+    OCStackResult ret = OC_STACK_ERROR;
 
-        unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
-        uint32_t outLen = 0;
-        B64Result b64Ret = B64_OK;
+    CborValue credCbor;
+    CborParser parser;
+    CborError cborFindResult = CborNoError;
+    OicSecCred_t *cred = NULL;
 
-        VERIFY_SUCCESS(TAG, numCred > 0, ERROR);
-        do
-        {
-            cJSON *jsonCred = cJSON_GetArrayItem(jsonCredArray, idx);
-            VERIFY_NON_NULL(TAG, jsonCred, ERROR);
+    int cborLen = size;
+    if (0 == size)
+    {
+        cborLen = CBOR_SIZE;
+    }
+    cbor_parser_init(cborPayload, cborLen, 0, &parser, &credCbor);
 
-            OicSecCred_t *cred = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
-            VERIFY_NON_NULL(TAG, cred, ERROR);
+    OicSecCred_t *headCred = NULL;
 
-            headCred = (headCred) ? headCred : cred;
-            if (prevCred)
-            {
-                prevCred->next = cred;
-            }
-            size_t jsonObjLen = 0;
-            cJSON *jsonObj = NULL;
+    size_t len = 0;
+    CborValue credArray;
+    cborFindResult = cbor_value_enter_container(&credCbor, &credArray);
+    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Cred Array.");
 
-            //CredId -- Mandatory
-            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_CREDID_NAME);
-            if(jsonObj)
-            {
-                VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
-                cred->credId = jsonObj->valueint;
-            }
+    while (cbor_value_is_valid(&credArray))
+    {
+        cred = (OicSecCred_t *) OICCalloc(1, sizeof(OicSecCred_t));
+        VERIFY_NON_NULL(TAG, cred, ERROR);
 
-            //subject -- Mandatory
-            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_SUBJECT_NAME);
-            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-            VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
-            outLen = 0;
-            memset(base64Buff, 0, sizeof(base64Buff));
-            b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring),
-                    base64Buff, sizeof(base64Buff), &outLen);
-            VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(cred->subject.id)),
-                           ERROR);
-            memcpy(cred->subject.id, base64Buff, outLen);
-
-            //CredType -- Mandatory
-            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_CREDTYPE_NAME);
-            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-            VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
-            cred->credType = (OicSecCredType_t)jsonObj->valueint;
-
-            //PrivateData is mandatory for some of the credential types listed below.
-            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_PRIVATEDATA_NAME);
-            if ((cred->credType & SYMMETRIC_PAIR_WISE_KEY) ||
-                (cred->credType & SYMMETRIC_GROUP_KEY) ||
-                (cred->credType & PIN_PASSWORD))
-            {
-                if(jsonObj)
-                {
-                    VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
-                }
-            }
-#ifdef __WITH_X509__
-            else if (cred->credType & SIGNED_ASYMMETRIC_KEY)
-            {
-                VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-                VERIFY_SUCCESS(TAG, cJSON_Object == jsonObj->type, ERROR);
-            }
-#endif //  __WITH_X509__
-            if (NULL != jsonObj)
-            {
-                if (cJSON_String == jsonObj->type)
-                {
-                    jsonObjLen = strlen(jsonObj->valuestring) + 1;
-                    cred->privateData.data = (char *)OICMalloc(jsonObjLen);
-                    VERIFY_NON_NULL(TAG, (cred->privateData.data), ERROR);
-                    strncpy((char *)cred->privateData.data, (char *)jsonObj->valuestring, jsonObjLen);
-                }
-#ifdef __WITH_X509__
-                else if (SIGNED_ASYMMETRIC_KEY == cred->credType && cJSON_Object == jsonObj->type)
-                {
-                    cred->privateData.data = cJSON_PrintUnformatted(jsonObj);
-                    VERIFY_NON_NULL(TAG, (cred->privateData.data), ERROR);
-                }
-#endif // __WITH_X509__
-            }
-            else
+        //CredId -- Mandatory
+        CborValue credMap;
+        cborFindResult = cbor_value_map_find_value(&credArray, OIC_JSON_CREDID_NAME, &credMap);
+        if (CborNoError == cborFindResult && cbor_value_is_integer(&credMap))
+        {
+            cborFindResult = cbor_value_get_int(&credMap, (int *) &cred->credId);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding CredId.");
+        }
+        //subject -- Mandatory
+        cborFindResult = cbor_value_map_find_value(&credArray, OIC_JSON_SUBJECT_NAME, &credMap);
+        if (CborNoError == cborFindResult && cbor_value_is_byte_string(&credMap))
+        {
+            uint8_t *id = NULL;
+            cborFindResult = cbor_value_dup_byte_string(&credMap, &id, &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Subject Name.");
+            memcpy(cred->subject.id, id, len);
+            OICFree(id);
+        }
+        //CredType -- Mandatory
+        cborFindResult = cbor_value_map_find_value(&credArray, OIC_JSON_CREDTYPE_NAME, &credMap);
+        if (CborNoError == cborFindResult && cbor_value_is_integer(&credMap))
+        {
+            cborFindResult = cbor_value_get_int(&credMap, (int *) &cred->credType);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding CredType.");
+        }
+        //Owners -- Mandatory
+        cborFindResult = cbor_value_map_find_value(&credArray, OIC_JSON_OWNERS_NAME, &credMap);
+        if (CborNoError == cborFindResult && cbor_value_is_array(&credMap))
+        {
+            CborValue owners;
+            cborFindResult = cbor_value_get_array_length(&credMap, &cred->ownersLen);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Array Len.");
+            cborFindResult = cbor_value_enter_container(&credMap, &owners);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering Container.");
+            int i = 0;
+            cred->owners = (OicUuid_t *)OICCalloc(cred->ownersLen, sizeof(*cred->owners));
+            VERIFY_NON_NULL(TAG, cred->owners, ERROR);
+            while (cbor_value_is_valid(&owners))
             {
-                cred->privateData.data = NULL;
+                uint8_t *owner = NULL;
+                cborFindResult = cbor_value_dup_byte_string(&owners, &owner, &len, NULL);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owner Byte String.");
+                memcpy(cred->owners[i++].id, owner, len);
+                OICFree(owner);
+                cborFindResult = cbor_value_advance(&owners);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Array.");
             }
-
-            //PublicData is mandatory only for SIGNED_ASYMMETRIC_KEY credentials type.
-            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_PUBLICDATA_NAME);
+        }
+        //PrivateData is mandatory for some of the credential types listed below.
+        cborFindResult = cbor_value_map_find_value(&credArray, OIC_JSON_PRIVATEDATA_NAME, &credMap);
+        if (CborNoError == cborFindResult && cbor_value_is_byte_string(&credMap))
+        {
+            cborFindResult = cbor_value_dup_byte_string(&credMap,
+                &cred->privateData.data, &cred->privateData.len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Byte Array.");
+        }
 #ifdef __WITH_X509__
+        //PublicData is mandatory only for SIGNED_ASYMMETRIC_KEY credentials type.
+        cborFindResult = cbor_value_map_find_value(&credArray, OIC_JSON_PUBLICDATA_NAME, &credMap);
+        if (CborNoError == cborFindResult && cbor_value_is_byte_string(&credMap))
+        {
             if (cred->credType & SIGNED_ASYMMETRIC_KEY)
             {
-                VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-                VERIFY_SUCCESS(TAG, cJSON_Object == jsonObj->type, ERROR);
-            }
-#endif //  __WITH_X509__
-            if (NULL != jsonObj)
-            {
-                if (cJSON_String == jsonObj->type)
-                {
-                    jsonObjLen = strlen(jsonObj->valuestring) + 1;
-                    cred->publicData.data = (char *)OICMalloc(jsonObjLen);
-                    VERIFY_NON_NULL(TAG, (cred->publicData.data), ERROR);
-                    strncpy((char *)cred->publicData.data, (char *)jsonObj->valuestring, jsonObjLen);
-                }
-#ifdef __WITH_X509__
-                else if (SIGNED_ASYMMETRIC_KEY == cred->credType && cJSON_Object == jsonObj->type)
-                {
-                    cred->publicData.data = cJSON_PrintUnformatted(jsonObj);
-                    VERIFY_NON_NULL(TAG, (cred->publicData.data), ERROR);
-                }
-#endif //  __WITH_X509__
-            }
-
-            //Period -- Not Mandatory
-            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_PERIOD_NAME);
-            if(jsonObj && cJSON_String == jsonObj->type)
-            {
-                jsonObjLen = strlen(jsonObj->valuestring) + 1;
-                cred->period = (char *)OICMalloc(jsonObjLen);
-                VERIFY_NON_NULL(TAG, cred->period, ERROR);
-                strncpy(cred->period, jsonObj->valuestring, jsonObjLen);
+                cborFindResult = cbor_value_dup_byte_string(&credMap, &cred->publicData.data,
+                &cred->publicData.len, NULL);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Public Data.");
             }
-
-            //Owners -- Mandatory
-            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_OWNERS_NAME);
-            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-            VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
-            cred->ownersLen = (size_t)cJSON_GetArraySize(jsonObj);
-            VERIFY_SUCCESS(TAG, cred->ownersLen > 0, ERROR);
-            cred->owners = (OicUuid_t*)OICCalloc(cred->ownersLen, sizeof(OicUuid_t));
-            VERIFY_NON_NULL(TAG, (cred->owners), ERROR);
-            for(size_t i = 0; i < cred->ownersLen; i++)
+        }
+#endif  //__WITH_X509__
+        //Period -- Not Mandatory
+        cborFindResult = cbor_value_map_find_value(&credArray, OIC_JSON_PERIOD_NAME, &credMap);
+        if (CborNoError == cborFindResult && cbor_value_is_text_string(&credMap))
+        {
+            cborFindResult = cbor_value_dup_text_string(&credMap, &cred->period, &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Period.");
+        }
+        cred->next = NULL;
+        if (NULL == headCred)
+        {
+            headCred = cred;
+        }
+        else
+        {
+            OicSecCred_t *temp = headCred;
+            while (temp->next)
             {
-                cJSON *jsonOwnr = cJSON_GetArrayItem(jsonObj, i);
-                VERIFY_NON_NULL(TAG, jsonOwnr, ERROR);
-                VERIFY_SUCCESS(TAG, cJSON_String == jsonOwnr->type, ERROR);
-                outLen = 0;
-                memset(base64Buff, 0, sizeof(base64Buff));
-                b64Ret = b64Decode(jsonOwnr->valuestring, strlen(jsonOwnr->valuestring),
-                         base64Buff, sizeof(base64Buff), &outLen);
-                VERIFY_SUCCESS(TAG, (b64Ret == B64_OK &&
-                               outLen <= sizeof(cred->owners[i].id)), ERROR);
-                memcpy(cred->owners[i].id, base64Buff, outLen);
+                temp = temp->next;
             }
-            prevCred = cred;
-        } while( ++idx < numCred);
+            temp->next = cred;
+        }
+        if (cbor_value_is_valid(&credArray))
+        {
+            cborFindResult = cbor_value_advance(&credArray);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Cred Array.");
+        }
     }
-
+    *secCred = headCred;
     ret = OC_STACK_OK;
 
+    OIC_LOG(DEBUG, TAG, "CBORPayloadToCred OUT");
+
 exit:
-    cJSON_Delete(jsonRoot);
-    if (OC_STACK_OK != ret)
+    if (CborNoError != cborFindResult)
     {
         DeleteCredList(headCred);
         headCred = NULL;
+        ret = OC_STACK_ERROR;
     }
-    return headCred;
+
+    return ret;
 }
 
-/**
- * This function generates the bin credential data.
- *
- * @param subject pointer to subject of this credential.
- * @param credType credential type.
- * @param publicData public data such as public key.
- * @param privateData private data such as private key.
- *        The privateData is expected in base64 encoded format.
- * @param ownersLen length of owners array
- * @param owners array of owners.
- *
- * @retval
- *      pointer to instance of OicSecCred_t  - success
- *      NULL                                 - error
- */
 OicSecCred_t * GenerateCredential(const OicUuid_t * subject, OicSecCredType_t credType,
-                                 const char * publicData, const char * privateData,
-                                 size_t ownersLen, const OicUuid_t * owners)
+                                  const OicSecCert_t * publicData, const OicSecKey_t* privateData,
+                                  size_t ownersLen, const OicUuid_t * owners)
 {
     (void)publicData;
     OCStackResult ret = OC_STACK_ERROR;
 
-    OicSecCred_t *cred = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
+    OicSecCred_t *cred = (OicSecCred_t *)OICCalloc(1, sizeof(*cred));
     VERIFY_NON_NULL(TAG, cred, ERROR);
 
     //CredId is assigned before appending new cred to the existing
@@ -455,27 +467,29 @@ OicSecCred_t * GenerateCredential(const OicUuid_t * subject, OicSecCredType_t cr
     cred->credType = credType;
 
 #ifdef __WITH_X509__
-    if(publicData)
+    if (publicData && publicData->data)
     {
-        cred->publicData.data = (char *)OICMalloc(strlen(publicData)+1);
+        cred->publicData.data = (uint8_t *)OICCalloc(1, publicData->len);
         VERIFY_NON_NULL(TAG, cred->publicData.data, ERROR);
-        strncpy((char *)cred->publicData.data, publicData, strlen(publicData)+1);
+        memcpy(cred->publicData.data, publicData->data, publicData->len);
+        cred->publicData.len = publicData->len;
     }
 #endif // __WITH_X509__
 
-    if(privateData)
+    if (privateData && privateData->data)
     {
-        cred->privateData.data = (char *)OICMalloc(strlen(privateData)+1);
+        cred->privateData.data = (uint8_t *)OICCalloc(1, privateData->len);
         VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
-        strncpy((char *)cred->privateData.data, privateData, strlen(privateData)+1);
+        memcpy(cred->privateData.data, privateData->data, privateData->len);
+        cred->privateData.len = privateData->len;
     }
 
     VERIFY_SUCCESS(TAG, ownersLen > 0, ERROR);
     cred->ownersLen = ownersLen;
 
-    cred->owners = (OicUuid_t*)OICCalloc(cred->ownersLen, sizeof(OicUuid_t));
+    cred->owners = (OicUuid_t *)OICCalloc(cred->ownersLen, sizeof(*cred->owners));
     VERIFY_NON_NULL(TAG, cred->owners, ERROR);
-    for(size_t i = 0; i < cred->ownersLen; i++)
+    for (size_t i = 0; i < cred->ownersLen; i++)
     {
         memcpy(cred->owners[i].id, owners[i].id, sizeof(cred->owners[i].id));
     }
@@ -495,22 +509,23 @@ static bool UpdatePersistentStorage(const OicSecCred_t *cred)
     bool ret = false;
 
     // Convert Cred data into JSON for update to persistent storage
-    char *jsonStr = BinToCredJSON(cred);
-    if (jsonStr)
+    if (cred)
     {
-        cJSON *jsonCred = cJSON_Parse(jsonStr);
-        OICFree(jsonStr);
-
-        if ((jsonCred) &&
-          (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_CRED_NAME, jsonCred)))
+        uint8_t *payload = NULL;
+        size_t size = 0;
+        OCStackResult res = CredToCBORPayload(cred, &payload, &size);
+        if ((OC_STACK_OK == res) && payload)
         {
-            ret = true;
+            if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_CRED_NAME, payload, size))
+            {
+                ret = true;
+            }
+            OICFree(payload);
         }
-        cJSON_Delete(jsonCred );
     }
     else //Empty cred list
     {
-        if (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_CRED_NAME, NULL))
+        if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_CRED_NAME, NULL, 0))
         {
             ret = true;
         }
@@ -519,23 +534,22 @@ static bool UpdatePersistentStorage(const OicSecCred_t *cred)
 }
 
 /**
- * Compare function used LL_SORT for sorting credentials
+ * Compare function used LL_SORT for sorting credentials.
  *
- * @param first   pointer to OicSecCred_t struct
- * @param second  pointer to OicSecCred_t struct
+ * @param first pointer to OicSecCred_t struct.
+ * @param second  pointer to OicSecCred_t struct.
  *
- *@retval
- *  -1    if credId of first is less than credId of second
- *   0    if credId of first is equal to credId of second
- *   1    if credId of first is greater than credId of second
+ *@return -1, if credId of first is less than credId of second.
+ * 0, if credId of first is equal to credId of second.
+ * 1, if credId of first is greater than credId of second.
  */
 static int CmpCredId(const OicSecCred_t * first, const OicSecCred_t *second)
 {
-    if(first->credId < second->credId)
+    if (first->credId < second->credId)
     {
         return -1;
     }
-    else if(first->credId > second->credId)
+    else if (first->credId > second->credId)
     {
         return 1;
     }
@@ -549,23 +563,19 @@ static int CmpCredId(const OicSecCred_t * first, const OicSecCred_t *second)
  * available due deletion of OicSecCred_t object or one more than
  * credId of last credential in the list.
  *
- * @retval
- *      next available credId  - success
- *      0                      - error
+ * @return next available credId if successful, else 0 for error.
  */
-
 static uint16_t GetCredId()
 {
     //Sorts credential list in incremental order of credId
     LL_SORT(gCred, CmpCredId);
 
-
     OicSecCred_t *currentCred = NULL, *credTmp = NULL;
     uint16_t nextCredId = 1;
 
     LL_FOREACH_SAFE(gCred, currentCred, credTmp)
     {
-        if(currentCred->credId == nextCredId)
+        if (currentCred->credId == nextCredId)
         {
             nextCredId += 1;
         }
@@ -583,38 +593,29 @@ exit:
 }
 
 /**
- * Get the default value
- * @retval  NULL for now. Update it when we finalize the default info.
+ * Get the default value.
+ *
+ * @return  NULL for now.
  */
 static OicSecCred_t* GetCredDefault()
 {
+    // TODO:Update it when we finalize the default info.
     return NULL;
 }
 
-/**
- * This function adds the new cred to the credential list.
- *
- * @param cred pointer to new credential.
- *
- * @retval
- *      OC_STACK_OK     - cred not NULL and persistent storage gets updated
- *      OC_STACK_ERROR  - cred is NULL or fails to update persistent storage
- */
 OCStackResult AddCredential(OicSecCred_t * newCred)
 {
     OCStackResult ret = OC_STACK_ERROR;
-
     VERIFY_SUCCESS(TAG, NULL != newCred, ERROR);
 
     //Assigning credId to the newCred
     newCred->credId = GetCredId();
-
     VERIFY_SUCCESS(TAG, newCred->credId != 0, ERROR);
 
     //Append the new Cred to existing list
     LL_APPEND(gCred, newCred);
 
-    if(UpdatePersistentStorage(gCred))
+    if (UpdatePersistentStorage(gCred))
     {
         ret = OC_STACK_OK;
     }
@@ -632,7 +633,7 @@ OCStackResult RemoveCredential(const OicUuid_t *subject)
 
     LL_FOREACH_SAFE(gCred, cred, tempCred)
     {
-        if(memcmp(cred->subject.id, subject->id, sizeof(subject->id)) == 0)
+        if (memcmp(cred->subject.id, subject->id, sizeof(subject->id)) == 0)
         {
             LL_DELETE(gCred, cred);
             FreeCred(cred);
@@ -640,9 +641,9 @@ OCStackResult RemoveCredential(const OicUuid_t *subject)
         }
     }
 
-    if(deleteFlag)
+    if (deleteFlag)
     {
-        if(UpdatePersistentStorage(gCred))
+        if (UpdatePersistentStorage(gCred))
         {
             ret = OC_STACK_RESOURCE_DELETED;
         }
@@ -663,7 +664,7 @@ OCStackResult RemoveAllCredentials(void)
     DeleteCredList(gCred);
     gCred = GetCredDefault();
 
-    if(!UpdatePersistentStorage(gCred))
+    if (!UpdatePersistentStorage(gCred))
     {
         return OC_STACK_ERROR;
     }
@@ -678,7 +679,7 @@ OCStackResult RemoveAllCredentials(void)
  * @param ownerAdd address of OBT(PT)
  * @param doxm current device's doxm resource
  *
- * @retval
+ * @return
  *     true successfully done and valid ower psk information
  *     false Invalid owner psk information or failed to owner psk generation
  */
@@ -701,34 +702,18 @@ static bool FillPrivateDataOfOwnerPSK(OicSecCred_t* receviedCred, const CAEndpoi
     OIC_LOG_BUFFER(DEBUG, TAG, ownerPSK, OWNER_PSK_LENGTH_128);
 
     //Generate owner credential based on recevied credential information
-    size_t b64BufSize = B64ENCODE_OUT_SAFESIZE(OWNER_PSK_LENGTH_128 * sizeof(char));
-    uint8_t* encodeBuff = OICMalloc((b64BufSize + 1) * sizeof(char));
-    VERIFY_NON_NULL(TAG, encodeBuff, ERROR);
-    uint32_t encodedSize = 0;
-    B64Result b64Ret = b64Encode(ownerPSK, OWNER_PSK_LENGTH_128,
-                                 (char*)encodeBuff, b64BufSize + 1, &encodedSize);
-    VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
-    encodeBuff[encodedSize] = '\0';
-
-    //memory re-allocation for private data
-    OICFree(receviedCred->privateData.data);
-    receviedCred->privateData.data = (char*)OICMalloc((encodedSize + 1) * sizeof(char));
+    receviedCred->privateData.data = (uint8_t *)OICCalloc(1, OWNER_PSK_LENGTH_128);
     VERIFY_NON_NULL(TAG, receviedCred->privateData.data, ERROR);
-
-    //fill the base64 encoded private data
-    strncpy(receviedCred->privateData.data, (char*)encodeBuff, b64BufSize + 1);
+    receviedCred->privateData.len = OWNER_PSK_LENGTH_128;
+    memcpy(receviedCred->privateData.data, ownerPSK, OWNER_PSK_LENGTH_128);
 
     OIC_LOG(INFO, TAG, "PrivateData of OwnerPSK was calculated successfully");
 
-    //deallocate local memory
-    OICFree(encodeBuff);
-
     //Verify OwnerPSK information
     return (memcmp(&(receviedCred->subject), &(doxm->owner), sizeof(OicUuid_t)) == 0 &&
             receviedCred->credType == SYMMETRIC_PAIR_WISE_KEY);
 exit:
     //receviedCred->privateData.data will be deallocated when deleting credential.
-    OICFree(encodeBuff);
     return false;
 }
 
@@ -737,11 +722,14 @@ exit:
 static OCEntityHandlerResult HandlePutRequest(const OCEntityHandlerRequest * ehRequest)
 {
     OCEntityHandlerResult ret = OC_EH_ERROR;
-
-    //Get binary representation of json
-    OicSecCred_t * cred  = JSONToCredBin(((OCSecurityPayload*)ehRequest->payload)->securityData);
-
-    if(cred)
+    OIC_LOG(DEBUG, TAG, "HandleCREDPutRequest IN");
+
+    //Get binary representation of cbor
+    OicSecCred_t *cred  = NULL;
+    uint8_t *payload = (((OCSecurityPayload*)ehRequest->payload)->securityData1);
+    size_t size = (((OCSecurityPayload*)ehRequest->payload)->payloadSize);
+    OCStackResult res = CBORPayloadToCred(payload, size, &cred);
+    if (res == OC_STACK_OK)
     {
 #ifdef __WITH_DTLS__
         OicUuid_t emptyUuid = {.id={0}};
@@ -867,7 +855,7 @@ static OCEntityHandlerResult HandlePutRequest(const OCEntityHandlerRequest * ehR
 #endif//__WITH_DTLS__
     }
 
-    if(OC_EH_RESOURCE_CREATED != ret)
+    if (OC_EH_RESOURCE_CREATED != ret)
     {
         if(OC_STACK_OK != RemoveCredential(&cred->subject))
         {
@@ -875,7 +863,7 @@ static OCEntityHandlerResult HandlePutRequest(const OCEntityHandlerRequest * ehR
         }
         FreeCred(cred);
     }
-
+    OIC_LOG(DEBUG, TAG, "HandleCREDPutRequest OUT");
     return ret;
 }
 
@@ -883,10 +871,12 @@ static OCEntityHandlerResult HandlePostRequest(const OCEntityHandlerRequest * eh
 {
     OCEntityHandlerResult ret = OC_EH_ERROR;
 
-    //Get binary representation of json
-    OicSecCred_t * cred  = JSONToCredBin(((OCSecurityPayload*)ehRequest->payload)->securityData);
-
-    if(cred)
+    //Get binary representation of CBOR
+    OicSecCred_t *cred  = NULL;
+    uint8_t *payload = ((OCSecurityPayload*)ehRequest->payload)->securityData1;
+    size_t size = ((OCSecurityPayload*)ehRequest->payload)->payloadSize;
+    OCStackResult res = CBORPayloadToCred(payload, size, &cred);
+    if ((OC_STACK_OK == res) && cred)
     {
         //If the Post request credential has credId, it will be
         //discarded and the next available credId will be assigned
@@ -904,34 +894,33 @@ static OCEntityHandlerResult HandleDeleteRequest(const OCEntityHandlerRequest *e
 
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
 
-    if(NULL == ehRequest->query)
+    unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
+    B64Result b64Ret = B64_OK;
+    uint32_t outLen = 0;
+
+    if (NULL == ehRequest->query)
    {
        return ehRet;
    }
 
-   OicParseQueryIter_t parseIter = {.attrPos=NULL};
+   OicParseQueryIter_t parseIter = { .attrPos=NULL };
    OicUuid_t subject = {.id={0}};
 
    //Parsing REST query to get the subject
    ParseQueryIterInit((unsigned char *)ehRequest->query, &parseIter);
-   while(GetNextQuery(&parseIter))
+   while (GetNextQuery(&parseIter))
    {
-       if(strncasecmp((char *)parseIter.attrPos, OIC_JSON_SUBJECT_NAME,
+       if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_SUBJECT_NAME,
                parseIter.attrLen) == 0)
        {
-           unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
-           uint32_t outLen = 0;
-           B64Result b64Ret = B64_OK;
-
-           b64Ret = b64Decode((char *)parseIter.valPos, parseIter.valLen,
-                   base64Buff, sizeof(base64Buff), &outLen);
-
-           VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(subject.id)), ERROR);
-           memcpy(subject.id, base64Buff, outLen);
-       }
+            b64Ret = b64Decode((char*)parseIter.valPos,  parseIter.valLen, base64Buff,
+                    sizeof(base64Buff), &outLen);
+            VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(subject.id)), ERROR);
+            memcpy(subject.id, base64Buff, outLen);
+        }
    }
 
-   if(OC_STACK_RESOURCE_DELETED == RemoveCredential(&subject))
+   if (OC_STACK_RESOURCE_DELETED == RemoveCredential(&subject))
    {
        ehRet = OC_EH_RESOURCE_DELETED;
    }
@@ -940,18 +929,14 @@ exit:
     return ehRet;
 }
 
-/*
- * This internal method is the entity handler for Cred resources
- * to handle REST request (PUT/POST/DEL)
- */
-OCEntityHandlerResult CredEntityHandler (OCEntityHandlerFlag flag,
+OCEntityHandlerResult CredEntityHandler(OCEntityHandlerFlag flag,
                                         OCEntityHandlerRequest * ehRequest,
                                         void* callbackParameter)
 {
     (void)callbackParameter;
     OCEntityHandlerResult ret = OC_EH_ERROR;
 
-    if(!ehRequest)
+    if (!ehRequest)
     {
         return OC_EH_ERROR;
     }
@@ -959,7 +944,7 @@ OCEntityHandlerResult CredEntityHandler (OCEntityHandlerFlag flag,
     {
         OIC_LOG (DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
         //TODO :  Handle PUT/DEL methods
-        switch(ehRequest->method)
+        switch (ehRequest->method)
         {
             case OC_REST_GET:
                 ret = OC_EH_FORBIDDEN;
@@ -980,26 +965,21 @@ OCEntityHandlerResult CredEntityHandler (OCEntityHandlerFlag flag,
     }
 
     //Send payload to request originator
-    ret = (SendSRMResponse(ehRequest, ret, NULL) == OC_STACK_OK ?
-                       ret : OC_EH_ERROR);
+    ret = (SendSRMCBORResponse(ehRequest, ret, NULL, 0) == OC_STACK_OK) ?
+                       ret : OC_EH_ERROR;
 
     return ret;
 }
 
-/*
- * This internal method is used to create '/oic/sec/Cred' resource.
- */
 OCStackResult CreateCredResource()
 {
-    OCStackResult ret;
-
-    ret = OCCreateResource(&gCredHandle,
-                           OIC_RSRC_TYPE_SEC_CRED,
-                           OIC_MI_DEF,
-                           OIC_RSRC_CRED_URI,
-                           CredEntityHandler,
-                           NULL,
-                           OC_RES_PROP_NONE);
+    OCStackResult ret = OCCreateResource(&gCredHandle,
+                                         OIC_RSRC_TYPE_SEC_CRED,
+                                         OIC_MI_DEF,
+                                         OIC_RSRC_CRED_URI,
+                                         CredEntityHandler,
+                                         NULL,
+                                         OC_RES_PROP_NONE);
 
     if (OC_STACK_OK != ret)
     {
@@ -1009,49 +989,40 @@ OCStackResult CreateCredResource()
     return ret;
 }
 
-/**
- * Initialize Cred resource by loading data from persistent storage.
- *
- * @retval
- *     OC_STACK_OK    - no errors
- *     OC_STACK_ERROR - stack process error
- */
 OCStackResult InitCredResource()
 {
     OCStackResult ret = OC_STACK_ERROR;
 
     //Read Cred resource from PS
-    char* jsonSVRDatabase = GetSVRDatabase();
-
-    if (jsonSVRDatabase)
+    uint8_t *data = NULL;
+    size_t size = 0;
+    ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_CRED_NAME, &data, &size);
+    // If database read failed
+    if (ret != OC_STACK_OK)
+    {
+        OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
+    }
+    if (data)
     {
-        //Convert JSON Cred into binary format
-        gCred = JSONToCredBin(jsonSVRDatabase);
+        // Read ACL resource from PS
+        ret = CBORPayloadToCred(data, size, &gCred);
     }
+
     /*
      * If SVR database in persistent storage got corrupted or
      * is not available for some reason, a default Cred is created
      * which allows user to initiate Cred provisioning again.
      */
-    if (!jsonSVRDatabase || !gCred)
+    if (ret != OC_STACK_OK || !data || !gCred)
     {
         gCred = GetCredDefault();
     }
     //Instantiate 'oic.sec.cred'
     ret = CreateCredResource();
-    OICFree(jsonSVRDatabase);
+    OICFree(data);
     return ret;
 }
 
-/**
- * Perform cleanup for Cred resources.
- *
- * @return
- *     OC_STACK_OK              - no errors
- *     OC_STACK_ERROR           - stack process error
- *     OC_STACK_NO_RESOURCE     - resource not found
- *     OC_STACK_INVALID_PARAM   - invalid param
- */
 OCStackResult DeInitCredResource()
 {
     OCStackResult result = OCDeleteResource(gCredHandle);
@@ -1060,15 +1031,6 @@ OCStackResult DeInitCredResource()
     return result;
 }
 
-/**
- * This method is used by tinydtls/SRM to retrieve credential for given Subject.
- *
- * @param subject - subject for which credential is required.
- *
- * @retval
- *     reference to OicSecCred_t - if credential is found
- *     NULL                      - if credential not found
- */
 const OicSecCred_t* GetCredResourceData(const OicUuid_t* subject)
 {
     OicSecCred_t *cred = NULL;
@@ -1090,22 +1052,9 @@ const OicSecCred_t* GetCredResourceData(const OicUuid_t* subject)
 
 
 #if defined(__WITH_DTLS__)
-/**
- * This internal callback is used by lower stack (i.e. CA layer) to
- * retrieve PSK credentials from RI security layer.
- *
- * @param[in]  type type of PSK data required by tinyDTLS layer during DTLS handshake.
- * @param[in]  desc Additional request information.
- * @param[in]  desc_len The actual length of desc.
- * @param[out] result  Must be filled with the requested information.
- * @param[in]  result_length  Maximum size of @p result.
- *
- * @return The number of bytes written to @p result or a value
- *         less than zero on error.
- */
-int32_t GetDtlsPskCredentials( CADtlsPskCredType_t type,
-              const unsigned char *desc, size_t desc_len,
-              unsigned char *result, size_t result_length)
+int32_t GetDtlsPskCredentials(CADtlsPskCredType_t type,
+              const uint8_t *desc, size_t desc_len,
+              uint8_t *result, size_t result_length)
 {
     int32_t ret = -1;
 
@@ -1164,18 +1113,10 @@ int32_t GetDtlsPskCredentials( CADtlsPskCredType_t type,
                             }
                         }
 
-                        // Convert PSK from Base64 encoding to binary before copying
-                        uint32_t outLen = 0;
-                        B64Result b64Ret = b64Decode(cred->privateData.data,
-                                strlen(cred->privateData.data), result,
-                                result_length, &outLen);
-                        if (B64_OK != b64Ret)
-                        {
-                            OIC_LOG (ERROR, TAG, "Base64 decoding failed.");
-                            ret = -1;
-                            return ret;
-                        }
-                        return outLen;
+                        // Copy PSK.
+                        result_length = cred->privateData.len;
+                        memcpy(result, cred->privateData.data, result_length);
+                        return result_length;
                     }
                 }
             }
@@ -1210,6 +1151,7 @@ OCStackResult AddTmpPskWithPIN(const OicUuid_t* tmpSubject, OicSecCredType_t cre
                             size_t ownersLen, const OicUuid_t * owners, OicUuid_t* tmpCredSubject)
 {
     OCStackResult ret = OC_STACK_ERROR;
+    OIC_LOG(DEBUG, TAG, "AddTmpPskWithPIN IN");
 
     if(NULL == tmpSubject || NULL == pin || 0 == pinSize || NULL == tmpCredSubject)
     {
@@ -1217,19 +1159,15 @@ OCStackResult AddTmpPskWithPIN(const OicUuid_t* tmpSubject, OicSecCredType_t cre
     }
 
     uint8_t privData[OWNER_PSK_LENGTH_128] = {0,};
+    OicSecKey_t privKey = {privData, OWNER_PSK_LENGTH_128};
+    OicSecCred_t* cred = NULL;
     int dtlsRes = DeriveCryptoKeyFromPassword((const unsigned char *)pin, pinSize, owners->id,
                                               UUID_LENGTH, PBKDF_ITERATIONS,
                                               OWNER_PSK_LENGTH_128, privData);
     VERIFY_SUCCESS(TAG, (0 == dtlsRes) , ERROR);
 
-    uint32_t outLen = 0;
-    char base64Buff[B64ENCODE_OUT_SAFESIZE(OWNER_PSK_LENGTH_128) + 1] = {};
-    B64Result b64Ret = b64Encode(privData, OWNER_PSK_LENGTH_128, base64Buff,
-                                sizeof(base64Buff), &outLen);
-    VERIFY_SUCCESS(TAG, (B64_OK == b64Ret), ERROR);
-
-    OicSecCred_t* cred = GenerateCredential(tmpSubject, credType, NULL,
-                                            base64Buff, ownersLen, owners);
+    cred = GenerateCredential(tmpSubject, credType, NULL,
+                              &privKey, ownersLen, owners);
     if(NULL == cred)
     {
         OIC_LOG(ERROR, TAG, "GeneratePskWithPIN() : Failed to generate credential");
@@ -1244,6 +1182,7 @@ OCStackResult AddTmpPskWithPIN(const OicUuid_t* tmpSubject, OicSecCredType_t cre
         RemoveCredential(tmpSubject);
         OIC_LOG(ERROR, TAG, "GeneratePskWithPIN() : Failed to add credential");
     }
+    OIC_LOG(DEBUG, TAG, "AddTmpPskWithPIN OUT");
 
 exit:
     return ret;
@@ -1258,21 +1197,12 @@ exit:
 #define CERTIFICATE ("x5c")
 #define PRIVATE_KEY ("d")
 
-
-static void WriteCertPrefix(uint8_t *prefix, uint32_t certLen)
-{
-    for (size_t i = 0; i < CERT_LEN_PREFIX; ++i)
-    {
-        prefix[i] = (certLen >> (BYTE_SIZE * (CERT_LEN_PREFIX - 1 - i))) & 0xFF;
-    }
-}
-
-static uint32_t ParseCertPrefix(uint8_t *prefix)
+static uint32_t parseCertPrefix(uint8_t *prefix)
 {
     uint32_t res = 0;
-    if(NULL != prefix)
+    if (NULL != prefix)
     {
-        for(int i=0; i < CERT_LEN_PREFIX; ++i)
+        for (int i = 0; i < CERT_LEN_PREFIX; ++i)
         {
             res |= (((uint32_t) prefix[i]) << ((CERT_LEN_PREFIX - 1 -i) * BYTE_SIZE));
         }
@@ -1280,34 +1210,16 @@ static uint32_t ParseCertPrefix(uint8_t *prefix)
     return res;
 }
 
-static uint32_t appendCert2Chain(uint8_t *appendPoint, char *cert, uint32_t max_len)
+static OCStackResult GetCAPublicKeyData(CADtlsX509Creds_t *credInfo)
 {
-    uint32_t ret = 0;
-    VERIFY_NON_NULL(TAG, appendPoint, ERROR);
-    VERIFY_NON_NULL(TAG, cert, ERROR);
-
-    uint32_t certLen;
-    VERIFY_SUCCESS(TAG, B64_OK == b64Decode(cert, strlen(cert), appendPoint + CERT_LEN_PREFIX,
-                                            max_len - CERT_LEN_PREFIX, &certLen), ERROR);
-    WriteCertPrefix(appendPoint, certLen);
-
-    ret = certLen + CERT_LEN_PREFIX;
-exit:
-    return ret;
-}
-
-static OCStackResult GetCAPublicKeyData(CADtlsX509Creds_t *credInfo){
     OCStackResult ret = OC_STACK_ERROR;
     uint8_t *ccPtr = credInfo->certificateChain;
-    for(uint32_t i =0; i < credInfo->chainLen - 1; ++i)
+    for (uint8_t i = 0; i < credInfo->chainLen - 1; ++i)
     {
-        ccPtr += CERT_LEN_PREFIX + ParseCertPrefix(ccPtr);
+        ccPtr += CERT_LEN_PREFIX + parseCertPrefix(ccPtr);
     }
 
-    ByteArray cert = {
-        .data = ccPtr + CERT_LEN_PREFIX,
-        .len = ParseCertPrefix(ccPtr)
-         };
+    ByteArray cert = { .data = ccPtr + CERT_LEN_PREFIX, .len = parseCertPrefix(ccPtr) };
     CertificateX509 certStruct;
 
     VERIFY_SUCCESS(TAG, PKI_SUCCESS == DecodeCertificate(cert, &certStruct), ERROR);
@@ -1322,70 +1234,6 @@ static OCStackResult GetCAPublicKeyData(CADtlsX509Creds_t *credInfo){
     return ret;
 }
 
-static OCStackResult GetCertCredPublicData(CADtlsX509Creds_t *credInfo, OicSecCred_t *cred)
-{
-    OCStackResult ret = OC_STACK_ERROR;
-    cJSON *jsonRoot = NULL;
-
-    VERIFY_NON_NULL(TAG, credInfo, ERROR);
-    VERIFY_NON_NULL(TAG, cred, ERROR);
-    VERIFY_NON_NULL(TAG, cred->publicData.data, ERROR);
-    //VERIFY_SUCCESS(TAG, NULL == credInfo->certificateChain.data, ERROR);
-    jsonRoot = cJSON_Parse(cred->publicData.data);
-    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
-
-    //Get certificate chain
-    cJSON *jsonObj = cJSON_GetObjectItem(jsonRoot, CERTIFICATE);//TODO define field names constants
-    VERIFY_SUCCESS(TAG, NULL != jsonObj && cJSON_Array == jsonObj->type, ERROR);
-
-    size_t certChainLen = (size_t)cJSON_GetArraySize(jsonObj);
-    credInfo->chainLen = certChainLen;
-    VERIFY_SUCCESS(TAG, MAX_CHAIN_LEN >= certChainLen, ERROR);
-
-    uint32_t len = 0;
-    for (size_t i = 0; i < certChainLen; ++i)
-    {
-        cJSON *item = cJSON_GetArrayItem(jsonObj, i);
-        VERIFY_NON_NULL(TAG, item, ERROR);
-        VERIFY_SUCCESS(TAG, cJSON_String == item->type, ERROR);
-        uint32_t appendedLen = appendCert2Chain(credInfo->certificateChain + len, item->valuestring,
-                                              MAX_CERT_MESSAGE_LEN - len);
-        VERIFY_SUCCESS(TAG, 0 != appendedLen, ERROR);
-        len += appendedLen;
-    }
-    credInfo->certificateChainLen = len;
-    VERIFY_SUCCESS(TAG, OC_STACK_OK == GetCAPublicKeyData(credInfo), ERROR);
-    ret = OC_STACK_OK;
-exit:
-    cJSON_Delete(jsonRoot);
-    return ret;
-}
-
-static OCStackResult GetCertCredPrivateData(CADtlsX509Creds_t *credInfo, OicSecCred_t *cred)
-{
-    OCStackResult ret = OC_STACK_ERROR;
-    cJSON *jsonRoot = NULL;
-    VERIFY_NON_NULL(TAG, credInfo, ERROR);
-    VERIFY_NON_NULL(TAG, cred, ERROR);
-    VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
-    jsonRoot = cJSON_Parse(cred->privateData.data);
-    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
-
-    cJSON *jsonObj = cJSON_GetObjectItem(jsonRoot, PRIVATE_KEY);//TODO define field names constants
-    VERIFY_SUCCESS(TAG, NULL != jsonObj && cJSON_String == jsonObj->type, ERROR);
-
-    uint32_t read = 0u;
-    VERIFY_SUCCESS(TAG, B64_OK == b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring),
-                                            credInfo->devicePrivateKey, PRIVATE_KEY_SIZE, &read)
-                   && PRIVATE_KEY_SIZE == read, ERROR);
-
-    ret = OC_STACK_OK;
-
-exit:
-    cJSON_Delete(jsonRoot);
-    return ret;
-}
-
 int GetDtlsX509Credentials(CADtlsX509Creds_t *credInfo)
 {
     int ret = 1;
@@ -1399,9 +1247,14 @@ int GetDtlsX509Credentials(CADtlsX509Creds_t *credInfo)
     LL_SEARCH_SCALAR(gCred, cred, credType, SIGNED_ASYMMETRIC_KEY);
     VERIFY_NON_NULL(TAG, cred, ERROR);
 
-    VERIFY_SUCCESS(TAG, OC_STACK_OK == GetCertCredPrivateData(credInfo, cred), ERROR);
-    VERIFY_SUCCESS(TAG, OC_STACK_OK == GetCertCredPublicData(credInfo, cred), ERROR);
-
+    if (cred->publicData.len > MAX_CERT_MESSAGE_LEN || cred->privateData.len > PRIVATE_KEY_SIZE)
+    {
+        goto exit;
+    }
+    memcpy(credInfo->certificateChain, cred->publicData.data, cred->publicData.len);
+    memcpy(credInfo->devicePrivateKey, cred->privateData.data, cred->privateData.len);
+    credInfo->certificateChainLen = parseCertPrefix(cred->publicData.data);
+    GetCAPublicKeyData(credInfo);
     ret = 0;
 exit:
 
index 9255508..8ee41b8 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#include <stdlib.h>
-#include <string.h>
-#include "ocstack.h"
-#include "logger.h"
-#include "oic_malloc.h"
-#include "cJSON.h"
-#include "base64.h"
-#include "resourcemanager.h"
-#include "psinterface.h"
 #include "utlist.h"
+#include "payload_logging.h"
+#include "psinterface.h"
+#include "resourcemanager.h"
 #include "srmresourcestrings.h"
-#include "doxmresource.h"
 #include "srmutility.h"
+#include "doxmresource.h"
+#include "ocpayload.h"
 #ifdef __WITH_X509__
 #include "crlresource.h"
 #include "crl.h"
 
 #define SEPARATOR                   ":"
 #define SEPARATOR_LEN               (1)
-#define JSON_CRL_NAME               "\"CRL\""
-#define JSON_CRL_NAME_LEN           (5)
-#define OIC_JSON_CRL_NAME           "crl"
-#define OIC_JSON_CRL_ID             "CRLId"
-#define OIC_JSON_CRL_THIS_UPDATE    "ThisUpdate"
-#define OIC_JSON_CRL_DATA           "CRLData"
+#define CBOR_CRL_NAME               "\"CRL\""
+#define CBOR_CRL_NAME_LEN           (5)
+#define OIC_CBOR_CRL_NAME           "crl"
+#define OIC_CBOR_CRL_ID             "CRLId"
+#define OIC_CBOR_CRL_THIS_UPDATE    "ThisUpdate"
+#define OIC_CBOR_CRL_DATA           "CRLData"
 #define CRL_DEFAULT_CRL_ID           1
 #define CRL_DEFAULT_THIS_UPDATE     "150101000000Z"
 #define CRL_DEFAULT_CRL_DATA        "-"
 static OCResourceHandle     gCrlHandle  = NULL;
 static OicSecCrl_t         *gCrl        = NULL;
 
+/** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
+ * The value of payload size is increased until reaching below max cbor size. */
+static const uint8_t CBOR_SIZE = 255;
+
+// Max cbor size payload.
+static const uint16_t CBOR_MAX_SIZE = 4400;
+
+// PSTAT Map size - Number of mandatory items
+static const uint8_t CRL_MAP_SIZE = 3;
 
 void DeleteCrlBinData(OicSecCrl_t *crl)
 {
@@ -69,215 +73,230 @@ void DeleteCrlBinData(OicSecCrl_t *crl)
     }
 }
 
-char *BinToCrlJSON(const OicSecCrl_t *crl)
+OCStackResult CrlToCBORPayload(const OicSecCrl_t *crl, uint8_t **payload, size_t *size)
 {
-    if (NULL == crl)
+    if (NULL == crl || NULL == payload || NULL != *payload || NULL == size)
     {
-        return NULL;
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    size_t cborLen = *size;
+    if (0 == cborLen)
+    {
+        cborLen = CBOR_SIZE;
     }
 
-    char *base64Buff = NULL;
-    uint32_t outLen = 0;
-    uint32_t base64CRLLen = 0;
-    B64Result b64Ret = B64_OK;
-    char *jsonStr = NULL;
-    cJSON *jsonRoot = cJSON_CreateObject();
-    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
-    cJSON *jsonCrl = cJSON_CreateObject();
-    VERIFY_NON_NULL(TAG, jsonCrl, ERROR);
+    *payload = NULL;
+    *size = 0;
 
-    cJSON_AddItemToObject(jsonRoot, OIC_JSON_CRL_NAME, jsonCrl);
+    OCStackResult ret = OC_STACK_ERROR;
+
+    CborEncoder encoder = { {.ptr = NULL }, .end = 0 };
+    CborEncoder crlMap = { {.ptr = NULL }, .end = 0 };
+
+    CborError cborEncoderResult = CborNoError;
+
+    uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
+    VERIFY_NON_NULL(TAG, outPayload, ERROR);
+    cbor_encoder_init(&encoder, outPayload, cborLen, 0);
+
+    cborEncoderResult = cbor_encoder_create_map(&encoder, &crlMap, CRL_MAP_SIZE);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, ERROR);
 
     //CRLId -- Mandatory
-    cJSON_AddNumberToObject(jsonCrl, OIC_JSON_CRL_ID, (int)crl->CrlId);
+    cborEncoderResult = cbor_encode_text_string(&crlMap, OIC_CBOR_CRL_ID,
+        strlen(OIC_CBOR_CRL_ID));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, ERROR);
+    cborEncoderResult = cbor_encode_int(&crlMap, crl->CrlId);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, ERROR);
 
     //ThisUpdate -- Mandatory
-    outLen = 0;
-    base64CRLLen = (uint32_t)B64ENCODE_OUT_SAFESIZE(crl->ThisUpdate.len);
-    base64Buff = OICMalloc(base64CRLLen);
-    b64Ret = b64Encode(crl->ThisUpdate.data, crl->ThisUpdate.len, base64Buff,
-             base64CRLLen, &outLen);
-    VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
-    cJSON_AddStringToObject(jsonCrl, OIC_JSON_CRL_THIS_UPDATE, base64Buff);
-    OICFree(base64Buff);
+    cborEncoderResult = cbor_encode_text_string(&crlMap, OIC_CBOR_CRL_THIS_UPDATE,
+        strlen(OIC_CBOR_CRL_THIS_UPDATE));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, ERROR);
+    cborEncoderResult = cbor_encode_byte_string(&crlMap, crl->ThisUpdate.data,
+                                                crl->ThisUpdate.len);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, ERROR);
 
     //CRLData -- Mandatory
-    outLen = 0;
-    base64CRLLen = (uint32_t)B64ENCODE_OUT_SAFESIZE(crl->CrlData.len);
-    base64Buff = OICMalloc(base64CRLLen);
-    b64Ret = b64Encode(crl->CrlData.data, crl->CrlData.len, base64Buff,
-             base64CRLLen, &outLen);
-    VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
-    cJSON_AddStringToObject(jsonCrl, OIC_JSON_CRL_DATA, base64Buff);
-
-    jsonStr = cJSON_PrintUnformatted(jsonRoot);
+    cborEncoderResult = cbor_encode_text_string(&crlMap, OIC_CBOR_CRL_DATA,
+        strlen(OIC_CBOR_CRL_DATA));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, ERROR);
+    cborEncoderResult = cbor_encode_byte_string(&crlMap, crl->CrlData.data,
+                                                crl->CrlData.len);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, ERROR);
+
+    cborEncoderResult = cbor_encoder_close_container(&encoder, &crlMap);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, ERROR);
+
+    *size = encoder.ptr - outPayload;
+    *payload = outPayload;
+    ret = OC_STACK_OK;
 
 exit:
-    OICFree(base64Buff);
-    if (jsonRoot)
+    if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
     {
-        cJSON_Delete(jsonRoot);
+        // reallocate and try again!
+        OICFree(outPayload);
+        // Since the allocated initial memory failed, double the memory.
+        cborLen += encoder.ptr - encoder.end;
+        cborEncoderResult = CborNoError;
+        ret = CrlToCBORPayload(crl, payload, &cborLen);
     }
-    return jsonStr;
+
+    if ((CborNoError != cborEncoderResult) || (OC_STACK_OK != ret))
+    {
+        OICFree(outPayload);
+        outPayload = NULL;
+        *payload = NULL;
+        *size = 0;
+        ret = OC_STACK_ERROR;
+    }
+
+    return ret;
 }
 
-OicSecCrl_t *JSONToCrlBin(const char * jsonStr)
+OCStackResult CBORPayloadToCrl(const uint8_t *cborPayload, const size_t size,
+                               OicSecCrl_t **secCrl)
 {
-    if (NULL == jsonStr)
+    if (NULL == cborPayload || NULL == secCrl || NULL != *secCrl)
     {
-        return NULL;
+        return OC_STACK_INVALID_PARAM;
     }
 
     OCStackResult ret = OC_STACK_ERROR;
-    OicSecCrl_t *crl =  NULL;
-    cJSON *jsonCrl = NULL;
-    cJSON *jsonObj = NULL;
-
-    unsigned char *base64Buff = NULL;
-    uint32_t base64CRLLen = 0;
-    uint32_t outLen = 0;
-    B64Result b64Ret = B64_OK;
+    *secCrl = NULL;
 
-    cJSON *jsonRoot = cJSON_Parse(jsonStr);
-    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+    CborValue crlCbor = { .parser = NULL };
+    CborParser parser = { .end = NULL };
+    CborError cborFindResult = CborNoError;
+    int cborLen = size;
+    if (0 == size)
+    {
+        cborLen = CBOR_SIZE;
+    }
+    cbor_parser_init(cborPayload, cborLen, 0, &parser, &crlCbor);
+    CborValue crlMap = { .parser = NULL } ;
+    OicSecCrl_t *crl = NULL;
+    char *name = NULL;
+    size_t outLen = 0;
+    cborFindResult = cbor_value_enter_container(&crlCbor, &crlMap);
+    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
 
-    jsonCrl = cJSON_GetObjectItem(jsonRoot, OIC_JSON_CRL_NAME);
-    VERIFY_NON_NULL(TAG, jsonCrl, ERROR);
     crl = (OicSecCrl_t *)OICCalloc(1, sizeof(OicSecCrl_t));
     VERIFY_NON_NULL(TAG, crl, ERROR);
 
-    //CRLId -- Mandatory
-    jsonObj = cJSON_GetObjectItem(jsonCrl, OIC_JSON_CRL_ID);
-    if(jsonObj)
+    while (cbor_value_is_valid(&crlMap))
     {
-        VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
-        crl->CrlId = (uint16_t)jsonObj->valueint;
+        size_t len = 0;
+        cborFindResult = cbor_value_dup_text_string(&crlMap, &name, &len, NULL);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
+        cborFindResult = cbor_value_advance(&crlMap);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
+
+        CborType type = cbor_value_get_type(&crlMap);
+
+        if (0 == strcmp(OIC_CBOR_CRL_ID, name))
+        {
+            cborFindResult = cbor_value_get_int(&crlMap, (int *) &crl->CrlId);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
+        }
+        if (0 == strcmp(OIC_CBOR_CRL_THIS_UPDATE, name))
+        {
+            uint8_t *crlByte = NULL;
+            cborFindResult = cbor_value_dup_byte_string(&crlMap, &crlByte, &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
+            crl->ThisUpdate.data = (uint8_t*) OICMalloc(len);
+            VERIFY_NON_NULL(TAG, crl->ThisUpdate.data, ERROR);
+            memcpy(crl->ThisUpdate.data, crlByte, len);
+            crl->ThisUpdate.len = len;
+            OICFree(crlByte);
+        }
+        if (0 == strcmp(OIC_CBOR_CRL_DATA, name))
+        {
+            uint8_t *crlByte = NULL;
+            cborFindResult = cbor_value_dup_byte_string(&crlMap, &crlByte, &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
+            crl->CrlData.data = (uint8_t*) OICMalloc(len);
+            VERIFY_NON_NULL(TAG, crl->CrlData.data, ERROR);
+            memcpy(crl->CrlData.data, crlByte, len);
+            crl->CrlData.len = len;
+            OICFree(crlByte);
+        }
+        if (CborMapType != type && cbor_value_is_valid(&crlMap))
+        {
+            cborFindResult = cbor_value_advance(&crlMap);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
+        }
+        OICFree(name);
+        name = NULL;
     }
-    else // PUT/POST JSON may not have CRLId so set it to the gCRList->CRLId
+    // PUT/POST CBOR may not have mandatory values set default values.
+    if (!crl->CrlId)
     {
         VERIFY_NON_NULL(TAG, gCrl, ERROR);
         crl->CrlId = gCrl->CrlId;
     }
-
-    //ThisUpdate -- Mandatory
-    jsonObj = cJSON_GetObjectItem(jsonCrl, OIC_JSON_CRL_THIS_UPDATE);
-    if(jsonObj)
-    {
-        VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
-        if(cJSON_String == jsonObj->type)
-        {
-            //Check for empty string, in case ThisUpdate field has not been set yet
-            if (jsonObj->valuestring[0])
-            {
-                base64CRLLen = B64ENCODE_OUT_SAFESIZE(strlen(jsonObj->valuestring));
-                base64Buff = OICMalloc(base64CRLLen);
-                b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff,
-                        base64CRLLen, &outLen);
-                VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= base64CRLLen),
-                                ERROR);
-                crl->ThisUpdate.data = OICMalloc(outLen + 1);
-                memcpy(crl->ThisUpdate.data, base64Buff, outLen);
-                crl->ThisUpdate.len = outLen;
-                OICFree(base64Buff);
-                base64Buff = NULL;
-            }
-        }
-    }
-    else // PUT/POST JSON will not have ThisUpdate so set it to the gCRList->ThisUpdate
+    if (!crl->ThisUpdate.data)
     {
         VERIFY_NON_NULL(TAG, gCrl, ERROR);
-        outLen = (uint32_t)gCrl->ThisUpdate.len;
-        crl->ThisUpdate.data = OICMalloc(outLen + 1);
+        outLen = gCrl->ThisUpdate.len;
+        crl->ThisUpdate.data = (uint8_t*) OICMalloc(outLen);
+        VERIFY_NON_NULL(TAG, crl->ThisUpdate.data, ERROR);
         memcpy(crl->ThisUpdate.data, gCrl->ThisUpdate.data, outLen);
         crl->ThisUpdate.len = outLen;
     }
-
-    //CRLData -- Mandatory
-    jsonObj = cJSON_GetObjectItem(jsonCrl, OIC_JSON_CRL_DATA);
-    if(jsonObj)
-    {
-        VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
-        if(cJSON_String == jsonObj->type)
-        {
-            //Check for empty string, in case CRLData field has not been set yet
-            if (jsonObj->valuestring[0])
-            {
-                outLen = 0;
-                base64CRLLen = B64ENCODE_OUT_SAFESIZE(strlen(jsonObj->valuestring));
-                base64Buff = OICMalloc(base64CRLLen);
-                b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff,
-                        base64CRLLen, &outLen);
-                VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= base64CRLLen),
-                                ERROR);
-                crl->CrlData.data = OICMalloc(outLen + 1);
-                memcpy(crl->CrlData.data, base64Buff, outLen);
-                crl->CrlData.len = outLen;
-                OICFree(base64Buff);
-                base64Buff = NULL;
-            }
-        }
-    }
-    else // PUT/POST JSON will not have CRLData so set it to the gCRList->CRLData
+    if (!crl->CrlData.data)
     {
         VERIFY_NON_NULL(TAG, gCrl, ERROR);
-        outLen = (uint32_t)gCrl->CrlData.len;
-        crl->CrlData.data = OICMalloc(outLen + 1);
+        outLen = gCrl->CrlData.len;
+        crl->CrlData.data = (uint8_t*) OICMalloc(outLen);
+        VERIFY_NON_NULL(TAG, crl->CrlData.data, ERROR);
         memcpy(crl->CrlData.data, gCrl->CrlData.data, outLen);
         crl->CrlData.len = outLen;
     }
 
+    *secCrl = crl;
     ret = OC_STACK_OK;
 exit:
-    cJSON_Delete(jsonRoot);
-    OICFree(base64Buff);
-    base64Buff = NULL;
-    if (OC_STACK_OK != ret)
+    if (CborNoError != cborFindResult)
     {
+        OIC_LOG (ERROR, TAG, "CBORPayloadToCrl failed");
         DeleteCrlBinData(crl);
         crl = NULL;
+        ret = OC_STACK_ERROR;
     }
-    return crl;
+    if (name)
+    {
+        OICFree(name);
+    }
+    return ret;
 }
 
 OCStackResult UpdateCRLResource(const OicSecCrl_t *crl)
 {
-    char *jsonStr = NULL;
-    OCStackResult res = OC_STACK_ERROR;
-
-    jsonStr = BinToCrlJSON((OicSecCrl_t *) crl);
-    if (!jsonStr)
-    {
-        return OC_STACK_ERROR;
-    }
-
-    cJSON *jsonObj = cJSON_Parse(jsonStr);
-    OICFree(jsonStr);
+    uint8_t *payload = NULL;
+    size_t size = 0;
 
-    if (jsonObj == NULL)
+    OCStackResult res = CrlToCBORPayload((OicSecCrl_t *) crl, &payload, &size);
+    if (OC_STACK_OK != res)
     {
-        return OC_STACK_ERROR;
+        return res;
     }
 
-    res = UpdateSVRDatabase(OIC_JSON_CRL_NAME, jsonObj);
-    cJSON_Delete(jsonObj);
-
-    return res;
+    return UpdateSecureResourceInPS(OIC_CBOR_CRL_NAME, payload, size);
 }
 
 static OCEntityHandlerResult HandleCRLPostRequest(const OCEntityHandlerRequest *ehRequest)
 {
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
+    OicSecCrl_t *crl = NULL;
+    uint8_t *payload = ((OCSecurityPayload *)ehRequest->payload)->securityData1;
 
-    char *jsonCRL = (char *)(((OCSecurityPayload *)ehRequest->payload)->securityData);
-
-    if (jsonCRL)
+    if (payload)
     {
         OIC_LOG(INFO, TAG, "UpdateSVRDB...");
-        OIC_LOG_V(INFO, TAG, "crl: \"%s\"", jsonCRL);
-
-        cJSON *jsonObj = cJSON_Parse(jsonCRL);
-        OicSecCrl_t *crl = NULL;
-        crl = JSONToCrlBin(jsonCRL);
+        CBORPayloadToCrl(payload, CBOR_SIZE, &crl);
         VERIFY_NON_NULL(TAG, crl, ERROR);
 
         gCrl->CrlId = crl->CrlId;
@@ -285,27 +304,27 @@ static OCEntityHandlerResult HandleCRLPostRequest(const OCEntityHandlerRequest *
         OICFree(gCrl->ThisUpdate.data);
         gCrl->ThisUpdate.data = NULL;
         gCrl->ThisUpdate.data = OICMalloc(crl->ThisUpdate.len);
+        VERIFY_NON_NULL(TAG, gCrl->ThisUpdate.data, ERROR);
         memcpy(gCrl->ThisUpdate.data, crl->ThisUpdate.data, crl->ThisUpdate.len);
         gCrl->ThisUpdate.len = crl->ThisUpdate.len;
 
         OICFree(gCrl->CrlData.data);
-        gCrl->CrlData.data = NULL;
         gCrl->CrlData.data = OICMalloc(crl->CrlData.len);
+        VERIFY_NON_NULL(TAG, gCrl->CrlData.data, ERROR);
         memcpy(gCrl->CrlData.data, crl->CrlData.data, crl->CrlData.len);
         gCrl->CrlData.len = crl->CrlData.len;
 
-        if (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_CRL_NAME, jsonObj))
+        size_t size = 0;
+        if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_CBOR_CRL_NAME, payload, size))
         {
-            OIC_LOG(INFO, TAG, "UpdateSVRDB == OK");
-            ehRet = OC_EH_RESOURCE_CREATED;
+            ehRet = OC_EH_OK;
         }
 
         DeleteCrlBinData(crl);
-
-        exit:
-        cJSON_Delete(jsonObj);
+        OICFree(payload);
     }
 
+exit:
     // Send payload to request originator
     SendSRMResponse(ehRequest, ehRet, NULL);
 
@@ -314,13 +333,13 @@ static OCEntityHandlerResult HandleCRLPostRequest(const OCEntityHandlerRequest *
 }
 
 
-/*
+/**
  * This internal method is the entity handler for CRL resource and
  * will handle REST request (GET/PUT/POST/DEL) for them.
  */
-OCEntityHandlerResult CRLEntityHandler(OCEntityHandlerFlag flag,
-                                       OCEntityHandlerRequest *ehRequest,
-                                       void *callbackParameter)
+static OCEntityHandlerResult CRLEntityHandler(OCEntityHandlerFlag flag,
+                                              OCEntityHandlerRequest *ehRequest,
+                                              void *callbackParameter)
 {
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
     (void)callbackParameter;
@@ -356,19 +375,18 @@ OCEntityHandlerResult CRLEntityHandler(OCEntityHandlerFlag flag,
     return ehRet;
 }
 
-/*
+/**
  * This internal method is used to create '/oic/sec/crl' resource.
  */
-OCStackResult CreateCRLResource()
+static OCStackResult CreateCRLResource()
 {
-    OCStackResult ret;
-    ret = OCCreateResource(&gCrlHandle,
-                           OIC_RSRC_TYPE_SEC_CRL,
-                           OIC_MI_DEF,
-                           OIC_RSRC_CRL_URI,
-                           CRLEntityHandler,
-                           NULL,
-                           OC_OBSERVABLE);
+    OCStackResult ret = OCCreateResource(&gCrlHandle,
+                                         OIC_RSRC_TYPE_SEC_CRL,
+                                         OIC_MI_DEF,
+                                         OIC_RSRC_CRL_URI,
+                                         CRLEntityHandler,
+                                         NULL,
+                                         OC_OBSERVABLE);
 
     if (OC_STACK_OK != ret)
     {
@@ -379,23 +397,39 @@ OCStackResult CreateCRLResource()
 }
 
 /**
- * Get the default value
- * @retval  NULL for now. Update it when we finalize the default info.
+ * Get the default value.
+ * @return defaultCrl for now.
  */
 static OicSecCrl_t *GetCrlDefault()
 {
-    OicSecCrl_t *defaultCrl = NULL;
-    defaultCrl = (OicSecCrl_t *)OICCalloc(1, sizeof(OicSecCrl_t));
-
+    OicSecCrl_t *defaultCrl = (OicSecCrl_t *)OICCalloc(1, sizeof(OicSecCrl_t));
+    if (NULL == defaultCrl)
+    {
+        return NULL;
+    }
     defaultCrl->CrlId = CRL_DEFAULT_CRL_ID;
 
     defaultCrl->CrlData.len = strlen(CRL_DEFAULT_CRL_DATA);
-    defaultCrl->CrlData.data = OICMalloc(defaultCrl->CrlData.len);
-    memcpy(defaultCrl->CrlData.data, CRL_DEFAULT_CRL_DATA, defaultCrl->CrlData.len);
+    defaultCrl->CrlData.data = (uint8_t*) OICMalloc(defaultCrl->CrlData.len);
+    if (defaultCrl->CrlData.data)
+    {
+        memcpy(defaultCrl->CrlData.data, CRL_DEFAULT_CRL_DATA, defaultCrl->CrlData.len);
+    }
+    else
+    {
+        defaultCrl->CrlData.len = 0;
+    }
 
     defaultCrl->ThisUpdate.len = strlen(CRL_DEFAULT_THIS_UPDATE);
-    defaultCrl->ThisUpdate.data = OICMalloc(defaultCrl->ThisUpdate.len);
-    memcpy(defaultCrl->ThisUpdate.data, CRL_DEFAULT_THIS_UPDATE, defaultCrl->ThisUpdate.len);
+    defaultCrl->ThisUpdate.data = (uint8_t*) OICMalloc(defaultCrl->ThisUpdate.len);
+    if (defaultCrl->ThisUpdate.data)
+    {
+        memcpy(defaultCrl->ThisUpdate.data, CRL_DEFAULT_THIS_UPDATE, defaultCrl->ThisUpdate.len);
+    }
+    else
+    {
+        defaultCrl->ThisUpdate.len = 0;
+    }
 
     return defaultCrl;
 }
@@ -410,28 +444,33 @@ static OicSecCrl_t *GetCrlDefault()
 OCStackResult InitCRLResource()
 {
     OCStackResult ret = OC_STACK_ERROR;
-    char* jsonSVRDatabase;
-
-    //Read CRL resource from PS
-    jsonSVRDatabase = GetSVRDatabase();
-
-    if (jsonSVRDatabase)
+    // Read Crl resource from PS
+    uint8_t *data = NULL;
+    size_t size = 0;
+    ret = GetSecureVirtualDatabaseFromPS(OIC_CBOR_CRL_NAME, &data, &size);
+    // If database read failed
+    if (OC_STACK_OK != ret)
     {
-        //Convert JSON CRL into binary format
-        gCrl = JSONToCrlBin(jsonSVRDatabase);
+        OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
     }
+    if (data)
+    {
+        // Read ACL resource from PS
+        ret = CBORPayloadToCrl(data, size, &gCrl);
+    }
+
     /*
      * If SVR database in persistent storage got corrupted or
      * is not available for some reason, a default CrlResource is created
      * which allows user to initiate CrlResource provisioning again.
      */
-    if (!jsonSVRDatabase || !gCrl)
+    if ((OC_STACK_OK != ret) || !data || !gCrl)
     {
         gCrl = GetCrlDefault();
     }
 
     ret = CreateCRLResource();
-    OICFree(jsonSVRDatabase);
+    OICFree(data);
     return ret;
 }
 
@@ -451,58 +490,39 @@ OicSecCrl_t *GetCRLResource()
     OicSecCrl_t *crl =  NULL;
 
     //Read CRL resource from PS
-    char* jsonSVRDatabase = GetSVRDatabase();
-
-    if (jsonSVRDatabase)
+    uint8_t *data = NULL;
+    size_t size = 0;
+    OCStackResult ret = GetSecureVirtualDatabaseFromPS(OIC_CBOR_CRL_NAME, &data, &size);
+    if (data)
     {
-        //Convert JSON CRL into binary format
-        crl = JSONToCrlBin(jsonSVRDatabase);
+        //Convert CBOR CRL into binary format
+        ret = CBORPayloadToCrl(data, size, &crl);
     }
     /*
      * If SVR database in persistent storage got corrupted or
      * is not available for some reason, a default CrlResource is created
      * which allows user to initiate CrlResource provisioning again.
      */
-    if (!jsonSVRDatabase || !crl)
+    if ((OC_STACK_OK != ret) || !data || !crl)
     {
         crl = GetCrlDefault();
     }
-    OICFree(jsonSVRDatabase);
+    OICFree(data);
 
     return crl;
 }
 
-char *GetBase64CRL()
+uint8_t *GetCrl()
 {
-    cJSON *jsonCrl = NULL;
-    cJSON *jsonObj = NULL;
-    char *jsonSVRDatabase = GetSVRDatabase();
-    char* ret = NULL;
-
-    cJSON *jsonRoot = cJSON_Parse(jsonSVRDatabase);
-    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
-
-    jsonCrl = cJSON_GetObjectItem(jsonRoot, OIC_JSON_CRL_NAME);
-    VERIFY_NON_NULL(TAG, jsonCrl, ERROR);
-
-    //CRLData -- Mandatory
-    jsonObj = cJSON_GetObjectItem(jsonCrl, OIC_JSON_CRL_DATA);
-    if(jsonObj)
+    uint8_t *data = NULL;
+    size_t size = 0;
+    OicSecCrl_t *crl = NULL;
+    if (OC_STACK_OK == GetSecureVirtualDatabaseFromPS(OIC_CBOR_CRL_NAME, &data, &size) && data &&
+        OC_STACK_OK == CBORPayloadToCrl(data, size, &crl))
     {
-        VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
-        if(cJSON_String == jsonObj->type)
-        {
-            //Check for empty string, in case CRLData field has not been set yet
-            if (jsonObj->valuestring[0])
-            {
-                ret = jsonObj->valuestring;
-            }
-        }
+        return crl->CrlData.data;
     }
-exit:
-    OICFree(jsonSVRDatabase);
-    cJSON_Delete(jsonRoot);
-    return ret;
+    return NULL;
 }
 
 void  GetDerCrl(ByteArray crlArray)
index 0690724..908c5ff 100644 (file)
@@ -55,6 +55,7 @@
 \r
 \r
 #define TAG ("DP")\r
+static const uint64_t CBOR_SIZE=255;\r
 \r
 /**\r
  * Structure to carry direct-pairing API data to callback.\r
@@ -333,7 +334,8 @@ static OCStackApplicationResult DirectPairingFinalizeHandler(void *ctx, OCDoHand
         if(OC_STACK_OK == clientResponse->result)\r
         {\r
             // result\r
-            OIC_LOG(INFO, TAG, "DirectPairingFinalizeHandler : success PUT request to /oic/sec/dpairing");\r
+            OIC_LOG(INFO, TAG, "DirectPairingFinalizeHandler : success PUT"\r
+                    " request to /oic/sec/dpairing");\r
 \r
             CAEndpoint_t endpoint;\r
             memset(&endpoint, 0x00, sizeof(CAEndpoint_t));\r
@@ -375,7 +377,8 @@ static OCStackApplicationResult DirectPairingFinalizeHandler(void *ctx, OCDoHand
             OIC_LOG(INFO, TAG, "Direct-Papring was successfully completed.");\r
 \r
             // update paired list\r
-            OCDirectPairingDev_t *dev = getDev(&g_dp_discover, peer->endpoint.addr, peer->endpoint.port);\r
+            OCDirectPairingDev_t *dev = getDev(&g_dp_discover, peer->endpoint.addr,\r
+                    peer->endpoint.port);\r
             res = addDev2(&g_dp_paired, dev);\r
             if (OC_STACK_OK != res)\r
             {\r
@@ -436,14 +439,17 @@ OCStackResult FinalizeDirectPairing(OCDirectPairingDev_t* peer,
         return OC_STACK_NO_MEMORY;\r
     }\r
     secPayload->base.type = PAYLOAD_TYPE_SECURITY;\r
-    secPayload->securityData = BinToDpairingJSON(&dpair);\r
-    if(NULL == secPayload->securityData)\r
+\r
+    OCStackResult ret = DpairingToCBORPayload(&dpair, &(secPayload->securityData1),\r
+            &(secPayload->payloadSize));\r
+\r
+    if(OC_STACK_OK != ret)\r
     {\r
         OICFree(secPayload);\r
-        OIC_LOG(ERROR, TAG, "Failed to BinToDpairingJSON");\r
+        OIC_LOG(ERROR, TAG, "Failed to DpairingToCBORPayload");\r
         return OC_STACK_NO_MEMORY;\r
     }\r
-    OIC_LOG_V(INFO, TAG, "DPARING : %s", secPayload->securityData);\r
+    OIC_LOG_V(INFO, TAG, "DPARING : %s", secPayload->securityData1);\r
 \r
     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};\r
     if(!DPGenerateQuery(true,\r
@@ -476,7 +482,7 @@ OCStackResult FinalizeDirectPairing(OCDirectPairingDev_t* peer,
     OCMethod method = OC_REST_PUT;\r
     OCDoHandle handle = NULL;\r
     OIC_LOG(DEBUG, TAG, "Sending DPAIRNG setting to resource server");\r
-    OCStackResult ret = OCDoResource(&handle, method, query,\r
+    ret = OCDoResource(&handle, method, query,\r
             &peer->endpoint, (OCPayload*)secPayload,\r
             peer->connType, OC_LOW_QOS, &cbData, NULL, 0);\r
     if(OC_STACK_OK != ret)\r
@@ -612,7 +618,8 @@ static OCStackApplicationResult DirectPairingHandler(void *ctx, OCDoHandle UNUSE
             VERIFY_NON_NULL(TAG, endpoint, FATAL);\r
             memcpy(endpoint,&dpairData->peer->endpoint,sizeof(CAEndpoint_t));\r
             endpoint->port = dpairData->peer->securePort;\r
-            OIC_LOG_V(INFO, TAG, "Initiate DTLS handshake to %s(%d)", endpoint->addr, endpoint->port);\r
+            OIC_LOG_V(INFO, TAG, "Initiate DTLS handshake to %s(%d)", endpoint->addr,\r
+                    endpoint->port);\r
 \r
             caresult = CAInitiateHandshake(endpoint);\r
             OICFree(endpoint);\r
@@ -687,14 +694,17 @@ OCStackResult DPDirectPairing(OCDirectPairingDev_t* peer, OicSecPrm_t pmSel, cha
         return OC_STACK_NO_MEMORY;\r
     }\r
     secPayload->base.type = PAYLOAD_TYPE_SECURITY;\r
-    secPayload->securityData = BinToDpairingJSON(&dpair);\r
-    if(NULL == secPayload->securityData)\r
+\r
+    OCStackResult ret = DpairingToCBORPayload(&dpair, &(secPayload->securityData1),\r
+            &(secPayload->payloadSize));\r
+\r
+    if(OC_STACK_OK != ret)\r
     {\r
         OICFree(secPayload);\r
-        OIC_LOG(ERROR, TAG, "Failed to BinToDpairingJSON");\r
+        OIC_LOG(ERROR, TAG, "Failed to DpairingToCBORPayload");\r
         return OC_STACK_NO_MEMORY;\r
     }\r
-    OIC_LOG_V(INFO, TAG, "DPAIRING : %s", secPayload->securityData);\r
+    OIC_LOG_V(INFO, TAG, "DPARING : %s", secPayload->securityData1);\r
 \r
     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};\r
     if(!DPGenerateQuery(false,\r
@@ -729,7 +739,7 @@ OCStackResult DPDirectPairing(OCDirectPairingDev_t* peer, OicSecPrm_t pmSel, cha
     OCMethod method = OC_REST_POST;\r
     OCDoHandle handle = NULL;\r
     OIC_LOG(DEBUG, TAG, "Sending DPAIRNG setting to resource server");\r
-    OCStackResult ret = OCDoResource(&handle, method, query,\r
+    ret = OCDoResource(&handle, method, query,\r
             &peer->endpoint, (OCPayload*)secPayload,\r
             peer->connType, OC_LOW_QOS, &cbData, NULL, 0);\r
     if(OC_STACK_OK != ret)\r
@@ -755,7 +765,8 @@ OCStackResult DPDirectPairing(OCDirectPairingDev_t* peer, OicSecPrm_t pmSel, cha
 static OCStackApplicationResult DirectPairingPortDiscoveryHandler(void *ctx, OCDoHandle UNUSED,\r
                                  OCClientResponse *clientResponse)\r
 {\r
-    OIC_LOG(INFO, TAG, "Callback Context for Direct-Pairing Secure Port DISCOVER query recvd successfully");\r
+    OIC_LOG(INFO, TAG, "Callback Context for Direct-Pairing Secure Port DISCOVER "\r
+            "query recvd successfully");\r
 \r
     (void)ctx;\r
     (void)UNUSED;\r
@@ -844,11 +855,14 @@ static OCStackApplicationResult DirectPairingDiscoveryHandler(void* ctx, OCDoHan
         }\r
 \r
         OIC_LOG_PAYLOAD(INFO, clientResponse->payload);\r
-        OicSecPconf_t *pconf = JSONToPconfBin(\r
-                    ((OCSecurityPayload*)clientResponse->payload)->securityData);\r
-        if (NULL == pconf)\r
+        OicSecPconf_t *pconf = NULL;\r
+\r
+        OCStackResult res = CBORPayloadToPconf(\r
+                ((OCSecurityPayload*)clientResponse->payload)->securityData1,\r
+                CBOR_SIZE,&pconf);\r
+        if (OC_STACK_OK != res )\r
         {\r
-            OIC_LOG(INFO, TAG, "Ignoring malformed JSON");\r
+            OIC_LOG(INFO, TAG, "Ignoring malformed CBOR");\r
             return OC_STACK_KEEP_TRANSACTION;\r
         }\r
         else\r
@@ -865,6 +879,7 @@ static OCStackApplicationResult DirectPairingDiscoveryHandler(void* ctx, OCDoHan
                 return OC_STACK_KEEP_TRANSACTION;\r
             }\r
 \r
+\r
             char rsrc_uri[MAX_URI_LENGTH+1] = {0};\r
             int wr_len = snprintf(rsrc_uri, sizeof(rsrc_uri), "%s?%s=%s",\r
                       OC_RSRVD_WELL_KNOWN_URI, OC_RSRVD_RESOURCE_TYPE, OIC_RSRC_TYPE_SEC_DPAIRING);\r
index 860a78d..cf958c8 100644 (file)
 // limitations under the License.
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#include <stdlib.h>
+#include <string.h>
+
+#if HAVE_STRINGS_H
+#include <strings.h>
+#endif
+
+#ifdef __WITH_DTLS__
+#include "global.h"
+#endif
 
 #include "ocstack.h"
-#include "logger.h"
 #include "oic_malloc.h"
-#include "cJSON.h"
+#include "payload_logging.h"
+#include "utlist.h"
+#include "ocrandom.h"
+#include "ocpayload.h"
+#include "cainterface.h"
+#include "ocserverrequest.h"
 #include "resourcemanager.h"
 #include "doxmresource.h"
 #include "pstatresource.h"
 #include "aclresource.h"
 #include "psinterface.h"
-#include "utlist.h"
 #include "srmresourcestrings.h"
 #include "securevirtualresourcetypes.h"
-#include "base64.h"
-#include "ocrandom.h"
-#include "cainterface.h"
 #include "credresource.h"
-#include "ocserverrequest.h"
 #include "srmutility.h"
 #include "pinoxmcommon.h"
 
-#ifdef __WITH_DTLS__
-#include "global.h"
-#endif
+#define TAG  "SRM-DOXM"
 
-#include <stdlib.h>
-#include <string.h>
+/** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
+ * The value of payload size is increased until reaching belox max cbor size. */
+static const uint8_t CBOR_SIZE = 255;
 
-#if HAVE_STRINGS_H
-#include <strings.h>
-#endif
+/** Max cbor size payload. */
+static const uint16_t CBOR_MAX_SIZE = 4400;
 
-#define TAG  "SRM-DOXM"
+/** DOXM Map size - Number of mandatory items. */
+static const uint8_t DOXM_MAP_SIZE = 6;
 
 static OicSecDoxm_t        *gDoxm = NULL;
 static OCResourceHandle    gDoxmHandle = NULL;
@@ -88,58 +96,102 @@ void DeleteDoxmBinData(OicSecDoxm_t* doxm)
     }
 }
 
-char * BinToDoxmJSON(const OicSecDoxm_t * doxm)
+OCStackResult DoxmToCBORPayload(const OicSecDoxm_t *doxm, uint8_t **payload, size_t *size)
 {
-    if (NULL == doxm)
+    if (NULL == doxm || NULL == payload || NULL != *payload || NULL == size)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+    size_t cborLen = *size;
+    if (0 == cborLen)
     {
-        return NULL;
+        cborLen = CBOR_SIZE;
     }
+    *payload = NULL;
+    *size = 0;
 
-    char *jsonStr = NULL;
-    cJSON *jsonDoxm = NULL;
-    char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};
-    uint32_t outLen = 0;
-    B64Result b64Ret = B64_OK;
+    OCStackResult ret = OC_STACK_ERROR;
 
-    cJSON *jsonRoot = cJSON_CreateObject();
-    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+    CborEncoder encoder = { {.ptr = NULL }, .end = 0 };
+    CborEncoder doxmMap = { {.ptr = NULL }, .end = 0 };
 
-    jsonDoxm = cJSON_CreateObject();
-    VERIFY_NON_NULL(TAG, jsonDoxm, ERROR);
-    cJSON_AddItemToObject(jsonRoot, OIC_JSON_DOXM_NAME, jsonDoxm );
+    int64_t cborEncoderResult = CborNoError;
+    uint8_t mapSize = DOXM_MAP_SIZE;
+    if (doxm->oxmTypeLen > 0)
+    {
+        mapSize++;
+    }
+    if (doxm->oxmLen > 0)
+    {
+        mapSize++;
+    }
+
+    uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
+    VERIFY_NON_NULL(TAG, outPayload, ERROR);
+    cbor_encoder_init(&encoder, outPayload, cborLen, 0);
+
+    cborEncoderResult |= cbor_encoder_create_map(&encoder, &doxmMap, mapSize);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Doxm Map.");
 
     //OxmType -- Not Mandatory
-    if(doxm->oxmTypeLen > 0)
+    if (doxm->oxmTypeLen > 0)
     {
-        cJSON *jsonOxmTyArray = cJSON_CreateArray();
-        VERIFY_NON_NULL(TAG, jsonOxmTyArray, ERROR);
-        cJSON_AddItemToObject (jsonDoxm, OIC_JSON_OXM_TYPE_NAME, jsonOxmTyArray );
+        cborEncoderResult |= cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_TYPE_NAME,
+            strlen(OIC_JSON_OXM_TYPE_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Tag.");
+        CborEncoder oxmType;
+        cborEncoderResult |= cbor_encoder_create_array(&doxmMap, &oxmType, doxm->oxmTypeLen);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Array.");
+
         for (size_t i = 0; i < doxm->oxmTypeLen; i++)
         {
-            cJSON_AddItemToArray (jsonOxmTyArray, cJSON_CreateString(doxm->oxmType[i]));
+            cborEncoderResult |= cbor_encode_text_string(&oxmType, doxm->oxmType[i],
+                strlen(doxm->oxmType[i]));
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Value.");
         }
+        cborEncoderResult |= cbor_encoder_close_container(&doxmMap, &oxmType);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmType.");
     }
 
     //Oxm -- Not Mandatory
-    if(doxm->oxmLen > 0)
+    if (doxm->oxmLen > 0)
     {
-        cJSON *jsonOxmArray = cJSON_CreateArray();
-        VERIFY_NON_NULL(TAG, jsonOxmArray, ERROR);
-        cJSON_AddItemToObject (jsonDoxm, OIC_JSON_OXM_NAME,jsonOxmArray );
+        cborEncoderResult |= cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_NAME,
+            strlen(OIC_JSON_OXM_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Tag.");
+        CborEncoder oxm;
+        cborEncoderResult |= cbor_encoder_create_array(&doxmMap, &oxm, doxm->oxmLen);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Array.");
+
         for (size_t i = 0; i < doxm->oxmLen; i++)
         {
-            cJSON_AddItemToArray (jsonOxmArray, cJSON_CreateNumber(doxm->oxm[i]));
+            cborEncoderResult |= cbor_encode_int(&oxm, doxm->oxm[i]);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Value");
         }
+        cborEncoderResult |= cbor_encoder_close_container(&doxmMap, &oxm);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmName.");
     }
 
     //OxmSel -- Mandatory
-    cJSON_AddNumberToObject(jsonDoxm, OIC_JSON_OXM_SEL_NAME, (int)doxm->oxmSel);
+    cborEncoderResult |= cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_SEL_NAME,
+        strlen(OIC_JSON_OXM_SEL_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Tag.");
+    cborEncoderResult |= cbor_encode_int(&doxmMap, doxm->oxmSel);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Value.");
 
     //sct -- Mandatory
-    cJSON_AddNumberToObject(jsonDoxm, OIC_JSON_SUPPORTED_CRED_TYPE_NAME, (int)doxm->sct);
+    cborEncoderResult |= cbor_encode_text_string(&doxmMap, OIC_JSON_SUPPORTED_CRED_TYPE_NAME,
+        strlen(OIC_JSON_SUPPORTED_CRED_TYPE_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Tag");
+    cborEncoderResult |= cbor_encode_int(&doxmMap, doxm->sct);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Value.");
 
     //Owned -- Mandatory
-    cJSON_AddBoolToObject(jsonDoxm, OIC_JSON_OWNED_NAME, doxm->owned);
+    cborEncoderResult |= cbor_encode_text_string(&doxmMap, OIC_JSON_OWNED_NAME,
+        strlen(OIC_JSON_OWNED_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Tag.");
+    cborEncoderResult |= cbor_encode_boolean(&doxmMap, doxm->owned);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Value.");
 
     //TODO: Need more clarification on deviceIDFormat field type.
 #if 0
@@ -148,105 +200,142 @@ char * BinToDoxmJSON(const OicSecDoxm_t * doxm)
 #endif
 
     //DeviceId -- Mandatory
-    outLen = 0;
-    b64Ret = b64Encode(doxm->deviceID.id, sizeof(doxm->deviceID.id), base64Buff,
-                    sizeof(base64Buff), &outLen);
-    VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
-    cJSON_AddStringToObject(jsonDoxm, OIC_JSON_DEVICE_ID_NAME, base64Buff);
+    cborEncoderResult |= cbor_encode_text_string(&doxmMap, OIC_JSON_DEVICE_ID_NAME,
+        strlen(OIC_JSON_DEVICE_ID_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Tag.");
+    cborEncoderResult |= cbor_encode_byte_string(&doxmMap, doxm->deviceID.id,
+                                                sizeof(doxm->deviceID.id));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Value.");
 
     //DPC -- Mandatory
-    cJSON_AddBoolToObject(jsonDoxm, OIC_JSON_DPC_NAME, doxm->dpc);
+    cborEncoderResult |= cbor_encode_text_string(&doxmMap, OIC_JSON_DPC_NAME,
+        strlen(OIC_JSON_DPC_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DPC Tag.");
+    cborEncoderResult |= cbor_encode_boolean(&doxmMap, doxm->dpc);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DPC Value.");
 
     //Owner -- Mandatory
-    outLen = 0;
-    b64Ret = b64Encode(doxm->owner.id, sizeof(doxm->owner.id), base64Buff,
-                    sizeof(base64Buff), &outLen);
-    VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
-    cJSON_AddStringToObject(jsonDoxm, OIC_JSON_OWNER_NAME, base64Buff);
+    cborEncoderResult |= cbor_encode_text_string(&doxmMap, OIC_JSON_OWNER_NAME,
+        strlen(OIC_JSON_OWNER_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner tag.");
+    cborEncoderResult |= cbor_encode_byte_string(&doxmMap, doxm->owner.id,
+                                                sizeof(doxm->owner.id));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Value");
 
-    jsonStr = cJSON_PrintUnformatted(jsonRoot);
+    cborEncoderResult |= cbor_encoder_close_container(&encoder, &doxmMap);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing DoxmMap.");
 
+    if (CborNoError == cborEncoderResult)
+    {
+        *size = encoder.ptr - outPayload;
+        *payload = outPayload;
+        ret = OC_STACK_OK;
+    }
 exit:
-    if (jsonRoot)
+    if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
     {
-        cJSON_Delete(jsonRoot);
+        OIC_LOG(DEBUG, TAG, "Memory getting reallocated.");
+        // reallocate and try again!
+        OICFree(outPayload);
+        // Since the allocated initial memory failed, double the memory.
+        cborLen += encoder.ptr - encoder.end;
+        OIC_LOG_V(DEBUG, TAG, "Doxm reallocation size : %zd.", cborLen);
+        cborEncoderResult = CborNoError;
+        ret = DoxmToCBORPayload(doxm, payload, &cborLen);
+        *size = cborLen;
     }
-    return jsonStr;
+
+    if ((CborNoError != cborEncoderResult) || (OC_STACK_OK != ret))
+    {
+       OICFree(outPayload);
+       outPayload = NULL;
+       *payload = NULL;
+       *size = 0;
+       ret = OC_STACK_ERROR;
+    }
+
+    return ret;
 }
 
-OicSecDoxm_t * JSONToDoxmBin(const char * jsonStr)
+OCStackResult CBORPayloadToDoxm(const uint8_t *cborPayload, size_t size,
+                                OicSecDoxm_t **secDoxm)
 {
-
-    if (NULL == jsonStr)
+    if (NULL == cborPayload || NULL == secDoxm || NULL != *secDoxm)
     {
-        return NULL;
+        return OC_STACK_INVALID_PARAM;
     }
 
     OCStackResult ret = OC_STACK_ERROR;
-    OicSecDoxm_t *doxm =  NULL;
-    cJSON *jsonDoxm = NULL;
-    cJSON *jsonObj = NULL;
-
-    size_t jsonObjLen = 0;
-    unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
-    uint32_t outLen = 0;
-    B64Result b64Ret = B64_OK;
-
-    cJSON *jsonRoot = cJSON_Parse(jsonStr);
-    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
-
-    jsonDoxm = cJSON_GetObjectItem(jsonRoot, OIC_JSON_DOXM_NAME);
-    VERIFY_NON_NULL(TAG, jsonDoxm, ERROR);
-
-    doxm = (OicSecDoxm_t*)OICCalloc(1, sizeof(OicSecDoxm_t));
+    *secDoxm = NULL;
+
+    CborParser parser;
+    CborError cborFindResult = CborNoError;
+    int cborLen = (size == 0) ? CBOR_SIZE : size;
+    size_t len = 0;
+    CborValue doxmCbor;
+    cbor_parser_init(cborPayload, cborLen, 0, &parser, &doxmCbor);
+    CborValue doxmMap;
+    OicSecDoxm_t *doxm = (OicSecDoxm_t *)OICCalloc(1, sizeof(*doxm));
     VERIFY_NON_NULL(TAG, doxm, ERROR);
 
+    cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_TYPE_NAME, &doxmMap);
     //OxmType -- not Mandatory
-    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OXM_TYPE_NAME);
-    if ((jsonObj) && (cJSON_Array == jsonObj->type))
+    if (CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
     {
-        doxm->oxmTypeLen = (size_t)cJSON_GetArraySize(jsonObj);
-        VERIFY_SUCCESS(TAG, doxm->oxmTypeLen > 0, ERROR);
+        CborValue oxmType;
 
-        doxm->oxmType = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(char *));
-        VERIFY_NON_NULL(TAG, (doxm->oxmType), ERROR);
+        cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmTypeLen);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmTypeLen.")
+        VERIFY_SUCCESS(TAG, doxm->oxmTypeLen != 0, ERROR);
 
-        for (size_t i  = 0; i < doxm->oxmTypeLen ; i++)
-        {
-            cJSON *jsonOxmTy = cJSON_GetArrayItem(jsonObj, i);
-            VERIFY_NON_NULL(TAG, jsonOxmTy, ERROR);
+        doxm->oxmType = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(*doxm->oxmType));
+        VERIFY_NON_NULL(TAG, doxm->oxmType, ERROR);
+
+        cborFindResult = cbor_value_enter_container(&doxmMap, &oxmType);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmType Array.")
 
-            jsonObjLen = strlen(jsonOxmTy->valuestring) + 1;
-            doxm->oxmType[i] = (char*)OICMalloc(jsonObjLen);
-            VERIFY_NON_NULL(TAG, doxm->oxmType[i], ERROR);
-            strncpy((char *)doxm->oxmType[i], (char *)jsonOxmTy->valuestring, jsonObjLen);
+        int i = 0;
+        size_t len = 0;
+        while (cbor_value_is_valid(&oxmType))
+        {
+            cborFindResult = cbor_value_dup_text_string(&oxmType, &doxm->oxmType[i++],
+                                                        &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding omxType text string.")
+            cborFindResult = cbor_value_advance(&oxmType);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmType.")
         }
     }
 
+    cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_NAME, &doxmMap);
     //Oxm -- not Mandatory
-    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OXM_NAME);
-    if (jsonObj && cJSON_Array == jsonObj->type)
+    if (CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
     {
-        doxm->oxmLen = (size_t)cJSON_GetArraySize(jsonObj);
-        VERIFY_SUCCESS(TAG, doxm->oxmLen > 0, ERROR);
+        CborValue oxm;
+        cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmLen);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName array Length.")
+        VERIFY_SUCCESS(TAG, doxm->oxmLen != 0, ERROR);
 
-        doxm->oxm = (OicSecOxm_t*)OICCalloc(doxm->oxmLen, sizeof(OicSecOxm_t));
+        doxm->oxm = (OicSecOxm_t *)OICCalloc(doxm->oxmLen, sizeof(*doxm->oxm));
         VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
 
-        for (size_t i  = 0; i < doxm->oxmLen ; i++)
+        cborFindResult = cbor_value_enter_container(&doxmMap, &oxm);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmName Array.")
+
+        int i = 0;
+        while (cbor_value_is_valid(&oxm))
         {
-            cJSON *jsonOxm = cJSON_GetArrayItem(jsonObj, i);
-            VERIFY_NON_NULL(TAG, jsonOxm, ERROR);
-            doxm->oxm[i] = (OicSecOxm_t)jsonOxm->valueint;
+            cborFindResult = cbor_value_get_int(&oxm, (int *) &doxm->oxm[i++]);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName Value")
+            cborFindResult = cbor_value_advance(&oxm);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmName.")
         }
     }
 
-    //OxmSel -- Mandatory
-    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OXM_SEL_NAME);
-    if(jsonObj)
+    cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_SEL_NAME, &doxmMap);
+    if (CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
     {
-        VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
-        doxm->oxmSel = (OicSecOxm_t)jsonObj->valueint;
+        cborFindResult = cbor_value_get_int(&doxmMap, (int *) &doxm->oxmSel);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sel Name Value.")
     }
     else // PUT/POST JSON may not have oxmsel so set it to the gDoxm->oxmSel
     {
@@ -254,12 +343,11 @@ OicSecDoxm_t * JSONToDoxmBin(const char * jsonStr)
         doxm->oxmSel = gDoxm->oxmSel;
     }
 
-    //sct -- Mandatory
-    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_SUPPORTED_CRED_TYPE_NAME);
-    if(jsonObj)
+    cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_SUPPORTED_CRED_TYPE_NAME, &doxmMap);
+    if (CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
     {
-        VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
-        doxm->sct = (OicSecCredType_t)jsonObj->valueint;
+        cborFindResult = cbor_value_get_int(&doxmMap, (int *) &doxm->sct);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sct Name Value.")
     }
     else // PUT/POST JSON may not have sct so set it to the gDoxm->sct
     {
@@ -267,12 +355,11 @@ OicSecDoxm_t * JSONToDoxmBin(const char * jsonStr)
         doxm->sct = gDoxm->sct;
     }
 
-    //Owned -- Mandatory
-    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OWNED_NAME);
-    if(jsonObj)
+    cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OWNED_NAME, &doxmMap);
+    if (CborNoError == cborFindResult && cbor_value_is_boolean(&doxmMap))
     {
-        VERIFY_SUCCESS(TAG, (cJSON_True == jsonObj->type || cJSON_False == jsonObj->type), ERROR);
-        doxm->owned = jsonObj->valueint;
+        cborFindResult = cbor_value_get_boolean(&doxmMap, &doxm->owned);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owned Value.")
     }
     else // PUT/POST JSON may not have owned so set it to the gDomx->owned
     {
@@ -280,77 +367,49 @@ OicSecDoxm_t * JSONToDoxmBin(const char * jsonStr)
         doxm->owned = gDoxm->owned;
     }
 
-    //DeviceId -- Mandatory
-    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_DEVICE_ID_NAME);
-    if(jsonObj)
+    cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DPC_NAME, &doxmMap);
+    if (CborNoError == cborFindResult && cbor_value_is_boolean(&doxmMap))
     {
-        VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
-        if(cJSON_String == jsonObj->type)
-        {
-            //Check for empty string, in case DeviceId field has not been set yet
-            if (jsonObj->valuestring[0])
-            {
-                outLen = 0;
-                b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff,
-                        sizeof(base64Buff), &outLen);
-                VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(doxm->deviceID.id)),
-                                ERROR);
-                memcpy(doxm->deviceID.id, base64Buff, outLen);
-            }
-        }
+        cborFindResult = cbor_value_get_boolean(&doxmMap, &doxm->dpc);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding DPC Value.")
     }
-    else // PUT/POST JSON will not have deviceID so set it to the gDoxm->deviceID.id
+    else // PUT/POST JSON may not have owned so set it to the gDomx->owned
     {
         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
-        memcpy((char *)doxm->deviceID.id, (char *)gDoxm->deviceID.id, sizeof(doxm->deviceID.id));
+        doxm->owned = false;
     }
 
-    //DPC -- Mandatory
-    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_DPC_NAME);
-    if(jsonObj)
+    cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVICE_ID_NAME, &doxmMap);
+    if (CborNoError == cborFindResult && cbor_value_is_byte_string(&doxmMap))
     {
-        VERIFY_SUCCESS(TAG, (cJSON_True == jsonObj->type || cJSON_False == jsonObj->type), ERROR);
-        doxm->dpc = jsonObj->valueint;
+        uint8_t *id = NULL;
+        cborFindResult = cbor_value_dup_byte_string(&doxmMap, &id, &len, NULL);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding DeviceId Value.")
+        memcpy(doxm->deviceID.id, id, len);
+        OICFree(id);
     }
-    else // PUT/POST JSON may not have owned so set it to the gDomx->dpc
+    cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OWNER_NAME, &doxmMap);
+    if (CborNoError == cborFindResult && cbor_value_is_byte_string(&doxmMap))
     {
-        if(NULL != gDoxm)
-        {
-            doxm->dpc = gDoxm->dpc;
-        }
-        else
-        {
-            doxm->dpc = false; // default is false
-        }
-    }
-
-    //Owner -- will be empty when device status is unowned.
-    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OWNER_NAME);
-    if(true == doxm->owned)
-    {
-        VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-    }
-    if(jsonObj)
-    {
-        VERIFY_SUCCESS(TAG, (cJSON_String == jsonObj->type), ERROR);
-        outLen = 0;
-        b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff,
-                sizeof(base64Buff), &outLen);
-        VERIFY_SUCCESS(TAG, ((b64Ret == B64_OK) && (outLen <= sizeof(doxm->owner.id))), ERROR);
-        memcpy(doxm->owner.id, base64Buff, outLen);
+        uint8_t *id = NULL;
+        cborFindResult = cbor_value_dup_byte_string(&doxmMap, &id , &len, NULL);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owner Name Value.")
+        memcpy(doxm->owner.id, id, len);
+        OICFree(id);
     }
 
+    *secDoxm = doxm;
     ret = OC_STACK_OK;
 
 exit:
-    cJSON_Delete(jsonRoot);
-    if (OC_STACK_OK != ret)
+    if (CborNoError != cborFindResult)
     {
+        OIC_LOG (ERROR, TAG, "CBORPayloadToDoxm failed!!!");
         DeleteDoxmBinData(doxm);
         doxm = NULL;
+        ret = OC_STACK_ERROR;
     }
-
-    return doxm;
+    return ret;
 }
 
 /**
@@ -363,19 +422,22 @@ static bool UpdatePersistentStorage(OicSecDoxm_t * doxm)
 
     if (NULL != doxm)
     {
-        // Convert Doxm data into JSON for update to persistent storage
-        char *jsonStr = BinToDoxmJSON(doxm);
-        if (jsonStr)
+        // Convert Doxm data into CBOR for update to persistent storage
+        uint8_t *payload = NULL;
+        size_t size = 0;
+        OCStackResult res = DoxmToCBORPayload(doxm, &payload, &size);
+        if (payload && (OC_STACK_OK == res)
+            && (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, payload, size)))
+        {
+                bRet = true;
+        }
+        OICFree(payload);
+    }
+    else
+    {
+        if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, NULL, 0))
         {
-            cJSON *jsonDoxm = cJSON_Parse(jsonStr);
-            OICFree(jsonStr);
-
-            if (jsonDoxm &&
-                    (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_DOXM_NAME, jsonDoxm)))
-            {
                 bRet = true;
-            }
-            cJSON_Delete(jsonDoxm);
         }
     }
 
@@ -407,262 +469,267 @@ static bool ValidateQuery(const char * query)
 
     ParseQueryIterInit((unsigned char*)query, &parseIter);
 
-    while(GetNextQuery(&parseIter))
+    while (GetNextQuery(&parseIter))
     {
-        if(strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
+        if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
         {
             bOwnedQry = true;
-            if((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
+            if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
                     (gDoxm->owned))
             {
                 bOwnedMatch = true;
             }
-            else if((strncasecmp((char *)parseIter.valPos, OIC_SEC_FALSE, parseIter.valLen) == 0)
+            else if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_FALSE, parseIter.valLen) == 0)
                     && (!gDoxm->owned))
             {
                 bOwnedMatch = true;
             }
         }
 
-        if(strncasecmp((char *)parseIter.attrPos, OIC_JSON_DEVICE_ID_NAME, parseIter.attrLen) == 0)
+        if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_DEVICE_ID_NAME, parseIter.attrLen) == 0)
         {
             bDeviceIDQry = true;
             OicUuid_t subject = {.id={0}};
-            unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
-            uint32_t outLen = 0;
-            B64Result b64Ret = B64_OK;
-
-            b64Ret = b64Decode((char *)parseIter.valPos, parseIter.valLen, base64Buff,
-                                           sizeof(base64Buff), &outLen);
 
-            VERIFY_SUCCESS(TAG, (B64_OK == b64Ret && outLen <= sizeof(subject.id)), ERROR);
-                       memcpy(subject.id, base64Buff, outLen);
-            if(0 == memcmp(&gDoxm->deviceID.id, &subject.id, sizeof(gDoxm->deviceID.id)))
+            memcpy(subject.id, parseIter.valPos, parseIter.valLen);
+            if (0 == memcmp(&gDoxm->deviceID.id, &subject.id, sizeof(gDoxm->deviceID.id)))
             {
                 bDeviceIDMatch = true;
             }
         }
     }
 
-exit:
     return ((bOwnedQry ? bOwnedMatch : true) && (bDeviceIDQry ? bDeviceIDMatch : true));
 }
 
 static OCEntityHandlerResult HandleDoxmGetRequest (const OCEntityHandlerRequest * ehRequest)
 {
-    char* jsonStr = NULL;
     OCEntityHandlerResult ehRet = OC_EH_OK;
 
-    OIC_LOG (DEBUG, TAG, "Doxm EntityHandle processing GET request");
+    OIC_LOG(DEBUG, TAG, "Doxm EntityHandle processing GET request");
 
     //Checking if Get request is a query.
-    if(ehRequest->query)
+    if (ehRequest->query)
     {
-        OIC_LOG (DEBUG, TAG, "HandleDoxmGetRequest processing query");
-        if(!ValidateQuery(ehRequest->query))
+        OIC_LOG(DEBUG, TAG, "HandleDoxmGetRequest processing query");
+        if (!ValidateQuery(ehRequest->query))
         {
             ehRet = OC_EH_ERROR;
         }
     }
 
     /*
-     * For GET or Valid Query request return doxm resource json payload.
+     * For GET or Valid Query request return doxm resource CBOR payload.
      * For non-valid query return NULL json payload.
-     * A device will 'always' have a default Doxm, so BinToDoxmJSON will
+     * A device will 'always' have a default Doxm, so DoxmToCBORPayload will
      * return valid doxm resource json.
      */
+    uint8_t *payload = NULL;
+    size_t size = 0;
 
-    jsonStr = (ehRet == OC_EH_OK) ? BinToDoxmJSON(gDoxm) : NULL;
+    if (ehRet == OC_EH_OK)
+    {
+        if (OC_STACK_OK != DoxmToCBORPayload(gDoxm, &payload, &size))
+        {
+            payload = NULL;
+        }
+    }
 
     // Send response payload to request originator
-    if(OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, jsonStr))
+    if (OC_STACK_OK != SendSRMCBORResponse(ehRequest, ehRet, payload, size))
     {
-        OIC_LOG (ERROR, TAG, "SendSRMResponse failed in HandleDoxmGetRequest");
+        OIC_LOG(ERROR, TAG, "SendSRMCBORResponse failed in HandleDoxmGetRequest");
     }
 
-    OICFree(jsonStr);
+    OICFree(payload);
 
     return ehRet;
 }
 
-static OCEntityHandlerResult HandleDoxmPutRequest (const OCEntityHandlerRequest * ehRequest)
+static OCEntityHandlerResult HandleDoxmPutRequest(const OCEntityHandlerRequest * ehRequest)
 {
     OIC_LOG (DEBUG, TAG, "Doxm EntityHandle  processing PUT request");
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
-    OicUuid_t emptyOwner = {.id = {0}};
+    OicUuid_t emptyOwner = {.id = {0} };
 
     /*
-     * Convert JSON Doxm data into binary. This will also validate
+     * Convert CBOR Doxm data into binary. This will also validate
      * the Doxm data received.
      */
-    OicSecDoxm_t* newDoxm = JSONToDoxmBin(((OCSecurityPayload*)ehRequest->payload)->securityData);
+    OicSecDoxm_t *newDoxm = NULL;
 
-    if (newDoxm)
+    if (ehRequest->payload)
     {
-        // Iotivity SRM ONLY supports OIC_JUST_WORKS now
-        if (OIC_JUST_WORKS == newDoxm->oxmSel)
+        uint8_t *payload = ((OCSecurityPayload *)ehRequest->payload)->securityData1;
+        size_t size = ((OCSecurityPayload *)ehRequest->payload)->payloadSize;
+        OCStackResult res = CBORPayloadToDoxm(payload, size, &newDoxm);
+
+        if (newDoxm && OC_STACK_OK == res)
         {
-            if ((false == gDoxm->owned) && (false == newDoxm->owned))
+            if (OIC_JUST_WORKS == newDoxm->oxmSel)
             {
-                /*
-                 * If current state of the device is un-owned, enable
-                 * anonymous ECDH cipher in tinyDTLS so that Provisioning
-                 * tool can initiate JUST_WORKS ownership transfer process.
-                 */
-                if(memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
+                if ((false == gDoxm->owned) && (false == newDoxm->owned))
                 {
-                    OIC_LOG (INFO, TAG, "Doxm EntityHandle  enabling AnonECDHCipherSuite");
+                    /*
+                     * If current state of the device is un-owned, enable
+                     * anonymous ECDH cipher in tinyDTLS so that Provisioning
+                     * tool can initiate JUST_WORKS ownership transfer process.
+                     */
+                    if (memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
+                    {
+                        OIC_LOG (INFO, TAG, "Doxm EntityHandle  enabling AnonECDHCipherSuite");
 #ifdef __WITH_DTLS__
-                    ehRet = (CAEnableAnonECDHCipherSuite(true) == CA_STATUS_OK) ? OC_EH_OK : OC_EH_ERROR;
+                        ehRet = (CAEnableAnonECDHCipherSuite(true) == CA_STATUS_OK) ? OC_EH_OK : OC_EH_ERROR;
 #endif //__WITH_DTLS__
-                    goto exit;
-                }
-                else
-                {
-#ifdef __WITH_DTLS__
-                    //Save the owner's UUID to derive owner credential
-                    memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
-
-//                    OCServerRequest *request = (OCServerRequest *)ehRequest->requestHandle;
-//                    //Generating OwnerPSK
-//                    OIC_LOG (INFO, TAG, "Doxm EntityHandle  generating OwnerPSK");
-//                    //Generate new credential for provisioning tool
-//                    ehRet = AddOwnerPSK((CAEndpoint_t *)&request->devAddr, newDoxm,
-//                            (uint8_t*) OXM_JUST_WORKS, strlen(OXM_JUST_WORKS));
-//                    VERIFY_SUCCESS(TAG, OC_EH_OK == ehRet, ERROR);
-
-                    // Update new state in persistent storage
-                    if (true == UpdatePersistentStorage(gDoxm))
-                    {
-                        ehRet = OC_EH_OK;
+                        goto exit;
                     }
                     else
                     {
-                        OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
-                        ehRet = OC_EH_ERROR;
-                    }
-
-                    /*
-                     * Disable anonymous ECDH cipher in tinyDTLS since device is now
-                     * in owned state.
-                     */
-                    CAResult_t caRes = CA_STATUS_OK;
-                    caRes = CAEnableAnonECDHCipherSuite(false);
-                    VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
-                    OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
+#ifdef __WITH_DTLS__
+                        //Save the owner's UUID to derive owner credential
+                        memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
+
+                        // OCServerRequest *request = (OCServerRequest *)ehRequest->requestHandle;
+                        // Generating OwnerPSK
+                        // OIC_LOG (INFO, TAG, "Doxm EntityHandle  generating OwnerPSK");
+                        // Generate new credential for provisioning tool
+                        // ehRet = AddOwnerPSK((CAEndpoint_t *)&request->devAddr, newDoxm,
+                        //       (uint8_t*) OXM_JUST_WORKS, strlen(OXM_JUST_WORKS));
+                        // VERIFY_SUCCESS(TAG, OC_EH_OK == ehRet, ERROR);
+
+                        // Update new state in persistent storage
+                        if (true == UpdatePersistentStorage(gDoxm))
+                        {
+                            ehRet = OC_EH_OK;
+                        }
+                        else
+                        {
+                            OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
+                            ehRet = OC_EH_ERROR;
+                        }
+
+                        /*
+                         * Disable anonymous ECDH cipher in tinyDTLS since device is now
+                         * in owned state.
+                         */
+                        CAResult_t caRes = CA_STATUS_OK;
+                        caRes = CAEnableAnonECDHCipherSuite(false);
+                        VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
+                        OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
 
 #ifdef __WITH_X509__
 #define TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 0xC0AE
-                    CASelectCipherSuite(TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8);
+                        CASelectCipherSuite(TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8);
 #endif //__WITH_X509__
 #endif //__WITH_DTLS__
+                    }
                 }
             }
-        }
-        else if(OIC_RANDOM_DEVICE_PIN == newDoxm->oxmSel)
-        {
-            if ((false == gDoxm->owned) && (false == newDoxm->owned))
+            else if (OIC_RANDOM_DEVICE_PIN == newDoxm->oxmSel)
             {
-                /*
-                 * If current state of the device is un-owned, enable
-                 * anonymous ECDH cipher in tinyDTLS so that Provisioning
-                 * tool can initiate JUST_WORKS ownership transfer process.
-                 */
-                if(memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
+                if ((false == gDoxm->owned) && (false == newDoxm->owned))
                 {
-                    gDoxm->oxmSel = newDoxm->oxmSel;
-                    //Update new state in persistent storage
-                    if((UpdatePersistentStorage(gDoxm) == true))
-                    {
-                        ehRet = OC_EH_OK;
-                    }
-                    else
+                    /*
+                     * If current state of the device is un-owned, enable
+                     * anonymous ECDH cipher in tinyDTLS so that Provisioning
+                     * tool can initiate JUST_WORKS ownership transfer process.
+                     */
+                    if(memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
                     {
-                        OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
-                        ehRet = OC_EH_ERROR;
-                    }
+                        gDoxm->oxmSel = newDoxm->oxmSel;
+                        //Update new state in persistent storage
+                        if ((UpdatePersistentStorage(gDoxm) == true))
+                        {
+                            ehRet = OC_EH_OK;
+                        }
+                        else
+                        {
+                            OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
+                            ehRet = OC_EH_ERROR;
+                        }
 
 #ifdef __WITH_DTLS__
-                    CAResult_t caRes = CA_STATUS_OK;
-
-                    caRes = CAEnableAnonECDHCipherSuite(false);
-                    VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
-                    OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
+                        CAResult_t caRes = CA_STATUS_OK;
 
-                    caRes = CASelectCipherSuite(TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256);
-                    VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
-
-                    char ranPin[OXM_RANDOM_PIN_SIZE + 1] = {0,};
-                    if(OC_STACK_OK == GeneratePin(ranPin, OXM_RANDOM_PIN_SIZE + 1))
-                    {
-                        //Set the device id to derive temporal PSK
-                        SetUuidForRandomPinOxm(&gDoxm->deviceID);
+                        caRes = CAEnableAnonECDHCipherSuite(false);
+                        VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
+                        OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
 
-                        /**
-                         * 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 = CARegisterDTLSCredentialsHandler(GetDtlsPskForRandomPinOxm);
+                        caRes = CASelectCipherSuite(TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256);
                         VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
-                        ehRet = OC_EH_OK;
+
+                        char ranPin[OXM_RANDOM_PIN_SIZE + 1] = {0,};
+                        if(OC_STACK_OK == GeneratePin(ranPin, OXM_RANDOM_PIN_SIZE + 1))
+                        {
+                            //Set the device id to derive temporal PSK
+                            SetUuidForRandomPinOxm(&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 = CARegisterDTLSCredentialsHandler(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__
                     }
                     else
                     {
-                        OIC_LOG(ERROR, TAG, "Failed to generate random PIN");
-                        ehRet = OC_EH_ERROR;
+#ifdef __WITH_DTLS__
+                        //Save the owner's UUID to derive owner credential
+                        memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
+
+                        //Update new state in persistent storage
+                        if (UpdatePersistentStorage(gDoxm) == true)
+                        {
+                            ehRet = OC_EH_OK;
+                        }
+                        else
+                        {
+                            OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
+                            ehRet = OC_EH_ERROR;
+                        }
+#endif
                     }
-#endif //__WITH_DTLS__
                 }
-                else
-                {
-#ifdef __WITH_DTLS__
-                    //Save the owner's UUID to derive owner credential
-                    memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
+            }
 
-                    //Update new state in persistent storage
-                    if((UpdatePersistentStorage(gDoxm) == true))
+            /*
+             * When current state of the device is un-owned and Provisioning
+             * Tool is attempting to change the state to 'Owned' with a
+             * qualified value for the field 'Owner'
+             */
+            if ((false == gDoxm->owned) && (true == newDoxm->owned) &&
+                    (memcmp(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t)) == 0))
+            {
+                gDoxm->owned = true;
+                // Update new state in persistent storage
+                if (UpdatePersistentStorage(gDoxm))
+                {
+                    //Update default ACL of security resource to prevent anonymous user access.
+                    if(OC_STACK_OK == UpdateDefaultSecProvACL())
                     {
                         ehRet = OC_EH_OK;
                     }
                     else
                     {
-                        OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
+                        OIC_LOG(ERROR, TAG, "Failed to remove default ACL for security provisioning");
                         ehRet = OC_EH_ERROR;
                     }
-#endif
-                }
-            }
-        }
-
-        /*
-         * When current state of the device is un-owned and Provisioning
-         * Tool is attempting to change the state to 'Owned' with a
-         * qualified value for the field 'Owner'
-         */
-        if ((false == gDoxm->owned) && (true == newDoxm->owned) &&
-            (memcmp(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t)) == 0))
-        {
-            gDoxm->owned = true;
-            // Update new state in persistent storage
-            if (UpdatePersistentStorage(gDoxm))
-            {
-                //Update default ACL of security resource to prevent anonymous user access.
-                if(OC_STACK_OK == UpdateDefaultSecProvACL())
-                {
-                    ehRet = OC_EH_OK;
                 }
                 else
                 {
-                    OIC_LOG(ERROR, TAG, "Failed to remove default ACL for security provisioning");
+                    OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
                     ehRet = OC_EH_ERROR;
                 }
             }
-            else
-            {
-                OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
-                ehRet = OC_EH_ERROR;
-            }
         }
     }
 
@@ -681,19 +748,16 @@ exit:
     }
 
     //Send payload to request originator
-    if(OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, NULL))
+    if (OC_STACK_OK != SendSRMCBORResponse(ehRequest, ehRet, NULL, 0))
     {
-        OIC_LOG (ERROR, TAG, "SendSRMResponse failed in HandlePstatPostRequest");
+        OIC_LOG(ERROR, TAG, "SendSRMCBORResponse failed in HandleDoxmPostRequest");
     }
     DeleteDoxmBinData(newDoxm);
 
     return ehRet;
 }
 
-/*
- * This internal method is the entity handler for DOXM resources.
- */
-OCEntityHandlerResult DoxmEntityHandler (OCEntityHandlerFlag flag,
+OCEntityHandlerResult DoxmEntityHandler(OCEntityHandlerFlag flag,
                                         OCEntityHandlerRequest * ehRequest,
                                         void* callbackParam)
 {
@@ -705,10 +769,10 @@ OCEntityHandlerResult DoxmEntityHandler (OCEntityHandlerFlag flag,
         return ehRet;
     }
 
-
     if (flag & OC_REQUEST_FLAG)
     {
-        OIC_LOG (DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
+        OIC_LOG(DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
+
         switch (ehRequest->method)
         {
             case OC_REST_GET:
@@ -721,7 +785,7 @@ OCEntityHandlerResult DoxmEntityHandler (OCEntityHandlerFlag flag,
 
             default:
                 ehRet = OC_EH_ERROR;
-                SendSRMResponse(ehRequest, ehRet, NULL);
+                SendSRMCBORResponse(ehRequest, ehRet, NULL, 0);
                 break;
         }
     }
@@ -729,20 +793,16 @@ OCEntityHandlerResult DoxmEntityHandler (OCEntityHandlerFlag flag,
     return ehRet;
 }
 
-/*
- * This internal method is used to create '/oic/sec/doxm' resource.
- */
 OCStackResult CreateDoxmResource()
 {
-    OCStackResult ret;
-
-    ret = OCCreateResource(&gDoxmHandle,
-                           OIC_RSRC_TYPE_SEC_DOXM,
-                           OIC_MI_DEF,
-                           OIC_RSRC_DOXM_URI,
-                           DoxmEntityHandler,
-                           NULL,
-                           OC_OBSERVABLE | OC_SECURE | OC_EXPLICIT_DISCOVERABLE);
+    OCStackResult ret = OCCreateResource(&gDoxmHandle,
+                                         OIC_RSRC_TYPE_SEC_DOXM,
+                                         OIC_MI_DEF,
+                                         OIC_RSRC_DOXM_URI,
+                                         DoxmEntityHandler,
+                                         NULL,
+                                         OC_OBSERVABLE | OC_SECURE |
+                                         OC_EXPLICIT_DISCOVERABLE);
 
     if (OC_STACK_OK != ret)
     {
@@ -756,7 +816,6 @@ OCStackResult CreateDoxmResource()
  * Checks if DeviceID is generated during provisioning for the new device.
  * If DeviceID is NULL then generates the new DeviceID.
  * Once DeviceID is assigned to the device it does not change for the lifetime of the device.
- *
  */
 static OCStackResult CheckDeviceID()
 {
@@ -780,7 +839,7 @@ static OCStackResult CheckDeviceID()
         }
         ret = OC_STACK_OK;
 
-        if (UpdatePersistentStorage(gDoxm))
+        if (!UpdatePersistentStorage(gDoxm))
         {
             //TODO: After registering PSI handler in all samples, do ret = OC_STACK_OK here.
             OIC_LOG(FATAL, TAG, "UpdatePersistentStorage failed!");
@@ -795,46 +854,44 @@ static OCStackResult CheckDeviceID()
 
 /**
  * Get the default value.
- * @retval  the gDefaultDoxm pointer;
+ *
+ * @return the default value of doxm, @ref OicSecDoxm_t.
  */
 static OicSecDoxm_t* GetDoxmDefault()
 {
-    OIC_LOG (DEBUG, TAG, "GetDoxmToDefault");
+    OIC_LOG(DEBUG, TAG, "GetDoxmToDefault");
     return &gDefaultDoxm;
 }
 
-/**
- * This method is used by SRM to retrieve DOXM resource data.
- *
- * @retval  reference to @ref OicSecDoxm_t, binary format of Doxm resource data
- */
 const OicSecDoxm_t* GetDoxmResourceData()
 {
     return gDoxm;
 }
 
-/**
- * Initialize DOXM resource by loading data from persistent storage.
- *
- * @retval  OC_STACK_OK for Success, otherwise some error value
- */
 OCStackResult InitDoxmResource()
 {
     OCStackResult ret = OC_STACK_ERROR;
 
     //Read DOXM resource from PS
-    char* jsonSVRDatabase = GetSVRDatabase();
-    if(jsonSVRDatabase)
+    uint8_t *data = NULL;
+    size_t size = 0;
+    ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_DOXM_NAME, &data, &size);
+    // If database read failed
+    if (OC_STACK_OK != ret)
+    {
+       OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
+    }
+    if (data)
     {
-        //Convert JSON DOXM into binary format
-        gDoxm = JSONToDoxmBin(jsonSVRDatabase);
+       // Read DOXM resource from PS
+       ret = CBORPayloadToDoxm(data, size, &gDoxm);
     }
     /*
      * If SVR database in persistent storage got corrupted or
      * is not available for some reason, a default doxm is created
      * which allows user to initiate doxm provisioning again.
      */
-    if(!jsonSVRDatabase || !gDoxm)
+     if ((OC_STACK_OK != ret) || !data || !gDoxm)
     {
         gDoxm = GetDoxmDefault();
     }
@@ -849,6 +906,7 @@ OCStackResult InitDoxmResource()
     ret = CheckDeviceID();
     if (ret == OC_STACK_OK)
     {
+        OIC_LOG_V(DEBUG, TAG, "Initial Doxm Owned = %d", gDoxm->owned);
         //Instantiate 'oic.sec.doxm'
         ret = CreateDoxmResource();
     }
@@ -856,28 +914,20 @@ OCStackResult InitDoxmResource()
     {
         OIC_LOG (ERROR, TAG, "CheckDeviceID failed");
     }
-    OICFree(jsonSVRDatabase);
+    OICFree(data);
     return ret;
 }
 
-/**
- * Perform cleanup for DOXM resources.
- *
- * @return
- * OC_STACK_OK    - no error
- * OC_STACK_ERROR - stack process error
- *
- */
 OCStackResult DeInitDoxmResource()
 {
     OCStackResult ret = OCDeleteResource(gDoxmHandle);
-    if(gDoxm  != &gDefaultDoxm)
+    if (gDoxm  != &gDefaultDoxm)
     {
         DeleteDoxmBinData(gDoxm);
     }
     gDoxm = NULL;
 
-    if(OC_STACK_OK == ret)
+    if (OC_STACK_OK == ret)
     {
         return OC_STACK_OK;
     }
@@ -887,15 +937,9 @@ OCStackResult DeInitDoxmResource()
     }
 }
 
-
-/**
- * This method returns the SRM device ID for this device.
- *
- * @retval  OC_STACK_OK for Success, otherwise some error value
- */
 OCStackResult GetDoxmDeviceID(OicUuid_t *deviceID)
 {
-    if(deviceID && gDoxm)
+    if (deviceID && gDoxm)
     {
        *deviceID = gDoxm->deviceID;
         return OC_STACK_OK;
@@ -903,17 +947,14 @@ OCStackResult GetDoxmDeviceID(OicUuid_t *deviceID)
     return OC_STACK_ERROR;
 }
 
-/**
- * @brief Gets the OicUuid_t value for the owner of this device.
- *
- * @return OC_STACK_OK if devOwner is a valid UUID, otherwise OC_STACK_ERROR.
- */
 OCStackResult GetDoxmDevOwnerId(OicUuid_t *devOwner)
 {
     OCStackResult retVal = OC_STACK_ERROR;
-    if(gDoxm)
+    if (gDoxm)
     {
-        if(gDoxm->owned) {
+        OIC_LOG_V(DEBUG, TAG, "gDoxm owned =  %d.", gDoxm->owned);
+        if (gDoxm->owned)
+        {
             *devOwner = gDoxm->owner; // TODO change to devOwner when available
             retVal = OC_STACK_OK;
         }
old mode 100644 (file)
new mode 100755 (executable)
index 7a72c87..781289f
@@ -38,6 +38,9 @@
 #include "aclresource.h"
 #include "srmutility.h"
 #include "ocserverrequest.h"
+#include "ocpayloadcbor.h"
+#include "ocpayload.h"
+#include "payload_logging.h"
 #include <stdlib.h>
 #ifdef WITH_ARDUINO
 #include <string.h>
 
 #define TAG  "SRM-DPAIRING"
 
+/** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
+ * The value of payload size is increased until reaching belox max cbor size. */
+static const uint8_t CBOR_SIZE = 255;
+
+/** Max cbor size payload. */
+static const uint16_t CBOR_MAX_SIZE = 4400;
+
+/** DOXM Map size - Number of mandatory items. */
+static const uint8_t DPAIR_MAP_SIZE = 3;
 
 static OicSecDpairing_t     *gDpair = NULL;
 static OCResourceHandle   gDpairHandle = NULL;
@@ -124,6 +136,7 @@ OCStackResult SavePairingPSK(OCDevAddr *endpoint,
     }
 
     uint8_t pairingPSK[OWNER_PSK_LENGTH_128] = {0};
+    OicSecKey_t pairingKey = {pairingPSK, OWNER_PSK_LENGTH_128};
 
     //Generating PairingPSK using OwnerPSK scheme
     CAResult_t pskRet = CAGenerateOwnerPSK((const CAEndpoint_t *)endpoint,
@@ -139,16 +152,10 @@ OCStackResult SavePairingPSK(OCDevAddr *endpoint,
         OIC_LOG_BUFFER(INFO, TAG, pairingPSK, OWNER_PSK_LENGTH_128);
         //Generating new credential for direct-pairing client
         size_t ownLen = 1;
-        uint32_t outLen = 0;
-
-        char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(pairingPSK)) + 1] = {};
-        B64Result b64Ret = b64Encode(pairingPSK, sizeof(pairingPSK), base64Buff, sizeof(base64Buff),
-                &outLen);
-        VERIFY_SUCCESS(TAG, B64_OK == b64Ret, ERROR);
 
         OicSecCred_t *cred = GenerateCredential(peerDevID,
                 SYMMETRIC_PAIR_WISE_KEY, NULL,
-                base64Buff, ownLen, owner);
+                &pairingKey, ownLen, owner);
         VERIFY_NON_NULL(TAG, cred, ERROR);
 
         res = AddCredential(cred);
@@ -169,163 +176,175 @@ exit:
 }
 #endif // __WITH_DTLS__
 
-/*
- * This internal method converts DPairing data into JSON format.
- * Does not error-check here, but check it in caller
- *
- * Note: Caller needs to invoke 'free' when finished done using
- * return string.
- */
-char * BinToDpairingJSON(const OicSecDpairing_t * dpair)
+OCStackResult DpairingToCBORPayload(const OicSecDpairing_t *dpair, uint8_t **payload, size_t *size)
 {
-    OIC_LOG(DEBUG, TAG, "BinToDpairingJSON() IN");
+    if (NULL == dpair || NULL == payload || NULL != *payload || NULL == size)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
 
-    if (NULL == dpair)
+    size_t cborLen = *size;
+    if (0 == cborLen)
     {
-        return NULL;
+        cborLen = CBOR_SIZE;
     }
 
-    char *jsonStr = NULL;
-    cJSON *jsonDpair = NULL;
-    char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};
-    uint32_t outLen = 0;
-    B64Result b64Ret = B64_OK;
+    *payload = NULL;
+    *size = 0;
 
-    cJSON *jsonRoot = cJSON_CreateObject();
-    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+    OCStackResult ret = OC_STACK_ERROR;
 
-    jsonDpair = cJSON_CreateObject();
-    VERIFY_NON_NULL(TAG, jsonDpair, ERROR);
-    cJSON_AddItemToObject(jsonRoot, OIC_JSON_DPAIRING_NAME, jsonDpair );
+    CborEncoder encoder = { {.ptr = NULL }, .end = 0 };
+    CborEncoder dpairMap = { {.ptr = NULL }, .end = 0 };
 
-    //SPM -- Mandatory
-    if(PRM_RANDOM_PIN >= dpair->spm) // don't need to check "PRM_NOT_ALLOWED <= dpair->spm" because of always true
-    {
-        cJSON_AddNumberToObject(jsonDpair, OIC_JSON_SPM_NAME, (int)dpair->spm);
-    }
+    int64_t cborEncoderResult = CborNoError;
+    uint8_t mapSize = DPAIR_MAP_SIZE;
+
+    uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
+    VERIFY_NON_NULL(TAG, outPayload, ERROR);
+    cbor_encoder_init(&encoder, outPayload, cborLen, 0);
+
+    cborEncoderResult |= cbor_encoder_create_map(&encoder, &dpairMap, mapSize);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Creating DPAIRING Map");
+
+    //spm -- Mandatory
+    cborEncoderResult |= cbor_encode_text_string(&dpairMap, OIC_JSON_SPM_NAME,
+        strlen(OIC_JSON_SPM_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SPM name tag");
+    cborEncoderResult |= cbor_encode_int(&dpairMap, dpair->spm);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SPM value");
+
+    //PDEVICEID -- Mandatory
+    cborEncoderResult |= cbor_encode_text_string(&dpairMap, OIC_JSON_PDEVICE_ID_NAME,
+        strlen(OIC_JSON_PDEVICE_ID_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PDeviceID tag");
+    cborEncoderResult |= cbor_encode_byte_string(&dpairMap, dpair->pdeviceID.id,
+        sizeof(dpair->pdeviceID.id));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PDeviceID value");
+
+    //ROWNER -- Mandatory
+    cborEncoderResult |= cbor_encode_text_string(&dpairMap, OIC_JSON_ROWNER_NAME,
+        strlen(OIC_JSON_ROWNER_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROWNER tag");
+    cborEncoderResult |= cbor_encode_byte_string(&dpairMap, dpair->rowner.id,
+        sizeof(dpair->rowner.id));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Rowner ID value");
 
-    //PDeviceID -- Mandatory
-    //There may not be paired devices if it did not be received pairing request
-    if ('\0' != (char)dpair->pdeviceID.id[0])
+    cborEncoderResult |= cbor_encoder_close_container(&encoder, &dpairMap);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to close dpairMap");
+
+     if (CborNoError == cborEncoderResult)
     {
-        outLen = 0;
-        b64Ret = b64Encode(dpair->pdeviceID.id, sizeof(dpair->pdeviceID.id), base64Buff,
-                    sizeof(base64Buff), &outLen);
-        VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
-        cJSON_AddStringToObject(jsonDpair, OIC_JSON_PDEVICE_ID_NAME, base64Buff);
+        *size = encoder.ptr - outPayload;
+        *payload = outPayload;
+        ret = OC_STACK_OK;
     }
 
-    //ROwner -- Mandatory
-    if ('\0' != (char)dpair->rowner.id[0])
+exit:
+    if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
     {
-        outLen = 0;
-        b64Ret = b64Encode(dpair->rowner.id, sizeof(dpair->rowner.id), base64Buff,
-                    sizeof(base64Buff), &outLen);
-        VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
-        cJSON_AddStringToObject(jsonDpair, OIC_JSON_ROWNER_NAME, base64Buff);
+       // reallocate and try again!
+       OICFree(outPayload);
+       // Since the allocated initial memory failed, double the memory.
+       cborLen += encoder.ptr - encoder.end;
+       cborEncoderResult = CborNoError;
+       ret = DpairingToCBORPayload(dpair, payload, &cborLen);
+       *size = cborLen;
     }
 
-
-    jsonStr = cJSON_PrintUnformatted(jsonRoot);
-
-exit:
-    if (jsonRoot)
+    if ((CborNoError != cborEncoderResult) || (OC_STACK_OK != ret))
     {
-        cJSON_Delete(jsonRoot);
+       OICFree(outPayload);
+       outPayload = NULL;
+       *payload = NULL;
+       *size = 0;
+       ret = OC_STACK_ERROR;
     }
-    return jsonStr;
+
+    return ret;
 }
 
-/*
- * This internal method converts JSON Dpairing into binary Dpairing.
- * Does not error-check here, but check it in caller
- */
-OicSecDpairing_t* JSONToDpairingBin(const char * jsonStr)
+OCStackResult CBORPayloadToDpair(const uint8_t *cborPayload, size_t size,
+                                OicSecDpairing_t **secDpair)
 {
-    OIC_LOG(DEBUG, TAG, "JSONToDpairingBin() IN");
+    if (NULL == cborPayload || NULL == secDpair || NULL != *secDpair || 0 == size)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
 
     OCStackResult ret = OC_STACK_ERROR;
-    OicSecDpairing_t *dpair =  NULL;
-    cJSON *jsonRoot = NULL;
-    cJSON *jsonDpair = NULL;
-    cJSON *jsonObj = NULL;
-
-    unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
-    uint32_t outLen = 0;
-    B64Result b64Ret = B64_OK;
+    *secDpair = NULL;
 
+    CborValue dpairCbor = { .parser = NULL };
+    CborParser parser = { .end = NULL };
+    CborError cborFindResult = CborNoError;
+    int cborLen = size;
 
-    VERIFY_NON_NULL(TAG, jsonStr, ERROR);
+    cbor_parser_init(cborPayload, cborLen, 0, &parser, &dpairCbor);
+    CborValue dpairMap = { .parser = NULL };
+    OicSecDpairing_t *dpair = NULL;
+    cborFindResult = cbor_value_enter_container(&dpairCbor, &dpairMap);
+    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering DPairing Map");
 
-    jsonRoot = cJSON_Parse(jsonStr);
-    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
-
-    jsonDpair = cJSON_GetObjectItem(jsonRoot, OIC_JSON_DPAIRING_NAME);
-    VERIFY_NON_NULL(TAG, jsonDpair, ERROR);
-
-    dpair = (OicSecDpairing_t*)OICCalloc(1, sizeof(OicSecDpairing_t));
+    dpair = (OicSecDpairing_t *)OICCalloc(1, sizeof(*dpair));
     VERIFY_NON_NULL(TAG, dpair, ERROR);
 
-    //SPM -- Mandatory
-    jsonObj = cJSON_GetObjectItem(jsonDpair, OIC_JSON_SPM_NAME);
-    if (jsonObj && cJSON_Number == jsonObj->type)
+    while (cbor_value_is_valid(&dpairMap))
     {
-        dpair->spm = (OicSecPrm_t)jsonObj->valueint;
-        OIC_LOG_V (DEBUG, TAG, "jsonObj->valueint = %d", jsonObj->valueint);
-        OIC_LOG_V (DEBUG, TAG, "dpair->spm = %d", dpair->spm);
+        char *name = NULL;
+        size_t len = 0;
+        cborFindResult = cbor_value_dup_text_string(&dpairMap, &name, &len, NULL);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding tag name");
+        cborFindResult = cbor_value_advance(&dpairMap);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing a value in DPair map");
 
-        // don't need to check "PRM_NOT_ALLOWED <= dpair->spm" because of always true
-        VERIFY_SUCCESS(TAG, (PRM_RANDOM_PIN >= dpair->spm), ERROR);
-    }
-    else
-    {
-        dpair->spm = PRM_NOT_ALLOWED;
-    }
+        CborType type = cbor_value_get_type(&dpairMap);
 
-    //PDeviceId -- Mandatory
-    outLen = 0;
-    jsonObj = cJSON_GetObjectItem(jsonDpair, OIC_JSON_PDEVICE_ID_NAME);
-    if (jsonObj && cJSON_String == jsonObj->type)
-    {
-        b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff,
-                sizeof(base64Buff), &outLen);
-        VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(dpair->pdeviceID.id)), ERROR);
-        memcpy(dpair->pdeviceID.id, base64Buff, outLen);
-    }
-    else
-    {
-        memset(&dpair->pdeviceID, 0, sizeof(OicUuid_t));
-    }
+        if (0 == strcmp(OIC_JSON_SPM_NAME, name))
+        {
+            cborFindResult = cbor_value_get_int(&dpairMap, (int *) &dpair->spm);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SPM Value");
+        }
 
-    // ROwner -- Mandatory
-    outLen = 0;
-    jsonObj = cJSON_GetObjectItem(jsonDpair, OIC_JSON_ROWNER_NAME);
-    if (jsonObj && cJSON_String == jsonObj->type)
-    {
-        b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff,
-                sizeof(base64Buff), &outLen);
-        VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(dpair->rowner.id)), ERROR);
-        memcpy(dpair->rowner.id, base64Buff, outLen);
-    }
-    else
-    {
-        memset(&dpair->rowner, 0, sizeof(OicUuid_t));
+        if (0 == strcmp(OIC_JSON_PDEVICE_ID_NAME, name))
+        {
+            uint8_t *id = NULL;
+            cborFindResult = cbor_value_dup_byte_string(&dpairMap, &id, &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding PDeviceID value");
+            memcpy(dpair->pdeviceID.id, id, len);
+            OICFree(id);
+        }
+
+        if (0 == strcmp(OIC_JSON_ROWNER_NAME, name))
+        {
+            uint8_t *id = NULL;
+            cborFindResult = cbor_value_dup_byte_string(&dpairMap, &id, &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding RownerID value");
+            memcpy(dpair->rowner.id, id, len);
+            OICFree(id);
+        }
+
+        if (CborMapType != type && cbor_value_is_valid(&dpairMap))
+        {
+            cborFindResult = cbor_value_advance(&dpairMap);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing the Dpair Map");
+        }
+        OICFree(name);
     }
 
+    *secDpair = dpair;
     ret = OC_STACK_OK;
 
 exit:
-    cJSON_Delete(jsonRoot);
-    if (OC_STACK_OK != ret)
+    if (CborNoError != cborFindResult)
     {
+        OIC_LOG (ERROR, TAG, "CBORPayloadToDoxm failed");
         DeleteDpairingBinData(dpair);
         dpair = NULL;
+        ret = OC_STACK_ERROR;
     }
-
-    OIC_LOG(DEBUG, TAG, "JSONToDpairingBin() OUT");
-    return dpair;
+    return ret;
 }
-
 /**
  * Function to handle the handshake result in Direct-Pairing.
  * This function will be invoked after DTLS handshake
@@ -368,12 +387,17 @@ static OCEntityHandlerResult HandleDpairingPostRequest (const OCEntityHandlerReq
     OIC_LOG (DEBUG, TAG, "Dpairing EntityHandle  processing POST request");
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
     OicSecDpairing_t* newDpair = NULL;
+    OCStackResult res = OC_STACK_OK;
 
     const OicSecPconf_t *pconf = GetPconfResourceData();
     if (true == pconf->edp)
     {
-        // Convert JSON DPAIRING data into binary. This will also validate the DPAIRING data received.
-        newDpair = JSONToDpairingBin(((OCSecurityPayload*)ehRequest->payload)->securityData);
+        uint8_t *payload = ((OCSecurityPayload*)ehRequest->payload)->securityData1;
+        size_t size = ((OCSecurityPayload*)ehRequest->payload)->payloadSize;
+        if (payload)
+        {
+            res = CBORPayloadToDpair(payload, size, &newDpair);
+        }
     }
     else
     {
@@ -381,7 +405,7 @@ static OCEntityHandlerResult HandleDpairingPostRequest (const OCEntityHandlerReq
         ehRet = OC_EH_ERROR;
     }
 
-    if (newDpair && false == IsPairedDevice(&newDpair->pdeviceID))
+    if (OC_STACK_OK == res && newDpair && false == IsPairedDevice(&newDpair->pdeviceID))
     {
         // Check if valid Post request
         bool prmMached = false;
@@ -393,7 +417,8 @@ static OCEntityHandlerResult HandleDpairingPostRequest (const OCEntityHandlerReq
                 break;
             }
         }
-        OIC_LOG_V(DEBUG, TAG, "Parsed spm is %s", prmMached ? "valid" : "invalid, send error response");
+        OIC_LOG_V(DEBUG, TAG, "Parsed spm is %s", prmMached ? "valid" :
+                "invalid, send error response");
 
         // Update local Dpairing with new Dpairing & prepare dtls session
         if (prmMached && '\0' != (char)newDpair->pdeviceID.id[0])
@@ -431,7 +456,8 @@ static OCEntityHandlerResult HandleDpairingPostRequest (const OCEntityHandlerReq
 
             if(CA_STATUS_OK != CARegisterDTLSHandshakeCallback(DPairingDTLSHandshakeCB))
             {
-                OIC_LOG(WARNING, TAG, "DirectPairingHandler : Failed to register DTLS handshake callback.");
+                OIC_LOG(WARNING, TAG, "DirectPairingHandler : Failed to register"
+                        " DTLS handshake callback.");
                 goto exit;
             }
 #endif // __WITH_DTLS__
@@ -459,9 +485,9 @@ exit:
     }
 
     // Send payload to request originator
-    if(OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, NULL))
+    if(OC_STACK_OK != SendSRMCBORResponse(ehRequest, ehRet, NULL, 0))
     {
-        OIC_LOG (ERROR, TAG, "SendSRMResponse failed in HandleDpairingPostRequest");
+        OIC_LOG (ERROR, TAG, "SendSRMCBORResponse failed in HandleDpairingPostRequest");
     }
 
     DeleteDpairingBinData(newDpair);
@@ -475,12 +501,18 @@ static OCEntityHandlerResult HandleDpairingPutRequest (const OCEntityHandlerRequ
 
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
     OicSecDpairing_t* newDpair = NULL;
+    OCStackResult res = OC_STACK_OK;
 
     const OicSecPconf_t *pconf = GetPconfResourceData();
     if (true == pconf->edp)
     {
-        // Convert JSON DPAIRING data into binary. This will also validate the DPAIRING data received.
-        newDpair = JSONToDpairingBin(((OCSecurityPayload*)ehRequest->payload)->securityData);
+        uint8_t *payload = ((OCSecurityPayload*)ehRequest->payload)->securityData1;
+        size_t size = ((OCSecurityPayload*)ehRequest->payload)->payloadSize;
+        if (payload)
+        {
+            res = CBORPayloadToDpair(payload, size, &newDpair);
+        }
+
     }
     else
     {
@@ -488,7 +520,8 @@ static OCEntityHandlerResult HandleDpairingPutRequest (const OCEntityHandlerRequ
         ehRet = OC_EH_ERROR;
     }
 
-    if (gDpair && newDpair)
+
+    if ((OC_STACK_OK == res) && gDpair && newDpair)
     {
         OIC_LOG(DEBUG, TAG, "Received direct-pairing finalization request");
 
@@ -503,9 +536,10 @@ static OCEntityHandlerResult HandleDpairingPutRequest (const OCEntityHandlerRequ
         VERIFY_SUCCESS(TAG, (request->devAddr.flags | OC_FLAG_SECURE), ERROR);
 
         //Generate new credential
-        OIC_LOG_V(INFO, TAG, "SavePairingPSK for %s(%d)", request->devAddr.addr, request->devAddr.port);
+        OIC_LOG_V(INFO, TAG, "SavePairingPSK for %s(%d)", request->devAddr.addr,
+                request->devAddr.port);
         OCStackResult res = SavePairingPSK(&request->devAddr, &newDpair->pdeviceID,
-                                                                  (OicUuid_t *)&pconf->rowner, true);
+                (OicUuid_t *)&pconf->rowner, true);
         VERIFY_SUCCESS(TAG, OC_STACK_OK == res, ERROR);
 #endif //__WITH_DTLS__
 
@@ -525,11 +559,12 @@ static OCEntityHandlerResult HandleDpairingPutRequest (const OCEntityHandlerRequ
             acl.recurrences = pdAcl->recurrences;
             acl.prdRecrLen = pdAcl->prdRecrLen;
 
-            char* aclJson = BinToAclJSON(&acl);
-            if (aclJson)
+            size_t size = 0;
+            uint8_t *payload = NULL;
+            if (OC_STACK_OK == AclToCBORPayload(&acl, &payload, &size))
             {
-                InstallNewACL(aclJson);
-                OICFree(aclJson);
+                InstallNewACL(payload, size);
+                OICFree(payload);
             }
         }
 
@@ -539,16 +574,17 @@ static OCEntityHandlerResult HandleDpairingPutRequest (const OCEntityHandlerRequ
         //Initialize dpairing resource
         gDpair = NULL;
 
-        OIC_LOG (DEBUG, TAG, "/oic/sec/dpairing resource updated, direct-pairing finalization success");
+        OIC_LOG (DEBUG, TAG, "/oic/sec/dpairing resource updated,"
+                "direct-pairing finalization success");
         ehRet = OC_EH_OK;
     }
 
 exit:
 
     //Send payload to request originator
-    if(OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, NULL))
+    if(OC_STACK_OK != SendSRMCBORResponse(ehRequest, ehRet, NULL, 0))
     {
-        OIC_LOG (ERROR, TAG, "SendSRMResponse failed in HandleDpairingPutRequest");
+        OIC_LOG (ERROR, TAG, "SendSRMCBORResponse failed in HandleDpairingPutRequest");
     }
 
     DeleteDpairingBinData(newDpair);
@@ -593,7 +629,7 @@ OCEntityHandlerResult DpairingEntityHandler (OCEntityHandlerFlag flag,
 
             default:
                 ehRet = OC_EH_ERROR;
-                SendSRMResponse(ehRequest, ehRet, NULL);
+                SendSRMCBORResponse(ehRequest, ehRet, NULL, 0);
         }
     }
 
@@ -663,6 +699,3 @@ OCStackResult DeInitDpairingResource()
         return OC_STACK_ERROR;
     }
 }
-
-
-
index 5652236..f1354aa 100644 (file)
@@ -1,24 +1,24 @@
-/*****************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * *****************************************************************/
-
- #include <memory.h>
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#include <memory.h>
 
 #include "ocstack.h"
 #include "ocrandom.h"
@@ -204,4 +204,3 @@ int32_t GetDtlsPskForRandomPinOxm( CADtlsPskCredType_t type,
     return ret;
 }
 #endif //__WITH_DTLS__
-
index ca614ec..02c984a 100644 (file)
@@ -1,22 +1,23 @@
-/* *****************************************************************
- *
- * Copyright 2015 Samsung Electronics All Rights Reserved.
- *
- *
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- *     http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- * *****************************************************************/
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
 #include <string.h>
 #include <math.h>
 #include "pbkdf2.h"
 
 #define TAG "PBDKF2"
 #define XOR_BUF(in, out, bufSize)\
-do{\
+do \
+{\
     size_t i=0;\
-    for(i=0; i< (bufSize); i++)\
+    for (i=0; i< (bufSize); i++)\
     {\
         (out)[i] = (in)[i] ^ (out)[i];\
     }\
-}while(0)\
-
+} while(0)\
 
 static int isLittle()
 {
index f1764c1..9ad996d 100644 (file)
@@ -26,6 +26,8 @@
 #include "oic_string.h"\r
 #include "cJSON.h"\r
 #include "base64.h"\r
+#include "ocpayload.h"\r
+#include "payload_logging.h"\r
 #include "resourcemanager.h"\r
 #include "pconfresource.h"\r
 #include "psinterface.h"\r
@@ -35,6 +37,8 @@
 #include "srmutility.h"\r
 #include "ocserverrequest.h"\r
 #include <stdlib.h>\r
+#include "psinterface.h"\r
+#include "security_internals.h"\r
 #ifdef WITH_ARDUINO\r
 #include <string.h>\r
 #else\r
@@ -43,6 +47,9 @@
 \r
 #define TAG  "SRM-PCONF"\r
 \r
+static const uint64_t CBOR_SIZE = 255;\r
+static const uint64_t CBOR_MAX_SIZE = 4400;\r
+static const uint8_t  PCONF_MAP_SIZE = 4;\r
 \r
 static OicSecPconf_t          *gPconf = NULL;\r
 static OCResourceHandle   gPconfHandle = NULL;\r
@@ -129,462 +136,566 @@ void DeletePconfBinData(OicSecPconf_t* pconf)
     }\r
 }\r
 \r
-/*\r
- * This internal method converts PCONF data into JSON format.\r
- *\r
- * Note: Caller needs to invoke 'free' when finished done using\r
- * return string.\r
- */\r
-char * BinToPconfJSON(const OicSecPconf_t * pconf)\r
+static size_t OicPdAclSize(const OicSecPdAcl_t *pdAcl)\r
 {\r
-    OIC_LOG(DEBUG, TAG, "BinToPconfJSON() IN");\r
+    if (!pdAcl)\r
+    {\r
+        return 0;\r
+    }\r
 \r
-    if (NULL == pconf)\r
+    OicSecPdAcl_t *tmp = (OicSecPdAcl_t *)pdAcl;\r
+    size_t size = 0;\r
+    while (tmp)\r
     {\r
-        return NULL;\r
+        size++;\r
+        tmp = tmp->next;\r
     }\r
+    return size;\r
+}\r
 \r
-    char *jsonStr = NULL;\r
-    cJSON *jsonPconf = NULL;\r
-    char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};\r
-    uint32_t outLen = 0;\r
-    B64Result b64Ret = B64_OK;\r
+OCStackResult PconfToCBORPayload(const OicSecPconf_t *pconf,uint8_t **payload,size_t *size)\r
+{\r
+    if (NULL == pconf || NULL == payload || NULL != *payload || NULL == size)\r
+    {\r
+        return OC_STACK_INVALID_PARAM;\r
+    }\r
+    size_t cborLen = *size;\r
+    if(0 == cborLen)\r
+    {\r
+        cborLen = CBOR_SIZE;\r
+    }\r
+    *payload = NULL;\r
 \r
-    cJSON *jsonRoot = cJSON_CreateObject();\r
-    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);\r
+    OCStackResult ret = OC_STACK_ERROR;\r
+    CborEncoder encoder = { {.ptr = NULL}, .end = 0};\r
+    CborEncoder pconfMap = { {.ptr = NULL}, .end = 0};\r
 \r
-    jsonPconf = cJSON_CreateObject();\r
-    VERIFY_NON_NULL(TAG, jsonPconf, ERROR);\r
-    cJSON_AddItemToObject(jsonRoot, OIC_JSON_PCONF_NAME, jsonPconf );\r
+    int64_t cborEncoderResult = CborNoError;\r
+    uint8_t mapSize = PCONF_MAP_SIZE;\r
 \r
+    if (pconf->prmLen > 0)\r
+    {\r
+        mapSize++;\r
+    }\r
+    if (pconf->pdacls)\r
+    {\r
+        mapSize++;\r
+    }\r
+    if (pconf->pddevs)\r
+    {\r
+        mapSize++;\r
+    }\r
+\r
+    uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);\r
+    VERIFY_NON_NULL(TAG, outPayload, ERROR);\r
 \r
-    //EDP -- Mandatory\r
-    cJSON_AddBoolToObject(jsonPconf, OIC_JSON_EDP_NAME, pconf->edp);\r
+    cbor_encoder_init(&encoder, outPayload, cborLen, 0);\r
+    cborEncoderResult = cbor_encoder_create_map(&encoder, &pconfMap, mapSize);\r
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Creating Pconf Map.");\r
 \r
-    //PRM type -- Mandatory\r
-    if(0< pconf->prmLen)\r
+    //edp  -- Mandatory\r
+    cborEncoderResult |= cbor_encode_text_string(&pconfMap, OIC_JSON_EDP_NAME,\r
+            strlen(OIC_JSON_EDP_NAME));\r
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Encode EDP String.");\r
+    cborEncoderResult |= cbor_encode_boolean(&pconfMap, pconf->edp);\r
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Convert PconfEDP value");\r
+\r
+    //PRM type -- Not Mandatory\r
+    if(pconf->prmLen > 0)\r
     {\r
-        cJSON *jsonPrmArray = cJSON_CreateArray();\r
-        VERIFY_NON_NULL(TAG, jsonPrmArray, ERROR);\r
-        cJSON_AddItemToObject (jsonPconf, OIC_JSON_PRM_NAME, jsonPrmArray);\r
-        OIC_LOG_V (DEBUG, TAG, "pconf->prmLen = %d", (int)pconf->prmLen);\r
+        cborEncoderResult |= cbor_encode_text_string(&pconfMap, OIC_JSON_PRM_NAME,\r
+                strlen(OIC_JSON_PRM_NAME));\r
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Convert Pconf PRM NAME");\r
+        CborEncoder prm = { {.ptr = NULL }, .end = 0 };\r
+        cborEncoderResult |= cbor_encoder_create_array(&pconfMap, &prm, pconf->prmLen);\r
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Convert Pconf PRM value");\r
+\r
         for (size_t i = 0; i < pconf->prmLen; i++)\r
         {\r
-            OIC_LOG_V (DEBUG, TAG, "pconf->prm[%d] = %d", (int)i, pconf->prm[i]);\r
-            cJSON_AddItemToArray (jsonPrmArray, cJSON_CreateNumber(pconf->prm[i]));\r
+            cborEncoderResult |= cbor_encode_int(&prm, pconf->prm[i]);\r
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Convert Pconf PRM Array");\r
         }\r
+        cborEncoderResult |= cbor_encoder_close_container(&pconfMap, &prm);\r
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to close encode array");\r
     }\r
 \r
     //PIN -- Mandatory\r
-    if(DP_PIN_LENGTH == strlen((const char*)pconf->pin.val))\r
-    {\r
-        cJSON_AddStringToObject(jsonPconf, OIC_JSON_PIN_NAME, (char*)pconf->pin.val);\r
-    }\r
+    cborEncoderResult |= cbor_encode_text_string(&pconfMap, OIC_JSON_PIN_NAME,\r
+            strlen(OIC_JSON_PIN_NAME));\r
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to create OIC_JSON_PIN_NAME");\r
+    cborEncoderResult |= cbor_encode_byte_string(&pconfMap, pconf->pin.val, sizeof(pconf->pin.val));\r
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to convert pin value");\r
 \r
     //PDACL -- Mandatory\r
-    if(pconf->pdacls)\r
+    if (pconf->pdacls)\r
     {\r
-        cJSON *jsonAclArray = NULL;\r
-        OicSecPdAcl_t *pdacl = NULL;\r
-        cJSON_AddItemToObject (jsonPconf, OIC_JSON_PDACL_NAME,\r
-                jsonAclArray = cJSON_CreateArray());\r
-        VERIFY_NON_NULL(TAG, jsonAclArray, ERROR);\r
+        cborEncoderResult |= cbor_encode_text_string(&pconfMap, OIC_JSON_PDACL_NAME,\r
+                strlen(OIC_JSON_PDACL_NAME));\r
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to create OIC_JSON_PIN_NAME");\r
+        OicSecPdAcl_t *pdacl = pconf->pdacls;\r
+        CborEncoder pdAclArray;\r
+        cborEncoderResult |= cbor_encoder_create_array(&pconfMap, &pdAclArray,\r
+                OicPdAclSize(pconf->pdacls));\r
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to creeate _pdacl array");\r
 \r
-        pdacl = pconf->pdacls;\r
         while(pdacl)\r
         {\r
-            cJSON *jsonAcl = cJSON_CreateObject();\r
+            CborEncoder pdAclMap = { {.ptr = NULL }, .end = 0, .added = 0, .flags = 0 };\r
+            // PDACL Map size - Number of mandatory items\r
+            uint8_t aclMapSize = 2;\r
+\r
+            if (pdacl->prdRecrLen)\r
+            {\r
+                ++aclMapSize;\r
+            }\r
+            if (pdacl->recurrences)\r
+            {\r
+                ++aclMapSize;\r
+            }\r
+\r
+            cborEncoderResult |= cbor_encoder_create_map(&pdAclArray, &pdAclMap, aclMapSize);\r
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult,  "Failed to creeate _pdacl array");\r
 \r
             // Resources -- Mandatory\r
-            cJSON *jsonRsrcArray = NULL;\r
-            cJSON_AddItemToObject (jsonAcl, OIC_JSON_RESOURCES_NAME,\r
-                    jsonRsrcArray = cJSON_CreateArray());\r
-            VERIFY_NON_NULL(TAG, jsonRsrcArray, ERROR);\r
+            cborEncoderResult |= cbor_encode_text_string(&pdAclMap, OIC_JSON_RESOURCES_NAME,\r
+                    strlen(OIC_JSON_RESOURCES_NAME));\r
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult,  "Failed to encode resource result");\r
+\r
+            CborEncoder resources = { {.ptr = NULL }, .end = 0, .added = 0, .flags = 0 };\r
+            cborEncoderResult |= cbor_encoder_create_array(&pdAclMap, &resources,\r
+                    pdacl->resourcesLen);\r
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult,  "Failed to create resource array");\r
+\r
             for (size_t i = 0; i < pdacl->resourcesLen; i++)\r
             {\r
-                cJSON_AddItemToArray (jsonRsrcArray,\r
-                        cJSON_CreateString(pdacl->resources[i]));\r
+                cborEncoderResult |= cbor_encode_text_string(&resources, pdacl->resources[i],\r
+                        strlen(pdacl->resources[i]));\r
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult,  "Failed to convert resource array");\r
             }\r
+            cborEncoderResult = cbor_encoder_close_container(&pdAclMap, &resources);\r
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult,  "Failed to close resource array");\r
 \r
             // Permissions -- Mandatory\r
-            cJSON_AddNumberToObject (jsonAcl, OIC_JSON_PERMISSION_NAME, pdacl->permission);\r
-\r
-            //Period & Recurrence -- Not Mandatory\r
-            if(0 != pdacl->prdRecrLen && pdacl->periods)\r
+            cborEncoderResult |= cbor_encode_text_string(&pdAclMap, OIC_JSON_PERMISSION_NAME,\r
+                    strlen(OIC_JSON_PERMISSION_NAME));\r
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult,  "Failed to create permition string");\r
+            cborEncoderResult |= cbor_encode_int(&pdAclMap, pdacl->permission);\r
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to encode permition calue");\r
+\r
+            // Period -- Not Mandatory\r
+            if (pdacl->periods)\r
             {\r
-                cJSON *jsonPeriodArray = NULL;\r
-                cJSON_AddItemToObject (jsonAcl, OIC_JSON_PERIODS_NAME,\r
-                        jsonPeriodArray = cJSON_CreateArray());\r
-                VERIFY_NON_NULL(TAG, jsonPeriodArray, ERROR);\r
+                CborEncoder period = { {.ptr = NULL }, .end = 0, .added = 0, .flags = 0 };\r
+                cborEncoderResult |= cbor_encode_text_string(&pdAclMap, OIC_JSON_PERIODS_NAME,\r
+                        strlen(OIC_JSON_PERIODS_NAME));\r
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to encode period value");\r
+                cborEncoderResult |= cbor_encoder_create_array(&pdAclMap, &period,\r
+                        pdacl->prdRecrLen);\r
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to create array");\r
+\r
                 for (size_t i = 0; i < pdacl->prdRecrLen; i++)\r
                 {\r
-                    cJSON_AddItemToArray (jsonPeriodArray,\r
-                            cJSON_CreateString(pdacl->periods[i]));\r
+                    cborEncoderResult |= cbor_encode_text_string(&period, pdacl->periods[i],\r
+                            strlen(pdacl->periods[i]));\r
+                    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to encode period");\r
                 }\r
+                cborEncoderResult = cbor_encoder_close_container(&pdAclMap, &period);\r
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult,"Failed to close period array");\r
             }\r
 \r
-            //Recurrence -- Not Mandatory\r
+            // Period -- Not Mandatory\r
             if(0 != pdacl->prdRecrLen && pdacl->recurrences)\r
             {\r
-                cJSON *jsonRecurArray  = NULL;\r
-                cJSON_AddItemToObject (jsonAcl, OIC_JSON_RECURRENCES_NAME,\r
-                        jsonRecurArray = cJSON_CreateArray());\r
-                VERIFY_NON_NULL(TAG, jsonRecurArray, ERROR);\r
+                CborEncoder recurrences = { {.ptr = NULL }, .end = 0, .added = 0, .flags = 0 };\r
+                cborEncoderResult |= cbor_encode_text_string(&pdAclMap, OIC_JSON_RECURRENCES_NAME,\r
+                        strlen(OIC_JSON_RECURRENCES_NAME));\r
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult,"Failed to encode recurrences");\r
+                cborEncoderResult |= cbor_encoder_create_array(&pdAclMap, &recurrences,\r
+                        pdacl->prdRecrLen);\r
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to create rec array");\r
+\r
                 for (size_t i = 0; i < pdacl->prdRecrLen; i++)\r
                 {\r
-                    cJSON_AddItemToArray (jsonRecurArray,\r
-                            cJSON_CreateString(pdacl->recurrences[i]));\r
+                    cborEncoderResult |= cbor_encode_text_string(&recurrences,\r
+                            pdacl->recurrences[i], strlen(pdacl->recurrences[i]));\r
+                    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to encode recurrences");\r
                 }\r
+                cborEncoderResult |= cbor_encoder_close_container(&pdAclMap, &recurrences);\r
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to close rec array");\r
             }\r
+            cborEncoderResult |= cbor_encoder_close_container(&pdAclArray, &pdAclMap);\r
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to close acl map");\r
 \r
-            // Attach current acl node to Acl Array\r
-            cJSON_AddItemToArray(jsonAclArray, jsonAcl);\r
             pdacl = pdacl->next;\r
         }\r
+        //clsoe the array\r
+        cborEncoderResult |= cbor_encoder_close_container(&pconfMap, &pdAclArray);\r
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to close acl array");\r
     }\r
 \r
     //PDDev -- Mandatory\r
     //There may not be paired devices if it did not pairing before\r
     if (pconf->pddevs && 0 < pconf->pddevLen)\r
     {\r
-        cJSON *jsonPdDevArray = cJSON_CreateArray();\r
-        VERIFY_NON_NULL(TAG, jsonPdDevArray, ERROR);\r
-        cJSON_AddItemToObject (jsonPconf, OIC_JSON_PDDEV_LIST_NAME, jsonPdDevArray );\r
+        cborEncoderResult |= cbor_encode_text_string(&pconfMap, OIC_JSON_PDDEV_LIST_NAME,\r
+                strlen(OIC_JSON_PDDEV_LIST_NAME));\r
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to encode pddev");\r
+        CborEncoder pddev = { {.ptr = NULL }, .end = 0, .added = 0, .flags = 0 };\r
+        cborEncoderResult |= cbor_encoder_create_array(&pconfMap, &pddev,  pconf->pddevLen);\r
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to create array");\r
+\r
         for (size_t i = 0; i < pconf->pddevLen; i++)\r
         {\r
-            outLen = 0;\r
-            b64Ret = b64Encode(pconf->pddevs[i].id, sizeof(pconf->pddevs[i].id), base64Buff,\r
-                        sizeof(base64Buff), &outLen);\r
-            VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);\r
-            cJSON_AddItemToArray (jsonPdDevArray, cJSON_CreateString(base64Buff));\r
+            cborEncoderResult |= cbor_encode_byte_string(&pddev, (uint8_t *)pconf->pddevs[i].id,\r
+                    sizeof(pconf->pddevs[i].id));\r
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to encode pddev id");\r
         }\r
+        cborEncoderResult |= cbor_encoder_close_container(&pconfMap, &pddev);\r
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to close pddev array");\r
     }\r
 \r
     //DeviceId -- Mandatory\r
     //There may not be devicd id if caller is provisoning tool\r
-    if ('\0' != (char)pconf->deviceID.id[0])\r
-    {\r
-        outLen = 0;\r
-        b64Ret = b64Encode(pconf->deviceID.id, sizeof(pconf->deviceID.id), base64Buff,\r
-                    sizeof(base64Buff), &outLen);\r
-        VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);\r
-        cJSON_AddStringToObject(jsonPconf, OIC_JSON_DEVICE_ID_NAME, base64Buff);\r
-    }\r
+    cborEncoderResult |= cbor_encode_text_string(&pconfMap, OIC_JSON_DEVICE_ID_NAME,\r
+            strlen(OIC_JSON_DEVICE_ID_NAME));\r
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to encode device id");\r
+    cborEncoderResult |= cbor_encode_byte_string(&pconfMap, (uint8_t *)pconf->deviceID.id,\r
+            sizeof(pconf->deviceID.id));\r
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to encode deviceID value");\r
 \r
     //ROwner -- Mandatory\r
-    VERIFY_SUCCESS(TAG, '\0' != (char)pconf->rowner.id[0], ERROR);\r
-    outLen = 0;\r
-    b64Ret = b64Encode(pconf->rowner.id, sizeof(pconf->rowner.id), base64Buff,\r
-                    sizeof(base64Buff), &outLen);\r
-    VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);\r
-    cJSON_AddStringToObject(jsonPconf, OIC_JSON_ROWNER_NAME, base64Buff);\r
-\r
-\r
-    jsonStr = cJSON_PrintUnformatted(jsonRoot);\r
-\r
+    cborEncoderResult |= cbor_encode_text_string(&pconfMap, OIC_JSON_ROWNER_NAME,\r
+            strlen(OIC_JSON_ROWNER_NAME));\r
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to encode rowner string");\r
+    cborEncoderResult |= cbor_encode_byte_string(&pconfMap, (uint8_t *)pconf->rowner.id,\r
+            sizeof(pconf->rowner.id));\r
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to encode rwoner value");\r
+\r
+    cborEncoderResult |= cbor_encoder_close_container(&encoder, &pconfMap);\r
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to close pconfMap");\r
+\r
+    *size = encoder.ptr - outPayload;\r
+    *payload = outPayload;\r
+    ret = OC_STACK_OK;\r
 exit:\r
-    if (jsonRoot)\r
+    if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))\r
     {\r
-        cJSON_Delete(jsonRoot);\r
+        // reallocate and try again!\r
+        OICFree(outPayload);\r
+        // Since the allocated initial memory failed, double the memory.\r
+        cborLen += encoder.ptr - encoder.end;\r
+        cborEncoderResult = CborNoError;\r
+        ret = PconfToCBORPayload(pconf, payload, &cborLen);\r
+        *size = cborLen;\r
     }\r
-    return jsonStr;\r
+    if ((CborNoError != cborEncoderResult) || (OC_STACK_OK != ret))\r
+    {\r
+        OICFree(outPayload);\r
+        outPayload = NULL;\r
+        *payload = NULL;\r
+        *size = 0;\r
+        ret = OC_STACK_ERROR;\r
+    }\r
+    return ret;\r
 }\r
 \r
-/*\r
- * This internal method converts JSON PCONF into binary PCONF.\r
- */\r
-OicSecPconf_t * JSONToPconfBin(const char * jsonStr)\r
+OCStackResult CBORPayloadToPconf(const uint8_t *cborPayload, size_t size, OicSecPconf_t **secPconf)\r
 {\r
-    OIC_LOG(DEBUG, TAG, "JSONToPconfBin() IN");\r
-\r
+    if (NULL == cborPayload || NULL == secPconf || NULL != *secPconf || 0 == size)\r
+    {\r
+        return OC_STACK_INVALID_PARAM;\r
+    }\r
     OCStackResult ret = OC_STACK_ERROR;\r
-    OicSecPconf_t * pconf =  NULL;\r
-    cJSON *jsonRoot = NULL;\r
-    cJSON *jsonPconf = NULL;\r
-    cJSON *jsonObj = NULL;\r
-    size_t jsonObjLen = 0;\r
-\r
-    unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};\r
-    uint32_t outLen = 0;\r
-    B64Result b64Ret = B64_OK;\r
-\r
-\r
-    VERIFY_NON_NULL(TAG, jsonStr, ERROR);\r
-\r
-    jsonRoot = cJSON_Parse(jsonStr);\r
-    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);\r
-\r
-    jsonPconf = cJSON_GetObjectItem(jsonRoot, OIC_JSON_PCONF_NAME);\r
-    VERIFY_NON_NULL(TAG, jsonPconf, ERROR);\r
-\r
-    pconf = (OicSecPconf_t*)OICCalloc(1, sizeof(OicSecPconf_t));\r
+    *secPconf = NULL;\r
+    CborValue pconfCbor = { .parser = NULL };\r
+    CborParser parser = { .end = NULL };\r
+    CborError cborFindResult = CborNoError;\r
+    int cborLen = size;\r
+\r
+    cbor_parser_init(cborPayload, cborLen, 0, &parser, &pconfCbor);\r
+    CborValue pconfMap = { .parser = NULL } ;\r
+    OicSecPconf_t *pconf = NULL;\r
+    cborFindResult = cbor_value_enter_container(&pconfCbor, &pconfMap);\r
+    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to enter map");\r
+    pconf = (OicSecPconf_t *)OICCalloc(1, sizeof(*pconf));\r
     VERIFY_NON_NULL(TAG, pconf, ERROR);\r
-\r
-    //EDP -- Mandatory\r
-    jsonObj = cJSON_GetObjectItem(jsonPconf, OIC_JSON_EDP_NAME);\r
-    VERIFY_NON_NULL(TAG, jsonObj, ERROR);\r
-    VERIFY_SUCCESS(TAG, (cJSON_True == jsonObj->type || cJSON_False == jsonObj->type) , ERROR);\r
-    pconf->edp = jsonObj->valueint;\r
-\r
-    //PRM type -- Mandatory\r
-    jsonObj = cJSON_GetObjectItem(jsonPconf, OIC_JSON_PRM_NAME);\r
-    if (jsonObj && cJSON_Array == jsonObj->type)\r
+    while (cbor_value_is_valid(&pconfMap))\r
     {\r
-        int arrLen = cJSON_GetArraySize(jsonObj);\r
-        if(0 < arrLen)\r
+        char *name = NULL;\r
+        size_t len = 0;\r
+        CborType type = cbor_value_get_type(&pconfMap);\r
+        if (type == CborTextStringType)\r
         {\r
-            pconf->prmLen = (size_t)arrLen;\r
-            pconf->prm = (OicSecPrm_t *)OICCalloc(pconf->prmLen, sizeof(OicSecPrm_t));\r
-            VERIFY_NON_NULL(TAG, pconf->prm, ERROR);\r
-\r
-            for (size_t i  = 0; i < pconf->prmLen ; i++)\r
-            {\r
-                cJSON *jsonPrm = cJSON_GetArrayItem(jsonObj, i);\r
-                VERIFY_NON_NULL(TAG, jsonPrm, ERROR);\r
-                pconf->prm[i] = (OicSecPrm_t)jsonPrm->valueint;\r
-                OIC_LOG_V (DEBUG, TAG, "jsonPrm->valueint = %d", jsonPrm->valueint);\r
-                OIC_LOG_V (DEBUG, TAG, "pconf->prm[%d] = %d", (int)i, pconf->prm[i]);\r
-            }\r
+            cborFindResult = cbor_value_dup_text_string(&pconfMap, &name, &len, NULL);\r
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get value");\r
+            cborFindResult = cbor_value_advance(&pconfMap);\r
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to advance value");\r
         }\r
-    }\r
-\r
-    //PIN -- Mandatory\r
-    jsonObj = cJSON_GetObjectItem(jsonPconf, OIC_JSON_PIN_NAME);\r
-    if (jsonObj)\r
-    {\r
-        VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);\r
-        VERIFY_SUCCESS(TAG, DP_PIN_LENGTH == strlen(jsonObj->valuestring), ERROR);\r
-        OICStrcpy((char*)pconf->pin.val, DP_PIN_LENGTH + 1, (char*)jsonObj->valuestring);\r
-    }\r
-    else\r
-    {\r
-        memset(pconf->pin.val, 0, DP_PIN_LENGTH+1);\r
-    }\r
-\r
-    //PDACL -- Mandatory\r
-    jsonObj = cJSON_GetObjectItem(jsonPconf, OIC_JSON_PDACL_NAME);\r
-    if (jsonObj)\r
-    {\r
-        VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);\r
-\r
-        OicSecPdAcl_t * headAcl = NULL;\r
-        OicSecPdAcl_t * prevAcl = NULL;\r
-        int numPdAcl = cJSON_GetArraySize(jsonObj);\r
-        int idx = 0;\r
 \r
-        while(idx < numPdAcl)\r
+        if (name)\r
         {\r
-            cJSON *jsonPdAcl = cJSON_GetArrayItem(jsonObj, idx);\r
-            VERIFY_NON_NULL(TAG, jsonPdAcl, ERROR);\r
-\r
-            OicSecPdAcl_t *pdacl = (OicSecPdAcl_t*)OICCalloc(1, sizeof(OicSecPdAcl_t));\r
-            VERIFY_NON_NULL(TAG, pdacl, ERROR);\r
-\r
-            headAcl = (headAcl) ? headAcl : pdacl;\r
-            if (prevAcl)\r
+            //EDP -- Mandatory\r
+            if(0 == strcmp(OIC_JSON_EDP_NAME, name))\r
             {\r
-                prevAcl->next = pdacl;\r
+                cborFindResult = cbor_value_get_boolean(&pconfMap, &pconf->edp);\r
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get value");\r
             }\r
-\r
-            cJSON *jsonAclObj = NULL;\r
-\r
-            // Resources -- Mandatory\r
-            jsonAclObj = cJSON_GetObjectItem(jsonPdAcl, OIC_JSON_RESOURCES_NAME);\r
-            VERIFY_NON_NULL(TAG, jsonAclObj, ERROR);\r
-            VERIFY_SUCCESS(TAG, cJSON_Array == jsonAclObj->type, ERROR);\r
-\r
-            pdacl->resourcesLen = (size_t)cJSON_GetArraySize(jsonAclObj);\r
-            VERIFY_SUCCESS(TAG, pdacl->resourcesLen > 0, ERROR);\r
-            pdacl->resources = (char**)OICCalloc(pdacl->resourcesLen, sizeof(char*));\r
-            VERIFY_NON_NULL(TAG, (pdacl->resources), ERROR);\r
-\r
-            size_t idxx = 0;\r
-            do\r
+            if (0 == strcmp(OIC_JSON_PRM_NAME, name))\r
             {\r
-                cJSON *jsonRsrc = cJSON_GetArrayItem(jsonAclObj, idxx);\r
-                VERIFY_NON_NULL(TAG, jsonRsrc, ERROR);\r
-\r
-                jsonObjLen = strlen(jsonRsrc->valuestring) + 1;\r
-                pdacl->resources[idxx] = (char*)OICMalloc(jsonObjLen);\r
-                VERIFY_NON_NULL(TAG, (pdacl->resources[idxx]), ERROR);\r
-                OICStrcpy(pdacl->resources[idxx], jsonObjLen, jsonRsrc->valuestring);\r
-            } while ( ++idxx < pdacl->resourcesLen);\r
-\r
-            // Permissions -- Mandatory\r
-            jsonAclObj = cJSON_GetObjectItem(jsonPdAcl,\r
-                                OIC_JSON_PERMISSION_NAME);\r
-            VERIFY_NON_NULL(TAG, jsonAclObj, ERROR);\r
-            VERIFY_SUCCESS(TAG, cJSON_Number == jsonAclObj->type, ERROR);\r
-            pdacl->permission = jsonAclObj->valueint;\r
-\r
-            //Period -- Not Mandatory\r
-            cJSON *jsonPeriodObj = cJSON_GetObjectItem(jsonPdAcl,\r
-                    OIC_JSON_PERIODS_NAME);\r
-            if(jsonPeriodObj)\r
-            {\r
-                VERIFY_SUCCESS(TAG, cJSON_Array == jsonPeriodObj->type,\r
-                               ERROR);\r
-                pdacl->prdRecrLen = (size_t)cJSON_GetArraySize(jsonPeriodObj);\r
-                if(pdacl->prdRecrLen > 0)\r
+                CborValue prm = { .parser = NULL };\r
+                cborFindResult = cbor_value_get_array_length(&pconfMap, &pconf->prmLen);\r
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get length");\r
+                VERIFY_SUCCESS(TAG, pconf->prmLen != 0, ERROR);\r
+\r
+                pconf->prm = (OicSecPrm_t *)OICCalloc(pconf->prmLen, sizeof(OicSecPrm_t));\r
+                VERIFY_NON_NULL(TAG, pconf->prm, ERROR);\r
+                cborFindResult = cbor_value_enter_container(&pconfMap, &prm);\r
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to eneter array");\r
+                int i = 0;\r
+\r
+                while (cbor_value_is_valid(&prm))\r
                 {\r
-                    pdacl->periods = (char**)OICCalloc(pdacl->prdRecrLen,\r
-                                    sizeof(char*));\r
-                    VERIFY_NON_NULL(TAG, pdacl->periods, ERROR);\r
-\r
-                    cJSON *jsonPeriod = NULL;\r
-                    for(size_t i = 0; i < pdacl->prdRecrLen; i++)\r
-                    {\r
-                        jsonPeriod = cJSON_GetArrayItem(jsonPeriodObj, i);\r
-                        VERIFY_NON_NULL(TAG, jsonPeriod, ERROR);\r
-\r
-                        jsonObjLen = strlen(jsonPeriod->valuestring) + 1;\r
-                        pdacl->periods[i] = (char*)OICMalloc(jsonObjLen);\r
-                        VERIFY_NON_NULL(TAG, pdacl->periods[i], ERROR);\r
-                        OICStrcpy(pdacl->periods[i], jsonObjLen,\r
-                                  jsonPeriod->valuestring);\r
-                    }\r
+                    cborFindResult = cbor_value_get_int(&prm, (int *)&pconf->prm[i++]);\r
+                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get value");\r
+                    cborFindResult = cbor_value_advance(&prm);\r
+                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to advance value");\r
                 }\r
             }\r
+            //PIN -- Mandatory\r
+            if (0 == strcmp(OIC_JSON_PIN_NAME, name))\r
+            {\r
+                uint8_t *pin = NULL;\r
+                cborFindResult = cbor_value_dup_byte_string(&pconfMap, &pin, &len, NULL);\r
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get value");\r
+                memcpy(pconf->pin.val, pin, len);\r
+                OICFree(pin);\r
+            }\r
 \r
-            //Recurrence -- Not mandatory\r
-            cJSON *jsonRecurObj = cJSON_GetObjectItem(jsonPdAcl,\r
-                                        OIC_JSON_RECURRENCES_NAME);\r
-            if(jsonRecurObj)\r
+            //PDACL -- Mandatory\r
+            if (0 == strcmp(OIC_JSON_PDACL_NAME, name))\r
             {\r
-                VERIFY_SUCCESS(TAG, cJSON_Array == jsonRecurObj->type,\r
-                               ERROR);\r
+                CborValue pdAclArray = { .parser = NULL};\r
+                cborFindResult = cbor_value_enter_container(&pconfMap, &pdAclArray);\r
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to enter");\r
+                OicSecPdAcl_t *headPdacl = NULL;\r
 \r
-                if(pdacl->prdRecrLen > 0)\r
+                while (cbor_value_is_valid(&pdAclArray))\r
                 {\r
-                    pdacl->recurrences = (char**)OICCalloc(pdacl->prdRecrLen,\r
-                                             sizeof(char*));\r
-                    VERIFY_NON_NULL(TAG, pdacl->recurrences, ERROR);\r
+                    CborValue pdAclMap = { .parser = NULL};\r
+                    cborFindResult = cbor_value_enter_container(&pdAclArray, &pdAclMap);\r
+                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to enter");\r
+                    OicSecPdAcl_t *pdacl = (OicSecPdAcl_t *) OICCalloc(1, sizeof(OicSecPdAcl_t));\r
+                    VERIFY_NON_NULL(TAG, pdacl, ERROR);\r
 \r
-                    cJSON *jsonRecur = NULL;\r
-                    for(size_t i = 0; i < pdacl->prdRecrLen; i++)\r
+                    while (cbor_value_is_valid(&pdAclMap))\r
                     {\r
-                        jsonRecur = cJSON_GetArrayItem(jsonRecurObj, i);\r
-                        VERIFY_NON_NULL(TAG, jsonRecur, ERROR);\r
-                        jsonObjLen = strlen(jsonRecur->valuestring) + 1;\r
-                        pdacl->recurrences[i] = (char*)OICMalloc(jsonObjLen);\r
-                        VERIFY_NON_NULL(TAG, pdacl->recurrences[i], ERROR);\r
-                        OICStrcpy(pdacl->recurrences[i], jsonObjLen,\r
-                              jsonRecur->valuestring);\r
+                        char* name = NULL;\r
+                        size_t len = 0;\r
+                        CborType type = cbor_value_get_type(&pdAclMap);\r
+                        if (type == CborTextStringType)\r
+                        {\r
+                            cborFindResult = cbor_value_dup_text_string(&pdAclMap, &name,\r
+                                    &len, NULL);\r
+                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get text");\r
+                            cborFindResult = cbor_value_advance(&pdAclMap);\r
+                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to advance value");\r
+                        }\r
+                        if (name)\r
+                        {\r
+                            // Resources -- Mandatory\r
+                            if (strcmp(name, OIC_JSON_RESOURCES_NAME) == 0)\r
+                            {\r
+                                CborValue resources = { .parser = NULL };\r
+                                cborFindResult = cbor_value_get_array_length(&pdAclMap,\r
+                                        &pdacl->resourcesLen);\r
+                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get length");\r
+                                cborFindResult = cbor_value_enter_container(&pdAclMap, &resources);\r
+                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to enter");\r
+                                pdacl->resources = (char **) OICCalloc(pdacl->resourcesLen,\r
+                                        sizeof(char*));\r
+                                VERIFY_NON_NULL(TAG, pdacl->resources, ERROR);\r
+                                int i = 0;\r
+                                while (cbor_value_is_text_string(&resources))\r
+                                {\r
+                                    cborFindResult = cbor_value_dup_text_string(&resources,\r
+                                            &pdacl->resources[i++], &len, NULL);\r
+                                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get text");\r
+                                    cborFindResult = cbor_value_advance(&resources);\r
+                                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to advance");\r
+                                }\r
+                            }\r
+\r
+                            // Permissions -- Mandatory\r
+                            if (strcmp(name, OIC_JSON_PERMISSION_NAME) == 0)\r
+                            {\r
+                                cborFindResult = cbor_value_get_uint64(&pdAclMap,\r
+                                        (uint64_t *) &pdacl->permission);\r
+                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get value");\r
+                            }\r
+\r
+                            // Period -- Not mandatory\r
+                            if (strcmp(name, OIC_JSON_PERIODS_NAME) == 0)\r
+                            {\r
+                                CborValue period = { .parser = NULL };\r
+                                cborFindResult = cbor_value_get_array_length(&pdAclMap,\r
+                                        &pdacl->prdRecrLen);\r
+                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get length");\r
+                                cborFindResult = cbor_value_enter_container(&pdAclMap, &period);\r
+                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to enter");\r
+                                pdacl->periods = (char **) OICCalloc(pdacl->prdRecrLen, sizeof(char*));\r
+                                VERIFY_NON_NULL(TAG, pdacl->periods, ERROR);\r
+                                int i = 0;\r
+                                while (cbor_value_is_text_string(&period))\r
+                                {\r
+                                    cborFindResult = cbor_value_dup_text_string(&period,\r
+                                            &pdacl->periods[i++], &len, NULL);\r
+                                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get text");\r
+                                    cborFindResult = cbor_value_advance(&period);\r
+                                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to advance");\r
+                                    pdacl->prdRecrLen++;\r
+                                }\r
+                            }\r
+\r
+                            // Recurrence -- Not mandatory\r
+                            if (strcmp(name, OIC_JSON_RECURRENCES_NAME) == 0)\r
+                            {\r
+                                CborValue recurrences = { .parser = NULL };\r
+                                cborFindResult = cbor_value_get_array_length(&pdAclMap, &pdacl->prdRecrLen);\r
+                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get length");\r
+                                cborFindResult = cbor_value_enter_container(&pdAclMap, &recurrences);\r
+                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to enter");\r
+                                pdacl->recurrences = (char **) OICCalloc(pdacl->prdRecrLen, sizeof(char*));\r
+                                VERIFY_NON_NULL(TAG, pdacl->recurrences, ERROR);\r
+                                int i = 0;\r
+\r
+                                while (cbor_value_is_text_string(&recurrences))\r
+                                {\r
+                                    cborFindResult = cbor_value_dup_text_string(&recurrences,\r
+                                            &pdacl->recurrences[i++], &len, NULL);\r
+                                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get value");\r
+                                    cborFindResult = cbor_value_advance(&recurrences);\r
+                                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to advance");\r
+                                }\r
+                            }\r
+                            if (type != CborMapType && cbor_value_is_valid(&pdAclMap))\r
+                            {\r
+                                cborFindResult = cbor_value_advance(&pdAclMap);\r
+                                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to advance");\r
+                            }\r
+                        }\r
+                        if (cbor_value_is_valid(&pdAclArray))\r
+                        {\r
+                            cborFindResult = cbor_value_advance(&pdAclArray);\r
+                            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to advance");\r
+                        }\r
+                        OICFree(name);\r
+                        name = NULL;\r
+                    }\r
+                    pdacl->next = NULL;\r
+                    if (headPdacl == NULL)\r
+                    {\r
+                        headPdacl = pdacl;\r
+                    }\r
+                    else\r
+                    {\r
+                        OicSecPdAcl_t *temp = headPdacl;\r
+                        while (temp->next)\r
+                        {\r
+                            temp = temp->next;\r
+                        }\r
+                        temp->next = pdacl;\r
                     }\r
                 }\r
+                pconf->pdacls = headPdacl;\r
             }\r
 \r
-            prevAcl = pdacl;\r
-            idx++;\r
-        }\r
-\r
-        pconf->pdacls = headAcl;\r
-    }\r
-    else\r
-    {\r
-        pconf->pdacls = NULL;\r
-    }\r
+            //PDDev -- Mandatory\r
+            if (strcmp(name, OIC_JSON_PDDEV_LIST_NAME) == 0)\r
+            {\r
+                CborValue pddevs = { .parser = NULL };\r
+                cborFindResult = cbor_value_get_array_length(&pconfMap, &pconf->pddevLen);\r
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get length");\r
+                cborFindResult = cbor_value_enter_container(&pconfMap, &pddevs);\r
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to enter");\r
+                int i = 0;\r
+\r
+                pconf->pddevs = (OicUuid_t *)OICMalloc(pconf->pddevLen * sizeof(OicUuid_t));\r
+                VERIFY_NON_NULL(TAG, pconf->pddevs, ERROR);\r
+                while (cbor_value_is_valid(&pddevs))\r
+                {\r
+                    uint8_t *pddev = NULL;\r
+                    cborFindResult = cbor_value_dup_byte_string(&pddevs, &pddev, &len, NULL);\r
+                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get value");\r
+                    cborFindResult = cbor_value_advance(&pddevs);\r
+                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to advance");\r
+                    memcpy(pconf->pddevs[i++].id, pddev, len);\r
+                    OICFree(pddev);\r
+                }\r
+            }\r
 \r
-    //PDDev -- Mandatory\r
-    jsonObj = cJSON_GetObjectItem(jsonPconf, OIC_JSON_PDDEV_LIST_NAME);\r
-    if (jsonObj && cJSON_Array == jsonObj->type)\r
-    {\r
-        pconf->pddevLen = (size_t)cJSON_GetArraySize(jsonObj);\r
-        if(0 < pconf->pddevLen)\r
-        {\r
-            pconf->pddevs = (OicUuid_t *)OICCalloc(pconf->pddevLen, sizeof(OicUuid_t));\r
-            VERIFY_NON_NULL(TAG, pconf->pddevs, ERROR);\r
+            //Mandatory - Device Id\r
+            if (0 == strcmp(OIC_JSON_DEVICE_ID_NAME, name))\r
+            {\r
+                uint8_t *deviceId = NULL;\r
+                cborFindResult = cbor_value_dup_byte_string(&pconfMap, &deviceId, &len, NULL);\r
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get deviceID");\r
+                memcpy(pconf->deviceID.id, deviceId, len);\r
+                OICFree(deviceId);\r
+            }\r
 \r
-            for (size_t i  = 0; i < pconf->pddevLen ; i++)\r
+            // ROwner -- Mandatory\r
+            if (0 == strcmp(OIC_JSON_ROWNER_NAME, name))\r
             {\r
-                cJSON *jsonPdDev = cJSON_GetArrayItem(jsonObj, i);\r
-                VERIFY_NON_NULL(TAG, jsonPdDev, ERROR);\r
-\r
-                outLen = 0;\r
-                b64Ret = b64Decode(jsonPdDev->valuestring, strlen(jsonPdDev->valuestring), base64Buff,\r
-                        sizeof(base64Buff), &outLen);\r
-                VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(pconf->pddevs[i].id)), ERROR);\r
-                memcpy(pconf->pddevs[i].id, base64Buff, outLen);\r
+                uint8_t *rowner = NULL;\r
+                cborFindResult = cbor_value_dup_byte_string(&pconfMap, &rowner, &len, NULL);\r
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to get rowner");\r
+                memcpy(pconf->rowner.id, rowner, len);\r
+                OICFree(rowner);\r
             }\r
         }\r
+        if (CborMapType != type && cbor_value_is_valid(&pconfMap))\r
+        {\r
+            cborFindResult = cbor_value_advance(&pconfMap);\r
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to advance");\r
+        }\r
+        OICFree(name);\r
+        name = NULL;\r
     }\r
-    else\r
-    {\r
-        pconf->pddevs = NULL;\r
-        pconf->pddevLen = 0;\r
-    }\r
-\r
-    //DeviceId -- Mandatory\r
-    outLen = 0;\r
-    jsonObj = cJSON_GetObjectItem(jsonPconf, OIC_JSON_DEVICE_ID_NAME);\r
-    if (jsonObj && cJSON_String == jsonObj->type)\r
-    {\r
-        b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff,\r
-                sizeof(base64Buff), &outLen);\r
-        VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(pconf->deviceID.id)), ERROR);\r
-        memcpy(pconf->deviceID.id, base64Buff, outLen);\r
-    }\r
-    else\r
-    {\r
-        OicUuid_t deviceId = {.id = {0}};\r
-        OCStackResult ret = GetDoxmDeviceID( &deviceId);\r
-        VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);\r
-        memcpy(&pconf->deviceID, &deviceId, sizeof(OicUuid_t));\r
-    }\r
-\r
-    // ROwner -- Mandatory\r
-    outLen = 0;\r
-    jsonObj = cJSON_GetObjectItem(jsonPconf, OIC_JSON_ROWNER_NAME);\r
-    if (jsonObj && cJSON_String == jsonObj->type)\r
-    {\r
-        b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff,\r
-                sizeof(base64Buff), &outLen);\r
-        VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(pconf->rowner.id)), ERROR);\r
-        memcpy(pconf->rowner.id, base64Buff, outLen);\r
-    }\r
-    else\r
-    {\r
-        memset(&pconf->rowner, 0, sizeof(OicUuid_t));\r
-    }\r
-\r
+    *secPconf=pconf;\r
     ret = OC_STACK_OK;\r
-\r
 exit:\r
-    cJSON_Delete(jsonRoot);\r
-    if (OC_STACK_OK != ret)\r
+    if (CborNoError != cborFindResult)\r
     {\r
+        OIC_LOG (ERROR, TAG, "CBORPayloadToPconf failed");\r
         DeletePconfBinData(pconf);\r
         pconf = NULL;\r
+        ret = OC_STACK_ERROR;\r
     }\r
-\r
-    OIC_LOG(DEBUG, TAG, "JSONToPconfBin() OUT");\r
-    return pconf;\r
+    return ret;\r
 }\r
 \r
 static bool UpdatePersistentStorage(const OicSecPconf_t * pconf)\r
 {\r
     bool ret = false;\r
 \r
-    // Convert PCONF data into JSON for update to persistent storage\r
-    char *jsonStr = BinToPconfJSON(pconf);\r
-    if (jsonStr)\r
+    // Convert PCONF data into Cborpayload for update to persistent storage\r
+    uint8_t *payload = NULL;\r
+    size_t size = 0;\r
+    if (OC_STACK_OK == PconfToCBORPayload(pconf, &payload, &size) && NULL !=payload)\r
     {\r
-        cJSON *jsonPconf = cJSON_Parse(jsonStr);\r
-        OICFree(jsonStr);\r
-\r
-        if ((jsonPconf) &&\r
-                (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_PCONF_NAME, jsonPconf)))\r
+        if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_PCONF_NAME, payload, size))\r
         {\r
             ret = true;\r
         }\r
-        cJSON_Delete(jsonPconf);\r
+        OICFree(payload);\r
     }\r
     return ret;\r
 }\r
 \r
 static OCEntityHandlerResult HandlePconfGetRequest (const OCEntityHandlerRequest * ehRequest)\r
 {\r
-    char* jsonStr = NULL;\r
+    uint8_t* payload = NULL;\r
+    size_t size = 0;\r
     OCEntityHandlerResult ehRet = OC_EH_OK;\r
 \r
     OicSecPconf_t pconf;\r
@@ -596,7 +707,7 @@ static OCEntityHandlerResult HandlePconfGetRequest (const OCEntityHandlerRequest
     {\r
         //Making response elements for Get request\r
         if( (true == gPconf->edp) && (gPconf->prm && 0 < gPconf->prmLen) &&\r
-            (0 < strlen((const char*)gPconf->deviceID.id)) && (0 < strlen((const char*)gPconf->rowner.id)))\r
+                (0 < strlen((const char*)gPconf->deviceID.id)) && (0 < strlen((const char*)gPconf->rowner.id)))\r
         {\r
             pconf.edp = true;\r
             pconf.prm = gPconf->prm;\r
@@ -620,18 +731,18 @@ static OCEntityHandlerResult HandlePconfGetRequest (const OCEntityHandlerRequest
     else\r
     {\r
         OIC_LOG (DEBUG, TAG, "DPC == false : Direct-Pairing Disabled");\r
-        ehRet = OC_EH_ERROR;\r
     }\r
 \r
-    jsonStr = (ehRet == OC_EH_OK) ? BinToPconfJSON(&pconf) : NULL;\r
 \r
-    // Send response payload to request originator\r
-    if(OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, jsonStr))\r
+    if (OC_STACK_OK != PconfToCBORPayload(gPconf, &payload, &size))\r
     {\r
-        OIC_LOG (ERROR, TAG, "SendSRMResponse failed in HandleDpairingGetRequest");\r
+        ehRet = OC_EH_ERROR;\r
     }\r
+    ehRet = (payload ? OC_EH_OK : OC_EH_ERROR);\r
 \r
-    OICFree(jsonStr);\r
+    // Send response payload to request originator\r
+    SendSRMCBORResponse(ehRequest, ehRet, payload, size);\r
+    OIC_LOG_V(DEBUG, TAG, "%s RetVal %d", __func__, ehRet);\r
 \r
     return ehRet;\r
 }\r
@@ -639,12 +750,18 @@ static OCEntityHandlerResult HandlePconfGetRequest (const OCEntityHandlerRequest
 static OCEntityHandlerResult HandlePconfPostRequest (const OCEntityHandlerRequest * ehRequest)\r
 {\r
     OCEntityHandlerResult ehRet = OC_EH_OK;\r
+    OCStackResult res=OC_STACK_OK;\r
     OicSecPconf_t* newPconf = NULL;\r
 \r
     if (true == GetDoxmResourceData()->dpc)\r
     {\r
-        // Convert JSON PCONF data into binary. This will also validate the PCONF data received.\r
-        newPconf = JSONToPconfBin(((OCSecurityPayload*)ehRequest->payload)->securityData);\r
+        // Convert CBOR PCONF data into binary. This will also validate the PCONF data received.\r
+        uint8_t *payload = ((OCSecurityPayload *) ehRequest->payload)->securityData1;\r
+        size_t size = ((OCSecurityPayload *) ehRequest->payload)->payloadSize;\r
+\r
+        if(payload){\r
+            res = CBORPayloadToPconf(payload, size, &newPconf);\r
+        }\r
     }\r
     else\r
     {\r
@@ -652,11 +769,11 @@ static OCEntityHandlerResult HandlePconfPostRequest (const OCEntityHandlerReques
         ehRet = OC_EH_ERROR;\r
     }\r
 \r
-    if (newPconf)\r
+    if (newPconf && res == OC_STACK_OK)\r
     {\r
         // Check if valid Post request\r
         if ((true == newPconf->edp) && (0 < newPconf->prmLen) &&\r
-                DP_PIN_LENGTH == strlen((const char*)newPconf->pin.val))\r
+                DP_PIN_LENGTH == sizeof((const char*)newPconf->pin.val))\r
         {\r
             OicSecPrm_t *oldPrm = gPconf->prm;\r
             OicSecPdAcl_t *oldPdacl = gPconf->pdacls;\r
@@ -696,7 +813,7 @@ static OCEntityHandlerResult HandlePconfPostRequest (const OCEntityHandlerReques
     }\r
 \r
     // Send payload to request originator\r
-    SendSRMResponse(ehRequest, ehRet, NULL);\r
+    SendSRMCBORResponse(ehRequest, ehRet, NULL, 0);\r
 \r
     OIC_LOG_V (DEBUG, TAG, "%s RetVal %d", __func__ , ehRet);\r
     return ehRet;\r
@@ -737,7 +854,7 @@ OCEntityHandlerResult PconfEntityHandler (OCEntityHandlerFlag flag,
 \r
             default:\r
                 ehRet = OC_EH_ERROR;\r
-                SendSRMResponse(ehRequest, ehRet, NULL);\r
+                SendSRMCBORResponse(ehRequest, ehRet, NULL, 0);\r
         }\r
     }\r
 \r
@@ -797,16 +914,21 @@ OCStackResult InitPconfResource()
 {\r
     OCStackResult ret = OC_STACK_ERROR;\r
 \r
-    // Read PCONF resource from PS\r
-    char* jsonSVRDatabase = GetSVRDatabase();\r
+    uint8_t *data = NULL;\r
+    size_t size = 0;\r
 \r
-    if (jsonSVRDatabase)\r
+    ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_PCONF_NAME, &data, &size);\r
+    // If database read failed\r
+    if (ret != OC_STACK_OK)\r
     {\r
-        // Convert JSON PCONF into binary format\r
-        gPconf = JSONToPconfBin(jsonSVRDatabase);\r
+        OIC_LOG(DEBUG, TAG, "ReadSVDataFromPS failed");\r
+    }\r
+    if (data)\r
+    {\r
+        CBORPayloadToPconf(data, size, &gPconf);\r
     }\r
 \r
-    if(!jsonSVRDatabase || !gPconf)\r
+    if (!data || !gPconf)\r
     {\r
         gPconf = GetPconfDefault();\r
 \r
@@ -826,7 +948,7 @@ exit:
     {\r
         DeInitPconfResource();\r
     }\r
-    OICFree(jsonSVRDatabase);\r
+    OICFree(data);\r
     return ret;\r
 }\r
 \r
@@ -977,5 +1099,3 @@ bool IsPairedDevice(const OicUuid_t* pdeviceId)
     }\r
     return false;\r
 }\r
-\r
-\r
index 088496a..d0cddc1 100644 (file)
@@ -17,6 +17,7 @@
 // limitations under the License.
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#include <string.h>
 
 #include "oic_malloc.h"
 #include "policyengine.h"
 #include "srmutility.h"
 #include "doxmresource.h"
 #include "iotvticalendar.h"
-#include <string.h>
 
 #define TAG "SRM-PE"
 
-/**
- * Return the uint16_t CRUDN permission corresponding to passed CAMethod_t.
- */
 uint16_t GetPermissionFromCAMethod_t(const CAMethod_t method)
 {
     uint16_t perm = 0;
-    switch(method)
+    switch (method)
     {
         case CA_GET:
             perm = (uint16_t)PERMISSION_READ;
@@ -59,10 +56,11 @@ uint16_t GetPermissionFromCAMethod_t(const CAMethod_t method)
 }
 
 /**
- * @brief Compares two OicUuid_t structs.
+ * Compares two OicUuid_t structs.
+ *
  * @return true if the two OicUuid_t structs are equal, else false.
  */
-bool UuidCmp(OicUuid_t *firstId, OicUuid_t *secondId)
+static bool UuidCmp(OicUuid_t *firstId, OicUuid_t *secondId)
 {
     // TODO use VERIFY macros to check for null when they are merged.
     if(NULL == firstId || NULL == secondId)
@@ -79,12 +77,9 @@ bool UuidCmp(OicUuid_t *firstId, OicUuid_t *secondId)
     return true;
 }
 
-/**
- * Set the state and clear other stateful context vars.
- */
 void SetPolicyEngineState(PEContext_t *context, const PEState_t state)
 {
-    if(NULL == context)
+    if (NULL == context)
     {
         return;
     }
@@ -106,11 +101,11 @@ void SetPolicyEngineState(PEContext_t *context, const PEState_t state)
 }
 
 /**
- * @brief Compare the request's subject to DevOwner.
+ * Compare the request's subject to DevOwner.
  *
- * @return true if context->subjectId == GetDoxmDevOwner(), else false
+ * @return true if context->subjectId == GetDoxmDevOwner(), else false.
  */
-bool IsRequestFromDevOwner(PEContext_t *context)
+static bool IsRequestFromDevOwner(PEContext_t *context)
 {
     bool retVal = false;
     OicUuid_t owner;
@@ -128,7 +123,6 @@ bool IsRequestFromDevOwner(PEContext_t *context)
     return retVal;
 }
 
-
 inline static bool IsRequestSubjectEmpty(PEContext_t *context)
 {
     OicUuid_t emptySubject = {.id={}};
@@ -142,17 +136,18 @@ inline static bool IsRequestSubjectEmpty(PEContext_t *context)
             true : false;
 }
 
-
 /**
  * Bitwise check to see if 'permission' contains 'request'.
- * @param   permission  The allowed CRUDN permission.
- * @param   request     The CRUDN permission being requested.
+ *
+ * @param permission is the allowed CRUDN permission.
+ * @param request is the CRUDN permission being requested.
+ *
  * @return true if 'permission' bits include all 'request' bits.
  */
 static inline bool IsPermissionAllowingRequest(const uint16_t permission,
     const uint16_t request)
 {
-    if(request == (request & permission))
+    if (request == (request & permission))
     {
         return true;
     }
@@ -164,6 +159,7 @@ static inline bool IsPermissionAllowingRequest(const uint16_t permission,
 
 /**
  * Compare the passed subject to the wildcard (aka anonymous) subjectId.
+ *
  * @return true if 'subject' is the wildcard, false if it is not.
  */
 static inline bool IsWildCardSubject(OicUuid_t *subject)
@@ -187,15 +183,14 @@ static inline bool IsWildCardSubject(OicUuid_t *subject)
 /**
  * Copy the subject, resource and permission into the context fields.
  */
-void CopyParamsToContext(
-    PEContext_t     *context,
-    const OicUuid_t *subjectId,
-    const char      *resource,
-    const uint16_t  requestedPermission)
+static void CopyParamsToContext(PEContext_t     *context,
+                                const OicUuid_t *subjectId,
+                                const char      *resource,
+                                const uint16_t  requestedPermission)
 {
     size_t length = 0;
 
-    if(NULL == context || NULL == subjectId || NULL == resource)
+    if (NULL == context || NULL == subjectId || NULL == resource)
     {
         return;
     }
@@ -204,7 +199,7 @@ void CopyParamsToContext(
 
     // Copy the resource string into context.
     length = strlen(resource) + 1;
-    if(0 < length)
+    if (0 < length)
     {
         strncpy(context->resource, resource, length);
         context->resource[length - 1] = '\0';
@@ -214,32 +209,32 @@ void CopyParamsToContext(
     context->permission = requestedPermission;
 }
 
-
 /**
  * Check whether 'resource' is getting accessed within the valid time period.
- * @param   acl         The ACL to check.
- * @return
- *      true if access is within valid time period or if the period or recurrence is not present.
- *      false if period and recurrence present and the access is not within valid time period.
+ *
+ * @param acl is the ACL to check.
+ *
+ * @return true if access is within valid time period or if the period or recurrence is not present.
+ * false if period and recurrence present and the access is not within valid time period.
  */
 static bool IsAccessWithinValidTime(const OicSecAcl_t *acl)
 {
 #ifndef WITH_ARDUINO //Period & Recurrence not supported on Arduino due
                      //lack of absolute time
-    if(NULL== acl || NULL == acl->periods || 0 == acl->prdRecrLen)
+    if (NULL== acl || NULL == acl->periods || 0 == acl->prdRecrLen)
     {
         return true;
     }
 
     //periods & recurrences rules are paired.
-    if(NULL == acl->recurrences)
+    if (NULL == acl->recurrences)
     {
         return false;
     }
 
-    for(size_t i = 0; i < acl->prdRecrLen; i++)
+    for (size_t i = 0; i < acl->prdRecrLen; i++)
     {
-        if(IOTVTICAL_VALID_ACCESS ==  IsRequestWithinValidTime(acl->periods[i],
+        if (IOTVTICAL_VALID_ACCESS ==  IsRequestWithinValidTime(acl->periods[i],
             acl->recurrences[i]))
         {
             OIC_LOG(INFO, TAG, "Access request is in allowed time period");
@@ -256,21 +251,23 @@ static bool IsAccessWithinValidTime(const OicSecAcl_t *acl)
 
 /**
  * Check whether 'resource' is in the passed ACL.
- * @param   resource    The resource to search for.
- * @param   acl         The ACL to check.
+ *
+ * @param resource is the resource being searched.
+ * @param acl is the ACL to check.
+ *
  * @return true if 'resource' found, otherwise false.
  */
- bool IsResourceInAcl(const char *resource, const OicSecAcl_t *acl)
static bool IsResourceInAcl(const char *resource, const OicSecAcl_t *acl)
 {
-    if(NULL== acl || NULL == resource)
+    if (NULL== acl || NULL == resource)
     {
         return false;
     }
 
-     for(size_t n = 0; n < acl->resourcesLen; n++)
+     for (size_t n = 0; n < acl->resourcesLen; n++)
      {
-         if(0 == strcmp(resource, acl->resources[n]) || // TODO null terms?
-                 0 == strcmp(WILDCARD_RESOURCE_URI, acl->resources[n]))
+         if (0 == strcmp(resource, acl->resources[n]) || // TODO null terms?
+             0 == strcmp(WILDCARD_RESOURCE_URI, acl->resources[n]))
          {
              return true;
          }
@@ -284,16 +281,14 @@ static bool IsAccessWithinValidTime(const OicSecAcl_t *acl)
  * Search each ACL for requested resource.
  * If resource found, check for context->permission and period validity.
  * If the ACL is not found locally and AMACL for the resource is found
- * then sends the request to AMS service for the ACL
+ * then sends the request to AMS service for the ACL.
  * Set context->retVal to result from first ACL found which contains
  * correct subject AND resource.
- *
- * @retval void
  */
-void ProcessAccessRequest(PEContext_t *context)
+static void ProcessAccessRequest(PEContext_t *context)
 {
     OIC_LOG(DEBUG, TAG, "Entering ProcessAccessRequest()");
-    if(NULL != context)
+    if (NULL != context)
     {
         const OicSecAcl_t *currentAcl = NULL;
         OicSecAcl_t *savePtr = NULL;
@@ -308,7 +303,7 @@ void ProcessAccessRequest(PEContext_t *context)
             OIC_LOG_V(DEBUG, TAG, "%s: getting ACL..." ,__func__);
             currentAcl = GetACLResourceData(&context->subject, &savePtr);
 
-            if(NULL != currentAcl)
+            if (NULL != currentAcl)
             {
                 // Found the subject, so how about resource?
                 OIC_LOG_V(DEBUG, TAG, "%s:found ACL matching subject" ,__func__);
@@ -316,17 +311,17 @@ void ProcessAccessRequest(PEContext_t *context)
                 // Subject was found, so err changes to Rsrc not found for now.
                 context->retVal = ACCESS_DENIED_RESOURCE_NOT_FOUND;
                 OIC_LOG_V(DEBUG, TAG, "%s:Searching for resource..." ,__func__);
-                if(IsResourceInAcl(context->resource, currentAcl))
+                if (IsResourceInAcl(context->resource, currentAcl))
                 {
                     OIC_LOG_V(INFO, TAG, "%s:found matching resource in ACL" ,__func__);
                     context->matchingAclFound = true;
 
                     // Found the resource, so it's down to valid period & permission.
                     context->retVal = ACCESS_DENIED_INVALID_PERIOD;
-                    if(IsAccessWithinValidTime(currentAcl))
+                    if (IsAccessWithinValidTime(currentAcl))
                     {
                         context->retVal = ACCESS_DENIED_INSUFFICIENT_PERMISSION;
-                        if(IsPermissionAllowingRequest(currentAcl->permission, context->permission))
+                        if (IsPermissionAllowingRequest(currentAcl->permission, context->permission))
                         {
                             context->retVal = ACCESS_GRANTED;
                         }
@@ -337,10 +332,9 @@ void ProcessAccessRequest(PEContext_t *context)
             {
                 OIC_LOG_V(INFO, TAG, "%s:no ACL found matching subject for resource %s",__func__, context->resource);
             }
-        }
-        while((NULL != currentAcl) && (false == context->matchingAclFound));
+        } while ((NULL != currentAcl) && (false == context->matchingAclFound));
 
-        if(IsAccessGranted(context->retVal))
+        if (IsAccessGranted(context->retVal))
         {
             OIC_LOG_V(INFO, TAG, "%s:Leaving ProcessAccessRequest(ACCESS_GRANTED)", __func__);
         }
@@ -355,20 +349,10 @@ void ProcessAccessRequest(PEContext_t *context)
     }
 }
 
-/**
- * Check whether a request should be allowed.
- * @param   context     Pointer to (Initialized) Policy Engine context to use.
- * @param   subjectId   Pointer to Id of the requesting entity.
- * @param   resource    Pointer to URI of Resource being requested.
- * @param   permission  Requested permission.
- * @return  ACCESS_GRANTED if request should go through,
- *          otherwise some flavor of ACCESS_DENIED
- */
-SRMAccessResponse_t CheckPermission(
-    PEContext_t     *context,
-    const OicUuid_t *subjectId,
-    const char      *resource,
-    const uint16_t  requestedPermission)
+SRMAccessResponse_t CheckPermission(PEContext_t     *context,
+                                    const OicUuid_t *subjectId,
+                                    const char      *resource,
+                                    const uint16_t  requestedPermission)
 {
     SRMAccessResponse_t retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
 
@@ -379,9 +363,9 @@ SRMAccessResponse_t CheckPermission(
     // Each state machine context can only be processing one request at a time.
     // Therefore if the context is not in AWAITING_REQUEST or AWAITING_AMS_RESPONSE
     // state, return error. Otherwise, change to BUSY state and begin processing request.
-    if(AWAITING_REQUEST == context->state || AWAITING_AMS_RESPONSE == context->state)
+    if (AWAITING_REQUEST == context->state || AWAITING_AMS_RESPONSE == context->state)
     {
-        if(AWAITING_REQUEST == context->state)
+        if (AWAITING_REQUEST == context->state)
         {
             SetPolicyEngineState(context, BUSY);
             CopyParamsToContext(context, subjectId, resource, requestedPermission);
@@ -389,7 +373,7 @@ SRMAccessResponse_t CheckPermission(
 
         // Before doing any processing, check if request coming
         // from DevOwner and if so, always GRANT.
-        if(IsRequestFromDevOwner(context))
+        if (IsRequestFromDevOwner(context))
         {
             context->retVal = ACCESS_GRANTED;
         }
@@ -401,7 +385,7 @@ SRMAccessResponse_t CheckPermission(
             ProcessAccessRequest(context);
 
             // If matching ACL not found, and subject != wildcard, try wildcard.
-            if((false == context->matchingAclFound) && \
+            if ((false == context->matchingAclFound) && \
               (false == IsWildCardSubject(&context->subject)))
             {
                 //Saving subject for Amacl check
@@ -418,7 +402,7 @@ SRMAccessResponse_t CheckPermission(
             }
 
             //No local ACE found for the request so checking Amacl resource
-            if(ACCESS_GRANTED != context->retVal)
+            if (ACCESS_GRANTED != context->retVal)
             {
                 //If subject is not empty then restore the original subject
                 //else keep the subject to WILDCARD_SUBJECT_ID
@@ -445,7 +429,7 @@ SRMAccessResponse_t CheckPermission(
     // Capture retVal before resetting state for next request.
     retVal = context->retVal;
 
-   if(!context->amsProcessing)
+   if (!context->amsProcessing)
     {
         OIC_LOG(INFO, TAG, "Resetting PE context and PE State to AWAITING_REQUEST");
         SetPolicyEngineState(context, AWAITING_REQUEST);
@@ -455,11 +439,6 @@ exit:
     return retVal;
 }
 
-/**
- * Initialize the Policy Engine. Call this before calling CheckPermission().
- * @param   context     Pointer to Policy Engine context to initialize.
- * @return  OC_STACK_OK for Success, otherwise some error value
- */
 OCStackResult InitPolicyEngine(PEContext_t *context)
 {
     if(NULL == context)
@@ -477,12 +456,6 @@ OCStackResult InitPolicyEngine(PEContext_t *context)
     return OC_STACK_OK;
 }
 
-/**
- * De-Initialize the Policy Engine.  Call this before exiting to allow Policy
- * Engine to do cleanup on context.
- * @param   context     Pointer to Policy Engine context to de-initialize.
- * @return  none
- */
 void DeInitPolicyEngine(PEContext_t *context)
 {
     if(NULL != context)
index 719d51b..5b3169f 100644 (file)
 // limitations under the License.
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#ifdef WITH_ARDUINO
+#define __STDC_LIMIT_MACROS
+#endif
 
+#include <stdlib.h>
+#include <string.h>
 #include "ocstack.h"
 #include "logger.h"
 #include "oic_malloc.h"
-#include "cJSON.h"
+#include "ocpayload.h"
+#include "ocpayloadcbor.h"
+#include "payload_logging.h"
 #include "cainterface.h"
 #include "secureresourcemanager.h"
 #include "resourcemanager.h"
 #include "srmresourcestrings.h"
 #include "srmutility.h"
-#include <stdlib.h>
-#include <string.h>
 
 #define TAG  "SRM-PSI"
 
@@ -38,11 +43,11 @@ const size_t DB_FILE_SIZE_BLOCK = 1023;
 /**
  * Gets the Secure Virtual Database size.
  *
- * @param ps  pointer of OCPersistentStorage for the SVR name ("acl", "cred", "pstat" etc).
+ * @param ps pointer of OCPersistentStorage for the SVR name ("acl", "cred", "pstat" etc).
  *
- * @retval  total size of the SVR database.
+ * @return total size of the SVR database.
  */
-size_t GetSVRDatabaseSize(OCPersistentStorage* ps)
+static size_t GetSVRDatabaseSize(const OCPersistentStorage* ps)
 {
     size_t size = 0;
     if (!ps)
@@ -51,7 +56,7 @@ size_t GetSVRDatabaseSize(OCPersistentStorage* ps)
     }
     size_t bytesRead  = 0;
     char buffer[DB_FILE_SIZE_BLOCK];
-    FILE* fp = ps->open(SVR_DB_FILE_NAME, "r");
+    FILE* fp = ps->open(SVR_DB_DAT_FILE_NAME, "r");
     if (fp)
     {
         do
@@ -64,147 +69,307 @@ size_t GetSVRDatabaseSize(OCPersistentStorage* ps)
     return size;
 }
 
-/**
- * Reads the Secure Virtual Database from PS into dynamically allocated
- * memory buffer.
- *
- * @note Caller of this method MUST use OICFree() method to release memory
- *       referenced by return value.
- *
- * @retval  reference to memory buffer containing SVR database.
- */
-char * GetSVRDatabase()
+OCStackResult GetSecureVirtualDatabaseFromPS(const char *rsrcName, uint8_t **data, size_t *size)
 {
-    char * jsonStr = NULL;
-    FILE * fp = NULL;
-    OCPersistentStorage* ps = SRMGetPersistentStorageHandler();
-    int size = GetSVRDatabaseSize(ps);
-    if (0 == size)
+    if (!data || !size)
     {
-        OIC_LOG (ERROR, TAG, "FindSVRDatabaseSize failed");
-        return NULL;
+        return OC_STACK_INVALID_PARAM;
     }
+    OCStackResult ret = OC_STACK_ERROR;
+    *data = NULL;
 
-    if (ps && ps->open)
+    FILE *fp = NULL;
+    size_t fileSize = 0;
+    uint8_t *fsData = NULL;
+
+    OCPersistentStorage *ps = SRMGetPersistentStorageHandler();
+    VERIFY_NON_NULL(TAG, ps, ERROR);
+
+    fileSize = GetSVRDatabaseSize(ps);
+    if (fileSize != 0)
     {
-        // Open default SRM database file. An app could change the path for its server.
-        fp = ps->open(SVR_DB_FILE_NAME, "r");
-        if (fp)
-        {
-            jsonStr = (char*)OICMalloc(size + 1);
-            VERIFY_NON_NULL(TAG, jsonStr, FATAL);
-            size_t bytesRead = ps->read(jsonStr, 1, size, fp);
-            jsonStr[bytesRead] = '\0';
-
-            OIC_LOG_V(DEBUG, TAG, "Read %zu bytes from SVR database file", bytesRead);
-            ps->close(fp);
-            fp = NULL;
-        }
-        else
+        OIC_LOG_V(DEBUG, TAG, "File Read Size: %zu", fileSize);
+        fsData = (uint8_t *)OICCalloc(1, fileSize);
+        VERIFY_NON_NULL(TAG, fsData, ERROR);
+
+        FILE *fp = ps->open(SVR_DB_DAT_FILE_NAME, "rb");
+        VERIFY_NON_NULL(TAG, fp, ERROR);
+        size_t itemsRead = ps->read(fsData, 1, fileSize, fp);
+        if (itemsRead == fileSize)
         {
-            OIC_LOG (ERROR, TAG, "Unable to open SVR database file!!");
+            VERIFY_NON_NULL(TAG, fsData, ERROR);
+            if (rsrcName != NULL)
+            {
+                CborParser parser = { .end = NULL };
+                CborValue cbor =  { .parser = NULL };
+                cbor_parser_init(fsData, fileSize, 0, &parser, &cbor);
+                CborValue cborValue =  { .parser = NULL };
+                // CborError cborFindResult = cbor_value_enter_container(&cbor, &cborValue);
+                CborError cborFindResult = cbor_value_map_find_value(&cbor, rsrcName, &cborValue);
+                if (CborNoError == cborFindResult && cbor_value_is_byte_string(&cborValue))
+                {
+                    cborFindResult = cbor_value_dup_byte_string(&cborValue, data, size, NULL);
+                    VERIFY_SUCCESS(TAG, cborFindResult == CborNoError, ERROR);
+                    ret = OC_STACK_OK;
+                    goto exit;
+                }
+            }
+            // return everything in case rsrcName is NULL
+            else
+            {
+                *size = fileSize;
+                *data = (uint8_t *)OICCalloc(1, fileSize);
+                VERIFY_NON_NULL(TAG, *data, ERROR);
+                memcpy(*data, fsData, fileSize);
+            }
         }
     }
-
-exit:
-    if (ps && fp)
+    else
     {
-        ps->close(fp);
+        ret = OC_STACK_OK;
     }
-    return jsonStr;
-}
 
+exit:
+    OICFree(fsData);
+    return ret;
+}
 
-/**
- * This method is used by a entity handlers of SVR's to update
- * SVR database.
- *
- * @param rsrcName string denoting the SVR name ("acl", "cred", "pstat" etc).
- * @param jsonObj JSON object containing the SVR contents.
- *
- * @retval  OC_STACK_OK for Success, otherwise some error value
- */
-OCStackResult UpdateSVRDatabase(const char* rsrcName, cJSON* jsonObj)
+OCStackResult UpdateSecureResourceInPS(const char* rsrcName, const uint8_t* psPayload, size_t psSize)
 {
-    OCStackResult ret = OC_STACK_ERROR;
-    cJSON *jsonSVRDb = NULL;
-    OCPersistentStorage* ps = NULL;
+    OIC_LOG(DEBUG,  TAG, "Entering UpdateSecureResourceInPS IN");
+    /*
+     * This function stores cbor payload of each resource by appending resource name.
+     */
+     // Empty payload implies deleting the value
+    if (!rsrcName)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
 
-    // Read SVR database from PS
-    char* jsonSVRDbStr = GetSVRDatabase();
-    VERIFY_NON_NULL(TAG,jsonSVRDbStr, ERROR);
+    OCStackResult ret = OC_STACK_ERROR;
 
-    // Use cJSON_Parse to parse the existing SVR database
-    jsonSVRDb = cJSON_Parse(jsonSVRDbStr);
-    VERIFY_NON_NULL(TAG,jsonSVRDb, ERROR);
+    uint8_t *dbData = NULL;
+    size_t dbSize = 0;
+    size_t cborSize = 0;
+    uint8_t *outPayload = NULL;
+    uint8_t *aclCbor = NULL;
+    uint8_t *pstatCbor = NULL;
+    uint8_t *amaclCbor = NULL;
+    uint8_t *doxmCbor = NULL;
+    uint8_t *svcCbor = NULL;
+    uint8_t *credCbor = NULL;
+    uint8_t *pconfCbor = NULL;
 
-    OICFree(jsonSVRDbStr);
-    jsonSVRDbStr = NULL;
+    int64_t cborEncoderResult = CborNoError;
+    CborEncoder encoder;
 
-    //If Cred resource gets updated with empty list then delete the Cred
-    //object from database.
-    if(NULL == jsonObj && (0 == strcmp(rsrcName, OIC_JSON_CRED_NAME)))
-    {
-        cJSON_DeleteItemFromObject(jsonSVRDb, rsrcName);
-    }
-    else if (jsonObj->child )
+    ret = GetSecureVirtualDatabaseFromPS(NULL, &dbData, &dbSize);
+    if (dbData && dbSize != 0)
     {
-        // Create a duplicate of the JSON object which was passed.
-        cJSON* jsonDuplicateObj = cJSON_Duplicate(jsonObj, 1);
-        VERIFY_NON_NULL(TAG,jsonDuplicateObj, ERROR);
-
-        cJSON* jsonObj = cJSON_GetObjectItem(jsonSVRDb, rsrcName);
-
-        /*
-         ACL, PStat & Doxm resources at least have default entries in the database but
-         Cred resource may have no entries. The first cred resource entry (for provisioning tool)
-         is created when the device is owned by provisioning tool and it's ownerpsk is generated.*/
-        if((strcmp(rsrcName, OIC_JSON_CRED_NAME) == 0 ||
-                strcmp(rsrcName, OIC_JSON_CRL_NAME) == 0 ||
-                strcmp(rsrcName, OIC_JSON_PCONF_NAME) == 0 ||
-                strcmp(rsrcName, OIC_JSON_DPAIRING_NAME) == 0) && (!jsonObj))
+        size_t aclCborLen = 0;
+        size_t pstatCborLen = 0;
+        size_t doxmCborLen = 0;
+        size_t amaclCborLen = 0;
+        size_t svcCborLen = 0;
+        size_t credCborLen = 0;
+        size_t pconfCborLen = 0;
+
         {
-            // Add the fist cred object in existing SVR database json
-            cJSON_AddItemToObject(jsonSVRDb, rsrcName, jsonDuplicateObj->child);
+            CborValue cbor;
+            CborParser parser;
+            cbor_parser_init(dbData, dbSize, 0, &parser, &cbor);
+            CborError cborFindResult = CborNoError;
+
+            CborValue curVal;
+            cborFindResult = cbor_value_map_find_value(&cbor, OIC_JSON_ACL_NAME, &curVal);
+            if (CborNoError == cborFindResult && cbor_value_is_byte_string(&curVal))
+            {
+                cborFindResult = cbor_value_dup_byte_string(&curVal, &aclCbor, &aclCborLen, NULL);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding ACL Name Value.");
+            }
+
+            cborFindResult = cbor_value_map_find_value(&cbor, OIC_JSON_DOXM_NAME, &curVal);
+            if (CborNoError == cborFindResult && cbor_value_is_byte_string(&curVal))
+            {
+                cborFindResult = cbor_value_dup_byte_string(&curVal, &doxmCbor, &doxmCborLen, NULL);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult,  "Failed Finding DOXM Name Value.");
+            }
+
+            cborFindResult = cbor_value_map_find_value(&cbor, OIC_JSON_PSTAT_NAME, &curVal);
+            if (CborNoError == cborFindResult && cbor_value_is_byte_string(&curVal))
+            {
+                cborFindResult = cbor_value_dup_byte_string(&curVal, &pstatCbor, &pstatCborLen, NULL);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding PSTAT Name Value.");
+            }
+
+            cborFindResult = cbor_value_map_find_value(&cbor, OIC_JSON_AMACL_NAME, &curVal);
+            if (CborNoError == cborFindResult && cbor_value_is_byte_string(&curVal))
+            {
+                cborFindResult = cbor_value_dup_byte_string(&curVal, &amaclCbor, &amaclCborLen, NULL);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding AMACL Name Value.");
+            }
+
+            cborFindResult = cbor_value_map_find_value(&cbor, OIC_JSON_SVC_NAME, &curVal);
+            if (CborNoError == cborFindResult && cbor_value_is_byte_string(&curVal))
+            {
+                cborFindResult = cbor_value_dup_byte_string(&curVal, &svcCbor, &svcCborLen, NULL);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SVC Name Value.");
+            }
+
+            cborFindResult = cbor_value_map_find_value(&cbor, OIC_JSON_CRED_NAME, &curVal);
+            if (CborNoError == cborFindResult && cbor_value_is_byte_string(&curVal))
+            {
+                cborFindResult = cbor_value_dup_byte_string(&curVal, &credCbor, &credCborLen, NULL);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding CRED Name Value.");
+            }
+
+            cborFindResult = cbor_value_map_find_value(&cbor, OIC_JSON_PCONF_NAME, &curVal);
+            if (CborNoError == cborFindResult && cbor_value_is_byte_string(&curVal))
+            {
+                cborFindResult = cbor_value_dup_byte_string(&curVal, &pconfCbor, &pconfCborLen, NULL);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding PCONF Name Value.");
+            }
+
         }
-        else
+
         {
-            VERIFY_NON_NULL(TAG,jsonObj, ERROR);
+            size_t size = aclCborLen + pstatCborLen + doxmCborLen + amaclCborLen + svcCborLen
+                + credCborLen + pconfCborLen + psSize;
+            // This is arbitrary value that is added to cover the name of the resource, map addition and ending.
+            size += 255;
+
+            outPayload = (uint8_t *)OICCalloc(1, size);
+            VERIFY_NON_NULL(TAG, outPayload, ERROR);
+            cbor_encoder_init(&encoder, outPayload, size, 0);
+
+            CborEncoder secRsrc;
+            cborEncoderResult |= cbor_encoder_create_map(&encoder, &secRsrc, CborIndefiniteLength);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PS Map.");
+
+            if (psPayload)
+            {
+                cborEncoderResult |= cbor_encode_text_string(&secRsrc, rsrcName, strlen(rsrcName));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Value Tag");
+                cborEncoderResult |= cbor_encode_byte_string(&secRsrc, psPayload, psSize);
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Value.");
+            }
+
+            if (0 != strcmp(OIC_JSON_ACL_NAME, rsrcName) && aclCborLen > 0)
+            {
+                cborEncoderResult |= cbor_encode_text_string(&secRsrc, OIC_JSON_ACL_NAME, strlen(OIC_JSON_ACL_NAME));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ACL Name.");
+                cborEncoderResult |= cbor_encode_byte_string(&secRsrc, aclCbor, aclCborLen);
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ACL Value.");
+            }
+            if (0 != strcmp(OIC_JSON_PSTAT_NAME, rsrcName) && pstatCborLen > 0)
+            {
+                cborEncoderResult |= cbor_encode_text_string(&secRsrc, OIC_JSON_PSTAT_NAME, strlen(OIC_JSON_PSTAT_NAME));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PSTAT Name.");
+                cborEncoderResult |= cbor_encode_byte_string(&secRsrc, pstatCbor, pstatCborLen);
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PSTAT Value.");
+            }
+            if (0 != strcmp(OIC_JSON_DOXM_NAME, rsrcName) && doxmCborLen > 0)
+            {
+                cborEncoderResult |= cbor_encode_text_string(&secRsrc, OIC_JSON_DOXM_NAME, strlen(OIC_JSON_DOXM_NAME));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Doxm Name.");
+                cborEncoderResult |= cbor_encode_byte_string(&secRsrc, doxmCbor, doxmCborLen);
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Doxm Value.");
+            }
+            if (0 != strcmp(OIC_JSON_AMACL_NAME, rsrcName) && amaclCborLen > 0)
+            {
+                cborEncoderResult |= cbor_encode_text_string(&secRsrc, OIC_JSON_AMACL_NAME, strlen(OIC_JSON_AMACL_NAME));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Amacl Name.");
+                cborEncoderResult |= cbor_encode_byte_string(&secRsrc, amaclCbor, amaclCborLen);
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Amacl Value.");
+            }
+            if (0 != strcmp(OIC_JSON_SVC_NAME, rsrcName) && svcCborLen > 0)
+            {
+                cborEncoderResult |= cbor_encode_text_string(&secRsrc, OIC_JSON_SVC_NAME, strlen(OIC_JSON_SVC_NAME));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SVC Name.");
+                cborEncoderResult |= cbor_encode_byte_string(&secRsrc, svcCbor, svcCborLen);
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SVC Value.");
+            }
+            if (0 != strcmp(OIC_JSON_CRED_NAME, rsrcName) && credCborLen > 0)
+            {
+                cborEncoderResult |= cbor_encode_text_string(&secRsrc, OIC_JSON_CRED_NAME, strlen(OIC_JSON_CRED_NAME));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Name.");
+                cborEncoderResult |= cbor_encode_byte_string(&secRsrc, credCbor, credCborLen);
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Value.");
+            }
+            if (0 != strcmp(OIC_JSON_PCONF_NAME, rsrcName) && pconfCborLen > 0)
+            {
+                cborEncoderResult |= cbor_encode_text_string(&secRsrc, OIC_JSON_PCONF_NAME, strlen(OIC_JSON_PCONF_NAME));
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Pconf Name.");
+                cborEncoderResult |= cbor_encode_byte_string(&secRsrc, pconfCbor, pconfCborLen);
+                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Pconf Value.");
+            }
+
+            cborEncoderResult |= cbor_encoder_close_container(&encoder, &secRsrc);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Array.");
 
-            // Replace the modified json object in existing SVR database json
-            cJSON_ReplaceItemInObject(jsonSVRDb, rsrcName, jsonDuplicateObj->child);
+            cborSize = encoder.ptr - outPayload;
         }
     }
+    else if (psPayload)
+    {
+        size_t size = psSize + 255;
+        outPayload = (uint8_t *)OICCalloc(1, size);
+        VERIFY_NON_NULL(TAG, outPayload, ERROR);
+        CborEncoder encoder;
+        cbor_encoder_init(&encoder, outPayload, size, 0);
 
-    // Generate string representation of updated SVR database json object
-    jsonSVRDbStr = cJSON_PrintUnformatted(jsonSVRDb);
-    VERIFY_NON_NULL(TAG,jsonSVRDbStr, ERROR);
+        CborEncoder secRsrc ;
+        cborEncoderResult |= cbor_encoder_create_map(&encoder, &secRsrc, CborIndefiniteLength);
+        cborEncoderResult |= cbor_encode_text_string(&secRsrc, rsrcName, strlen(rsrcName));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Value Tag");
+        cborEncoderResult |= cbor_encode_byte_string(&secRsrc, psPayload, psSize);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Value.");
+        cborEncoderResult |= cbor_encoder_close_container(&encoder, &secRsrc);
+        cborSize = encoder.ptr - outPayload;
+    }
 
-    // Update the persistent storage with new SVR database
-    ps = SRMGetPersistentStorageHandler();
-    if (ps && ps->open)
+    if (outPayload && cborSize > 0)
     {
-        FILE* fp = ps->open(SVR_DB_FILE_NAME, "w");
-        if (fp)
+        OIC_LOG_V(DEBUG, TAG, "Writting in the file. %zd", cborSize);
+        OCPersistentStorage* ps = SRMGetPersistentStorageHandler();
+        if (ps)
         {
-            size_t bytesWritten = ps->write(jsonSVRDbStr, 1, strlen(jsonSVRDbStr), fp);
-            if (bytesWritten == strlen(jsonSVRDbStr))
+            FILE *fp = ps->open(SVR_DB_DAT_FILE_NAME, "w+");
+            if (fp)
             {
-                ret = OC_STACK_OK;
+                size_t numberItems = ps->write(outPayload, 1, cborSize, fp);
+                if (cborSize == numberItems)
+                {
+                    OIC_LOG_V(DEBUG, TAG, "Written %zu bytes into SVR database file", cborSize);
+                    ret = OC_STACK_OK;
+                }
+                else
+                {
+                    OIC_LOG_V(ERROR, TAG, "Failed writing %zu in the database", numberItems);
+                }
+                ps->close(fp);
             }
-            OIC_LOG_V(DEBUG, TAG, "Written %zu bytes into SVR database file", bytesWritten);
-            ps->close(fp);
-            fp = NULL;
-        }
-        else
-        {
-            OIC_LOG (ERROR, TAG, "Unable to open SVR database file!! ");
+            else
+            {
+                OIC_LOG(ERROR, TAG, "File open failed.");
+            }
+
         }
+        OIC_LOG_V(DEBUG, TAG, "Writing in the file . %zd", cborSize);
     }
 
+    OIC_LOG(DEBUG,  TAG, "Exiting UpdateSecureResourceInPS OUT");
+
 exit:
-    OICFree(jsonSVRDbStr);
-    cJSON_Delete(jsonSVRDb);
+    OICFree(dbData);
+    OICFree(outPayload);
+
+    OICFree(aclCbor);
+    OICFree(pstatCbor);
+    OICFree(amaclCbor);
+    OICFree(doxmCbor);
+    OICFree(svcCbor);
+    OICFree(credCbor);
 
     return ret;
 }
index d3ecc27..2fb01c0 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+#include <stdlib.h>
+#include <string.h>
+
 #include "ocstack.h"
-#include "logger.h"
 #include "oic_malloc.h"
-#include "cJSON.h"
+#include "ocpayload.h"
+#include "payload_logging.h"
 #include "resourcemanager.h"
 #include "pstatresource.h"
 #include "doxmresource.h"
 #include "psinterface.h"
-#include "utlist.h"
-#include "base64.h"
 #include "srmresourcestrings.h"
 #include "srmutility.h"
-#include <stdlib.h>
-#include <string.h>
 
 #define TAG  "SRM-PSTAT"
 
+/** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
+ * The value of payload size is increased until reaching below max cbor size. */
+static const uint8_t CBOR_SIZE = 255;
+
+// Max cbor size payload.
+static const uint16_t CBOR_MAX_SIZE = 4400;
+
+// PSTAT Map size - Number of mandatory items
+static const uint8_t PSTAT_MAP_SIZE = 7;
+
 static OicSecDpom_t gSm = SINGLE_SERVICE_CLIENT_DRIVEN;
 static OicSecPstat_t gDefaultPstat =
 {
@@ -66,156 +75,248 @@ void DeletePstatBinData(OicSecPstat_t* pstat)
     }
 }
 
-char * BinToPstatJSON(const OicSecPstat_t * pstat)
+OCStackResult PstatToCBORPayload(const OicSecPstat_t *pstat, uint8_t **payload, size_t *size)
 {
-    if(NULL == pstat)
+    if (NULL == pstat || NULL == payload || NULL != *payload || NULL == size)
     {
-        return NULL;
+        return OC_STACK_INVALID_PARAM;
     }
 
-    cJSON *jsonPstat = NULL;
-    char *jsonStr = NULL;
-    cJSON *jsonSmArray = NULL;
-    char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*) 0)->id)) + 1] = {};
-    uint32_t outLen = 0;
-    B64Result b64Ret = B64_OK;
+    size_t cborLen = *size;
+    if (0 == cborLen)
+    {
+        cborLen = CBOR_SIZE;
+    }
 
-    cJSON *jsonRoot = cJSON_CreateObject();
-    VERIFY_NON_NULL(TAG, jsonRoot, INFO);
+    *payload = NULL;
+    *size = 0;
 
-    cJSON_AddItemToObject(jsonRoot, OIC_JSON_PSTAT_NAME, jsonPstat=cJSON_CreateObject());
-    cJSON_AddBoolToObject(jsonPstat, OIC_JSON_ISOP_NAME, pstat->isOp);
+    OCStackResult ret = OC_STACK_ERROR;
 
-    b64Ret = b64Encode(pstat->deviceID.id,
-            sizeof(pstat->deviceID.id), base64Buff, sizeof(base64Buff), &outLen);
-    VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
+    CborEncoder encoder = { {.ptr = NULL }, .end = 0 };
+    CborEncoder pstatMap = { {.ptr = NULL }, .end = 0 };
+
+    int64_t cborEncoderResult = CborNoError;
+
+    uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
+    VERIFY_NON_NULL(TAG, outPayload, ERROR);
+    cbor_encoder_init(&encoder, outPayload, cborLen, 0);
+
+    cborEncoderResult |= cbor_encoder_create_map(&encoder, &pstatMap, PSTAT_MAP_SIZE);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Pstat Map.");
+
+    cborEncoderResult |= cbor_encode_text_string(&pstatMap, OIC_JSON_ISOP_NAME,
+        strlen(OIC_JSON_ISOP_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ISOP Name Tag.");
+    cborEncoderResult |= cbor_encode_boolean(&pstatMap, pstat->isOp);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ISOP Name Value.");
+
+    cborEncoderResult |= cbor_encode_text_string(&pstatMap, OIC_JSON_DEVICE_ID_NAME,
+        strlen(OIC_JSON_DEVICE_ID_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Tag.");
+    cborEncoderResult |= cbor_encode_byte_string(&pstatMap, (uint8_t *)pstat->deviceID.id,
+                                                sizeof(pstat->deviceID.id));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Value.");
+
+    cborEncoderResult |= cbor_encode_text_string(&pstatMap, OIC_JSON_COMMIT_HASH_NAME,
+        strlen(OIC_JSON_COMMIT_HASH_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Commit Hash Tag.");
+    cborEncoderResult |= cbor_encode_int(&pstatMap, pstat->commitHash);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Commit Hash Value.");
+
+    cborEncoderResult |= cbor_encode_text_string(&pstatMap, OIC_JSON_CM_NAME,
+        strlen(OIC_JSON_CM_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding CM Name Tag.");
+    cborEncoderResult |= cbor_encode_int(&pstatMap, pstat->cm);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding CM Name Value.");
+
+    cborEncoderResult |= cbor_encode_text_string(&pstatMap, OIC_JSON_TM_NAME,
+        strlen(OIC_JSON_TM_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding TM Name Tag.");
+    cborEncoderResult |= cbor_encode_int(&pstatMap, pstat->tm);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding TM Name Value.");
+
+    cborEncoderResult |= cbor_encode_text_string(&pstatMap, OIC_JSON_OM_NAME,
+        strlen(OIC_JSON_OM_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding OM Name Tag.");
+    cborEncoderResult |= cbor_encode_int(&pstatMap, pstat->om);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding OM Name Value.");
+
+    cborEncoderResult |= cbor_encode_text_string(&pstatMap, OIC_JSON_SM_NAME,
+        strlen(OIC_JSON_SM_NAME));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SM Name Tag.");
+    {
+        CborEncoder sm;
+        cborEncoderResult |= cbor_encoder_create_array(&pstatMap, &sm, pstat->smLen);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SM Array.");
 
-    cJSON_AddStringToObject(jsonPstat, OIC_JSON_DEVICE_ID_NAME, base64Buff);
-    cJSON_AddNumberToObject(jsonPstat, OIC_JSON_COMMIT_HASH_NAME, pstat->commitHash);
-    cJSON_AddNumberToObject(jsonPstat, OIC_JSON_CM_NAME, (int)pstat->cm);
-    cJSON_AddNumberToObject(jsonPstat, OIC_JSON_TM_NAME, (int)pstat->tm);
-    cJSON_AddNumberToObject(jsonPstat, OIC_JSON_OM_NAME, (int)pstat->om);
+        for (size_t i = 0; i < pstat->smLen; i++)
+        {
+            cborEncoderResult |= cbor_encode_int(&sm, pstat->sm[i]);
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SM Value in Array.");
+        }
+        cborEncoderResult |= cbor_encoder_close_container(&pstatMap, &sm);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing SM Array.");
+    }
+    cborEncoderResult |= cbor_encoder_close_container(&encoder, &pstatMap);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Closing PSTAT Map.");
 
-    cJSON_AddItemToObject(jsonPstat, OIC_JSON_SM_NAME, jsonSmArray = cJSON_CreateArray());
-    VERIFY_NON_NULL(TAG, jsonSmArray, INFO);
-    for (size_t i = 0; i < pstat->smLen; i++)
+    if (CborNoError == cborEncoderResult)
     {
-        cJSON_AddItemToArray(jsonSmArray, cJSON_CreateNumber((int )pstat->sm[i]));
+        *size = encoder.ptr - outPayload;
+        *payload = outPayload;
+        ret = OC_STACK_OK;
     }
-    jsonStr = cJSON_Print(jsonRoot);
-
 exit:
-    if (jsonRoot)
+    if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
+    {
+        // reallocate and try again!
+        OICFree(outPayload);
+        // Since the allocated initial memory failed, double the memory.
+        cborLen += encoder.ptr - encoder.end;
+        cborEncoderResult = CborNoError;
+        ret = PstatToCBORPayload(pstat, payload, &cborLen);
+        if (OC_STACK_OK == ret)
+        {
+            *size = cborLen;
+        }
+    }
+
+    if ((CborNoError != cborEncoderResult) || (OC_STACK_OK != ret))
     {
-        cJSON_Delete(jsonRoot);
+        OICFree(outPayload);
+        outPayload = NULL;
+        *payload = NULL;
+        *size = 0;
+        ret = OC_STACK_ERROR;
     }
-    return jsonStr;
+
+    return ret;
 }
 
-OicSecPstat_t * JSONToPstatBin(const char * jsonStr)
+OCStackResult CBORPayloadToPstat(const uint8_t *cborPayload, const size_t size,
+                                 OicSecPstat_t **secPstat)
 {
-    if(NULL == jsonStr)
+    if (NULL == cborPayload || NULL == secPstat || NULL != *secPstat)
     {
-        return NULL;
+        return OC_STACK_INVALID_PARAM;
     }
 
     OCStackResult ret = OC_STACK_ERROR;
+    *secPstat = NULL;
+
+    CborValue pstatCbor;
+    CborParser parser;
+    CborError cborFindResult = CborNoError;
+    int cborLen = size;
+    size_t len = 0;
+    if (0 == size)
+    {
+        cborLen = CBOR_SIZE;
+    }
+    cbor_parser_init(cborPayload, cborLen, 0, &parser, &pstatCbor);
+    CborValue pstatMap;
+
     OicSecPstat_t *pstat = NULL;
-    cJSON *jsonPstat = NULL;
-    cJSON *jsonObj = NULL;
-
-    unsigned char base64Buff[sizeof(((OicUuid_t*) 0)->id)] = {};
-    uint32_t outLen = 0;
-    B64Result b64Ret = B64_OK;
-
-    cJSON *jsonRoot = cJSON_Parse(jsonStr);
-    VERIFY_NON_NULL(TAG, jsonRoot, INFO);
-
-    jsonPstat = cJSON_GetObjectItem(jsonRoot, OIC_JSON_PSTAT_NAME);
-    VERIFY_NON_NULL(TAG, jsonPstat, INFO);
-
-    pstat = (OicSecPstat_t*)OICCalloc(1, sizeof(OicSecPstat_t));
-    VERIFY_NON_NULL(TAG, pstat, INFO);
-    jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_ISOP_NAME);
-    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-    VERIFY_SUCCESS(TAG, (cJSON_True == jsonObj->type || cJSON_False == jsonObj->type) , ERROR);
-    pstat->isOp = jsonObj->valueint;
-
-    jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_DEVICE_ID_NAME);
-    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-    VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
-    b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff,
-                sizeof(base64Buff), &outLen);
-    VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(pstat->deviceID.id)), ERROR);
-    memcpy(pstat->deviceID.id, base64Buff, outLen);
-
-    jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_COMMIT_HASH_NAME);
-    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-    VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
-    pstat->commitHash  = jsonObj->valueint;
-
-    jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_CM_NAME);
-    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-    VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
-    pstat->cm  = (OicSecDpm_t)jsonObj->valueint;
-
-    jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_OM_NAME);
-    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-    VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
-    pstat->om  = (OicSecDpom_t)jsonObj->valueint;
-
-    jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_SM_NAME);
-    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-    if (cJSON_Array == jsonObj->type)
+    cborFindResult = cbor_value_enter_container(&pstatCbor, &pstatMap);
+    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding PSTAT Map.");
+
+    pstat = (OicSecPstat_t *)OICCalloc(1, sizeof(OicSecPstat_t));
+    VERIFY_NON_NULL(TAG, pstat, ERROR);
+
+    cborFindResult = cbor_value_map_find_value(&pstatCbor, OIC_JSON_ISOP_NAME, &pstatMap);
+    if (CborNoError == cborFindResult && cbor_value_is_boolean(&pstatMap))
+    {
+        cborFindResult = cbor_value_get_boolean(&pstatMap, &pstat->isOp);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding isOp Value.");
+    }
+
+    cborFindResult = cbor_value_map_find_value(&pstatCbor, OIC_JSON_DEVICE_ID_NAME, &pstatMap);
+    if (CborNoError == cborFindResult && cbor_value_is_byte_string(&pstatMap))
+    {
+        uint8_t *subjectId = NULL;
+        cborFindResult = cbor_value_dup_byte_string(&pstatMap, &subjectId, &len, NULL);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding subjectId Value.");
+        memcpy(pstat->deviceID.id, subjectId, len);
+        OICFree(subjectId);
+    }
+
+    cborFindResult = cbor_value_map_find_value(&pstatCbor, OIC_JSON_COMMIT_HASH_NAME, &pstatMap);
+    if (CborNoError == cborFindResult && cbor_value_is_integer(&pstatMap))
     {
-        pstat->smLen = (size_t)cJSON_GetArraySize(jsonObj);
-        size_t idxx = 0;
-        VERIFY_SUCCESS(TAG, pstat->smLen != 0, ERROR);
-        pstat->sm = (OicSecDpom_t*)OICCalloc(pstat->smLen, sizeof(OicSecDpom_t));
+        cborFindResult = cbor_value_get_int(&pstatMap, (int *) &pstat->commitHash);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding commitHash.");
+    }
+
+    cborFindResult = cbor_value_map_find_value(&pstatCbor, OIC_JSON_CM_NAME, &pstatMap);
+    if (CborNoError == cborFindResult && cbor_value_is_integer(&pstatMap))
+    {
+        cborFindResult = cbor_value_get_int(&pstatMap, (int *) &pstat->cm);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding CM.");
+    }
+
+    cborFindResult = cbor_value_map_find_value(&pstatCbor, OIC_JSON_OM_NAME, &pstatMap);
+    if (CborNoError == cborFindResult && cbor_value_is_integer(&pstatMap))
+    {
+        cborFindResult = cbor_value_get_int(&pstatMap, (int *) &pstat->om);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding OM.");
+    }
+
+    cborFindResult = cbor_value_map_find_value(&pstatCbor, OIC_JSON_SM_NAME, &pstatMap);
+    if (CborNoError == cborFindResult && cbor_value_is_array(&pstatMap))
+    {
+        CborValue sm = { .parser = NULL };
+        cborFindResult = cbor_value_get_array_length(&pstatMap, &pstat->smLen);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Array Len.");
+
+        pstat->sm = (OicSecDpom_t *)OICCalloc(pstat->smLen, sizeof(OicSecDpom_t));
         VERIFY_NON_NULL(TAG, pstat->sm, ERROR);
-        do
+
+        cborFindResult = cbor_value_enter_container(&pstatMap, &sm);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering SM.");
+
+        int i = 0;
+        while (cbor_value_is_valid(&sm))
         {
-            cJSON *jsonSm = cJSON_GetArrayItem(jsonObj, idxx);
-            VERIFY_NON_NULL(TAG, jsonSm, ERROR);
-            pstat->sm[idxx] = (OicSecDpom_t)jsonSm->valueint;
-        }while ( ++idxx < pstat->smLen);
+            cborFindResult = cbor_value_get_int(&sm, (int *)&pstat->sm[i++]);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SM.");
+            cborFindResult = cbor_value_advance(&sm);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Closing SM.");
+        }
     }
+
+    *secPstat = pstat;
     ret = OC_STACK_OK;
 
 exit:
-    cJSON_Delete(jsonRoot);
-    if (OC_STACK_OK != ret)
+    if (CborNoError != cborFindResult)
     {
-        OIC_LOG (ERROR, TAG, "JSONToPstatBin failed");
+        OIC_LOG(ERROR, TAG, "CBORPayloadToPstat failed");
         DeletePstatBinData(pstat);
         pstat = NULL;
+        ret = OC_STACK_ERROR;
     }
-    return pstat;
+
+    return ret;
 }
 
 /**
  * Function to update persistent storage
  */
-static bool UpdatePersistentStorage(OicSecPstat_t * pstat)
+static bool UpdatePersistentStorage(OicSecPstat_t *pstat)
 {
     bool bRet = false;
 
-    if (pstat)
+    size_t size = 0;
+    uint8_t *cborPayload = NULL;
+    OCStackResult ret = PstatToCBORPayload(pstat, &cborPayload, &size);
+    if (OC_STACK_OK == ret)
     {
-        // Convert pstat data into JSON for update to persistent storage
-        char *jsonStr = BinToPstatJSON(pstat);
-        if (jsonStr)
+        if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_PSTAT_NAME, cborPayload, size))
         {
-            cJSON *jsonPstat = cJSON_Parse(jsonStr);
-            OICFree(jsonStr);
-
-            if (jsonPstat &&
-                (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_PSTAT_NAME, jsonPstat)))
-            {
-                bRet = true;
-            }
-            cJSON_Delete(jsonPstat);
+            bRet = true;
         }
+        OICFree(cborPayload);
     }
 
     return bRet;
@@ -227,16 +328,19 @@ static bool UpdatePersistentStorage(OicSecPstat_t * pstat)
  */
 static OCEntityHandlerResult HandlePstatGetRequest (const OCEntityHandlerRequest * ehRequest)
 {
-    OIC_LOG (INFO, TAG, "HandlePstatGetRequest  processing GET request");
-   // Convert ACL data into JSON for transmission
-    char* jsonStr = BinToPstatJSON(gPstat);
+    OIC_LOG(INFO, TAG, "HandlePstatGetRequest  processing GET request");
+
+    // Convert ACL data into CBOR for transmission
+    size_t size = 0;
+    uint8_t *payload = NULL;
+    OCStackResult res = PstatToCBORPayload(gPstat, &payload, &size);
 
-    // A device should always have a default pstat. Therefore, jsonStr should never be NULL.
-    OCEntityHandlerResult ehRet = (jsonStr ? OC_EH_OK : OC_EH_ERROR);
+    // A device should always have a default pstat. Therefore, payload should never be NULL.
+    OCEntityHandlerResult ehRet = (res == OC_STACK_OK) ? OC_EH_OK : OC_EH_ERROR;
 
     // Send response payload to request originator
-    SendSRMResponse(ehRequest, ehRet, jsonStr);
-    OICFree(jsonStr);
+    SendSRMCBORResponse(ehRequest, ehRet, payload, size);
+    OICFree(payload);
     return ehRet;
 }
 
@@ -249,56 +353,54 @@ static OCEntityHandlerResult HandlePstatGetRequest (const OCEntityHandlerRequest
 static OCEntityHandlerResult HandlePstatPutRequest(const OCEntityHandlerRequest *ehRequest)
 {
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
-    cJSON *postJson = NULL;
-    OIC_LOG (INFO, TAG, "HandlePstatPutRequest  processing PUT request");
+    OIC_LOG(INFO, TAG, "HandlePstatPutRequest  processing PUT request");
+    OicSecPstat_t *pstat = NULL;
 
     if (ehRequest->resource)
     {
-        postJson = cJSON_Parse(((OCSecurityPayload*)ehRequest->payload)->securityData);
-        VERIFY_NON_NULL(TAG, postJson, INFO);
-        cJSON *jsonPstat = cJSON_GetObjectItem(postJson, OIC_JSON_PSTAT_NAME);
-        VERIFY_NON_NULL(TAG, jsonPstat, INFO);
-        cJSON *commitHashJson = cJSON_GetObjectItem(jsonPstat, OIC_JSON_COMMIT_HASH_NAME);
-        uint16_t commitHash = 0;
-        if (commitHashJson)
-        {
-            commitHash = commitHashJson->valueint;
-        }
-        cJSON *tmJson = cJSON_GetObjectItem(jsonPstat, OIC_JSON_TM_NAME);
-        if (tmJson && gPstat)
+        uint8_t *payload = ((OCSecurityPayload *) ehRequest->payload)->securityData1;
+        size_t size = ((OCSecurityPayload *) ehRequest->payload)->payloadSize;
+        VERIFY_NON_NULL(TAG, payload, ERROR);
+
+        OCStackResult ret = CBORPayloadToPstat(payload, size, &pstat);
+        OICFree(payload);
+        VERIFY_NON_NULL(TAG, pstat, ERROR);
+        if (OC_STACK_OK == ret)
         {
-            gPstat->tm = (OicSecDpm_t)tmJson->valueint;
-            if(0 == tmJson->valueint && gPstat->commitHash == commitHash)
+            if (pstat->tm != NORMAL)
             {
-                gPstat->isOp = true;
-                gPstat->cm = NORMAL;
-                OIC_LOG (INFO, TAG, "CommitHash is valid and isOp is TRUE");
-            }
-            else
-            {
-                OIC_LOG (INFO, TAG, "CommitHash is not valid");
+                gPstat->tm = pstat->tm;
+                if(0 == pstat->tm && gPstat->commitHash == pstat->commitHash)
+                {
+                    gPstat->isOp = true;
+                    gPstat->cm = NORMAL;
+                    OIC_LOG (INFO, TAG, "CommitHash is valid and isOp is TRUE");
+                }
+                else
+                {
+                    OIC_LOG(DEBUG, TAG, "CommitHash is not valid");
+                }
             }
-        }
-        cJSON *omJson = cJSON_GetObjectItem(jsonPstat, OIC_JSON_OM_NAME);
-        if (omJson && gPstat)
-        {
-            /*
-             * Check if the operation mode is in the supported provisioning services
-             * operation mode list.
-             */
-            for(size_t i=0; i< gPstat->smLen; i++)
+            if (pstat->om != MULTIPLE_SERVICE_SERVER_DRIVEN && gPstat)
             {
-                if(gPstat->sm[i] == (unsigned int)omJson->valueint)
+                /*
+                 * Check if the operation mode is in the supported provisioning services
+                 * operation mode list.
+                 */
+                for (size_t i=0; i< gPstat->smLen; i++)
                 {
-                    gPstat->om = (OicSecDpom_t)omJson->valueint;
-                    break;
+                    if(gPstat->sm[i] == pstat->om)
+                    {
+                        gPstat->om = pstat->om;
+                        break;
+                    }
                 }
             }
-        }
-        // Convert pstat data into JSON for update to persistent storage
-        if(UpdatePersistentStorage(gPstat))
-        {
-            ehRet = OC_EH_OK;
+            // Convert pstat data into CBOR for update to persistent storage
+            if (UpdatePersistentStorage(gPstat))
+            {
+                ehRet = OC_EH_OK;
+            }
         }
     }
  exit:
@@ -313,27 +415,27 @@ static OCEntityHandlerResult HandlePstatPutRequest(const OCEntityHandlerRequest
     }
 
     //Send payload to request originator
-    if(OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, NULL))
+    if(OC_STACK_OK != SendSRMCBORResponse(ehRequest, ehRet, NULL, 0))
     {
         OIC_LOG (ERROR, TAG, "SendSRMResponse failed in HandlePstatPostRequest");
     }
-    cJSON_Delete(postJson);
+    DeletePstatBinData(pstat);
     return ehRet;
 }
 
 /**
  * This internal method is the entity handler for pstat resources.
  */
-OCEntityHandlerResult PstatEntityHandler(OCEntityHandlerFlag flag,
-        OCEntityHandlerRequest * ehRequest,
-        void *callbackParam)
+ OCEntityHandlerResult PstatEntityHandler(OCEntityHandlerFlag flag,
+                                          OCEntityHandlerRequest * ehRequest,
+                                          void *callbackParam)
 {
     (void)callbackParam;
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
     // This method will handle REST request (GET/POST) for /oic/sec/pstat
     if (flag & OC_REQUEST_FLAG)
     {
-        OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
+        OIC_LOG(INFO, TAG, "Flag includes OC_REQUEST_FLAG");
         switch (ehRequest->method)
         {
             case OC_REST_GET:
@@ -344,7 +446,7 @@ OCEntityHandlerResult PstatEntityHandler(OCEntityHandlerFlag flag,
                 break;
             default:
                 ehRet = OC_EH_ERROR;
-                SendSRMResponse(ehRequest, ehRet, NULL);
+                SendSRMCBORResponse(ehRequest, ehRet, NULL, 0);
                 break;
         }
     }
@@ -354,84 +456,78 @@ OCEntityHandlerResult PstatEntityHandler(OCEntityHandlerFlag flag,
 /**
  * This internal method is used to create '/oic/sec/pstat' resource.
  */
-OCStackResult CreatePstatResource()
+ OCStackResult CreatePstatResource()
 {
-    OCStackResult ret;
+    OCStackResult ret = OCCreateResource(&gPstatHandle,
+                                         OIC_RSRC_TYPE_SEC_PSTAT,
+                                         OIC_MI_DEF,
+                                         OIC_RSRC_PSTAT_URI,
+                                         PstatEntityHandler,
+                                         NULL,
+                                         OC_RES_PROP_NONE);
 
-    ret = OCCreateResource(&gPstatHandle,
-                           OIC_RSRC_TYPE_SEC_PSTAT,
-                           OIC_MI_DEF,
-                           OIC_RSRC_PSTAT_URI,
-                           PstatEntityHandler,
-                           NULL,
-                           OC_RES_PROP_NONE);
-
-    if (ret != OC_STACK_OK)
+    if (OC_STACK_OK != ret)
     {
-        OIC_LOG (FATAL, TAG, "Unable to instantiate pstat resource");
+        OIC_LOG(FATAL, TAG, "Unable to instantiate pstat resource");
         DeInitPstatResource();
     }
     return ret;
 }
 
 /**
- * Post ACL hander update the commitHash during ACL provisioning.
- */
-void SetCommitHash(uint16_t commitHash)
-{
-    gPstat->commitHash = commitHash;
-}
-
-/**
- * Get the default value
- * @retval  the gDefaultPstat pointer
+ * Get the default value.
+ *
+ * @return the gDefaultPstat pointer.
  */
 static OicSecPstat_t* GetPstatDefault()
 {
     return &gDefaultPstat;
 }
 
-/**
- * Initialize pstat resource by loading data from persistent storage.
- *
- * @retval  OC_STACK_OK for Success, otherwise some error value
- */
 OCStackResult InitPstatResource()
 {
     OCStackResult ret = OC_STACK_ERROR;
 
     // Read Pstat resource from PS
-    char* jsonSVRDatabase = GetSVRDatabase();
-    if (jsonSVRDatabase)
+    uint8_t *data = NULL;
+    size_t size = 0;
+    ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_PSTAT_NAME, &data, &size);
+    // If database read failed
+    if (OC_STACK_OK != ret)
     {
-        // Convert JSON Pstat into binary format
-        gPstat = JSONToPstatBin(jsonSVRDatabase);
+        OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
+    }
+    if (data)
+    {
+        // Read ACL resource from PS
+        ret = CBORPayloadToPstat(data, size, &gPstat);
+        OICFree(data);
     }
     /*
      * If SVR database in persistent storage got corrupted or
      * is not available for some reason, a default pstat is created
      * which allows user to initiate pstat provisioning again.
      */
-    if(!jsonSVRDatabase || !gPstat)
+    if ((OC_STACK_OK != ret) || !gPstat)
     {
         gPstat = GetPstatDefault();
     }
+    VERIFY_NON_NULL(TAG, gPstat, FATAL);
 
     // Instantiate 'oic.sec.pstat'
     ret = CreatePstatResource();
 
-    OICFree(jsonSVRDatabase);
+exit:
+    if (OC_STACK_OK != ret)
+    {
+        DeInitPstatResource();
+    }
     return ret;
 }
 
-/**
- * Perform cleanup for pstat resources.
- *
- * @retval  OC_STACK_OK for Success, otherwise some error value
- */
 OCStackResult DeInitPstatResource()
 {
-    if(gPstat != &gDefaultPstat)
+    if (gPstat != &gDefaultPstat)
     {
         DeletePstatBinData(gPstat);
         gPstat = NULL;
@@ -439,7 +535,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
@@ -458,7 +553,7 @@ void RestorePstatToInitState()
             gPstat->sm[0] = SINGLE_SERVICE_CLIENT_DRIVEN;
         }
 
-        if(!UpdatePersistentStorage(gPstat))
+        if (!UpdatePersistentStorage(gPstat))
         {
             OIC_LOG(ERROR, TAG, "Failed to revert DOXM in persistent storage");
         }
index 339ea48..90a4583 100644 (file)
@@ -18,6 +18,7 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+#include <string.h>
 #include "resourcemanager.h"
 #include "securevirtualresourcetypes.h"
 #include "aclresource.h"
@@ -30,7 +31,6 @@
 #include "oic_string.h"
 #include "logger.h"
 #include "utlist.h"
-#include <string.h>
 
 //#ifdef DIRECT_PAIRING
 #include "pconfresource.h"
 #include "crlresource.h"
 #endif // __WITH_X509__
 
-/**
- * This method is used by all secure resource modules to send responses to REST queries.
- *
- * @param ehRequest pointer to entity handler request data structure.
- * @param ehRet result code from entity handler.
- * @param rspPayload response payload in JSON.
- *
- * @retval  OC_STACK_OK for Success, otherwise some error value
- */
 OCStackResult SendSRMResponse(const OCEntityHandlerRequest *ehRequest,
         OCEntityHandlerResult ehRet, const char *rspPayload)
 {
@@ -74,11 +65,31 @@ OCStackResult SendSRMResponse(const OCEntityHandlerRequest *ehRequest,
     return OC_STACK_ERROR;
 }
 
-/**
- * Initialize all secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
- *
- * @retval  OC_STACK_OK for Success, otherwise some error value
- */
+OCStackResult SendSRMCBORResponse(const OCEntityHandlerRequest *ehRequest,
+        OCEntityHandlerResult ehRet, uint8_t *cborPayload, size_t size)
+{
+    OIC_LOG(DEBUG, TAG, "SRM sending SRM response");
+    OCEntityHandlerResponse response = {.requestHandle = NULL};
+    OCStackResult ret = OC_STACK_ERROR;
+
+    if (ehRequest)
+    {
+        OCSecurityPayload ocPayload = {.base = {.type = PAYLOAD_TYPE_INVALID}};
+
+        response.requestHandle = ehRequest->requestHandle;
+        response.resourceHandle = ehRequest->resource;
+        response.ehResult = ehRet;
+        response.payload = (OCPayload *)(&ocPayload);
+        response.payload->type = PAYLOAD_TYPE_SECURITY;
+        ((OCSecurityPayload *)response.payload)->securityData1 = cborPayload;
+        ((OCSecurityPayload *)response.payload)->payloadSize = size;
+        response.persistentBufferFlag = 0;
+
+        ret = OCDoResponse(&response);
+    }
+    return ret;
+}
+
 OCStackResult InitSecureResources( )
 {
     OCStackResult ret;
@@ -134,11 +145,6 @@ OCStackResult InitSecureResources( )
     return ret;
 }
 
-/**
- * Perform cleanup for secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
- *
- * @retval  OC_STACK_OK for Success, otherwise some error value
- */
 OCStackResult DestroySecureResources( )
 {
     DeInitACLResource();
index 02fe6ed..7c233be 100644 (file)
@@ -56,21 +56,11 @@ static SPResponseCallback gSPResponseHandler = NULL;
  */
 PEContext_t g_policyEngineContext;
 
-/**
- * @brief function to register provisoning API's response callback.
- * @param respHandler response handler callback.
- */
-void SRMRegisterProvisioningResponseHandler(SPResponseCallback respHandler)
-{
-    gSPResponseHandler = respHandler;
-}
-
-
 static void SRMSendUnAuthorizedAccessresponse(PEContext_t *context)
 {
     CAResponseInfo_t responseInfo = {.result = CA_EMPTY};
 
-    if(NULL == context ||
+    if (NULL == context ||
        NULL == context->amsMgrContext->requestInfo)
     {
         OIC_LOG_V(ERROR, TAG, "%s : NULL Parameter(s)",__func__);
@@ -92,7 +82,6 @@ static void SRMSendUnAuthorizedAccessresponse(PEContext_t *context)
     }
 }
 
-
 void SRMSendResponse(SRMAccessResponse_t responseVal)
 {
     OIC_LOG(DEBUG, TAG, "Sending response to remote device");
@@ -121,12 +110,11 @@ exit:
     SetPolicyEngineState(&g_policyEngineContext, AWAITING_REQUEST);
 }
 
-
 /**
- * @brief   Handle the request from the SRM.
- * @param   endPoint       [IN] Endpoint object from which the response is received.
- * @param   requestInfo    [IN] Information for the request.
- * @return  NONE
+ * Handle the request from the SRM.
+ *
+ * @param endPoint object from which the response is received.
+ * @param requestInfo contains information for the request.
  */
 void SRMRequestHandler(const CAEndpoint_t *endPoint, const CARequestInfo_t *requestInfo)
 {
@@ -164,7 +152,7 @@ void SRMRequestHandler(const CAEndpoint_t *endPoint, const CARequestInfo_t *requ
     OICStrcpyPartial(newUri, MAX_URI_LENGTH + 1, requestInfo->info.resourceUri, position);
 
     //New request are only processed if the policy engine state is AWAITING_REQUEST.
-    if(AWAITING_REQUEST == g_policyEngineContext.state)
+    if (AWAITING_REQUEST == g_policyEngineContext.state)
     {
         OIC_LOG_V(DEBUG, TAG, "Processing request with uri, %s for method, %d",
                 requestInfo->info.resourceUri, requestInfo->method);
@@ -189,7 +177,7 @@ void SRMRequestHandler(const CAEndpoint_t *endPoint, const CARequestInfo_t *requ
 
     VERIFY_NON_NULL(TAG, gRequestHandler, ERROR);
 
-    if(ACCESS_WAITING_FOR_AMS == response)
+    if (ACCESS_WAITING_FOR_AMS == response)
     {
         OIC_LOG(INFO, TAG, "Sending slow response");
 
@@ -222,10 +210,10 @@ exit:
 }
 
 /**
- * @brief   Handle the response from the SRM.
- * @param   endPoint     [IN] The remote endpoint.
- * @param   responseInfo [IN] Response information from the endpoint.
- * @return  NONE
+ * Handle the response from the SRM.
+ *
+ * @param endPoint points to the remote endpoint.
+ * @param responseInfo contains response information from the endpoint.
  */
 void SRMResponseHandler(const CAEndpoint_t *endPoint, const CAResponseInfo_t *responseInfo)
 {
@@ -248,12 +236,11 @@ void SRMResponseHandler(const CAEndpoint_t *endPoint, const CAResponseInfo_t *re
     }
 }
 
-
 /**
- * @brief   Handle the error from the SRM.
- * @param   endPoint  [IN] The remote endpoint.
- * @param   errorInfo [IN] Error information from the endpoint.
- * @return  NONE
+ * Handle the error from the SRM.
+ *
+ * @param endPoint is the remote endpoint.
+ * @param errorInfo contains error information from the endpoint.
  */
 void SRMErrorHandler(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
 {
@@ -265,16 +252,6 @@ void SRMErrorHandler(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInf
     }
 }
 
-
-/**
- * @brief   Register request and response callbacks.
- *          Requests and responses are delivered in these callbacks.
- * @param   reqHandler   [IN] Request handler callback ( for GET,PUT ..etc)
- * @param   respHandler  [IN] Response handler callback.
- * @return
- *     OC_STACK_OK    - No errors; Success
- *     OC_STACK_INVALID_PARAM - invalid parameter
- */
 OCStackResult SRMRegisterHandler(CARequestCallback reqHandler,
                                  CAResponseCallback respHandler,
                                  CAErrorCallback errHandler)
@@ -298,13 +275,6 @@ OCStackResult SRMRegisterHandler(CARequestCallback reqHandler,
     return OC_STACK_OK;
 }
 
-/**
- * @brief   Register Persistent storage callback.
- * @param   persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
- * @return
- *     OC_STACK_OK    - No errors; Success
- *     OC_STACK_INVALID_PARAM - Invalid parameter
- */
 OCStackResult SRMRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
 {
     OIC_LOG(DEBUG, TAG, "SRMRegisterPersistentStorageHandler !!");
@@ -317,22 +287,11 @@ OCStackResult SRMRegisterPersistentStorageHandler(OCPersistentStorage* persisten
     return OC_STACK_OK;
 }
 
-/**
- * @brief   Get Persistent storage handler pointer.
- * @return
- *     The pointer to Persistent Storage callback handler
- */
-
 OCPersistentStorage* SRMGetPersistentStorageHandler()
 {
     return gPersistentStorageHandler;
 }
 
-
-/**
- * @brief   Initialize all secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
- * @retval  OC_STACK_OK for Success, otherwise some error value
- */
 OCStackResult SRMInitSecureResources()
 {
     // TODO: temporarily returning OC_STACK_OK every time until default
@@ -355,38 +314,21 @@ OCStackResult SRMInitSecureResources()
     return ret;
 }
 
-/**
- * @brief   Perform cleanup for secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
- * @retval  none
- */
 void SRMDeInitSecureResources()
 {
     DestroySecureResources();
 }
 
-/**
- * @brief   Initialize Policy Engine.
- * @return  OC_STACK_OK for Success, otherwise some error value.
- */
 OCStackResult SRMInitPolicyEngine()
 {
     return InitPolicyEngine(&g_policyEngineContext);
 }
 
-/**
- * @brief   Cleanup Policy Engine.
- * @return  none
- */
 void SRMDeInitPolicyEngine()
 {
     return DeInitPolicyEngine(&g_policyEngineContext);
 }
 
-/**
- * @brief   Check the security resource URI.
- * @param   uri [IN] Pointers to security resource URI.
- * @return  true if the URI is one of security resources, otherwise false.
- */
 bool SRMIsSecurityResourceURI(const char* uri)
 {
     if (!uri)
index 34e92aa..b80e71e 100644 (file)
@@ -22,6 +22,7 @@
 #include "securevirtualresourcetypes.h"
 
 const char * SVR_DB_FILE_NAME = "oic_svr_db.json";
+const char * SVR_DB_DAT_FILE_NAME = "oic_svr_db.dat";
 const char * OIC_MI_DEF = "oic.mi.def";
 
 //AMACL
@@ -110,6 +111,8 @@ const char * OIC_JSON_SPM_NAME = "spm";
 const char * OIC_JSON_PDEVICE_ID_NAME = "pdeviceid";
 
 OicUuid_t WILDCARD_SUBJECT_ID = {"*"};
+OicUuid_t WILDCARD_SUBJECT_B64_ID = { .id = {'2', '2', '2', '2', '2', '2', '2', '2',
+                                             '2', '2', '2', '2', '2', '2', '2', '2' }};
 size_t WILDCARD_SUBJECT_ID_LEN = 1;
 const char * WILDCARD_RESOURCE_URI = "*";
 
index 8f8cc7f..f81b511 100644 (file)
 
 #define TAG  "SRM-UTILITY"
 
-/**
- * This method initializes the OicParseQueryIter_t struct
- *
- *@param query     - REST query, to be parsed
- *@param parseIter - OicParseQueryIter_t struct, to be initialized
- *
- */
-void ParseQueryIterInit(unsigned char * query, OicParseQueryIter_t * parseIter)
+void ParseQueryIterInit(const unsigned char * query, OicParseQueryIter_t * parseIter)
 {
-    OIC_LOG (INFO, TAG, "Initializing coap iterator");
-    if((NULL == query) || (NULL == parseIter))
+    OIC_LOG(INFO, TAG, "Initializing coap iterator");
+    if ((NULL == query) || (NULL == parseIter))
+    {
         return;
+    }
 
     parseIter->attrPos = NULL;
     parseIter->attrLen = 0;
     parseIter->valPos = NULL;
     parseIter->valLen = 0;
-    coap_parse_iterator_init(query, strlen((char *)query),
-          (unsigned char *)OIC_SEC_REST_QUERY_SEPARATOR, (unsigned char *) "", 0, &parseIter->pi);
+    coap_parse_iterator_init((unsigned char *)query, strlen((char *)query),
+                             (unsigned char *)OIC_SEC_REST_QUERY_SEPARATOR,
+                             (unsigned char *) "", 0, &parseIter->pi);
 }
 
-/**
- * This method fills the OicParseQueryIter_t struct with next REST query's
- * attribute's and value's information
- *
- *@param parseIter - OicParseQueryIter_t struct, has next query's attribute's & value's info
- *
- * @retval
- *     OicParseQueryIter_t *  - has parsed query info
- *     NULL                   - has no query to parse
- */
 OicParseQueryIter_t * GetNextQuery(OicParseQueryIter_t * parseIter)
 {
-    OIC_LOG (INFO, TAG, "Getting Next Query");
-    if(NULL == parseIter)
+    OIC_LOG(INFO, TAG, "Getting Next Query");
+    if (NULL == parseIter)
+    {
         return NULL;
+    }
 
     unsigned char * qrySeg = NULL;
     char * delimPos;
 
-    //Get the next query. Querys are separated by OIC_SEC_REST_QUERY_SEPARATOR
+    // Get the next query. Querys are separated by OIC_SEC_REST_QUERY_SEPARATOR.
     qrySeg = coap_parse_next(&parseIter->pi);
 
-    if(qrySeg)
+    if (qrySeg)
     {
         delimPos = strchr((char *)qrySeg, OIC_SEC_REST_QUERY_DELIMETER);
-        if(delimPos)
+        if (delimPos)
         {
             parseIter->attrPos = parseIter->pi.pos;
             parseIter->attrLen = (unsigned char *)delimPos - parseIter->pi.pos;
@@ -86,15 +74,14 @@ OicParseQueryIter_t * GetNextQuery(OicParseQueryIter_t * parseIter)
     return NULL;
 }
 
-
 // TODO This functionality is replicated in all SVR's and therefore we need
 // to encapsulate it in a common method. However, this may not be the right
 // file for this method.
-OCStackResult AddUuidArray(cJSON* jsonRoot, const char* arrayItem,
-                           size_t *numUuids, OicUuid_t** uuids )
+OCStackResult AddUuidArray(const cJSON* jsonRoot, const char* arrayItem,
+                           size_t *numUuids, OicUuid_t** uuids)
 {
     size_t idxx = 0;
-    cJSON* jsonObj = cJSON_GetObjectItem(jsonRoot, arrayItem);
+    cJSON* jsonObj = cJSON_GetObjectItem((cJSON *)jsonRoot, arrayItem);
     VERIFY_NON_NULL(TAG, jsonObj, ERROR);
     VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
 
@@ -115,10 +102,10 @@ OCStackResult AddUuidArray(cJSON* jsonRoot, const char* arrayItem,
 
         outLen = 0;
         b64Ret = b64Decode(jsonOwnr->valuestring, strlen(jsonOwnr->valuestring), base64Buff,
-                sizeof(base64Buff), &outLen);
+               sizeof(base64Buff), &outLen);
 
         VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof((*uuids)[idxx].id)),
-                ERROR);
+               ERROR);
         memcpy((*uuids)[idxx].id, base64Buff, outLen);
     } while ( ++idxx < *numUuids);
 
@@ -150,4 +137,3 @@ const char* GetOxmString(OicSecOxm_t oxmType)
             return NULL;
     }
 }
-
index bb55450..43f3fde 100644 (file)
 // limitations under the License.
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#include <stdlib.h>
+#include <string.h>
 
 #include "ocstack.h"
-#include "logger.h"
+#include "ocpayload.h"
 #include "oic_malloc.h"
-#include "cJSON.h"
-#include "base64.h"
+#include "utlist.h"
+#include "payload_logging.h"
 #include "resourcemanager.h"
 #include "psinterface.h"
 #include "svcresource.h"
-#include "utlist.h"
 #include "srmresourcestrings.h"
 #include "srmutility.h"
-#include <stdlib.h>
-#include <string.h>
+
+#include "security_internals.h"
 
 #define TAG  "SRM-SVC"
 
-OicSecSvc_t        *gSvc = NULL;
+/** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
+ * The value of payload size is increased until reaching belox max cbor size. */
+static const uint8_t CBOR_SIZE = 255;
+
+/** Max cbor size payload. */
+static const uint16_t CBOR_MAX_SIZE = 4400;
+
+/** SVC Map size - Number of mandatory items. */
+static const uint8_t SVC_MAP_SIZE = 3;
+
+static OicSecSvc_t        *gSvc = NULL;
 static OCResourceHandle    gSvcHandle = NULL;
 
 void DeleteSVCList(OicSecSvc_t* svc)
@@ -55,236 +66,310 @@ void DeleteSVCList(OicSecSvc_t* svc)
     }
 }
 
-/*
- * This internal method converts SVC data into JSON format.
- *
- * Note: Caller needs to invoke 'free' when finished done using
- * return string.
- */
-char * BinToSvcJSON(const OicSecSvc_t * svc)
+static size_t svcElementsCount(const OicSecSvc_t *secSvc)
 {
-    cJSON *jsonRoot = NULL;
-    char *jsonStr = NULL;
+    size_t size = 0;
+    for (const OicSecSvc_t *svc = secSvc; svc; svc = svc->next)
+    {
+        size++;
+    }
+    return size;
+}
 
-    if (svc)
+OCStackResult SVCToCBORPayload(const OicSecSvc_t *svc, uint8_t **cborPayload,
+                               size_t *cborSize)
+{
+    if (NULL == svc || NULL == cborPayload || NULL != *cborPayload || NULL == cborSize)
     {
-        jsonRoot = cJSON_CreateObject();
-        VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+       return OC_STACK_INVALID_PARAM;
+    }
 
-        cJSON *jsonSvcArray = NULL;
-        cJSON_AddItemToObject (jsonRoot, OIC_JSON_SVC_NAME, jsonSvcArray = cJSON_CreateArray());
-        VERIFY_NON_NULL(TAG, jsonSvcArray, ERROR);
+    size_t cborLen = *cborSize;
+    if (0 == cborLen)
+    {
+        cborLen = CBOR_SIZE;
+    }
+    *cborPayload = NULL;
+    *cborSize = 0;
 
-        while(svc)
-        {
-            char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};
-            uint32_t outLen = 0;
-            B64Result b64Ret = B64_OK;
+    int64_t cborEncoderResult = CborNoError;
+    OCStackResult ret = OC_STACK_ERROR;
+    CborEncoder encoder = { {.ptr = NULL }, .end = 0 };
+    CborEncoder svcArray = { {.ptr = NULL }, .end = 0 };
 
-            cJSON *jsonSvc = cJSON_CreateObject();
+    uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
+    VERIFY_NON_NULL(TAG, outPayload, ERROR);
 
-            // Service Device Identity
-            outLen = 0;
-            b64Ret = b64Encode(svc->svcdid.id, sizeof(OicUuid_t), base64Buff,
-                    sizeof(base64Buff), &outLen);
-            VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
-            cJSON_AddStringToObject(jsonSvc, OIC_JSON_SERVICE_DEVICE_ID, base64Buff );
+    cbor_encoder_init(&encoder, outPayload, cborLen, 0);
 
-            // Service Type
-            cJSON_AddNumberToObject (jsonSvc, OIC_JSON_SERVICE_TYPE, svc->svct);
+    // Create SVC Array
+    cborEncoderResult |= cbor_encoder_create_array(&encoder, &svcArray, svcElementsCount(svc));
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to Create SVC Array.");
 
-            // Owners
-            cJSON *jsonOwnrArray = NULL;
-            cJSON_AddItemToObject (jsonSvc, OIC_JSON_OWNERS_NAME, jsonOwnrArray = cJSON_CreateArray());
-            VERIFY_NON_NULL(TAG, jsonOwnrArray, ERROR);
-            for (unsigned int i = 0; i < svc->ownersLen; i++)
-            {
-                outLen = 0;
+    while (svc)
+    {
+        CborEncoder svcMap;
+        cborEncoderResult |= cbor_encoder_create_map(&svcArray, &svcMap, SVC_MAP_SIZE);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to Create SVC Map.");
+
+        // Service Device Identity
+        cborEncoderResult |= cbor_encode_text_string(&svcMap, OIC_JSON_SERVICE_DEVICE_ID,
+            strlen(OIC_JSON_SERVICE_DEVICE_ID));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to Add SVC Device Id.");
+        cborEncoderResult |= cbor_encode_byte_string(&svcMap, (uint8_t *)svc->svcdid.id,
+            sizeof(svc->svcdid.id));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to ");
+
+        // Service Type
+        cborEncoderResult |= cbor_encode_text_string(&svcMap, OIC_JSON_SERVICE_TYPE,
+            strlen(OIC_JSON_SERVICE_TYPE));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to Add SVC Serv Type Tag.");
+        cborEncoderResult |= cbor_encode_int(&svcMap, svc->svct);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to Add SVC Serv Type Value.");
+
+        // Owners
+        cborEncoderResult |= cbor_encode_text_string(&svcMap, OIC_JSON_OWNERS_NAME,
+            strlen(OIC_JSON_OWNERS_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to Add SVC Owners Tag.");
+        CborEncoder owners;
+        cborEncoderResult |= cbor_encoder_create_array(&svcMap, &owners, svc->ownersLen);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to Add SVC Array.");
+        for (size_t i = 0; i < svc->ownersLen; i++)
+        {
+            cborEncoderResult |= cbor_encode_byte_string(&owners, (uint8_t *)svc->owners[i].id,
+                sizeof(svc->owners[i].id));
+            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to Add SVC Owners Value.");
+        }
+        cborEncoderResult |= cbor_encoder_close_container(&svcMap, &owners);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to Close SVC Array.");
 
-                b64Ret = b64Encode(svc->owners[i].id, sizeof(((OicUuid_t*)0)->id), base64Buff,
-                        sizeof(base64Buff), &outLen);
-                VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
+        cborEncoderResult |= cbor_encoder_close_container(&svcArray, &svcMap);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to Close SVC Map.");
 
-                cJSON_AddItemToArray (jsonOwnrArray, cJSON_CreateString(base64Buff));
-            }
+        svc = svc->next;
+    }
 
-            // Attach current svc node to Svc Array
-            cJSON_AddItemToArray(jsonSvcArray, jsonSvc);
-            svc = svc->next;
-        }
+    cborEncoderResult |= cbor_encoder_close_container(&encoder, &svcArray);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to Close SVC Array.");
 
-        jsonStr = cJSON_PrintUnformatted(jsonRoot);
+    if (CborNoError == cborEncoderResult)
+    {
+        *cborPayload = outPayload;
+        *cborSize = encoder.ptr - outPayload;
+        ret = OC_STACK_OK;
     }
 
 exit:
-    if (jsonRoot)
+    if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
     {
-        cJSON_Delete(jsonRoot);
+        // reallocate and try again!
+        OICFree(outPayload);
+        outPayload = NULL;
+        // Since the allocated initial memory failed, double the memory.
+        cborLen += encoder.ptr - encoder.end;
+        cborEncoderResult = CborNoError;
+        ret = SVCToCBORPayload(svc, cborPayload, &cborLen);
+        *cborSize = cborLen;
     }
-    return jsonStr;
+
+    if (CborNoError != cborEncoderResult)
+    {
+        OICFree(outPayload);
+        outPayload = NULL;
+        *cborSize = 0;
+        *cborPayload = NULL;
+        ret = OC_STACK_ERROR;
+    }
+
+    return ret;
 }
 
-/*
- * This internal method converts JSON SVC into binary SVC.
- */
-OicSecSvc_t * JSONToSvcBin(const char * jsonStr)
+OCStackResult CBORPayloadToSVC(const uint8_t *cborPayload, size_t size,
+                               OicSecSvc_t **secSvc)
 {
+    if (NULL == cborPayload || NULL == secSvc || NULL != *secSvc)
+    {
+        return OC_STACK_INVALID_PARAM;
+    }
+
+    *secSvc = NULL;
+
     OCStackResult ret = OC_STACK_ERROR;
-    OicSecSvc_t * headSvc = NULL;
-    OicSecSvc_t * prevSvc = NULL;
-    cJSON *jsonRoot = NULL;
-    cJSON *jsonSvcArray = NULL;
 
-    VERIFY_NON_NULL(TAG, jsonStr, ERROR);
+    CborValue svcCbor;
+    CborParser parser;
+    CborError cborFindResult = CborNoError;
+    int cborLen = size;
+    if (0 == size)
+    {
+       cborLen = CBOR_SIZE;
+    }
+    cbor_parser_init(cborPayload, cborLen, 0, &parser, &svcCbor);
 
-    jsonRoot = cJSON_Parse(jsonStr);
-    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+    OicSecSvc_t *headSvc = NULL;
 
-    jsonSvcArray = cJSON_GetObjectItem(jsonRoot, OIC_JSON_SVC_NAME);
-    VERIFY_NON_NULL(TAG, jsonSvcArray, INFO);
+    CborValue svcArray;
+    cborFindResult = cbor_value_enter_container(&svcCbor, &svcArray);
+    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Enter SVC Array.");
 
-    if (cJSON_Array == jsonSvcArray->type)
+    while (cbor_value_is_valid(&svcArray))
     {
-        int numSvc = cJSON_GetArraySize(jsonSvcArray);
-        int idx = 0;
+        CborValue svcMap;
+        cborFindResult = cbor_value_enter_container(&svcArray, &svcMap);
+        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Enter SVC Map.");
+
+        OicSecSvc_t *svc = (OicSecSvc_t *) OICCalloc(1, sizeof(OicSecSvc_t));
+        VERIFY_NON_NULL(TAG, svc, ERROR);
 
-        VERIFY_SUCCESS(TAG, numSvc > 0, INFO);
-        do
+        while (cbor_value_is_valid(&svcMap))
         {
-            cJSON *jsonSvc = cJSON_GetArrayItem(jsonSvcArray, idx);
-            VERIFY_NON_NULL(TAG, jsonSvc, ERROR);
+            char* name = NULL;
+            size_t len = 0;
+            cborFindResult = cbor_value_dup_text_string(&svcMap, &name, &len, NULL);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Find Name.");
+            cborFindResult = cbor_value_advance(&svcMap);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Advance.");
 
-            OicSecSvc_t *svc = (OicSecSvc_t*)OICCalloc(1, sizeof(OicSecSvc_t));
-            VERIFY_NON_NULL(TAG, svc, ERROR);
+            CborType type = cbor_value_get_type(&svcMap);
 
-            headSvc = (headSvc) ? headSvc : svc;
-            if (prevSvc)
+            // Service Device Identity
+            if (0 == strcmp(OIC_JSON_SERVICE_DEVICE_ID, name))
             {
-                prevSvc->next = svc;
+                uint8_t *subjectId = NULL;
+                cborFindResult = cbor_value_dup_byte_string(&svcMap, &subjectId, &len, NULL);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Find SubjectId.");
+                memcpy(svc->svcdid.id, subjectId, len);
+                OICFree(subjectId);
             }
-
-            cJSON *jsonObj = NULL;
-
-            unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
-            uint32_t outLen = 0;
-            B64Result b64Ret = B64_OK;
-
-            // Service Device Identity
-            jsonObj = cJSON_GetObjectItem(jsonSvc, OIC_JSON_SERVICE_DEVICE_ID);
-            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-            VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
-            outLen = 0;
-            b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff,
-                        sizeof(base64Buff), &outLen);
-            VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(svc->svcdid.id)), ERROR);
-            memcpy(svc->svcdid.id, base64Buff, outLen);
-
             // Service Type
-            jsonObj = cJSON_GetObjectItem(jsonSvc, OIC_JSON_SERVICE_TYPE);
-            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-            VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
-            svc->svct = (OicSecSvcType_t)jsonObj->valueint;
-
-            // Resource Owners
-            jsonObj = cJSON_GetObjectItem(jsonSvc, OIC_JSON_OWNERS_NAME);
-            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
-            VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
-
-            svc->ownersLen = (size_t)cJSON_GetArraySize(jsonObj);
-            VERIFY_SUCCESS(TAG, svc->ownersLen > 0, ERROR);
-            svc->owners = (OicUuid_t*)OICCalloc(svc->ownersLen, sizeof(OicUuid_t));
-            VERIFY_NON_NULL(TAG, (svc->owners), ERROR);
-
-            size_t idxx = 0;
-            do
+            if (0 == strcmp(OIC_JSON_SERVICE_TYPE, name))
             {
-                cJSON *jsonOwnr = cJSON_GetArrayItem(jsonObj, idxx);
-                VERIFY_NON_NULL(TAG, jsonOwnr, ERROR);
-                VERIFY_SUCCESS(TAG, cJSON_String == jsonOwnr->type, ERROR);
-
-                outLen = 0;
-                b64Ret = b64Decode(jsonOwnr->valuestring, strlen(jsonOwnr->valuestring), base64Buff,
-                            sizeof(base64Buff), &outLen);
+                cborFindResult = cbor_value_get_int(&svcMap, (int *) &svc->svct);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Find SVCT.");
+            }
 
-                VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(svc->owners[idxx].id)),
-                                    ERROR);
-                memcpy(svc->owners[idxx].id, base64Buff, outLen);
-            } while ( ++idxx < svc->ownersLen);
+            // Owners -- Mandatory
+            if (0 == strcmp(OIC_JSON_OWNERS_NAME, name))
+            {
+                CborValue owners = { .parser = NULL };
+                cborFindResult = cbor_value_get_array_length(&svcMap, &svc->ownersLen);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Find Owner Len.");
+                cborFindResult = cbor_value_enter_container(&svcMap, &owners);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Enter Owner Array.");
+                int i = 0;
+                svc->owners = (OicUuid_t *)OICCalloc(svc->ownersLen, sizeof(*svc->owners));
+                VERIFY_NON_NULL(TAG, svc->owners, ERROR);
+                while (cbor_value_is_valid(&owners))
+                {
+                    uint8_t *owner = NULL;
+                    cborFindResult = cbor_value_dup_byte_string(&owners, &owner, &len, NULL);
+                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Find Owner Array Value.");
+                    cborFindResult = cbor_value_advance(&owners);
+                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Advance Owner Array.");
+                    memcpy(svc->owners[i++].id, owner, len);
+                    OICFree(owner);
+                }
+            }
+            if (CborMapType != type  && cbor_value_is_valid(&svcMap))
+            {
+                cborFindResult = cbor_value_advance(&svcMap);
+                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Advance SVC.");
+            }
+            OICFree(name);
+        }
 
-            prevSvc = svc;
-        } while( ++idx < numSvc);
+        svc->next = NULL;
+        if (NULL == headSvc)
+        {
+            headSvc = svc;
+        }
+        else
+        {
+            OicSecSvc_t *temp = headSvc;
+            while (temp->next)
+            {
+                temp = temp->next;
+            }
+            temp->next = svc;
+        }
+        if (cbor_value_is_valid(&svcArray))
+        {
+            cborFindResult = cbor_value_advance(&svcArray);
+            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Find Name.");
+        }
     }
-
+    *secSvc = headSvc;
     ret = OC_STACK_OK;
 
 exit:
-    cJSON_Delete(jsonRoot);
-    if (OC_STACK_OK != ret)
+    if (CborNoError != cborFindResult)
     {
         DeleteSVCList(headSvc);
         headSvc = NULL;
+        ret = OC_STACK_ERROR;
     }
-    return headSvc;
+    return ret;
 }
 
-static OCEntityHandlerResult HandleSVCGetRequest (const OCEntityHandlerRequest * ehRequest)
+static OCEntityHandlerResult HandleSVCGetRequest(const OCEntityHandlerRequest * ehRequest)
 {
     // Convert SVC data into JSON for transmission
-    char* jsonStr = BinToSvcJSON(gSvc);
-
-    OCEntityHandlerResult ehRet = (jsonStr ? OC_EH_OK : OC_EH_ERROR);
+    size_t size = 0;
+    uint8_t *cborSvc = NULL;
+    OCStackResult res =  SVCToCBORPayload(gSvc, &cborSvc, &size);
+    OCEntityHandlerResult ehRet = (res == OC_STACK_OK) ? OC_EH_OK : OC_EH_ERROR;
 
     // Send response payload to request originator
-    SendSRMResponse(ehRequest, ehRet, jsonStr);
+    SendSRMCBORResponse(ehRequest, ehRet, cborSvc, size);
 
-    OICFree(jsonStr);
+    OICFree(cborSvc);
 
     OIC_LOG_V (DEBUG, TAG, "%s RetVal %d", __func__ , ehRet);
     return ehRet;
 }
 
-static OCEntityHandlerResult HandleSVCPostRequest (const OCEntityHandlerRequest * ehRequest)
+static OCEntityHandlerResult HandleSVCPostRequest(const OCEntityHandlerRequest * ehRequest)
 {
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
-
-    // Convert JSON SVC data into binary. This will also validate the SVC data received.
-    OicSecSvc_t* newSvc = JSONToSvcBin(((OCSecurityPayload*)ehRequest->payload)->securityData);
-
-    if (newSvc)
+    uint8_t *payload = ((OCSecurityPayload *) ehRequest->payload)->securityData1;
+    size_t size = ((OCSecurityPayload *) ehRequest->payload)->payloadSize;
+    if (payload)
     {
-        // Append the new SVC to existing SVC
-        LL_APPEND(gSvc, newSvc);
-
-        // Convert SVC data into JSON for update to persistent storage
-        char *jsonStr = BinToSvcJSON(gSvc);
-        if (jsonStr)
+        // Convert CBOR SVC data into SVC. This will also validate the SVC data received.
+        OicSecSvc_t *newSvc = NULL;
+        OCStackResult res =  CBORPayloadToSVC(payload, size, &newSvc);
+        if (newSvc && res == OC_STACK_OK)
         {
-            cJSON *jsonSvc = cJSON_Parse(jsonStr);
-            OICFree(jsonStr);
-
-            if ((jsonSvc) &&
-                (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_SVC_NAME, jsonSvc)))
+            // Append the new SVC to existing SVC
+            LL_APPEND(gSvc, newSvc);
+
+            // Convert SVC data into JSON for update to persistent storage
+            size_t size = 0;
+            uint8_t *cborPayload = NULL;
+            res = SVCToCBORPayload(gSvc, &cborPayload, &size);
+            if (cborPayload && OC_STACK_OK == res &&
+                UpdateSecureResourceInPS(OIC_JSON_SVC_NAME, cborPayload, size) == OC_STACK_OK)
             {
                 ehRet = OC_EH_RESOURCE_CREATED;
             }
-            cJSON_Delete(jsonSvc);
+            OICFree(cborPayload);
         }
     }
 
     // Send payload to request originator
-    SendSRMResponse(ehRequest, ehRet, NULL);
+    SendSRMCBORResponse(ehRequest, ehRet, NULL, 0);
 
     OIC_LOG_V (DEBUG, TAG, "%s RetVal %d", __func__ , ehRet);
     return ehRet;
 }
 
-/*
+/**
  * This internal method is the entity handler for SVC resources and
  * will handle REST request (GET/PUT/POST/DEL) for them.
  */
-OCEntityHandlerResult SVCEntityHandler (OCEntityHandlerFlag flag,
-                                        OCEntityHandlerRequest * ehRequest,
-                                        void* callbackParameter)
+static OCEntityHandlerResult SVCEntityHandler(OCEntityHandlerFlag flag,
+                                              OCEntityHandlerRequest * ehRequest,
+                                              void* callbackParameter)
 {
     (void) callbackParameter;
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
@@ -308,51 +393,58 @@ OCEntityHandlerResult SVCEntityHandler (OCEntityHandlerFlag flag,
 
             default:
                 ehRet = OC_EH_ERROR;
-                SendSRMResponse(ehRequest, ehRet, NULL);
+                SendSRMCBORResponse(ehRequest, ehRet, NULL, 0);
         }
     }
 
     return ehRet;
 }
 
-/*
+/**
  * This internal method is used to create '/oic/sec/svc' resource.
  */
-OCStackResult CreateSVCResource()
+static OCStackResult CreateSVCResource()
 {
-    OCStackResult ret;
-
-    ret = OCCreateResource(&gSvcHandle,
-                           OIC_RSRC_TYPE_SEC_SVC,
-                           OIC_MI_DEF,
-                           OIC_RSRC_SVC_URI,
-                           SVCEntityHandler,
-                           NULL,
-                           OC_OBSERVABLE);
+    OCStackResult ret = OCCreateResource(&gSvcHandle,
+                                         OIC_RSRC_TYPE_SEC_SVC,
+                                         OIC_MI_DEF,
+                                         OIC_RSRC_SVC_URI,
+                                         SVCEntityHandler,
+                                         NULL,
+                                         OC_OBSERVABLE);
 
     if (OC_STACK_OK != ret)
     {
-        OIC_LOG (FATAL, TAG, "Unable to instantiate SVC resource");
+        OIC_LOG(FATAL, TAG, "Unable to instantiate SVC resource");
         DeInitSVCResource();
     }
     return ret;
 }
 
-
 OCStackResult InitSVCResource()
 {
     OCStackResult ret = OC_STACK_ERROR;
 
-    OIC_LOG_V (DEBUG, TAG, "Begin %s ", __func__ );
+    OIC_LOG_V(DEBUG, TAG, "Begin %s ", __func__ );
 
-    // Read SVC resource from PS
-    char* jsonSVRDatabase = GetSVRDatabase();
+    uint8_t *data = NULL;
+    size_t size = 0;
+    ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_SVC_NAME, &data, &size);
+    // If database read failed
+    if (ret != OC_STACK_OK)
+    {
+        OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
+    }
 
-    if (jsonSVRDatabase)
+    if (data)
     {
-        // Convert JSON SVC into binary format
-        gSvc = JSONToSvcBin(jsonSVRDatabase);
-        OICFree(jsonSVRDatabase);
+        // Convert CBOR SVC into binary format
+        ret = CBORPayloadToSVC(data, size, &gSvc);
+        if (ret != OC_STACK_OK)
+        {
+            OIC_LOG (DEBUG, TAG, " ConvertCBOR SVC into binary format failed");
+        }
+        OICFree(data);
     }
 
     // Instantiate 'oic.sec.svc'
@@ -363,15 +455,10 @@ OCStackResult InitSVCResource()
         DeInitSVCResource();
     }
 
-    OIC_LOG_V (DEBUG, TAG, "%s RetVal %d", __func__ , ret);
+    OIC_LOG_V(DEBUG, TAG, "%s RetVal %d", __func__ , ret);
     return ret;
 }
 
-/**
- * Perform cleanup for SVC resources.
- *
- * @retval  none
- */
 void DeInitSVCResource()
 {
     OCDeleteResource(gSvcHandle);
@@ -380,4 +467,3 @@ void DeInitSVCResource()
     DeleteSVCList(gSvc);
     gSvc = NULL;
 }
-
diff --git a/resource/csdk/security/tool/SConscript b/resource/csdk/security/tool/SConscript
new file mode 100644 (file)
index 0000000..9bb9569
--- /dev/null
@@ -0,0 +1,50 @@
+# //******************************************************************
+# //
+# // Copyright 2015 Samsung Electronics All Rights Reserved.
+# //
+# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+# //
+# // Licensed under the Apache License, Version 2.0 (the "License");
+# // you may not use this file except in compliance with the License.
+# // You may obtain a copy of the License at
+# //
+# //      http://www.apache.org/licenses/LICENSE-2.0
+# //
+# // Unless required by applicable law or agreed to in writing, software
+# // distributed under the License is distributed on an "AS IS" BASIS,
+# // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# // See the License for the specific language governing permissions and
+# // limitations under the License.
+# //
+# //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+#
+Import('env')
+
+tools_env = env.Clone()
+src_dir = tools_env.get('SRC_DIR')
+
+######################################################################
+# Build flags
+######################################################################
+tools_env.PrependUnique(CPPPATH = ['../../../../extlibs/cjson',
+                                  '../../stack/include',
+                                  '../../stack/include/internal',
+                                  '../../logger/include',
+                                  '../../../oc_logger/include',
+                                  '../../connectivity/api',
+                                  '../include',
+                                  '../include/internal',
+                                  '../../connectivity/lib/libcoap-4.1.1',
+
+                                  ])
+tools_env.AppendUnique(CXXFLAGS = ['-O2', '-g', '-Wall', '-Wextra', '-std=c++0x'])
+tools_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
+tools_env.AppendUnique(RPATH = [env.get('BUILD_DIR')])
+tools_env.PrependUnique(LIBS = ['oc', 'octbstack'])
+
+######################################################################
+# Source files and Targets
+######################################################################
+json2cbor = tools_env.Program('json2cbor', ['json2cbor.c'])
+Alias("json2cbor", [json2cbor])
+env.AppendTarget('json2cbor')
diff --git a/resource/csdk/security/tool/json2cbor.c b/resource/csdk/security/tool/json2cbor.c
new file mode 100644 (file)
index 0000000..3739eab
--- /dev/null
@@ -0,0 +1,1049 @@
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#include <stdlib.h>
+#include <string.h>
+#include "cJSON.h"
+#include "base64.h"
+#include "cainterface.h"
+#include "ocstack.h"
+#include "oic_malloc.h"
+#include "oic_string.h"
+#include "ocpayload.h"
+#include "ocpayloadcbor.h"
+#include "payload_logging.h"
+#include "secureresourcemanager.h"
+#include "srmresourcestrings.h"
+#include "srmutility.h"
+#include "aclresource.h"
+#include "pstatresource.h"
+#include "doxmresource.h"
+#include "amaclresource.h"
+#include "credresource.h"
+#include "svcresource.h"
+#include "security_internals.h"
+
+#define TAG  "JSON2CBOR"
+#define MAX_RANGE   18446744073709551615
+//SVR database buffer block size
+static const size_t DB_FILE_SIZE_BLOCK = 1023;
+
+static OicSecPstat_t* JSONToPstatBin(const char * jsonStr);
+static OicSecDoxm_t* JSONToDoxmBin(const char * jsonStr);
+static OicSecAcl_t *JSONToAclBin(const char * jsonStr);
+static OicSecSvc_t* JSONToSvcBin(const char * jsonStr);
+static OicSecAmacl_t* JSONToAmaclBin(const char * jsonStr);
+static OicSecCred_t* JSONToCredBin(const char * jsonStr);
+
+static size_t GetJSONFileSize(const char *jsonFileName)
+{
+    size_t size = 0;
+    size_t bytesRead  = 0;
+    char buffer[DB_FILE_SIZE_BLOCK];
+    FILE* fp = fopen(jsonFileName, "r");
+    if (fp)
+    {
+        do
+        {
+            bytesRead = fread(buffer, 1, DB_FILE_SIZE_BLOCK, fp);
+            if (size + bytesRead > MAX_RANGE)
+            {
+                fclose(fp);
+                return 0;
+            }
+            size += bytesRead;
+        } while (bytesRead > 0);
+        fclose(fp);
+    }
+    return size;
+}
+
+static void ConvertJsonToCBOR(const char *jsonFileName, const char *cborFileName)
+{
+    char *jsonStr = NULL;
+    FILE *fp = NULL;
+    FILE *fp1 = NULL;
+    uint8_t *aclCbor = NULL;
+    uint8_t *pstatCbor = NULL;
+    uint8_t *doxmCbor = NULL;
+    uint8_t *amaclCbor = NULL;
+    uint8_t *svcCbor = NULL;
+    uint8_t *credCbor = NULL;
+    cJSON *jsonRoot = NULL;
+    OCStackResult ret = OC_STACK_ERROR;
+    size_t size = GetJSONFileSize(jsonFileName);
+    if (0 == size)
+    {
+        OIC_LOG (ERROR, TAG, "Failed converting to JSON");
+        return;
+    }
+
+    fp = fopen(jsonFileName, "r");
+    if (fp)
+    {
+        jsonStr = (char *)OICMalloc(size + 1);
+        VERIFY_NON_NULL(TAG, jsonStr, FATAL);
+        size_t bytesRead = fread(jsonStr, 1, size, fp);
+        jsonStr[bytesRead] = '\0';
+
+        OIC_LOG_V(DEBUG, TAG, "Read %zu bytes", bytesRead);
+        fclose(fp);
+        fp = NULL;
+    }
+    else
+    {
+        OIC_LOG (ERROR, TAG, "Unable to open JSON file!!");
+        goto exit;
+    }
+
+    jsonRoot = cJSON_Parse(jsonStr);
+    cJSON *value = cJSON_GetObjectItem(jsonRoot, OIC_JSON_ACL_NAME);
+    size_t aclCborSize = 0;
+    if (NULL != value)
+    {
+        OicSecAcl_t *acl = JSONToAclBin(jsonStr);
+        VERIFY_NON_NULL(TAG, acl, FATAL);
+        ret = AclToCBORPayload(acl, &aclCbor, &aclCborSize);
+        if(OC_STACK_OK != ret)
+        {
+            OIC_LOG (ERROR, TAG, "Failed converting Acl to Cbor Payload");
+            DeleteACLList(acl);
+            goto exit;
+        }
+        printf("ACL Cbor Size: %zd\n", aclCborSize);
+        DeleteACLList(acl);
+    }
+    value = cJSON_GetObjectItem(jsonRoot, OIC_JSON_PSTAT_NAME);
+    size_t pstatCborSize = 0;
+    if (NULL != value)
+    {
+        OicSecPstat_t *pstat = JSONToPstatBin(jsonStr);
+        VERIFY_NON_NULL(TAG, pstat, FATAL);
+        ret = PstatToCBORPayload(pstat, &pstatCbor, &pstatCborSize);
+        if(OC_STACK_OK != ret)
+        {
+            OIC_LOG (ERROR, TAG, "Failed converting Pstat to Cbor Payload");
+            DeletePstatBinData(pstat);
+            goto exit;
+        }
+        printf("PSTAT Cbor Size: %zd\n", pstatCborSize);
+        DeletePstatBinData(pstat);
+    }
+    value = cJSON_GetObjectItem(jsonRoot, OIC_JSON_DOXM_NAME);
+    size_t doxmCborSize = 0;
+    if (NULL != value)
+    {
+        OicSecDoxm_t *doxm = JSONToDoxmBin(jsonStr);
+        VERIFY_NON_NULL(TAG, doxm, FATAL);
+        ret = DoxmToCBORPayload(doxm, &doxmCbor, &doxmCborSize);
+        if(OC_STACK_OK != ret)
+        {
+            OIC_LOG (ERROR, TAG, "Failed converting Doxm to Cbor Payload");
+            DeleteDoxmBinData(doxm);
+            goto exit;
+        }
+        printf("DOXM Cbor Size: %zd\n", doxmCborSize);
+        DeleteDoxmBinData(doxm);
+    }
+    value = cJSON_GetObjectItem(jsonRoot, OIC_JSON_AMACL_NAME);
+    size_t amaclCborSize = 0;
+    if (NULL != value)
+    {
+        OicSecAmacl_t *amacl = JSONToAmaclBin(jsonStr);
+        VERIFY_NON_NULL(TAG, amacl, FATAL);
+        ret = AmaclToCBORPayload(amacl, &amaclCbor, &amaclCborSize);
+        if(OC_STACK_OK != ret)
+        {
+            OIC_LOG (ERROR, TAG, "Failed converting Amacl to Cbor Payload");
+            DeleteAmaclList(amacl);
+            goto exit;
+        }
+        printf("AMACL Cbor Size: %zd\n", amaclCborSize);
+        DeleteAmaclList(amacl);
+    }
+    value = cJSON_GetObjectItem(jsonRoot, OIC_JSON_SVC_NAME);
+    size_t svcCborSize = 0;
+    if (NULL != value)
+    {
+        OicSecSvc_t *svc = JSONToSvcBin(jsonStr);
+        VERIFY_NON_NULL(TAG, svc, FATAL);
+        ret = SVCToCBORPayload(svc, &svcCbor, &svcCborSize);
+        if(OC_STACK_OK != ret)
+        {
+            OIC_LOG (ERROR, TAG, "Failed converting Svc to Cbor Payload");
+            DeleteSVCList(svc);
+            goto exit;
+        }
+        printf("SVC Cbor Size: %zd\n", svcCborSize);
+        DeleteSVCList(svc);
+    }
+    value = cJSON_GetObjectItem(jsonRoot, OIC_JSON_CRED_NAME);
+    size_t credCborSize = 0;
+    if (NULL != value)
+    {
+        OicSecCred_t *cred = JSONToCredBin(jsonStr);
+        VERIFY_NON_NULL(TAG, cred, FATAL);
+        ret = CredToCBORPayload(cred, &credCbor, &credCborSize);
+        if(OC_STACK_OK != ret)
+        {
+            OIC_LOG (ERROR, TAG, "Failed converting Cred to Cbor Payload");
+            DeleteCredList(cred);
+            goto exit;
+        }
+        printf("CRED Cbor Size: %zd\n", credCborSize);
+        DeleteCredList(cred);
+    }
+
+    cJSON_Delete(value);
+    CborEncoder encoder = { {.ptr = NULL }, .end = 0 };
+    size_t cborSize = aclCborSize + pstatCborSize + doxmCborSize + svcCborSize + credCborSize + amaclCborSize;
+    printf("Total Cbor Size : %zd\n", cborSize);
+    cborSize += 255; // buffer margin for adding map and byte string
+    uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborSize);
+    VERIFY_NON_NULL(TAG, outPayload, ERROR);
+    cbor_encoder_init(&encoder, outPayload, cborSize, 0);
+    CborEncoder map = { {.ptr = NULL }, .end = 0 };
+    CborError cborEncoderResult = cbor_encoder_create_map(&encoder, &map, CborIndefiniteLength);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Creating Main Map.");
+    if (aclCborSize > 0)
+    {
+        cborEncoderResult = cbor_encode_text_string(&map, OIC_JSON_ACL_NAME, strlen(OIC_JSON_ACL_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ACL Name.");
+        cborEncoderResult = cbor_encode_byte_string(&map, aclCbor, aclCborSize);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ACL Value.");
+    }
+    if (pstatCborSize > 0)
+    {
+        cborEncoderResult = cbor_encode_text_string(&map, OIC_JSON_PSTAT_NAME, strlen(OIC_JSON_PSTAT_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PSTAT Name.");
+        cborEncoderResult = cbor_encode_byte_string(&map, pstatCbor, pstatCborSize);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PSTAT Value.");
+    }
+    if (doxmCborSize > 0)
+    {
+        cborEncoderResult = cbor_encode_text_string(&map, OIC_JSON_DOXM_NAME, strlen(OIC_JSON_DOXM_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DOXM Name.");
+        cborEncoderResult = cbor_encode_byte_string(&map, doxmCbor, doxmCborSize);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DOXM Value.");
+    }
+    if (amaclCborSize > 0)
+    {
+        cborEncoderResult = cbor_encode_text_string(&map, OIC_JSON_AMACL_NAME, strlen(OIC_JSON_AMACL_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding AMACL Name.");
+        cborEncoderResult = cbor_encode_byte_string(&map, amaclCbor, amaclCborSize);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding AMACL Value.");
+    }
+    if (svcCborSize > 0)
+    {
+        cborEncoderResult = cbor_encode_text_string(&map, OIC_JSON_SVC_NAME, strlen(OIC_JSON_SVC_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SVC Name.");
+        cborEncoderResult = cbor_encode_byte_string(&map, svcCbor, svcCborSize);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SVC Value.");
+    }
+    if (credCborSize > 0)
+    {
+        cborEncoderResult = cbor_encode_text_string(&map, OIC_JSON_CRED_NAME, strlen(OIC_JSON_CRED_NAME));
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding CRED Name.");
+        cborEncoderResult = cbor_encode_byte_string(&map, credCbor, credCborSize);
+        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding CRED Value.");
+    }
+    cborEncoderResult = cbor_encoder_close_container(&encoder, &map);
+    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Container.");
+
+    size_t s = encoder.ptr - outPayload;
+    OIC_LOG_V(DEBUG, TAG, "Payload size %zu", s);
+
+    fp1 = fopen(cborFileName, "w");
+    if (fp1)
+    {
+        size_t bytesWritten = fwrite(outPayload, 1, s, fp1);
+        OIC_LOG_V(DEBUG, TAG, "Written %zu bytes", bytesWritten);
+        fclose(fp1);
+        fp1 = NULL;
+    }
+exit:
+    // cJSON_Delete(jsonRoot);
+    OICFree(aclCbor);
+    OICFree(doxmCbor);
+    OICFree(pstatCbor);
+    OICFree(amaclCbor);
+    OICFree(svcCbor);
+    OICFree(credCbor);
+    OICFree(jsonStr);
+    return ;
+}
+
+OicSecAcl_t* JSONToAclBin(const char * jsonStr)
+{
+    OCStackResult ret = OC_STACK_ERROR;
+    OicSecAcl_t * headAcl = NULL;
+    OicSecAcl_t * prevAcl = NULL;
+    cJSON *jsonRoot = NULL;
+    cJSON *jsonAclArray = NULL;
+
+    VERIFY_NON_NULL(TAG, jsonStr, ERROR);
+
+    jsonRoot = cJSON_Parse(jsonStr);
+    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+
+    jsonAclArray = cJSON_GetObjectItem(jsonRoot, OIC_JSON_ACL_NAME);
+    VERIFY_NON_NULL(TAG, jsonAclArray, ERROR);
+
+    if (cJSON_Array == jsonAclArray->type)
+    {
+        int numAcl = cJSON_GetArraySize(jsonAclArray);
+        int idx = 0;
+
+        VERIFY_SUCCESS(TAG, numAcl > 0, INFO);
+        do
+        {
+            cJSON *jsonAcl = cJSON_GetArrayItem(jsonAclArray, idx);
+            VERIFY_NON_NULL(TAG, jsonAcl, ERROR);
+
+            OicSecAcl_t *acl = (OicSecAcl_t*)OICCalloc(1, sizeof(OicSecAcl_t));
+            VERIFY_NON_NULL(TAG, acl, ERROR);
+
+            headAcl = (headAcl) ? headAcl : acl;
+            if (prevAcl)
+            {
+               prevAcl->next = acl;
+            }
+
+            size_t jsonObjLen = 0;
+            cJSON *jsonObj = NULL;
+            unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
+            uint32_t outLen = 0;
+            B64Result b64Ret = B64_OK;
+
+            jsonObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_SUBJECT_NAME);
+            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+            VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
+            outLen = 0;
+            b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff,
+                       sizeof(base64Buff), &outLen);
+            VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(acl->subject.id)), ERROR);
+            memcpy(acl->subject.id, base64Buff, outLen);
+
+            // Resources -- Mandatory
+            jsonObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_RESOURCES_NAME);
+            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+            VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
+
+            acl->resourcesLen = cJSON_GetArraySize(jsonObj);
+            VERIFY_SUCCESS(TAG, acl->resourcesLen > 0, ERROR);
+            acl->resources = (char**)OICCalloc(acl->resourcesLen, sizeof(char*));
+            VERIFY_NON_NULL(TAG, (acl->resources), ERROR);
+
+            size_t idxx = 0;
+            do
+            {
+                cJSON *jsonRsrc = cJSON_GetArrayItem(jsonObj, idxx);
+                VERIFY_NON_NULL(TAG, jsonRsrc, ERROR);
+
+                jsonObjLen = strlen(jsonRsrc->valuestring) + 1;
+                acl->resources[idxx] = (char*)OICMalloc(jsonObjLen);
+                VERIFY_NON_NULL(TAG, (acl->resources[idxx]), ERROR);
+                OICStrcpy(acl->resources[idxx], jsonObjLen, jsonRsrc->valuestring);
+            } while ( ++idxx < acl->resourcesLen);
+
+            // Permissions -- Mandatory
+            jsonObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_PERMISSION_NAME);
+            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+            VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
+            acl->permission = jsonObj->valueint;
+
+            //Period -- Not Mandatory
+            cJSON *jsonPeriodObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_PERIODS_NAME);
+            if(jsonPeriodObj)
+            {
+                VERIFY_SUCCESS(TAG, cJSON_Array == jsonPeriodObj->type, ERROR);
+                acl->prdRecrLen = (size_t)cJSON_GetArraySize(jsonPeriodObj);
+                if(acl->prdRecrLen > 0)
+                {
+                    acl->periods = (char**)OICCalloc(acl->prdRecrLen, sizeof(char*));
+                    VERIFY_NON_NULL(TAG, acl->periods, ERROR);
+
+                    cJSON *jsonPeriod = NULL;
+                    for(size_t i = 0; i < acl->prdRecrLen; i++)
+                    {
+                        jsonPeriod = cJSON_GetArrayItem(jsonPeriodObj, i);
+                        VERIFY_NON_NULL(TAG, jsonPeriod, ERROR);
+
+                        jsonObjLen = strlen(jsonPeriod->valuestring) + 1;
+                        acl->periods[i] = (char*)OICMalloc(jsonObjLen);
+                        VERIFY_NON_NULL(TAG, acl->periods[i], ERROR);
+                        OICStrcpy(acl->periods[i], jsonObjLen, jsonPeriod->valuestring);
+                    }
+                }
+            }
+
+            //Recurrence -- Not mandatory
+            cJSON *jsonRecurObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_RECURRENCES_NAME);
+            if(jsonRecurObj)
+            {
+                VERIFY_SUCCESS(TAG, cJSON_Array == jsonRecurObj->type, ERROR);
+
+                if(acl->prdRecrLen > 0)
+                {
+                    acl->recurrences = (char**)OICCalloc(acl->prdRecrLen, sizeof(char*));
+                    VERIFY_NON_NULL(TAG, acl->recurrences, ERROR);
+
+                    cJSON *jsonRecur = NULL;
+                    for(size_t i = 0; i < acl->prdRecrLen; i++)
+                    {
+                        jsonRecur = cJSON_GetArrayItem(jsonRecurObj, i);
+                        VERIFY_NON_NULL(TAG, jsonRecur, ERROR);
+                        jsonObjLen = strlen(jsonRecur->valuestring) + 1;
+                        acl->recurrences[i] = (char*)OICMalloc(jsonObjLen);
+                        VERIFY_NON_NULL(TAG, acl->recurrences[i], ERROR);
+                        OICStrcpy(acl->recurrences[i], jsonObjLen, jsonRecur->valuestring);
+                    }
+                }
+            }
+
+            // Owners -- Mandatory
+            jsonObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_OWNERS_NAME);
+            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+            VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
+
+            acl->ownersLen = cJSON_GetArraySize(jsonObj);
+            VERIFY_SUCCESS(TAG, acl->ownersLen > 0, ERROR);
+            acl->owners = (OicUuid_t*)OICCalloc(acl->ownersLen, sizeof(OicUuid_t));
+            VERIFY_NON_NULL(TAG, (acl->owners), ERROR);
+
+            idxx = 0;
+            do
+            {
+                cJSON *jsonOwnr = cJSON_GetArrayItem(jsonObj, idxx);
+                VERIFY_NON_NULL(TAG, jsonOwnr, ERROR);
+                VERIFY_SUCCESS(TAG, cJSON_String == jsonOwnr->type, ERROR);
+                outLen = 0;
+                b64Ret = b64Decode(jsonOwnr->valuestring, strlen(jsonOwnr->valuestring), base64Buff,
+                            sizeof(base64Buff), &outLen);
+                VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(acl->owners[idxx].id)),
+                                    ERROR);
+                memcpy(acl->owners[idxx].id, base64Buff, outLen);
+            } while ( ++idxx < acl->ownersLen);
+
+            prevAcl = acl;
+        } while( ++idx < numAcl);
+    }
+
+    ret = OC_STACK_OK;
+
+exit:
+    cJSON_Delete(jsonRoot);
+    if (OC_STACK_OK != ret)
+    {
+        DeleteACLList(headAcl);
+        headAcl = NULL;
+    }
+    return headAcl;
+}
+
+OicSecDoxm_t* JSONToDoxmBin(const char * jsonStr)
+{
+    if (NULL == jsonStr)
+    {
+        return NULL;
+    }
+
+    OCStackResult ret = OC_STACK_ERROR;
+    OicSecDoxm_t *doxm =  NULL;
+    cJSON *jsonDoxm = NULL;
+    cJSON *jsonObj = NULL;
+
+    size_t jsonObjLen = 0;
+    unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
+    uint32_t outLen = 0;
+    B64Result b64Ret = B64_OK;
+
+    cJSON *jsonRoot = cJSON_Parse(jsonStr);
+    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+
+    jsonDoxm = cJSON_GetObjectItem(jsonRoot, OIC_JSON_DOXM_NAME);
+    VERIFY_NON_NULL(TAG, jsonDoxm, ERROR);
+
+    doxm = (OicSecDoxm_t *)OICCalloc(1, sizeof(OicSecDoxm_t));
+    VERIFY_NON_NULL(TAG, doxm, ERROR);
+
+    //OxmType -- not Mandatory
+    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OXM_TYPE_NAME);
+    if ((jsonObj) && (cJSON_Array == jsonObj->type))
+    {
+        doxm->oxmTypeLen = (size_t)cJSON_GetArraySize(jsonObj);
+        VERIFY_SUCCESS(TAG, doxm->oxmTypeLen > 0, ERROR);
+
+        doxm->oxmType = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(char *));
+        VERIFY_NON_NULL(TAG, (doxm->oxmType), ERROR);
+
+        for (size_t i  = 0; i < doxm->oxmTypeLen ; i++)
+        {
+            cJSON *jsonOxmTy = cJSON_GetArrayItem(jsonObj, i);
+            VERIFY_NON_NULL(TAG, jsonOxmTy, ERROR);
+
+            jsonObjLen = strlen(jsonOxmTy->valuestring) + 1;
+            doxm->oxmType[i] = (char*)OICMalloc(jsonObjLen);
+            VERIFY_NON_NULL(TAG, doxm->oxmType[i], ERROR);
+            strncpy((char *)doxm->oxmType[i], (char *)jsonOxmTy->valuestring, jsonObjLen);
+        }
+    }
+
+    //Oxm -- not Mandatory
+    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OXM_NAME);
+    if (jsonObj && cJSON_Array == jsonObj->type)
+    {
+        doxm->oxmLen = cJSON_GetArraySize(jsonObj);
+        VERIFY_SUCCESS(TAG, doxm->oxmLen > 0, ERROR);
+
+        doxm->oxm = (OicSecOxm_t*)OICCalloc(doxm->oxmLen, sizeof(OicSecOxm_t));
+        VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
+
+        for (size_t i  = 0; i < doxm->oxmLen ; i++)
+        {
+            cJSON *jsonOxm = cJSON_GetArrayItem(jsonObj, i);
+            VERIFY_NON_NULL(TAG, jsonOxm, ERROR);
+            doxm->oxm[i] = (OicSecOxm_t)jsonOxm->valueint;
+        }
+    }
+
+    //OxmSel -- Mandatory
+    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OXM_SEL_NAME);
+    if (jsonObj)
+    {
+        VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
+        doxm->oxmSel = (OicSecOxm_t)jsonObj->valueint;
+    }
+
+    //sct -- Mandatory
+    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_SUPPORTED_CRED_TYPE_NAME);
+    if (jsonObj)
+    {
+        VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
+        doxm->sct = (OicSecCredType_t)jsonObj->valueint;
+    }
+
+    //Owned -- Mandatory
+    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OWNED_NAME);
+    if (jsonObj)
+    {
+        VERIFY_SUCCESS(TAG, (cJSON_True == jsonObj->type || cJSON_False == jsonObj->type), ERROR);
+        doxm->owned = jsonObj->valueint;
+    }
+
+    //DPC -- Mandatory
+    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_DPC_NAME);
+    if (jsonObj)
+    {
+        VERIFY_SUCCESS(TAG, (cJSON_True == jsonObj->type || cJSON_False == jsonObj->type), ERROR);
+        doxm->dpc = jsonObj->valueint;
+    }
+
+    //DeviceId -- Mandatory
+    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_DEVICE_ID_NAME);
+    if (jsonObj)
+    {
+        VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
+        if (cJSON_String == jsonObj->type)
+        {
+            //Check for empty string, in case DeviceId field has not been set yet
+            if (jsonObj->valuestring[0])
+            {
+                outLen = 0;
+                b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff,
+                       sizeof(base64Buff), &outLen);
+                VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(doxm->deviceID.id)),
+                               ERROR);
+                memcpy(doxm->deviceID.id, base64Buff, outLen);
+            }
+        }
+    }
+
+    //Owner -- will be empty when device status is unowned.
+    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OWNER_NAME);
+    if (true == doxm->owned)
+    {
+        VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+    }
+    if (jsonObj)
+    {
+        outLen = 0;
+        b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff,
+              sizeof(base64Buff), &outLen);
+        VERIFY_SUCCESS(TAG, ((b64Ret == B64_OK) && (outLen <= sizeof(doxm->owner.id))), ERROR);
+        memcpy(doxm->owner.id, base64Buff, outLen);
+    }
+
+    ret = OC_STACK_OK;
+
+exit:
+    cJSON_Delete(jsonRoot);
+    if (OC_STACK_OK != ret)
+    {
+        DeleteDoxmBinData(doxm);
+        doxm = NULL;
+    }
+
+    return doxm;
+}
+
+OicSecPstat_t* JSONToPstatBin(const char * jsonStr)
+{
+    if(NULL == jsonStr)
+    {
+        return NULL;
+    }
+
+    OCStackResult ret = OC_STACK_ERROR;
+    OicSecPstat_t *pstat = NULL;
+    cJSON *jsonPstat = NULL;
+    cJSON *jsonObj = NULL;
+
+    unsigned char base64Buff[sizeof(((OicUuid_t*) 0)->id)] = {};
+    uint32_t outLen = 0;
+    B64Result b64Ret = B64_OK;
+
+    cJSON *jsonRoot = cJSON_Parse(jsonStr);
+    VERIFY_NON_NULL(TAG, jsonRoot, INFO);
+
+    jsonPstat = cJSON_GetObjectItem(jsonRoot, OIC_JSON_PSTAT_NAME);
+    VERIFY_NON_NULL(TAG, jsonPstat, INFO);
+
+    pstat = (OicSecPstat_t*)OICCalloc(1, sizeof(OicSecPstat_t));
+    VERIFY_NON_NULL(TAG, pstat, INFO);
+    jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_ISOP_NAME);
+    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+    VERIFY_SUCCESS(TAG, (cJSON_True == jsonObj->type || cJSON_False == jsonObj->type) , ERROR);
+    pstat->isOp = jsonObj->valueint;
+
+    jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_DEVICE_ID_NAME);
+    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+    VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
+    b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff,
+                  sizeof(base64Buff), &outLen);
+    VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(pstat->deviceID.id)), ERROR);
+    memcpy(pstat->deviceID.id, base64Buff, outLen);
+
+    jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_COMMIT_HASH_NAME);
+    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+    VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
+    pstat->commitHash  = jsonObj->valueint;
+
+    jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_CM_NAME);
+    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+    VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
+    pstat->cm  = (OicSecDpm_t)jsonObj->valueint;
+
+    jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_OM_NAME);
+    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+    VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
+    pstat->om  = (OicSecDpom_t)jsonObj->valueint;
+
+    jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_SM_NAME);
+    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+    if (cJSON_Array == jsonObj->type)
+    {
+        pstat->smLen = (size_t)cJSON_GetArraySize(jsonObj);
+        size_t idxx = 0;
+        VERIFY_SUCCESS(TAG, pstat->smLen != 0, ERROR);
+        pstat->sm = (OicSecDpom_t*)OICCalloc(pstat->smLen, sizeof(OicSecDpom_t));
+        VERIFY_NON_NULL(TAG, pstat->sm, ERROR);
+        do
+        {
+            cJSON *jsonSm = cJSON_GetArrayItem(jsonObj, idxx);
+            VERIFY_NON_NULL(TAG, jsonSm, ERROR);
+            pstat->sm[idxx] = (OicSecDpom_t)jsonSm->valueint;
+        } while ( ++idxx < pstat->smLen);
+    }
+    ret = OC_STACK_OK;
+
+exit:
+    cJSON_Delete(jsonRoot);
+    if (OC_STACK_OK != ret)
+    {
+        OIC_LOG(ERROR, TAG, "JSONToPstatBin failed");
+    }
+    return pstat;
+}
+
+OicSecCred_t * JSONToCredBin(const char * jsonStr)
+{
+    OCStackResult ret = OC_STACK_ERROR;
+    OicSecCred_t * headCred = NULL;
+    OicSecCred_t * prevCred = NULL;
+    cJSON *jsonCredArray = NULL;
+
+    cJSON *jsonRoot = cJSON_Parse(jsonStr);
+    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+
+    jsonCredArray = cJSON_GetObjectItem(jsonRoot, OIC_JSON_CRED_NAME);
+    VERIFY_NON_NULL(TAG, jsonCredArray, ERROR);
+    if (cJSON_Array == jsonCredArray->type)
+    {
+        int numCred = cJSON_GetArraySize(jsonCredArray);
+        VERIFY_SUCCESS(TAG, numCred > 0, ERROR);
+        unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
+        uint32_t outLen = 0;
+        B64Result b64Ret = B64_OK;
+        int idx = 0;
+        do
+        {
+            cJSON *jsonCred = cJSON_GetArrayItem(jsonCredArray, idx);
+            VERIFY_NON_NULL(TAG, jsonCred, ERROR);
+
+            OicSecCred_t *cred = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
+            VERIFY_NON_NULL(TAG, cred, ERROR);
+
+            headCred = (headCred) ? headCred : cred;
+            if (prevCred)
+            {
+                prevCred->next = cred;
+            }
+            size_t jsonObjLen = 0;
+            cJSON *jsonObj = NULL;
+
+            //CredId -- Mandatory
+            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_CREDID_NAME);
+            if(jsonObj)
+            {
+                VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
+                cred->credId = jsonObj->valueint;
+            }
+
+            //subject -- Mandatory
+            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_SUBJECT_NAME);
+            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+            VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
+            outLen = 0;
+            memset(base64Buff, 0, sizeof(base64Buff));
+            b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring),
+                   base64Buff, sizeof(base64Buff), &outLen);
+            VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(cred->subject.id)),
+                          ERROR);
+            memcpy(cred->subject.id, base64Buff, outLen);
+
+            //CredType -- Mandatory
+            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_CREDTYPE_NAME);
+            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+            VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
+            cred->credType = (OicSecCredType_t)jsonObj->valueint;
+
+            //PrivateData is mandatory for some of the credential types listed below.
+            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_PRIVATEDATA_NAME);
+            if ((cred->credType & SYMMETRIC_PAIR_WISE_KEY) ||
+                (cred->credType & SYMMETRIC_GROUP_KEY) ||
+                (cred->credType & PIN_PASSWORD))
+            {
+                VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+                VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
+            }
+#ifdef __WITH_X509__
+            else if (cred->credType & SIGNED_ASYMMETRIC_KEY)
+            {
+                VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+                VERIFY_SUCCESS(TAG, cJSON_Object == jsonObj->type, ERROR);
+            }
+#endif //  __WITH_X509__
+            if (NULL != jsonObj)
+            {
+                if (cJSON_String == jsonObj->type)
+                {
+                    jsonObjLen = strlen(jsonObj->valuestring) + 1;
+                    cred->privateData.data = (uint8_t *)OICCalloc(1, jsonObjLen);
+                    VERIFY_NON_NULL(TAG, (cred->privateData.data), ERROR);
+                    memcpy(cred->privateData.data, jsonObj->valuestring, jsonObjLen);
+                }
+#ifdef __WITH_X509__
+                else if (SIGNED_ASYMMETRIC_KEY == cred->credType && cJSON_Object == jsonObj->type)
+                {
+                    cred->privateData.data = cJSON_PrintUnformatted(jsonObj);
+                    VERIFY_NON_NULL(TAG, (cred->privateData.data), ERROR);
+                }
+#endif // __WITH_X509__
+            }
+#ifdef __WITH_X509__
+            //PublicData is mandatory only for SIGNED_ASYMMETRIC_KEY credentials type.
+            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_PUBLICDATA_NAME);
+            if (cred->credType & SIGNED_ASYMMETRIC_KEY)
+            {
+                VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+                VERIFY_SUCCESS(TAG, cJSON_Object == jsonObj->type, ERROR);
+            }
+            if (NULL != jsonObj)
+            {
+                if (cJSON_String == jsonObj->type)
+                {
+                    jsonObjLen = strlen(jsonObj->valuestring) + 1;
+                    cred->publicData.data = (uint8_t *)OICCalloc(1, jsonObjLen);
+                    VERIFY_NON_NULL(TAG, (cred->publicData.data), ERROR);
+                    memcpy(cred->publicData.data, jsonObj->valuestring, jsonObjLen);
+                }
+                else if (SIGNED_ASYMMETRIC_KEY == cred->credType && cJSON_Object == jsonObj->type)
+                {
+                    cred->publicData.data = cJSON_PrintUnformatted(jsonObj);
+                    VERIFY_NON_NULL(TAG, (cred->publicData.data), ERROR);
+                }
+            }
+#endif //  __WITH_X509__
+            //Period -- Not Mandatory
+            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_PERIOD_NAME);
+            if(jsonObj && cJSON_String == jsonObj->type)
+            {
+                jsonObjLen = strlen(jsonObj->valuestring) + 1;
+                cred->period = (char *)OICMalloc(jsonObjLen);
+                VERIFY_NON_NULL(TAG, cred->period, ERROR);
+                strncpy(cred->period, jsonObj->valuestring, jsonObjLen);
+            }
+
+            //Owners -- Mandatory
+            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_OWNERS_NAME);
+            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+            VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
+            cred->ownersLen = (size_t)cJSON_GetArraySize(jsonObj);
+            VERIFY_SUCCESS(TAG, cred->ownersLen > 0, ERROR);
+            cred->owners = (OicUuid_t*)OICCalloc(cred->ownersLen, sizeof(OicUuid_t));
+            VERIFY_NON_NULL(TAG, (cred->owners), ERROR);
+            for(size_t i = 0; i < cred->ownersLen; i++)
+            {
+                cJSON *jsonOwnr = cJSON_GetArrayItem(jsonObj, i);
+                VERIFY_NON_NULL(TAG, jsonOwnr, ERROR);
+                VERIFY_SUCCESS(TAG, cJSON_String == jsonOwnr->type, ERROR);
+                outLen = 0;
+                memset(base64Buff, 0, sizeof(base64Buff));
+                b64Ret = b64Decode(jsonOwnr->valuestring, strlen(jsonOwnr->valuestring),
+                         base64Buff, sizeof(base64Buff), &outLen);
+                VERIFY_SUCCESS(TAG, (b64Ret == B64_OK &&
+                               outLen <= sizeof(cred->owners[i].id)), ERROR);
+                memcpy(cred->owners[i].id, base64Buff, outLen);
+            }
+            prevCred = cred;
+        } while( ++idx < numCred);
+    }
+
+    ret = OC_STACK_OK;
+
+exit:
+    cJSON_Delete(jsonRoot);
+    if (OC_STACK_OK != ret)
+    {
+        DeleteCredList(headCred);
+        headCred = NULL;
+    }
+    return headCred;
+}
+
+static OicSecSvc_t* JSONToSvcBin(const char * jsonStr)
+{
+    OCStackResult ret = OC_STACK_ERROR;
+    OicSecSvc_t * headSvc = NULL;
+    OicSecSvc_t * prevSvc = NULL;
+    cJSON *jsonRoot = NULL;
+    cJSON *jsonSvcArray = NULL;
+
+    VERIFY_NON_NULL(TAG, jsonStr, ERROR);
+
+    jsonRoot = cJSON_Parse(jsonStr);
+    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+
+    jsonSvcArray = cJSON_GetObjectItem(jsonRoot, OIC_JSON_SVC_NAME);
+    VERIFY_NON_NULL(TAG, jsonSvcArray, INFO);
+
+    if (cJSON_Array == jsonSvcArray->type)
+    {
+        int numSvc = cJSON_GetArraySize(jsonSvcArray);
+        int idx = 0;
+
+        VERIFY_SUCCESS(TAG, numSvc > 0, INFO);
+        do
+        {
+            cJSON *jsonSvc = cJSON_GetArrayItem(jsonSvcArray, idx);
+            VERIFY_NON_NULL(TAG, jsonSvc, ERROR);
+
+            OicSecSvc_t *svc = (OicSecSvc_t*)OICCalloc(1, sizeof(OicSecSvc_t));
+            VERIFY_NON_NULL(TAG, svc, ERROR);
+
+            headSvc = (headSvc) ? headSvc : svc;
+            if (prevSvc)
+            {
+                prevSvc->next = svc;
+            }
+
+            cJSON *jsonObj = NULL;
+            unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
+            uint32_t outLen = 0;
+            B64Result b64Ret = B64_OK;
+
+            // Service Device Identity
+            jsonObj = cJSON_GetObjectItem(jsonSvc, OIC_JSON_SERVICE_DEVICE_ID);
+            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+            VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
+            outLen = 0;
+            b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff,
+                       sizeof(base64Buff), &outLen);
+            VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(svc->svcdid.id)), ERROR);
+            memcpy(svc->svcdid.id, base64Buff, outLen);
+
+            // Service Type
+            jsonObj = cJSON_GetObjectItem(jsonSvc, OIC_JSON_SERVICE_TYPE);
+            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+            VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
+            svc->svct = (OicSecSvcType_t)jsonObj->valueint;
+
+            // Resource Owners
+            jsonObj = cJSON_GetObjectItem(jsonSvc, OIC_JSON_OWNERS_NAME);
+            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+            VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
+
+            svc->ownersLen = (size_t)cJSON_GetArraySize(jsonObj);
+            VERIFY_SUCCESS(TAG, svc->ownersLen > 0, ERROR);
+            svc->owners = (OicUuid_t*)OICCalloc(svc->ownersLen, sizeof(OicUuid_t));
+            VERIFY_NON_NULL(TAG, (svc->owners), ERROR);
+
+            size_t idxx = 0;
+            do
+            {
+                cJSON *jsonOwnr = cJSON_GetArrayItem(jsonObj, idxx);
+                VERIFY_NON_NULL(TAG, jsonOwnr, ERROR);
+                VERIFY_SUCCESS(TAG, cJSON_String == jsonOwnr->type, ERROR);
+                outLen = 0;
+                b64Ret = b64Decode(jsonOwnr->valuestring, strlen(jsonOwnr->valuestring), base64Buff,
+                           sizeof(base64Buff), &outLen);
+
+                VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(svc->owners[idxx].id)),
+                                   ERROR);
+                memcpy(svc->owners[idxx].id, base64Buff, outLen);
+            } while ( ++idxx < svc->ownersLen);
+
+            prevSvc = svc;
+        } while( ++idx < numSvc);
+    }
+
+    ret = OC_STACK_OK;
+
+exit:
+    cJSON_Delete(jsonRoot);
+    if (OC_STACK_OK != ret)
+    {
+        DeleteSVCList(headSvc);
+        headSvc = NULL;
+    }
+    return headSvc;
+}
+
+static OicSecAmacl_t* JSONToAmaclBin(const char * jsonStr)
+{
+    OCStackResult ret = OC_STACK_ERROR;
+    OicSecAmacl_t * headAmacl = NULL;
+    OicSecAmacl_t * prevAmacl = NULL;
+    cJSON *jsonRoot = NULL;
+    cJSON *jsonAmaclArray = NULL;
+
+    VERIFY_NON_NULL(TAG, jsonStr, ERROR);
+
+    jsonRoot = cJSON_Parse(jsonStr);
+    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+
+    jsonAmaclArray = cJSON_GetObjectItem(jsonRoot, OIC_JSON_AMACL_NAME);
+    VERIFY_NON_NULL(TAG, jsonAmaclArray, INFO);
+
+    if (cJSON_Array == jsonAmaclArray->type)
+    {
+        int numAmacl = cJSON_GetArraySize(jsonAmaclArray);
+        int idx = 0;
+
+        VERIFY_SUCCESS(TAG, numAmacl > 0, INFO);
+        do
+        {
+            cJSON *jsonAmacl = cJSON_GetArrayItem(jsonAmaclArray, idx);
+            VERIFY_NON_NULL(TAG, jsonAmacl, ERROR);
+
+            OicSecAmacl_t *amacl = (OicSecAmacl_t*)OICCalloc(1, sizeof(OicSecAmacl_t));
+            VERIFY_NON_NULL(TAG, amacl, ERROR);
+
+            headAmacl = (headAmacl) ? headAmacl : amacl;
+            if (prevAmacl)
+            {
+                prevAmacl->next = amacl;
+            }
+
+            size_t jsonObjLen = 0;
+            cJSON *jsonObj = NULL;
+
+            // Resources -- Mandatory
+            jsonObj = cJSON_GetObjectItem(jsonAmacl, OIC_JSON_RESOURCES_NAME);
+            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+            VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
+
+            amacl->resourcesLen = (size_t)cJSON_GetArraySize(jsonObj);
+            VERIFY_SUCCESS(TAG, amacl->resourcesLen > 0, ERROR);
+            amacl->resources = (char**)OICCalloc(amacl->resourcesLen, sizeof(char*));
+            VERIFY_NON_NULL(TAG, (amacl->resources), ERROR);
+
+            size_t idxx = 0;
+            do
+            {
+                cJSON *jsonRsrc = cJSON_GetArrayItem(jsonObj, idxx);
+                VERIFY_NON_NULL(TAG, jsonRsrc, ERROR);
+
+                jsonObjLen = strlen(jsonRsrc->valuestring) + 1;
+                amacl->resources[idxx] = (char*)OICMalloc(jsonObjLen);
+                VERIFY_NON_NULL(TAG, (amacl->resources[idxx]), ERROR);
+                OICStrcpy(amacl->resources[idxx], jsonObjLen, jsonRsrc->valuestring);
+            } while ( ++idxx < amacl->resourcesLen);
+
+            // Amss -- Mandatory
+            VERIFY_SUCCESS( TAG, OC_STACK_OK == AddUuidArray(jsonAmacl, OIC_JSON_AMSS_NAME,
+                               &(amacl->amssLen), &(amacl->amss)), ERROR);
+
+            // Owners -- Mandatory
+            VERIFY_SUCCESS( TAG, OC_STACK_OK == AddUuidArray(jsonAmacl, OIC_JSON_OWNERS_NAME,
+                               &(amacl->ownersLen), &(amacl->owners)), ERROR);
+
+            prevAmacl = amacl;
+        } while( ++idx < numAmacl);
+    }
+
+    ret = OC_STACK_OK;
+
+exit:
+    cJSON_Delete(jsonRoot);
+    if (OC_STACK_OK != ret)
+    {
+        DeleteAmaclList(headAmacl);
+        headAmacl = NULL;
+    }
+    return headAmacl;
+}
+
+int main(int argc, char* argv[])
+{
+    if (argc == 3)
+    {
+        printf("JSON File Name: %s\n CBOR File Name: %s \n", argv[1], argv[2]);
+        ConvertJsonToCBOR(argv[1], argv[2]);
+    }
+    else
+    {
+        printf("This program requires two inputs:\n");
+        printf("1. First input is a json file tha will be converted to cbor. \n");
+        printf("2. Second input is a resulting cbor file that will store converted cbor. \n");
+        printf("\t json2cbor <json_file_name> <cbor_file_name>. \n");
+    }
+}
index 17266d0..c431d77 100644 (file)
@@ -48,6 +48,7 @@ srmtest_env.PrependUnique(CPPPATH = [
 #              '../../../../extlibs/tinydtls/',
                '../include'
                ])
+
 srmtest_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
 srmtest_env.AppendUnique(LIBS = ['-lpthread'])
 srmtest_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
@@ -70,6 +71,7 @@ if not env.get('RELEASE'):
 # Source files and Targets
 ######################################################################
 unittest = srmtest_env.Program('unittest', ['aclresourcetest.cpp',
+                                            'amaclresourcetest.cpp',
                                             'pstatresource.cpp',
                                             'doxmresource.cpp',
                                             'policyengine.cpp',
@@ -85,7 +87,9 @@ unittest = srmtest_env.Program('unittest', ['aclresourcetest.cpp',
 Alias("test", [unittest])
 
 unittest_src_dir = src_dir + '/resource/csdk/security/unittest/'
-unittest_build_dir = env.get('BUILD_DIR') +'/resource/csdk/security/unittest'
+unittest_build_dir = env.get('BUILD_DIR') + 'resource/csdk/security/unittest'
+
+srmtest_env.AppendUnique(CPPDEFINES = ['SECURITY_BUILD_UNITTEST_DIR='+unittest_build_dir])
 
 srmtest_env.Alias("install", srmtest_env.Install( unittest_build_dir,
     unittest_src_dir + 'oic_unittest.json'))
@@ -94,6 +98,13 @@ srmtest_env.Alias("install", srmtest_env.Install( unittest_build_dir,
 srmtest_env.Alias("install", srmtest_env.Install( unittest_build_dir,
     unittest_src_dir + 'oic_unittest_default_acl.json'))
 
+srmtest_env.Alias("install", srmtest_env.Install( unittest_build_dir,
+    unittest_src_dir + 'oic_unittest.dat'))
+srmtest_env.Alias("install", srmtest_env.Install( unittest_build_dir,
+    unittest_src_dir + 'oic_unittest_acl1.dat'))
+srmtest_env.Alias("install", srmtest_env.Install( unittest_build_dir,
+    unittest_src_dir + 'oic_unittest_default_acl.dat'))
+
 env.AppendTarget('test')
 if env.get('TEST') == '1':
        target_os = env.get('TARGET_OS')
@@ -107,4 +118,3 @@ if env.get('TEST') == '1':
                srmtest_env.AppendENVPath('LD_LIBRARY_PATH', ['./extlibs/gtest/gtest-1.7.0/lib/.libs'])
                ut = srmtest_env.Command ('ut', None, out_dir + '/resource/csdk/security/unittest/unittest')
                AlwaysBuild ('ut')
-
index 74fb3c5..59bdada 100644 (file)
 #include <linux/limits.h>
 #include <sys/stat.h>
 #include "ocstack.h"
+#include "psinterface.h"
 #include "ocpayload.h"
 #include "oic_malloc.h"
 #include "oic_string.h"
-#include "cJSON.h"
 #include "cainterface.h"
 #include "secureresourcemanager.h"
 #include "securevirtualresourcetypes.h"
 #include "srmtestcommon.h"
 #include "srmutility.h"
 #include "logger.h"
+#include "doxmresource.h"
+#include "ocpayload.h"
+#include "ocpayloadcbor.h"
+#include "payload_logging.h"
+#include "security_internals.h"
 
 using namespace std;
 
 #define TAG  "SRM-ACL-UT"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-extern char * BinToAclJSON(const OicSecAcl_t * acl);
-extern OicSecAcl_t * JSONToAclBin(const char * jsonStr);
-extern void DeleteACLList(OicSecAcl_t* acl);
-OCStackResult  GetDefaultACL(OicSecAcl_t** defaultAcl);
-OCEntityHandlerResult ACLEntityHandler (OCEntityHandlerFlag flag,
-                                        OCEntityHandlerRequest * ehRequest);
-#ifdef __cplusplus
-}
-#endif
-
-const char* JSON_FILE_NAME = "oic_unittest.json";
-const char* DEFAULT_ACL_JSON_FILE_NAME = "oic_unittest_default_acl.json";
-const char* ACL1_JSON_FILE_NAME = "oic_unittest_acl1.json";
+// These paths match jenkins build configuration.
+const char* DEFAULT_ACL_FILE_NAME = "/oic_unittest_default_acl.dat";
+const char* ACL1_FILE_NAME = "/oic_unittest_acl1.dat";
 
-#define NUM_ACE_FOR_WILDCARD_IN_ACL1_JSON (2)
+#define NUM_ACE_FOR_WILDCARD_IN_ACL1_DAT (1)
 
-// JSON Marshalling Tests
-TEST(ACLResourceTest, JSONMarshallingTests)
+TEST(ACLResourceTest, CBORDefaultACLConversion)
 {
-    char *jsonStr1 = ReadFile(ACL1_JSON_FILE_NAME);
-    if (jsonStr1)
+    OicSecAcl_t *defaultAcl = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
+    ASSERT_TRUE(defaultAcl != NULL);
+    uint8_t defaultAclSub[] = { 0x2a };
+    memcpy(defaultAcl->subject.id, defaultAclSub, sizeof(defaultAclSub));
+    defaultAcl->permission = 2;
+    const char *defaulAclRsrc[] = { "/oic/res", "/oic/d", "/oic/p", "/oic/res/types/d",
+            "/oic/ad", "/oic/sec/acl", "/oic/sec/doxm", "/oic/sec/pstat"};
+    defaultAcl->resourcesLen = 8;
+    defaultAcl->resources = (char **)OICCalloc(defaultAcl->resourcesLen, sizeof(char *));
+    ASSERT_TRUE(defaultAcl->resources != NULL);
+    for (size_t i = 0 ; i < defaultAcl->resourcesLen; i++)
     {
-        cJSON_Minify(jsonStr1);
-        /* Workaround : cJSON_Minify does not remove all the unwanted characters
-         from the end. Here is an attempt to remove those characters */
-        int len = strlen(jsonStr1);
-        while (len > 0)
-        {
-            if (jsonStr1[--len] == '}')
-            {
-                break;
-            }
-        }
-        jsonStr1[len + 1] = 0;
-
-        OicSecAcl_t * acl = JSONToAclBin(jsonStr1);
-        EXPECT_TRUE(NULL != acl);
-
-        char * jsonStr2 = BinToAclJSON(acl);
-        EXPECT_TRUE(NULL != jsonStr2);
+        defaultAcl->resources[i] = OICStrdup(defaulAclRsrc[i]);
+        ASSERT_TRUE(defaultAcl->resources[i] != NULL);
+    }
+    defaultAcl->ownersLen = 1;
+    uint8_t defaultAclOwnrs[] = {0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32,
+        0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32};
+    defaultAcl->owners = (OicUuid_t *)OICCalloc(1, sizeof(OicUuid_t));
+    ASSERT_TRUE(defaultAcl->owners != NULL);
+    memcpy(defaultAcl->owners[0].id, defaultAclOwnrs, sizeof(defaultAclOwnrs));
+
+    size_t defaultAclSize = 0;
+    uint8_t *defaultPsStorage = NULL;
+    EXPECT_EQ(OC_STACK_OK, AclToCBORPayload(defaultAcl, &defaultPsStorage, &defaultAclSize));
+    ASSERT_TRUE(defaultPsStorage != NULL);
+    EXPECT_NE(0, defaultAclSize);
+
+    // This creates a default file oic_svr_db.dat, which is then needed by unit test.
+    CborEncoder encoder = { 0, 0, 0, 0};
+    const size_t cborSize = 255;
+    uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborSize);
+    ASSERT_TRUE(outPayload != NULL);
+    cbor_encoder_init(&encoder, outPayload, cborSize, 0);
+    CborEncoder map = { 0, 0, 0, 0 };
+    CborError cborEncoderResult = cbor_encoder_create_map(&encoder, &map, CborIndefiniteLength);
+    EXPECT_EQ(CborNoError, cborEncoderResult);
+    cborEncoderResult = cbor_encode_text_string(&map, OIC_JSON_ACL_NAME, strlen(OIC_JSON_ACL_NAME));
+    EXPECT_EQ(CborNoError, cborEncoderResult);
+    cborEncoderResult = cbor_encode_byte_string(&map, defaultPsStorage, defaultAclSize);
+    EXPECT_EQ(CborNoError, cborEncoderResult);
+    cborEncoderResult = cbor_encoder_close_container(&encoder, &map);
+    EXPECT_EQ(CborNoError, cborEncoderResult);
+    OICFree(outPayload);
+    DeleteACLList(defaultAcl);
+    OICFree(defaultPsStorage);
+}
 
-        EXPECT_STREQ(jsonStr1, jsonStr2);
+TEST(ACLResourceTest, CBORACLConversion)
+{
+    OicSecAcl_t *secAcl = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
+    ASSERT_TRUE(secAcl != NULL);
+    uint8_t subjectBytes[] = { 0x2a };
+    memcpy(secAcl->subject.id, subjectBytes, sizeof(subjectBytes));
+    secAcl->permission = 2;
+    const char *rsrc[] = { "/oic/res", "/oic/d", "/oic/p", "/oic/res/types/d",
+                           "/oic/ad", "/oic/sec/acl"};
+    secAcl->resourcesLen = 6;
+    secAcl->resources = (char **)OICCalloc(secAcl->resourcesLen, sizeof(char *));
+    ASSERT_TRUE(secAcl->resources != NULL);
+    for (size_t i = 0 ; i < secAcl->resourcesLen; i++)
+    {
+        secAcl->resources[i] = OICStrdup(rsrc[i]);
+        ASSERT_TRUE(secAcl->resources[i] != NULL);
 
-        OICFree(jsonStr1);
-        OICFree(jsonStr2);
-        DeleteACLList(acl);
     }
+    secAcl->ownersLen = 1;
+    uint8_t ownrs[] = {0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32,
+        0x32, 0x32, 0x32, 0x32, 0x32, 0x32};
+    secAcl->owners = (OicUuid_t *)OICCalloc(1, sizeof(OicUuid_t));
+    ASSERT_TRUE(secAcl->owners != NULL);
+    memcpy(secAcl->owners[0].id, ownrs, sizeof(ownrs));
+
+    OicSecAcl_t *secAcl1 = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
+    ASSERT_TRUE(secAcl1 != NULL);
+    memcpy(secAcl1->subject.id, subjectBytes, sizeof(subjectBytes));
+    secAcl1->permission = 6;
+    const char *rsrc1[] = { "/oic/sec/doxm", "/oic/sec/pstat"};
+    secAcl1->resourcesLen = 2;
+    secAcl1->resources = (char **)OICCalloc(secAcl1->resourcesLen, sizeof(char *));
+    ASSERT_TRUE(secAcl1->resources != NULL);
+    for (size_t i = 0 ; i < secAcl1->resourcesLen; i++)
+    {
+        secAcl1->resources[i] = OICStrdup(rsrc1[i]);
+        ASSERT_TRUE(secAcl1->resources[i] != NULL);
+    }
+    secAcl1->ownersLen = 1;
+    secAcl1->owners = (OicUuid_t *)OICCalloc(1, sizeof(OicUuid_t));
+    ASSERT_TRUE(secAcl1->owners != NULL);
+    memcpy(secAcl1->owners[0].id, ownrs, sizeof(ownrs));
+    secAcl->next = secAcl1;
+
+    OicSecAcl_t *secAcl2 = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
+    ASSERT_TRUE(secAcl2 != NULL);
+    uint8_t subjectBytes1[] = {0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
+        0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31};
+    memcpy(secAcl2->subject.id, subjectBytes1, sizeof(subjectBytes1));
+    secAcl2->permission = 255;
+    const char *rsrc2[] = {"/oic/light", "/oic/fan" };
+    secAcl2->resourcesLen = 2;
+    secAcl2->resources = (char **)OICCalloc(secAcl2->resourcesLen, sizeof(char *));
+    ASSERT_TRUE(secAcl2->resources != NULL);
+    for (size_t i = 0 ; i < secAcl2->resourcesLen; i++)
+    {
+        secAcl2->resources[i] = OICStrdup(rsrc2[i]);
+        ASSERT_TRUE(secAcl2->resources[i] != NULL);
+    }
+    secAcl2->ownersLen = 1;
+    secAcl2->owners = (OicUuid_t *)OICCalloc(1, sizeof(OicUuid_t));
+    ASSERT_TRUE(secAcl2->owners != NULL);
+    memcpy(secAcl2->owners[0].id, ownrs, sizeof(ownrs));
+    secAcl1->next = secAcl2;
+
+    OicSecAcl_t *secAcl3 = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
+    ASSERT_TRUE(secAcl3 != NULL);
+    uint8_t subjectBytes2[] = {0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33,
+                               0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33};
+    memcpy(secAcl3->subject.id, subjectBytes2, sizeof(subjectBytes2));
+    secAcl3->permission = 255;
+    const char *rsrc3[] = {"/oic/light", "/oic/garage" };
+    secAcl3->resourcesLen = 2;
+    secAcl3->resources = (char **)OICCalloc(secAcl3->resourcesLen, sizeof(char *));
+    ASSERT_TRUE(secAcl3->resources != NULL);
+    for (size_t i = 0 ; i < secAcl3->resourcesLen; i++)
+    {
+        secAcl3->resources[i] = OICStrdup(rsrc3[i]);
+        ASSERT_TRUE(secAcl3->resources[i] != NULL);
+    }
+    secAcl3->ownersLen = 2;
+    secAcl3->owners = (OicUuid_t *)OICCalloc(2, sizeof(OicUuid_t));
+    ASSERT_TRUE(secAcl3->owners != NULL);
+    memcpy(secAcl3->owners[0].id, ownrs, sizeof(ownrs));
+    uint8_t ownrs1[] = {0x34, 0x34, 0x34, 0x34, 0x34, 0x34, 0x34, 0x34, 0x34, 0x34,
+                        0x34, 0x34, 0x34, 0x34, 0x34, 0x34};
+    memcpy(secAcl3->owners[1].id, ownrs1, sizeof(ownrs1));
+    secAcl2->next = secAcl3;
+    secAcl3->next = NULL;
+
+    size_t size = 0;
+    uint8_t *psStorage = NULL;
+    EXPECT_EQ(OC_STACK_OK, AclToCBORPayload(secAcl, &psStorage, &size));
+    ASSERT_TRUE(NULL != psStorage);
+    OicSecAcl_t *acl = CBORPayloadToAcl(psStorage, size);
+    ASSERT_TRUE(NULL != acl);
+    EXPECT_EQ(2, acl->permission);
+    EXPECT_EQ(6 , acl->resourcesLen);
+    EXPECT_STREQ("/oic/res", acl->resources[0]);
+    EXPECT_EQ(1, acl->ownersLen);
+    DeleteACLList(acl);
+    OICFree(psStorage);
+    DeleteACLList(secAcl);
+}
+
+//InitResource Tests
+TEST(ACLResourceTest, InitAclResource)
+{
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, InitACLResource());
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, DeInitACLResource());
 }
 
 // Default ACL tests
 TEST(ACLResourceTest, GetDefaultACLTests)
 {
-    // Read default ACL from the file
-    char *jsonStr = ReadFile(DEFAULT_ACL_JSON_FILE_NAME);
-    if (jsonStr)
-    {
-        OicSecAcl_t * acl = JSONToAclBin(jsonStr);
-        EXPECT_TRUE(NULL != acl);
+    uint8_t *payload = NULL;
+    size_t size = 0;
 
-        // Invoke API to generate default ACL
-        OicSecAcl_t * defaultAcl = NULL;
-        OCStackResult ret = GetDefaultACL(&defaultAcl);
-        EXPECT_TRUE(NULL == defaultAcl);
+    ASSERT_TRUE(ReadCBORFile(DEFAULT_ACL_FILE_NAME, &payload, &size));
+    ASSERT_TRUE(payload != NULL);
 
-        EXPECT_TRUE(OC_STACK_ERROR == ret);
+    OicSecAcl_t *psAcl = CBORPayloadToAcl(payload, size);
+    ASSERT_TRUE(psAcl != NULL);
 
-        // Verify if the SRM generated default ACL matches with unit test default
-        if (acl && defaultAcl)
+    OicSecAcl_t *acl = NULL;
+    EXPECT_EQ(OC_STACK_OK, GetDefaultACL(&acl));
+    ASSERT_TRUE(acl != NULL);
+
+    // Verify if the SRM generated default ACL matches with unit test default
+    if (acl && psAcl)
+    {
+        EXPECT_TRUE(memcmp(&(acl->subject), &(psAcl->subject), sizeof(OicUuid_t)) == 0);
+        EXPECT_EQ(acl->resourcesLen, psAcl->resourcesLen);
+        for (size_t i = 0; i < acl->resourcesLen; i++)
         {
-            EXPECT_TRUE(memcmp(&(acl->subject), &(defaultAcl->subject), sizeof(OicUuid_t)) == 0);
-            EXPECT_EQ(acl->resourcesLen, defaultAcl->resourcesLen);
-            for (size_t i = 0; i < acl->resourcesLen; i++)
-            {
-                EXPECT_EQ(strlen(acl->resources[i]), strlen(defaultAcl->resources[i]));
-                EXPECT_TRUE(
-                        memcmp(acl->resources[i], defaultAcl->resources[i],
-                                strlen(acl->resources[i])) == 0);
-            }
-            EXPECT_EQ(acl->permission, defaultAcl->permission);
+            EXPECT_EQ(strlen(acl->resources[i]), strlen(psAcl->resources[i]));
+            EXPECT_TRUE(memcmp(acl->resources[i], psAcl->resources[i],
+                            strlen(acl->resources[i])) == 0);
         }
-
-        // Perform cleanup
-        DeleteACLList(acl);
-        DeleteACLList(defaultAcl);
-        OICFree(jsonStr);
+        EXPECT_EQ(acl->permission, psAcl->permission);
     }
-}
 
+    DeleteACLList(psAcl);
+    DeleteACLList(acl);
+    DeInitACLResource();
+    OICFree(payload);
+}
 
 // 'POST' ACL tests
 TEST(ACLResourceTest, ACLPostTest)
 {
-    OCEntityHandlerRequest ehReq =  OCEntityHandlerRequest();
-
     // Read an ACL from the file
-    char *jsonStr = ReadFile(ACL1_JSON_FILE_NAME);
-    if (jsonStr)
-    {
-        static OCPersistentStorage ps = OCPersistentStorage();
+    uint8_t *payload = NULL;
+    size_t size = 0;
 
-        SetPersistentHandler(&ps, true);
+    ASSERT_TRUE(ReadCBORFile(ACL1_FILE_NAME, &payload, &size));
+    ASSERT_TRUE(NULL != payload);
 
-        // Create Entity Handler POST request payload
-        ehReq.method = OC_REST_POST;
-        ehReq.payload = (OCPayload*)OCSecurityPayloadCreate(jsonStr);
+    OCSecurityPayload *securityPayload = OCSecurityPayloadCBORCreate(payload, size);
+    ASSERT_TRUE(NULL != securityPayload);
 
-        OCEntityHandlerResult ehRet = ACLEntityHandler(OC_REQUEST_FLAG, &ehReq);
-        EXPECT_TRUE(OC_EH_ERROR == ehRet);
+    static OCPersistentStorage ps = OCPersistentStorage();
+    SetPersistentHandler(&ps, true);
 
-        // Convert JSON into OicSecAcl_t for verification
-        OicSecAcl_t * acl = JSONToAclBin(jsonStr);
-        EXPECT_TRUE(NULL != acl);
+    // Create Entity Handler POST request payload
+    OCEntityHandlerRequest ehReq = OCEntityHandlerRequest();
+    ehReq.method = OC_REST_POST;
+    ehReq.payload = (OCPayload *) securityPayload;
 
-        // Verify if SRM contains ACL for the subject
-        OicSecAcl_t* savePtr = NULL;
-        const OicSecAcl_t* subjectAcl = GetACLResourceData(&(acl->subject), &savePtr);
-        EXPECT_TRUE(NULL != subjectAcl);
+    OCEntityHandlerResult ehRet = ACLEntityHandler(OC_REQUEST_FLAG, &ehReq, NULL);
+    EXPECT_EQ(OC_EH_RESOURCE_CREATED, ehRet);
 
-        // Perform cleanup
-        DeleteACLList(acl);
-        DeInitACLResource();
-        OCPayloadDestroy(ehReq.payload);
-        OICFree(jsonStr);
-    }
-}
+    OicSecAcl_t *acl = CBORPayloadToAcl(payload, size);
+    ASSERT_TRUE(NULL != acl);
 
+    // Verify if SRM contains ACL for the subject
+    OicSecAcl_t *savePtr = NULL;
+    const OicSecAcl_t* subjectAcl = GetACLResourceData(&(acl->subject), &savePtr);
+    ASSERT_TRUE(NULL != subjectAcl);
+
+    // Perform cleanup
+    OICFree(payload);
+    OCPayloadDestroy((OCPayload *) securityPayload);
+    DeInitACLResource();
+    DeleteACLList(acl);
+}
 
 // GetACLResource tests
 TEST(ACLResourceTest, GetACLResourceTests)
 {
-    // gAcl is a pointer to the the global ACL used by SRM
-    extern OicSecAcl_t  *gAcl;
-
     // Read an ACL from the file
-    char *jsonStr = ReadFile(ACL1_JSON_FILE_NAME);
-    if (jsonStr)
-    {
-        gAcl = JSONToAclBin(jsonStr);
-        EXPECT_TRUE(NULL != gAcl);
+    static OCPersistentStorage ps = OCPersistentStorage();
+    SetPersistentHandler(&ps, true);
 
-        // Verify that ACL file contains 2 ACE entries for 'WILDCARD' subject
-        const OicSecAcl_t* acl = NULL;
-        OicSecAcl_t* savePtr = NULL;
-        OicUuid_t subject = WILDCARD_SUBJECT_ID;
-        int count = 0;
+    uint8_t *payload = NULL;
+    size_t size = 0;
 
-        do
-        {
-            acl = GetACLResourceData(&subject, &savePtr);
-            count = (NULL != acl) ? count + 1 : count;
-        } while (acl != NULL);
+    ASSERT_TRUE(ReadCBORFile(ACL1_FILE_NAME, &payload, &size));
+    ASSERT_TRUE(payload != NULL);
 
-        EXPECT_EQ(count, NUM_ACE_FOR_WILDCARD_IN_ACL1_JSON);
+    OicSecAcl_t *defaultPsAcl = CBORPayloadToAcl(payload, size);
+    ASSERT_TRUE(defaultPsAcl != NULL);
 
-        /* Perform cleanup */
-        DeleteACLList(gAcl);
-        gAcl = NULL;
-        OICFree(jsonStr);
-    }
+    OicSecAcl_t *acl1 = NULL;
+    EXPECT_EQ(OC_STACK_OK, GetDefaultACL(&acl1));
+    ASSERT_TRUE(acl1 != NULL);
+    EXPECT_EQ(OC_STACK_OK, SetDefaultACL(acl1));
+
+    // Verify that ACL file contains 2 ACE entries for 'WILDCARD' subject
+    const OicSecAcl_t *acl = NULL;
+    OicSecAcl_t *savePtr = NULL;
+    OicUuid_t subject = WILDCARD_SUBJECT_ID;
+    int count = 0;
+
+    do
+    {
+        acl = GetACLResourceData(&subject, &savePtr);
+        count = (NULL != acl) ? count + 1 : count;
+    } while (acl != NULL);
+
+    EXPECT_EQ(count, NUM_ACE_FOR_WILDCARD_IN_ACL1_DAT);
+
+    /* Perform cleanup */
+    OICFree(payload);
+    DeleteACLList(defaultPsAcl);
+    DeInitACLResource();
 }
 
 static OCStackResult  populateAcl(OicSecAcl_t *acl,  int numRsrc)
 {
-    OCStackResult ret = OC_STACK_ERROR;
+     OCStackResult ret = OC_STACK_ERROR;
     memcpy(acl->subject.id, "2222222222222222", sizeof(acl->subject.id));
     acl->resourcesLen = (size_t)numRsrc;
     acl->resources = (char**)OICCalloc(acl->resourcesLen, sizeof(char*));
     VERIFY_NON_NULL(TAG, acl->resources, ERROR);
     acl->resources[0] = (char*)OICMalloc(strlen("/a/led")+1);
     VERIFY_NON_NULL(TAG, acl->resources[0], ERROR);
-    OICStrcpy(acl->resources[0], sizeof(acl->resources[0]), "/a/led");
+    OICStrcpy(acl->resources[0], sizeof(acl->resources[0]) - 1, "/a/led");
     if(numRsrc == 2)
     {
         acl->resources[1] = (char*)OICMalloc(strlen("/a/fan")+1);
         VERIFY_NON_NULL(TAG, acl->resources[1], ERROR);
-        OICStrcpy(acl->resources[1], sizeof(acl->resources[1]), "/a/fan");
+        OICStrcpy(acl->resources[1], sizeof(acl->resources[1]) - 1, "/a/fan");
     }
     acl->permission = 6;
     acl->ownersLen = 1;
@@ -237,158 +361,153 @@ exit:
 //'DELETE' ACL test
 TEST(ACLResourceTest, ACLDeleteWithSingleResourceTest)
 {
-    OCEntityHandlerRequest ehReq = OCEntityHandlerRequest();
-    static OCPersistentStorage ps = OCPersistentStorage();
-    char *jsonStr = NULL;
+    //Populate ACL
     OicSecAcl_t acl = OicSecAcl_t();
-    OicSecAcl_t* savePtr = NULL;
-    const OicSecAcl_t* subjectAcl1 = NULL;
-    const OicSecAcl_t* subjectAcl2 = NULL;
-    OCEntityHandlerResult ehRet = OC_EH_ERROR;
-    char query[] = "sub=MjIyMjIyMjIyMjIyMjIyMg==;rsrc=/a/led";
+    EXPECT_EQ(OC_STACK_OK, populateAcl(&acl, 1));
 
-    SetPersistentHandler(&ps, true);
+    //GET CBOR POST payload
+    size_t size = 0;
+    uint8_t  *payload = NULL;
+    EXPECT_EQ(OC_STACK_OK, AclToCBORPayload(&acl, &payload, &size));
+    ASSERT_TRUE(NULL != payload);
 
-    //Populate ACL
-    VERIFY_SUCCESS(TAG, (OC_STACK_OK == populateAcl(&acl, 1)), ERROR);
+    // Security Payload
+    OCSecurityPayload *securityPayload = OCSecurityPayloadCBORCreate(payload, size);
+    ASSERT_TRUE(NULL != securityPayload);
 
-    //GET json POST payload
-    jsonStr = BinToAclJSON(&acl);
-    VERIFY_NON_NULL(TAG, jsonStr, ERROR);
+    static OCPersistentStorage ps = OCPersistentStorage();
+    SetPersistentHandler(&ps, true);
 
     // Create Entity Handler POST request payload
+    OCEntityHandlerRequest ehReq = OCEntityHandlerRequest();
+    ehReq.payload = (OCPayload *) securityPayload;
     ehReq.method = OC_REST_POST;
-    ehReq.payload = (OCPayload*)OCSecurityPayloadCreate(jsonStr);
-    ehRet = ACLEntityHandler(OC_REQUEST_FLAG, &ehReq);
-    EXPECT_TRUE(OC_EH_ERROR == ehRet);
+    OCEntityHandlerResult ehRet = OC_EH_ERROR;
+    ehRet = ACLEntityHandler(OC_REQUEST_FLAG, &ehReq, NULL);
+    EXPECT_EQ(OC_EH_RESOURCE_CREATED, ehRet);
 
     // Verify if SRM contains ACE for the subject
-    savePtr = NULL;
-    subjectAcl1 = GetACLResourceData(&acl.subject, &savePtr);
-    EXPECT_TRUE(NULL != subjectAcl1);
+    OicSecAcl_t* savePtr = NULL;
+    const OicSecAcl_t* subjectAcl1 = GetACLResourceData(&acl.subject, &savePtr);
+    ASSERT_TRUE(NULL != subjectAcl1);
 
     // Create Entity Handler DELETE request
     ehReq.method = OC_REST_DELETE;
-    ehReq.query = (char*)OICMalloc(strlen(query)+1);
-    VERIFY_NON_NULL(TAG, ehReq.query, ERROR);
+    char query[] = "sub=2222222222222222;rsrc=/a/led";
+    ehReq.query = (char *)OICMalloc(strlen(query)+1);
+    ASSERT_TRUE(NULL !=  ehReq.query);
     OICStrcpy(ehReq.query, strlen(query)+1, query);
-    ehRet = ACLEntityHandler(OC_REQUEST_FLAG, &ehReq);
-    EXPECT_TRUE(OC_EH_ERROR == ehRet);
+    ehRet = ACLEntityHandler(OC_REQUEST_FLAG, &ehReq, NULL);
+    // This returns error as WILDARD is used as a subject query.
+    EXPECT_EQ(OC_EH_RESOURCE_DELETED, ehRet);
 
     // Verify if SRM has deleted ACE for the subject
     savePtr = NULL;
-    subjectAcl2 = GetACLResourceData(&acl.subject, &savePtr);
-    EXPECT_TRUE(NULL == subjectAcl2);
+    const OicSecAcl_t* subjectAcl2 = GetACLResourceData(&acl.subject, &savePtr);
+    ASSERT_TRUE(NULL == subjectAcl2);
 
-exit:
     // Perform cleanup
-    if(NULL != subjectAcl1)
-    {
-        DeInitACLResource();
-    }
-    OCPayloadDestroy(ehReq.payload);
+    DeInitACLResource();
     OICFree(ehReq.query);
-    OICFree(jsonStr);
-
+    OCPayloadDestroy((OCPayload *)securityPayload);
+    OICFree(payload);
 }
 
 TEST(ACLResourceTest, ACLDeleteWithMultiResourceTest)
 {
-    OCEntityHandlerRequest ehReq = OCEntityHandlerRequest();
-    static OCPersistentStorage ps = OCPersistentStorage();
+    //Populate ACL
     OicSecAcl_t acl = OicSecAcl_t();
-    char *jsonStr = NULL;
-    OicSecAcl_t* savePtr = NULL;
-    const OicSecAcl_t* subjectAcl1 = NULL;
-    const OicSecAcl_t* subjectAcl2 = NULL;
-    OCEntityHandlerResult ehRet = OC_EH_ERROR;
-    char query[] = "sub=MjIyMjIyMjIyMjIyMjIyMg==;rsrc=/a/led";
+    EXPECT_EQ(OC_STACK_OK, populateAcl(&acl, 2));
 
-    SetPersistentHandler(&ps, true);
+    //GET CBOR POST payload
+    size_t size = 0;
+    uint8_t *payload = NULL;
+    EXPECT_EQ(OC_STACK_OK, AclToCBORPayload(&acl, &payload, &size));
+    ASSERT_TRUE(NULL != payload);
 
-    //Populate ACL
-    VERIFY_SUCCESS(TAG, (OC_STACK_OK == populateAcl(&acl, 2)), ERROR);
+    // Security Payload
+    OCSecurityPayload *securityPayload = OCSecurityPayloadCBORCreate(payload, size);
+    ASSERT_TRUE(NULL!= securityPayload);
 
-    //GET json POST payload
-    jsonStr = BinToAclJSON(&acl);
-    VERIFY_NON_NULL(TAG, jsonStr, ERROR);
+    static OCPersistentStorage ps = OCPersistentStorage();
+    SetPersistentHandler(&ps, true);
 
     // Create Entity Handler POST request payload
+    OCEntityHandlerRequest ehReq = OCEntityHandlerRequest();
     ehReq.method = OC_REST_POST;
-    ehReq.payload = (OCPayload*)OCSecurityPayloadCreate(jsonStr);
-    ehRet = ACLEntityHandler(OC_REQUEST_FLAG, &ehReq);
-    EXPECT_TRUE(OC_EH_ERROR == ehRet);
+    ehReq.payload = (OCPayload *)securityPayload;
+    OCEntityHandlerResult ehRet = ACLEntityHandler(OC_REQUEST_FLAG, &ehReq, NULL);
+    EXPECT_EQ(OC_EH_RESOURCE_CREATED, ehRet);
 
     // Verify if SRM contains ACE for the subject with two resources
-    savePtr = NULL;
-    subjectAcl1 = GetACLResourceData(&acl.subject, &savePtr);
-    VERIFY_NON_NULL(TAG, subjectAcl1, ERROR);
-    EXPECT_TRUE(subjectAcl1->resourcesLen == 2);
+    OicSecAcl_t* savePtr = NULL;
+    const OicSecAcl_t* subjectAcl1 = GetACLResourceData(&acl.subject, &savePtr);
+    ASSERT_TRUE(NULL != subjectAcl1);
+    EXPECT_EQ(2, subjectAcl1->resourcesLen);
 
     // Create Entity Handler DELETE request
     ehReq.method = OC_REST_DELETE;
-    ehReq.query = (char*)OICMalloc(strlen(query)+1);
-    VERIFY_NON_NULL(TAG, ehReq.query, ERROR);
+    char query[] = "sub=2222222222222222;rsrc=/a/led";
+    ehReq.query = (char *)OICMalloc(strlen(query)+1);
+    ASSERT_TRUE(NULL != ehReq.query);
     OICStrcpy(ehReq.query, strlen(query)+1, query);
 
-    ehRet = ACLEntityHandler(OC_REQUEST_FLAG, &ehReq);
-    EXPECT_TRUE(OC_EH_ERROR == ehRet);
+    ehRet = ACLEntityHandler(OC_REQUEST_FLAG, &ehReq, NULL);
+    EXPECT_EQ(OC_EH_RESOURCE_DELETED, ehRet);
 
     // Verify if SRM contains ACL for the subject but only with one resource
     savePtr = NULL;
-    subjectAcl2 = GetACLResourceData(&acl.subject, &savePtr);
-    VERIFY_NON_NULL(TAG, subjectAcl2, ERROR);
-    EXPECT_TRUE(subjectAcl2->resourcesLen == 1);
+    const OicSecAcl_t* subjectAcl2 = GetACLResourceData(&acl.subject, &savePtr);
+    ASSERT_TRUE(NULL != subjectAcl2);
+    EXPECT_EQ(1, subjectAcl2->resourcesLen);
 
-exit:
     // Perform cleanup
-    if(NULL != subjectAcl1)
-    {
-        DeInitACLResource();
-    }
-    OCPayloadDestroy(ehReq.payload);
+    OCPayloadDestroy((OCPayload *)securityPayload);
+    DeInitACLResource();
     OICFree(ehReq.query);
-    OICFree(jsonStr);
+    OICFree(payload);
 }
 
 //'GET' with query ACL test
-
 TEST(ACLResourceTest, ACLGetWithQueryTest)
 {
-    OCEntityHandlerRequest ehReq = OCEntityHandlerRequest();
-    static OCPersistentStorage ps = OCPersistentStorage();
+    //Populate ACL
     OicSecAcl_t acl = OicSecAcl_t();
-    char *jsonStr = NULL;
-    OCEntityHandlerResult ehRet = OC_EH_ERROR;
-    char query[] = "sub=MjIyMjIyMjIyMjIyMjIyMg==;rsrc=/a/led";
+    EXPECT_EQ(OC_STACK_OK, populateAcl(&acl, 1));
 
-    SetPersistentHandler(&ps, true);
+    //GET CBOR POST payload
+    size_t size = 0;
+    uint8_t *payload = NULL;
+    EXPECT_EQ(OC_STACK_OK, AclToCBORPayload(&acl, &payload, &size));
+    ASSERT_TRUE(NULL != payload);
 
-    //Populate ACL
-    VERIFY_SUCCESS(TAG, (OC_STACK_OK == populateAcl(&acl, 1)), ERROR);
+    // Security Payload
+    OCSecurityPayload *securityPayload = OCSecurityPayloadCBORCreate(payload, size);
+    ASSERT_TRUE(NULL != securityPayload);
 
-    //GET json POST payload
-    jsonStr = BinToAclJSON(&acl);
-    VERIFY_NON_NULL(TAG, jsonStr, ERROR);
+    static OCPersistentStorage ps = OCPersistentStorage();
+    SetPersistentHandler(&ps, true);
 
     //Create Entity Handler POST request payload
+    OCEntityHandlerRequest ehReq = OCEntityHandlerRequest();
     ehReq.method = OC_REST_POST;
-    ehReq.payload = (OCPayload*)OCSecurityPayloadCreate(jsonStr);
-    ehRet = ACLEntityHandler(OC_REQUEST_FLAG, &ehReq);
-    EXPECT_TRUE(OC_EH_ERROR == ehRet);
+    ehReq.payload = (OCPayload *)securityPayload;
+    OCEntityHandlerResult ehRet = ACLEntityHandler(OC_REQUEST_FLAG, &ehReq, NULL);
+    EXPECT_EQ(OC_EH_RESOURCE_CREATED, ehRet);
 
     //Create Entity Handler GET request wit query
-    ehReq.method =  OC_REST_GET;
+    ehReq.method = OC_REST_GET;
+    char query[] = "sub=2222222222222222;rsrc=/a/led";
     ehReq.query = (char*)OICMalloc(strlen(query)+1);
-    VERIFY_NON_NULL(TAG, ehReq.query, ERROR);
+    ASSERT_TRUE(NULL != ehReq.query);
     OICStrcpy(ehReq.query, strlen(query)+1, query);
 
-    ehRet = ACLEntityHandler(OC_REQUEST_FLAG, &ehReq);
-    EXPECT_TRUE(OC_EH_OK == ehRet);
+    ehRet = ACLEntityHandler(OC_REQUEST_FLAG, &ehReq, NULL);
+    EXPECT_EQ(OC_EH_OK, ehRet);
 
-exit:
     // Perform cleanup
-    OCPayloadDestroy(ehReq.payload);
+    OCPayloadDestroy((OCPayload *)securityPayload);
+    DeInitACLResource();
     OICFree(ehReq.query);
-    OICFree(jsonStr);
+    OICFree(payload);
 }
diff --git a/resource/csdk/security/unittest/amaclresourcetest.cpp b/resource/csdk/security/unittest/amaclresourcetest.cpp
new file mode 100644 (file)
index 0000000..d76b162
--- /dev/null
@@ -0,0 +1,165 @@
+//******************************************************************
+//
+// Copyright 2015 Samsung Electronics All Rights Reserved.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+//
+//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
+
+#include "gtest/gtest.h"
+#include "cainterface.h"
+#include "ocstack.h"
+#include "ocpayload.h"
+#include "oic_malloc.h"
+#include "oic_string.h"
+#include "payload_logging.h"
+#include "psinterface.h"
+#include "secureresourcemanager.h"
+#include "securevirtualresourcetypes.h"
+#include "srmresourcestrings.h"
+#include "srmutility.h"
+#include "amaclresource.h"
+#include "security_internals.h"
+
+using namespace std;
+
+#define TAG  "SRM-AMACL-UT"
+
+TEST(AMACLResourceTest, CBORAMACLConversion)
+{
+    OicSecAmacl_t *secAmacl = (OicSecAmacl_t *) OICCalloc(1, sizeof(*secAmacl));
+    ASSERT_TRUE(NULL != secAmacl);
+    uint8_t amss[] = {0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35,
+        0x35, 0x35, 0x35, 0x35, 0x35, 0x35};
+    uint8_t amss1[] = {0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
+        0x36, 0x36, 0x36, 0x36, 0x36, 0x36};
+    secAmacl->amssLen = 2;
+    secAmacl->amss = (OicUuid_t *)OICCalloc(secAmacl->amssLen, sizeof(*secAmacl->amss));
+    if (!secAmacl->amss)
+    {
+        DeleteAmaclList(secAmacl);
+    }
+    ASSERT_TRUE(NULL != secAmacl->amss);
+    memcpy(secAmacl->amss[0].id, amss, sizeof(amss));
+    memcpy(secAmacl->amss[1].id, amss1, sizeof(amss1));
+
+    const char *rsrc[] = { "/a/led", "/a/fan"};
+    secAmacl->resourcesLen = 2;
+    secAmacl->resources = (char **)OICCalloc(secAmacl->resourcesLen,
+                          sizeof(*secAmacl->resources));
+    if (!secAmacl->resources)
+    {
+        DeleteAmaclList(secAmacl);
+    }
+    ASSERT_TRUE(NULL != secAmacl->resources);
+    for (size_t i = 0 ; i < secAmacl->resourcesLen; i++)
+    {
+        secAmacl->resources[i] = OICStrdup(rsrc[i]);
+        ASSERT_TRUE(NULL != secAmacl->resources[i]);
+    }
+    secAmacl->ownersLen = 1;
+    uint8_t ownrs[] = {0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32,
+        0x32, 0x32, 0x32, 0x32, 0x32, 0x32};
+    secAmacl->owners = (OicUuid_t *)OICCalloc(1, sizeof(*secAmacl->owners));
+    if (!secAmacl->owners)
+    {
+        DeleteAmaclList(secAmacl);
+    }
+    ASSERT_TRUE(NULL != secAmacl->owners);
+    memcpy(secAmacl->owners[0].id, ownrs, sizeof(ownrs));
+
+    OicSecAmacl_t *secAmacl1 = (OicSecAmacl_t *) OICCalloc(1, sizeof(*secAmacl1));
+    if (!secAmacl1)
+    {
+        DeleteAmaclList(secAmacl);
+    }
+    ASSERT_TRUE(NULL != secAmacl1);
+    secAmacl1->amssLen = 2;
+    secAmacl1->amss = (OicUuid_t *)OICCalloc(2, sizeof(*secAmacl1->amss));
+    if (!secAmacl1->amss)
+    {
+        DeleteAmaclList(secAmacl);
+        DeleteAmaclList(secAmacl1);
+    }
+    ASSERT_TRUE(NULL != secAmacl1->amss);
+    memcpy(secAmacl1->amss[0].id, amss, sizeof(amss));
+    memcpy(secAmacl1->amss[1].id, amss1, sizeof(amss1));
+
+    const char *rsrc1[] = { "/b/led", "/b/fan"};
+    secAmacl1->resourcesLen = 2;
+    secAmacl1->resources = (char **)OICCalloc(secAmacl1->resourcesLen,
+                            sizeof(*secAmacl1->resources));
+    if (!secAmacl1->resources)
+    {
+        DeleteAmaclList(secAmacl);
+        DeleteAmaclList(secAmacl1);
+    }
+    ASSERT_TRUE(NULL != secAmacl1->resources);
+    for (size_t i = 0 ; i < secAmacl1->resourcesLen; i++)
+    {
+        secAmacl1->resources[i] = OICStrdup(rsrc1[i]);
+        ASSERT_TRUE(NULL != secAmacl1->resources[i]);
+    }
+    secAmacl1->ownersLen = 1;
+    secAmacl1->owners = (OicUuid_t *)OICCalloc(1, sizeof(*secAmacl1->owners));
+    if (!secAmacl1->owners)
+    {
+        DeleteAmaclList(secAmacl);
+        DeleteAmaclList(secAmacl1);
+    }
+    ASSERT_TRUE(NULL != secAmacl1->owners);
+    memcpy(secAmacl1->owners[0].id, ownrs, sizeof(ownrs));
+    secAmacl1->next = NULL;
+    secAmacl->next = secAmacl1;
+
+    size_t size = 0;
+    uint8_t *psStorage = NULL;
+    EXPECT_EQ(OC_STACK_OK, AmaclToCBORPayload(secAmacl, &psStorage, &size));
+    if (!psStorage)
+    {
+        DeleteAmaclList(secAmacl);
+    }
+    ASSERT_TRUE(NULL != psStorage);
+
+    OicSecAmacl_t *amacl = NULL;
+    EXPECT_EQ(OC_STACK_OK, CBORPayloadToAmacl(psStorage, size, &amacl));
+    if (!amacl)
+    {
+        DeleteAmaclList(secAmacl);
+        OICFree(psStorage);
+    }
+    ASSERT_TRUE(NULL != amacl);
+
+    EXPECT_EQ(secAmacl->amssLen, amacl->amssLen);
+    EXPECT_EQ(sizeof(secAmacl->amss[0].id), sizeof(amacl->amss[0].id));
+    EXPECT_EQ(sizeof(secAmacl->amss[1].id), sizeof(amacl->amss[1].id));
+    EXPECT_STREQ(secAmacl->resources[0], amacl->resources[0]);
+    EXPECT_STREQ(secAmacl->resources[1], amacl->resources[1]);
+    EXPECT_EQ(secAmacl->resourcesLen, amacl->resourcesLen);
+    EXPECT_EQ(secAmacl->ownersLen, amacl->ownersLen);
+    EXPECT_EQ(*secAmacl->owners[0].id, *amacl->owners[0].id);
+
+    EXPECT_EQ(secAmacl->next->amssLen, amacl->next->amssLen);
+    EXPECT_EQ(sizeof(secAmacl->next->amss[0].id), sizeof(amacl->next->amss[0].id));
+    EXPECT_STREQ(secAmacl->next->resources[0], amacl->next->resources[0]);
+    EXPECT_STREQ(secAmacl->next->resources[1], amacl->next->resources[1]);
+    EXPECT_EQ(secAmacl->next->resourcesLen, amacl->next->resourcesLen);
+    EXPECT_EQ(secAmacl->next->ownersLen, amacl->next->ownersLen);
+    EXPECT_EQ(*secAmacl->next->owners[0].id, *amacl->next->owners[0].id);
+
+    DeleteAmaclList(secAmacl);
+    DeleteAmaclList(amacl);
+    OICFree(psStorage);
+}
index dd62f15..97ce11b 100644 (file)
@@ -1,3 +1,5 @@
+//******************************************************************
+//
 // Copyright 2015 Intel Mobile Communications GmbH All Rights Reserved.
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #include "gtest/gtest.h"
-#include "ocstack.h"
+#include "logger.h"
 #include "ocpayload.h"
-#include "resourcemanager.h"
-#include "securevirtualresourcetypes.h"
-#include "credresource.h"
+#include "ocstack.h"
 #include "oic_malloc.h"
 #include "oic_string.h"
+#include "resourcemanager.h"
+#include "credresource.h"
+#include "securevirtualresourcetypes.h"
 #include "srmtestcommon.h"
 #include "srmutility.h"
-#include "logger.h"
+#include "psinterface.h"
+#include "security_internals.h"
 
 #define TAG "SRM-CRED-UT"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-//Declare Cred resource methods for testing
-OCStackResult CreateCredResource();
-OCEntityHandlerResult CredEntityHandler (OCEntityHandlerFlag flag,
-                OCEntityHandlerRequest * ehRequest);
-char * BinToCredJSON(const OicSecCred_t * pstat);
-OicSecCred_t * JSONToCredBin(const char * jsonStr);
-void InitSecCredInstance(OicSecCred_t * cred);
-void DeleteCredList(OicSecCred_t* cred);
-const OicSecCred_t* GetCredResourceData(const OicUuid_t* subject);
-
-#ifdef __cplusplus
-}
-#endif
-
-
 OicSecCred_t * getCredList()
 {
-
-    OicSecCred_t * cred = NULL;
     size_t sz = 0;
-
-    cred = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
+    OicSecCred_t *cred = (OicSecCred_t *)OICCalloc(1, sizeof(*cred));
     VERIFY_NON_NULL(TAG, cred, ERROR);
     cred->credId = 1234;
     OICStrcpy((char *)cred->subject.id, sizeof(cred->subject.id), "subject1");
@@ -70,15 +52,14 @@ OicSecCred_t * getCredList()
 #endif
 
     cred->credType = SYMMETRIC_PAIR_WISE_KEY;
-    cred->privateData.data = (char *)OICCalloc(1, strlen("My private Key11") + 1);
+    cred->privateData.data = (uint8_t *)OICCalloc(1, strlen("My private Key11") + 1);
     VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
-    OICStrcpy(cred->privateData.data, strlen("My private Key11")+1,"My private Key11");
+    OICStrcpy((char *)cred->privateData.data, strlen("My private Key11")+1,"My private Key11");
     cred->ownersLen = 1;
-    cred->owners = (OicUuid_t*)OICCalloc(cred->ownersLen, sizeof(OicUuid_t));
+    cred->owners = (OicUuid_t *)OICCalloc(cred->ownersLen, sizeof(*cred->owners));
     VERIFY_NON_NULL(TAG, cred->owners, ERROR);
     OICStrcpy((char *)cred->owners[0].id, sizeof(cred->owners[0].id), "ownersId11");
-
-    cred->next = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
+    cred->next = (OicSecCred_t*)OICCalloc(1, sizeof(*cred->next));
     VERIFY_NON_NULL(TAG, cred->next, ERROR);
     cred->next->credId = 5678;
     OICStrcpy((char *)cred->next->subject.id, sizeof(cred->next->subject.id), "subject2");
@@ -87,9 +68,9 @@ OicSecCred_t * getCredList()
 #endif
     cred->next->credType = SYMMETRIC_PAIR_WISE_KEY;
     sz = strlen("My private Key21") + 1;
-    cred->next->privateData.data = (char *)OICCalloc(1, sz);
+    cred->next->privateData.data = (uint8_t *)OICCalloc(1, sz);
     VERIFY_NON_NULL(TAG, cred->next->privateData.data, ERROR);
-    OICStrcpy(cred->next->privateData.data, sz,"My private Key21");
+    OICStrcpy((char *)cred->next->privateData.data, sz, "My private Key21");
 #if 0
     sz = strlen("My Public Key123") + 1
     cred->next->publicData.data = (char *)OICCalloc(1, sz);
@@ -97,7 +78,7 @@ OicSecCred_t * getCredList()
     OICStrcpy(cred->next->publicData.data, sz,"My Public Key123");
 #endif
     cred->next->ownersLen = 2;
-    cred->next->owners = (OicUuid_t*)OICCalloc(cred->next->ownersLen, sizeof(OicUuid_t));
+    cred->next->owners = (OicUuid_t *)OICCalloc(cred->next->ownersLen, sizeof(*cred->next->owners));
     VERIFY_NON_NULL(TAG, cred->next->owners, ERROR);
     OICStrcpy((char *)cred->next->owners[0].id, sizeof(cred->next->owners[0].id), "ownersId21");
     OICStrcpy((char *)cred->next->owners[1].id, sizeof(cred->next->owners[1].id), "ownersId22");
@@ -118,7 +99,7 @@ static void printCred(const OicSecCred_t * cred)
     EXPECT_TRUE(NULL != cred);
 
     const OicSecCred_t *credTmp1 = NULL;
-    for(credTmp1 = cred; credTmp1; credTmp1 = credTmp1->next)
+    for (credTmp1 = cred; credTmp1; credTmp1 = credTmp1->next)
     {
         OIC_LOG_V(INFO, TAG, "\ncred->credId = %d", credTmp1->credId);
         OIC_LOG_V(INFO, TAG, "cred->subject.id = %s", credTmp1->subject.id);
@@ -127,10 +108,12 @@ static void printCred(const OicSecCred_t * cred)
         {
             OIC_LOG_V(INFO, TAG, "cred->privateData.data = %s", credTmp1->privateData.data);
         }
+#ifdef __WITH_X509__
         if(credTmp1->publicData.data)
         {
            OIC_LOG_V(INFO, TAG, "cred->publicData.data = %s", credTmp1->publicData.data);
         }
+#endif /* __WITH_X509__ */
         OIC_LOG_V(INFO, TAG, "cred->ownersLen = %zu", credTmp1->ownersLen);
         for(size_t i = 0; i < cred->ownersLen; i++)
         {
@@ -140,68 +123,78 @@ static void printCred(const OicSecCred_t * cred)
 }
 
  //InitCredResource Tests
-TEST(InitCredResourceTest, InitCredResource)
+TEST(CredResourceTest, InitCredResource)
 {
     EXPECT_EQ(OC_STACK_INVALID_PARAM, InitCredResource());
 }
 
 //DeInitCredResource Tests
-TEST(DeInitCredResourceTest, DeInitCredResource)
+TEST(CredResourceTest, DeInitCredResource)
 {
     EXPECT_EQ(OC_STACK_INVALID_PARAM, DeInitCredResource());
 }
 
 //CreateCredResource Tests
-TEST(CreateCredResourceTest, CreateCredResource)
+TEST(CredResourceTest, CreateCredResource)
 {
     EXPECT_EQ(OC_STACK_INVALID_PARAM, CreateCredResource());
 }
 
  //CredEntityHandler Tests
-TEST(CredEntityHandlerTest, CredEntityHandlerWithDummyRequest)
+TEST(CredResourceTest, CredEntityHandlerWithDummyRequest)
 {
-    OCEntityHandlerRequest req;
+    OCEntityHandlerRequest req = OCEntityHandlerRequest();
     EXPECT_EQ(OC_EH_ERROR,
-            CredEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req));
+            CredEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req, NULL));
 }
 
-TEST(CredEntityHandlerTest, CredEntityHandlerWithNULLRequest)
+TEST(CredResourceTest, CredEntityHandlerWithNULLRequest)
 {
     EXPECT_EQ(OC_EH_ERROR,
-            CredEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, NULL));
+            CredEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, NULL, NULL));
 }
 
-TEST(CredEntityHandlerTest, CredEntityHandlerInvalidFlag)
+TEST(CredResourceTest, CredEntityHandlerInvalidFlag)
 {
-    OCEntityHandlerRequest req;
+    OCEntityHandlerRequest req = OCEntityHandlerRequest();
     EXPECT_EQ(OC_EH_ERROR,
-            CredEntityHandler(OCEntityHandlerFlag::OC_OBSERVE_FLAG, &req));
+            CredEntityHandler(OCEntityHandlerFlag::OC_OBSERVE_FLAG, &req, NULL));
 }
 
 //Cred DELETE request
-TEST(CredEntityHandlerTest, CredEntityHandlerDeleteTest)
+TEST(CredResourceTest, CredEntityHandlerDeleteTest)
 {
     OCEntityHandlerRequest ehReq =  OCEntityHandlerRequest();
     static OCPersistentStorage ps =  OCPersistentStorage();
     const OicSecCred_t* subjectCred1 = NULL;
     const OicSecCred_t* subjectCred2 = NULL;
-    char *jsonStr = NULL;
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
-    char query[] = "sub=c3ViamVjdDE=";
+    char query[] = "sub=c3ViamVjdDE="; //base64 Encoding of subject1
 
     SetPersistentHandler(&ps, true);
 
     OicSecCred_t *cred = getCredList();
-    VERIFY_NON_NULL(TAG, cred, ERROR);
+    ASSERT_TRUE(NULL != cred);
 
-    jsonStr = BinToCredJSON(cred);
-    VERIFY_NON_NULL(TAG, jsonStr, ERROR);
+    uint8_t *payload = NULL;
+    size_t size = 0;
+    EXPECT_EQ(OC_STACK_OK, CredToCBORPayload(cred, &payload, &size));
+    if (!payload)
+    {
+        DeleteCredList(cred);
+    }
+    ASSERT_TRUE(NULL != payload);
 
     // Create Entity Handler POST request payload
     ehReq.method = OC_REST_POST;
-    ehReq.payload = (OCPayload*)OCSecurityPayloadCreate(jsonStr);
-    ehRet = CredEntityHandler(OC_REQUEST_FLAG, &ehReq);
-    EXPECT_TRUE(OC_EH_ERROR == ehRet);
+    ehReq.payload = (OCPayload *)OCSecurityPayloadCBORCreate(payload, size);
+    if (!ehReq.payload)
+    {
+        OICFree(payload);
+        DeleteCredList(cred);
+    }
+    ASSERT_TRUE( NULL != ehReq.payload);
+    EXPECT_EQ(OC_EH_ERROR, CredEntityHandler(OC_REQUEST_FLAG, &ehReq, NULL));
 
     // Verify if SRM contains Credential for the subject
     subjectCred1 = GetCredResourceData(&cred->subject);
@@ -209,96 +202,126 @@ TEST(CredEntityHandlerTest, CredEntityHandlerDeleteTest)
 
    // Create Entity Handler DELETE request
    ehReq.method = OC_REST_DELETE;
-   ehReq.query = (char*)OICMalloc(strlen(query)+1);
-   VERIFY_NON_NULL(TAG, ehReq.query, ERROR);
+   ehReq.query = (char *)OICCalloc(1, strlen(query)+1);
+   if (!ehReq.query)
+   {
+       OICFree(payload);
+       DeleteCredList(cred);
+   }
+   ASSERT_TRUE(NULL != ehReq.query);
    OICStrcpy(ehReq.query, strlen(query)+1, query);
 
-   ehRet = CredEntityHandler(OC_REQUEST_FLAG, &ehReq);
-   EXPECT_TRUE(OC_EH_ERROR == ehRet);
+   ehRet = CredEntityHandler(OC_REQUEST_FLAG, &ehReq, NULL);
+   EXPECT_EQ(OC_EH_ERROR, ehRet);
 
    // Verify if SRM has deleted ACE for the subject
    subjectCred2 = GetCredResourceData(&cred->subject);
    EXPECT_TRUE(NULL == subjectCred2);
 
-exit:
    // Perform cleanup
    OICFree(ehReq.query);
-   OICFree(jsonStr);
-   OCPayloadDestroy(ehReq.payload);
-   if(NULL != cred)
-   {
-       DeInitCredResource();
-       DeleteCredList(cred);
-   }
+   OICFree(payload);
+   DeInitCredResource();
+   DeleteCredList(cred);
+   OCPayloadDestroy((OCPayload *)ehReq.payload);
 }
 
-//BinToCredJSON Tests
-TEST(BinToCredJSONTest, BinToCredJSONNullCred)
+TEST(CredResourceTest, CredToCBORPayloadNULL)
 {
-    char* value = BinToCredJSON(NULL);
-    EXPECT_TRUE(value == NULL);
+    OicSecCred_t *cred = getCredList();
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, CredToCBORPayload(NULL, NULL, 0));
+    size_t size = 0;
+    uint8_t *cborPayload = (uint8_t *) OICCalloc(1, 10);
+    if (!cborPayload)
+    {
+        DeleteCredList(cred);
+    }
+    ASSERT_TRUE(NULL != cborPayload);
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, CredToCBORPayload(cred, &cborPayload, &size));
+    OICFree(cborPayload);
+    cborPayload = NULL;
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, CredToCBORPayload(NULL, &cborPayload, &size));
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, CredToCBORPayload(cred, &cborPayload, 0));
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, CredToCBORPayload(cred, NULL, &size));
+    DeleteCredList(cred);
 }
 
-TEST(BinToCredJSONTest, BinToCredJSONValidCred)
+TEST(CredResourceTest, CredToCBORPayloadVALID)
 {
-    char* json = NULL;
-    OicSecCred_t * cred = getCredList();
+    uint8_t* payload = NULL;
+    size_t size = 0;
+    OicSecCred_t *cred = getCredList();
 
-    json = BinToCredJSON(cred);
+    EXPECT_EQ(OC_STACK_OK, CredToCBORPayload(cred, &payload, &size));
+    if (!payload)
+    {
+        DeleteCredList(cred);
+    }
+    ASSERT_TRUE(NULL != payload);
 
-    OIC_LOG_V(INFO, TAG, "BinToCredJSON:%s\n", json);
-    EXPECT_TRUE(json != NULL);
     DeleteCredList(cred);
-    OICFree(json);
+    OICFree(payload);
 }
 
-//JSONToCredBin Tests
-TEST(JSONToCredBinTest, JSONToCredBinValidJSON)
+TEST(CredResourceTest, CBORPayloadToCredVALID)
 {
-    OicSecCred_t* cred1 = getCredList();
-    char* json = BinToCredJSON(cred1);
+    OicSecCred_t *cred1 = getCredList();
 
-    EXPECT_TRUE(json != NULL);
-    OicSecCred_t *cred2 = JSONToCredBin(json);
-    EXPECT_TRUE(cred2 != NULL);
+    uint8_t *payload = NULL;
+    size_t size = 0;
+    EXPECT_EQ(OC_STACK_OK, CredToCBORPayload(cred1, &payload, &size));
     DeleteCredList(cred1);
+    ASSERT_TRUE(NULL != payload);
+
+    OicSecCred_t *cred2 = NULL;
+    EXPECT_EQ(OC_STACK_OK, CBORPayloadToCred(payload, size, &cred2));
+    OICFree(payload);
+    ASSERT_TRUE(cred2 != NULL);
     DeleteCredList(cred2);
-    OICFree(json);
 }
 
-TEST(JSONToCredBinTest, JSONToCredBinNullJSON)
+TEST(CredResourceTest, CBORPayloadToCredNULL)
 {
-    OicSecCred_t *cred = JSONToCredBin(NULL);
-    EXPECT_TRUE(cred == NULL);
+    OicSecCred_t *cred = NULL;
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, CBORPayloadToCred(NULL, 0, NULL));
+    uint8_t *cborPayload = (uint8_t *) OICCalloc(1, 10);
+    ASSERT_TRUE(NULL != cborPayload);
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, CBORPayloadToCred(NULL, 0, &cred));
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, CBORPayloadToCred(cborPayload, 0, NULL));
+    cred = getCredList();
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, CBORPayloadToCred(cborPayload, 0, &cred));
+    DeleteCredList(cred);
+    OICFree(cborPayload);
 }
 
 //GetCredResourceData Test
-TEST(CredGetResourceDataTest, GetCredResourceDataNULLSubject)
+TEST(CredResourceTest, GetCredResourceDataNULLSubject)
 {
-    EXPECT_TRUE(NULL == GetCredResourceData(NULL));
+    EXPECT_EQ(NULL, GetCredResourceData(NULL));
 }
 
-TEST(CredGenerateCredentialTest, GenerateCredentialValidInput)
+TEST(CredResourceTest, GenerateCredentialValidInput)
 {
     OicUuid_t owners[1];
-    OICStrcpy((char *)owners[0].id, sizeof(owners[0].id), "ownersId21");
+    OICStrcpy((char *)owners[0].id, strlen("ownersId21"), "ownersId21");
 
     OicUuid_t subject = {{0}};
-    OICStrcpy((char *)subject.id, sizeof(subject.id), "subject11");
+    OICStrcpy((char *)subject.id, strlen("subject11"), "subject11");
 
-    char privateKey[] = "My private Key11";
+    uint8_t privateKey[] = "My private Key11";
+    OicSecKey_t key = {privateKey, sizeof(privateKey)};
 
     OicSecCred_t * cred  = NULL;
 
     cred = GenerateCredential(&subject, SYMMETRIC_PAIR_WISE_KEY, NULL,
-                             privateKey, 1, owners);
+                              &key, 1, owners);
     printCred(cred);
 
-    EXPECT_TRUE(NULL != cred);
+    ASSERT_TRUE(NULL != cred);
     DeleteCredList(cred);
 }
 
-TEST(GenerateAndAddCredentialTest, GenerateAndAddCredentialValidInput)
+TEST(CredResourceTest, GenerateAndAddCredentialValidInput)
 {
     OicUuid_t owners[1];
     OICStrcpy((char *)owners[0].id, sizeof(owners[0].id), "ownersId11");
@@ -306,35 +329,35 @@ TEST(GenerateAndAddCredentialTest, GenerateAndAddCredentialValidInput)
     OicUuid_t subject = {{0}};
     OICStrcpy((char *)subject.id, sizeof(subject.id), "subject11");
 
-    char privateKey[] = "My private Key11";
+    uint8_t privateKey[] = "My private Key11";
+    OicSecKey_t key = {privateKey, sizeof(privateKey)};
 
-    OicSecCred_t * cred1  = NULL;
-    OicSecCred_t * headCred = NULL;
+    OicSecCred_t *cred1  = NULL;
+    OicSecCred_t *headCred = NULL;
 
     cred1 = GenerateCredential(&subject, SYMMETRIC_PAIR_WISE_KEY, NULL,
-                                 privateKey, 1, owners);
+                               &key, 1, owners);
 
-    EXPECT_EQ(OC_STACK_ERROR, AddCredential(cred1));
+    EXPECT_EQ(OC_STACK_OK, AddCredential(cred1));
     headCred = cred1;
 
     OICStrcpy((char *)owners[0].id, sizeof(owners[0].id), "ownersId22");
     OICStrcpy((char *)subject.id, sizeof(subject.id), "subject22");
     cred1 = GenerateCredential(&subject, SYMMETRIC_PAIR_WISE_KEY, NULL,
-                                     privateKey, 1, owners);
-    EXPECT_EQ(OC_STACK_ERROR, AddCredential(cred1));
+                               &key, 1, owners);
+    EXPECT_EQ(OC_STACK_OK, AddCredential(cred1));
 
     OICStrcpy((char *)owners[0].id, sizeof(owners[0].id), "ownersId33");
     OICStrcpy((char *)subject.id, sizeof(subject.id), "subject33");
     cred1 = GenerateCredential(&subject, SYMMETRIC_PAIR_WISE_KEY, NULL,
-                                     privateKey, 1, owners);
-    EXPECT_EQ(OC_STACK_ERROR, AddCredential(cred1));
+                               &key, 1, owners);
+    EXPECT_EQ(OC_STACK_OK, AddCredential(cred1));
 
     const OicSecCred_t* credList = GetCredResourceData(&headCred->subject);
 
     printCred(credList);
 
     DeleteCredList(headCred);
-
 }
 
 #if 0
@@ -344,5 +367,3 @@ TEST(CredGetResourceDataTest, GetCredResourceDataValidSubject)
     EXPECT_TRUE(NULL != GetCredResourceData(cred->subject));
 }
 #endif
-
-
index f303030..a26ae14 100644 (file)
@@ -1,3 +1,5 @@
+//******************************************************************
+//
 // Copyright 2015 Intel Mobile Communications GmbH All Rights Reserved.
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #include "gtest/gtest.h"
 #include "ocstack.h"
+#include "ocserverrequest.h"
+#include "oic_string.h"
+#include "oic_malloc.h"
 #include "resourcemanager.h"
 #include "securevirtualresourcetypes.h"
 #include "srmresourcestrings.h"
 #include "doxmresource.h"
-#include "ocserverrequest.h"
-#include "oic_string.h"
-#include "oic_malloc.h"
-#include "logger.h"
+#include "security_internals.h"
 
 #define TAG  "SRM-DOXM"
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-
-//Declare Doxm resource methods for testing
-OCStackResult CreateDoxmResource();
-OCEntityHandlerResult DoxmEntityHandler (OCEntityHandlerFlag flag,
-                OCEntityHandlerRequest * ehRequest);
-char * BinToDoxmJSON(const OicSecDoxm_t * doxm);
-OicSecDoxm_t * JSONToDoxmBin(const char * jsonStr);
-void InitSecDoxmInstance(OicSecDoxm_t * doxm);
-OCEntityHandlerResult HandleDoxmPostRequest (const OCEntityHandlerRequest * ehRequest);
-void DeleteDoxmBinData(OicSecDoxm_t* doxm);
-OCEntityHandlerResult HandleDoxmGetRequest (const OCEntityHandlerRequest * ehRequest);
-#ifdef __cplusplus
-}
-#endif
-
-
 OicSecDoxm_t * getBinDoxm()
 {
-    OicSecDoxm_t * doxm = (OicSecDoxm_t*)OICCalloc(1, sizeof(OicSecDoxm_t));
-    if(!doxm)
+    OicSecDoxm_t *doxm = (OicSecDoxm_t *)OICCalloc(1, sizeof(*doxm));
+    if (!doxm)
     {
         return NULL;
     }
     doxm->oxmTypeLen =  1;
-    doxm->oxmType    = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(char *));
-    if(!doxm->oxmType)
+    doxm->oxmType = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(*doxm->oxmType));
+    if (!doxm->oxmType)
     {
         OICFree(doxm);
         return NULL;
     }
-    doxm->oxmType[0] = (char*)OICMalloc(strlen(OXM_JUST_WORKS) + 1);
-    if(!doxm->oxmType[0])
+    doxm->oxmType[0] = (char *) OICMalloc(strlen(OXM_JUST_WORKS) + 1);
+    if (!doxm->oxmType[0])
     {
         OICFree(doxm->oxmType);
         OICFree(doxm);
@@ -88,109 +70,134 @@ OicSecDoxm_t * getBinDoxm()
     doxm->owned      = true;
     //TODO: Need more clarification on deviceIDFormat field type.
     //doxm.deviceIDFormat = URN;
-    OICStrcpy((char *) doxm->deviceID.id, strlen("deviceId") + 1, "deviceId");
-    OICStrcpy((char *) doxm->owner.id, strlen("ownersId") + 1, "ownersId");
+
+    uint8_t deviceId[] = {0x64, 0x65, 0x76, 0x69, 0x63, 0x65, 0x49, 0x64};
+    memcpy(doxm->deviceID.id, deviceId, sizeof(deviceId));
+    uint8_t ownerId[] = {0x6f, 0x77, 0x6e, 0x65, 0x72, 0x73, 0x49, 0x64};
+    memcpy(doxm->owner.id, ownerId, sizeof(ownerId));
     return doxm;
 }
 
  //InitDoxmResource Tests
-TEST(InitDoxmResourceTest, InitDoxmResource)
+TEST(DoxmResourceTest, InitDoxmResource)
 {
     EXPECT_EQ(OC_STACK_INVALID_PARAM, InitDoxmResource());
 }
 
 //DeInitDoxmResource Tests
-TEST(DeInitDoxmResourceTest, DeInitDoxmResource)
+TEST(DoxmResourceTest, DeInitDoxmResource)
 {
     EXPECT_EQ(OC_STACK_ERROR, DeInitDoxmResource());
 }
 
 //CreateDoxmResource Tests
-TEST(CreateDoxmResourceTest, CreateDoxmResource)
+TEST(DoxmResourceTest, CreateDoxmResource)
 {
     EXPECT_EQ(OC_STACK_INVALID_PARAM, CreateDoxmResource());
 }
 
  //DoxmEntityHandler Tests
-TEST(DoxmEntityHandlerTest, DoxmEntityHandlerWithDummyRequest)
+TEST(DoxmResourceTest, DoxmEntityHandlerWithDummyRequest)
 {
-    OCEntityHandlerRequest req;
-    EXPECT_EQ(OC_EH_ERROR, DoxmEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req));
+    OCEntityHandlerRequest req = OCEntityHandlerRequest();
+    EXPECT_EQ(OC_EH_ERROR, DoxmEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req, NULL));
 }
 
-TEST(DoxmEntityHandlerTest, DoxmEntityHandlerWithNULLRequest)
+TEST(DoxmResourceTest, DoxmEntityHandlerWithNULLRequest)
 {
-    EXPECT_EQ(OC_EH_ERROR, DoxmEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, NULL));
+    EXPECT_EQ(OC_EH_ERROR, DoxmEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, NULL, NULL));
 }
 
-TEST(DoxmEntityHandlerTest, DoxmEntityHandlerInvalidFlag)
+TEST(DoxmResourceTest, DoxmEntityHandlerInvalidFlag)
 {
-    OCEntityHandlerRequest req;
-    EXPECT_EQ(OC_EH_ERROR, DoxmEntityHandler(OCEntityHandlerFlag::OC_OBSERVE_FLAG, &req));
+    OCEntityHandlerRequest req = OCEntityHandlerRequest();
+    EXPECT_EQ(OC_EH_ERROR, DoxmEntityHandler(OCEntityHandlerFlag::OC_OBSERVE_FLAG, &req, NULL));
 }
 
-TEST(DoxmEntityHandlerTest, DoxmEntityHandlerValidRequest)
+TEST(DoxmResourceTest, DoxmEntityHandlerValidRequest)
 {
     EXPECT_EQ(OC_STACK_INVALID_PARAM, InitDoxmResource());
     char query[] = "oxm=0;owned=false;owner=owner1";
     OCEntityHandlerRequest req = OCEntityHandlerRequest();
     req.method = OC_REST_GET;
     req.query = OICStrdup(query);
-    EXPECT_EQ(OC_EH_ERROR, DoxmEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req));
+    EXPECT_EQ(OC_EH_ERROR, DoxmEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req, NULL));
 
     OICFree(req.query);
 }
 
-TEST(DoxmEntityHandlerTest, DoxmEntityHandlerDeviceIdQuery)
+TEST(DoxmResourceTest, DoxmEntityHandlerDeviceIdQuery)
 {
     EXPECT_EQ(OC_STACK_INVALID_PARAM, InitDoxmResource());
-    char query[] = "deviceid=MjIyMjIyMjIyMjIyMjIyMg==";
+    char query[] = "deviceid=2222222222222222";
     OCEntityHandlerRequest req = OCEntityHandlerRequest();
     req.method = OC_REST_GET;
     req.query = OICStrdup(query);
-    EXPECT_EQ(OC_EH_ERROR, DoxmEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req));
+    EXPECT_EQ(OC_EH_ERROR, DoxmEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req, NULL));
 
     OICFree(req.query);
 }
 
-//BinToDoxmJSON Tests
-TEST(BinToDoxmJSONTest, BinToDoxmJSONNullDoxm)
+TEST(DoxmResourceTest, DoxmToCBORPayloadNULL)
 {
-    char* value = BinToDoxmJSON(NULL);
-    EXPECT_TRUE(value == NULL);
+    OicSecDoxm_t *doxm =  getBinDoxm();
+    size_t size = 10;
+    uint8_t *payload = NULL;
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, DoxmToCBORPayload(NULL, NULL, 0));
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, DoxmToCBORPayload(doxm, NULL, &size));
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, DoxmToCBORPayload(doxm, &payload, 0));
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, DoxmToCBORPayload(NULL, &payload, &size));
+    DeleteDoxmBinData(doxm);
 }
 
-TEST(BinToDoxmJSONTest, BinToDoxmJSONValidDoxm)
+TEST(DoxmResourceTest, DoxmToCBORPayloadVALID)
 {
-    OicSecDoxm_t * doxm =  getBinDoxm();
+    OicSecDoxm_t *doxm =  getBinDoxm();
 
-    char * json = BinToDoxmJSON(doxm);
-    OIC_LOG_V(INFO, TAG, "BinToDoxmJSON:%s", json);
-    EXPECT_TRUE(json != NULL);
+    uint8_t *payload = NULL;
+    size_t size = 0;
+    EXPECT_EQ(OC_STACK_OK, DoxmToCBORPayload(doxm, &payload, &size));
+    EXPECT_TRUE(payload != NULL);
 
     DeleteDoxmBinData(doxm);
-    OICFree(json);
+    OICFree(payload);
 }
 
-//JSONToDoxmBin Tests
-TEST(JSONToDoxmBinTest, JSONToDoxmBinValidJSON)
+//CBORPayloadToDoxm Tests
+TEST(DoxmResourceTest, CBORPayloadToDoxmNULL)
 {
-    OicSecDoxm_t * doxm1 =  getBinDoxm();
-    char * json = BinToDoxmJSON(doxm1);
-    EXPECT_TRUE(json != NULL);
-
-    OicSecDoxm_t *doxm2 = JSONToDoxmBin(json);
-    EXPECT_TRUE(doxm2 != NULL);
-
-    DeleteDoxmBinData(doxm1);
-    DeleteDoxmBinData(doxm2);
-    OICFree(json);
+    OicSecDoxm_t *doxm = NULL;
+    uint8_t *cborPayload = (uint8_t *)OICCalloc(1, sizeof(uint8_t));
+    size_t size = 10;
+    ASSERT_TRUE(NULL != cborPayload);
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, CBORPayloadToDoxm(NULL, 0, NULL));
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, CBORPayloadToDoxm(NULL, size, &doxm));
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, CBORPayloadToDoxm(cborPayload, size, NULL));
+    OICFree(cborPayload);
 }
 
-TEST(JSONToDoxmBinTest, JSONToDoxmBinNullJSON)
+TEST(DoxmResourceTest, CBORPayloadToDoxmVALID)
 {
-    OicSecDoxm_t *doxm = JSONToDoxmBin(NULL);
-    EXPECT_TRUE(doxm == NULL);
+    OicSecDoxm_t *doxm =  getBinDoxm();
+    uint8_t *payload = NULL;
+    size_t size = 0;
+    EXPECT_EQ(OC_STACK_OK, DoxmToCBORPayload(doxm, &payload, &size));
+    EXPECT_TRUE(payload != NULL);
+
+    OicSecDoxm_t *doxmSec = NULL;
+    EXPECT_EQ(OC_STACK_OK, CBORPayloadToDoxm(payload, size, &doxmSec));
+    ASSERT_TRUE(doxmSec != NULL);
+    EXPECT_EQ(doxmSec->oxmTypeLen, doxm->oxmTypeLen);
+    EXPECT_STREQ(doxmSec->oxmType[0], doxm->oxmType[0]);
+    EXPECT_EQ(doxmSec->oxmLen, doxm->oxmLen);
+    EXPECT_EQ(doxmSec->oxm[0], doxm->oxm[0]);
+    EXPECT_EQ(doxmSec->oxmSel, doxm->oxmSel);
+    EXPECT_EQ(doxmSec->sct, doxm->sct);
+    EXPECT_EQ(doxmSec->owned, doxm->owned);
+
+    DeleteDoxmBinData(doxmSec);
+    DeleteDoxmBinData(doxm);
+    OICFree(payload);
 }
 
 #if 0
diff --git a/resource/csdk/security/unittest/oic_svr_db.dat b/resource/csdk/security/unittest/oic_svr_db.dat
new file mode 100644 (file)
index 0000000..bf1647b
Binary files /dev/null and b/resource/csdk/security/unittest/oic_svr_db.dat differ
diff --git a/resource/csdk/security/unittest/oic_unittest.dat b/resource/csdk/security/unittest/oic_unittest.dat
new file mode 100644 (file)
index 0000000..8d39ad7
Binary files /dev/null and b/resource/csdk/security/unittest/oic_unittest.dat differ
diff --git a/resource/csdk/security/unittest/oic_unittest_acl1.dat b/resource/csdk/security/unittest/oic_unittest_acl1.dat
new file mode 100644 (file)
index 0000000..14c6db7
Binary files /dev/null and b/resource/csdk/security/unittest/oic_unittest_acl1.dat differ
index a179c2c..91ee7b4 100644 (file)
@@ -1,53 +1,26 @@
-{
-    "acl": [
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/res",
-                "/oic/d",
-                "/oic/p",
-                "/oic/res/types/d",
-                "/oic/ad",
-                "/oic/sec/acl"
-                       ],
-                       "perms": 2,
-                       "ownrs" : [
-                               "MjIyMjIyMjIyMjIyMjIyMg=="
-                       ]
-               },
-        {
-            "sub": "Kg==",
-            "rsrc": [
-                "/oic/sec/doxm",
-                "/oic/sec/pstat"
-                       ],
-                       "perms": 6,
-                       "ownrs" : [
-                               "MjIyMjIyMjIyMjIyMjIyMg=="
-                       ]
-               },
-        {
-            "sub": "MTExMTExMTExMTExMTExMQ==",
-            "rsrc": [
-                               "/oic/light",
-                               "/oic/fan"
-                       ],
-                       "perms": 255,
-                       "ownrs" : [
-                               "MjIyMjIyMjIyMjIyMjIyMg=="
-                       ]
-               },
-               {
-            "sub": "MzMzMzMzMzMzMzMzMzMzMw==",
-            "rsrc": [
-                               "/oic/light",
-                               "/oic/garage"
-                       ],
-                       "perms": 255,
-                       "ownrs" : [
-                               "MjIyMjIyMjIyMjIyMjIyMg==",
-                "NDQ0NDQ0NDQ0NDQ0NDQ0NA=="
-                       ]
-               }
-       ]
-}
+[
+  {
+    "sub":"Kg",
+    "rsrc":["/oic/res","/oic/d","/oic/p","/oic/res/types/d","/oic/ad","/oic/sec/acl"],
+    "perms":2,
+    "ownrs":["MjIyMjIyMjIyMjIyMjIyMg"]
+  },
+  {
+    "sub":"Kg",
+    "rsrc":["/oic/sec/doxm","/oic/sec/pstat"],
+    "perms":6,
+    "ownrs":["MjIyMjIyMjIyMjIyMjIyMg"]
+  },
+  {
+    "sub":"MTExMTExMTExMTExMTExMQ",
+    "rsrc":["/oic/light","/oic/fan"],
+    "perms":255,
+    "ownrs":["MjIyMjIyMjIyMjIyMjIyMg"]
+  },
+  {
+    "sub":"MzMzMzMzMzMzMzMzMzMzMw",
+    "rsrc":["/oic/light","/oic/garage"],
+    "perms":255,
+    "ownrs":["MjIyMjIyMjIyMjIyMjIyMg","NDQ0NDQ0NDQ0NDQ0NDQ0NA"]
+  }
+]
diff --git a/resource/csdk/security/unittest/oic_unittest_default_acl.dat b/resource/csdk/security/unittest/oic_unittest_default_acl.dat
new file mode 100644 (file)
index 0000000..f284271
Binary files /dev/null and b/resource/csdk/security/unittest/oic_unittest_default_acl.dat differ
index 03c8a68..a14209c 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+#include <unistd.h>
 #include "gtest/gtest.h"
+
+#include "ocpayload.h"
 #include "ocstack.h"
-#include "resourcemanager.h"
-#include "pstatresource.h"
 #include "oic_malloc.h"
-#include "cJSON.h"
-#include "base64.h"
 #include "cainterface.h"
+#include "resourcemanager.h"
 #include "secureresourcemanager.h"
-#include "srmtestcommon.h"
-#include "ocpayload.h"
-#include <unistd.h>
-#ifdef __cplusplus
-extern "C" {
-#endif
-//Declare Provision status resource methods for testing
-OCStackResult CreatePstatResource();
-OCEntityHandlerResult PstatEntityHandler (OCEntityHandlerFlag flag,
-                                        OCEntityHandlerRequest * ehRequest);
-char * BinToPstatJSON(const OicSecPstat_t * pstat);
-OicSecPstat_t * JSONToPstatBin(const char * jsonStr);
-const char* UNIT_TEST_JSON_FILE_NAME = "oic_unittest.json";
-#ifdef __cplusplus
-}
-#endif
+#include "pstatresource.h"
+#include "security_internals.h"
 
-//InitPstatResource Tests
-TEST(InitPstatResourceTest, InitPstatResource)
+// InitPstatResource Tests
+TEST(PstatResourceTest, InitPstatResource)
 {
-    EXPECT_EQ(OC_STACK_INVALID_PARAM,  InitPstatResource());
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, InitPstatResource());
 }
 
-
-//DeInitPstatResource Tests
-TEST(DeInitPstatResourceTest, DeInitPstatResource)
+// DeInitPstatResource Tests
+TEST(PstatResourceTest, DeInitPstatResource)
 {
     EXPECT_EQ(OC_STACK_INVALID_PARAM, DeInitPstatResource());
 }
 
 //CreatePstatResource Tests
-TEST(CreatePstatResourceTest, CreatePstatResource)
+TEST(PstatResourceTest, CreatePstatResource)
 {
-    EXPECT_EQ(OC_STACK_INVALID_PARAM,  CreatePstatResource());
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, CreatePstatResource());
 }
 
 //PstatEntityHandler Tests
-TEST(PstatEntityHandlerTest, PstatEntityHandlerWithDummyRequest)
+TEST(PstatResourceTest, PstatEntityHandlerWithDummyRequest)
 {
-    OCEntityHandlerRequest req;
+    OCEntityHandlerRequest req = OCEntityHandlerRequest();
     EXPECT_EQ(OC_EH_ERROR, PstatEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req));
 }
 
-TEST(PstatEntityHandlerTest, PstatEntityHandlerWithPostRequest)
+TEST(PstatResourceTest, PstatEntityHandlerWithPostRequest)
 {
-    OCEntityHandlerRequest req;
+    OicSecPstat_t *defaultPstat = (OicSecPstat_t *) OICCalloc(1, sizeof(*defaultPstat));
+    ASSERT_TRUE(defaultPstat != NULL);
+    defaultPstat->isOp = false;
+    uint8_t deviceId[] = {0x64, 0x65, 0x76, 0x69, 0x63, 0x65, 0x69, 0x64, 0x00,
+                          0x00, 0x00, 0x00, 0x00, 0x18, 0x5a, 0x9f};
+    memcpy(defaultPstat->deviceID.id, deviceId, sizeof(deviceId));
+    EXPECT_EQ(sizeof(defaultPstat->deviceID.id), sizeof(deviceId));
+    defaultPstat->commitHash = 1234;
+    defaultPstat->cm = (OicSecDpm_t) 63;
+    defaultPstat->tm = (OicSecDpm_t) 48;
+    defaultPstat->om = (OicSecDpom_t) 0;
+    defaultPstat->smLen = 2;
+    defaultPstat->sm = (OicSecDpom_t *)OICCalloc(defaultPstat->smLen, sizeof(*defaultPstat->sm));
+    ASSERT_TRUE(defaultPstat->sm != NULL);
+    defaultPstat->sm[0] = (OicSecDpom_t) 3;
+    defaultPstat->sm[1] = (OicSecDpom_t) 1;
+    size_t size = 0;
+    uint8_t *cbor = NULL;
+    EXPECT_EQ(OC_STACK_OK, PstatToCBORPayload(defaultPstat, &cbor, &size));
+    DeletePstatBinData(defaultPstat);
+    ASSERT_TRUE(cbor != NULL);
+
+    OCEntityHandlerRequest req = OCEntityHandlerRequest();
     req.method = OC_REST_POST;
-    req.payload = reinterpret_cast<OCPayload*>(
-            OCSecurityPayloadCreate("{ \"pstat\": { \"tm\": 0, \"om\": 3 }}"));
+    req.payload = (OCPayload *) OCSecurityPayloadCBORCreate(cbor, size);
     EXPECT_EQ(OC_EH_ERROR, PstatEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req));
+    OICFree(cbor);
     OCPayloadDestroy(req.payload);
 }
 
-TEST(PstatEntityHandlerTest, PstatEntityHandlerInvalidRequest)
+TEST(PstatResourceTest, PstatEntityHandlerInvalidRequest)
 {
     EXPECT_EQ(OC_EH_ERROR, PstatEntityHandler(OCEntityHandlerFlag::OC_OBSERVE_FLAG, NULL));
 }
 
-//BinToJSON Tests
-TEST(BinToJSONTest, BinToNullJSON)
+TEST(PstatResourceTest, PstatToCBORPayloadNULL)
 {
-    char* value = BinToPstatJSON(NULL);
-    EXPECT_TRUE(value == NULL);
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, PstatToCBORPayload(NULL, NULL, 0));
+    // Case when cbor payload is NULL
+    OicSecPstat_t pstat;
+    size_t size = 10;
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, PstatToCBORPayload(&pstat, NULL, &size));
+    uint8_t *cborPayload = (uint8_t *) OICCalloc(1, size);
+    ASSERT_TRUE(NULL != cborPayload);
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, PstatToCBORPayload(&pstat, &cborPayload, &size));
+    OICFree(cborPayload);
+    cborPayload = NULL;
+    // Case when pstat is zero.
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, PstatToCBORPayload(NULL, &cborPayload, &size));
+    // Case when size is 0.
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, PstatToCBORPayload(&pstat, &cborPayload, 0));
+    OICFree(cborPayload);
 }
 
-TEST(JSONToBinTest, NullJSONToBin)
+TEST(PstatResourceTest, CBORPayloadToPstat)
 {
-    OicSecPstat_t *pstat1 = JSONToPstatBin(NULL);
-    EXPECT_TRUE(pstat1 == NULL);
+    EXPECT_EQ(OC_STACK_INVALID_PARAM, CBORPayloadToPstat(NULL, 0, NULL));
 }
 
-TEST(MarshalingAndUnMarshalingTest, BinToPstatJSONAndJSONToPstatBin)
+TEST(PstatResourceTest, PstatToCBORPayloadAndCBORPayloadToPstat)
 {
-    const char* id = "ZGV2aWNlaWQAAAAAABhanw==";
     OicSecPstat_t pstat;
     pstat.cm = NORMAL;
     pstat.commitHash = 0;
-    uint32_t outLen = 0;
-    unsigned char base64Buff[sizeof(((OicUuid_t*) 0)->id)] = {};
-    EXPECT_EQ(B64_OK, b64Decode(id, strlen(id), base64Buff, sizeof(base64Buff), &outLen));
-    memcpy(pstat.deviceID.id, base64Buff, outLen);
+    uint8_t deviceId[] = {0x64, 0x65, 0x76, 0x69, 0x63, 0x65, 0x69, 0x64, 0x00,
+                          0x00, 0x00, 0x00, 0x00, 0x18, 0x5a, 0x9f};
+    memcpy(pstat.deviceID.id, deviceId, sizeof(deviceId));
     pstat.isOp = true;
     pstat.tm = NORMAL;
     pstat.om = SINGLE_SERVICE_CLIENT_DRIVEN;
     pstat.smLen = 2;
-    pstat.sm = (OicSecDpom_t*)OICCalloc(pstat.smLen, sizeof(OicSecDpom_t));
-    if(!pstat.sm)
-    {
-        FAIL() << "Failed to allocate the pstat.sm";
-    }
+    pstat.sm = (OicSecDpom_t*)OICCalloc(pstat.smLen, sizeof(*pstat.sm));
+    ASSERT_TRUE(NULL != pstat.sm);
     pstat.sm[0] = SINGLE_SERVICE_CLIENT_DRIVEN;
     pstat.sm[1] = SINGLE_SERVICE_SERVER_DRIVEN;
-    char* jsonPstat = BinToPstatJSON(&pstat);
-    if(!jsonPstat)
+
+    size_t size = 0;
+    uint8_t *cbor = NULL;
+    EXPECT_EQ(OC_STACK_OK, PstatToCBORPayload(&pstat, &cbor, &size));
+    if (!cbor)
     {
         OICFree(pstat.sm);
-        FAIL() << "Failed to convert BinToPstatJSON";
+        FAIL() << "Failed to convert PstatToCBORPayload";
         return;
     }
-    printf("BinToJSON Dump:\n%s\n\n", jsonPstat);
-    EXPECT_TRUE(jsonPstat != NULL);
-    OicSecPstat_t *pstat1 = JSONToPstatBin(jsonPstat);
-    EXPECT_TRUE(pstat1 != NULL);
-    if(pstat1)
-    {
-        OICFree(pstat1->sm);
-    }
-    OICFree(pstat1);
-    OICFree(jsonPstat);
-    OICFree(pstat.sm);
-}
-
-TEST(PstatTests, JSONMarshalliingTests)
-{
-    char *jsonStr1 = ReadFile(UNIT_TEST_JSON_FILE_NAME);
-    if (NULL != jsonStr1)
-    {
-        cJSON_Minify(jsonStr1);
-        /* Workaround : cJSON_Minify does not remove all the unwanted characters
-         from the end. Here is an attempt to remove those characters */
-        int len = strlen(jsonStr1);
-        while (len > 0)
-        {
-            if (jsonStr1[--len] == '}')
-            {
-                break;
-            }
-        }
-        jsonStr1[len + 1] = 0;
-
-        OicSecPstat_t* pstat = JSONToPstatBin(jsonStr1);
-        EXPECT_TRUE(NULL != pstat);
-
-        char* jsonStr2 = BinToPstatJSON(pstat);
-        EXPECT_STRNE(jsonStr1, jsonStr2);
+    ASSERT_TRUE(NULL != cbor);
+    OicSecPstat_t *pstat1 = NULL;
+    EXPECT_EQ(OC_STACK_OK, CBORPayloadToPstat(cbor, size, &pstat1));
+    ASSERT_TRUE(NULL != pstat1);
+    EXPECT_EQ(pstat.commitHash, pstat1->commitHash);
+    EXPECT_EQ(pstat.isOp, pstat1->isOp);
+    EXPECT_EQ(pstat.tm, pstat1->tm);
+    EXPECT_EQ(pstat.om, pstat1->om);
+    EXPECT_EQ(pstat.smLen, pstat1->smLen);
+    EXPECT_EQ(pstat.sm[0], pstat1->sm[0]);
+    EXPECT_EQ(pstat.sm[1], pstat1->sm[1]);
 
-        OICFree(jsonStr1);
-        OICFree(jsonStr2);
-        OICFree(pstat);
-   }
-    else
-    {
-        printf("Please copy %s into unittest folder\n", UNIT_TEST_JSON_FILE_NAME);
-    }
+    DeletePstatBinData(pstat1);
+    OICFree(cbor);
+    OICFree(pstat.sm);
 }
index 6f51329..8e8f186 100644 (file)
 #include "gtest/gtest.h"
 #include "oic_malloc.h"
 #include "ocstack.h"
+#include <stdlib.h>
 
+#define STRINGIZE2(x) #x
+#define STRINGIZE(x) STRINGIZE2(x)
+
+// TODO: Remove this, once all cbor related are completed.
 char* ReadFile(const char* filename)
 {
 
@@ -54,6 +59,61 @@ char* ReadFile(const char* filename)
     return data;
 }
 
+bool ReadCBORFile(const char* filename, uint8_t **data, size_t *size)
+{
+    bool status = false;
+    if (!data || !size)
+    {
+        printf("Passed parameter are INVALID \n");
+        return status;
+    }
+    int len = strlen(STRINGIZE(SECURITY_BUILD_UNITTEST_DIR)) + strlen(filename) + 1;
+    char *filepath = (char *)OICCalloc(1, len);
+    if (!filepath)
+    {
+        printf("filepath memory allocation failed. \n");
+        return false;
+    }
+    int ret = snprintf(filepath, len, "%s%s", STRINGIZE(SECURITY_BUILD_UNITTEST_DIR), filename);
+    printf("Root build path: %s \n", filepath);
+
+    if (ret == len-1)
+    {
+        FILE *fp = fopen(filepath, "rb");
+        if (fp)
+        {
+            struct stat st;
+            if (stat(filepath, &st) == 0)
+            {
+                *data = (uint8_t *)OICMalloc(st.st_size);
+                if (*data)
+                {
+                    if (fread(*data, 1, st.st_size, fp) != (size_t)st.st_size)
+                    {
+                        printf("Error in reading file %s\n", filename);
+                    }
+                    else
+                    {
+                        *size = st.st_size;
+                        status = true;
+                    }
+                }
+            }
+            fclose(fp);
+        }
+        else
+        {
+            printf("Unable to open %s file\n", filepath);
+        }
+    }
+    else
+    {
+        printf("Filepath copy failed.\n");
+    }
+    OICFree(filepath);
+    return status;
+}
+
 void SetPersistentHandler(OCPersistentStorage *ps, bool set)
 {
     if (set)
index 1a8685e..bf1b571 100644 (file)
@@ -22,6 +22,7 @@
 #define IOTVT_SRM_TEST_COMMON_H
 
 char* ReadFile(const char* filename);
+bool ReadCBORFile(const char* filename, uint8_t **payload, size_t *size);
 void SetPersistentHandler(OCPersistentStorage *ps, bool set);
 
 #endif //IOTVT_SRM_TEST_COMMON_H
index 5c3f75e..8d4553f 100644 (file)
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #include "gtest/gtest.h"
-#include <pwd.h>
-#include <grp.h>
-#include <linux/limits.h>
-#include <sys/stat.h>
 #include "ocstack.h"
 #include "oic_malloc.h"
-#include "cJSON.h"
 #include "cainterface.h"
 #include "secureresourcemanager.h"
 #include "securevirtualresourcetypes.h"
 #include "srmresourcestrings.h"
 #include "svcresource.h"
 #include "srmtestcommon.h"
+#include "security_internals.h"
 
 using namespace std;
 
-#ifdef __cplusplus
-extern "C" {
-#endif
-extern char * BinToSvcJSON(const OicSecSvc_t * svc);
-extern OicSecSvc_t * JSONToSvcBin(const char * jsonStr);
-extern void DeleteSVCList(OicSecSvc_t* svc);
-#ifdef __cplusplus
-}
-#endif
-
-static const char* JSON_FILE_NAME = "oic_unittest.json";
-
-#define NUM_SVC_IN_JSON_DB (2)
+#define NUM_SVC_IN_CBOR_DB (2)
 
-
-// JSON Marshalling Tests
-TEST(SVCResourceTest, JSONMarshallingTests)
+TEST(SVCResourceTest, CBORConversionTests)
 {
-    char *jsonStr1 = ReadFile(JSON_FILE_NAME);
-    if (jsonStr1)
-    {
-        OicSecSvc_t * svc = JSONToSvcBin(jsonStr1);
-        EXPECT_TRUE(NULL != svc);
+    OicSecSvc_t *svc1 = (OicSecSvc_t *) OICCalloc(1, sizeof(*svc1));
+    ASSERT_TRUE(NULL != svc1);
+    uint8_t svcdid[] = {0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35,
+                        0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35};
+    memcpy(svc1->svcdid.id, svcdid, sizeof(svcdid));
+    ASSERT_EQ(sizeof(svc1->svcdid.id), sizeof(svcdid));
 
-        int cnt = 0;
-        OicSecSvc_t * tempSvc = svc;
-        while(tempSvc)
-        {
+    svc1->svct = (OicSecSvcType_t) 1;
+    uint8_t owners[] = {0x39, 0x39, 0x39, 0x39, 0x39, 0x39, 0x39, 0x39, 0x39,
+                        0x39, 0x39, 0x39, 0x39, 0x39, 0x39, 0x39};
+    svc1->ownersLen = 1;
+    svc1->owners = (OicUuid_t *)OICCalloc(svc1->ownersLen, sizeof(*svc1->owners));
+    ASSERT_TRUE(NULL != svc1->owners);
+    memcpy(svc1->owners[0].id, owners, sizeof(owners));
+    ASSERT_EQ(sizeof(svc1->owners[0].id), sizeof(owners));
 
-            EXPECT_EQ(tempSvc->svct, ACCESS_MGMT_SERVICE);
-            cnt++;
-            tempSvc = tempSvc->next;
-        }
-        EXPECT_EQ(cnt, NUM_SVC_IN_JSON_DB);
+    svc1->next = (OicSecSvc_t *) OICCalloc(1, sizeof(*svc1->next));
+    ASSERT_TRUE(svc1->next != NULL);
+    memcpy(svc1->next->svcdid.id, svcdid, sizeof(svcdid));
+    ASSERT_EQ(sizeof(svc1->next->svcdid.id), sizeof(svcdid));
+    svc1->next->svct = (OicSecSvcType_t) 1;
+    uint8_t owners1[] = {0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
+                        0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36};
+    svc1->next->ownersLen = 1;
+    svc1->next->owners = (OicUuid_t *)OICCalloc(svc1->next->ownersLen,
+                                                sizeof(*svc1->next->owners));
+    ASSERT_TRUE(NULL != svc1->next->owners);
+    memcpy(svc1->next->owners[0].id, owners1, sizeof(owners1));
+    svc1->next->next = NULL;
 
-        char * jsonStr2 = BinToSvcJSON(svc);
-        EXPECT_TRUE(NULL != jsonStr2);
+    size_t size = 0;
+    uint8_t *psStorage = NULL;
+    EXPECT_EQ(OC_STACK_OK, SVCToCBORPayload(svc1, &psStorage, &size));
+    ASSERT_TRUE(NULL != psStorage);
 
-        OICFree(jsonStr1);
-        OICFree(jsonStr2);
-        DeleteSVCList(svc);
+    OicSecSvc_t *svc = NULL;
+    EXPECT_EQ(OC_STACK_OK, CBORPayloadToSVC(psStorage, size, &svc));
+    ASSERT_TRUE(NULL != svc);
+
+    int cnt = 0;
+    OicSecSvc_t *tempSvc = svc;
+    while (tempSvc)
+    {
+        EXPECT_EQ(ACCESS_MGMT_SERVICE, tempSvc->svct);
+        cnt++;
+        tempSvc = tempSvc->next;
     }
-}
+    EXPECT_EQ(NUM_SVC_IN_CBOR_DB, cnt);
 
+    OICFree(psStorage);
+    DeleteSVCList(svc);
+    DeleteSVCList(svc1);
+}
index 789d5d7..56bab1b 100644 (file)
@@ -219,7 +219,9 @@ void OCRepPayloadDestroy(OCRepPayload* payload);
 // Discovery Payload
 OCDiscoveryPayload* OCDiscoveryPayloadCreate();
 
+// TODO: Remove OCSecurityPayloadCBORCreate once all cbor changes land.
 OCSecurityPayload* OCSecurityPayloadCreate(const char* securityData);
+OCSecurityPayload* OCSecurityPayloadCBORCreate(const uint8_t* securityData, size_t size);
 void OCSecurityPayloadDestroy(OCSecurityPayload* payload);
 
 void OCDiscoveryPayloadAddResource(OCDiscoveryPayload* payload, const OCResource* res,
index 3b01e45..7b27a5e 100644 (file)
@@ -1200,6 +1200,8 @@ typedef struct
 {
     OCPayload base;
     char* securityData;
+    uint8_t *securityData1;
+    size_t payloadSize;
 } OCSecurityPayload;
 
 #ifdef WITH_PRESENCE
index 53be70f..e15ae78 100644 (file)
@@ -88,4 +88,12 @@ samples_env.Alias("install", samples_env.Install( sec_samples_build_dir,
 if env.get('SECURED') == '1':
        samples_env.Alias("install", samples_env.Install( sec_samples_build_dir,
                sec_samples_src_dir + 'oic_svr_db_client_directpairing.json'))
+       samples_env.Alias("install", samples_env.Install( sec_samples_build_dir,
+       sec_samples_src_dir + 'oic_svr_db_client_directpairing.dat'))
 
+samples_env.Alias("install", samples_env.Install( sec_samples_build_dir,
+    sec_samples_src_dir + 'oic_svr_db_server.dat'))
+samples_env.Alias("install", samples_env.Install( sec_samples_build_dir,
+    sec_samples_src_dir + 'oic_svr_db_client.dat'))
+samples_env.Alias("install", samples_env.Install( sec_samples_build_dir,
+    sec_samples_src_dir + 'oic_amss_db.dat'))
index d7755bf..4a6b14e 100644 (file)
@@ -16,7 +16,7 @@ int gQuitFlag = 0;
 
 //AMS service database, hold AMS service Identity and
 //the PSK credentials of trusted devices
-static char AMSS_DB_FILE[] = "oic_amss_db.json";
+static char AMSS_DB_FILE[] = "oic_amss_db.dat";
 
 /* SIGINT handler: set gQuitFlag to 1 for graceful termination */
 void handleSigInt(int signum)
index 38aefe1..0f5d93b 100644 (file)
@@ -49,7 +49,7 @@ 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";
+static char CRED_FILE[] = "oic_svr_db_client.dat";
 
 
 int gQuitFlag = 0;
index e976ffc..0979901 100644 (file)
@@ -49,7 +49,7 @@ static char DISCOVERY_QUERY[] = "%s/oic/res";
 //Secure Virtual Resource database for Iotivity Client application\r
 //It contains Client's Identity and the PSK credentials\r
 //of other devices which the client trusts\r
-static char CRED_FILE[] = "oic_svr_db_client_directpairing.json";\r
+static char CRED_FILE[] = "oic_svr_db_client_directpairing.dat";\r
 \r
 static const OCDPDev_t *discoveredDevs = NULL;\r
 static const OCDPDev_t *pairedDevs = NULL;\r
index cacef07..22bc674 100644 (file)
@@ -45,7 +45,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.json";
+static char CRED_FILE[] = "oic_svr_db_server.dat";
 
 OCRepPayload* getPayload(const char* uri, int64_t power, bool state)
 {
diff --git a/resource/csdk/stack/samples/linux/secure/oic_amss_db.dat b/resource/csdk/stack/samples/linux/secure/oic_amss_db.dat
new file mode 100644 (file)
index 0000000..3ece409
Binary files /dev/null and b/resource/csdk/stack/samples/linux/secure/oic_amss_db.dat differ
diff --git a/resource/csdk/stack/samples/linux/secure/oic_svr_db_client.dat b/resource/csdk/stack/samples/linux/secure/oic_svr_db_client.dat
new file mode 100644 (file)
index 0000000..e258f9e
Binary files /dev/null and b/resource/csdk/stack/samples/linux/secure/oic_svr_db_client.dat differ
diff --git a/resource/csdk/stack/samples/linux/secure/oic_svr_db_client_directpairing.dat b/resource/csdk/stack/samples/linux/secure/oic_svr_db_client_directpairing.dat
new file mode 100644 (file)
index 0000000..917900f
Binary files /dev/null and b/resource/csdk/stack/samples/linux/secure/oic_svr_db_client_directpairing.dat differ
index e819a71..3da1ae9 100644 (file)
@@ -30,7 +30,7 @@
        "pstat":        {
                "isop": false,
                "deviceid":     "ZGlyZWN0cGFpcmluZ0Rldg==",
-               "commithash": 0,
+               "ch": 0,
                "cm":   0,
                "tm":   0,
                "om":   3,
@@ -41,6 +41,7 @@
                "oxmsel": 0,
                "sct": 1,
                "owned": false,
-               "deviceid":     "ZGlyZWN0cGFpcmluZ0Rldg=="
+               "deviceid":     "ZGlyZWN0cGFpcmluZ0Rldg==",
+        "dpc": false
        }
 }
diff --git a/resource/csdk/stack/samples/linux/secure/oic_svr_db_server.dat b/resource/csdk/stack/samples/linux/secure/oic_svr_db_server.dat
new file mode 100644 (file)
index 0000000..2bbe94b
Binary files /dev/null and b/resource/csdk/stack/samples/linux/secure/oic_svr_db_server.dat differ
diff --git a/resource/csdk/stack/samples/linux/secure/oic_svr_db_server_justworks.dat b/resource/csdk/stack/samples/linux/secure/oic_svr_db_server_justworks.dat
new file mode 100644 (file)
index 0000000..605683a
Binary files /dev/null and b/resource/csdk/stack/samples/linux/secure/oic_svr_db_server_justworks.dat differ
index 030b1c8..ccfe159 100644 (file)
@@ -1289,6 +1289,7 @@ OCDiscoveryPayload* OCDiscoveryPayloadCreate()
     return payload;
 }
 
+//TODO : Remove this once all cbor changes land.
 OCSecurityPayload* OCSecurityPayloadCreate(const char* securityData)
 {
     OCSecurityPayload* payload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
@@ -1304,14 +1305,38 @@ OCSecurityPayload* OCSecurityPayloadCreate(const char* securityData)
     return payload;
 }
 
+// TODO : To convert this to OCSecurityPayloadCreate once all cbor changes land.
+OCSecurityPayload* OCSecurityPayloadCBORCreate(const uint8_t* securityData, size_t size)
+{
+    OCSecurityPayload* payload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
+
+    if (!payload)
+    {
+        return NULL;
+    }
+
+    payload->base.type = PAYLOAD_TYPE_SECURITY;
+    payload->securityData1 = (uint8_t *)OICCalloc(1, size);
+    if (!payload->securityData1)
+    {
+        OICFree(payload);
+        return NULL;
+    }
+    memcpy(payload->securityData1, (uint8_t *)securityData, size);
+    payload->payloadSize = size;
+
+    return payload;
+}
+
 void OCSecurityPayloadDestroy(OCSecurityPayload* payload)
 {
     if (!payload)
     {
         return;
     }
-
+    // Remove this once all cbor changes land.
     OICFree(payload->securityData);
+    // OICFree(payload->securityData1);
     OICFree(payload);
 }
 
index 946cdd9..d9ecc1e 100644 (file)
@@ -106,7 +106,7 @@ OCStackResult OCConvertPayload(OCPayload* payload, uint8_t** outPayload, size_t*
 
     if (err == CborNoError)
     {
-        if (curSize < INIT_SIZE)
+        if (curSize < INIT_SIZE && PAYLOAD_TYPE_SECURITY != payload->type)
         {
             uint8_t *out2 = (uint8_t *)OICRealloc(out, curSize);
             VERIFY_PARAM_NON_NULL(TAG, out2, "Failed to increase payload size");
@@ -173,29 +173,21 @@ static int64_t checkError(int64_t err, CborEncoder* encoder, uint8_t* outPayload
 static int64_t OCConvertSecurityPayload(OCSecurityPayload* payload, uint8_t* outPayload,
         size_t* size)
 {
-    CborEncoder encoder;
-    cbor_encoder_init(&encoder, outPayload, *size, 0);
-
-    CborEncoder map;
-    int64_t err = cbor_encoder_create_map(&encoder, &map, CborIndefiniteLength);
-    VERIFY_CBOR_SUCCESS(TAG, err, "Creating security map");
-
-    if (payload->securityData)
-    {
-        err |= cbor_encode_text_string(&map, payload->securityData,
-                                      (size_t)(strlen(payload->securityData)));
-        VERIFY_CBOR_SUCCESS(TAG, err, "Encoding security data");
-    }
-    else
+    if (*size < payload->payloadSize)
     {
-        err |= cbor_encode_null(&map);
-        VERIFY_CBOR_SUCCESS(TAG, err, "Encoding security data");
+        uint8_t *out2 = (uint8_t *)OICRealloc(outPayload, payload->payloadSize);
+        if (!out2)
+        {
+            OICFree(outPayload);
+            return CborErrorOutOfMemory;
+        }
+        outPayload = out2;
     }
 
-    err |= cbor_encoder_close_container(&encoder, &map);
-    VERIFY_CBOR_SUCCESS(TAG, err, "Closing security map");
-exit:
-    return checkError(err, &encoder, outPayload, size);
+    memcpy(outPayload, payload->securityData1, payload->payloadSize);
+    *size = payload->payloadSize;
+
+    return CborNoError;
 }
 
 static char* OCStringLLJoin(OCStringLL* val)
index d57ac6c..c7da786 100644 (file)
@@ -44,7 +44,7 @@ static OCStackResult OCParsePlatformPayload(OCPayload **outPayload, CborValue *a
 static CborError OCParseSingleRepPayload(OCRepPayload **outPayload, CborValue *repParent, bool isRoot);
 static OCStackResult OCParseRepPayload(OCPayload **outPayload, CborValue *arrayVal);
 static OCStackResult OCParsePresencePayload(OCPayload **outPayload, CborValue *arrayVal);
-static OCStackResult OCParseSecurityPayload(OCPayload **outPayload, CborValue * rrayVal);
+static OCStackResult OCParseSecurityPayload(OCPayload **outPayload, const uint8_t *payload, size_t size);
 
 OCStackResult OCParsePayload(OCPayload **outPayload, OCPayloadType payloadType,
         const uint8_t *payload, size_t payloadSize)
@@ -81,7 +81,7 @@ OCStackResult OCParsePayload(OCPayload **outPayload, OCPayloadType payloadType,
             result = OCParsePresencePayload(outPayload, &rootValue);
             break;
         case PAYLOAD_TYPE_SECURITY:
-            result = OCParseSecurityPayload(outPayload, &rootValue);
+            result = OCParseSecurityPayload(outPayload, payload, payloadSize);
             break;
         case PAYLOAD_TYPE_RD:
             result = OCRDCborToPayload(&rootValue, outPayload);
@@ -100,41 +100,18 @@ exit:
 
 void OCFreeOCStringLL(OCStringLL* ll);
 
-static OCStackResult OCParseSecurityPayload(OCPayload** outPayload, CborValue* rootValue)
+static OCStackResult OCParseSecurityPayload(OCPayload** outPayload, const uint8_t *payload,
+        size_t size)
 {
-    OCStackResult ret = OC_STACK_ERROR;
-    CborError err;
-    char *securityData = NULL;
-    CborValue strVal;
-
-    VERIFY_PARAM_NON_NULL(TAG, outPayload, "Invalid parameter outPayload");
-    VERIFY_PARAM_NON_NULL(TAG, rootValue, "Invalid parameter rootValue");
-    *outPayload = NULL;
-
-    err = cbor_value_enter_container(rootValue, &strVal);
-    VERIFY_CBOR_SUCCESS(TAG, err, "Failed entering container");
-
-    if (cbor_value_is_text_string(&strVal))
+    if (size > 0)
     {
-        size_t len = 0;
-        err = cbor_value_dup_text_string(&strVal, &securityData, &len, NULL);
-        VERIFY_CBOR_SUCCESS(TAG, err, "Failed reading security data");
-        *outPayload = (OCPayload *)OCSecurityPayloadCreate(securityData);
-        VERIFY_PARAM_NON_NULL(TAG, *outPayload, "Invalid cbor");
-        ret = OC_STACK_OK;
-    }
-    else if(cbor_value_is_valid(&strVal))
-    {
-        ret = OC_STACK_OK;
+        *outPayload = (OCPayload *)OCSecurityPayloadCBORCreate(payload, size);
     }
     else
     {
-        ret = OC_STACK_MALFORMED_RESPONSE;
+        *outPayload = NULL;
     }
-
-exit:
-    OICFree(securityData);
-    return ret;
+    return OC_STACK_OK;
 }
 
 static char* InPlaceStringTrim(char* str)
index 8e9c696..ceb52bf 100644 (file)
@@ -96,7 +96,8 @@ svr_db_src_dir = src_dir + '/resource/provisioning/examples/'
 svr_db_build_dir = env.get('BUILD_DIR') +'/resource/provisioning/examples/'
 
 clientjson = examples_env.Install(svr_db_build_dir, svr_db_src_dir + 'oic_svr_db_client.json')
+clientdat = examples_env.Install(svr_db_build_dir, svr_db_src_dir + 'oic_svr_db_client.dat')
 
-Alias("examples", [provisioningclient, clientjson])
+Alias("examples", [provisioningclient, clientjson,clientdat])
 env.AppendTarget('examples')
 
diff --git a/resource/provisioning/examples/oic_svr_db_client.dat b/resource/provisioning/examples/oic_svr_db_client.dat
new file mode 100644 (file)
index 0000000..6a39661
Binary files /dev/null and b/resource/provisioning/examples/oic_svr_db_client.dat differ
index d6fdd41..57af892 100644 (file)
@@ -50,6 +50,7 @@
 #define TAG  "provisioningclient"
 
 #define JSON_DB_PATH "./oic_svr_db_client.json"
+#define DAT_DB_PATH "./oic_svr_db_client.dat"
 #define DEV_STATUS_ON "DEV_STATUS_ON"
 #define DEV_STATUS_OFF "DEV_STATUS_OFF"
 
@@ -63,7 +64,7 @@ static int transferDevIdx, ask = 1;
 static FILE* client_open(const char *UNUSED_PARAM, const char *mode)
 {
     (void)UNUSED_PARAM;
-    return fopen(JSON_DB_PATH, mode);
+    return fopen(DAT_DB_PATH, mode);
 }
 
 void printMenu()