Security CBOR conversion 79/6079/11
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)
@@ -87,5 +87,11 @@ provisioning_env.Alias("install", provisioning_env.Install( sec_provisioning_bui
        sec_provisioning_src_dir + 'oic_svr_db_light.json'))
 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)