Revert back cbor related patches.
authorleechul <chuls.lee@samsung.com>
Tue, 15 Mar 2016 05:34:34 +0000 (14:34 +0900)
committerRandeep Singh <randeep.s@samsung.com>
Tue, 15 Mar 2016 14:24:50 +0000 (14:24 +0000)
[Patch #1] Intial upload.
[Patch #2] Modify provisionig sample's SConscript to ignore sample codes in case of tizen.
             * The json file will be copied in case of tizen.
[Patch #3] Remove the segmentation fault in debug mode.
[Patch #4] Modify the build script to not include security samples in case of tizen build.
[Patch #5] Revmoe the printf

Change-Id: I88b9b5b68bc641f219bcf0c26dbf1dd4c61ae177
Signed-off-by: leechul <chuls.lee@samsung.com>
Reviewed-on: https://gerrit.iotivity.org/gerrit/5897
Reviewed-by: Jongsung Lee <js126.lee@samsung.com>
Reviewed-by: dongik Lee <dongik.lee@samsung.com>
Tested-by: jenkins-iotivity <jenkins-iotivity@opendaylight.org>
Reviewed-by: Randeep Singh <randeep.s@samsung.com>
73 files changed:
oic_svr_db.dat [deleted file]
oic_svr_db.json [deleted file]
resource/csdk/security/SConscript
resource/csdk/security/include/base64.h
resource/csdk/security/include/internal/aclresource.h
resource/csdk/security/include/internal/amaclresource.h [changed mode: 0755->0644]
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/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 [deleted file]
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/SConscript
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/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: 0755->0644]
resource/csdk/security/src/oxmpincommon.c
resource/csdk/security/src/pbkdf2.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/unittest/SConscript
resource/csdk/security/unittest/aclresourcetest.cpp
resource/csdk/security/unittest/amaclresourcetest.cpp [deleted file]
resource/csdk/security/unittest/credentialresource.cpp
resource/csdk/security/unittest/doxmresource.cpp
resource/csdk/security/unittest/oic_unittest.dat [deleted file]
resource/csdk/security/unittest/oic_unittest_acl1.dat [deleted file]
resource/csdk/security/unittest/oic_unittest_acl1.json
resource/csdk/security/unittest/oic_unittest_default_acl.dat [deleted file]
resource/csdk/security/unittest/oic_unittest_default_acl.json
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 [changed mode: 0755->0644]
resource/csdk/stack/include/octypes.h
resource/csdk/stack/src/ocpayload.c [changed mode: 0755->0644]
resource/csdk/stack/src/ocpayloadconvert.c
resource/csdk/stack/src/ocpayloadparse.c [changed mode: 0755->0644]
resource/provisioning/SConscript [changed mode: 0755->0644]

diff --git a/oic_svr_db.dat b/oic_svr_db.dat
deleted file mode 100644 (file)
index 62fc7db..0000000
Binary files a/oic_svr_db.dat and /dev/null differ
diff --git a/oic_svr_db.json b/oic_svr_db.json
deleted file mode 100644 (file)
index 7f8b100..0000000
+++ /dev/null
@@ -1,3 +0,0 @@
-{
-  "acl": "gaRnc3ViAHJzckEqZ3JzcmMAYW2IaC9vaWMvcmVzZi9vaWMvZGYvb2ljL3BwL29pYy9yZXMvdHlwZXMvZGcvb2ljL2FkbC9vaWMvc2VjL2FjbG0vb2ljL3NlYy9kb3htbi9vaWMvc2VjL3BzdGF0Z3Blcm1zAG8CZ293bnJzAG-BUDIyMjIyMjIyMjIyMjIyMjI"
-}
index 04a98db..f2aed83 100644 (file)
@@ -145,3 +145,4 @@ libocsrm_env.InstallTarget(libocsrm, 'libocsrm')
 
 if target_os in ['linux', 'android', 'tizen'] and env.get('SECURED') == '1':
        SConscript('provisioning/SConscript')
+
index a983f1e..4d5837d 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 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.
+ * @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
  *
- * @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 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.
+ * @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
  *
- * @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 97c6716..ccd97ef 100644 (file)
@@ -28,15 +28,16 @@ extern "C" {
 /**
  * Initialize ACL resource by loading data from persistent storage.
  *
- * @return ::OC_STACK_OK for Success, otherwise some error value.
+ * @retval  OC_STACK_OK for Success, otherwise some error value
  */
 OCStackResult InitACLResource();
 
 /**
  * Perform cleanup for ACL resources.
  *
+ * @retval  none
  */
-OCStackResult DeInitACLResource();
+void DeInitACLResource();
 
 /**
  * This method is used by PolicyEngine to retrieve ACL for a Subject.
@@ -45,39 +46,38 @@ OCStackResult DeInitACLResource();
  * @param savePtr is used internally by @ref GetACLResourceData to maintain index between
  *                successive calls for same subjectId.
  *
- * @note On the first call to @ref GetACLResourceData, savePtr should point to NULL.
+ * @retval  reference to @ref OicSecAcl_t if ACL is found, else NULL
  *
- * @return 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);
 
 /**
- * This function converts ACL data into CBOR format.
+ * 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.
  *
- * @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.
+ * @retval  pointer to ACL in json format.
  */
-OCStackResult AclToCBORPayload(const OicSecAcl_t * acl, uint8_t **outPayload, size_t *size);
+char* BinToAclJSON(const OicSecAcl_t * acl);
+
 
 /**
  * This function deletes ACL data.
  *
- * @param acl instance of @ref OicSecAcl_t structure to be deleted.
+ * @param acl  instance of OicSecAcl_t structure.
  */
 void DeleteACLList(OicSecAcl_t* acl);
 
+
 /**
  * This function installs a new ACL.
+ * @param newJsonStr JSON string representing a new ACL.
  *
- * @param payload cbor value representing a new ACL.
- * @param size of the cbor payload.
- *
- * @return ::OC_STACK_OK for Success, otherwise some error value
+ * @retval  OC_STACK_OK for Success, otherwise some error value
  */
-OCStackResult InstallNewACL(const uint8_t* payload, const size_t size);
+OCStackResult InstallNewACL(const char* newJsonStr);
 
 /**
  * This function updates default ACL which is required for ownership transfer.
@@ -92,3 +92,5 @@ OCStackResult UpdateDefaultSecProvACL();
 #endif
 
 #endif //IOTVT_SRM_ACLR_H
+
+
old mode 100755 (executable)
new mode 100644 (file)
index e3dc1fa..9c37a0e
@@ -36,12 +36,14 @@ extern "C" {
 /**
  * Initialize Amacl resource by loading data from persistent storage.
  *
- * @return ::OC_STACK_OK for Success, otherwise some error value.
+ * @retval  OC_STACK_OK for Success, otherwise some error value
  */
 OCStackResult InitAmaclResource();
 
 /**
  * Perform cleanup for Amacl resources.
+ *
+ * @retval  none
  */
 void DeInitAmaclResource();
 
@@ -50,31 +52,30 @@ void DeInitAmaclResource();
  * If the Amacl is found for the given resource then populate the parameter
  * amsId with Amacl resource amss id.
  *
- * @param resource for which AMS service is required.
- * @param amsId of the ams service for the given resource.
+ * @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
  *
- * @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 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.
+ * 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.
  *
- * @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.
+ * @retval  pointer to Amacl in json format.
  */
-OCStackResult AmaclToCBORPayload(const OicSecAmacl_t *amacl, uint8_t **cborPayload,
-                                 size_t *cborSize);
+char* BinToAmaclJSON(const OicSecAmacl_t * amacl);
 
 #ifdef __cplusplus
 }
 #endif
 
 #endif //IOTVT_SRM_AMACLR_H
+
+
index e07b442..d9d74b5 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;
 /**
- * The AMS context.
+ * @brief   The AMS context..
  */
 typedef struct AmsMgrContext
 {
@@ -41,95 +40,103 @@ typedef struct AmsMgrContext
     CARequestInfo_t     *requestInfo;
 } AmsMgrContext_t;
 
+
 /**
- * This method updates AmsMgr context's endpoint & requestInfo.
+ * @brief This method updates AmsMgr context's endpoint & requestInfo
  *
- * @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.
+ * @param context          Policy engine context.
+ * @param endpoint         CA Endpoint info of the requester
+ * @param requestInfo      CA RequestInfo of the requester
  */
-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".
+ * with deviceId="AMSSrvcDeviceID"
+ *
+ * @param context   Policy engine context.
  *
- * @param context is the policy engine context.
+ * @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.
  *
- * @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 is the policy engine context.
+ * @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
  *
- * @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 is the policy engine context.
+ * @param context   Policy engine context.
  *
- * @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.
+ * @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
  *
  */
-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 is the pointer to @ref CARequestInfo_t.
+ * Cleanup CARequestInfo_t object
+ * @param requestInfo        pointer to RequestInfo_t object
  */
 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 is the policy engine context.
+ * @param context   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.
+ * This method is used by Policy engine to process AMS request
+ *
+ * @param context   Policy engine context.
  *
- * @param context is the policy engine context.
  */
 void ProcessAMSRequest(PEContext_t *context);
 
+
 /*
- * This method is used by Policy engine to free AMS context requestInfo/
+ * This method is used by Policy engine to free AMS context requestInfo
+ *
+ * @param requestInfo   pointer to CARequestInfo_t.
  *
- * @param requestInfo is the pointer to @ref CARequestInfo_t.
  */
 void FreeCARequestInfo(CARequestInfo_t *requestInfo);
 
index a7cad66..74ea373 100644 (file)
@@ -32,42 +32,45 @@ extern "C" {
 /**
  * Initialize credential resource by loading data from persistent storage.
  *
- * @return ::OC_STACK_OK, if initialization is successful, else ::OC_STACK_ERROR if
- * initialization fails.
+ * @retval
+ *     OC_STACK_OK    - no errors
+ *     OC_STACK_ERROR - stack process error
  */
 OCStackResult InitCredResource();
 
 /**
  * Perform cleanup for credential resources.
  *
- * @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.
+ * @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
  */
 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 subjectId for which credential is required.
+ * @param subject - subject for which credential is required.
  *
- * @return reference to @ref OicSecCred_t, if credential is found, else NULL, if credential
- * not found.
+ * @retval
+ *     reference to OicSecCred_t - if credential is found
+ *     NULL                      - if credential not found
  */
 const OicSecCred_t* GetCredResourceData(const OicUuid_t* subjectId);
 
 /**
- * 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.
+ * 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
  */
-OCStackResult CredToCBORPayload(const OicSecCred_t* cred, uint8_t **cborPayload,
-                                size_t *cborSize);
+char* BinToCredJSON(const OicSecCred_t* cred);
 
 /**
  * This function generates the bin credential data.
@@ -79,42 +82,53 @@ OCStackResult CredToCBORPayload(const OicSecCred_t* cred, uint8_t **cborPayload,
  * @param ownersLen length of owners array
  * @param owners array of owners.
  *
- * @return pointer to instance of @ref OicSecCred_t if successful. else NULL in case of error.
-
+ * @retval
+ *      pointer to instance of OicSecCred_t  - success
+ *      NULL                                 - error
  */
 OicSecCred_t * GenerateCredential(const OicUuid_t* subject, OicSecCredType_t credType,
-                     const uint8_t * publicData, const uint8_t * privateData,
-                     size_t ownersLen, const OicUuid_t * owners);
+                     const char * publicData, const char * privateData, size_t ownersLen,
+                     const OicUuid_t * owners);
 
 /**
  * This function adds the new cred to the credential list.
  *
- * @param cred is the pointer to new credential.
+ * @param cred pointer to new credential.
  *
- * @return ::OC_STACK_OK, cred not NULL and persistent storage gets updated.
- * ::OC_STACK_ERROR, cred is NULL or fails to update persistent storage.
+ * @retval
+ *      OC_STACK_OK     - cred not NULL and persistent storage gets updated
+ *      OC_STACK_ERROR  - cred is NULL or fails to update persistent storage
  */
 OCStackResult AddCredential(OicSecCred_t * cred);
 
 /**
  * Function to remove the credential from SVR DB.
  *
- * @param credId is the Credential ID to be deleted.
+ * @param credId Credential ID to be deleted.
  *
- * @return ::OC_STACK_OK for success, or errorcode otherwise.
+ * @return OC_STACK_OK for success and errorcode otherwise.
  */
-OCStackResult RemoveCredential(const OicUuid_t *credId);
+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);
 
 #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 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.
+ * @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.
  *
  * @return The number of bytes written to @p result or a value
  *         less than zero on error.
@@ -124,22 +138,21 @@ 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 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.
+ * @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.
  *
- * @return ::OC_STACK_OK for success or else errorcode.
+ * @return OC_STACK_OK for success and errorcode otherwise.
  */
 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__ */
 
@@ -147,17 +160,18 @@ OCStackResult AddTmpPskWithPIN(const OicUuid_t* tmpSubject, OicSecCredType_t cre
 /**
  * This function is used toretrieve certificate credentials from RI security layer.
  *
- * @param credInfo is the binary structure containing certificate credentials
+ * @param credInfo
+ *     binary structure containing certificate credentials
  *
- * @return 0 on success.
+ * @retval 0  on scuccess
  */
 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);
@@ -167,3 +181,5 @@ void DeleteCredList(OicSecCred_t* cred);
 #endif
 
 #endif //IOTVT_SRM_CREDR_H
+
+
index c31143d..75178d8 100644 (file)
@@ -29,46 +29,43 @@ extern "C" {
 #endif
 
 /**
- * This function stores CRL in SRM.
+ * This function stores CRL in SRM
+ * @param crl - CRL
  *
- * @param crl to be stored in SRM.
- *
- * @return ::OC_STACK_OK for Success, otherwise some error value.
+ * @returns OC_STACK_OK for Success, otherwise some error value
  */
 OCStackResult UpdateCRLResource(const OicSecCrl_t *crl);
 
 /**
- * This function get encoded with base64 CRL from SRM.
- *
- * @note Caller responsible for resulting string memory (use OICFree to remove it).
+ * This function get encoded with base64 CRL from SRM
  *
- * @return encoded CRL with base64 format. NULL if error occured (e.g. CRL did not set).
+ * @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)
  */
 char* GetBase64CRL();
 /**
- * This function get encoded with DER CRL from SRM.
+ * This function get encoded with DER CRL from SRM
  *
- * @return encoded CRL with DER format. array len is 0 if error occured (e.g. CRL did not set).
+ * @returns 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 get CRL from SRM
  *
- * @param crl is a pointer to buffer that contains crl. Shoul be not NULL. Buffer
+ * @param crl [out] - 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 is a pointer to length of the CRL buffer. Should be not NULL.
+ * @param outlen [out] - pointer to length of the CRL buffer. Shoul be not NULL.
  *
- * @note Caller responsible for crl buffer memory (use OICFree to free it).
- *
- * @return ::OC_STACK_OK if success, otherwise some error value.
+ * @returns OC_STACK_OK if success and errorcode otherwise.
+ * @note Caller responsible for crl buffer memory (use OICFree to free it)
  */
 OicSecCrl_t * JSONToCrlBin(const char * jsonStr);
 
 /**
- * Initialize CRL resource by loading data from persistent storage.
+ * Initialize CLR resource by loading data from persistent storage.
  *
- * @return ::OC_STACK_OK for Success, otherwise some error value.
+ * @returns OC_STACK_OK for Success, otherwise some error value
  */
 OCStackResult InitCRLResource();
 
@@ -77,15 +74,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 e9ce684..237da64 100644 (file)
@@ -30,71 +30,67 @@ extern "C" {
 /**
  * Initialize DOXM resource by loading data from persistent storage.
  *
- * @return ::OC_STACK_OK for Success, otherwise some error value.
+ * @retval  OC_STACK_OK for Success, otherwise some error value
  */
 OCStackResult InitDoxmResource();
 
 /**
  * Perform cleanup for DOXM resources.
  *
- * @return ::OC_STACK_OK for Success, otherwise some error value.
+ * @retval  OC_STACK_OK for Success, otherwise some error value
  */
 OCStackResult DeInitDoxmResource();
 
 /**
  * This method is used by SRM to retrieve DOXM resource data..
  *
- * @return reference to @ref OicSecDoxm_t, binary format of Doxm resource data.
+ * @retval  reference to @ref OicSecDoxm_t, binary format of Doxm resource data
  */
 const OicSecDoxm_t* GetDoxmResourceData();
 
 /**
- * This method converts CBOR DOXM into binary DOXM.
- * The CBOR DOXM can be from persistent database or
+ * This method converts JSON DOXM into binary DOXM.
+ * The JSON DOXM can be from persistent database or
  * or received as PUT/POST request.
  *
- * @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.
+ * @param[in] jsonStr  doxm data in json string.
+ * @return pointer to OicSecDoxm_t.
  *
- * @return ::OC_STACK_OK for Success, otherwise some error value.
+ * @note Caller needs to invoke OCFree after done
+ *       using the return pointer
  */
-OCStackResult CBORPayloadToDoxm(const uint8_t *cborPayload, size_t size,
-                                OicSecDoxm_t **doxm);
+OicSecDoxm_t * JSONToDoxmBin(const char * jsonStr);
 
 /**
- * This method converts DOXM data into CBOR format.
+ * This method converts DOXM data into JSON format.
  * Caller needs to invoke 'free' when finished done using
- * return string.
+ * return 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.
+ * @param[in] doxm  Pointer to OicSecDoxm_t.
+ * @return pointer to json string.
  *
- * @return ::OC_STACK_OK for Success, otherwise some error value.
+ * @note Caller needs to invoke OCFree after done
+ *       using the return pointer
  */
-OCStackResult DoxmToCBORPayload(const OicSecDoxm_t * doxm, uint8_t **cborPayload,
-                                size_t *cborSize);
+char * BinToDoxmJSON(const OicSecDoxm_t * doxm);
 
 /**
  * This method returns the SRM device ID for this device.
  *
- * @return ::OC_STACK_OK for Success, otherwise some error value.
+ * @retval  OC_STACK_OK for Success, otherwise some error value
  */
 OCStackResult GetDoxmDeviceID(OicUuid_t *deviceID);
 
 /**
- * Gets the OicUuid_t value for the owner of this device.
+ * @brief Gets the OicUuid_t value for the owner of this device.
  *
- * @return ::OC_STACK_OK if devOwner is a valid UUID, otherwise ::OC_STACK_ERROR.
+ * @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 doxm is the pointer to @ref OicSecDoxm_t.
+ * @param[in] doxm  Pointer to OicSecDoxm_t.
  */
 void DeleteDoxmBinData(OicSecDoxm_t* doxm);
 
@@ -109,3 +105,5 @@ void RestoreDoxmToInitState();
 #endif
 
 #endif //IOTVT_SRM_DOXMR_H
+
+
index 72aa01c..ba40d68 100644 (file)
@@ -31,6 +31,7 @@
 
 typedef struct AmsMgrContext AmsMgrContext_t;
 
+
 typedef enum PEState
 {
     STOPPED = 0,              //Policy engine state machine is not running
@@ -39,6 +40,7 @@ typedef enum PEState
     BUSY                      //Can't process new request as processing other requests
 } PEState_t;
 
+
 typedef struct PEContext
 {
     PEState_t   state;
@@ -54,12 +56,13 @@ typedef struct PEContext
 /**
  * Check whether a request should be allowed.
  *
- * @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.
+ * @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.
  *
- * @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,
@@ -71,35 +74,33 @@ 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 is the pointer to Policy Engine context to initialize.
- *
- * @return ::OC_STACK_OK for Success, otherwise some error value.
+ * @param   context     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 is the pointer to Policy Engine context to de-initialize.
+ * @param   context     Pointer to Policy Engine context to de-initialize.
+ * @return  none
  */
 void DeInitPolicyEngine(PEContext_t *context);
 
 /**
- * Get CRUDN permission for a method.
- *
- * @param method is CRUDN permission being seeked.
- *
- * @return the uint16_t CRUDN permission .
+ * Return the uint16_t CRUDN permission corresponding to passed CAMethod_t.
  */
 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 is the policy engine context.
- * @param state set Policy engine state to this.
+ * @param context  Policy engine context.
+ * @param state    Set Policy engine state to this.
+ *
+ * @return         none
  */
 void SetPolicyEngineState(PEContext_t *context, const PEState_t state);
 
index 34a7822..b48c674 100644 (file)
@@ -21,8 +21,6 @@
 #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.
@@ -30,7 +28,7 @@
  * @note Caller of this method MUST use OCFree() method to release memory
  *       referenced by return value.
  *
- * @return char * reference to memory buffer containing SVR database.
+ * @retval  reference to memory buffer containing SVR database.
  */
 char * GetSVRDatabase();
 
@@ -41,34 +39,8 @@ char * GetSVRDatabase();
  * @param rsrcName string denoting the SVR name ("acl", "cred", "pstat" etc).
  * @param jsonObj JSON object containing the SVR contents.
  *
- * @return ::OC_STACK_OK for Success, otherwise some error value
+ * @retval  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 facab4e..3134788 100644 (file)
@@ -28,45 +28,36 @@ extern "C" {
 /**
  * Initialize Pstat resource by loading data from persistent storage.
  *
- * @return ::OC_STACK_OK for Success, otherwise some error value.
+ * @retval  OC_STACK_OK for Success, otherwise some error value
  */
 OCStackResult InitPstatResource();
 
 /**
  * Perform cleanup for Pstat resources.
  *
- * @return ::OC_STACK_OK for Success, otherwise some error value.
+ * @retval  OC_STACK_OK for Success, otherwise some error value
  */
 OCStackResult DeInitPstatResource();
 
 /**
- * This method converts PSTAT into the cbor payload.
+ * This method converts JSON PSTAT into binary PSTAT.
  *
- * @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.
+ * @param[in] jsonStr  pstat data in json string.
+ * @return pointer to OicSecPstat_t.
  */
- OCStackResult PstatToCBORPayload(const OicSecPstat_t *pstat, uint8_t **cborPayload,
-                                  size_t *cborSize);
+OicSecPstat_t * JSONToPstatBin(const char * jsonStr);
 
 /**
- * This method converts cbor into PSTAT data.
+ * This method converts pstat data into JSON format.
  *
- * @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.
+ * @param[in] pstat  pstat data in binary format.
+ * @return pointer to pstat json string.
  */
- OCStackResult CBORPayloadToPstat(const uint8_t *cborPayload, const size_t cborSize,
-                                  OicSecPstat_t **pstat);
+char * BinToPstatJSON(const OicSecPstat_t * pstat);
 
 /** This function deallocates the memory for OicSecPstat_t.
  *
- * @param pstat is the pointer to @ref OicSecPstat_t.
+ * @param[in] pstat  Pointer to OicSecPstat_t.
  */
 void DeletePstatBinData(OicSecPstat_t* pstat);
 
@@ -81,3 +72,5 @@ void RestorePstatToInitState();
 #endif
 
 #endif //IOTVT_SRM_PSTATR_H
+
+
index 6f8cc8c..3e946f5 100644 (file)
 /**
  * Initialize all secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
  *
- * @return ::OC_STACK_OK for Success, otherwise some error value
+ * @retval  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).
  *
- * @return ::OC_STACK_OK for Success, otherwise some error value
+ * @retval  OC_STACK_OK for Success, otherwise some error value
  */
 OCStackResult DestroySecureResources();
 
@@ -44,24 +44,13 @@ OCStackResult DestroySecureResources();
  *
  * @param ehRequest pointer to entity handler request data structure.
  * @param ehRet result code from entity handler.
- * @param rspPayload response payload.
+ * @param rspPayload response payload in JSON.
  *
- * @return ::OC_STACK_OK for Success, otherwise some error value.
+ * @retval  OC_STACK_OK for Success, otherwise some error value
  */
 OCStackResult SendSRMResponse(const OCEntityHandlerRequest *ehRequest,
         OCEntityHandlerResult ehRet, const char *rspPayload);
 
-/**
- * This method is used by all secure resource modules to send responses to REST queries.
- *
- * @param ehRequest pointer to entity handler request data structure.
- * @param ehRet result code from entity handler.
- * @param cborPayload response payload.
- *
- * @return ::OC_STACK_OK for Success, otherwise some error value.
- */
-OCStackResult SendSRMCBORResponse(const OCEntityHandlerRequest *ehRequest,
-        OCEntityHandlerResult ehRet, uint8_t *cborPayload);
-
 #endif //IOTVT_SRM_RM_H
 
+
index 51f6a3f..eb2643b 100644 (file)
@@ -28,85 +28,85 @@ extern "C" {
 #endif
 
 /**
- * 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.
+ * @brief   Register Persistent storage callback.
+ * @param   persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
+ * @return
+ *     OC_STACK_OK    - No errors; Success
+ *     OC_STACK_INVALID_PARAM - Invalid parameter
  */
 OCStackResult SRMRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler);
 
 /**
- * Get Persistent storage handler pointer.
- *
- * @return The pointer to Persistent Storage callback handler.
+ * @brief   Get Persistent storage handler pointer.
+ * @return
+ *     The pointer to Persistent Storage callback handler
  */
 OCPersistentStorage* SRMGetPersistentStorageHandler();
 
 /**
- * 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.
+ * @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
  */
 OCStackResult SRMRegisterHandler(CARequestCallback reqHandler,
                                  CAResponseCallback respHandler,
                                  CAErrorCallback errHandler);
 
 /**
- * Initialize all secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
- * @return  ::OC_STACK_OK for Success, otherwise some error value.
+ * @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
  */
 OCStackResult SRMInitSecureResources();
 
 /**
- * Perform cleanup for secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
+ * @brief   Perform cleanup for secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
+ * @return  none
  */
 void SRMDeInitSecureResources();
 
 /**
- * Initialize Policy Engine context.
- *
- * @return ::OC_STACK_OK for Success, otherwise some error value.
+ * @brief   Initialize Policy Engine context.
+ * @return  OC_STACK_OK for Success, otherwise some error value.
  */
 OCStackResult SRMInitPolicyEngine();
 
 /**
- * Cleanup Policy Engine context.
+ * @brief   Cleanup Policy Engine context.
+ * @return  none
  */
 void SRMDeInitPolicyEngine();
 
 /**
- * Provisioning API response callback.
- *
- * @param object endpoint instance.
- * @param responseInfo instance of CAResponseInfo_t structure.
- *
+ * @brief   Provisioning API response callback.
+ * @param object[IN]       endpoint instance.
+ * @param responseInfo[IN] 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);
 
 /**
- * Function to register provisoning API's response callback.
- *
+ * @brief function to register provisoning API's response callback.
  * @param respHandler response handler callback.
  */
 void SRMRegisterProvisioningResponseHandler(SPResponseCallback respHandler);
 
 /**
- * Check the security resource URI.
- * @param uri Pointers to security resource URI.
- * @return true if the URI is one of security resources, otherwise false.
+ * @brief   Check the security resource URI.
+ * @param   uri [IN] Pointers to security resource URI.
+ * @return  true if the URI is one of security resources, otherwise false.
  */
 bool SRMIsSecurityResourceURI(const char* uri);
 
 /**
- * Sends Response
- * @param resposeVal Response @ref SRMAccessResponse_t value.
+ * @brief   Sends Response
+ * @param   resposeVal       SRMAccessResponse_t value
+ * @return  NONE
  */
 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
deleted file mode 100644 (file)
index e477a0a..0000000
+++ /dev/null
@@ -1,114 +0,0 @@
-#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);
-
-/**
- * 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 a7a2df1..568bfa4 100644 (file)
@@ -24,7 +24,6 @@
 #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
@@ -113,7 +112,6 @@ 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 ce759f8..9db42c5 100644 (file)
@@ -28,33 +28,31 @@ extern "C" {
 /**
  * Initialize SVC resource by loading data from persistent storage.
  *
- * @return ::OC_STACK_OK for Success, otherwise some error value.
+ * @retval  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 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.
+ * 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.
  *
- * @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.
+ * @retval  pointer to SVC in json format.
  */
- OCStackResult SVCToCBORPayload(const OicSecSvc_t *svc, uint8_t **cborPayload,
-                                size_t *cborSize);
+char* BinToSvcJSON(const OicSecSvc_t * svc);
 
 #ifdef __cplusplus
 }
 #endif
 
 #endif //IOTVT_SRM_SVCR_H
+
+
index 2957db8..ff2e3e5 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 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
+ * @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
  *       derivedKey size)
- * @param derivedKey is the generated derived key
+ * @param[out] derivedKey is the generated derived key
  *
  * @return  0 on success
  */
index 67f07ac..de15015 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 pinCB implementation of generate PIN callback.
+ * @param[in] 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 pinCB implementation of input PIN callback.
+ * @param[in] pinCB implementation of input PIN callback
  */
 void SetInputPinCB(InputPinCallback pinCB);
 
@@ -58,20 +58,18 @@ void SetInputPinCB(InputPinCallback pinCB);
  * Function to generate random PIN.
  * This function will send generated PIN to user via callback.
  *
- * @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.
+ * @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.
  */
 OCStackResult GeneratePin(char* pinBuffer, size_t bufferSize);
 
 /**
- * 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.
+ * Function to input PIN callback via input callback
  *
- * @return ::OC_STACK_SUCCESS in case of success or other value in ccase of error.
+ * @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.
  */
 OCStackResult InputPin(char* pinBuffer, size_t bufferSize);
 
index 2357604..d8f7048 100644 (file)
@@ -52,8 +52,8 @@ extern "C" {
 #endif
 
 /**
- * Values used to create bit-maskable enums for single-value response with
- * embedded code.
+ * @brief   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;
 
 /**
- * /oic/sec/credtype (Credential Type) data type.
- * Derived from OIC Security Spec /oic/sec/cred; see Spec for details.
+ * @brief   /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
@@ -265,7 +265,7 @@ typedef struct OicSecCrl OicSecCrl_t;
 #endif /* __WITH_X509__ */
 
 /**
- * /oic/uuid (Universal Unique Identifier) data type.
+ * @brief   /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,19 +281,18 @@ struct OicUuid
 };
 
 /**
- * /oic/sec/jwk (JSON Web Key) data type.
- * See JSON Web Key (JWK)  draft-ietf-jose-json-web-key-41
+ * @brief   /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
 {
-    uint8_t                *data;
-    size_t                  len;
+    char                *data;
 };
 
 /**
- * /oic/sec/acl (Access Control List) data type.
- * Derived from OIC Security Spec; see Spec for details.
+ * @brief   /oic/sec/acl (Access Control List) data type.
+ *          Derived from OIC Security Spec; see Spec for details.
  */
 struct OicSecAcl
 {
@@ -317,8 +316,9 @@ struct OicSecAcl
 };
 
 /**
- * /oic/sec/amacl (Access Manager Service Accesss Control List) data type.
- * Derived from OIC Security Spec; see Spec for details.
+ * @brief   /oic/sec/amacl (Access Manager Service Accesss Control List)
+ *          data type.
+ *          Derived from OIC Security Spec; see Spec for details.
  */
 struct OicSecAmacl
 {
@@ -337,8 +337,8 @@ struct OicSecAmacl
 };
 
 /**
- * /oic/sec/cred (Credential) data type.
- * Derived from OIC Security Spec; see Spec for details.
+ * @brief   /oic/sec/cred (Credential) data type.
+ *          Derived from OIC Security Spec; see Spec for details.
  */
 struct OicSecCred
 {
@@ -363,8 +363,8 @@ struct OicSecCred
 };
 
 /**
- * /oic/sec/doxm (Device Owner Transfer Methods) data type
- * Derived from OIC Security Spec; see Spec for details.
+ * @brief   /oic/sec/doxm (Device Owner Transfer Methods) data type
+ *          Derived from OIC Security Spec; see Spec for details.
  */
 struct OicSecDoxm
 {
@@ -389,7 +389,7 @@ struct OicSecDoxm
 };
 
 /**
- * /oic/sec/pstat (Provisioning Status) data type.
+ * @brief   /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 +409,8 @@ struct OicSecPstat
 };
 
 /**
- * /oic/sec/role (Role) data type.
- * Derived from OIC Security Spec; see Spec for details.
+ * @brief   /oic/sec/role (Role) data type.
+ *          Derived from OIC Security Spec; see Spec for details.
  */
 struct OicSecRole
 {
@@ -420,8 +420,8 @@ struct OicSecRole
 };
 
 /**
- * /oic/sec/sacl (Signed Access Control List) data type.
- * Derived from OIC Security Spec; see Spec for details.
+ * @brief   /oic/sec/sacl (Signed Access Control List) data type.
+ *          Derived from OIC Security Spec; see Spec for details.
  */
 struct OicSecSacl
 {
@@ -430,8 +430,8 @@ struct OicSecSacl
 };
 
 /**
- * /oic/sec/svc (Service requiring a secure connection) data type.
- * Derived from OIC Security Spec; see Spec for details.
+ * @brief   /oic/sec/svc (Service requiring a secure connection) data type.
+ *          Derived from OIC Security Spec; see Spec for details.
  */
 struct OicSecSvc
 {
index 029a41b..80548f0 100644 (file)
@@ -33,76 +33,86 @@ extern "C"
 }
 #endif
 
+
 #ifdef __cplusplus
 extern "C" {
 #endif // __cplusplus
 
+
 typedef struct OicParseQueryIter OicParseQueryIter_t;
 
 /**
- * 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().
+ * @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().
  *
  */
 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*/
 };
 
 /**
- * Macro to verify success of operation.
+ * @def VERIFY_SUCCESS
+ * @brief 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)
 
 /**
- * Macro to verify argument is not equal to NULL.
+ * @def VERIFY_NON_NULL
+ * @brief 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 @ref OicParseQueryIter_t struct.
+ * This method initializes the OicParseQueryIter_t struct
+ *
+ *@param query     - REST query, to be parsed
+ *@param parseIter - OicParseQueryIter_t struct, to be initialized
  *
- * @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(const unsigned char * query, OicParseQueryIter_t * parseIter);
+void ParseQueryIterInit(unsigned char * query, OicParseQueryIter_t * parseIter);
+
 
 /**
- * This method fills the @ref OicParseQueryIter_t struct with next REST query's
- * attribute's and value's information.
+ * This method fills the OicParseQueryIter_t struct with next REST query's
+ * attribute's and value's information
  *
- * @param parseIter is the @ref OicParseQueryIter_t struct, has next query's attribute's
- *  & value's info.
+ *@param parseIter - OicParseQueryIter_t struct, has next query's attribute's & value's info
  *
- * @return reference to the @ref OicParseQueryIter_t if it has parsed query info, else
- * NULL if it has no query to parse.
+ * @retval
+ *     OicParseQueryIter_t *  - has parsed query info
+ *     NULL                   - has no query to parse
  */
 OicParseQueryIter_t * GetNextQuery(OicParseQueryIter_t * parseIter);
 
+
+
 /**
- * This method acts as a helper function for JSON unmarshalling by various SVR's.
+ * This method acts as a helper funtion for JSON unmarshalling by various SVR'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.
+ * @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
  *
  * @return ::OC_STACK_OK on success, some other value upon failure.
  */
-OCStackResult AddUuidArray(const cJSON* jsonRoot, const char* arrayItem,
-                           size_t *numUuids, OicUuid_t** uuids);
+OCStackResult AddUuidArray(cJSON* jsonRoot, const char* arrayItem,
+                           size_t *numUuids, OicUuid_t** uuids );
 
 /**
  * Function to getting string of ownership transfer method
index 2385e84..5558dd0 100644 (file)
@@ -116,6 +116,6 @@ provisioning_env.UserInstallTargetLib(provisioningserver, 'libocpmapi')
 if env.get('DTLS_WITH_X509') == '1':
        SConscript('ck_manager/SConscript')
 
-if target_os in ['linux', 'tizen']:
+if target_os in ['linux']:
        SConscript('sample/SConscript')
 
index 57ce4f6..bf7deed 100644 (file)
@@ -75,8 +75,7 @@ typedef OCStackResult (*OTMCreateSecureSession)(OTMContext_t* otmCtx);
 /*\r
  * Callback for creating CoAP payload.\r
  */\r
-typedef OCStackResult (*OTMCreatePayloadCallback)(OTMContext_t* otmCtx, uint8_t **payload, \r
-                                                  size_t *size);\r
+typedef char* (*OTMCreatePayloadCallback)(OTMContext_t* otmCtx);\r
 \r
 /**\r
  * Required callback for performing ownership transfer\r
index 0b9f81e..190b55d 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,45 +35,35 @@ 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 otmCtx Context of OTM, It includes current device information.
- *
- * @return ::OC_STACK_SUCCESS in case of success and other value otherwise.
+ * @param[in] selectedDeviceInfo Selected device infomation
+ * @return OC_STACK_SUCCESS in case of success and other value otherwise.
  */
 OCStackResult CreateSecureSessionJustWorksCallback(OTMContext_t* otmCtx);
 
 /**
  * Generate payload for select OxM request.
  *
- * @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.
+ * @param[in] selectedDeviceInfo Selected device infomation
+ * @return DOXM JSON payload including the selected OxM.
+ *         NOTE : Returned memory should be deallocated by caller.
  */
-OCStackResult CreateJustWorksSelectOxmPayload(OTMContext_t *otmCtx, uint8_t **cborPayload,
-                                             size_t *cborSize);
+char* CreateJustWorksSelectOxmPayload(OTMContext_t* otmCtx);
 
 /**
  * Generate payload for owner transfer request.
  *
- * @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.
+ * @param[in] selectedDeviceInfo Selected device infomation
+ * @return DOXM JSON payload including the owner information.
+ *         NOTE : Returned memory should be deallocated by caller.
  */
-OCStackResult CreateJustWorksOwnerTransferPayload(OTMContext_t *otmCtx, uint8_t **cborPayload,
-                                                  size_t *cborSize);
+char* CreateJustWorksOwnerTransferPayload(OTMContext_t* otmCtx);
+
 #ifdef __cplusplus
 }
 #endif
index ae7b110..b458ef3 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,46 +34,36 @@ extern "C" {
 /**
  * Callback implementation to input the PIN code from user.
  *
- * @param otmCtx Context of OTM, It includes current device information.
- *
- * @return ::OC_STACK_SUCCESS in case of success and other value otherwise.
+ * @otmCtx  Context of OTM, It includes current device infomation.
+ * @return OC_STACK_SUCCESS in case of success and other value otherwise.
  */
-OCStackResult InputPinCodeCallback(OTMContext_t *otmCtx);
+OCStackResult InputPinCodeCallback(OTMContext_totmCtx);
 
 /**
- * Callback implemenration to establish a secure channel with PSK cipher suite.
- *
- * @param otmCtx Context of OTM, It includes current device information.
+ * Callback implemenration to establish a secure channel with PSK cipher suite
  *
- * @return ::OC_STACK_SUCCESS in case of success and other value otherwise.
+ * @param[in] selectedDeviceInfo Selected device infomation
+ * @return OC_STACK_SUCCESS in case of success and other value otherwise.
  */
 OCStackResult CreateSecureSessionRandomPinCallback(OTMContext_t *otmCtx);
 
 /**
  * Generate payload for select OxM request.
  *
- * @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.
+ * @param[in] selectedDeviceInfo Selected device infomation
+ * @return DOXM JSON payload including the selected OxM.
+ *         NOTE : Returned memory should be deallocated by caller.
  */
-OCStackResult CreatePinBasedSelectOxmPayload(OTMContext_t *otmCtx, uint8_t **cborPayload,
-                                             size_t *cborSize);
+char* CreatePinBasedSelectOxmPayload(OTMContext_t* otmCtx);
 
 /**
  * Generate payload for owner transfer request.
  *
- * @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.
+ * @param[in] selectedDeviceInfo Selected device infomation
+ * @return DOXM JSON payload including the owner information.
+ *         NOTE : Returned memory should be deallocated by caller.
  */
-OCStackResult CreatePinBasedOwnerTransferPayload(OTMContext_t *otmCtx, uint8_t **cborPayload,
-                                                 size_t *cborSize);
+char* CreatePinBasedOwnerTransferPayload(OTMContext_t* otmCtx);
 
 #ifdef __cplusplus
 }
index 74e4568..46fe3d8 100644 (file)
@@ -23,6 +23,8 @@ Import('env')
 
 provisioning_env = env.Clone()
 
+target_os = env.get('TARGET_OS')
+
 ######################################################################
 # Build flags
 ######################################################################
@@ -60,20 +62,18 @@ 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
 ######################################################################
 
-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')
-
 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,
index eb16fd6..df7754b 100644 (file)
  * *****************************************************************/
 #include <string.h>
 #include "credentialgenerator.h"
-#include "base64.h"
 #include "oic_malloc.h"
 #include "oic_string.h"
-#include "ocpayload.h"
-#include "payload_logging.h"
+#include "logger.h"
 #include "credresource.h"
 #include "ocrandom.h"
-#include "srmutility.h"
+#include "base64.h"
 #include "stdbool.h"
 #include "securevirtualresourcetypes.h"
 #ifdef __WITH_X509__
 
 #define TAG "SRPAPI-CG"
 
-static const char OIC_JSON_CRV_NAME[] = "crv";
-static const char OIC_JSON_KTY_NAME[] = "kty";
-static const char OIC_JSON_CERTIFICATE_NAME[] = "x5c";
-static const char OIC_JSON_D_NAME[] = "d";
-static const char kty[] = "EC";
-static const char crv[] = "P-256";
-static const uint8_t CertMapSize = 3;
+/**
+ * @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)
     {
@@ -61,30 +71,42 @@ 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;
 
-    uint8_t *privData = (uint8_t *)OICCalloc(privDataKeySize, sizeof(uint8_t));
-    VERIFY_NON_NULL(TAG, privData, ERROR);
+    privData = (uint8_t*) OICCalloc(privDataKeySize,sizeof(uint8_t));
+    PM_VERIFY_NON_NULL(TAG, privData, OC_STACK_NO_MEMORY, ERROR);
 
-    OCFillRandomMem(privData, privDataKeySize);
+    OCFillRandomMem(privData,privDataKeySize);
+
+    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);
 
     // TODO: currently owner array is 1. only provisioning tool's id.
-    tempFirstCred =  GenerateCredential(secondDeviceId, type, NULL, privData, 1, ptDeviceId);
-    VERIFY_NON_NULL(TAG, tempFirstCred, ERROR);
+    tempFirstCred =  GenerateCredential(secondDeviceId, type, NULL, base64Buff, 1, ptDeviceId);
+    PM_VERIFY_NON_NULL(TAG, tempFirstCred, OC_STACK_ERROR, ERROR);
 
     // TODO: currently owner array is 1. only provisioning tool's id.
-    tempSecondCred =  GenerateCredential(firstDeviceId, type, NULL, privData, 1, ptDeviceId);
-    VERIFY_NON_NULL(TAG, tempSecondCred, ERROR);
+    tempSecondCred =  GenerateCredential(firstDeviceId, type, NULL, base64Buff, 1, ptDeviceId);
+    PM_VERIFY_NON_NULL(TAG, tempSecondCred, OC_STACK_ERROR, ERROR);
 
     *firstCred = tempFirstCred;
     *secondCred = tempSecondCred;
     res = OC_STACK_OK;
 
-exit:
+bail:
     OICFree(privData);
+    OICFree(base64Buff);
 
     if(res != OC_STACK_OK)
     {
@@ -101,22 +123,17 @@ exit:
 /**
  * Function to compose JSON Web Key (JWK) string from a certificate and a public key.
  *
- * @param certificateChain    Array of Base64 encoded certificate strings.
- * @param chainLength         Number of the certificates in certificateChain.
- * @param payload Valid JWK CBOR on success, or NULL on fail.
-
+ * @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 OCStackResult CreateCertificatePublicJWK(const char *const *certificateChain,
-       const size_t chainLength, uint8_t **cborPayload, size_t *size)
+static char *CreateCertificatePublicJWK(const char *const *certificateChain,
+                                        const size_t chainLength)
 {
-    OCStackResult ret = OC_STACK_ERROR;
-    *cborPayload = NULL;
-    *size = 0;
-
     if (NULL == certificateChain || chainLength == 0)
     {
         OIC_LOG(ERROR, TAG, "Error CreateCertificatePublicJWK: Invalid params");
-        return OC_STACK_INVALID_PARAM;
+        return NULL;
     }
 
     size_t certChainSize = 0;
@@ -129,118 +146,70 @@ static OCStackResult CreateCertificatePublicJWK(const char *const *certificateCh
         else
         {
             OIC_LOG(ERROR, TAG, "Error CreateCertificatePublicJWK: Invalid params");
-            return OC_STACK_INVALID_PARAM;
+            return NULL;
         }
-    }
 
-    // cborArbitraryLen is a value to conver field names and cbor map, cbor array.
-    size_t cborArbitraryLen = 255;
-    size_t cborLen = certChainSize + cborArbitraryLen;
-    int64_t cborEncoderResult = CborNoError;
-    CborEncoder encoder = { .end = 0 };
-    uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
-    VERIFY_NON_NULL(TAG, outPayload, ERROR);
-    cbor_encoder_init(&encoder, outPayload, cborLen, 0);
-
-    CborEncoder credMap = { .end = 0 };
-    cborEncoderResult |= cbor_encoder_create_map(&encoder, &credMap, CertMapSize);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Map.");
-
-    cborEncoderResult |= cbor_encode_text_string(&credMap, OIC_JSON_KTY_NAME,
-            strlen(OIC_JSON_KTY_NAME));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ");
-    cborEncoderResult |= cbor_encode_text_string(&credMap, kty, strlen(kty));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ");
-
-    cborEncoderResult |= cbor_encode_text_string(&credMap, OIC_JSON_CRV_NAME,
-            strlen(OIC_JSON_CRV_NAME));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ");
-    cborEncoderResult |= cbor_encode_text_string(&credMap, crv, strlen(crv));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ");
-
-    cborEncoderResult |= cbor_encode_text_string(&credMap, OIC_JSON_CERTIFICATE_NAME,
-            strlen(OIC_JSON_CERTIFICATE_NAME));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Certificate Name.");
-    CborEncoder certs = { {.ptr = NULL }, .end = 0 };
-    cborEncoderResult |= cbor_encoder_create_array(&credMap, &certs, chainLength);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Certificate Array.");
-    for (size_t i = 0; i < chainLength; i++)
+    }
+    /* 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)
     {
-        cborEncoderResult |= cbor_encode_byte_string(&certs, (uint8_t *)certificateChain[i], strlen(certificateChain[i]));
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Certificate Chain.");
+        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);
     }
-    cborEncoderResult |= cbor_encoder_close_container(&credMap, &certs);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Certificate Chain.");
-
-    cborEncoderResult |= cbor_encoder_close_container(&encoder, &credMap);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Cred Map.");
-
-    *cborPayload = outPayload;
-    *size = encoder.ptr - outPayload;
-    ret = OC_STACK_OK;
-
-exit:
-    return ret;
+    else
+    {
+        OIC_LOG(ERROR, TAG, "Error while memory allocation");
+    }
+    return certPubJWK;
 }
 
 /**
  * Function to compose JWK string from a private key.
  *
- * @param privateKey to be converted to CBOR.
- * @ Valid JWK string on success, or NULL on fail.
+ * @param[in]  privateKey    Base64 encoded private key.
+ * @return     Valid JWK string on success, or NULL on fail.
  */
-OCStackResult CreateCertificatePrivateJWK(const char *privateKey, uint8_t **cborPayload,
-        size_t *size)
+static char *CreateCertificatePrivateJWK(const char *privateKey)
 {
-    *cborPayload = NULL;
-    *size = 0;
-    OCStackResult ret = OC_STACK_INVALID_PARAM;
-    VERIFY_NON_NULL(TAG, privateKey, ERROR);
-
-    // cborArbitraryLen is a value to conver field names and cbor map, cbor array.
-    size_t cborArbitraryLen = 255;
-    size_t cborLen = strlen(privateKey) + cborArbitraryLen;
-    int64_t cborEncoderResult = CborNoError;
-    ret = OC_STACK_ERROR;
-    uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
-    VERIFY_NON_NULL(TAG, outPayload, ERROR);
-
-    CborEncoder encoder = { .end = 0 };
-    cbor_encoder_init(&encoder, outPayload, cborLen, 0);
-
-    CborEncoder credMap = { .end = 0 };
-    cborEncoderResult |= cbor_encoder_create_map(&encoder, &credMap, 3);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ");
-
-    cborEncoderResult |= cbor_encode_text_string(&credMap, OIC_JSON_KTY_NAME,
-            strlen(OIC_JSON_KTY_NAME));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ");
-    cborEncoderResult |= cbor_encode_text_string(&credMap, kty, strlen(kty));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ");
-
-    cborEncoderResult |= cbor_encode_text_string(&credMap, OIC_JSON_CRV_NAME,
-            strlen(OIC_JSON_CRV_NAME));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ");
-    cborEncoderResult |= cbor_encode_text_string(&credMap, crv, strlen(crv));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ");
-
-    cborEncoderResult |= cbor_encode_text_string(&credMap, OIC_JSON_D_NAME,
-            strlen(OIC_JSON_D_NAME));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding D tag.");
-    cborEncoderResult |= cbor_encode_byte_string(&credMap, (uint8_t *)privateKey, strlen(privateKey));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding D Value.");
-
-    cborEncoderResult |= cbor_encoder_close_container(&encoder, &credMap);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Cred Map.");
-
-    *cborPayload = outPayload;
-    *size = encoder.ptr - outPayload;
-    ret = OC_STACK_OK;
-
-exit:
-    return ret;
+    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);
+
+    if (NULL != certPrivJWK)
+    {
+        snprintf(certPrivJWK, len, "%s%s%s", firstPart, privateKey, secondPart);
+    }
+    else
+    {
+        OIC_LOG(ERROR, TAG, "Error while memory allocation");
+    }
+    return certPrivJWK;
 }
 
+
 /**
  * Function to generate Base64 encoded credential data for device.
  *
@@ -370,6 +339,7 @@ memclean:
     return OC_STACK_OK;
 }
 
+
 OCStackResult PMGenerateCertificateCredentials(const OicUuid_t *ptDeviceId,
         const OicUuid_t *deviceId, OicSecCred_t **const cred)
 {
@@ -387,18 +357,8 @@ OCStackResult PMGenerateCertificateCredentials(const OicUuid_t *ptDeviceId,
         return OC_STACK_ERROR;
     }
 
-    uint8_t *publicJWK = NULL;
-    size_t len = 0;
-    if (OC_STACK_OK == CreateCertificatePublicJWK(certificateChain, certChainLen, &publicJWK, &len))
-    {
-
-    }
-    uint8_t *privateJWK = NULL;
-    size_t len1 = 0;
-    if (OC_STACK_OK == CreateCertificatePrivateJWK(privKey, &privateJWK, &len1))
-    {
-
-    }
+    char *publicJWK = CreateCertificatePublicJWK(certificateChain, certChainLen);
+    char *privateJWK = CreateCertificatePrivateJWK(privKey);
     for (size_t i = 0; i < certChainLen; ++i)
     {
         OICFree(certificateChain[i]);
index 185dd7d..486cf73 100644 (file)
@@ -58,8 +58,6 @@
 #include "srmutility.h"
 #include "provisioningdatabasemanager.h"
 #include "oxmrandompin.h"
-#include "ocpayload.h"
-#include "payload_logging.h"
 
 #define TAG "OTM"
 
@@ -439,10 +437,16 @@ 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,
-                ownerPSK, ownLen, &ptDeviceID);
+                base64Buff, ownLen, &ptDeviceID);
         VERIFY_NON_NULL(TAG, cred, ERROR);
 
         res = AddCredential(cred);
@@ -539,14 +543,12 @@ static OCStackApplicationResult ListMethodsHandler(void *ctx, OCDoHandle UNUSED,
             SetResult(otmCtx, OC_STACK_ERROR);
             return OC_STACK_DELETE_TRANSACTION;
         }
-        uint8_t size = 0;
-        OicSecPstat_t* pstat = NULL;
-        OCStackResult result = CBORPayloadToPstat(
-                ((OCSecurityPayload*)clientResponse->payload)->securityData1,
-                size, &pstat);
-        if(NULL == pstat && result != OC_STACK_OK)
+
+        OicSecPstat_t* pstat = JSONToPstatBin(
+                ((OCSecurityPayload*)clientResponse->payload)->securityData);
+        if(NULL == pstat)
         {
-            OIC_LOG(ERROR, TAG, "Error while converting cbor to pstat.");
+            OIC_LOG(ERROR, TAG, "Error while converting json to pstat bin");
             SetResult(otmCtx, OC_STACK_ERROR);
             return OC_STACK_DELETE_TRANSACTION;
         }
@@ -930,8 +932,8 @@ static OCStackResult PutOwnerCredential(OTMContext_t* otmCtx)
         newCredential.privateData.data = NULL;
 
         //Send owner credential to new device : PUT /oic/sec/cred [ owner credential ]
-        size_t size = 0;
-        if (OC_STACK_OK != CredToCBORPayload(&newCredential, &secPayload->securityData1, &size))
+        secPayload->securityData = BinToCredJSON(&newCredential);
+        if (NULL == secPayload->securityData)
         {
             OICFree(secPayload);
             OIC_LOG(ERROR, TAG, "Error while converting bin to json");
@@ -992,14 +994,11 @@ static OCStackResult PutOwnerTransferModeToResource(OTMContext_t* otmCtx)
         return OC_STACK_NO_MEMORY;
     }
     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
-    size_t size = 0;
-    OCStackResult res = g_OTMDatas[selectedOxm].createSelectOxmPayloadCB(otmCtx,
-                                                                         &secPayload->securityData1,
-                                                                         &size);
-    if (OC_STACK_OK != res && NULL == secPayload->securityData1)
-    {
-        OCPayloadDestroy((OCPayload *)secPayload);
-        OIC_LOG(ERROR, TAG, "Error while converting bin to cbor");
+    secPayload->securityData = g_OTMDatas[selectedOxm].createSelectOxmPayloadCB(otmCtx);
+    if (NULL == secPayload->securityData)
+    {
+        OICFree(secPayload);
+        OIC_LOG(ERROR, TAG, "Error while converting bin to json");
         return OC_STACK_ERROR;
     }
 
@@ -1007,9 +1006,9 @@ static OCStackResult PutOwnerTransferModeToResource(OTMContext_t* otmCtx)
     cbData.cb = &OwnerTransferModeHandler;
     cbData.context = (void *)otmCtx;
     cbData.cd = NULL;
-    res = OCDoResource(NULL, OC_REST_PUT, query,
-                       &deviceInfo->endpoint, (OCPayload *)secPayload,
-                       deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
+    OCStackResult 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");
@@ -1088,24 +1087,23 @@ static OCStackResult PutOwnerUuid(OTMContext_t* otmCtx)
         return OC_STACK_NO_MEMORY;
     }
     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
-    size_t size = 0;
-    OCStackResult res =  g_OTMDatas[deviceInfo->doxm->oxmSel].createOwnerTransferPayloadCB(
-            otmCtx, &secPayload->securityData1, &size);
-    if (NULL == secPayload->securityData1)
+    secPayload->securityData =
+        g_OTMDatas[deviceInfo->doxm->oxmSel].createOwnerTransferPayloadCB(otmCtx);
+    if (NULL == secPayload->securityData)
     {
-        OCPayloadDestroy((OCPayload *)secPayload);
-        OIC_LOG(ERROR, TAG, "Error while converting doxm bin to cbor.");
+        OICFree(secPayload);
+        OIC_LOG(ERROR, TAG, "Error while converting doxm bin to json");
         return OC_STACK_INVALID_PARAM;
     }
-    OIC_LOG_V(DEBUG, TAG, "Payload : %s", secPayload->securityData1);
+    OIC_LOG_V(DEBUG, TAG, "Payload : %s", secPayload->securityData);
 
     OCCallbackData cbData;
     cbData.cb = &OwnerUuidUpdateHandler;
     cbData.context = (void *)otmCtx;
     cbData.cd = NULL;
 
-    res = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload *)secPayload,
-            deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
+    OCStackResult 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");
@@ -1147,14 +1145,10 @@ static OCStackResult PutOwnershipInformation(OTMContext_t* otmCtx)
     }
 
     otmCtx->selectedDeviceInfo->doxm->owned = true;
-
-    secPayload->base.type = PAYLOAD_TYPE_SECURITY;
-    size_t size = 0;
-    OCStackResult res = DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm,
-            &secPayload->securityData1, &size);
-    if (OC_STACK_OK != res && NULL == secPayload->securityData1)
+    secPayload->securityData = BinToDoxmJSON(otmCtx->selectedDeviceInfo->doxm);
+    if (NULL == secPayload->securityData)
     {
-        OCPayloadDestroy((OCPayload *)secPayload);
+        OICFree(secPayload);
         OIC_LOG(ERROR, TAG, "Error while converting doxm bin to json");
         return OC_STACK_INVALID_PARAM;
     }
@@ -1165,8 +1159,8 @@ static OCStackResult PutOwnershipInformation(OTMContext_t* otmCtx)
     cbData.context = (void *)otmCtx;
     cbData.cd = NULL;
 
-    res = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload*)secPayload,
-                       deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
+    OCStackResult 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");
@@ -1205,13 +1199,11 @@ static OCStackResult PutUpdateOperationMode(OTMContext_t* otmCtx)
         return OC_STACK_NO_MEMORY;
     }
     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
-    size_t size = 0;
-    OCStackResult res = PstatToCBORPayload(deviceInfo->pstat, &secPayload->securityData1,
-                                           &size);
-   if (OC_STACK_OK != res)
+    secPayload->securityData = BinToPstatJSON(deviceInfo->pstat);
+    if (NULL == secPayload->securityData)
     {
-        OCPayloadDestroy((OCPayload *)secPayload);
-        OIC_LOG(ERROR, TAG, "Error while converting pstat to cbor.");
+        OICFree(secPayload);
+        OIC_LOG(ERROR, TAG, "Error while converting pstat bin to json");
         return OC_STACK_INVALID_PARAM;
     }
 
@@ -1219,8 +1211,8 @@ static OCStackResult PutUpdateOperationMode(OTMContext_t* otmCtx)
     cbData.cb = &OperationModeUpdateHandler;
     cbData.context = (void *)otmCtx;
     cbData.cd = NULL;
-    res = OCDoResource(NULL, OC_REST_PUT, query, 0, (OCPayload*)secPayload,
-                       deviceInfo->connType, OC_LOW_QOS, &cbData, NULL, 0);
+    OCStackResult 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");
@@ -1375,6 +1367,7 @@ error:
     OICFree(otmCtx->ctxResultArray);
     OICFree(otmCtx);
     return res;
+
 }
 
 OCStackResult PutProvisioningStatus(OTMContext_t* otmCtx)
@@ -1403,15 +1396,14 @@ OCStackResult PutProvisioningStatus(OTMContext_t* otmCtx)
         return OC_STACK_NO_MEMORY;
     }
     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
-    size_t size = 0;
-    if (OC_STACK_OK != PstatToCBORPayload(otmCtx->selectedDeviceInfo->pstat,
-            &secPayload->securityData1, &size))
+    secPayload->securityData = BinToPstatJSON(otmCtx->selectedDeviceInfo->pstat);
+    if (NULL == secPayload->securityData)
     {
-        OCPayloadDestroy((OCPayload *)secPayload);
+        OICFree(secPayload);
         SetResult(otmCtx, OC_STACK_INVALID_JSON);
         return OC_STACK_INVALID_JSON;
     }
-    OIC_LOG_V(INFO, TAG, "Created payload for commit hash: %s",secPayload->securityData1);
+    OIC_LOG_V(INFO, TAG, "Created payload for commit hash: %s",secPayload->securityData);
 
     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
     if(!PMGenerateQuery(true,
@@ -1442,3 +1434,4 @@ OCStackResult PutProvisioningStatus(OTMContext_t* otmCtx)
 
     return ret;
 }
+
index 480a50d..ca65bdd 100644 (file)
 
 #define TAG "OXM_JustWorks"
 
-OCStackResult CreateJustWorksSelectOxmPayload(OTMContext_t *otmCtx, uint8_t **payload, size_t *size)
+char* CreateJustWorksSelectOxmPayload(OTMContext_t* otmCtx)
 {
-    if (!otmCtx || !otmCtx->selectedDeviceInfo || !payload || *payload || !size)
+    if(!otmCtx || !otmCtx->selectedDeviceInfo)
     {
-        return OC_STACK_INVALID_PARAM;
+        return NULL;
     }
 
     otmCtx->selectedDeviceInfo->doxm->oxmSel = OIC_JUST_WORKS;
-    *payload = NULL;
-    *size = 0;
-
-    return DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm, payload, size);
+    return BinToDoxmJSON(otmCtx->selectedDeviceInfo->doxm);
 }
 
-OCStackResult CreateJustWorksOwnerTransferPayload(OTMContext_t* otmCtx, uint8_t **payload, size_t *size)
+char* CreateJustWorksOwnerTransferPayload(OTMContext_t* otmCtx)
 {
-    if (!otmCtx || !otmCtx->selectedDeviceInfo || !payload || *payload || !size)
+    if(!otmCtx || !otmCtx->selectedDeviceInfo)
     {
-        return OC_STACK_INVALID_PARAM;
+        return NULL;
     }
 
     OicUuid_t uuidPT = {.id={0}};
@@ -58,14 +55,11 @@ OCStackResult CreateJustWorksOwnerTransferPayload(OTMContext_t* otmCtx, uint8_t
     if (OC_STACK_OK != GetDoxmDeviceID(&uuidPT))
     {
         OIC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
-        return OC_STACK_ERROR;
+        return NULL;
     }
     memcpy(otmCtx->selectedDeviceInfo->doxm->owner.id, uuidPT.id , UUID_LENGTH);
 
-    *payload = NULL;
-    *size = 0;
-
-    return DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm, payload, size);;
+    return BinToDoxmJSON(otmCtx->selectedDeviceInfo->doxm);
 }
 
 OCStackResult LoadSecretJustWorksCallback(OTMContext_t* UNUSED_PARAM)
@@ -78,7 +72,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;
     }
@@ -108,13 +102,13 @@ OCStackResult CreateSecureSessionJustWorksCallback(OTMContext_t* otmCtx)
     }
     OIC_LOG(INFO, TAG, "TLS_ECDH_anon_WITH_AES_128_CBC_SHA_256 cipher suite selected.");
 
-    OCProvisionDev_t *selDevInfo = otmCtx->selectedDeviceInfo;
+    OCProvisionDev_tselDevInfo = 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 04643c5..138c274 100644 (file)
 
 #define TAG "OXM_RandomPIN"
 
-OCStackResult CreatePinBasedSelectOxmPayload(OTMContext_t* otmCtx, uint8_t **payload, size_t *size)
+char* CreatePinBasedSelectOxmPayload(OTMContext_t* otmCtx)
 {
-    *payload = NULL;
-    *size = 0;
-    if(!otmCtx || !otmCtx->selectedDeviceInfo || !payload || *payload || !size)
+    if(!otmCtx || !otmCtx->selectedDeviceInfo)
     {
-        return OC_STACK_INVALID_PARAM;
+        return NULL;
     }
 
     otmCtx->selectedDeviceInfo->doxm->oxmSel = OIC_RANDOM_DEVICE_PIN;
 
-    return DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm, payload, size);
+    return BinToDoxmJSON(otmCtx->selectedDeviceInfo->doxm);
 }
 
-OCStackResult CreatePinBasedOwnerTransferPayload(OTMContext_t* otmCtx, uint8_t **payload, size_t *size)
+char* CreatePinBasedOwnerTransferPayload(OTMContext_t* otmCtx)
 {
-    if(!otmCtx || !otmCtx->selectedDeviceInfo || !payload || *payload || !size)
+    if(!otmCtx || !otmCtx->selectedDeviceInfo)
     {
-        return OC_STACK_INVALID_PARAM;
+        return NULL;
     }
 
     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 OC_STACK_ERROR;
+        return NULL;
     }
     memcpy(otmCtx->selectedDeviceInfo->doxm->owner.id, uuidPT.id , UUID_LENGTH);
 
-    return DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm, payload, size);
+    return BinToDoxmJSON(otmCtx->selectedDeviceInfo->doxm);
 }
 
-OCStackResult InputPinCodeCallback(OTMContext_t *otmCtx)
+OCStackResult InputPinCodeCallback(OTMContext_totmCtx)
 {
-    if (!otmCtx || !otmCtx->selectedDeviceInfo)
+    if(!otmCtx || !otmCtx->selectedDeviceInfo)
     {
         return OC_STACK_INVALID_PARAM;
     }
@@ -83,7 +79,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;
@@ -110,7 +106,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;
     }
@@ -131,9 +127,10 @@ 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;
     }
@@ -151,3 +148,4 @@ OCStackResult CreateSecureSessionRandomPinCallback(OTMContext_t* otmCtx)
 
     return OC_STACK_OK;
 }
+
index 31208db..2e4158b 100644 (file)
@@ -489,17 +489,16 @@ static OCStackApplicationResult DeviceDiscoveryHandler(void *ctx, OCDoHandle UNU
                 OIC_LOG(INFO, TAG, "Unknown payload type");
                 return OC_STACK_KEEP_TRANSACTION;
             }
-            OicSecDoxm_t *ptrDoxm = NULL;
-            uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData1;
-            OCStackResult res = CBORPayloadToDoxm(payload, 0, &ptrDoxm);
-            if ((NULL == ptrDoxm) && (OC_STACK_OK != res))
+            OicSecDoxm_t *ptrDoxm = JSONToDoxmBin(
+                            ((OCSecurityPayload*)clientResponse->payload)->securityData);
+            if (NULL == ptrDoxm)
             {
-                OIC_LOG(INFO, TAG, "Ignoring malformed CBOR");
+                OIC_LOG(INFO, TAG, "Ignoring malformed JSON");
                 return OC_STACK_KEEP_TRANSACTION;
             }
             else
             {
-                OIC_LOG(DEBUG, TAG, "Successfully converted doxm cbor to bin.");
+                OIC_LOG(DEBUG, TAG, "Successfully converted doxm json to bin.");
 
                 //If this is owend device discovery we have to filter out the responses.
                 DiscoveryInfo* pDInfo = (DiscoveryInfo*)ctx;
index 35bcd77..d3056c0 100644 (file)
@@ -40,7 +40,6 @@
 #include "provisioningdatabasemanager.h"
 #include "base64.h"
 #include "utlist.h"
-#include "ocpayload.h"
 
 #ifdef __WITH_X509__
 #include "crlresource.h"
@@ -298,21 +297,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;
-    size_t size = 0;
-    OCStackResult res = CredToCBORPayload(cred, &secPayload->securityData1, &size);
-    if((OC_STACK_OK != res) && (NULL == secPayload->securityData1))
+    secPayload->securityData = BinToCredJSON(cred);
+    if(NULL == secPayload->securityData)
     {
-        OCPayloadDestroy((OCPayload *)secPayload);
-        OIC_LOG(ERROR, TAG, "Failed to CredToCBORPayload");
+        OICFree(secPayload);
+        OIC_LOG(ERROR, TAG, "Failed to BinToCredJSON");
         return OC_STACK_NO_MEMORY;
     }
 
+    OIC_LOG_V(INFO, TAG, "Credential for provisioning : %s",secPayload->securityData);
     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
     if(!PMGenerateQuery(true,
                         deviceInfo->endpoint.addr,
@@ -498,7 +497,7 @@ OCStackResult SRPProvisionCRL(void *ctx, const OCProvisionDev_t *selectedDeviceI
     crlData->resArr = (OCProvisionResult_t*)OICCalloc(1, sizeof(OCProvisionResult_t));
     if (crlData->resArr == NULL)
     {
-        OICFree(secPayload->securityData1);
+        OICFree(secPayload->securityData);
         OICFree(secPayload);
         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
         return OC_STACK_NO_MEMORY;
@@ -542,16 +541,16 @@ static OCStackResult provisionCertCred(const OicSecCred_t *cred,
         return OC_STACK_NO_MEMORY;
     }
     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
-    size_t size = 0;
-    OCStackResult res = CredToCBORPayload(cred, &secPayload->securityData1, &size);
+    secPayload->securityData = BinToCredJSON(cred);
 
-    if ((OC_STACK_OK != res) || (NULL == secPayload->securityData1))
+    if (NULL == secPayload->securityData)
     {
         OICFree(secPayload);
-        OIC_LOG(ERROR, TAG, "Failed to CredToCBORPayload");
+        OIC_LOG(ERROR, TAG, "Failed to BinToCredJSON");
         return OC_STACK_NO_MEMORY;
     }
 
+    OIC_LOG_V(INFO, TAG, "Credential for provisioning : %s",secPayload->securityData);
     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
     if(!PMGenerateQuery(true,
                         deviceInfo->endpoint.addr,
@@ -560,7 +559,8 @@ static OCStackResult provisionCertCred(const OicSecCred_t *cred,
                         query, sizeof(query), OIC_RSRC_CRED_URI))
     {
         OIC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
-        OCPayloadDestroy((OCPayload *)secPayload);
+        OICFree(secPayload->securityData);
+        OICFree(secPayload);
         return OC_STACK_ERROR;
     }
     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
@@ -848,13 +848,15 @@ OCStackResult SRPProvisionACL(void *ctx, const OCProvisionDev_t *selectedDeviceI
         return OC_STACK_NO_MEMORY;
     }
     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
-    size_t size = 0;
-    if(OC_STACK_OK != AclToCBORPayload(acl, &secPayload->securityData1, &size))
+    secPayload->securityData = BinToAclJSON(acl);
+    if(NULL == secPayload->securityData)
     {
-        OCPayloadDestroy((OCPayload *)secPayload);
-        OIC_LOG(ERROR, TAG, "Failed to AclToCBORPayload");
+        OICFree(secPayload);
+        OIC_LOG(ERROR, TAG, "Failed to BinToAclJSON");
         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,
@@ -872,7 +874,8 @@ OCStackResult SRPProvisionACL(void *ctx, const OCProvisionDev_t *selectedDeviceI
     ACLData_t *aclData = (ACLData_t *) OICCalloc(1, sizeof(ACLData_t));
     if (aclData == NULL)
     {
-        OCPayloadDestroy((OCPayload *)secPayload);
+        OICFree(secPayload->securityData);
+        OICFree(secPayload);
         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
         return OC_STACK_NO_MEMORY;
     }
@@ -886,7 +889,8 @@ OCStackResult SRPProvisionACL(void *ctx, const OCProvisionDev_t *selectedDeviceI
     if (aclData->resArr == NULL)
     {
         OICFree(aclData);
-        OCPayloadDestroy((OCPayload *)secPayload);
+        OICFree(secPayload->securityData);
+        OICFree(secPayload);
         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
         return OC_STACK_NO_MEMORY;
     }
index aa5e752..4e85e79 100644 (file)
@@ -28,64 +28,73 @@ using namespace std;
 
 TEST(JustWorksOxMTest, NullParam)
 {
+
     OTMContext_t* otmCtx = NULL;
-    uint8_t *payloadRes = NULL;
-    size_t size = 0;
+    OCStackResult res = OC_STACK_ERROR;
+    char* payloadRes;
 
     //LoadSecretJustWorksCallback always returns OC_STACK_OK.
-    EXPECT_EQ(OC_STACK_OK, LoadSecretJustWorksCallback(otmCtx));
+    res = LoadSecretJustWorksCallback(otmCtx);
+    EXPECT_TRUE(OC_STACK_OK == res);
 
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CreateSecureSessionJustWorksCallback(otmCtx));
+    res = CreateSecureSessionJustWorksCallback(otmCtx);
+    EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CreateJustWorksSelectOxmPayload(otmCtx, &payloadRes, &size));
+    payloadRes = CreateJustWorksSelectOxmPayload(otmCtx);
     EXPECT_TRUE(NULL == payloadRes);
 
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CreateJustWorksOwnerTransferPayload(otmCtx, &payloadRes, &size));
+    payloadRes = CreateJustWorksOwnerTransferPayload(otmCtx);
     EXPECT_TRUE(NULL == payloadRes);
 
     OTMContext_t otmCtx2;
     otmCtx2.selectedDeviceInfo = NULL;
 
     //LoadSecretJustWorksCallback always returns OC_STACK_OK.
-    EXPECT_EQ(OC_STACK_OK, LoadSecretJustWorksCallback(&otmCtx2));
+    res = LoadSecretJustWorksCallback(&otmCtx2);
+    EXPECT_TRUE(OC_STACK_OK == res);
 
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CreateSecureSessionJustWorksCallback(&otmCtx2));
+    res = CreateSecureSessionJustWorksCallback(&otmCtx2);
+    EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CreateJustWorksSelectOxmPayload(&otmCtx2, &payloadRes, &size));
+    payloadRes = CreateJustWorksSelectOxmPayload(&otmCtx2);
     EXPECT_TRUE(NULL == payloadRes);
 
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CreateJustWorksOwnerTransferPayload(&otmCtx2, &payloadRes, &size));
+    payloadRes = CreateJustWorksOwnerTransferPayload(&otmCtx2);
     EXPECT_TRUE(NULL == payloadRes);
 }
 
 TEST(RandomPinOxMTest, NullParam)
 {
     OTMContext_t* otmCtx = NULL;
-    uint8_t *payloadRes = NULL;
-    size_t size = 0;
+    OCStackResult res = OC_STACK_ERROR;
+    char* payloadRes;
 
     //LoadSecretJustWorksCallback always returns OC_STACK_OK.
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, InputPinCodeCallback(otmCtx));
+    res = InputPinCodeCallback(otmCtx);
+    EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CreateSecureSessionRandomPinCallback(otmCtx));
+    res = CreateSecureSessionRandomPinCallback(otmCtx);
+    EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CreatePinBasedSelectOxmPayload(otmCtx, &payloadRes, &size));
+    payloadRes = CreatePinBasedSelectOxmPayload(otmCtx);
     EXPECT_TRUE(NULL == payloadRes);
 
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CreatePinBasedOwnerTransferPayload(otmCtx, &payloadRes, &size));
+    payloadRes = CreatePinBasedOwnerTransferPayload(otmCtx);
     EXPECT_TRUE(NULL == payloadRes);
 
     OTMContext_t otmCtx2;
     otmCtx2.selectedDeviceInfo = NULL;
 
     //LoadSecretJustWorksCallback always returns OC_STACK_OK.
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, InputPinCodeCallback(&otmCtx2));
+    res = InputPinCodeCallback(&otmCtx2);
+    EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CreateSecureSessionRandomPinCallback(&otmCtx2));
+    res = CreateSecureSessionRandomPinCallback(&otmCtx2);
+    EXPECT_TRUE(OC_STACK_INVALID_PARAM == res);
 
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CreatePinBasedSelectOxmPayload(&otmCtx2, &payloadRes, &size));
+    payloadRes = CreatePinBasedSelectOxmPayload(&otmCtx2);
     EXPECT_TRUE(NULL == payloadRes);
 
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CreatePinBasedOwnerTransferPayload(&otmCtx2, &payloadRes, &size));
+    payloadRes = CreatePinBasedOwnerTransferPayload(&otmCtx2);
     EXPECT_TRUE(NULL == payloadRes);
 }
index 6f46f43..e142ca7 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#ifdef WITH_ARDUINO
-#include <string.h>
-#else
-#include <strings.h>
-#endif
 #include <stdlib.h>
-
+#include <string.h>
 #include "ocstack.h"
-#include "ocserverrequest.h"
+#include "logger.h"
 #include "oic_malloc.h"
 #include "oic_string.h"
-#include "ocrandom.h"
-#include "ocpayload.h"
+#include "cJSON.h"
+#include "base64.h"
+#include "resourcemanager.h"
+#include "aclresource.h"
+#include "psinterface.h"
 #include "utlist.h"
-#include "payload_logging.h"
 #include "srmresourcestrings.h"
-#include "aclresource.h"
 #include "doxmresource.h"
-#include "resourcemanager.h"
 #include "srmutility.h"
-#include "psinterface.h"
-
-#include "security_internals.h"
+#include "ocserverrequest.h"
+#include <stdlib.h>
+#ifdef WITH_ARDUINO
+#include <string.h>
+#else
+#include <strings.h>
+#endif
 
 #define TAG  "SRM-ACL"
 #define NUMBER_OF_SEC_PROV_RSCS 4
 #define NUMBER_OF_DEFAULT_SEC_RSCS 2
 
-// CborSize is the default cbor payload size being used.
-static uint64_t CborSize = 255;
-
-static OicSecAcl_t *gAcl = NULL;
-static OCResourceHandle gAclHandle = NULL;
+OicSecAcl_t               *gAcl = NULL;
+static OCResourceHandle    gAclHandle = NULL;
 
 /**
  * This function frees OicSecAcl_t object's fields and object itself.
@@ -58,9 +54,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;
     }
 
@@ -72,9 +68,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]);
         }
@@ -82,9 +78,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]);
         }
@@ -112,376 +108,298 @@ void DeleteACLList(OicSecAcl_t* acl)
     }
 }
 
-static size_t OicSecAclSize(const OicSecAcl_t *secAcl)
+/*
+ * 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)
 {
-    if (!secAcl)
-    {
-        return 0;
-    }
-    OicSecAcl_t *acl = (OicSecAcl_t *)secAcl;
-    size_t size = 0;
-    while (acl)
-    {
-       size++;
-       acl = acl->next;
-    }
-    return size;
-}
+    cJSON *jsonRoot = NULL;
+    char *jsonStr = NULL;
 
-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;
-    OicSecAcl_t *acl = (OicSecAcl_t *)secAcl;
-    VERIFY_NON_NULL(TAG, secAcl, ERROR);
-
-    CborEncoder encoder;
-    CborEncoder oicSecAclArray;
-    if (cborLen == 0)
+    if (acl)
     {
-        cborLen = CborSize;
-    }
-    *size = 0;
-    *payload = NULL;
-
-    // Please note: This has been initialized prior to use because of VERIFY macro
+        jsonRoot = cJSON_CreateObject();
+        VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
 
-    outPayload = (uint8_t *)OICCalloc(1, cborLen);
-    VERIFY_NON_NULL(TAG, outPayload, ERROR);
-    cbor_encoder_init(&encoder, outPayload, cborLen, 0);
+        cJSON *jsonAclArray = NULL;
+        cJSON_AddItemToObject (jsonRoot, OIC_JSON_ACL_NAME, jsonAclArray = cJSON_CreateArray());
+        VERIFY_NON_NULL(TAG, jsonAclArray, ERROR);
 
-    // Create ACL Array
-    cborEncoderResult |= cbor_encoder_create_array(&encoder, &oicSecAclArray, OicSecAclSize(secAcl));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Creating ACL Array.");
-
-    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,
-            sizeof(OIC_JSON_SUBJECT_NAME) - 1);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Subject Name Tag.");
-        size_t inLen = 0;
-        if (memcmp(&(acl->subject), &WILDCARD_SUBJECT_ID, sizeof(OicUuid_t)) == 0)
+        while(acl)
         {
-            inLen = WILDCARD_SUBJECT_ID_LEN;
-        }
-        else
-        {
-            inLen = 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 = { {.ptr = NULL }, .end = 0, .added = 0, .flags = 0 };
-        cborEncoderResult |= cbor_encode_text_string(&oicSecAclMap, OIC_JSON_RESOURCES_NAME,
-            sizeof(OIC_JSON_RESOURCES_NAME) -1);
-        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++)
-        {
-            cborEncoderResult |= cbor_encode_text_string(&resources, acl->resources[i],
-                strlen(acl->resources[i]));
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Resource Name Array Value.");
+            char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};
+            uint32_t outLen = 0;
+            size_t inLen = 0;
+            B64Result b64Ret = B64_OK;
 
-        }
-        cborEncoderResult |= cbor_encoder_close_container(&oicSecAclMap, &resources);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Resource Name Array.");
-
-        // Permissions -- Mandatory
-        cborEncoderResult |= cbor_encode_text_string(&oicSecAclMap, OIC_JSON_PERMISSION_NAME,
-            sizeof(OIC_JSON_PERMISSION_NAME) -1);
-        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 -- Not Mandatory
-        if (acl->periods)
-        {
-            CborEncoder period = { {.ptr = NULL }, .end = 0, .added = 0, .flags = 0 };
-            cborEncoderResult |= cbor_encode_text_string(&oicSecAclMap, OIC_JSON_PERIODS_NAME,
-                sizeof(OIC_JSON_PERIODS_NAME) -1);
-            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++)
-            {
-                cborEncoderResult |= cbor_encode_text_string(&period, acl->periods[i],
-                    strlen(acl->periods[i]));
-                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Period Value in Array.");
+            cJSON *jsonAcl = cJSON_CreateObject();
 
+            // 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);
+            for (size_t i = 0; i < acl->resourcesLen; i++)
+            {
+                cJSON_AddItemToArray (jsonRsrcArray, cJSON_CreateString(acl->resources[i]));
             }
-            cborEncoderResult |= cbor_encoder_close_container(&oicSecAclMap, &period);
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Period Array.");
-        }
 
-        // Recurrence -- Not Mandatory
-        if (acl->recurrences)
-        {
-            CborEncoder recurrences = { {.ptr = NULL }, .end = 0, .added = 0, .flags = 0 };
-            cborEncoderResult |= cbor_encode_text_string(&oicSecAclMap, OIC_JSON_RECURRENCES_NAME,
-                sizeof(OIC_JSON_RECURRENCES_NAME) -1);
-            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++)
+            // Permissions -- Mandatory
+            cJSON_AddNumberToObject (jsonAcl, OIC_JSON_PERMISSION_NAME, acl->permission);
+
+            //Period & Recurrence -- Not Mandatory
+            if(0 != acl->prdRecrLen)
             {
-                cborEncoderResult |= cbor_encode_text_string(&recurrences, acl->recurrences[i],
-                    strlen(acl->recurrences[i]));
-                VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Recurrence Array Value.");
+                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_encoder_close_container(&oicSecAclMap, &recurrences);
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Recurrence Array");
-        }
 
-        cborEncoderResult |= cbor_encode_text_string(&oicSecAclMap, OIC_JSON_OWNERS_NAME,
-            sizeof(OIC_JSON_OWNERS_NAME) - 1);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Name.");
-        CborEncoder owners = { {.ptr = NULL }, .end = 0, .added = 0, .flags = 0 };
-        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.");
+            //Recurrence -- Not Mandatory
+            if(0 != acl->prdRecrLen && acl->recurrences)
+            {
+                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_encoder_close_container(&oicSecAclMap, &owners);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Owner 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;
 
-        cborEncoderResult |= cbor_encoder_close_container(&oicSecAclArray, &oicSecAclMap);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing ACL Map.");
+                b64Ret = b64Encode(acl->owners[i].id, sizeof(((OicUuid_t*)0)->id), base64Buff,
+                    sizeof(base64Buff), &outLen);
+                VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
 
-        acl = acl->next;
-    }
-    cborEncoderResult |= cbor_encoder_close_container(&encoder, &oicSecAclArray);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing ACL Array.");
+                cJSON_AddItemToArray (jsonOwnrArray, cJSON_CreateString(base64Buff));
+            }
 
-    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;
+            // Attach current acl node to Acl Array
+            cJSON_AddItemToArray(jsonAclArray, jsonAcl);
+            acl = acl->next;
         }
+
+        jsonStr = cJSON_PrintUnformatted(jsonRoot);
     }
 
-    if (cborEncoderResult != CborNoError)
+exit:
+    if (jsonRoot)
     {
-        OICFree(outPayload);
-        outPayload = NULL;
-        *size = 0;
-        ret = OC_STACK_ERROR;
+        cJSON_Delete(jsonRoot);
     }
-
-    return ret;
+    return 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)
+/*
+ * This internal method converts JSON ACL into binary ACL.
+ */
+OicSecAcl_t * JSONToAclBin(const char * jsonStr)
 {
-    if (NULL == cborPayload)
-    {
-        return NULL;
-    }
+    OCStackResult ret = OC_STACK_ERROR;
+    OicSecAcl_t * headAcl = NULL;
+    OicSecAcl_t * prevAcl = NULL;
+    cJSON *jsonRoot = NULL;
+    cJSON *jsonAclArray = NULL;
 
-    CborValue aclCbor = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
-    CborParser parser = { .end = NULL, .flags = 0 };
-    CborError cborFindResult = CborNoError;
-    cbor_parser_init(cborPayload, size, 0, &parser, &aclCbor);
+    VERIFY_NON_NULL(TAG, jsonStr, ERROR);
 
-    OicSecAcl_t *headAcl = NULL;
+    jsonRoot = cJSON_Parse(jsonStr);
+    VERIFY_NON_NULL(TAG, jsonRoot, 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.");
+    jsonAclArray = cJSON_GetObjectItem(jsonRoot, OIC_JSON_ACL_NAME);
+    VERIFY_NON_NULL(TAG, jsonAclArray, ERROR);
 
-    while (cbor_value_is_valid(&aclArray))
+    if (cJSON_Array == jsonAclArray->type)
     {
-        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);
+        int numAcl = cJSON_GetArraySize(jsonAclArray);
+        int idx = 0;
 
-        while (cbor_value_is_valid(&aclMap))
+        VERIFY_SUCCESS(TAG, numAcl > 0, INFO);
+        do
         {
-            char* name = NULL;
-            size_t len = 0;
-            CborType type = cbor_value_get_type(&aclMap);
-            if (type == CborTextStringType)
+            cJSON *jsonAcl = cJSON_GetArrayItem(jsonAclArray, idx);
+            VERIFY_NON_NULL(TAG, jsonAcl, ERROR);
+
+            OicSecAcl_t *acl = (OicSecAcl_t*)OICCalloc(1, sizeof(OicSecAcl_t));
+            VERIFY_NON_NULL(TAG, acl, ERROR);
+
+            headAcl = (headAcl) ? headAcl : acl;
+            if (prevAcl)
             {
-                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.");
+                prevAcl->next = acl;
             }
-            if (name)
-            {
-                // Subject -- Mandatory
-                if (strcmp(name, OIC_JSON_SUBJECT_NAME)  == 0)
-                {
-                    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);
-                }
 
-                // Resources -- Mandatory
-                if (strcmp(name, OIC_JSON_RESOURCES_NAME) == 0)
+            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
+            {
+                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)
                 {
-                    CborValue resources = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
-                    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->periods = (char**)OICCalloc(acl->prdRecrLen,
+                                    sizeof(char*));
+                    VERIFY_NON_NULL(TAG, acl->periods, ERROR);
 
-                    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))
+                    cJSON *jsonPeriod = NULL;
+                    for(size_t i = 0; i < acl->prdRecrLen; i++)
                     {
-                        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.");
+                        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);
                     }
                 }
+            }
 
-                // 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.");
-                }
-
-                // Period -- Not mandatory
-                if (strcmp(name, OIC_JSON_PERIODS_NAME) == 0)
-                {
-                    CborValue period = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
-                    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.");
-                    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
+            cJSON *jsonRecurObj = cJSON_GetObjectItem(jsonAcl,
+                                        OIC_JSON_RECURRENCES_NAME);
+            if(jsonRecurObj)
+            {
+                VERIFY_SUCCESS(TAG, cJSON_Array == jsonRecurObj->type,
+                               ERROR);
 
-                // Recurrence -- Not mandatory
-                if (strcmp(name, OIC_JSON_RECURRENCES_NAME) == 0)
+                if(acl->prdRecrLen > 0)
                 {
-                    CborValue recurrences = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
-                    cborFindResult = cbor_value_enter_container(&aclMap, &recurrences);
-                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Adding Recurrence Array.");
-                    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.");
-                    }
-                }
+                    acl->recurrences = (char**)OICCalloc(acl->prdRecrLen,
+                                             sizeof(char*));
+                    VERIFY_NON_NULL(TAG, acl->recurrences, ERROR);
 
-                // Owners -- Mandatory
-                if (strcmp(name, OIC_JSON_OWNERS_NAME) == 0)
-                {
-                    CborValue owners = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
-                    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))
+                    cJSON *jsonRecur = NULL;
+                    for(size_t i = 0; i < acl->prdRecrLen; i++)
                     {
-                        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);
+                        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);
                     }
                 }
             }
-            if (type != CborMapType && cbor_value_is_valid(&aclMap))
-            {
-                cborFindResult = cbor_value_advance(&aclMap);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing the Array.");
-            }
-        }
 
-        acl->next = NULL;
-        if (headAcl == NULL)
-        {
-            headAcl = acl;
-        }
-        else
-        {
-            OicSecAcl_t *temp = headAcl;
-            while (temp->next)
+            // 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
             {
-                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.");
-        }
+                cJSON *jsonOwnr = cJSON_GetArrayItem(jsonObj, idxx);
+                VERIFY_NON_NULL(TAG, jsonOwnr, ERROR);
+                VERIFY_SUCCESS(TAG, cJSON_String == jsonOwnr->type, ERROR);
+
+                outLen = 0;
+                b64Ret = b64Decode(jsonOwnr->valuestring, strlen(jsonOwnr->valuestring), base64Buff,
+                            sizeof(base64Buff), &outLen);
+
+                VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(acl->owners[idxx].id)),
+                                    ERROR);
+                memcpy(acl->owners[idxx].id, base64Buff, outLen);
+            } while ( ++idxx < acl->ownersLen);
+
+            prevAcl = acl;
+        } while( ++idx < numAcl);
     }
 
+    ret = OC_STACK_OK;
+
 exit:
-    if (cborFindResult != CborNoError)
+    cJSON_Delete(jsonRoot);
+    if (OC_STACK_OK != ret)
     {
         DeleteACLList(headAcl);
         headAcl = NULL;
@@ -489,18 +407,37 @@ 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 of the ACE
- * @param resource of the ACE
+ * @param subject  - subject of the ACE
+ * @param resource - resource of the ACE
  *
  * @return
- *     ::OC_STACK_RESOURCE_DELETED on success
- *     ::OC_STACK_NO_RESOURCE on failure to find the appropriate ACE
- *     ::OC_STACK_INVALID_PARAM on invalid parameter
+ *     OC_STACK_RESOURCE_DELETED on success
+ *     OC_STACK_NO_RESOURC 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");
 
@@ -509,18 +446,18 @@ static OCStackResult RemoveACE(const OicUuid_t * subject, const char * resource)
     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);
@@ -536,9 +473,9 @@ static OCStackResult RemoveACE(const OicUuid_t * subject, const char * resource)
         //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);
@@ -547,24 +484,24 @@ static OCStackResult RemoveACE(const OicUuid_t * subject, const char * resource)
                 }
                 else
                 {
-                    size_t resPos = -1;
+                    int 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 <= (int) resPos)
+                    if((0 <= resPos))
                     {
                         OICFree(acl->resources[resPos]);
                         acl->resources[resPos] = NULL;
                         acl->resourcesLen -= 1;
-                        for (i = resPos; i < acl->resourcesLen; i++)
+                        for(i = (size_t)resPos; i < acl->resourcesLen; i++)
                         {
-                            acl->resources[i] = acl->resources[i + 1];
+                            acl->resources[i] = acl->resources[i+1];
                         }
                         deleteFlag = true;
                         break;
@@ -574,31 +511,17 @@ static OCStackResult RemoveACE(const OicUuid_t * subject, const char * resource)
         }
     }
 
-    if (deleteFlag)
+    if(deleteFlag)
     {
-        // In case of unit test do not update persistant storage.
-        if (memcmp(subject->id, &WILDCARD_SUBJECT_B64_ID, sizeof(subject->id)) == 0)
+        if(UpdatePersistentStorage(gAcl))
         {
             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.
  *
@@ -609,25 +532,33 @@ static OCStackResult RemoveACE(const OicUuid_t * subject, const char * resource)
  */
 static bool GetSubjectFromQueryString(const char *query, OicUuid_t *subject)
 {
-    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_SUBJECT_NAME, parseIter.attrLen) == 0)
+        if(strncasecmp((char *)parseIter.attrPos, OIC_JSON_SUBJECT_NAME, parseIter.attrLen) == 0)
         {
             VERIFY_SUCCESS(TAG, 0 != parseIter.valLen, ERROR);
-            memcpy(subject->id, parseIter.valPos, parseIter.valLen);
+            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);
+
             return true;
         }
     }
 
 exit:
-    return false;
+   return false;
 }
 
-/**
+/*
  * This method parses the query string received for REST requests and
  * retrieves the 'resource' field.
  *
@@ -639,17 +570,16 @@ 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;
         }
@@ -659,26 +589,28 @@ exit:
    return false;
 }
 
-static OCEntityHandlerResult HandleACLGetRequest(const OCEntityHandlerRequest *ehRequest)
+
+
+static OCEntityHandlerResult HandleACLGetRequest (const OCEntityHandlerRequest * ehRequest)
 {
-    OIC_LOG(INFO, TAG, "HandleACLGetRequest processing the request");
-    uint8_t* payload = NULL;
-    size_t size = 0;
-    OCEntityHandlerResult ehRet;
+    OCEntityHandlerResult ehRet = OC_EH_ERROR;
+    char* jsonStr = NULL;
 
     // 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));
 
@@ -687,7 +619,7 @@ static OCEntityHandlerResult HandleACLGetRequest(const OCEntityHandlerRequest *e
          * 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
@@ -695,121 +627,104 @@ static OCEntityHandlerResult HandleACLGetRequest(const OCEntityHandlerRequest *e
              */
             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 CBOR format for transmission
-                        if (OC_STACK_OK != AclToCBORPayload(currentAce, &payload, &size))
-                        {
-                            ehRet = OC_EH_ERROR;
-                        }
+                        // Convert ACL data into JSON for transmission
+                        jsonStr = BinToAclJSON(currentAce);
                         goto exit;
                     }
                 }
             }
             else
             {
-                // Convert ACL data into CBOR format for transmission
-                if (OC_STACK_OK != AclToCBORPayload(currentAce, &payload, &size))
-                {
-                    ehRet = OC_EH_ERROR;
-                }
+                // Convert ACL data into JSON for transmission
+                jsonStr = BinToAclJSON(currentAce);
                 goto exit;
             }
         }
     }
     else
     {
-        // Convert ACL data into CBOR format for transmission.
-        if (OC_STACK_OK != AclToCBORPayload(gAcl, &payload, &size))
-        {
-            ehRet = OC_EH_ERROR;
-        }
+        // Convert ACL data into JSON for transmission
+        jsonStr = BinToAclJSON(gAcl);
     }
+
 exit:
-    // A device should always have a default acl. Therefore, payload should never be NULL.
-    ehRet = (payload ? OC_EH_OK : OC_EH_ERROR);
+    ehRet = (jsonStr ? OC_EH_OK : OC_EH_ERROR);
 
     // Send response payload to request originator
-    SendSRMCBORResponse(ehRequest, ehRet, payload);
+    SendSRMResponse(ehRequest, ehRet, jsonStr);
 
-    OIC_LOG_V(DEBUG, TAG, "%s RetVal %d", __func__, ehRet);
+    OICFree(jsonStr);
+
+    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 CBOR into ACL data and update to SVR buffers. This will also validate the ACL data received.
-    uint8_t *payload = ((OCSecurityPayload *) ehRequest->payload)->securityData1;;
-    if (payload)
+    // Convert JSON ACL data into binary. This will also validate the ACL data received.
+    OicSecAcl_t* newAcl = JSONToAclBin(((OCSecurityPayload*)ehRequest->payload)->securityData);
+
+    if (newAcl)
     {
-        OicSecAcl_t *newAcl = CBORPayloadToAcl(payload, CborSize);
-        if (newAcl)
+        // Append the new ACL to existing ACL
+        LL_APPEND(gAcl, newAcl);
+
+        if(UpdatePersistentStorage(gAcl))
         {
-            // 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;
-                    }
-                }
-            }
+            ehRet = OC_EH_RESOURCE_CREATED;
         }
     }
 
     // Send payload to request originator
-    SendSRMCBORResponse(ehRequest, ehRet, NULL);
+    SendSRMResponse(ehRequest, ehRet, NULL);
 
-    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
-    SendSRMCBORResponse(ehRequest, ehRet, NULL);
+    SendSRMResponse(ehRequest, ehRet, NULL);
 
     return ehRet;
 }
 
-OCEntityHandlerResult ACLEntityHandler(OCEntityHandlerFlag flag, OCEntityHandlerRequest * ehRequest,
-        void* callbackParameter)
+/*
+ * 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)
 {
     OIC_LOG(DEBUG, TAG, "Received request ACLEntityHandler");
     (void)callbackParameter;
@@ -823,7 +738,7 @@ OCEntityHandlerResult ACLEntityHandler(OCEntityHandlerFlag flag, OCEntityHandler
     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:
@@ -840,17 +755,17 @@ OCEntityHandlerResult ACLEntityHandler(OCEntityHandlerFlag flag, OCEntityHandler
 
             default:
                 ehRet = OC_EH_ERROR;
-                SendSRMCBORResponse(ehRequest, ehRet, NULL);
+                SendSRMResponse(ehRequest, ehRet, NULL);
         }
     }
 
     return ehRet;
 }
 
-/**
+/*
  * This internal method is used to create '/oic/sec/acl' resource.
  */
-static OCStackResult CreateACLResource()
+OCStackResult CreateACLResource()
 {
     OCStackResult ret;
 
@@ -864,24 +779,23 @@ static 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 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)
+/*
+ * 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)
 {
     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
@@ -908,22 +822,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]);
     }
@@ -934,18 +848,11 @@ OCStackResult GetDefaultACL(OicSecAcl_t** defaultAcl)
     acl->recurrences = NULL;
 
     // Device ID is the owner of this default ACL
-    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);
-    }
+    ret = GetDoxmDeviceID( &ownerId);
+    VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, 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));
 
@@ -965,29 +872,30 @@ 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;
 
-    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)
-    {
-        OIC_LOG(DEBUG, TAG, "ReadSVDataFromPS failed");
-    }
-    if (data)
+    // Read ACL resource from PS
+    char* jsonSVRDatabase = GetSVRDatabase();
+
+    if (jsonSVRDatabase)
     {
-        // Read ACL resource from PS
-        gAcl = CBORPayloadToAcl(data, size);
+        // Convert JSON ACL into binary format
+        gAcl = JSONToAclBin(jsonSVRDatabase);
+        OICFree(jsonSVRDatabase);
     }
     /*
      * 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 (!gAcl)
+    if (!jsonSVRDatabase || !gAcl)
     {
         GetDefaultACL(&gAcl);
         // TODO Needs to update persistent storage
@@ -1005,25 +913,37 @@ exit:
     return ret;
 }
 
-OCStackResult DeInitACLResource()
+/**
+ * Perform cleanup for ACL resources.
+ *
+ * @retval  none
+ */
+void DeInitACLResource()
 {
-    OCStackResult ret =  OCDeleteResource(gAclHandle);
+    OCDeleteResource(gAclHandle);
     gAclHandle = NULL;
 
-    if (gAcl)
-    {
-        DeleteACLList(gAcl);
-        gAcl = NULL;
-    }
-    return ret;
+    DeleteACLList(gAcl);
+    gAcl = NULL;
 }
 
+/**
+ * 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;
     }
@@ -1067,36 +987,31 @@ const OicSecAcl_t* GetACLResourceData(const OicUuid_t* subjectId, OicSecAcl_t **
     return NULL;
 }
 
-OCStackResult InstallNewACL(const uint8_t *cborPayload, const size_t size)
+
+OCStackResult InstallNewACL(const char* newJsonStr)
 {
     OCStackResult ret = OC_STACK_ERROR;
 
-    // Convert CBOR format to ACL data. This will also validate the ACL data received.
-    OicSecAcl_t* newAcl = CBORPayloadToAcl(cborPayload, size);
+    // Convert JSON ACL data into binary. This will also validate the ACL data received.
+    OicSecAcl_t* newAcl = JSONToAclBin(newJsonStr);
 
     if (newAcl)
     {
         // Append the new ACL to existing ACL
         LL_APPEND(gAcl, newAcl);
 
-        // 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)
-        {
-            ret = OC_STACK_OK;
-        }
-        else
+        // Convert ACL data into JSON for update to persistent storage
+        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);
+
+            if (jsonAcl)
             {
-                if (UpdateSecureResourceInPS(OIC_JSON_ACL_NAME, payload, size) == OC_STACK_OK)
-                {
-                    ret = OC_STACK_OK;
-                }
-                OICFree(payload);
+                ret = UpdateSVRDatabase(OIC_JSON_ACL_NAME, jsonAcl);
             }
+            cJSON_Delete(jsonAcl);
         }
     }
 
@@ -1106,7 +1021,7 @@ OCStackResult InstallNewACL(const uint8_t *cborPayload, const size_t size)
 /**
  * This function generates default ACL for security resource in case of owned status.
  *
- * @return Default ACL for security resource.
+ * @retval Default ACL for security resource.
  */
 static OicSecAcl_t* GetSecDefaultACL()
 {
@@ -1214,20 +1129,27 @@ OCStackResult UpdateDefaultSecProvACL()
              *      resources :  '/oic/sec/doxm', '/oic/sec/pstat'
              *      permission : READ
              */
-            OicSecAcl_t *newDefaultAcl = GetSecDefaultACL();
-            if (newDefaultAcl)
+            OicSecAcl_tnewDefaultAcl = GetSecDefaultACL();
+            if(newDefaultAcl)
             {
                 LL_APPEND(gAcl, newDefaultAcl);
 
-                size_t size = 0;
-                uint8_t *payload = NULL;
-                if (OC_STACK_OK == AclToCBORPayload(gAcl, &payload, &size))
+                char *jsonStr = BinToAclJSON(gAcl);
+                if(jsonStr)
                 {
-                    if (UpdateSecureResourceInPS(OIC_JSON_ACL_NAME, payload, size) == OC_STACK_OK)
+                    cJSON *jsonAcl = cJSON_Parse(jsonStr);
+                    OICFree(jsonStr);
+
+                    //Update SVR DB
+                    if (jsonAcl)
                     {
-                        ret = OC_STACK_OK;
+                        ret = UpdateSVRDatabase(OIC_JSON_ACL_NAME, jsonAcl);
+                        if(OC_STACK_OK != ret)
+                        {
+                            OIC_LOG(WARNING, TAG, "Failed to update SVR DB");
+                        }
                     }
-                    OICFree(payload);
+                    cJSON_Delete(jsonAcl);
                 }
             }
         }
index 3671549..63aef6a 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
+
 #include <stdlib.h>
 #include <string.h>
+#include "ocstack.h"
+#include "logger.h"
 #include "oic_malloc.h"
-#include "ocpayload.h"
-#include "payload_logging.h"
-#include "psinterface.h"
+#include "oic_string.h"
+#include "cJSON.h"
+#include "base64.h"
 #include "resourcemanager.h"
+#include "psinterface.h"
 #include "utlist.h"
 #include "srmresourcestrings.h"
-#include "srmutility.h"
 #include "amaclresource.h"
+#include "srmutility.h"
+#include <stdlib.h>
+#include <string.h>
 
 #define TAG  "SRM-AMACL"
 
-/** 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;
+OicSecAmacl_t *gAmacl = NULL;
 static OCResourceHandle gAmaclHandle = NULL;
 
 void DeleteAmaclList(OicSecAmacl_t* amacl)
@@ -73,318 +69,193 @@ void DeleteAmaclList(OicSecAmacl_t* amacl)
     }
 }
 
-static size_t OicSecAmaclCount(const OicSecAmacl_t *secAmacl)
-{
-    size_t size = 0;
-    for (const OicSecAmacl_t *amacl = secAmacl; amacl; amacl = amacl->next)
-    {
-        size++;
-    }
-    return size;
-}
-
-OCStackResult AmaclToCBORPayload(const OicSecAmacl_t *amaclS, uint8_t **cborPayload,
-                                 size_t *cborSize)
+/*
+ * 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)
 {
-    if (NULL == amaclS || NULL == cborPayload || NULL != *cborPayload || NULL == cborSize)
-    {
-        return OC_STACK_INVALID_PARAM;
-    }
+    cJSON *jsonRoot = NULL;
+    char *jsonStr = NULL;
 
-    OCStackResult ret = OC_STACK_ERROR;
-    size_t cborLen = *cborSize;
-    if (0 == cborLen)
+    if (amacl)
     {
-        cborLen = CBOR_SIZE;
-    }
-
-    *cborSize = 0;
-    *cborPayload = NULL;
+        jsonRoot = cJSON_CreateObject();
+        VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
 
-    CborEncoder encoder = { {.ptr = NULL }, .end = 0 };
-    CborEncoder amaclArray = { {.ptr = NULL }, .end = 0 };
-    CborError cborEncoderResult = CborNoError;
+        cJSON *jsonAmaclArray = NULL;
+        cJSON_AddItemToObject (jsonRoot, OIC_JSON_AMACL_NAME, jsonAmaclArray = cJSON_CreateArray());
+        VERIFY_NON_NULL(TAG, jsonAmaclArray, ERROR);
 
-    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);
-
-    // Create AMACL Array
-    cborEncoderResult = cbor_encoder_create_array(&encoder, &amaclArray, OicSecAmaclCount(amacl));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding AMACL Array.");
+        while(amacl)
+        {
+            char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};
+            uint32_t outLen = 0;
+            B64Result b64Ret = B64_OK;
 
-    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.");
+            cJSON *jsonAmacl = cJSON_CreateObject();
 
-        // 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++)
+            // 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++)
             {
-                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(jsonRsrcArray, cJSON_CreateString(amacl->resources[i]));
             }
-            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++)
+
+            // 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++)
             {
-                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.");
+                outLen = 0;
+
+                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));
             }
-            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++)
+
+            // 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++)
             {
-                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.");
+                outLen = 0;
+
+                b64Ret = b64Encode(amacl->owners[i].id, sizeof(((OicUuid_t*) 0)->id), base64Buff,
+                        sizeof(base64Buff), &outLen);
+                VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
+
+                cJSON_AddItemToArray(jsonOwnrArray, cJSON_CreateString(base64Buff));
             }
-            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.");
 
-        amacl = amacl->next;
-    }
-    cborEncoderResult = cbor_encoder_close_container(&encoder, &amaclArray);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Amacl Array.");
+            // Attach current amacl node to Amacl Array
+            cJSON_AddItemToArray(jsonAmaclArray, jsonAmacl);
+            amacl = amacl->next;
+        }
 
-    if (CborNoError == cborEncoderResult)
-    {
-        *cborPayload = outPayload;
-        *cborSize = encoder.ptr - outPayload;
-        ret = OC_STACK_OK;
+        jsonStr = cJSON_PrintUnformatted(jsonRoot);
     }
 
 exit:
-    if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
+    if (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 = AmaclToCBORPayload(amaclS, cborPayload, &cborLen);
-       if (OC_STACK_OK == ret)
-       {
-           *cborSize = cborLen;
-           ret = OC_STACK_OK;
-       }
+        cJSON_Delete(jsonRoot);
     }
-
-    if (CborNoError != cborEncoderResult)
-    {
-       OICFree(outPayload);
-       outPayload = NULL;
-       *cborSize = 0;
-       *cborPayload = NULL;
-       ret = OC_STACK_ERROR;
-    }
-
-    return ret;
+    return jsonStr;
 }
 
-OCStackResult CBORPayloadToAmacl(const uint8_t *cborPayload, size_t size,
-                                 OicSecAmacl_t **secAmacl)
-{
-    if (NULL == cborPayload || NULL == secAmacl || NULL != *secAmacl)
-    {
-        return OC_STACK_INVALID_PARAM;
-    }
 
-    *secAmacl = NULL;
 
+
+/*
+ * This internal method converts JSON AMACL into binary AMACL.
+ */
+OicSecAmacl_t * JSONToAmaclBin(const char * jsonStr)
+{
     OCStackResult ret = OC_STACK_ERROR;
+    OicSecAmacl_t * headAmacl = NULL;
+    OicSecAmacl_t * prevAmacl = NULL;
+    cJSON *jsonRoot = NULL;
+    cJSON *jsonAmaclArray = NULL;
 
-    CborValue amaclCbor = { .parser = NULL };
-    CborParser parser = { .end = NULL };
-    CborError cborFindResult = CborNoError;
-    int cborLen = size;
-    if (0 == size)
-    {
-        cborLen = CBOR_SIZE;
-    }
-    cbor_parser_init(cborPayload, cborLen, 0, &parser, &amaclCbor);
+    VERIFY_NON_NULL(TAG, jsonStr, ERROR);
 
-    OicSecAmacl_t *headAmacl = NULL;
+    jsonRoot = cJSON_Parse(jsonStr);
+    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
 
-    CborValue amaclArray = { .parser = NULL };
-    cborFindResult = cbor_value_enter_container(&amaclCbor, &amaclArray);
-    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
+    jsonAmaclArray = cJSON_GetObjectItem(jsonRoot, OIC_JSON_AMACL_NAME);
+    VERIFY_NON_NULL(TAG, jsonAmaclArray, INFO);
 
-    while (cbor_value_is_valid(&amaclArray))
+    if (cJSON_Array == jsonAmaclArray->type)
     {
-        CborValue amaclMap = { .parser = NULL };
-        cborFindResult = cbor_value_enter_container(&amaclArray, &amaclMap);
-        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
+        int numAmacl = cJSON_GetArraySize(jsonAmaclArray);
+        int idx = 0;
 
-        OicSecAmacl_t *amacl = (OicSecAmacl_t *) OICCalloc(1, sizeof(*amacl));
-        VERIFY_NON_NULL(TAG, amacl, ERROR);
-
-        while (cbor_value_is_valid(&amaclMap))
+        VERIFY_SUCCESS(TAG, numAmacl > 0, INFO);
+        do
         {
-            char *name = NULL;
-            size_t len = 0;
-            cborFindResult = cbor_value_dup_text_string(&amaclMap, &name, &len, NULL);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
-            cborFindResult = cbor_value_advance(&amaclMap);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
+            cJSON *jsonAmacl = cJSON_GetArrayItem(jsonAmaclArray, idx);
+            VERIFY_NON_NULL(TAG, jsonAmacl, ERROR);
 
-            CborType type = cbor_value_get_type(&amaclMap);
+            OicSecAmacl_t *amacl = (OicSecAmacl_t*)OICCalloc(1, sizeof(OicSecAmacl_t));
+            VERIFY_NON_NULL(TAG, amacl, ERROR);
 
-            // Resources -- Mandatory
-            if (0 == strcmp(OIC_JSON_RESOURCES_NAME, name))
+            headAmacl = (headAmacl) ? headAmacl : amacl;
+            if (prevAmacl)
             {
-                CborValue resources = { .parser = NULL  };
-                cborFindResult = cbor_value_get_array_length(&amaclMap, &amacl->resourcesLen);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
-
-                cborFindResult = cbor_value_enter_container(&amaclMap, &resources);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
-
-                amacl->resources = (char **) OICMalloc(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, ERROR);
-                    cborFindResult = cbor_value_advance(&resources);
-                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
-                }
+                prevAmacl->next = amacl;
             }
 
-            // Amss -- Mandatory
-            if (0 == strcmp(OIC_JSON_AMSS_NAME, name))
+            size_t jsonObjLen = 0;
+            cJSON *jsonObj = NULL;
+
+            // Resources -- Mandatory
+            jsonObj = cJSON_GetObjectItem(jsonAmacl, OIC_JSON_RESOURCES_NAME);
+            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+            VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
+
+            amacl->resourcesLen = (size_t)cJSON_GetArraySize(jsonObj);
+            VERIFY_SUCCESS(TAG, amacl->resourcesLen > 0, ERROR);
+            amacl->resources = (char**)OICCalloc(amacl->resourcesLen, sizeof(char*));
+            VERIFY_NON_NULL(TAG, (amacl->resources), ERROR);
+
+            size_t idxx = 0;
+            do
             {
-                CborValue amss = { .parser = NULL };
-                cborFindResult = cbor_value_get_array_length(&amaclMap, &amacl->amssLen);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
-                cborFindResult = cbor_value_enter_container(&amaclMap, &amss);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
-                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, ERROR);
-                    cborFindResult = cbor_value_advance(&amss);
-                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
-                    memcpy(amacl->amss[i].id, amssId, len);
-                    OICFree(amssId);
-                }
-            }
+                cJSON *jsonRsrc = cJSON_GetArrayItem(jsonObj, idxx);
+                VERIFY_NON_NULL(TAG, jsonRsrc, ERROR);
+
+                jsonObjLen = strlen(jsonRsrc->valuestring) + 1;
+                amacl->resources[idxx] = (char*)OICMalloc(jsonObjLen);
+                VERIFY_NON_NULL(TAG, (amacl->resources[idxx]), ERROR);
+                OICStrcpy(amacl->resources[idxx], jsonObjLen, jsonRsrc->valuestring);
+            } while ( ++idxx < amacl->resourcesLen);
+
+            // Amss -- Mandatory
+            VERIFY_SUCCESS( TAG, OC_STACK_OK == AddUuidArray(jsonAmacl, OIC_JSON_AMSS_NAME,
+                               &(amacl->amssLen), &(amacl->amss)), ERROR);
 
             // Owners -- Mandatory
-            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, ERROR);
-                cborFindResult = cbor_value_enter_container(&amaclMap, &owners);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
-                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, ERROR);
-                    cborFindResult = cbor_value_advance(&owners);
-                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, ERROR);
-                    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, ERROR);
-            }
-            OICFree(name);
-        }
+            VERIFY_SUCCESS( TAG, OC_STACK_OK == AddUuidArray(jsonAmacl, OIC_JSON_OWNERS_NAME,
+                               &(amacl->ownersLen), &(amacl->owners)), ERROR);
 
-        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, ERROR);
-        }
+            prevAmacl = amacl;
+        } while( ++idx < numAmacl);
     }
-    *secAmacl = headAmacl;
+
     ret = OC_STACK_OK;
+
 exit:
-    if (CborNoError != cborFindResult)
+    cJSON_Delete(jsonRoot);
+    if (OC_STACK_OK != ret)
     {
         DeleteAmaclList(headAmacl);
         headAmacl = NULL;
-        ret = OC_STACK_ERROR;
     }
-    return ret;
+    return headAmacl;
 }
 
 static OCEntityHandlerResult HandleAmaclGetRequest (const OCEntityHandlerRequest * ehRequest)
 {
     // Convert Amacl data into JSON for transmission
-    size_t size = 0;
-    uint8_t *cborPayload = NULL;
-    OCStackResult res = AmaclToCBORPayload(gAmacl, &cborPayload, &size);
+    char* jsonStr = BinToAmaclJSON(gAmacl);
 
-    OCEntityHandlerResult ehRet = (res == OC_STACK_OK) ? OC_EH_OK : OC_EH_ERROR;
+    OCEntityHandlerResult ehRet = (jsonStr ? OC_EH_OK : OC_EH_ERROR);
 
     // Send response payload to request originator
-    SendSRMCBORResponse(ehRequest, ehRet, cborPayload);
+    SendSRMResponse(ehRequest, ehRet, jsonStr);
 
-    OICFree(cborPayload);
+    OICFree(jsonStr);
 
     OIC_LOG_V (DEBUG, TAG, "%s RetVal %d", __func__ , ehRet);
     return ehRet;
@@ -394,44 +265,44 @@ static OCEntityHandlerResult HandleAmaclPostRequest (const OCEntityHandlerReques
 {
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
 
-    // Convert CBOR Amacl data into binary. This will also validate the Amacl data received.
-    uint8_t *payload = ((OCSecurityPayload *) ehRequest->payload)->securityData1;;
-    if (payload)
+    // Convert JSON Amacl data into binary. This will also validate the Amacl data received.
+    OicSecAmacl_t* newAmacl = JSONToAmaclBin(((OCSecurityPayload*)ehRequest->payload)->securityData);
+
+    if (newAmacl)
     {
-        OicSecAmacl_t *newAmacl = NULL;
-        OCStackResult res = CBORPayloadToAmacl(payload, CBOR_SIZE, &newAmacl);
-        if (newAmacl && OC_STACK_OK == res)
+        // 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)
         {
-            // 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)))
+            cJSON *jsonAmacl = cJSON_Parse(jsonStr);
+            OICFree(jsonStr);
+
+            if ((jsonAmacl) &&
+                (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_AMACL_NAME, jsonAmacl)))
             {
                 ehRet = OC_EH_RESOURCE_CREATED;
             }
-            OICFree(cborPayload);
+            cJSON_Delete(jsonAmacl);
         }
-        OICFree(payload);
     }
 
     // Send payload to request originator
-    SendSRMCBORResponse(ehRequest, ehRet, NULL);
+    SendSRMResponse(ehRequest, ehRet, NULL);
 
-    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.
  */
-static OCEntityHandlerResult AmaclEntityHandler (OCEntityHandlerFlag flag,
-                                                 OCEntityHandlerRequest * ehRequest,
-                                                 void* callbackParameter)
+OCEntityHandlerResult AmaclEntityHandler (OCEntityHandlerFlag flag,
+                                          OCEntityHandlerRequest * ehRequest,
+                                          void* callbackParameter)
 {
     (void) callbackParameter;
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
@@ -463,18 +334,20 @@ static OCEntityHandlerResult AmaclEntityHandler (OCEntityHandlerFlag flag,
     return ehRet;
 }
 
-/**
+/*
  * This internal method is used to create '/oic/sec/amacl' resource.
  */
-static OCStackResult CreateAmaclResource()
+OCStackResult CreateAmaclResource()
 {
-    OCStackResult ret = OCCreateResource(&gAmaclHandle,
-                                         OIC_RSRC_TYPE_SEC_AMACL,
-                                         OIC_MI_DEF,
-                                         OIC_RSRC_AMACL_URI,
-                                         AmaclEntityHandler,
-                                         NULL,
-                                         OC_OBSERVABLE);
+    OCStackResult ret;
+
+    ret = OCCreateResource(&gAmaclHandle,
+                           OIC_RSRC_TYPE_SEC_AMACL,
+                           OIC_MI_DEF,
+                           OIC_RSRC_AMACL_URI,
+                           AmaclEntityHandler,
+                           NULL,
+                           OC_OBSERVABLE);
 
     if (OC_STACK_OK != ret)
     {
@@ -484,24 +357,23 @@ static 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;
 
-    uint8_t *data = NULL;
-    size_t size = 0;
-    ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_AMACL_NAME, &data, &size);
+    // Read Amacl resource from PS
+    char* jsonSVRDatabase = GetSVRDatabase();
 
-    // If database read failed
-    if (OC_STACK_OK != ret)
-    {
-        OIC_LOG(DEBUG, TAG, "ReadSVDataFromPS failed");
-    }
-    if (data)
+    if (jsonSVRDatabase)
     {
-        // Read AMACL resource from PS
-        ret = CBORPayloadToAmacl(data, size, &gAmacl);
-        OICFree(data);
+        // Convert JSON Amacl into binary format
+        gAmacl = JSONToAmaclBin(jsonSVRDatabase);
+        OICFree(jsonSVRDatabase);
     }
 
     // Instantiate 'oic/sec/amacl' resource
@@ -514,6 +386,11 @@ OCStackResult InitAmaclResource()
     return ret;
 }
 
+/**
+ * Perform cleanup for Amacl resources.
+ *
+ * @retval  none
+ */
 void DeInitAmaclResource()
 {
     OCDeleteResource(gAmaclHandle);
@@ -523,6 +400,7 @@ void DeInitAmaclResource()
     gAmacl = NULL;
 }
 
+
 OCStackResult AmaclGetAmsDeviceId(const char *resource, OicUuid_t *amsDeviceId)
 {
     OicSecAmacl_t *amacl = NULL;
@@ -534,7 +412,7 @@ OCStackResult AmaclGetAmsDeviceId(const char *resource, OicUuid_t *amsDeviceId)
     {
         for(size_t i = 0; i < amacl->resourcesLen; i++)
         {
-            if (0 == strncmp((amacl->resources[i]), resource, strlen(amacl->resources[i])))
+            if (strncmp((amacl->resources[i]), resource, strlen(amacl->resources[i])) == 0)
             {
                 //Returning the ID of the first AMS service for the resource
                 memcpy(amsDeviceId, &amacl->amss[0], sizeof(*amsDeviceId));
index ed6d9e2..c9be755 100644 (file)
@@ -18,7 +18,6 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#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);
@@ -50,6 +51,7 @@ 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");
@@ -87,6 +89,7 @@ exit:
     return ret;
 }
 
+
 static OCStackApplicationResult AmsMgrDiscoveryCallback(void *ctx, OCDoHandle handle,
                          OCClientResponse * clientResponse)
 {
@@ -111,16 +114,15 @@ 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)->securityData1);
-    uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData1;
+          ((OCSecurityPayload*)clientResponse->payload)->securityData);
+    doxm = JSONToDoxmBin(((OCSecurityPayload*)clientResponse->payload)->securityData);
 
     //As doxm is NULL amsmgr can't test if response from trusted AMS service
     //so keep the transaction.
-    if (OC_STACK_OK == CBORPayloadToDoxm(payload, 0, &doxm))
+    if(NULL == doxm)
     {
-        OIC_LOG_V(ERROR, TAG, "%s : Unable to convert CBOR to Binary",__func__);
+        OIC_LOG_V(ERROR, TAG, "%s : Unable to convert JSON to Binary",__func__);
         return OC_STACK_KEEP_TRANSACTION;
     }
 
@@ -136,7 +138,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;
@@ -148,6 +150,7 @@ static OCStackApplicationResult AmsMgrDiscoveryCallback(void *ctx, OCDoHandle ha
     return OC_STACK_DELETE_TRANSACTION;
 }
 
+
 OCStackResult SendUnicastSecurePortDiscovery(PEContext_t *context,OCDevAddr *devAddr,
                                       OCConnectivityType connType)
 {
@@ -195,7 +198,7 @@ static OCStackApplicationResult SecurePortDiscoveryCallback(void *ctx, OCDoHandl
         return OC_STACK_DELETE_TRANSACTION;
     }
 
-    OCResourcePayload *resPayload = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
+    OCResourcePayloadresPayload = ((OCDiscoveryPayload*)clientResponse->payload)->resources;
 
     //Verifying if the ID of the sender is an AMS service that this device trusts.
     if(resPayload &&
@@ -225,6 +228,7 @@ static OCStackApplicationResult SecurePortDiscoveryCallback(void *ctx, OCDoHandl
     return OC_STACK_DELETE_TRANSACTION;
 }
 
+
 OCStackResult SendAclReq(PEContext_t *context, OCDevAddr *devAddr, OCConnectivityType connType,
         uint16_t securedPort)
 {
@@ -265,6 +269,7 @@ exit:
     return ret;
 }
 
+
 static OCStackApplicationResult AmsMgrAclReqCallback(void *ctx, OCDoHandle handle,
     OCClientResponse * clientResponse)
 {
@@ -300,9 +305,8 @@ static OCStackApplicationResult AmsMgrAclReqCallback(void *ctx, OCDoHandle handl
         memcmp(context->amsMgrContext->amsDeviceId.id, clientResponse->identity.id,
                        sizeof(context->amsMgrContext->amsDeviceId.id)) == 0)
     {
-        size_t size = strlen((char *)clientResponse->payload);
         OCStackResult ret =
-                InstallNewACL(((OCSecurityPayload*)clientResponse->payload)->securityData1, size);
+                InstallNewACL(((OCSecurityPayload*)clientResponse->payload)->securityData);
         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
 
         OIC_LOG_V(INFO, TAG, "%s : Calling checkPermission", __func__);
@@ -321,6 +325,7 @@ exit:
     return OC_STACK_DELETE_TRANSACTION;
 }
 
+
 OCStackResult UpdateAmsMgrContext(PEContext_t *context, const CAEndpoint_t *endpoint,
                         const CARequestInfo_t *requestInfo)
 {
@@ -328,7 +333,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;
@@ -337,7 +342,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;
@@ -351,7 +356,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;
@@ -375,7 +380,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);
@@ -392,11 +397,12 @@ 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 b77c4e5..2a1ac98 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 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.
+ * @param[in] in  octet stream, max 3 byte
+ * @param[out] out  base64 encoded stream, 4 byte
+ * @param[in] len  byte-length of in
  *
- * @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,9 +77,25 @@ 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;
@@ -88,13 +104,12 @@ B64Result b64Encode(const uint8_t* in, const size_t inLen,
     *outLen = ((inLen / 3) * 3 == inLen) ?
               ((inLen / 3) * 4) :
               (((inLen / 3) + 1) * 4);
-    uint32_t minBufSize = (*outLen + 1);
-    if (outBufSize < minBufSize)
+    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))
@@ -105,7 +120,7 @@ B64Result b64Encode(const uint8_t* in, const size_t inLen,
 
     if (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;
         }
@@ -117,11 +132,11 @@ B64Result b64Encode(const uint8_t* in, const size_t inLen,
 }
 
 /**
- * Get decoded value.
+ * Get decoded value
  *
- * @param c is the Base64 encoded character.
+ * @param[in] c  Base64 encoded charactor
  *
- * @return decoded value, 6-bit.
+ * @return decoded value, 6-bit
  */
 static uint32_t b64GetVal(char c)
 {
@@ -154,21 +169,23 @@ static uint32_t b64GetVal(char c)
 }
 
 /**
- * Base64 block decode function.
+ * base64 block decode function
  *
- * @param in is the Base64 encoded stream, 4 bytes.
- * @param out is the Octet stream, 3 bytes.
+ * @param[in] in  Base64 encoded stream, 4 bytes
+ * @param[out] out  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)
 {
-    if (NULL == in || NULL == out)
+    uint32_t val;
+
+    if(NULL == in || NULL == out)
     {
         return B64_INVALID_PARAM;
     }
 
-    uint32_t val = (b64GetVal(in[0]) << 18) | (b64GetVal(in[1]) << 12) |
+    val = (b64GetVal(in[0]) << 18) | (b64GetVal(in[1]) << 12) |
           (b64GetVal(in[2]) << 6) | (b64GetVal(in[3]));
 
     out[0] = (val >> 16) & 0xff;
@@ -185,32 +202,47 @@ 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;
-    uint32_t minBufSize = (inLen / 4) * 3;
-    if ('=' == in[inLen - 1])
+    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 (uint32_t i = 0; i < inLen / 4; i++)
+    for (i = 0; i < inLen / 4; i++)
     {
         if(B64_OK != b64DecodeBlk(in + i * 4, outBuf + i * 3))
         {
index 70fb2b4..54f17b4 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 "ocrandom.h"
-#include "ocserverrequest.h"
+#include "logger.h"
 #include "oic_malloc.h"
-#include "ocpayload.h"
+#include "cJSON.h"
+#include "resourcemanager.h"
+#include "psinterface.h"
 #include "utlist.h"
+#include "srmresourcestrings.h"
 #include "credresource.h"
+#include "ocrandom.h"
 #include "doxmresource.h"
-#include "pstatresource.h"
-#include "iotvticalendar.h"
-#include "pbkdf2.h"
-#include "resourcemanager.h"
-#include "srmresourcestrings.h"
+#include "base64.h"
 #include "srmutility.h"
-#include "psinterface.h"
-#include "pinoxmcommon.h"
+#include "cainterface.h"
+#include "pbkdf2.h"
+#include <stdlib.h>
+#include "iotvticalendar.h"
+#include "ocserverrequest.h"
 
 #ifdef __WITH_DTLS__
 #include "global.h"
+#endif //__WITH_DTLS__
+
+#ifdef WITH_ARDUINO
+#include <string.h>
+#else
+#include <strings.h>
 #endif
+#include <stdint.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. */
-static const uint8_t CBOR_SIZE = 255;
-
-/** 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;
@@ -73,7 +62,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
@@ -111,292 +100,244 @@ void DeleteCredList(OicSecCred_t* cred)
     }
 }
 
-static size_t OicSecCredCount(const OicSecCred_t *secCred)
+/**
+ * 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)
 {
-    size_t size = 0;
-    for (const OicSecCred_t *cred = secCred; cred; cred = cred->next)
-    {
-        size++;
-    }
-    return size;
-}
+    cJSON *jsonRoot = NULL;
+    char *jsonStr = NULL;
 
-OCStackResult CredToCBORPayload(const OicSecCred_t *credS, uint8_t **cborPayload,
-                                size_t *cborSize)
-{
-    if (NULL == credS || NULL == cborPayload || NULL != *cborPayload || NULL == cborSize)
+    if (cred)
     {
-        return OC_STACK_INVALID_PARAM;
-    }
+        char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};
+        uint32_t outLen = 0;
+        B64Result b64Ret = B64_OK;
 
-    OCStackResult ret = OC_STACK_ERROR;
-    size_t cborLen = *cborSize;
-    if (0 == cborLen)
-    {
-        cborLen = CBOR_SIZE;
-    }
+        jsonRoot = cJSON_CreateObject();
+        VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
 
-    *cborSize = 0;
-    *cborPayload = NULL;
+        cJSON *jsonCredArray = NULL;
+        cJSON_AddItemToObject(jsonRoot, OIC_JSON_CRED_NAME,
+                jsonCredArray = cJSON_CreateArray());
+        VERIFY_NON_NULL(TAG, jsonCredArray, ERROR);
 
-    CborEncoder encoder = { {.ptr = NULL }, .end = 0 };
-    CborEncoder credArray = { {.ptr = NULL }, .end = 0 };
-    CborError cborEncoderResult = CborNoError;
+        while(cred)
+        {
+            cJSON *jsonCred = cJSON_CreateObject();
+            VERIFY_NON_NULL(TAG, jsonCred, ERROR);
 
-    const OicSecCred_t *cred = credS;
-    size_t mapSize = CRED_MAP_SIZE;
-    if (cred->period)
-    {
-        mapSize++;
-    }
-    if (cred->publicData.data)
-    {
-        mapSize++;
-    }
-    if (cred->privateData.data)
-    {
-        mapSize++;
-    }
-    if (cred->period)
-    {
-        mapSize++;
-    }
-    uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
-    VERIFY_NON_NULL(TAG, outPayload, ERROR);
-    cbor_encoder_init(&encoder, outPayload, cborLen, 0);
+            //CredID -- Mandatory
+            cJSON_AddNumberToObject(jsonCred, OIC_JSON_CREDID_NAME, (int)cred->credId);
 
-    // Create CRED Array
-    cborEncoderResult = cbor_encoder_create_array(&encoder, &credArray, OicSecCredCount(cred));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding0 Cred Array.");
+            //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);
 
-    while (cred)
-    {
-        CborEncoder credMap = { {.ptr = NULL }, .end = 0 };
-        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.");
+            //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
+
+            //CredType -- Mandatory
+            cJSON_AddNumberToObject(jsonCred, OIC_JSON_CREDTYPE_NAME,(int)cred->credType);
 
 #ifdef __WITH_X509__
-        //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,
-                    sizeof(cred->publicData.data));
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Public Tag Value.");
-        }
+            //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);
+                }
+            }
 #endif /*__WITH_X509__*/
-        //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,
-                sizeof(cred->privateData.data));
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Private Data Value.");
-        }
+            //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
+            }
 
-        //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.");
-        }
+            //Period -- Not Mandatory
+            if(cred->period)
+            {
+                cJSON_AddStringToObject(jsonCred, OIC_JSON_PERIOD_NAME,
+                                        cred->period);
+            }
 
-        //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.");
+            //Owners -- Mandatory
+            cJSON *jsonOwnrArray = NULL;
+            cJSON_AddItemToObject (jsonCred, OIC_JSON_OWNERS_NAME,
+                                             jsonOwnrArray = cJSON_CreateArray());
+            VERIFY_NON_NULL(TAG, jsonOwnrArray, ERROR);
             for (size_t i = 0; i < cred->ownersLen; i++)
             {
-                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.");
+                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_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.");
 
-        cred = cred->next;
-   }
-   cborEncoderResult = cbor_encoder_close_container(&encoder, &credArray);
-   VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Cred Array.");
+            /* Attach current cred node to cred Array */
+            cJSON_AddItemToArray(jsonCredArray, jsonCred);
+            cred = cred->next;
+        }
 
-   if (CborNoError == cborEncoderResult)
-   {
-       *cborPayload = outPayload;
-       *cborSize = encoder.ptr - outPayload;
-        ret = OC_STACK_OK;
+        jsonStr = cJSON_PrintUnformatted(jsonRoot);
     }
 
 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 = CredToCBORPayload(credS, cborPayload, &cborLen);
-       if (CborNoError == cborEncoderResult)
-       {
-           *cborSize = cborLen;
-            ret = OC_STACK_OK;
-        }
-    }
-
-    if (CborNoError != cborEncoderResult)
+    if (jsonRoot)
     {
-       OICFree(outPayload);
-       outPayload = NULL;
-       *cborSize = 0;
-       *cborPayload = NULL;
-       ret = OC_STACK_ERROR;
+        cJSON_Delete(jsonRoot);
     }
-
-    return ret;
+    return jsonStr;
 }
 
-OCStackResult CBORPayloadToCred(const uint8_t *cborPayload, size_t size,
-                                OicSecCred_t **secCred)
+/*
+ * This internal method converts JSON cred into binary cred.
+ */
+OicSecCred_t * JSONToCredBin(const char * jsonStr)
 {
-    if (NULL == cborPayload || NULL == secCred || NULL != *secCred)
-    {
-        return OC_STACK_INVALID_PARAM;
-    }
-
-    *secCred = NULL;
-
     OCStackResult ret = OC_STACK_ERROR;
+    OicSecCred_t * headCred = NULL;
+    OicSecCred_t * prevCred = NULL;
+    cJSON *jsonCredArray = NULL;
 
-    CborValue credCbor = { .parser = NULL };
-    CborParser parser = { .end = NULL };
-    CborError cborFindResult = CborNoError;
-    OicSecCred_t *cred = NULL;
-    char *name = NULL;
-
-    int cborLen = size;
-    if (0 == size)
-    {
-        cborLen = CBOR_SIZE;
-    }
-    cbor_parser_init(cborPayload, cborLen, 0, &parser, &credCbor);
-
-    OicSecCred_t *headCred = NULL;
+    cJSON *jsonRoot = cJSON_Parse(jsonStr);
+    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
 
-    CborValue credArray = { .parser = NULL };
-    cborFindResult = cbor_value_enter_container(&credCbor, &credArray);
-    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Cred Array.");
-
-    while (cbor_value_is_valid(&credArray))
+    jsonCredArray = cJSON_GetObjectItem(jsonRoot, OIC_JSON_CRED_NAME);
+    VERIFY_NON_NULL(TAG, jsonCredArray, ERROR);
+    if (cJSON_Array == jsonCredArray->type)
     {
-        CborValue credMap = { .parser = NULL };
-        cborFindResult = cbor_value_enter_container(&credArray, &credMap);
-        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Cred Map.");
+        int numCred = cJSON_GetArraySize(jsonCredArray);
+        int idx = 0;
 
-        cred = (OicSecCred_t *) OICCalloc(1, sizeof(*cred));
-        VERIFY_NON_NULL(TAG, cred, ERROR);
+        unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
+        uint32_t outLen = 0;
+        B64Result b64Ret = B64_OK;
 
-        while (cbor_value_is_valid(&credMap))
+        VERIFY_SUCCESS(TAG, numCred > 0, ERROR);
+        do
         {
-            size_t len = 0;
-            cborFindResult = cbor_value_dup_text_string(&credMap, &name, &len, NULL);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Cred Name.");
-            cborFindResult = cbor_value_advance(&credMap);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Cred Name. ");
+            cJSON *jsonCred = cJSON_GetArrayItem(jsonCredArray, idx);
+            VERIFY_NON_NULL(TAG, jsonCred, ERROR);
+
+            OicSecCred_t *cred = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
+            VERIFY_NON_NULL(TAG, cred, ERROR);
 
-            CborType type = cbor_value_get_type(&credMap);
+            headCred = (headCred) ? headCred : cred;
+            if (prevCred)
+            {
+                prevCred->next = cred;
+            }
+            size_t jsonObjLen = 0;
+            cJSON *jsonObj = NULL;
 
             //CredId -- Mandatory
-            if (0 == strcmp(OIC_JSON_CREDID_NAME, name))
+            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_CREDID_NAME);
+            if(jsonObj)
             {
-                cborFindResult = cbor_value_get_int(&credMap, (int *) &cred->credId);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Cred Id Value.");
+                VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
+                cred->credId = jsonObj->valueint;
             }
+
             //subject -- Mandatory
-            if (0 == strcmp(OIC_JSON_SUBJECT_NAME, name))
+            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))
             {
-                uint8_t *id = NULL;
-                cborFindResult = cbor_value_dup_byte_string(&credMap, &id, &len, NULL);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Subject Name Value.");
-                memcpy(cred->subject.id, id, len);
-                OICFree(id);
+                if(jsonObj)
+                {
+                    VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
+                }
             }
-            //CredType -- Mandatory
-            if (0 == strcmp(OIC_JSON_CREDTYPE_NAME, name))
+#ifdef __WITH_X509__
+            else if (cred->credType & SIGNED_ASYMMETRIC_KEY)
             {
-                cborFindResult = cbor_value_get_int(&credMap, (int *) &cred->credType);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Cred Type Value.");
+                VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+                VERIFY_SUCCESS(TAG, cJSON_Object == jsonObj->type, ERROR);
             }
-            //Owners -- Mandatory
-            if (0 == strcmp(OIC_JSON_OWNERS_NAME, name))
+#endif //  __WITH_X509__
+            if (NULL != jsonObj)
             {
-                CborValue owners = { .parser = NULL };
-                cborFindResult = cbor_value_get_array_length(&credMap, &cred->ownersLen);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owners Name Array Len.");
-                cborFindResult = cbor_value_enter_container(&credMap, &owners);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owners Name.");
-                int i = 0;
-                cred->owners = (OicUuid_t *)OICCalloc(cred->ownersLen, sizeof(*cred->owners));
-                VERIFY_NON_NULL(TAG, cred->owners, ERROR);
-                while (cbor_value_is_valid(&owners))
+                if (cJSON_String == jsonObj->type)
                 {
-                    uint8_t *owner = NULL;
-                    cborFindResult = cbor_value_dup_byte_string(&owners, &owner, &len, NULL);
-                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owner Value.");
-                    memcpy(cred->owners[i].id, owner, len);
-                    OICFree(owner);
-                    cborFindResult = cbor_value_advance(&owners);
-                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Owner Value.");
+                    jsonObjLen = strlen(jsonObj->valuestring) + 1;
+                    cred->privateData.data = (char *)OICMalloc(jsonObjLen);
+                    VERIFY_NON_NULL(TAG, (cred->privateData.data), ERROR);
+                    strncpy((char *)cred->privateData.data, (char *)jsonObj->valuestring, jsonObjLen);
                 }
-            }
-            //PrivateData is mandatory for some of the credential types listed below.
-            if (0 == strcmp(OIC_JSON_PRIVATEDATA_NAME, name))
-            {
-                if ((cred->credType & SYMMETRIC_PAIR_WISE_KEY) ||
-                    (cred->credType & SYMMETRIC_GROUP_KEY) ||
-                    (cred->credType & PIN_PASSWORD))
+#ifdef __WITH_X509__
+                else if (SIGNED_ASYMMETRIC_KEY == cred->credType && cJSON_Object == jsonObj->type)
                 {
-                    cborFindResult = cbor_value_dup_byte_string(&credMap,
-                        &cred->privateData.data, &len, NULL);
-                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Private Data Value.");
+                    cred->privateData.data = cJSON_PrintUnformatted(jsonObj);
+                    VERIFY_NON_NULL(TAG, (cred->privateData.data), ERROR);
                 }
+#endif // __WITH_X509__
             }
             else
             {
@@ -404,79 +345,102 @@ OCStackResult CBORPayloadToCred(const uint8_t *cborPayload, size_t size,
             }
 
             //PublicData is mandatory only for SIGNED_ASYMMETRIC_KEY credentials type.
-            if (0 == strcmp(OIC_JSON_PUBLICDATA_NAME, name))
+            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_PUBLICDATA_NAME);
+#ifdef __WITH_X509__
+            if (cred->credType & SIGNED_ASYMMETRIC_KEY)
             {
-                if (cred->credType & SIGNED_ASYMMETRIC_KEY)
+                VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+                VERIFY_SUCCESS(TAG, cJSON_Object == jsonObj->type, ERROR);
+            }
+#endif //  __WITH_X509__
+            if (NULL != jsonObj)
+            {
+                if (cJSON_String == jsonObj->type)
+                {
+                    jsonObjLen = strlen(jsonObj->valuestring) + 1;
+                    cred->publicData.data = (char *)OICMalloc(jsonObjLen);
+                    VERIFY_NON_NULL(TAG, (cred->publicData.data), ERROR);
+                    strncpy((char *)cred->publicData.data, (char *)jsonObj->valuestring, jsonObjLen);
+                }
+#ifdef __WITH_X509__
+                else if (SIGNED_ASYMMETRIC_KEY == cred->credType && cJSON_Object == jsonObj->type)
                 {
-                    cborFindResult = cbor_value_dup_byte_string(&credMap,
-                        &cred->publicData.data, &len, NULL);
-                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding ");
+                    cred->publicData.data = cJSON_PrintUnformatted(jsonObj);
+                    VERIFY_NON_NULL(TAG, (cred->publicData.data), ERROR);
                 }
+#endif //  __WITH_X509__
             }
+
             //Period -- Not Mandatory
-            if (0 == strcmp(OIC_JSON_PERIOD_NAME, name))
-            {
-                cborFindResult = cbor_value_dup_text_string(&credMap,
-                    &cred->period, &len, NULL);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Period Name Value.");
-            }
-            if (CborMapType != type && cbor_value_is_valid(&credMap))
+            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_PERIOD_NAME);
+            if(jsonObj && cJSON_String == jsonObj->type)
             {
-                cborFindResult = cbor_value_advance(&credMap);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Cred Map.");
+                jsonObjLen = strlen(jsonObj->valuestring) + 1;
+                cred->period = (char *)OICMalloc(jsonObjLen);
+                VERIFY_NON_NULL(TAG, cred->period, ERROR);
+                strncpy(cred->period, jsonObj->valuestring, jsonObjLen);
             }
-            OICFree(name);
-            name = NULL;
-        }
 
-        cred->next = NULL;
-        if (NULL == headCred)
-        {
-            headCred = cred;
-        }
-        else
-        {
-            OicSecCred_t *temp = headCred;
-            while (temp->next)
+            //Owners -- Mandatory
+            jsonObj = cJSON_GetObjectItem(jsonCred, OIC_JSON_OWNERS_NAME);
+            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+            VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
+            cred->ownersLen = (size_t)cJSON_GetArraySize(jsonObj);
+            VERIFY_SUCCESS(TAG, cred->ownersLen > 0, ERROR);
+            cred->owners = (OicUuid_t*)OICCalloc(cred->ownersLen, sizeof(OicUuid_t));
+            VERIFY_NON_NULL(TAG, (cred->owners), ERROR);
+            for(size_t i = 0; i < cred->ownersLen; i++)
             {
-                temp = temp->next;
+                cJSON *jsonOwnr = cJSON_GetArrayItem(jsonObj, i);
+                VERIFY_NON_NULL(TAG, jsonOwnr, ERROR);
+                VERIFY_SUCCESS(TAG, cJSON_String == jsonOwnr->type, ERROR);
+                outLen = 0;
+                memset(base64Buff, 0, sizeof(base64Buff));
+                b64Ret = b64Decode(jsonOwnr->valuestring, strlen(jsonOwnr->valuestring),
+                         base64Buff, sizeof(base64Buff), &outLen);
+                VERIFY_SUCCESS(TAG, (b64Ret == B64_OK &&
+                               outLen <= sizeof(cred->owners[i].id)), ERROR);
+                memcpy(cred->owners[i].id, base64Buff, outLen);
             }
-            temp->next = cred;
-        }
-        if (cbor_value_is_valid(&credArray))
-        {
-            cborFindResult = cbor_value_advance(&credArray);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Cred Array. ");
-        }
+            prevCred = cred;
+        } while( ++idx < numCred);
     }
-    *secCred = headCred;
+
     ret = OC_STACK_OK;
+
 exit:
-    if (CborNoError != cborFindResult)
+    cJSON_Delete(jsonRoot);
+    if (OC_STACK_OK != ret)
     {
         DeleteCredList(headCred);
         headCred = NULL;
-        ret = OC_STACK_ERROR;
-    }
-    if (cred)
-    {
-        DeleteCredList(cred);
     }
-    if (name)
-    {
-        OICFree(name);
-    }
-    return ret;
+    return headCred;
 }
 
+/**
+ * This function generates the bin credential data.
+ *
+ * @param subject pointer to subject of this credential.
+ * @param credType credential type.
+ * @param publicData public data such as public key.
+ * @param privateData private data such as private key.
+ *        The privateData is expected in base64 encoded format.
+ * @param ownersLen length of owners array
+ * @param owners array of owners.
+ *
+ * @retval
+ *      pointer to instance of OicSecCred_t  - success
+ *      NULL                                 - error
+ */
 OicSecCred_t * GenerateCredential(const OicUuid_t * subject, OicSecCredType_t credType,
-                                  const uint8_t * publicData, const uint8_t* privateData,
-                                  size_t ownersLen, const OicUuid_t * owners)
+                                 const char * publicData, const char * privateData,
+                                 size_t ownersLen, const OicUuid_t * owners)
 {
     (void)publicData;
     OCStackResult ret = OC_STACK_ERROR;
 
-    OicSecCred_t *cred = (OicSecCred_t *)OICCalloc(1, sizeof(*cred));
+    OicSecCred_t *cred = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
     VERIFY_NON_NULL(TAG, cred, ERROR);
 
     //CredId is assigned before appending new cred to the existing
@@ -491,29 +455,27 @@ OicSecCred_t * GenerateCredential(const OicUuid_t * subject, OicSecCredType_t cr
     cred->credType = credType;
 
 #ifdef __WITH_X509__
-    if (publicData)
+    if(publicData)
     {
-        cred->publicData.data = (uint8_t *)OICCalloc(1, PUBLIC_KEY_SIZE);
+        cred->publicData.data = (char *)OICMalloc(strlen(publicData)+1);
         VERIFY_NON_NULL(TAG, cred->publicData.data, ERROR);
-        memcpy(cred->publicData.data, publicData, PUBLIC_KEY_SIZE);
+        strncpy((char *)cred->publicData.data, publicData, strlen(publicData)+1);
     }
 #endif // __WITH_X509__
 
-    if (privateData)
+    if(privateData)
     {
-#ifdef __WITH_X509__
-        cred->privateData.data = (uint8_t *)OICCalloc(1, PRIVATE_KEY_SIZE);
+        cred->privateData.data = (char *)OICMalloc(strlen(privateData)+1);
         VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
-        memcpy(cred->privateData.data, privateData, PRIVATE_KEY_SIZE);
-#endif // __WITH_X509__
+        strncpy((char *)cred->privateData.data, privateData, strlen(privateData)+1);
     }
 
     VERIFY_SUCCESS(TAG, ownersLen > 0, ERROR);
     cred->ownersLen = ownersLen;
 
-    cred->owners = (OicUuid_t *)OICCalloc(cred->ownersLen, sizeof(*cred->owners));
+    cred->owners = (OicUuid_t*)OICCalloc(cred->ownersLen, sizeof(OicUuid_t));
     VERIFY_NON_NULL(TAG, cred->owners, ERROR);
-    for (size_t i = 0; i < cred->ownersLen; i++)
+    for(size_t i = 0; i < cred->ownersLen; i++)
     {
         memcpy(cred->owners[i].id, owners[i].id, sizeof(cred->owners[i].id));
     }
@@ -533,20 +495,22 @@ static bool UpdatePersistentStorage(const OicSecCred_t *cred)
     bool ret = false;
 
     // Convert Cred data into JSON for update to persistent storage
-    uint8_t *payload = NULL;
-    size_t size = 0;
-    OCStackResult res = CredToCBORPayload(cred, &payload, &size);
-    if ((OC_STACK_OK == res) && payload)
+    char *jsonStr = BinToCredJSON(cred);
+    if (jsonStr)
     {
-        if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_CRED_NAME, payload, size))
+        cJSON *jsonCred = cJSON_Parse(jsonStr);
+        OICFree(jsonStr);
+
+        if ((jsonCred) &&
+          (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_CRED_NAME, jsonCred)))
         {
             ret = true;
         }
-        OICFree(payload);
+        cJSON_Delete(jsonCred );
     }
     else //Empty cred list
     {
-        if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_CRED_NAME, NULL, size))
+        if (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_CRED_NAME, NULL))
         {
             ret = true;
         }
@@ -555,22 +519,23 @@ static bool UpdatePersistentStorage(const OicSecCred_t *cred)
 }
 
 /**
- * Compare function used LL_SORT for sorting credentials.
+ * Compare function used LL_SORT for sorting credentials
  *
- * @param first pointer to OicSecCred_t struct.
- * @param second  pointer to OicSecCred_t struct.
+ * @param first   pointer to OicSecCred_t struct
+ * @param second  pointer to OicSecCred_t struct
  *
- *@return -1, if credId of first is less than credId of second.
- * 0, if credId of first is equal to credId of second.
- * 1, if credId of first is greater than credId of second.
+ *@retval
+ *  -1    if credId of first is less than credId of second
+ *   0    if credId of first is equal to credId of second
+ *   1    if credId of first is greater than credId of second
  */
 static int CmpCredId(const OicSecCred_t * first, const OicSecCred_t *second)
 {
-    if (first->credId < second->credId)
+    if(first->credId < second->credId)
     {
         return -1;
     }
-    else if (first->credId > second->credId)
+    else if(first->credId > second->credId)
     {
         return 1;
     }
@@ -584,19 +549,23 @@ static int CmpCredId(const OicSecCred_t * first, const OicSecCred_t *second)
  * available due deletion of OicSecCred_t object or one more than
  * credId of last credential in the list.
  *
- * @return next available credId if successful, else 0 for error.
+ * @retval
+ *      next available credId  - success
+ *      0                      - error
  */
+
 static uint16_t GetCredId()
 {
     //Sorts credential list in incremental order of credId
     LL_SORT(gCred, CmpCredId);
 
+
     OicSecCred_t *currentCred = NULL, *credTmp = NULL;
     uint16_t nextCredId = 1;
 
     LL_FOREACH_SAFE(gCred, currentCred, credTmp)
     {
-        if (currentCred->credId == nextCredId)
+        if(currentCred->credId == nextCredId)
         {
             nextCredId += 1;
         }
@@ -614,29 +583,38 @@ exit:
 }
 
 /**
- * Get the default value.
- *
- * @return  NULL for now.
+ * Get the default value
+ * @retval  NULL for now. Update it when we finalize the default info.
  */
 static OicSecCred_t* GetCredDefault()
 {
-    // TODO:Update it when we finalize the default info.
     return NULL;
 }
 
+/**
+ * This function adds the new cred to the credential list.
+ *
+ * @param cred pointer to new credential.
+ *
+ * @retval
+ *      OC_STACK_OK     - cred not NULL and persistent storage gets updated
+ *      OC_STACK_ERROR  - cred is NULL or fails to update persistent storage
+ */
 OCStackResult AddCredential(OicSecCred_t * newCred)
 {
     OCStackResult ret = OC_STACK_ERROR;
+
     VERIFY_SUCCESS(TAG, NULL != newCred, ERROR);
 
     //Assigning credId to the newCred
     newCred->credId = GetCredId();
+
     VERIFY_SUCCESS(TAG, newCred->credId != 0, ERROR);
 
     //Append the new Cred to existing list
     LL_APPEND(gCred, newCred);
 
-    if (UpdatePersistentStorage(gCred))
+    if(UpdatePersistentStorage(gCred))
     {
         ret = OC_STACK_OK;
     }
@@ -654,7 +632,7 @@ OCStackResult RemoveCredential(const OicUuid_t *subject)
 
     LL_FOREACH_SAFE(gCred, cred, tempCred)
     {
-        if (memcmp(cred->subject.id, subject->id, sizeof(subject->id)) == 0)
+        if(memcmp(cred->subject.id, subject->id, sizeof(subject->id)) == 0)
         {
             LL_DELETE(gCred, cred);
             FreeCred(cred);
@@ -662,9 +640,9 @@ OCStackResult RemoveCredential(const OicUuid_t *subject)
         }
     }
 
-    if (deleteFlag)
+    if(deleteFlag)
     {
-        if (UpdatePersistentStorage(gCred))
+        if(UpdatePersistentStorage(gCred))
         {
             ret = OC_STACK_RESOURCE_DELETED;
         }
@@ -685,7 +663,7 @@ OCStackResult RemoveAllCredentials(void)
     DeleteCredList(gCred);
     gCred = GetCredDefault();
 
-    if (!UpdatePersistentStorage(gCred))
+    if(!UpdatePersistentStorage(gCred))
     {
         return OC_STACK_ERROR;
     }
@@ -700,7 +678,7 @@ OCStackResult RemoveAllCredentials(void)
  * @param ownerAdd address of OBT(PT)
  * @param doxm current device's doxm resource
  *
- * @return
+ * @retval
  *     true successfully done and valid ower psk information
  *     false Invalid owner psk information or failed to owner psk generation
  */
@@ -723,17 +701,34 @@ static bool FillPrivateDataOfOwnerPSK(OicSecCred_t* receviedCred, const CAEndpoi
     OIC_LOG_BUFFER(DEBUG, TAG, ownerPSK, OWNER_PSK_LENGTH_128);
 
     //Generate owner credential based on recevied credential information
-    receviedCred->privateData.data = (uint8_t *)OICCalloc(1, OWNER_PSK_LENGTH_128);
+    size_t b64BufSize = B64ENCODE_OUT_SAFESIZE(OWNER_PSK_LENGTH_128 * sizeof(char));
+    uint8_t* encodeBuff = OICMalloc((b64BufSize + 1) * sizeof(char));
+    VERIFY_NON_NULL(TAG, encodeBuff, ERROR);
+    uint32_t encodedSize = 0;
+    B64Result b64Ret = b64Encode(ownerPSK, OWNER_PSK_LENGTH_128,
+                                 (char*)encodeBuff, b64BufSize + 1, &encodedSize);
+    VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
+    encodeBuff[encodedSize] = '\0';
+
+    //memory re-allocation for private data
+    OICFree(receviedCred->privateData.data);
+    receviedCred->privateData.data = (char*)OICMalloc((encodedSize + 1) * sizeof(char));
     VERIFY_NON_NULL(TAG, receviedCred->privateData.data, ERROR);
-    memcpy(receviedCred->privateData.data, ownerPSK, OWNER_PSK_LENGTH_128);
+
+    //fill the base64 encoded private data
+    strncpy(receviedCred->privateData.data, (char*)encodeBuff, b64BufSize + 1);
 
     OIC_LOG(INFO, TAG, "PrivateData of OwnerPSK was calculated successfully");
 
+    //deallocate local memory
+    OICFree(encodeBuff);
+
     //Verify OwnerPSK information
     return (memcmp(&(receviedCred->subject), &(doxm->owner), sizeof(OicUuid_t)) == 0 &&
             receviedCred->credType == SYMMETRIC_PAIR_WISE_KEY);
 exit:
     //receviedCred->privateData.data will be deallocated when deleting credential.
+    OICFree(encodeBuff);
     return false;
 }
 
@@ -744,11 +739,9 @@ static OCEntityHandlerResult HandlePutRequest(const OCEntityHandlerRequest * ehR
     OCEntityHandlerResult ret = OC_EH_ERROR;
 
     //Get binary representation of json
-    OicSecCred_t * cred  = NULL;
-    uint8_t *payload = (((OCSecurityPayload*)ehRequest->payload)->securityData1);
-    //size_t size = (((OCSecurityPayload*)ehRequest->payload)->payloadSize);
-    OCStackResult res = CBORPayloadToCred(payload, 0, &cred);
-    if (res == OC_STACK_OK)
+    OicSecCred_t * cred  = JSONToCredBin(((OCSecurityPayload*)ehRequest->payload)->securityData);
+
+    if(cred)
     {
 #ifdef __WITH_DTLS__
         OicUuid_t emptyUuid = {.id={0}};
@@ -874,7 +867,7 @@ static OCEntityHandlerResult HandlePutRequest(const OCEntityHandlerRequest * ehR
 #endif//__WITH_DTLS__
     }
 
-    if (OC_EH_RESOURCE_CREATED != ret)
+    if(OC_EH_RESOURCE_CREATED != ret)
     {
         if(OC_STACK_OK != RemoveCredential(&cred->subject))
         {
@@ -890,11 +883,10 @@ static OCEntityHandlerResult HandlePostRequest(const OCEntityHandlerRequest * eh
 {
     OCEntityHandlerResult ret = OC_EH_ERROR;
 
-    //Get binary representation of CBOR
-    OicSecCred_t *cred  = NULL;
-    uint8_t *payload = ((OCSecurityPayload*)ehRequest->payload)->securityData1;
-    OCStackResult res = CBORPayloadToCred(payload, 0, &cred);
-    if ((OC_STACK_OK == res) && cred)
+    //Get binary representation of json
+    OicSecCred_t * cred  = JSONToCredBin(((OCSecurityPayload*)ehRequest->payload)->securityData);
+
+    if(cred)
     {
         //If the Post request credential has credId, it will be
         //discarded and the next available credId will be assigned
@@ -912,41 +904,54 @@ static OCEntityHandlerResult HandleDeleteRequest(const OCEntityHandlerRequest *e
 
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
 
-    if (NULL == ehRequest->query)
+    if(NULL == ehRequest->query)
    {
        return ehRet;
    }
 
-   OicParseQueryIter_t parseIter = { .attrPos=NULL };
+   OicParseQueryIter_t parseIter = {.attrPos=NULL};
    OicUuid_t subject = {.id={0}};
 
    //Parsing REST query to get the subject
    ParseQueryIterInit((unsigned char *)ehRequest->query, &parseIter);
-   while (GetNextQuery(&parseIter))
+   while(GetNextQuery(&parseIter))
    {
-       if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_SUBJECT_NAME,
+       if(strncasecmp((char *)parseIter.attrPos, OIC_JSON_SUBJECT_NAME,
                parseIter.attrLen) == 0)
        {
-           memcpy(subject.id, parseIter.valPos, parseIter.valLen);
+           unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
+           uint32_t outLen = 0;
+           B64Result b64Ret = B64_OK;
+
+           b64Ret = b64Decode((char *)parseIter.valPos, parseIter.valLen,
+                   base64Buff, sizeof(base64Buff), &outLen);
+
+           VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(subject.id)), ERROR);
+           memcpy(subject.id, base64Buff, outLen);
        }
    }
 
-   if (OC_STACK_RESOURCE_DELETED == RemoveCredential(&subject))
+   if(OC_STACK_RESOURCE_DELETED == RemoveCredential(&subject))
    {
        ehRet = OC_EH_RESOURCE_DELETED;
    }
 
+exit:
     return ehRet;
 }
 
-OCEntityHandlerResult CredEntityHandler(OCEntityHandlerFlag flag,
+/*
+ * 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)
 {
     (void)callbackParameter;
     OCEntityHandlerResult ret = OC_EH_ERROR;
 
-    if (!ehRequest)
+    if(!ehRequest)
     {
         return OC_EH_ERROR;
     }
@@ -954,7 +959,7 @@ OCEntityHandlerResult CredEntityHandler(OCEntityHandlerFlag flag,
     {
         OIC_LOG (DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
         //TODO :  Handle PUT/DEL methods
-        switch (ehRequest->method)
+        switch(ehRequest->method)
         {
             case OC_REST_GET:
                 ret = OC_EH_FORBIDDEN;
@@ -975,21 +980,26 @@ OCEntityHandlerResult CredEntityHandler(OCEntityHandlerFlag flag,
     }
 
     //Send payload to request originator
-    ret = (SendSRMCBORResponse(ehRequest, ret, NULL) == OC_STACK_OK) ?
-                       ret : OC_EH_ERROR;
+    ret = (SendSRMResponse(ehRequest, ret, NULL) == OC_STACK_OK ?
+                       ret : OC_EH_ERROR);
 
     return ret;
 }
 
+/*
+ * This internal method is used to create '/oic/sec/Cred' resource.
+ */
 OCStackResult CreateCredResource()
 {
-    OCStackResult ret = OCCreateResource(&gCredHandle,
-                                         OIC_RSRC_TYPE_SEC_CRED,
-                                         OIC_MI_DEF,
-                                         OIC_RSRC_CRED_URI,
-                                         CredEntityHandler,
-                                         NULL,
-                                         OC_RES_PROP_NONE);
+    OCStackResult ret;
+
+    ret = OCCreateResource(&gCredHandle,
+                           OIC_RSRC_TYPE_SEC_CRED,
+                           OIC_MI_DEF,
+                           OIC_RSRC_CRED_URI,
+                           CredEntityHandler,
+                           NULL,
+                           OC_RES_PROP_NONE);
 
     if (OC_STACK_OK != ret)
     {
@@ -999,40 +1009,49 @@ OCStackResult CreateCredResource()
     return ret;
 }
 
+/**
+ * Initialize Cred resource by loading data from persistent storage.
+ *
+ * @retval
+ *     OC_STACK_OK    - no errors
+ *     OC_STACK_ERROR - stack process error
+ */
 OCStackResult InitCredResource()
 {
     OCStackResult ret = OC_STACK_ERROR;
 
     //Read Cred resource from PS
-    uint8_t *data = NULL;
-    size_t size = 0;
-    ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_CRED_NAME, &data, &size);
-    // If database read failed
-    if (ret != OC_STACK_OK)
-    {
-        OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
-    }
-    if (data)
+    char* jsonSVRDatabase = GetSVRDatabase();
+
+    if (jsonSVRDatabase)
     {
-        // Read ACL resource from PS
-        ret = CBORPayloadToCred(data, size, &gCred);
+        //Convert JSON Cred into binary format
+        gCred = JSONToCredBin(jsonSVRDatabase);
     }
-
     /*
      * If SVR database in persistent storage got corrupted or
      * is not available for some reason, a default Cred is created
      * which allows user to initiate Cred provisioning again.
      */
-    if (ret != OC_STACK_OK || !data || !gCred)
+    if (!jsonSVRDatabase || !gCred)
     {
         gCred = GetCredDefault();
     }
     //Instantiate 'oic.sec.cred'
     ret = CreateCredResource();
-    OICFree(data);
+    OICFree(jsonSVRDatabase);
     return ret;
 }
 
+/**
+ * Perform cleanup for Cred resources.
+ *
+ * @return
+ *     OC_STACK_OK              - no errors
+ *     OC_STACK_ERROR           - stack process error
+ *     OC_STACK_NO_RESOURCE     - resource not found
+ *     OC_STACK_INVALID_PARAM   - invalid param
+ */
 OCStackResult DeInitCredResource()
 {
     OCStackResult result = OCDeleteResource(gCredHandle);
@@ -1041,6 +1060,15 @@ OCStackResult DeInitCredResource()
     return result;
 }
 
+/**
+ * This method is used by tinydtls/SRM to retrieve credential for given Subject.
+ *
+ * @param subject - subject for which credential is required.
+ *
+ * @retval
+ *     reference to OicSecCred_t - if credential is found
+ *     NULL                      - if credential not found
+ */
 const OicSecCred_t* GetCredResourceData(const OicUuid_t* subject)
 {
     OicSecCred_t *cred = NULL;
@@ -1062,9 +1090,22 @@ const OicSecCred_t* GetCredResourceData(const OicUuid_t* subject)
 
 
 #if defined(__WITH_DTLS__)
-int32_t GetDtlsPskCredentials(CADtlsPskCredType_t type,
-              const uint8_t *desc, size_t desc_len,
-              uint8_t *result, size_t result_length)
+/**
+ * This internal callback is used by lower stack (i.e. CA layer) to
+ * retrieve PSK credentials from RI security layer.
+ *
+ * @param[in]  type type of PSK data required by tinyDTLS layer during DTLS handshake.
+ * @param[in]  desc Additional request information.
+ * @param[in]  desc_len The actual length of desc.
+ * @param[out] result  Must be filled with the requested information.
+ * @param[in]  result_length  Maximum size of @p result.
+ *
+ * @return The number of bytes written to @p result or a value
+ *         less than zero on error.
+ */
+int32_t GetDtlsPskCredentials( CADtlsPskCredType_t type,
+              const unsigned char *desc, size_t desc_len,
+              unsigned char *result, size_t result_length)
 {
     int32_t ret = -1;
 
@@ -1123,10 +1164,18 @@ int32_t GetDtlsPskCredentials(CADtlsPskCredType_t type,
                             }
                         }
 
-                        // Copy PSK.
-                        result_length = sizeof(cred->privateData.data);
-                        memcpy(result, cred->privateData.data, result_length);
-                        return result_length;
+                        // Convert PSK from Base64 encoding to binary before copying
+                        uint32_t outLen = 0;
+                        B64Result b64Ret = b64Decode(cred->privateData.data,
+                                strlen(cred->privateData.data), result,
+                                result_length, &outLen);
+                        if (B64_OK != b64Ret)
+                        {
+                            OIC_LOG (ERROR, TAG, "Base64 decoding failed.");
+                            ret = -1;
+                            return ret;
+                        }
+                        return outLen;
                     }
                 }
             }
@@ -1168,14 +1217,19 @@ OCStackResult AddTmpPskWithPIN(const OicUuid_t* tmpSubject, OicSecCredType_t cre
     }
 
     uint8_t privData[OWNER_PSK_LENGTH_128] = {0,};
-    OicSecCred_t* cred = NULL;
     int dtlsRes = DeriveCryptoKeyFromPassword((const unsigned char *)pin, pinSize, owners->id,
                                               UUID_LENGTH, PBKDF_ITERATIONS,
                                               OWNER_PSK_LENGTH_128, privData);
     VERIFY_SUCCESS(TAG, (0 == dtlsRes) , ERROR);
 
-    cred = GenerateCredential(tmpSubject, credType, NULL,
-                              privData, ownersLen, owners);
+    uint32_t outLen = 0;
+    char base64Buff[B64ENCODE_OUT_SAFESIZE(OWNER_PSK_LENGTH_128) + 1] = {};
+    B64Result b64Ret = b64Encode(privData, OWNER_PSK_LENGTH_128, base64Buff,
+                                sizeof(base64Buff), &outLen);
+    VERIFY_SUCCESS(TAG, (B64_OK == b64Ret), ERROR);
+
+    OicSecCred_t* cred = GenerateCredential(tmpSubject, credType, NULL,
+                                            base64Buff, ownersLen, owners);
     if(NULL == cred)
     {
         OIC_LOG(ERROR, TAG, "GeneratePskWithPIN() : Failed to generate credential");
@@ -1204,6 +1258,7 @@ exit:
 #define CERTIFICATE ("x5c")
 #define PRIVATE_KEY ("d")
 
+
 static void WriteCertPrefix(uint8_t *prefix, uint32_t certLen)
 {
     for (size_t i = 0; i < CERT_LEN_PREFIX; ++i)
@@ -1215,9 +1270,9 @@ static void WriteCertPrefix(uint8_t *prefix, uint32_t certLen)
 static uint32_t ParseCertPrefix(uint8_t *prefix)
 {
     uint32_t res = 0;
-    if (NULL != prefix)
+    if(NULL != prefix)
     {
-        for (int i = 0; i < CERT_LEN_PREFIX; ++i)
+        for(int i=0; i < CERT_LEN_PREFIX; ++i)
         {
             res |= (((uint32_t) prefix[i]) << ((CERT_LEN_PREFIX - 1 -i) * BYTE_SIZE));
         }
@@ -1225,30 +1280,34 @@ static uint32_t ParseCertPrefix(uint8_t *prefix)
     return res;
 }
 
-static uint32_t appendCert2Chain(uint8_t *appendPoint, uint8_t *cert, size_t len, uint32_t max_len)
+static uint32_t appendCert2Chain(uint8_t *appendPoint, char *cert, uint32_t max_len)
 {
     uint32_t ret = 0;
     VERIFY_NON_NULL(TAG, appendPoint, ERROR);
     VERIFY_NON_NULL(TAG, cert, ERROR);
 
-    memcpy(appendPoint + CERT_LEN_PREFIX, cert, max_len - CERT_LEN_PREFIX);
-    WriteCertPrefix(appendPoint, len);
+    uint32_t certLen;
+    VERIFY_SUCCESS(TAG, B64_OK == b64Decode(cert, strlen(cert), appendPoint + CERT_LEN_PREFIX,
+                                            max_len - CERT_LEN_PREFIX, &certLen), ERROR);
+    WriteCertPrefix(appendPoint, certLen);
 
-    ret = len + CERT_LEN_PREFIX;
+    ret = certLen + CERT_LEN_PREFIX;
 exit:
     return ret;
 }
 
-static OCStackResult GetCAPublicKeyData(CADtlsX509Creds_t *credInfo)
-{
+static OCStackResult GetCAPublicKeyData(CADtlsX509Creds_t *credInfo){
     OCStackResult ret = OC_STACK_ERROR;
     uint8_t *ccPtr = credInfo->certificateChain;
-    for (uint8_t i = 0; i < credInfo->chainLen - 1; ++i)
+    for(uint32_t i =0; i < credInfo->chainLen - 1; ++i)
     {
         ccPtr += CERT_LEN_PREFIX + ParseCertPrefix(ccPtr);
     }
 
-    ByteArray cert = { .data = ccPtr + CERT_LEN_PREFIX, .len = ParseCertPrefix(ccPtr) };
+    ByteArray cert = {
+        .data = ccPtr + CERT_LEN_PREFIX,
+        .len = ParseCertPrefix(ccPtr)
+         };
     CertificateX509 certStruct;
 
     VERIFY_SUCCESS(TAG, PKI_SUCCESS == DecodeCertificate(cert, &certStruct), ERROR);
@@ -1263,6 +1322,70 @@ static OCStackResult GetCAPublicKeyData(CADtlsX509Creds_t *credInfo)
     return ret;
 }
 
+static OCStackResult GetCertCredPublicData(CADtlsX509Creds_t *credInfo, OicSecCred_t *cred)
+{
+    OCStackResult ret = OC_STACK_ERROR;
+    cJSON *jsonRoot = NULL;
+
+    VERIFY_NON_NULL(TAG, credInfo, ERROR);
+    VERIFY_NON_NULL(TAG, cred, ERROR);
+    VERIFY_NON_NULL(TAG, cred->publicData.data, ERROR);
+    //VERIFY_SUCCESS(TAG, NULL == credInfo->certificateChain.data, ERROR);
+    jsonRoot = cJSON_Parse(cred->publicData.data);
+    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+
+    //Get certificate chain
+    cJSON *jsonObj = cJSON_GetObjectItem(jsonRoot, CERTIFICATE);//TODO define field names constants
+    VERIFY_SUCCESS(TAG, NULL != jsonObj && cJSON_Array == jsonObj->type, ERROR);
+
+    size_t certChainLen = (size_t)cJSON_GetArraySize(jsonObj);
+    credInfo->chainLen = certChainLen;
+    VERIFY_SUCCESS(TAG, MAX_CHAIN_LEN >= certChainLen, ERROR);
+
+    uint32_t len = 0;
+    for (size_t i = 0; i < certChainLen; ++i)
+    {
+        cJSON *item = cJSON_GetArrayItem(jsonObj, i);
+        VERIFY_NON_NULL(TAG, item, ERROR);
+        VERIFY_SUCCESS(TAG, cJSON_String == item->type, ERROR);
+        uint32_t appendedLen = appendCert2Chain(credInfo->certificateChain + len, item->valuestring,
+                                              MAX_CERT_MESSAGE_LEN - len);
+        VERIFY_SUCCESS(TAG, 0 != appendedLen, ERROR);
+        len += appendedLen;
+    }
+    credInfo->certificateChainLen = len;
+    VERIFY_SUCCESS(TAG, OC_STACK_OK == GetCAPublicKeyData(credInfo), ERROR);
+    ret = OC_STACK_OK;
+exit:
+    cJSON_Delete(jsonRoot);
+    return ret;
+}
+
+static OCStackResult GetCertCredPrivateData(CADtlsX509Creds_t *credInfo, OicSecCred_t *cred)
+{
+    OCStackResult ret = OC_STACK_ERROR;
+    cJSON *jsonRoot = NULL;
+    VERIFY_NON_NULL(TAG, credInfo, ERROR);
+    VERIFY_NON_NULL(TAG, cred, ERROR);
+    VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
+    jsonRoot = cJSON_Parse(cred->privateData.data);
+    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+
+    cJSON *jsonObj = cJSON_GetObjectItem(jsonRoot, PRIVATE_KEY);//TODO define field names constants
+    VERIFY_SUCCESS(TAG, NULL != jsonObj && cJSON_String == jsonObj->type, ERROR);
+
+    uint32_t read = 0u;
+    VERIFY_SUCCESS(TAG, B64_OK == b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring),
+                                            credInfo->devicePrivateKey, PRIVATE_KEY_SIZE, &read)
+                   && PRIVATE_KEY_SIZE == read, ERROR);
+
+    ret = OC_STACK_OK;
+
+exit:
+    cJSON_Delete(jsonRoot);
+    return ret;
+}
+
 int GetDtlsX509Credentials(CADtlsX509Creds_t *credInfo)
 {
     int ret = 1;
@@ -1276,41 +1399,8 @@ int GetDtlsX509Credentials(CADtlsX509Creds_t *credInfo)
     LL_SEARCH_SCALAR(gCred, cred, credType, SIGNED_ASYMMETRIC_KEY);
     VERIFY_NON_NULL(TAG, cred, ERROR);
 
-    CborValue credCbor = { .parser = NULL };
-    CborParser parser = { .end = NULL };
-    CborError cborFindResult = CborNoError;
-    uint8_t *cborPayload = cred->publicData.data;
-    int cborLen = cred->publicData.len;
-    cbor_parser_init(cborPayload, cborLen, 0, &parser, &credCbor);
-    CborValue certMap;
-    cborFindResult = cbor_value_enter_container(&credCbor, &certMap);
-    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Cred Map.");
-
-    CborValue certs;
-    cborFindResult = cbor_value_map_find_value(&certs, CERTIFICATE, &certs);
-    if (cbor_value_is_array(&certs))
-    {
-        cborFindResult = cbor_value_get_array_length(&certs, (size_t *)&credInfo->chainLen);
-        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Chain Len.");
-        CborValue cert;
-        cborFindResult = cbor_value_enter_container(&certs, &cert);
-        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering Container.");
-        size_t len = 0;
-        size_t certLen = 0;
-        uint8_t *val = NULL;
-        while (cbor_value_is_byte_string(&cert))
-        {
-            cborFindResult = cbor_value_dup_byte_string(&cert, &val, &certLen, NULL);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a Period Array Value.");
-            cborFindResult = cbor_value_advance(&cert);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing a Period Array.");
-            uint32_t appendedLen = appendCert2Chain(credInfo->certificateChain + len, val, certLen, MAX_CERT_MESSAGE_LEN - len);
-            len += appendedLen;
-        }
-        credInfo->certificateChainLen = len;
-        GetCAPublicKeyData(credInfo);
-    }
-    memcpy(credInfo->devicePrivateKey, cred->privateData.data, PRIVATE_KEY_SIZE);
+    VERIFY_SUCCESS(TAG, OC_STACK_OK == GetCertCredPrivateData(credInfo, cred), ERROR);
+    VERIFY_SUCCESS(TAG, OC_STACK_OK == GetCertCredPublicData(credInfo, cred), ERROR);
 
     ret = 0;
 exit:
index e30c07d..9255508 100644 (file)
@@ -314,13 +314,13 @@ static OCEntityHandlerResult HandleCRLPostRequest(const OCEntityHandlerRequest *
 }
 
 
-/**
+/*
  * This internal method is the entity handler for CRL resource and
  * will handle REST request (GET/PUT/POST/DEL) for them.
  */
-static OCEntityHandlerResult CRLEntityHandler(OCEntityHandlerFlag flag,
-                                              OCEntityHandlerRequest *ehRequest,
-                                              void *callbackParameter)
+OCEntityHandlerResult CRLEntityHandler(OCEntityHandlerFlag flag,
+                                       OCEntityHandlerRequest *ehRequest,
+                                       void *callbackParameter)
 {
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
     (void)callbackParameter;
@@ -356,18 +356,19 @@ static OCEntityHandlerResult CRLEntityHandler(OCEntityHandlerFlag flag,
     return ehRet;
 }
 
-/**
+/*
  * This internal method is used to create '/oic/sec/crl' resource.
  */
-static OCStackResult CreateCRLResource()
+OCStackResult CreateCRLResource()
 {
-    OCStackResult ret = OCCreateResource(&gCrlHandle,
-                                         OIC_RSRC_TYPE_SEC_CRL,
-                                         OIC_MI_DEF,
-                                         OIC_RSRC_CRL_URI,
-                                         CRLEntityHandler,
-                                         NULL,
-                                         OC_OBSERVABLE);
+    OCStackResult ret;
+    ret = OCCreateResource(&gCrlHandle,
+                           OIC_RSRC_TYPE_SEC_CRL,
+                           OIC_MI_DEF,
+                           OIC_RSRC_CRL_URI,
+                           CRLEntityHandler,
+                           NULL,
+                           OC_OBSERVABLE);
 
     if (OC_STACK_OK != ret)
     {
@@ -378,8 +379,8 @@ static OCStackResult CreateCRLResource()
 }
 
 /**
- * Get the default value.
- * @return defaultCrl for now.
+ * Get the default value
+ * @retval  NULL for now. Update it when we finalize the default info.
  */
 static OicSecCrl_t *GetCrlDefault()
 {
index 6750a62..0690724 100644 (file)
@@ -826,7 +826,7 @@ static OCStackApplicationResult DirectPairingDiscoveryHandler(void* ctx, OCDoHan
     (void)UNUSED;\r
     if (clientResponse)\r
     {\r
-        OIC_LOG_V(INFO, TAG, "StackResult: %s", clientResponse->result);\r
+        OIC_LOG_V(INFO, TAG, "StackResult: %d", clientResponse->result);\r
         OIC_LOG_V(INFO, TAG,\r
                 "Device =============> Discovered @ %s:%d",\r
                 clientResponse->devAddr.addr,\r
@@ -865,7 +865,6 @@ static OCStackApplicationResult DirectPairingDiscoveryHandler(void* ctx, OCDoHan
                 return OC_STACK_KEEP_TRANSACTION;\r
             }\r
 \r
-\r
             char rsrc_uri[MAX_URI_LENGTH+1] = {0};\r
             int wr_len = snprintf(rsrc_uri, sizeof(rsrc_uri), "%s?%s=%s",\r
                       OC_RSRVD_WELL_KNOWN_URI, OC_RSRVD_RESOURCE_TYPE, OIC_RSRC_TYPE_SEC_DPAIRING);\r
index 49adaf9..860a78d 100644 (file)
 // limitations under the License.
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#include <stdlib.h>
-#include <string.h>
-
-#if HAVE_STRINGS_H
-#include <strings.h>
-#endif
-
-#ifdef __WITH_DTLS__
-#include "global.h"
-#endif
 
 #include "ocstack.h"
+#include "logger.h"
 #include "oic_malloc.h"
-#include "payload_logging.h"
-#include "utlist.h"
-#include "ocrandom.h"
-#include "ocpayload.h"
-#include "cainterface.h"
-#include "ocserverrequest.h"
+#include "cJSON.h"
 #include "resourcemanager.h"
 #include "doxmresource.h"
 #include "pstatresource.h"
 #include "aclresource.h"
 #include "psinterface.h"
+#include "utlist.h"
 #include "srmresourcestrings.h"
 #include "securevirtualresourcetypes.h"
+#include "base64.h"
+#include "ocrandom.h"
+#include "cainterface.h"
 #include "credresource.h"
+#include "ocserverrequest.h"
 #include "srmutility.h"
 #include "pinoxmcommon.h"
 
-#define TAG  "SRM-DOXM"
+#ifdef __WITH_DTLS__
+#include "global.h"
+#endif
 
-/** 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;
+#include <stdlib.h>
+#include <string.h>
 
-/** Max cbor size payload. */
-static const uint16_t CBOR_MAX_SIZE = 4400;
+#if HAVE_STRINGS_H
+#include <strings.h>
+#endif
 
-/** DOXM Map size - Number of mandatory items. */
-static const uint8_t DOXM_MAP_SIZE = 5;
+#define TAG  "SRM-DOXM"
 
 static OicSecDoxm_t        *gDoxm = NULL;
 static OCResourceHandle    gDoxmHandle = NULL;
@@ -96,106 +88,58 @@ void DeleteDoxmBinData(OicSecDoxm_t* doxm)
     }
 }
 
-OCStackResult DoxmToCBORPayload(const OicSecDoxm_t *doxm, uint8_t **payload, size_t *size)
+char * BinToDoxmJSON(const OicSecDoxm_t * doxm)
 {
-    if (NULL == doxm || NULL == payload || NULL != *payload || NULL == size)
+    if (NULL == doxm)
     {
-        return OC_STACK_INVALID_PARAM;
+        return NULL;
     }
 
-    size_t cborLen = *size;
-    if (0 == cborLen)
-    {
-        cborLen = CBOR_SIZE;
-    }
-
-    *payload = NULL;
-    *size = 0;
-
-    OCStackResult ret = OC_STACK_ERROR;
-
-    CborEncoder encoder = { {.ptr = NULL }, .end = 0 };
-    CborEncoder doxmMap = { {.ptr = NULL }, .end = 0 };
+    char *jsonStr = NULL;
+    cJSON *jsonDoxm = NULL;
+    char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};
+    uint32_t outLen = 0;
+    B64Result b64Ret = B64_OK;
 
-    CborError cborEncoderResult = CborNoError;
+    cJSON *jsonRoot = cJSON_CreateObject();
+    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
 
-    uint8_t mapSize = DOXM_MAP_SIZE;
-
-    if (doxm->oxmTypeLen > 0)
-    {
-        mapSize++;
-    }
-    if (doxm->oxmLen > 0)
-    {
-        mapSize++;
-    }
-
-    uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
-    VERIFY_NON_NULL(TAG, outPayload, ERROR);
-    cbor_encoder_init(&encoder, outPayload, cborLen, 0);
-
-    cborEncoderResult = cbor_encoder_create_map(&encoder, &doxmMap, mapSize);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Doxm Map.");
+    jsonDoxm = cJSON_CreateObject();
+    VERIFY_NON_NULL(TAG, jsonDoxm, ERROR);
+    cJSON_AddItemToObject(jsonRoot, OIC_JSON_DOXM_NAME, jsonDoxm );
 
     //OxmType -- Not Mandatory
-    if (doxm->oxmTypeLen > 0)
+    if(doxm->oxmTypeLen > 0)
     {
-        cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_TYPE_NAME,
-            strlen(OIC_JSON_OXM_TYPE_NAME));
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Tag.");
-        CborEncoder oxmType = { {.ptr = NULL }, .end = 0 };
-        cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxmType, doxm->oxmTypeLen);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Array.");
-
+        cJSON *jsonOxmTyArray = cJSON_CreateArray();
+        VERIFY_NON_NULL(TAG, jsonOxmTyArray, ERROR);
+        cJSON_AddItemToObject (jsonDoxm, OIC_JSON_OXM_TYPE_NAME, jsonOxmTyArray );
         for (size_t i = 0; i < doxm->oxmTypeLen; i++)
         {
-            cborEncoderResult = cbor_encode_text_string(&oxmType, doxm->oxmType[i],
-                strlen(doxm->oxmType[i]));
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Value.");
+            cJSON_AddItemToArray (jsonOxmTyArray, cJSON_CreateString(doxm->oxmType[i]));
         }
-        cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxmType);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmType.");
     }
 
     //Oxm -- Not Mandatory
-    if (doxm->oxmLen > 0)
+    if(doxm->oxmLen > 0)
     {
-        cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_NAME,
-            strlen(OIC_JSON_OXM_NAME));
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Tag.");
-        CborEncoder oxm = { {.ptr = NULL }, .end = 0 };
-        cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxm, doxm->oxmLen);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Array.");
-
+        cJSON *jsonOxmArray = cJSON_CreateArray();
+        VERIFY_NON_NULL(TAG, jsonOxmArray, ERROR);
+        cJSON_AddItemToObject (jsonDoxm, OIC_JSON_OXM_NAME,jsonOxmArray );
         for (size_t i = 0; i < doxm->oxmLen; i++)
         {
-            cborEncoderResult = cbor_encode_int(&oxm, doxm->oxm[i]);
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Value");
+            cJSON_AddItemToArray (jsonOxmArray, cJSON_CreateNumber(doxm->oxm[i]));
         }
-        cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxm);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmName.");
     }
 
     //OxmSel -- Mandatory
-    cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_SEL_NAME,
-        strlen(OIC_JSON_OXM_SEL_NAME));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Tag.");
-    cborEncoderResult = cbor_encode_int(&doxmMap, doxm->oxmSel);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Value.");
+    cJSON_AddNumberToObject(jsonDoxm, OIC_JSON_OXM_SEL_NAME, (int)doxm->oxmSel);
 
     //sct -- Mandatory
-    cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_SUPPORTED_CRED_TYPE_NAME,
-        strlen(OIC_JSON_SUPPORTED_CRED_TYPE_NAME));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Tag");
-    cborEncoderResult = cbor_encode_int(&doxmMap, doxm->sct);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Value.");
+    cJSON_AddNumberToObject(jsonDoxm, OIC_JSON_SUPPORTED_CRED_TYPE_NAME, (int)doxm->sct);
 
     //Owned -- Mandatory
-    cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OWNED_NAME,
-        strlen(OIC_JSON_OWNED_NAME));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Tag.");
-    cborEncoderResult = cbor_encode_boolean(&doxmMap, doxm->owned);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Value.");
+    cJSON_AddBoolToObject(jsonDoxm, OIC_JSON_OWNED_NAME, doxm->owned);
 
     //TODO: Need more clarification on deviceIDFormat field type.
 #if 0
@@ -204,209 +148,209 @@ OCStackResult DoxmToCBORPayload(const OicSecDoxm_t *doxm, uint8_t **payload, siz
 #endif
 
     //DeviceId -- Mandatory
-    cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVICE_ID_NAME,
-        strlen(OIC_JSON_DEVICE_ID_NAME));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Tag.");
-    cborEncoderResult = cbor_encode_byte_string(&doxmMap, doxm->deviceID.id,
-                                                sizeof(doxm->deviceID.id));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Value.");
+    outLen = 0;
+    b64Ret = b64Encode(doxm->deviceID.id, sizeof(doxm->deviceID.id), base64Buff,
+                    sizeof(base64Buff), &outLen);
+    VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
+    cJSON_AddStringToObject(jsonDoxm, OIC_JSON_DEVICE_ID_NAME, base64Buff);
 
     //DPC -- Mandatory
-    cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DPC_NAME,
-        strlen(OIC_JSON_DPC_NAME));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DPC Tag.");
-    cborEncoderResult = cbor_encode_boolean(&doxmMap, doxm->dpc);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DPC Value.");
+    cJSON_AddBoolToObject(jsonDoxm, OIC_JSON_DPC_NAME, doxm->dpc);
 
     //Owner -- Mandatory
-    cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OWNER_NAME,
-        strlen(OIC_JSON_OWNER_NAME));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner tag.");
-    cborEncoderResult = cbor_encode_byte_string(&doxmMap, doxm->owner.id,
-                                                sizeof(doxm->owner.id));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Value");
-
-    cborEncoderResult = cbor_encoder_close_container(&encoder, &doxmMap);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing DoxmMap.");
-
-    *size = encoder.ptr - outPayload;
-    *payload = outPayload;
-    ret = OC_STACK_OK;
+    outLen = 0;
+    b64Ret = b64Encode(doxm->owner.id, sizeof(doxm->owner.id), base64Buff,
+                    sizeof(base64Buff), &outLen);
+    VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
+    cJSON_AddStringToObject(jsonDoxm, OIC_JSON_OWNER_NAME, base64Buff);
 
-exit:
-    if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
-    {
-       // reallocate and try again!
-       OICFree(outPayload);
-       // Since the allocated initial memory failed, double the memory.
-       cborLen += encoder.ptr - encoder.end;
-       cborEncoderResult = CborNoError;
-       ret = DoxmToCBORPayload(doxm, payload, &cborLen);
-    }
+    jsonStr = cJSON_PrintUnformatted(jsonRoot);
 
-    if ((CborNoError != cborEncoderResult) || (OC_STACK_OK != ret))
+exit:
+    if (jsonRoot)
     {
-       OICFree(outPayload);
-       outPayload = NULL;
-       *payload = NULL;
-       *size = 0;
-       ret = OC_STACK_ERROR;
+        cJSON_Delete(jsonRoot);
     }
-
-    return ret;
+    return jsonStr;
 }
 
-OCStackResult CBORPayloadToDoxm(const uint8_t *cborPayload, size_t size,
-                                OicSecDoxm_t **secDoxm)
+OicSecDoxm_t * JSONToDoxmBin(const char * jsonStr)
 {
-    if (NULL == cborPayload || NULL == secDoxm || NULL != *secDoxm)
+
+    if (NULL == jsonStr)
     {
-        return OC_STACK_INVALID_PARAM;
+        return NULL;
     }
 
     OCStackResult ret = OC_STACK_ERROR;
-    *secDoxm = NULL;
+    OicSecDoxm_t *doxm =  NULL;
+    cJSON *jsonDoxm = NULL;
+    cJSON *jsonObj = NULL;
 
-    CborValue doxmCbor = { .parser = NULL };
-    CborParser parser = { .end = NULL };
-    CborError cborFindResult = CborNoError;
-    int cborLen = size;
-    if (0 == size)
-    {
-        cborLen = CBOR_SIZE;
-    }
-    cbor_parser_init(cborPayload, cborLen, 0, &parser, &doxmCbor);
-    CborValue doxmMap = { .parser = NULL } ;
-    OicSecDoxm_t *doxm = NULL;
-    cborFindResult = cbor_value_enter_container(&doxmCbor, &doxmMap);
-    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering Doxm Map.")
+    size_t jsonObjLen = 0;
+    unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
+    uint32_t outLen = 0;
+    B64Result b64Ret = B64_OK;
 
-    doxm = (OicSecDoxm_t *)OICCalloc(1, sizeof(*doxm));
+    cJSON *jsonRoot = cJSON_Parse(jsonStr);
+    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
+
+    jsonDoxm = cJSON_GetObjectItem(jsonRoot, OIC_JSON_DOXM_NAME);
+    VERIFY_NON_NULL(TAG, jsonDoxm, ERROR);
+
+    doxm = (OicSecDoxm_t*)OICCalloc(1, sizeof(OicSecDoxm_t));
     VERIFY_NON_NULL(TAG, doxm, ERROR);
 
-    while (cbor_value_is_valid(&doxmMap))
+    //OxmType -- not Mandatory
+    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OXM_TYPE_NAME);
+    if ((jsonObj) && (cJSON_Array == jsonObj->type))
     {
-        char *name = NULL;
-        size_t len = 0;
-        cborFindResult = cbor_value_dup_text_string(&doxmMap, &name, &len, NULL);
-        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Doxm Map Name.")
-        cborFindResult = cbor_value_advance(&doxmMap);
-        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Doxm Map.")
+        doxm->oxmTypeLen = (size_t)cJSON_GetArraySize(jsonObj);
+        VERIFY_SUCCESS(TAG, doxm->oxmTypeLen > 0, ERROR);
 
-        CborType type = cbor_value_get_type(&doxmMap);
+        doxm->oxmType = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(char *));
+        VERIFY_NON_NULL(TAG, (doxm->oxmType), ERROR);
 
-        //OxmType -- not Mandatory
-        if (0 == strcmp(OIC_JSON_OXM_TYPE_NAME, name))
+        for (size_t i  = 0; i < doxm->oxmTypeLen ; i++)
         {
-            CborValue oxmType = { .parser = NULL };
+            cJSON *jsonOxmTy = cJSON_GetArrayItem(jsonObj, i);
+            VERIFY_NON_NULL(TAG, jsonOxmTy, ERROR);
 
-            cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmTypeLen);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmTypeLen.")
-            VERIFY_SUCCESS(TAG, doxm->oxmTypeLen != 0, ERROR);
-
-            doxm->oxmType = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(*doxm->oxmType));
-            VERIFY_NON_NULL(TAG, doxm->oxmType, ERROR);
+            jsonObjLen = strlen(jsonOxmTy->valuestring) + 1;
+            doxm->oxmType[i] = (char*)OICMalloc(jsonObjLen);
+            VERIFY_NON_NULL(TAG, doxm->oxmType[i], ERROR);
+            strncpy((char *)doxm->oxmType[i], (char *)jsonOxmTy->valuestring, jsonObjLen);
+        }
+    }
 
-            cborFindResult = cbor_value_enter_container(&doxmMap, &oxmType);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmType Array.")
+    //Oxm -- not Mandatory
+    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OXM_NAME);
+    if (jsonObj && cJSON_Array == jsonObj->type)
+    {
+        doxm->oxmLen = (size_t)cJSON_GetArraySize(jsonObj);
+        VERIFY_SUCCESS(TAG, doxm->oxmLen > 0, ERROR);
 
-            int i = 0;
-            size_t len = 0;
-            while (cbor_value_is_valid(&oxmType))
-            {
-                cborFindResult = cbor_value_dup_text_string(&oxmType, &doxm->oxmType[i++],
-                                                            &len, NULL);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding omxType text string.")
-                cborFindResult = cbor_value_advance(&oxmType);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmType.")
-            }
-        }
+        doxm->oxm = (OicSecOxm_t*)OICCalloc(doxm->oxmLen, sizeof(OicSecOxm_t));
+        VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
 
-        //Oxm -- not Mandatory
-        if (0 == strcmp(OIC_JSON_OXM_NAME, name))
+        for (size_t i  = 0; i < doxm->oxmLen ; i++)
         {
-            CborValue oxm = { .parser = NULL };
+            cJSON *jsonOxm = cJSON_GetArrayItem(jsonObj, i);
+            VERIFY_NON_NULL(TAG, jsonOxm, ERROR);
+            doxm->oxm[i] = (OicSecOxm_t)jsonOxm->valueint;
+        }
+    }
 
-            cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmLen);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName array Length.")
-            VERIFY_SUCCESS(TAG, doxm->oxmLen != 0, ERROR);
+    //OxmSel -- Mandatory
+    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OXM_SEL_NAME);
+    if(jsonObj)
+    {
+        VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
+        doxm->oxmSel = (OicSecOxm_t)jsonObj->valueint;
+    }
+    else // PUT/POST JSON may not have oxmsel so set it to the gDoxm->oxmSel
+    {
+        VERIFY_NON_NULL(TAG, gDoxm, ERROR);
+        doxm->oxmSel = gDoxm->oxmSel;
+    }
 
-            doxm->oxm = (OicSecOxm_t *)OICCalloc(doxm->oxmLen, sizeof(*doxm->oxm));
-            VERIFY_NON_NULL(TAG, doxm->oxmType, ERROR);
+    //sct -- Mandatory
+    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_SUPPORTED_CRED_TYPE_NAME);
+    if(jsonObj)
+    {
+        VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
+        doxm->sct = (OicSecCredType_t)jsonObj->valueint;
+    }
+    else // PUT/POST JSON may not have sct so set it to the gDoxm->sct
+    {
+        VERIFY_NON_NULL(TAG, gDoxm, ERROR);
+        doxm->sct = gDoxm->sct;
+    }
 
-            cborFindResult = cbor_value_enter_container(&doxmMap, &oxm);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmName Array.")
+    //Owned -- Mandatory
+    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OWNED_NAME);
+    if(jsonObj)
+    {
+        VERIFY_SUCCESS(TAG, (cJSON_True == jsonObj->type || cJSON_False == jsonObj->type), ERROR);
+        doxm->owned = jsonObj->valueint;
+    }
+    else // PUT/POST JSON may not have owned so set it to the gDomx->owned
+    {
+        VERIFY_NON_NULL(TAG, gDoxm, ERROR);
+        doxm->owned = gDoxm->owned;
+    }
 
-            int i = 0;
-            while (cbor_value_is_valid(&oxm))
+    //DeviceId -- Mandatory
+    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_DEVICE_ID_NAME);
+    if(jsonObj)
+    {
+        VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
+        if(cJSON_String == jsonObj->type)
+        {
+            //Check for empty string, in case DeviceId field has not been set yet
+            if (jsonObj->valuestring[0])
             {
-                cborFindResult = cbor_value_get_int(&oxm, (int *) &doxm->oxm[i++]);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName Value")
-                cborFindResult = cbor_value_advance(&oxm);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmName.")
+                outLen = 0;
+                b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff,
+                        sizeof(base64Buff), &outLen);
+                VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(doxm->deviceID.id)),
+                                ERROR);
+                memcpy(doxm->deviceID.id, base64Buff, outLen);
             }
         }
+    }
+    else // PUT/POST JSON will not have deviceID so set it to the gDoxm->deviceID.id
+    {
+        VERIFY_NON_NULL(TAG, gDoxm, ERROR);
+        memcpy((char *)doxm->deviceID.id, (char *)gDoxm->deviceID.id, sizeof(doxm->deviceID.id));
+    }
 
-        if (0 == strcmp(OIC_JSON_OXM_SEL_NAME, name))
-        {
-            cborFindResult = cbor_value_get_int(&doxmMap, (int *) &doxm->oxmSel);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sel Name Value.")
-        }
-
-        if (0 == strcmp(OIC_JSON_SUPPORTED_CRED_TYPE_NAME, name))
-        {
-            cborFindResult = cbor_value_get_int(&doxmMap, (int *) &doxm->sct);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sct Name Value.")
-        }
-
-        if (0 == strcmp(OIC_JSON_OWNED_NAME, name))
+    //DPC -- Mandatory
+    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_DPC_NAME);
+    if(jsonObj)
+    {
+        VERIFY_SUCCESS(TAG, (cJSON_True == jsonObj->type || cJSON_False == jsonObj->type), ERROR);
+        doxm->dpc = jsonObj->valueint;
+    }
+    else // PUT/POST JSON may not have owned so set it to the gDomx->dpc
+    {
+        if(NULL != gDoxm)
         {
-            cborFindResult = cbor_value_get_boolean(&doxmMap, &doxm->owned);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owned Value.")
+            doxm->dpc = gDoxm->dpc;
         }
-
-        if (0 == strcmp(OIC_JSON_DPC_NAME, name))
+        else
         {
-            cborFindResult = cbor_value_get_boolean(&doxmMap, &doxm->dpc);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding DPC Value.")
+            doxm->dpc = false; // default is false
         }
+    }
 
-        if (0 == strcmp(OIC_JSON_DEVICE_ID_NAME, name))
-        {
-            uint8_t *id = NULL;
-            cborFindResult = cbor_value_dup_byte_string(&doxmMap, &id, &len, NULL);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding DeviceId Value.")
-            memcpy(doxm->deviceID.id, id, len);
-            OICFree(id);
-        }
-        if (0 == strcmp(OIC_JSON_OWNER_NAME, name))
-        {
-            uint8_t *id = NULL;
-            cborFindResult = cbor_value_dup_byte_string(&doxmMap, &id , &len, NULL);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owner Name Value.")
-            memcpy(doxm->owner.id, id, len);
-            OICFree(id);
-        }
-        if (CborMapType != type && cbor_value_is_valid(&doxmMap))
-        {
-            cborFindResult = cbor_value_advance(&doxmMap);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing DoxmMap.")
-        }
-        OICFree(name);
+    //Owner -- will be empty when device status is unowned.
+    jsonObj = cJSON_GetObjectItem(jsonDoxm, OIC_JSON_OWNER_NAME);
+    if(true == doxm->owned)
+    {
+        VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+    }
+    if(jsonObj)
+    {
+        VERIFY_SUCCESS(TAG, (cJSON_String == jsonObj->type), ERROR);
+        outLen = 0;
+        b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff,
+                sizeof(base64Buff), &outLen);
+        VERIFY_SUCCESS(TAG, ((b64Ret == B64_OK) && (outLen <= sizeof(doxm->owner.id))), ERROR);
+        memcpy(doxm->owner.id, base64Buff, outLen);
     }
 
-    *secDoxm = doxm;
     ret = OC_STACK_OK;
 
 exit:
-    if (CborNoError != cborFindResult)
+    cJSON_Delete(jsonRoot);
+    if (OC_STACK_OK != ret)
     {
-        OIC_LOG (ERROR, TAG, "CBORPayloadToDoxm failed!!!");
         DeleteDoxmBinData(doxm);
         doxm = NULL;
-        ret = OC_STACK_ERROR;
     }
-    return ret;
+
+    return doxm;
 }
 
 /**
@@ -419,16 +363,20 @@ static bool UpdatePersistentStorage(OicSecDoxm_t * doxm)
 
     if (NULL != doxm)
     {
-        // Convert Doxm data into CBOR for update to persistent storage
-        uint8_t *payload = NULL;
-        size_t size = 0;
-        OCStackResult res = DoxmToCBORPayload(doxm, &payload, &size);
-        if (payload && (OC_STACK_OK == res)
-            && (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, payload, size)))
+        // Convert Doxm data into JSON for update to persistent storage
+        char *jsonStr = BinToDoxmJSON(doxm);
+        if (jsonStr)
         {
+            cJSON *jsonDoxm = cJSON_Parse(jsonStr);
+            OICFree(jsonStr);
+
+            if (jsonDoxm &&
+                    (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_DOXM_NAME, jsonDoxm)))
+            {
                 bRet = true;
+            }
+            cJSON_Delete(jsonDoxm);
         }
-        OICFree(payload);
     }
 
     return bRet;
@@ -459,111 +407,109 @@ static bool ValidateQuery(const char * query)
 
     ParseQueryIterInit((unsigned char*)query, &parseIter);
 
-    while (GetNextQuery(&parseIter))
+    while(GetNextQuery(&parseIter))
     {
-        if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
+        if(strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
         {
             bOwnedQry = true;
-            if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
+            if((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
                     (gDoxm->owned))
             {
                 bOwnedMatch = true;
             }
-            else if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_FALSE, parseIter.valLen) == 0)
+            else if((strncasecmp((char *)parseIter.valPos, OIC_SEC_FALSE, parseIter.valLen) == 0)
                     && (!gDoxm->owned))
             {
                 bOwnedMatch = true;
             }
         }
 
-        if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_DEVICE_ID_NAME, parseIter.attrLen) == 0)
+        if(strncasecmp((char *)parseIter.attrPos, OIC_JSON_DEVICE_ID_NAME, parseIter.attrLen) == 0)
         {
             bDeviceIDQry = true;
             OicUuid_t subject = {.id={0}};
+            unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
+            uint32_t outLen = 0;
+            B64Result b64Ret = B64_OK;
+
+            b64Ret = b64Decode((char *)parseIter.valPos, parseIter.valLen, base64Buff,
+                                           sizeof(base64Buff), &outLen);
 
-            memcpy(subject.id, parseIter.valPos, parseIter.valLen);
-            if (0 == memcmp(&gDoxm->deviceID.id, &subject.id, sizeof(gDoxm->deviceID.id)))
+            VERIFY_SUCCESS(TAG, (B64_OK == b64Ret && outLen <= sizeof(subject.id)), ERROR);
+                       memcpy(subject.id, base64Buff, outLen);
+            if(0 == memcmp(&gDoxm->deviceID.id, &subject.id, sizeof(gDoxm->deviceID.id)))
             {
                 bDeviceIDMatch = true;
             }
         }
     }
 
+exit:
     return ((bOwnedQry ? bOwnedMatch : true) && (bDeviceIDQry ? bDeviceIDMatch : true));
 }
 
 static OCEntityHandlerResult HandleDoxmGetRequest (const OCEntityHandlerRequest * ehRequest)
 {
+    char* jsonStr = NULL;
     OCEntityHandlerResult ehRet = OC_EH_OK;
 
-    OIC_LOG(DEBUG, TAG, "Doxm EntityHandle processing GET request");
+    OIC_LOG (DEBUG, TAG, "Doxm EntityHandle processing GET request");
 
     //Checking if Get request is a query.
-    if (ehRequest->query)
+    if(ehRequest->query)
     {
-        OIC_LOG(DEBUG, TAG, "HandleDoxmGetRequest processing query");
-        if (!ValidateQuery(ehRequest->query))
+        OIC_LOG (DEBUG, TAG, "HandleDoxmGetRequest processing query");
+        if(!ValidateQuery(ehRequest->query))
         {
             ehRet = OC_EH_ERROR;
         }
     }
 
     /*
-     * For GET or Valid Query request return doxm resource CBOR payload.
+     * For GET or Valid Query request return doxm resource json payload.
      * For non-valid query return NULL json payload.
-     * A device will 'always' have a default Doxm, so DoxmToCBORPayload will
+     * A device will 'always' have a default Doxm, so BinToDoxmJSON will
      * return valid doxm resource json.
      */
-    uint8_t *payload = NULL;
 
-    if (ehRet == OC_EH_OK)
-    {
-        size_t size = 0;
-        if (OC_STACK_OK != DoxmToCBORPayload(gDoxm, &payload, &size))
-        {
-            payload = NULL;
-        }
-    }
+    jsonStr = (ehRet == OC_EH_OK) ? BinToDoxmJSON(gDoxm) : NULL;
 
     // Send response payload to request originator
-    if (OC_STACK_OK != SendSRMCBORResponse(ehRequest, ehRet, payload))
+    if(OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, jsonStr))
     {
-        OIC_LOG(ERROR, TAG, "SendSRMCBORResponse failed in HandleDoxmGetRequest");
+        OIC_LOG (ERROR, TAG, "SendSRMResponse failed in HandleDoxmGetRequest");
     }
 
-    OICFree(payload);
+    OICFree(jsonStr);
 
     return ehRet;
 }
 
-static OCEntityHandlerResult HandleDoxmPutRequest(const OCEntityHandlerRequest * ehRequest)
+static OCEntityHandlerResult HandleDoxmPutRequest (const OCEntityHandlerRequest * ehRequest)
 {
     OIC_LOG (DEBUG, TAG, "Doxm EntityHandle  processing PUT request");
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
-    OicUuid_t emptyOwner = {.id = {0} };
+    OicUuid_t emptyOwner = {.id = {0}};
 
     /*
-     * Convert CBOR Doxm data into binary. This will also validate
+     * Convert JSON Doxm data into binary. This will also validate
      * the Doxm data received.
      */
-    uint8_t *payload = ((OCSecurityPayload *)ehRequest->payload)->securityData1;
-    OicSecDoxm_t *newDoxm = NULL;
+    OicSecDoxm_t* newDoxm = JSONToDoxmBin(((OCSecurityPayload*)ehRequest->payload)->securityData);
 
-    if (payload)
+    if (newDoxm)
     {
-        OCStackResult res = CBORPayloadToDoxm(payload, CBOR_SIZE, &newDoxm);
-
-        if (newDoxm && OC_STACK_OK == res)
+        // Iotivity SRM ONLY supports OIC_JUST_WORKS now
+        if (OIC_JUST_WORKS == newDoxm->oxmSel)
         {
-            // Iotivity SRM ONLY supports OIC_JUST_WORKS now
-            if (OIC_JUST_WORKS == newDoxm->oxmSel)
+            if ((false == gDoxm->owned) && (false == newDoxm->owned))
             {
                 /*
                  * If current state of the device is un-owned, enable
                  * anonymous ECDH cipher in tinyDTLS so that Provisioning
                  * tool can initiate JUST_WORKS ownership transfer process.
                  */
-                if ((false == gDoxm->owned) && (false == newDoxm->owned))
+                if(memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
                 {
                     OIC_LOG (INFO, TAG, "Doxm EntityHandle  enabling AnonECDHCipherSuite");
 #ifdef __WITH_DTLS__
@@ -577,13 +523,13 @@ static OCEntityHandlerResult HandleDoxmPutRequest(const OCEntityHandlerRequest *
                     //Save the owner's UUID to derive owner credential
                     memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
 
-                    // OCServerRequest *request = (OCServerRequest *)ehRequest->requestHandle;
-                    // Generating OwnerPSK
-                    // OIC_LOG (INFO, TAG, "Doxm EntityHandle  generating OwnerPSK");
-                    // Generate new credential for provisioning tool
-                    // ehRet = AddOwnerPSK((CAEndpoint_t *)&request->devAddr, newDoxm,
-                    //       (uint8_t*) OXM_JUST_WORKS, strlen(OXM_JUST_WORKS));
-                    // VERIFY_SUCCESS(TAG, OC_EH_OK == ehRet, ERROR);
+//                    OCServerRequest *request = (OCServerRequest *)ehRequest->requestHandle;
+//                    //Generating OwnerPSK
+//                    OIC_LOG (INFO, TAG, "Doxm EntityHandle  generating OwnerPSK");
+//                    //Generate new credential for provisioning tool
+//                    ehRet = AddOwnerPSK((CAEndpoint_t *)&request->devAddr, newDoxm,
+//                            (uint8_t*) OXM_JUST_WORKS, strlen(OXM_JUST_WORKS));
+//                    VERIFY_SUCCESS(TAG, OC_EH_OK == ehRet, ERROR);
 
                     // Update new state in persistent storage
                     if (true == UpdatePersistentStorage(gDoxm))
@@ -596,10 +542,10 @@ static OCEntityHandlerResult HandleDoxmPutRequest(const OCEntityHandlerRequest *
                         ehRet = OC_EH_ERROR;
                     }
 
-                   /*
-                    * Disable anonymous ECDH cipher in tinyDTLS since device is now
-                    * in owned state.
-                    */
+                    /*
+                     * Disable anonymous ECDH cipher in tinyDTLS since device is now
+                     * in owned state.
+                     */
                     CAResult_t caRes = CA_STATUS_OK;
                     caRes = CAEnableAnonECDHCipherSuite(false);
                     VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
@@ -613,7 +559,7 @@ static OCEntityHandlerResult HandleDoxmPutRequest(const OCEntityHandlerRequest *
                 }
             }
         }
-        else if (OIC_RANDOM_DEVICE_PIN == newDoxm->oxmSel)
+        else if(OIC_RANDOM_DEVICE_PIN == newDoxm->oxmSel)
         {
             if ((false == gDoxm->owned) && (false == newDoxm->owned))
             {
@@ -626,7 +572,7 @@ static OCEntityHandlerResult HandleDoxmPutRequest(const OCEntityHandlerRequest *
                 {
                     gDoxm->oxmSel = newDoxm->oxmSel;
                     //Update new state in persistent storage
-                    if ((UpdatePersistentStorage(gDoxm) == true))
+                    if((UpdatePersistentStorage(gDoxm) == true))
                     {
                         ehRet = OC_EH_OK;
                     }
@@ -675,7 +621,7 @@ static OCEntityHandlerResult HandleDoxmPutRequest(const OCEntityHandlerRequest *
                     memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
 
                     //Update new state in persistent storage
-                    if (UpdatePersistentStorage(gDoxm) == true)
+                    if((UpdatePersistentStorage(gDoxm) == true))
                     {
                         ehRet = OC_EH_OK;
                     }
@@ -735,16 +681,19 @@ exit:
     }
 
     //Send payload to request originator
-    if (OC_STACK_OK != SendSRMCBORResponse(ehRequest, ehRet, NULL))
+    if(OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, NULL))
     {
-        OIC_LOG(ERROR, TAG, "SendSRMCBORResponse failed in HandleDoxmPostRequest");
+        OIC_LOG (ERROR, TAG, "SendSRMResponse failed in HandlePstatPostRequest");
     }
     DeleteDoxmBinData(newDoxm);
 
     return ehRet;
 }
 
-OCEntityHandlerResult DoxmEntityHandler(OCEntityHandlerFlag flag,
+/*
+ * This internal method is the entity handler for DOXM resources.
+ */
+OCEntityHandlerResult DoxmEntityHandler (OCEntityHandlerFlag flag,
                                         OCEntityHandlerRequest * ehRequest,
                                         void* callbackParam)
 {
@@ -756,10 +705,10 @@ OCEntityHandlerResult DoxmEntityHandler(OCEntityHandlerFlag flag,
         return ehRet;
     }
 
+
     if (flag & OC_REQUEST_FLAG)
     {
-        OIC_LOG(DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
-
+        OIC_LOG (DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
         switch (ehRequest->method)
         {
             case OC_REST_GET:
@@ -772,7 +721,7 @@ OCEntityHandlerResult DoxmEntityHandler(OCEntityHandlerFlag flag,
 
             default:
                 ehRet = OC_EH_ERROR;
-                SendSRMCBORResponse(ehRequest, ehRet, NULL);
+                SendSRMResponse(ehRequest, ehRet, NULL);
                 break;
         }
     }
@@ -780,16 +729,20 @@ OCEntityHandlerResult DoxmEntityHandler(OCEntityHandlerFlag flag,
     return ehRet;
 }
 
+/*
+ * This internal method is used to create '/oic/sec/doxm' resource.
+ */
 OCStackResult CreateDoxmResource()
 {
-    OCStackResult ret = OCCreateResource(&gDoxmHandle,
-                                         OIC_RSRC_TYPE_SEC_DOXM,
-                                         OIC_MI_DEF,
-                                         OIC_RSRC_DOXM_URI,
-                                         DoxmEntityHandler,
-                                         NULL,
-                                         OC_OBSERVABLE | OC_SECURE |
-                                         OC_EXPLICIT_DISCOVERABLE);
+    OCStackResult ret;
+
+    ret = OCCreateResource(&gDoxmHandle,
+                           OIC_RSRC_TYPE_SEC_DOXM,
+                           OIC_MI_DEF,
+                           OIC_RSRC_DOXM_URI,
+                           DoxmEntityHandler,
+                           NULL,
+                           OC_OBSERVABLE | OC_SECURE | OC_EXPLICIT_DISCOVERABLE);
 
     if (OC_STACK_OK != ret)
     {
@@ -803,6 +756,7 @@ OCStackResult CreateDoxmResource()
  * Checks if DeviceID is generated during provisioning for the new device.
  * If DeviceID is NULL then generates the new DeviceID.
  * Once DeviceID is assigned to the device it does not change for the lifetime of the device.
+ *
  */
 static OCStackResult CheckDeviceID()
 {
@@ -841,44 +795,46 @@ static OCStackResult CheckDeviceID()
 
 /**
  * Get the default value.
- *
- * @return the default value of doxm, @ref OicSecDoxm_t.
+ * @retval  the gDefaultDoxm pointer;
  */
 static OicSecDoxm_t* GetDoxmDefault()
 {
-    OIC_LOG(DEBUG, TAG, "GetDoxmToDefault");
+    OIC_LOG (DEBUG, TAG, "GetDoxmToDefault");
     return &gDefaultDoxm;
 }
 
+/**
+ * This method is used by SRM to retrieve DOXM resource data.
+ *
+ * @retval  reference to @ref OicSecDoxm_t, binary format of Doxm resource data
+ */
 const OicSecDoxm_t* GetDoxmResourceData()
 {
     return gDoxm;
 }
 
+/**
+ * Initialize DOXM resource by loading data from persistent storage.
+ *
+ * @retval  OC_STACK_OK for Success, otherwise some error value
+ */
 OCStackResult InitDoxmResource()
 {
     OCStackResult ret = OC_STACK_ERROR;
 
     //Read DOXM resource from PS
-    uint8_t *data = NULL;
-    size_t size = 0;
-    ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_DOXM_NAME, &data, &size);
-    // If database read failed
-    if (OC_STACK_OK != ret)
-    {
-       OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
-    }
-    if (data)
+    char* jsonSVRDatabase = GetSVRDatabase();
+    if(jsonSVRDatabase)
     {
-       // Read DOXM resource from PS
-       ret = CBORPayloadToDoxm(data, size, &gDoxm);
+        //Convert JSON DOXM into binary format
+        gDoxm = JSONToDoxmBin(jsonSVRDatabase);
     }
     /*
      * If SVR database in persistent storage got corrupted or
      * is not available for some reason, a default doxm is created
      * which allows user to initiate doxm provisioning again.
      */
-     if ((OC_STACK_OK != ret) || !data || !gDoxm)
+    if(!jsonSVRDatabase || !gDoxm)
     {
         gDoxm = GetDoxmDefault();
     }
@@ -900,20 +856,28 @@ OCStackResult InitDoxmResource()
     {
         OIC_LOG (ERROR, TAG, "CheckDeviceID failed");
     }
-    OICFree(data);
+    OICFree(jsonSVRDatabase);
     return ret;
 }
 
+/**
+ * Perform cleanup for DOXM resources.
+ *
+ * @return
+ * OC_STACK_OK    - no error
+ * OC_STACK_ERROR - stack process error
+ *
+ */
 OCStackResult DeInitDoxmResource()
 {
     OCStackResult ret = OCDeleteResource(gDoxmHandle);
-    if (gDoxm  != &gDefaultDoxm)
+    if(gDoxm  != &gDefaultDoxm)
     {
         DeleteDoxmBinData(gDoxm);
     }
     gDoxm = NULL;
 
-    if (OC_STACK_OK == ret)
+    if(OC_STACK_OK == ret)
     {
         return OC_STACK_OK;
     }
@@ -923,9 +887,15 @@ OCStackResult DeInitDoxmResource()
     }
 }
 
+
+/**
+ * This method returns the SRM device ID for this device.
+ *
+ * @retval  OC_STACK_OK for Success, otherwise some error value
+ */
 OCStackResult GetDoxmDeviceID(OicUuid_t *deviceID)
 {
-    if (deviceID && gDoxm)
+    if(deviceID && gDoxm)
     {
        *deviceID = gDoxm->deviceID;
         return OC_STACK_OK;
@@ -933,13 +903,17 @@ OCStackResult GetDoxmDeviceID(OicUuid_t *deviceID)
     return OC_STACK_ERROR;
 }
 
+/**
+ * @brief Gets the OicUuid_t value for the owner of this device.
+ *
+ * @return OC_STACK_OK if devOwner is a valid UUID, otherwise OC_STACK_ERROR.
+ */
 OCStackResult GetDoxmDevOwnerId(OicUuid_t *devOwner)
 {
     OCStackResult retVal = OC_STACK_ERROR;
-    if (gDoxm)
+    if(gDoxm)
     {
-        if (gDoxm->owned)
-        {
+        if(gDoxm->owned) {
             *devOwner = gDoxm->owner; // TODO change to devOwner when available
             retVal = OC_STACK_OK;
         }
old mode 100755 (executable)
new mode 100644 (file)
index dbdcbdf..7a72c87
@@ -525,12 +525,11 @@ static OCEntityHandlerResult HandleDpairingPutRequest (const OCEntityHandlerRequ
             acl.recurrences = pdAcl->recurrences;
             acl.prdRecrLen = pdAcl->prdRecrLen;
 
-            size_t size = 0;
-            uint8_t *payload = NULL;
-            if (OC_STACK_OK == AclToCBORPayload(&acl, &payload, &size))
+            char* aclJson = BinToAclJSON(&acl);
+            if (aclJson)
             {
-                InstallNewACL(payload, size);
-                OICFree(payload);
+                InstallNewACL(aclJson);
+                OICFree(aclJson);
             }
         }
 
@@ -664,3 +663,6 @@ OCStackResult DeInitDpairingResource()
         return OC_STACK_ERROR;
     }
 }
+
+
+
index f1354aa..5652236 100644 (file)
@@ -1,24 +1,24 @@
-//******************************************************************
-//
-// Copyright 2015 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include <memory.h>
+/*****************************************************************
+ *
+ * Copyright 2015 Samsung Electronics All Rights Reserved.
+ *
+ *
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * *****************************************************************/
+
+ #include <memory.h>
 
 #include "ocstack.h"
 #include "ocrandom.h"
@@ -204,3 +204,4 @@ int32_t GetDtlsPskForRandomPinOxm( CADtlsPskCredType_t type,
     return ret;
 }
 #endif //__WITH_DTLS__
+
index 02c984a..ca614ec 100644 (file)
@@ -1,23 +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.
+ *
+ * *****************************************************************/
 #include <string.h>
 #include <math.h>
 #include "pbkdf2.h"
 
 #define TAG "PBDKF2"
 #define XOR_BUF(in, out, bufSize)\
-do \
-{\
+do{\
     size_t i=0;\
-    for (i=0; i< (bufSize); i++)\
+    for(i=0; i< (bufSize); i++)\
     {\
         (out)[i] = (in)[i] ^ (out)[i];\
     }\
-} while(0)\
+}while(0)\
+
 
 static int isLittle()
 {
index d0cddc1..088496a 100644 (file)
@@ -17,7 +17,6 @@
 // limitations under the License.
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#include <string.h>
 
 #include "oic_malloc.h"
 #include "policyengine.h"
 #include "srmutility.h"
 #include "doxmresource.h"
 #include "iotvticalendar.h"
+#include <string.h>
 
 #define TAG "SRM-PE"
 
+/**
+ * Return the uint16_t CRUDN permission corresponding to passed CAMethod_t.
+ */
 uint16_t GetPermissionFromCAMethod_t(const CAMethod_t method)
 {
     uint16_t perm = 0;
-    switch (method)
+    switch(method)
     {
         case CA_GET:
             perm = (uint16_t)PERMISSION_READ;
@@ -56,11 +59,10 @@ uint16_t GetPermissionFromCAMethod_t(const CAMethod_t method)
 }
 
 /**
- * Compares two OicUuid_t structs.
- *
+ * @brief Compares two OicUuid_t structs.
  * @return true if the two OicUuid_t structs are equal, else false.
  */
-static bool UuidCmp(OicUuid_t *firstId, OicUuid_t *secondId)
+bool UuidCmp(OicUuid_t *firstId, OicUuid_t *secondId)
 {
     // TODO use VERIFY macros to check for null when they are merged.
     if(NULL == firstId || NULL == secondId)
@@ -77,9 +79,12 @@ static bool UuidCmp(OicUuid_t *firstId, OicUuid_t *secondId)
     return true;
 }
 
+/**
+ * Set the state and clear other stateful context vars.
+ */
 void SetPolicyEngineState(PEContext_t *context, const PEState_t state)
 {
-    if (NULL == context)
+    if(NULL == context)
     {
         return;
     }
@@ -101,11 +106,11 @@ void SetPolicyEngineState(PEContext_t *context, const PEState_t state)
 }
 
 /**
- * Compare the request's subject to DevOwner.
+ * @brief Compare the request's subject to DevOwner.
  *
- * @return true if context->subjectId == GetDoxmDevOwner(), else false.
+ * @return true if context->subjectId == GetDoxmDevOwner(), else false
  */
-static bool IsRequestFromDevOwner(PEContext_t *context)
+bool IsRequestFromDevOwner(PEContext_t *context)
 {
     bool retVal = false;
     OicUuid_t owner;
@@ -123,6 +128,7 @@ static bool IsRequestFromDevOwner(PEContext_t *context)
     return retVal;
 }
 
+
 inline static bool IsRequestSubjectEmpty(PEContext_t *context)
 {
     OicUuid_t emptySubject = {.id={}};
@@ -136,18 +142,17 @@ inline static bool IsRequestSubjectEmpty(PEContext_t *context)
             true : false;
 }
 
+
 /**
  * Bitwise check to see if 'permission' contains 'request'.
- *
- * @param permission is the allowed CRUDN permission.
- * @param request is the CRUDN permission being requested.
- *
+ * @param   permission  The allowed CRUDN permission.
+ * @param   request     The CRUDN permission being requested.
  * @return true if 'permission' bits include all 'request' bits.
  */
 static inline bool IsPermissionAllowingRequest(const uint16_t permission,
     const uint16_t request)
 {
-    if (request == (request & permission))
+    if(request == (request & permission))
     {
         return true;
     }
@@ -159,7 +164,6 @@ static inline bool IsPermissionAllowingRequest(const uint16_t permission,
 
 /**
  * Compare the passed subject to the wildcard (aka anonymous) subjectId.
- *
  * @return true if 'subject' is the wildcard, false if it is not.
  */
 static inline bool IsWildCardSubject(OicUuid_t *subject)
@@ -183,14 +187,15 @@ static inline bool IsWildCardSubject(OicUuid_t *subject)
 /**
  * Copy the subject, resource and permission into the context fields.
  */
-static void CopyParamsToContext(PEContext_t     *context,
-                                const OicUuid_t *subjectId,
-                                const char      *resource,
-                                const uint16_t  requestedPermission)
+void CopyParamsToContext(
+    PEContext_t     *context,
+    const OicUuid_t *subjectId,
+    const char      *resource,
+    const uint16_t  requestedPermission)
 {
     size_t length = 0;
 
-    if (NULL == context || NULL == subjectId || NULL == resource)
+    if(NULL == context || NULL == subjectId || NULL == resource)
     {
         return;
     }
@@ -199,7 +204,7 @@ static void CopyParamsToContext(PEContext_t     *context,
 
     // Copy the resource string into context.
     length = strlen(resource) + 1;
-    if (0 < length)
+    if(0 < length)
     {
         strncpy(context->resource, resource, length);
         context->resource[length - 1] = '\0';
@@ -209,32 +214,32 @@ static void CopyParamsToContext(PEContext_t     *context,
     context->permission = requestedPermission;
 }
 
+
 /**
  * Check whether 'resource' is getting accessed within the valid time period.
- *
- * @param acl is the ACL to check.
- *
- * @return true if access is within valid time period or if the period or recurrence is not present.
- * false if period and recurrence present and the access is not within valid time period.
+ * @param   acl         The ACL to check.
+ * @return
+ *      true if access is within valid time period or if the period or recurrence is not present.
+ *      false if period and recurrence present and the access is not within valid time period.
  */
 static bool IsAccessWithinValidTime(const OicSecAcl_t *acl)
 {
 #ifndef WITH_ARDUINO //Period & Recurrence not supported on Arduino due
                      //lack of absolute time
-    if (NULL== acl || NULL == acl->periods || 0 == acl->prdRecrLen)
+    if(NULL== acl || NULL == acl->periods || 0 == acl->prdRecrLen)
     {
         return true;
     }
 
     //periods & recurrences rules are paired.
-    if (NULL == acl->recurrences)
+    if(NULL == acl->recurrences)
     {
         return false;
     }
 
-    for (size_t i = 0; i < acl->prdRecrLen; i++)
+    for(size_t i = 0; i < acl->prdRecrLen; i++)
     {
-        if (IOTVTICAL_VALID_ACCESS ==  IsRequestWithinValidTime(acl->periods[i],
+        if(IOTVTICAL_VALID_ACCESS ==  IsRequestWithinValidTime(acl->periods[i],
             acl->recurrences[i]))
         {
             OIC_LOG(INFO, TAG, "Access request is in allowed time period");
@@ -251,23 +256,21 @@ static bool IsAccessWithinValidTime(const OicSecAcl_t *acl)
 
 /**
  * Check whether 'resource' is in the passed ACL.
- *
- * @param resource is the resource being searched.
- * @param acl is the ACL to check.
- *
+ * @param   resource    The resource to search for.
+ * @param   acl         The ACL to check.
  * @return true if 'resource' found, otherwise false.
  */
static bool IsResourceInAcl(const char *resource, const OicSecAcl_t *acl)
+ bool IsResourceInAcl(const char *resource, const OicSecAcl_t *acl)
 {
-    if (NULL== acl || NULL == resource)
+    if(NULL== acl || NULL == resource)
     {
         return false;
     }
 
-     for (size_t n = 0; n < acl->resourcesLen; n++)
+     for(size_t n = 0; n < acl->resourcesLen; n++)
      {
-         if (0 == strcmp(resource, acl->resources[n]) || // TODO null terms?
-             0 == strcmp(WILDCARD_RESOURCE_URI, acl->resources[n]))
+         if(0 == strcmp(resource, acl->resources[n]) || // TODO null terms?
+                 0 == strcmp(WILDCARD_RESOURCE_URI, acl->resources[n]))
          {
              return true;
          }
@@ -281,14 +284,16 @@ static bool IsAccessWithinValidTime(const OicSecAcl_t *acl)
  * Search each ACL for requested resource.
  * If resource found, check for context->permission and period validity.
  * If the ACL is not found locally and AMACL for the resource is found
- * then sends the request to AMS service for the ACL.
+ * then sends the request to AMS service for the ACL
  * Set context->retVal to result from first ACL found which contains
  * correct subject AND resource.
+ *
+ * @retval void
  */
-static void ProcessAccessRequest(PEContext_t *context)
+void ProcessAccessRequest(PEContext_t *context)
 {
     OIC_LOG(DEBUG, TAG, "Entering ProcessAccessRequest()");
-    if (NULL != context)
+    if(NULL != context)
     {
         const OicSecAcl_t *currentAcl = NULL;
         OicSecAcl_t *savePtr = NULL;
@@ -303,7 +308,7 @@ static void ProcessAccessRequest(PEContext_t *context)
             OIC_LOG_V(DEBUG, TAG, "%s: getting ACL..." ,__func__);
             currentAcl = GetACLResourceData(&context->subject, &savePtr);
 
-            if (NULL != currentAcl)
+            if(NULL != currentAcl)
             {
                 // Found the subject, so how about resource?
                 OIC_LOG_V(DEBUG, TAG, "%s:found ACL matching subject" ,__func__);
@@ -311,17 +316,17 @@ static void ProcessAccessRequest(PEContext_t *context)
                 // Subject was found, so err changes to Rsrc not found for now.
                 context->retVal = ACCESS_DENIED_RESOURCE_NOT_FOUND;
                 OIC_LOG_V(DEBUG, TAG, "%s:Searching for resource..." ,__func__);
-                if (IsResourceInAcl(context->resource, currentAcl))
+                if(IsResourceInAcl(context->resource, currentAcl))
                 {
                     OIC_LOG_V(INFO, TAG, "%s:found matching resource in ACL" ,__func__);
                     context->matchingAclFound = true;
 
                     // Found the resource, so it's down to valid period & permission.
                     context->retVal = ACCESS_DENIED_INVALID_PERIOD;
-                    if (IsAccessWithinValidTime(currentAcl))
+                    if(IsAccessWithinValidTime(currentAcl))
                     {
                         context->retVal = ACCESS_DENIED_INSUFFICIENT_PERMISSION;
-                        if (IsPermissionAllowingRequest(currentAcl->permission, context->permission))
+                        if(IsPermissionAllowingRequest(currentAcl->permission, context->permission))
                         {
                             context->retVal = ACCESS_GRANTED;
                         }
@@ -332,9 +337,10 @@ static void ProcessAccessRequest(PEContext_t *context)
             {
                 OIC_LOG_V(INFO, TAG, "%s:no ACL found matching subject for resource %s",__func__, context->resource);
             }
-        } while ((NULL != currentAcl) && (false == context->matchingAclFound));
+        }
+        while((NULL != currentAcl) && (false == context->matchingAclFound));
 
-        if (IsAccessGranted(context->retVal))
+        if(IsAccessGranted(context->retVal))
         {
             OIC_LOG_V(INFO, TAG, "%s:Leaving ProcessAccessRequest(ACCESS_GRANTED)", __func__);
         }
@@ -349,10 +355,20 @@ static void ProcessAccessRequest(PEContext_t *context)
     }
 }
 
-SRMAccessResponse_t CheckPermission(PEContext_t     *context,
-                                    const OicUuid_t *subjectId,
-                                    const char      *resource,
-                                    const uint16_t  requestedPermission)
+/**
+ * Check whether a request should be allowed.
+ * @param   context     Pointer to (Initialized) Policy Engine context to use.
+ * @param   subjectId   Pointer to Id of the requesting entity.
+ * @param   resource    Pointer to URI of Resource being requested.
+ * @param   permission  Requested permission.
+ * @return  ACCESS_GRANTED if request should go through,
+ *          otherwise some flavor of ACCESS_DENIED
+ */
+SRMAccessResponse_t CheckPermission(
+    PEContext_t     *context,
+    const OicUuid_t *subjectId,
+    const char      *resource,
+    const uint16_t  requestedPermission)
 {
     SRMAccessResponse_t retVal = ACCESS_DENIED_POLICY_ENGINE_ERROR;
 
@@ -363,9 +379,9 @@ SRMAccessResponse_t CheckPermission(PEContext_t     *context,
     // Each state machine context can only be processing one request at a time.
     // Therefore if the context is not in AWAITING_REQUEST or AWAITING_AMS_RESPONSE
     // state, return error. Otherwise, change to BUSY state and begin processing request.
-    if (AWAITING_REQUEST == context->state || AWAITING_AMS_RESPONSE == context->state)
+    if(AWAITING_REQUEST == context->state || AWAITING_AMS_RESPONSE == context->state)
     {
-        if (AWAITING_REQUEST == context->state)
+        if(AWAITING_REQUEST == context->state)
         {
             SetPolicyEngineState(context, BUSY);
             CopyParamsToContext(context, subjectId, resource, requestedPermission);
@@ -373,7 +389,7 @@ SRMAccessResponse_t CheckPermission(PEContext_t     *context,
 
         // Before doing any processing, check if request coming
         // from DevOwner and if so, always GRANT.
-        if (IsRequestFromDevOwner(context))
+        if(IsRequestFromDevOwner(context))
         {
             context->retVal = ACCESS_GRANTED;
         }
@@ -385,7 +401,7 @@ SRMAccessResponse_t CheckPermission(PEContext_t     *context,
             ProcessAccessRequest(context);
 
             // If matching ACL not found, and subject != wildcard, try wildcard.
-            if ((false == context->matchingAclFound) && \
+            if((false == context->matchingAclFound) && \
               (false == IsWildCardSubject(&context->subject)))
             {
                 //Saving subject for Amacl check
@@ -402,7 +418,7 @@ SRMAccessResponse_t CheckPermission(PEContext_t     *context,
             }
 
             //No local ACE found for the request so checking Amacl resource
-            if (ACCESS_GRANTED != context->retVal)
+            if(ACCESS_GRANTED != context->retVal)
             {
                 //If subject is not empty then restore the original subject
                 //else keep the subject to WILDCARD_SUBJECT_ID
@@ -429,7 +445,7 @@ SRMAccessResponse_t CheckPermission(PEContext_t     *context,
     // Capture retVal before resetting state for next request.
     retVal = context->retVal;
 
-   if (!context->amsProcessing)
+   if(!context->amsProcessing)
     {
         OIC_LOG(INFO, TAG, "Resetting PE context and PE State to AWAITING_REQUEST");
         SetPolicyEngineState(context, AWAITING_REQUEST);
@@ -439,6 +455,11 @@ exit:
     return retVal;
 }
 
+/**
+ * Initialize the Policy Engine. Call this before calling CheckPermission().
+ * @param   context     Pointer to Policy Engine context to initialize.
+ * @return  OC_STACK_OK for Success, otherwise some error value
+ */
 OCStackResult InitPolicyEngine(PEContext_t *context)
 {
     if(NULL == context)
@@ -456,6 +477,12 @@ OCStackResult InitPolicyEngine(PEContext_t *context)
     return OC_STACK_OK;
 }
 
+/**
+ * De-Initialize the Policy Engine.  Call this before exiting to allow Policy
+ * Engine to do cleanup on context.
+ * @param   context     Pointer to Policy Engine context to de-initialize.
+ * @return  none
+ */
 void DeInitPolicyEngine(PEContext_t *context)
 {
     if(NULL != context)
index bf27d58..719d51b 100644 (file)
 // limitations under the License.
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#ifdef WITH_ARDUINO
-#define __STDC_LIMIT_MACROS
-#endif
 
-#include <stdlib.h>
-#include <string.h>
 #include "ocstack.h"
 #include "logger.h"
 #include "oic_malloc.h"
-#include "ocpayload.h"
-#include "ocpayloadcbor.h"
-#include "payload_logging.h"
 #include "cJSON.h"
 #include "cainterface.h"
 #include "secureresourcemanager.h"
 #include "resourcemanager.h"
 #include "srmresourcestrings.h"
 #include "srmutility.h"
+#include <stdlib.h>
+#include <string.h>
 
 #define TAG  "SRM-PSI"
 
@@ -44,11 +38,11 @@ const size_t DB_FILE_SIZE_BLOCK = 1023;
 /**
  * Gets the Secure Virtual Database size.
  *
- * @param ps pointer of OCPersistentStorage for the SVR name ("acl", "cred", "pstat" etc).
+ * @param ps  pointer of OCPersistentStorage for the SVR name ("acl", "cred", "pstat" etc).
  *
- * @return total size of the SVR database.
+ * @retval  total size of the SVR database.
  */
-static size_t GetSVRDatabaseSize(const OCPersistentStorage* ps)
+size_t GetSVRDatabaseSize(OCPersistentStorage* ps)
 {
     size_t size = 0;
     if (!ps)
@@ -57,7 +51,7 @@ static size_t GetSVRDatabaseSize(const OCPersistentStorage* ps)
     }
     size_t bytesRead  = 0;
     char buffer[DB_FILE_SIZE_BLOCK];
-    FILE* fp = ps->open(SVR_DB_DAT_FILE_NAME, "r");
+    FILE* fp = ps->open(SVR_DB_FILE_NAME, "r");
     if (fp)
     {
         do
@@ -70,7 +64,16 @@ static size_t GetSVRDatabaseSize(const OCPersistentStorage* ps)
     return size;
 }
 
-char* GetSVRDatabase()
+/**
+ * Reads the Secure Virtual Database from PS into dynamically allocated
+ * memory buffer.
+ *
+ * @note Caller of this method MUST use OICFree() method to release memory
+ *       referenced by return value.
+ *
+ * @retval  reference to memory buffer containing SVR database.
+ */
+char * GetSVRDatabase()
 {
     char * jsonStr = NULL;
     FILE * fp = NULL;
@@ -111,6 +114,16 @@ exit:
     return jsonStr;
 }
 
+
+/**
+ * This method is used by a entity handlers of SVR's to update
+ * SVR database.
+ *
+ * @param rsrcName string denoting the SVR name ("acl", "cred", "pstat" etc).
+ * @param jsonObj JSON object containing the SVR contents.
+ *
+ * @retval  OC_STACK_OK for Success, otherwise some error value
+ */
 OCStackResult UpdateSVRDatabase(const char* rsrcName, cJSON* jsonObj)
 {
     OCStackResult ret = OC_STACK_ERROR;
@@ -195,218 +208,3 @@ exit:
 
     return ret;
 }
-
-OCStackResult GetSecureVirtualDatabaseFromPS(const char *rsrcName, uint8_t **data, size_t *size)
-{
-    if (!data || !size)
-    {
-        return OC_STACK_INVALID_PARAM;
-    }
-    OCStackResult ret = OC_STACK_ERROR;
-    *data = NULL;
-
-     FILE *fp = NULL;
-    size_t fileSize = 0;
-
-    OCPersistentStorage *ps = SRMGetPersistentStorageHandler();
-    VERIFY_NON_NULL(TAG, ps, ERROR);
-
-    fileSize = GetSVRDatabaseSize(ps);
-    if (fileSize != 0)
-    {
-        OIC_LOG_V(DEBUG, TAG, "File Read Size: %zu", fileSize);
-        uint8_t *fsData = (uint8_t *)OICCalloc(1, fileSize);
-        VERIFY_NON_NULL(TAG, fsData, ERROR);
-
-        FILE *fp = ps->open(SVR_DB_DAT_FILE_NAME, "r");
-        VERIFY_NON_NULL(TAG, fp, ERROR);
-        size_t itemsRead = ps->read(fsData, 1, fileSize, fp);
-        if (itemsRead == fileSize)
-        {
-            VERIFY_NON_NULL(TAG, fsData, ERROR);
-            if (rsrcName != NULL)
-            {
-                CborParser parser = { .end = NULL };
-                CborValue cbor =  { .parser = NULL };
-                cbor_parser_init(fsData, fileSize, 0, &parser, &cbor);
-                CborValue cborValue =  { .parser = NULL };
-                CborError cborFindResult = cbor_value_enter_container(&cbor, &cborValue);
-
-                while (cbor_value_is_valid(&cborValue))
-                {
-                    char *name = NULL;
-                    size_t len = 0;
-                    cborFindResult = cbor_value_dup_text_string(&cborValue, &name, &len, NULL);
-                    VERIFY_SUCCESS(TAG, cborFindResult == CborNoError, ERROR);
-                    cborFindResult = cbor_value_advance(&cborValue);
-                    VERIFY_SUCCESS(TAG, cborFindResult == CborNoError, ERROR);
-                    if (strcmp(name, rsrcName) == 0)
-                    {
-                        cborFindResult = cbor_value_dup_byte_string(&cborValue, data, size, NULL);
-                        VERIFY_SUCCESS(TAG, cborFindResult == CborNoError, ERROR);
-                        ret = OC_STACK_OK;
-                        OICFree(fsData);
-                        OICFree(name);
-                        goto exit;
-                    }
-                    OICFree(name);
-                    cborFindResult = cbor_value_advance(&cborValue);
-                    VERIFY_SUCCESS(TAG, cborFindResult == CborNoError, ERROR);
-                }
-            }
-            // return everything in case rsrcName is NULL
-            else
-            {
-                *data = fsData;
-                *size = fileSize;
-            }
-        }
-    }
-    else
-    {
-        OIC_LOG(ERROR, TAG, "Unable to open SVR database to read!! ");
-    }
-
-exit:
-    if (ps && fp)
-    {
-        ps->close(fp);
-    }
-    return ret;
-}
-
-OCStackResult UpdateSecureResourceInPS(const char* rsrcName, const uint8_t* psPayload, size_t psSize)
-{
-    /*
-     * This function stores cbor payload of each resource by appending resource name.
-     */
-    if (!rsrcName || !psPayload)
-    {
-        return OC_STACK_INVALID_PARAM;
-    }
-    OCStackResult ret = OC_STACK_ERROR;
-
-    size_t cborSize = 0;
-    uint8_t *dbData = NULL;
-    uint8_t *outPayload = NULL;
-    size_t dbSize = 0;
-
-    ret = GetSecureVirtualDatabaseFromPS(NULL, &dbData, &dbSize);
-    if (dbData && dbSize != 0)
-    {
-        uint8_t size = dbSize + psSize;
-
-        outPayload = (uint8_t *)OICCalloc(1, size);
-        VERIFY_NON_NULL(TAG, outPayload, ERROR);
-
-        CborEncoder encoder = { { .ptr = NULL }, .end = 0 };
-        cbor_encoder_init(&encoder, outPayload, size, 0);
-        {
-            CborEncoder map = { {.ptr = NULL }, .end = 0 };
-            CborError cborEncoderResult = cbor_encoder_create_map(&encoder, &map, CborIndefiniteLength);
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Creating PS Interface Map.");
-            {
-                bool found = false;
-                CborValue cbor = { .parser = NULL };
-                CborParser parser = { .end = NULL };
-                cbor_parser_init(dbData, size, 0, &parser, &cbor);
-
-                CborValue cborValue = { .parser = NULL };
-                CborError cborFindResult = CborNoError;
-
-                if (cbor_value_is_container(&cbor))
-                {
-                    cborFindResult = cbor_value_enter_container(&cbor, &cborValue);
-                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering PS Interface Map.");
-                }
-
-                while (cbor_value_is_valid(&cborValue))
-                {
-                    char *name = NULL;
-                    size_t len = 0;
-                    cborFindResult = cbor_value_dup_text_string(&cborValue, &name, &len, NULL);
-                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Duplicating Value.");
-                    cborFindResult = cbor_value_advance(&cborValue);
-                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Value.");
-
-                    cborEncoderResult = cbor_encode_text_string(&map, name, strlen(name));
-                    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Copying Text Str Value.");
-
-                    if (strcmp(name, rsrcName) == 0)
-                    {
-                        cborEncoderResult = cbor_encode_byte_string(&map, psPayload, psSize);
-                        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Encoding Byte String.");
-                        found = true;
-                    }
-                    else
-                    {
-                        uint8_t *byteString = NULL;
-                        size_t byteLen = 0;
-                        cborFindResult = cbor_value_dup_byte_string(&cborValue, &byteString, &byteLen, NULL);
-                        VERIFY_SUCCESS(TAG, cborFindResult == CborNoError, ERROR);
-                        if (byteString)
-                        {
-                            cborEncoderResult = cbor_encode_byte_string(&map, byteString, byteLen);
-                            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed adding value.");
-                        }
-                        OICFree(byteString);
-                    }
-                    OICFree(name);
-                    cbor_value_advance(&cborValue);
-                }
-
-                // This is an exception when the value is not stored in the database.
-                if (!found)
-                {
-                    cborEncoderResult = cbor_encode_text_string(&map, rsrcName, strlen(rsrcName));
-                    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed adding value.");
-                    cborEncoderResult = cbor_encode_byte_string(&map, psPayload, psSize);
-                    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed entering byte string.");
-                }
-            }
-            cborEncoderResult = cbor_encoder_close_container(&encoder, &map);
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed closing container.");
-        }
-        cborSize = encoder.ptr - outPayload;
-    }
-
-    {
-        OCPersistentStorage* ps = SRMGetPersistentStorageHandler();
-        if (ps)
-        {
-            FILE *fp = ps->open(SVR_DB_DAT_FILE_NAME, "w+");
-            if (fp)
-            {
-                size_t numberItems = ps->write(outPayload, 1, cborSize, fp);
-                if (cborSize == numberItems)
-                {
-                    OIC_LOG_V(DEBUG, TAG, "Written %zu bytes into SVR database file", cborSize);
-                    ret = OC_STACK_OK;
-                }
-                else
-                {
-                    OIC_LOG_V(ERROR, TAG, "Failed writing %zu in the database", numberItems);
-                }
-                ps->close(fp);
-            }
-            else
-            {
-                OIC_LOG(ERROR, TAG, "File open failed.");
-            }
-
-        }
-    }
-
-
-exit:
-    if (dbData)
-    {
-        OICFree(dbData);
-    }
-    if (outPayload)
-    {
-        OICFree(outPayload);
-    }
-
-    return ret;
-}
index bfd9ae1..d3ecc27 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#include <stdlib.h>
-#include <string.h>
-
 #include "ocstack.h"
+#include "logger.h"
 #include "oic_malloc.h"
-#include "ocpayload.h"
-#include "payload_logging.h"
+#include "cJSON.h"
 #include "resourcemanager.h"
 #include "pstatresource.h"
 #include "doxmresource.h"
 #include "psinterface.h"
+#include "utlist.h"
+#include "base64.h"
 #include "srmresourcestrings.h"
 #include "srmutility.h"
+#include <stdlib.h>
+#include <string.h>
 
 #define TAG  "SRM-PSTAT"
 
-/** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
- * The value of payload size is increased until reaching below max cbor size. */
-static const uint8_t CBOR_SIZE = 255;
-
-// Max cbor size payload.
-static const uint16_t CBOR_MAX_SIZE = 4400;
-
-// PSTAT Map size - Number of mandatory items
-static const uint8_t PSTAT_MAP_SIZE = 7;
-
 static OicSecDpom_t gSm = SINGLE_SERVICE_CLIENT_DRIVEN;
 static OicSecPstat_t gDefaultPstat =
 {
@@ -75,258 +66,156 @@ void DeletePstatBinData(OicSecPstat_t* pstat)
     }
 }
 
-OCStackResult PstatToCBORPayload(const OicSecPstat_t *pstat, uint8_t **payload, size_t *size)
+char * BinToPstatJSON(const OicSecPstat_t * pstat)
 {
-    if (NULL == pstat || NULL == payload || NULL != *payload || NULL == size)
-    {
-        return OC_STACK_INVALID_PARAM;
-    }
-
-    size_t cborLen = *size;
-    if (0 == cborLen)
+    if(NULL == pstat)
     {
-        cborLen = CBOR_SIZE;
+        return NULL;
     }
 
-    *payload = NULL;
-    *size = 0;
+    cJSON *jsonPstat = NULL;
+    char *jsonStr = NULL;
+    cJSON *jsonSmArray = NULL;
+    char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*) 0)->id)) + 1] = {};
+    uint32_t outLen = 0;
+    B64Result b64Ret = B64_OK;
 
-    OCStackResult ret = OC_STACK_ERROR;
+    cJSON *jsonRoot = cJSON_CreateObject();
+    VERIFY_NON_NULL(TAG, jsonRoot, INFO);
 
-    CborEncoder encoder = { {.ptr = NULL }, .end = 0 };
-    CborEncoder pstatMap = { {.ptr = NULL }, .end = 0 };
-
-    CborError cborEncoderResult = CborNoError;
-
-    uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
-    VERIFY_NON_NULL(TAG, outPayload, ERROR);
-    cbor_encoder_init(&encoder, outPayload, cborLen, 0);
-
-    cborEncoderResult = cbor_encoder_create_map(&encoder, &pstatMap, PSTAT_MAP_SIZE);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Pstat Map.");
-
-    cborEncoderResult = cbor_encode_text_string(&pstatMap, OIC_JSON_ISOP_NAME,
-        strlen(OIC_JSON_ISOP_NAME));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ISOP Name Tag.");
-    cborEncoderResult = cbor_encode_boolean(&pstatMap, pstat->isOp);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ISOP Name Value.");
-
-    cborEncoderResult = cbor_encode_text_string(&pstatMap, OIC_JSON_DEVICE_ID_NAME,
-        strlen(OIC_JSON_DEVICE_ID_NAME));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Tag.");
-    cborEncoderResult = cbor_encode_byte_string(&pstatMap, (uint8_t *)pstat->deviceID.id,
-                                                sizeof(pstat->deviceID.id));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Value.");
-
-    cborEncoderResult = cbor_encode_text_string(&pstatMap, OIC_JSON_COMMIT_HASH_NAME,
-        strlen(OIC_JSON_COMMIT_HASH_NAME));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Commit Hash Tag.");
-    cborEncoderResult = cbor_encode_int(&pstatMap, pstat->commitHash);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Commit Hash Value.");
-
-    cborEncoderResult = cbor_encode_text_string(&pstatMap, OIC_JSON_CM_NAME,
-        strlen(OIC_JSON_CM_NAME));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding CM Name Tag.");
-    cborEncoderResult = cbor_encode_int(&pstatMap, pstat->cm);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding CM Name Value.");
-
-    cborEncoderResult = cbor_encode_text_string(&pstatMap, OIC_JSON_TM_NAME,
-        strlen(OIC_JSON_TM_NAME));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding TM Name Tag.");
-    cborEncoderResult = cbor_encode_int(&pstatMap, pstat->tm);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding TM Name Value.");
-
-    cborEncoderResult = cbor_encode_text_string(&pstatMap, OIC_JSON_OM_NAME,
-        strlen(OIC_JSON_OM_NAME));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding OM Name Tag.");
-    cborEncoderResult = cbor_encode_int(&pstatMap, pstat->om);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding OM Name Value.");
-
-    cborEncoderResult = cbor_encode_text_string(&pstatMap, OIC_JSON_SM_NAME,
-        strlen(OIC_JSON_SM_NAME));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SM Name Tag.");
-    {
-        CborEncoder sm = { {.ptr = NULL }, .end = 0 };
-        cborEncoderResult = cbor_encoder_create_array(&pstatMap, &sm, pstat->smLen);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SM Array.");
+    cJSON_AddItemToObject(jsonRoot, OIC_JSON_PSTAT_NAME, jsonPstat=cJSON_CreateObject());
+    cJSON_AddBoolToObject(jsonPstat, OIC_JSON_ISOP_NAME, pstat->isOp);
 
-        for (size_t i = 0; i < pstat->smLen; i++)
-        {
-            cborEncoderResult = cbor_encode_int(&sm, pstat->sm[i]);
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SM Value in Array.");
-        }
-        cborEncoderResult = cbor_encoder_close_container(&pstatMap, &sm);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing SM Array.");
-    }
-    cborEncoderResult = cbor_encoder_close_container(&encoder, &pstatMap);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Closing PSTAT Map.");
+    b64Ret = b64Encode(pstat->deviceID.id,
+            sizeof(pstat->deviceID.id), base64Buff, sizeof(base64Buff), &outLen);
+    VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
 
-    *size = encoder.ptr - outPayload;
-    *payload = outPayload;
-    ret = OC_STACK_OK;
+    cJSON_AddStringToObject(jsonPstat, OIC_JSON_DEVICE_ID_NAME, base64Buff);
+    cJSON_AddNumberToObject(jsonPstat, OIC_JSON_COMMIT_HASH_NAME, pstat->commitHash);
+    cJSON_AddNumberToObject(jsonPstat, OIC_JSON_CM_NAME, (int)pstat->cm);
+    cJSON_AddNumberToObject(jsonPstat, OIC_JSON_TM_NAME, (int)pstat->tm);
+    cJSON_AddNumberToObject(jsonPstat, OIC_JSON_OM_NAME, (int)pstat->om);
 
-exit:
-    if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
+    cJSON_AddItemToObject(jsonPstat, OIC_JSON_SM_NAME, jsonSmArray = cJSON_CreateArray());
+    VERIFY_NON_NULL(TAG, jsonSmArray, INFO);
+    for (size_t i = 0; i < pstat->smLen; i++)
     {
-        // reallocate and try again!
-        OICFree(outPayload);
-        // Since the allocated initial memory failed, double the memory.
-        cborLen += encoder.ptr - encoder.end;
-        cborEncoderResult = CborNoError;
-        ret = PstatToCBORPayload(pstat, payload, &cborLen);
+        cJSON_AddItemToArray(jsonSmArray, cJSON_CreateNumber((int )pstat->sm[i]));
     }
+    jsonStr = cJSON_Print(jsonRoot);
 
-    if ((CborNoError != cborEncoderResult) || (OC_STACK_OK != ret))
+exit:
+    if (jsonRoot)
     {
-        OICFree(outPayload);
-        outPayload = NULL;
-        *payload = NULL;
-        *size = 0;
-        ret = OC_STACK_ERROR;
+        cJSON_Delete(jsonRoot);
     }
-
-    return ret;
+    return jsonStr;
 }
 
-OCStackResult CBORPayloadToPstat(const uint8_t *cborPayload, const size_t size,
-                                 OicSecPstat_t **secPstat)
+OicSecPstat_t * JSONToPstatBin(const char * jsonStr)
 {
-    if (NULL == cborPayload || NULL == secPstat || NULL != *secPstat)
+    if(NULL == jsonStr)
     {
-        return OC_STACK_INVALID_PARAM;
+        return NULL;
     }
 
     OCStackResult ret = OC_STACK_ERROR;
-    *secPstat = NULL;
-
-    CborValue pstatCbor = { .parser = NULL };
-    CborParser parser = { .end = NULL };
-    CborError cborFindResult = CborNoError;
-    int cborLen = size;
-    if (0 == size)
-    {
-        cborLen = CBOR_SIZE;
-    }
-    cbor_parser_init(cborPayload, cborLen, 0, &parser, &pstatCbor);
-    CborValue pstatMap = { .parser = NULL } ;
     OicSecPstat_t *pstat = NULL;
-    char *name = NULL;
-    cborFindResult = cbor_value_enter_container(&pstatCbor, &pstatMap);
-    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding PSTAT Map.");
-
-    pstat = (OicSecPstat_t *)OICCalloc(1, sizeof(OicSecPstat_t));
-    VERIFY_NON_NULL(TAG, pstat, ERROR);
-
-    while (cbor_value_is_valid(&pstatMap))
+    cJSON *jsonPstat = NULL;
+    cJSON *jsonObj = NULL;
+
+    unsigned char base64Buff[sizeof(((OicUuid_t*) 0)->id)] = {};
+    uint32_t outLen = 0;
+    B64Result b64Ret = B64_OK;
+
+    cJSON *jsonRoot = cJSON_Parse(jsonStr);
+    VERIFY_NON_NULL(TAG, jsonRoot, INFO);
+
+    jsonPstat = cJSON_GetObjectItem(jsonRoot, OIC_JSON_PSTAT_NAME);
+    VERIFY_NON_NULL(TAG, jsonPstat, INFO);
+
+    pstat = (OicSecPstat_t*)OICCalloc(1, sizeof(OicSecPstat_t));
+    VERIFY_NON_NULL(TAG, pstat, INFO);
+    jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_ISOP_NAME);
+    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+    VERIFY_SUCCESS(TAG, (cJSON_True == jsonObj->type || cJSON_False == jsonObj->type) , ERROR);
+    pstat->isOp = jsonObj->valueint;
+
+    jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_DEVICE_ID_NAME);
+    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+    VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
+    b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff,
+                sizeof(base64Buff), &outLen);
+    VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(pstat->deviceID.id)), ERROR);
+    memcpy(pstat->deviceID.id, base64Buff, outLen);
+
+    jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_COMMIT_HASH_NAME);
+    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+    VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
+    pstat->commitHash  = jsonObj->valueint;
+
+    jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_CM_NAME);
+    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+    VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
+    pstat->cm  = (OicSecDpm_t)jsonObj->valueint;
+
+    jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_OM_NAME);
+    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+    VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
+    pstat->om  = (OicSecDpom_t)jsonObj->valueint;
+
+    jsonObj = cJSON_GetObjectItem(jsonPstat, OIC_JSON_SM_NAME);
+    VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+    if (cJSON_Array == jsonObj->type)
     {
-        size_t len = 0;
-        cborFindResult = cbor_value_dup_text_string(&pstatMap, &name, &len, NULL);
-        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding PSTAT Name Value.");
-        cborFindResult = cbor_value_advance(&pstatMap);
-        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing PSTAT MAP.");
-
-        CborType type = cbor_value_get_type(&pstatMap);
-
-        if (0 == strcmp(OIC_JSON_ISOP_NAME, name))
-        {
-            cborFindResult = cbor_value_get_boolean(&pstatMap, &pstat->isOp);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding ISOP Name.");
-        }
-
-        if (0 == strcmp(OIC_JSON_DEVICE_ID_NAME, name))
-        {
-            uint8_t *subjectId = NULL;
-            cborFindResult = cbor_value_dup_byte_string(&pstatMap, &subjectId, &len, NULL);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SubjectId.");
-            memcpy(pstat->deviceID.id, subjectId, len);
-            OICFree(subjectId);
-        }
-
-        if (0 == strcmp(OIC_JSON_COMMIT_HASH_NAME, name))
-        {
-            cborFindResult = cbor_value_get_int(&pstatMap, (int *) &pstat->commitHash);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding CommitHash.");
-        }
-
-        if (0 == strcmp(OIC_JSON_CM_NAME, name))
-        {
-            cborFindResult = cbor_value_get_int(&pstatMap, (int *) &pstat->cm);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding CM Name.");
-        }
-
-        if (0 == strcmp(OIC_JSON_OM_NAME, name))
-        {
-            cborFindResult = cbor_value_get_int(&pstatMap, (int *) &pstat->om);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding OM Name.");
-        }
-
-        if (0 == strcmp(OIC_JSON_SM_NAME, name))
-        {
-            CborValue sm = { .parser = NULL };
-
-            cborFindResult = cbor_value_get_array_length(&pstatMap, &pstat->smLen);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SM Len Array.");
-            VERIFY_SUCCESS(TAG, pstat->smLen != 0, ERROR);
-
-            pstat->sm = (OicSecDpom_t *)OICCalloc(pstat->smLen, sizeof(OicSecDpom_t));
-            VERIFY_NON_NULL(TAG, pstat->sm, ERROR);
-
-            cborFindResult = cbor_value_enter_container(&pstatMap, &sm);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SM Container.");
-
-            int i = 0;
-            while (cbor_value_is_valid(&sm))
-            {
-                cborFindResult = cbor_value_get_int(&sm, (int *)&pstat->sm[i++]);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SM Value.");
-                cborFindResult = cbor_value_advance(&sm);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SM Array.");
-            }
-        }
-        if (CborMapType != type && cbor_value_is_valid(&pstatMap))
+        pstat->smLen = (size_t)cJSON_GetArraySize(jsonObj);
+        size_t idxx = 0;
+        VERIFY_SUCCESS(TAG, pstat->smLen != 0, ERROR);
+        pstat->sm = (OicSecDpom_t*)OICCalloc(pstat->smLen, sizeof(OicSecDpom_t));
+        VERIFY_NON_NULL(TAG, pstat->sm, ERROR);
+        do
         {
-            cborFindResult = cbor_value_advance(&pstatMap);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding PSTAT MAP.");
-        }
-        OICFree(name);
-        name = NULL;
+            cJSON *jsonSm = cJSON_GetArrayItem(jsonObj, idxx);
+            VERIFY_NON_NULL(TAG, jsonSm, ERROR);
+            pstat->sm[idxx] = (OicSecDpom_t)jsonSm->valueint;
+        }while ( ++idxx < pstat->smLen);
     }
-
-    *secPstat = pstat;
     ret = OC_STACK_OK;
 
 exit:
-    if (CborNoError != cborFindResult)
+    cJSON_Delete(jsonRoot);
+    if (OC_STACK_OK != ret)
     {
-        OIC_LOG(ERROR, TAG, "CBORPayloadToPstat failed");
+        OIC_LOG (ERROR, TAG, "JSONToPstatBin failed");
         DeletePstatBinData(pstat);
         pstat = NULL;
-        ret = OC_STACK_ERROR;
     }
-    if (name)
-    {
-        OICFree(name);
-    }
-    return ret;
+    return pstat;
 }
 
 /**
  * Function to update persistent storage
  */
-static bool UpdatePersistentStorage(OicSecPstat_t *pstat)
+static bool UpdatePersistentStorage(OicSecPstat_t * pstat)
 {
     bool bRet = false;
 
-    size_t size = 0;
-    uint8_t *cborPayload = NULL;
-    OCStackResult ret = PstatToCBORPayload(pstat, &cborPayload, &size);
-    if (OC_STACK_OK == ret)
+    if (pstat)
     {
-        if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_PSTAT_NAME, cborPayload, size))
+        // Convert pstat data into JSON for update to persistent storage
+        char *jsonStr = BinToPstatJSON(pstat);
+        if (jsonStr)
         {
-            bRet = true;
+            cJSON *jsonPstat = cJSON_Parse(jsonStr);
+            OICFree(jsonStr);
+
+            if (jsonPstat &&
+                (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_PSTAT_NAME, jsonPstat)))
+            {
+                bRet = true;
+            }
+            cJSON_Delete(jsonPstat);
         }
-        OICFree(cborPayload);
     }
 
     return bRet;
@@ -338,19 +227,16 @@ static bool UpdatePersistentStorage(OicSecPstat_t *pstat)
  */
 static OCEntityHandlerResult HandlePstatGetRequest (const OCEntityHandlerRequest * ehRequest)
 {
-    OIC_LOG(INFO, TAG, "HandlePstatGetRequest  processing GET request");
+    OIC_LOG (INFO, TAG, "HandlePstatGetRequest  processing GET request");
+   // Convert ACL data into JSON for transmission
+    char* jsonStr = BinToPstatJSON(gPstat);
 
-    // Convert ACL data into CBOR for transmission
-    size_t size = 0;
-    uint8_t *payload = NULL;
-    OCStackResult res = PstatToCBORPayload(gPstat, &payload, &size);
-
-    // A device should always have a default pstat. Therefore, payload should never be NULL.
-    OCEntityHandlerResult ehRet = (res == OC_STACK_OK) ? OC_EH_OK : OC_EH_ERROR;
+    // A device should always have a default pstat. Therefore, jsonStr should never be NULL.
+    OCEntityHandlerResult ehRet = (jsonStr ? OC_EH_OK : OC_EH_ERROR);
 
     // Send response payload to request originator
-    SendSRMCBORResponse(ehRequest, ehRet, payload);
-    OICFree(payload);
+    SendSRMResponse(ehRequest, ehRet, jsonStr);
+    OICFree(jsonStr);
     return ehRet;
 }
 
@@ -363,56 +249,57 @@ static OCEntityHandlerResult HandlePstatGetRequest (const OCEntityHandlerRequest
 static OCEntityHandlerResult HandlePstatPutRequest(const OCEntityHandlerRequest *ehRequest)
 {
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
-    OIC_LOG(INFO, TAG, "HandlePstatPutRequest  processing PUT request");
-    OicSecPstat_t *pstat = NULL;
+    cJSON *postJson = NULL;
+    OIC_LOG (INFO, TAG, "HandlePstatPutRequest  processing PUT request");
 
     if (ehRequest->resource)
     {
-        uint8_t *payload = ((OCSecurityPayload *) ehRequest->payload)->securityData1;
-        VERIFY_NON_NULL(TAG, payload, ERROR);
-
-        OCStackResult ret = CBORPayloadToPstat(payload, CBOR_SIZE, &pstat);
-        OICFree(payload);
-        VERIFY_NON_NULL(TAG, pstat, ERROR);
-        if (OC_STACK_OK == ret)
+        postJson = cJSON_Parse(((OCSecurityPayload*)ehRequest->payload)->securityData);
+        VERIFY_NON_NULL(TAG, postJson, INFO);
+        cJSON *jsonPstat = cJSON_GetObjectItem(postJson, OIC_JSON_PSTAT_NAME);
+        VERIFY_NON_NULL(TAG, jsonPstat, INFO);
+        cJSON *commitHashJson = cJSON_GetObjectItem(jsonPstat, OIC_JSON_COMMIT_HASH_NAME);
+        uint16_t commitHash = 0;
+        if (commitHashJson)
         {
-            if (pstat->tm)
+            commitHash = commitHashJson->valueint;
+        }
+        cJSON *tmJson = cJSON_GetObjectItem(jsonPstat, OIC_JSON_TM_NAME);
+        if (tmJson && gPstat)
+        {
+            gPstat->tm = (OicSecDpm_t)tmJson->valueint;
+            if(0 == tmJson->valueint && gPstat->commitHash == commitHash)
             {
-                gPstat->tm = pstat->tm;
-                if(0 == pstat->tm && gPstat->commitHash == pstat->commitHash)
-                {
-                    gPstat->isOp = true;
-                    gPstat->cm = NORMAL;
-                    OIC_LOG (INFO, TAG, "CommitHash is valid and isOp is TRUE");
-                }
-                else
-                {
-                    OIC_LOG(DEBUG, TAG, "CommitHash is not valid");
-                }
+                gPstat->isOp = true;
+                gPstat->cm = NORMAL;
+                OIC_LOG (INFO, TAG, "CommitHash is valid and isOp is TRUE");
             }
-            if (pstat->om && gPstat)
+            else
             {
-                /*
-                 * Check if the operation mode is in the supported provisioning services
-                 * operation mode list.
-                 */
-                for(size_t i=0; i< gPstat->smLen; i++)
-                {
-                    if(gPstat->sm[i] == pstat->om)
-                    {
-                        gPstat->om = pstat->om;
-                        break;
-                    }
-                }
+                OIC_LOG (INFO, TAG, "CommitHash is not valid");
             }
-            // Convert pstat data into CBOR for update to persistent storage
-            if(UpdatePersistentStorage(gPstat))
+        }
+        cJSON *omJson = cJSON_GetObjectItem(jsonPstat, OIC_JSON_OM_NAME);
+        if (omJson && gPstat)
+        {
+            /*
+             * Check if the operation mode is in the supported provisioning services
+             * operation mode list.
+             */
+            for(size_t i=0; i< gPstat->smLen; i++)
             {
-                ehRet = OC_EH_OK;
+                if(gPstat->sm[i] == (unsigned int)omJson->valueint)
+                {
+                    gPstat->om = (OicSecDpom_t)omJson->valueint;
+                    break;
+                }
             }
         }
-
-        OICFree(payload);
+        // Convert pstat data into JSON for update to persistent storage
+        if(UpdatePersistentStorage(gPstat))
+        {
+            ehRet = OC_EH_OK;
+        }
     }
  exit:
     if(OC_EH_OK != ehRet)
@@ -426,27 +313,27 @@ static OCEntityHandlerResult HandlePstatPutRequest(const OCEntityHandlerRequest
     }
 
     //Send payload to request originator
-    if (OC_STACK_OK != SendSRMCBORResponse(ehRequest, ehRet, NULL))
+    if(OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, NULL))
     {
         OIC_LOG (ERROR, TAG, "SendSRMResponse failed in HandlePstatPostRequest");
     }
-    DeletePstatBinData(pstat);
+    cJSON_Delete(postJson);
     return ehRet;
 }
 
 /**
  * This internal method is the entity handler for pstat resources.
  */
- OCEntityHandlerResult PstatEntityHandler(OCEntityHandlerFlag flag,
-                                          OCEntityHandlerRequest * ehRequest,
-                                          void *callbackParam)
+OCEntityHandlerResult PstatEntityHandler(OCEntityHandlerFlag flag,
+        OCEntityHandlerRequest * ehRequest,
+        void *callbackParam)
 {
     (void)callbackParam;
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
     // This method will handle REST request (GET/POST) for /oic/sec/pstat
     if (flag & OC_REQUEST_FLAG)
     {
-        OIC_LOG(INFO, TAG, "Flag includes OC_REQUEST_FLAG");
+        OIC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
         switch (ehRequest->method)
         {
             case OC_REST_GET:
@@ -457,7 +344,7 @@ static OCEntityHandlerResult HandlePstatPutRequest(const OCEntityHandlerRequest
                 break;
             default:
                 ehRet = OC_EH_ERROR;
-                SendSRMCBORResponse(ehRequest, ehRet, NULL);
+                SendSRMResponse(ehRequest, ehRet, NULL);
                 break;
         }
     }
@@ -467,78 +354,84 @@ static OCEntityHandlerResult HandlePstatPutRequest(const OCEntityHandlerRequest
 /**
  * This internal method is used to create '/oic/sec/pstat' resource.
  */
- OCStackResult CreatePstatResource()
+OCStackResult CreatePstatResource()
 {
-    OCStackResult ret = OCCreateResource(&gPstatHandle,
-                                         OIC_RSRC_TYPE_SEC_PSTAT,
-                                         OIC_MI_DEF,
-                                         OIC_RSRC_PSTAT_URI,
-                                         PstatEntityHandler,
-                                         NULL,
-                                         OC_RES_PROP_NONE);
+    OCStackResult ret;
 
-    if (OC_STACK_OK != ret)
+    ret = OCCreateResource(&gPstatHandle,
+                           OIC_RSRC_TYPE_SEC_PSTAT,
+                           OIC_MI_DEF,
+                           OIC_RSRC_PSTAT_URI,
+                           PstatEntityHandler,
+                           NULL,
+                           OC_RES_PROP_NONE);
+
+    if (ret != OC_STACK_OK)
     {
-        OIC_LOG(FATAL, TAG, "Unable to instantiate pstat resource");
+        OIC_LOG (FATAL, TAG, "Unable to instantiate pstat resource");
         DeInitPstatResource();
     }
     return ret;
 }
 
 /**
- * Get the default value.
- *
- * @return the gDefaultPstat pointer.
+ * Post ACL hander update the commitHash during ACL provisioning.
+ */
+void SetCommitHash(uint16_t commitHash)
+{
+    gPstat->commitHash = commitHash;
+}
+
+/**
+ * Get the default value
+ * @retval  the gDefaultPstat pointer
  */
 static OicSecPstat_t* GetPstatDefault()
 {
     return &gDefaultPstat;
 }
 
+/**
+ * Initialize pstat resource by loading data from persistent storage.
+ *
+ * @retval  OC_STACK_OK for Success, otherwise some error value
+ */
 OCStackResult InitPstatResource()
 {
     OCStackResult ret = OC_STACK_ERROR;
 
     // Read Pstat resource from PS
-    uint8_t *data = NULL;
-    size_t size = 0;
-    ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_PSTAT_NAME, &data, &size);
-    // If database read failed
-    if (OC_STACK_OK != ret)
-    {
-        OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
-    }
-    if (data)
+    char* jsonSVRDatabase = GetSVRDatabase();
+    if (jsonSVRDatabase)
     {
-        // Read ACL resource from PS
-        ret = CBORPayloadToPstat(data, size, &gPstat);
+        // Convert JSON Pstat into binary format
+        gPstat = JSONToPstatBin(jsonSVRDatabase);
     }
     /*
      * If SVR database in persistent storage got corrupted or
      * is not available for some reason, a default pstat is created
      * which allows user to initiate pstat provisioning again.
      */
-    if ((OC_STACK_OK != ret) || !data || !gPstat)
+    if(!jsonSVRDatabase || !gPstat)
     {
         gPstat = GetPstatDefault();
     }
-    VERIFY_NON_NULL(TAG, gPstat, FATAL);
 
     // Instantiate 'oic.sec.pstat'
     ret = CreatePstatResource();
 
-exit:
-    OICFree(data);
-    if (OC_STACK_OK != ret)
-    {
-        DeInitPstatResource();
-    }
+    OICFree(jsonSVRDatabase);
     return ret;
 }
 
+/**
+ * Perform cleanup for pstat resources.
+ *
+ * @retval  OC_STACK_OK for Success, otherwise some error value
+ */
 OCStackResult DeInitPstatResource()
 {
-    if (gPstat != &gDefaultPstat)
+    if(gPstat != &gDefaultPstat)
     {
         DeletePstatBinData(gPstat);
         gPstat = NULL;
@@ -546,6 +439,7 @@ OCStackResult DeInitPstatResource()
     return OCDeleteResource(gPstatHandle);
 }
 
+
 /**
  * Function to restore pstat resurce to initial status.
  * This function will use in case of error while ownership transfer
@@ -564,7 +458,7 @@ void RestorePstatToInitState()
             gPstat->sm[0] = SINGLE_SERVICE_CLIENT_DRIVEN;
         }
 
-        if (!UpdatePersistentStorage(gPstat))
+        if(!UpdatePersistentStorage(gPstat))
         {
             OIC_LOG(ERROR, TAG, "Failed to revert DOXM in persistent storage");
         }
index d40c4c9..339ea48 100644 (file)
@@ -18,7 +18,6 @@
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#include <string.h>
 #include "resourcemanager.h"
 #include "securevirtualresourcetypes.h"
 #include "aclresource.h"
@@ -31,6 +30,7 @@
 #include "oic_string.h"
 #include "logger.h"
 #include "utlist.h"
+#include <string.h>
 
 //#ifdef DIRECT_PAIRING
 #include "pconfresource.h"
 #include "crlresource.h"
 #endif // __WITH_X509__
 
+/**
+ * This method is used by all secure resource modules to send responses to REST queries.
+ *
+ * @param ehRequest pointer to entity handler request data structure.
+ * @param ehRet result code from entity handler.
+ * @param rspPayload response payload in JSON.
+ *
+ * @retval  OC_STACK_OK for Success, otherwise some error value
+ */
 OCStackResult SendSRMResponse(const OCEntityHandlerRequest *ehRequest,
         OCEntityHandlerResult ehRet, const char *rspPayload)
 {
@@ -65,30 +74,11 @@ OCStackResult SendSRMResponse(const OCEntityHandlerRequest *ehRequest,
     return OC_STACK_ERROR;
 }
 
-OCStackResult SendSRMCBORResponse(const OCEntityHandlerRequest *ehRequest,
-        OCEntityHandlerResult ehRet, uint8_t *cborPayload)
-{
-    OIC_LOG(DEBUG, TAG, "SRM sending SRM response");
-    OCEntityHandlerResponse response = {.requestHandle = NULL};
-    OCStackResult ret = OC_STACK_ERROR;
-
-    if (ehRequest)
-    {
-        OCSecurityPayload ocPayload = {.base = {.type = PAYLOAD_TYPE_INVALID}};
-
-        response.requestHandle = ehRequest->requestHandle;
-        response.resourceHandle = ehRequest->resource;
-        response.ehResult = ehRet;
-        response.payload = (OCPayload *)(&ocPayload);
-        response.payload->type = PAYLOAD_TYPE_SECURITY;
-        ((OCSecurityPayload *)response.payload)->securityData1 = cborPayload;
-        response.persistentBufferFlag = 0;
-
-        ret = OCDoResponse(&response);
-    }
-    return ret;
-}
-
+/**
+ * Initialize all secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
+ *
+ * @retval  OC_STACK_OK for Success, otherwise some error value
+ */
 OCStackResult InitSecureResources( )
 {
     OCStackResult ret;
@@ -144,6 +134,11 @@ OCStackResult InitSecureResources( )
     return ret;
 }
 
+/**
+ * Perform cleanup for secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
+ *
+ * @retval  OC_STACK_OK for Success, otherwise some error value
+ */
 OCStackResult DestroySecureResources( )
 {
     DeInitACLResource();
index 7c233be..02fe6ed 100644 (file)
@@ -56,11 +56,21 @@ static SPResponseCallback gSPResponseHandler = NULL;
  */
 PEContext_t g_policyEngineContext;
 
+/**
+ * @brief function to register provisoning API's response callback.
+ * @param respHandler response handler callback.
+ */
+void SRMRegisterProvisioningResponseHandler(SPResponseCallback respHandler)
+{
+    gSPResponseHandler = respHandler;
+}
+
+
 static void SRMSendUnAuthorizedAccessresponse(PEContext_t *context)
 {
     CAResponseInfo_t responseInfo = {.result = CA_EMPTY};
 
-    if (NULL == context ||
+    if(NULL == context ||
        NULL == context->amsMgrContext->requestInfo)
     {
         OIC_LOG_V(ERROR, TAG, "%s : NULL Parameter(s)",__func__);
@@ -82,6 +92,7 @@ static void SRMSendUnAuthorizedAccessresponse(PEContext_t *context)
     }
 }
 
+
 void SRMSendResponse(SRMAccessResponse_t responseVal)
 {
     OIC_LOG(DEBUG, TAG, "Sending response to remote device");
@@ -110,11 +121,12 @@ exit:
     SetPolicyEngineState(&g_policyEngineContext, AWAITING_REQUEST);
 }
 
+
 /**
- * Handle the request from the SRM.
- *
- * @param endPoint object from which the response is received.
- * @param requestInfo contains information for the request.
+ * @brief   Handle the request from the SRM.
+ * @param   endPoint       [IN] Endpoint object from which the response is received.
+ * @param   requestInfo    [IN] Information for the request.
+ * @return  NONE
  */
 void SRMRequestHandler(const CAEndpoint_t *endPoint, const CARequestInfo_t *requestInfo)
 {
@@ -152,7 +164,7 @@ void SRMRequestHandler(const CAEndpoint_t *endPoint, const CARequestInfo_t *requ
     OICStrcpyPartial(newUri, MAX_URI_LENGTH + 1, requestInfo->info.resourceUri, position);
 
     //New request are only processed if the policy engine state is AWAITING_REQUEST.
-    if (AWAITING_REQUEST == g_policyEngineContext.state)
+    if(AWAITING_REQUEST == g_policyEngineContext.state)
     {
         OIC_LOG_V(DEBUG, TAG, "Processing request with uri, %s for method, %d",
                 requestInfo->info.resourceUri, requestInfo->method);
@@ -177,7 +189,7 @@ void SRMRequestHandler(const CAEndpoint_t *endPoint, const CARequestInfo_t *requ
 
     VERIFY_NON_NULL(TAG, gRequestHandler, ERROR);
 
-    if (ACCESS_WAITING_FOR_AMS == response)
+    if(ACCESS_WAITING_FOR_AMS == response)
     {
         OIC_LOG(INFO, TAG, "Sending slow response");
 
@@ -210,10 +222,10 @@ exit:
 }
 
 /**
- * Handle the response from the SRM.
- *
- * @param endPoint points to the remote endpoint.
- * @param responseInfo contains response information from the endpoint.
+ * @brief   Handle the response from the SRM.
+ * @param   endPoint     [IN] The remote endpoint.
+ * @param   responseInfo [IN] Response information from the endpoint.
+ * @return  NONE
  */
 void SRMResponseHandler(const CAEndpoint_t *endPoint, const CAResponseInfo_t *responseInfo)
 {
@@ -236,11 +248,12 @@ void SRMResponseHandler(const CAEndpoint_t *endPoint, const CAResponseInfo_t *re
     }
 }
 
+
 /**
- * Handle the error from the SRM.
- *
- * @param endPoint is the remote endpoint.
- * @param errorInfo contains error information from the endpoint.
+ * @brief   Handle the error from the SRM.
+ * @param   endPoint  [IN] The remote endpoint.
+ * @param   errorInfo [IN] Error information from the endpoint.
+ * @return  NONE
  */
 void SRMErrorHandler(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInfo)
 {
@@ -252,6 +265,16 @@ void SRMErrorHandler(const CAEndpoint_t *endPoint, const CAErrorInfo_t *errorInf
     }
 }
 
+
+/**
+ * @brief   Register request and response callbacks.
+ *          Requests and responses are delivered in these callbacks.
+ * @param   reqHandler   [IN] Request handler callback ( for GET,PUT ..etc)
+ * @param   respHandler  [IN] Response handler callback.
+ * @return
+ *     OC_STACK_OK    - No errors; Success
+ *     OC_STACK_INVALID_PARAM - invalid parameter
+ */
 OCStackResult SRMRegisterHandler(CARequestCallback reqHandler,
                                  CAResponseCallback respHandler,
                                  CAErrorCallback errHandler)
@@ -275,6 +298,13 @@ OCStackResult SRMRegisterHandler(CARequestCallback reqHandler,
     return OC_STACK_OK;
 }
 
+/**
+ * @brief   Register Persistent storage callback.
+ * @param   persistentStorageHandler [IN] Pointers to open, read, write, close & unlink handlers.
+ * @return
+ *     OC_STACK_OK    - No errors; Success
+ *     OC_STACK_INVALID_PARAM - Invalid parameter
+ */
 OCStackResult SRMRegisterPersistentStorageHandler(OCPersistentStorage* persistentStorageHandler)
 {
     OIC_LOG(DEBUG, TAG, "SRMRegisterPersistentStorageHandler !!");
@@ -287,11 +317,22 @@ OCStackResult SRMRegisterPersistentStorageHandler(OCPersistentStorage* persisten
     return OC_STACK_OK;
 }
 
+/**
+ * @brief   Get Persistent storage handler pointer.
+ * @return
+ *     The pointer to Persistent Storage callback handler
+ */
+
 OCPersistentStorage* SRMGetPersistentStorageHandler()
 {
     return gPersistentStorageHandler;
 }
 
+
+/**
+ * @brief   Initialize all secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
+ * @retval  OC_STACK_OK for Success, otherwise some error value
+ */
 OCStackResult SRMInitSecureResources()
 {
     // TODO: temporarily returning OC_STACK_OK every time until default
@@ -314,21 +355,38 @@ OCStackResult SRMInitSecureResources()
     return ret;
 }
 
+/**
+ * @brief   Perform cleanup for secure resources ( /oic/sec/cred, /oic/sec/acl, /oic/sec/pstat etc).
+ * @retval  none
+ */
 void SRMDeInitSecureResources()
 {
     DestroySecureResources();
 }
 
+/**
+ * @brief   Initialize Policy Engine.
+ * @return  OC_STACK_OK for Success, otherwise some error value.
+ */
 OCStackResult SRMInitPolicyEngine()
 {
     return InitPolicyEngine(&g_policyEngineContext);
 }
 
+/**
+ * @brief   Cleanup Policy Engine.
+ * @return  none
+ */
 void SRMDeInitPolicyEngine()
 {
     return DeInitPolicyEngine(&g_policyEngineContext);
 }
 
+/**
+ * @brief   Check the security resource URI.
+ * @param   uri [IN] Pointers to security resource URI.
+ * @return  true if the URI is one of security resources, otherwise false.
+ */
 bool SRMIsSecurityResourceURI(const char* uri)
 {
     if (!uri)
index b80e71e..34e92aa 100644 (file)
@@ -22,7 +22,6 @@
 #include "securevirtualresourcetypes.h"
 
 const char * SVR_DB_FILE_NAME = "oic_svr_db.json";
-const char * SVR_DB_DAT_FILE_NAME = "oic_svr_db.dat";
 const char * OIC_MI_DEF = "oic.mi.def";
 
 //AMACL
@@ -111,8 +110,6 @@ const char * OIC_JSON_SPM_NAME = "spm";
 const char * OIC_JSON_PDEVICE_ID_NAME = "pdeviceid";
 
 OicUuid_t WILDCARD_SUBJECT_ID = {"*"};
-OicUuid_t WILDCARD_SUBJECT_B64_ID = { .id = {'2', '2', '2', '2', '2', '2', '2', '2',
-                                             '2', '2', '2', '2', '2', '2', '2', '2' }};
 size_t WILDCARD_SUBJECT_ID_LEN = 1;
 const char * WILDCARD_RESOURCE_URI = "*";
 
index df0636b..8f8cc7f 100644 (file)
 
 #define TAG  "SRM-UTILITY"
 
-void ParseQueryIterInit(const unsigned char * query, OicParseQueryIter_t * parseIter)
+/**
+ * This method initializes the OicParseQueryIter_t struct
+ *
+ *@param query     - REST query, to be parsed
+ *@param parseIter - OicParseQueryIter_t struct, to be initialized
+ *
+ */
+void ParseQueryIterInit(unsigned char * query, OicParseQueryIter_t * parseIter)
 {
-    OIC_LOG(INFO, TAG, "Initializing coap iterator");
-    if ((NULL == query) || (NULL == parseIter))
-    {
+    OIC_LOG (INFO, TAG, "Initializing coap iterator");
+    if((NULL == query) || (NULL == parseIter))
         return;
-    }
 
     parseIter->attrPos = NULL;
     parseIter->attrLen = 0;
     parseIter->valPos = NULL;
     parseIter->valLen = 0;
-    coap_parse_iterator_init((unsigned char *)query, strlen((char *)query),
-                             (unsigned char *)OIC_SEC_REST_QUERY_SEPARATOR,
-                             (unsigned char *) "", 0, &parseIter->pi);
+    coap_parse_iterator_init(query, strlen((char *)query),
+          (unsigned char *)OIC_SEC_REST_QUERY_SEPARATOR, (unsigned char *) "", 0, &parseIter->pi);
 }
 
+/**
+ * This method fills the OicParseQueryIter_t struct with next REST query's
+ * attribute's and value's information
+ *
+ *@param parseIter - OicParseQueryIter_t struct, has next query's attribute's & value's info
+ *
+ * @retval
+ *     OicParseQueryIter_t *  - has parsed query info
+ *     NULL                   - has no query to parse
+ */
 OicParseQueryIter_t * GetNextQuery(OicParseQueryIter_t * parseIter)
 {
-    OIC_LOG(INFO, TAG, "Getting Next Query");
-    if (NULL == parseIter)
-    {
+    OIC_LOG (INFO, TAG, "Getting Next Query");
+    if(NULL == parseIter)
         return NULL;
-    }
 
     unsigned char * qrySeg = NULL;
     char * delimPos;
 
-    // Get the next query. Querys are separated by OIC_SEC_REST_QUERY_SEPARATOR.
+    //Get the next query. Querys are separated by OIC_SEC_REST_QUERY_SEPARATOR
     qrySeg = coap_parse_next(&parseIter->pi);
 
-    if (qrySeg)
+    if(qrySeg)
     {
         delimPos = strchr((char *)qrySeg, OIC_SEC_REST_QUERY_DELIMETER);
-        if (delimPos)
+        if(delimPos)
         {
             parseIter->attrPos = parseIter->pi.pos;
             parseIter->attrLen = (unsigned char *)delimPos - parseIter->pi.pos;
@@ -74,14 +86,15 @@ OicParseQueryIter_t * GetNextQuery(OicParseQueryIter_t * parseIter)
     return NULL;
 }
 
+
 // TODO This functionality is replicated in all SVR's and therefore we need
 // to encapsulate it in a common method. However, this may not be the right
 // file for this method.
-OCStackResult AddUuidArray(const cJSON* jsonRoot, const char* arrayItem,
-                           size_t *numUuids, OicUuid_t** uuids)
+OCStackResult AddUuidArray(cJSON* jsonRoot, const char* arrayItem,
+                           size_t *numUuids, OicUuid_t** uuids )
 {
     size_t idxx = 0;
-    cJSON* jsonObj = cJSON_GetObjectItem((cJSON *)jsonRoot, arrayItem);
+    cJSON* jsonObj = cJSON_GetObjectItem(jsonRoot, arrayItem);
     VERIFY_NON_NULL(TAG, jsonObj, ERROR);
     VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
 
@@ -137,3 +150,4 @@ const char* GetOxmString(OicSecOxm_t oxmType)
             return NULL;
     }
 }
+
index 3cfe8ee..bb55450 100644 (file)
 // limitations under the License.
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-#include <stdlib.h>
-#include <string.h>
 
 #include "ocstack.h"
-#include "ocpayload.h"
+#include "logger.h"
 #include "oic_malloc.h"
-#include "utlist.h"
-#include "payload_logging.h"
+#include "cJSON.h"
+#include "base64.h"
 #include "resourcemanager.h"
 #include "psinterface.h"
 #include "svcresource.h"
+#include "utlist.h"
 #include "srmresourcestrings.h"
 #include "srmutility.h"
-
-#include "security_internals.h"
+#include <stdlib.h>
+#include <string.h>
 
 #define TAG  "SRM-SVC"
 
-/** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
- * The value of payload size is increased until reaching belox max cbor size. */
-static const uint8_t CBOR_SIZE = 255;
-
-/** Max cbor size payload. */
-static const uint16_t CBOR_MAX_SIZE = 4400;
-
-/** SVC Map size - Number of mandatory items. */
-static const uint8_t SVC_MAP_SIZE = 3;
-
-static OicSecSvc_t        *gSvc = NULL;
+OicSecSvc_t        *gSvc = NULL;
 static OCResourceHandle    gSvcHandle = NULL;
 
 void DeleteSVCList(OicSecSvc_t* svc)
@@ -66,306 +55,236 @@ void DeleteSVCList(OicSecSvc_t* svc)
     }
 }
 
-static size_t svcElementsCount(const OicSecSvc_t *secSvc)
-{
-    size_t size = 0;
-    for (const OicSecSvc_t *svc = secSvc; svc; svc = svc->next)
-    {
-        size++;
-    }
-    return size;
-}
-
-OCStackResult SVCToCBORPayload(const OicSecSvc_t *svc, uint8_t **cborPayload,
-                               size_t *cborSize)
+/*
+ * This internal method converts SVC data into JSON format.
+ *
+ * Note: Caller needs to invoke 'free' when finished done using
+ * return string.
+ */
+char * BinToSvcJSON(const OicSecSvc_t * svc)
 {
-    if (NULL == svc || NULL == cborPayload || NULL != *cborPayload || NULL == cborSize)
-    {
-       return OC_STACK_INVALID_PARAM;
-    }
+    cJSON *jsonRoot = NULL;
+    char *jsonStr = NULL;
 
-    size_t cborLen = *cborSize;
-    if (0 == cborLen)
+    if (svc)
     {
-        cborLen = CBOR_SIZE;
-    }
-    *cborPayload = NULL;
-    *cborSize = 0;
+        jsonRoot = cJSON_CreateObject();
+        VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
 
-    CborError cborEncoderResult = CborNoError;
-    OCStackResult ret = OC_STACK_ERROR;
-    CborEncoder encoder = { {.ptr = NULL }, .end = 0 };
-    CborEncoder svcArray = { {.ptr = NULL }, .end = 0 };
+        cJSON *jsonSvcArray = NULL;
+        cJSON_AddItemToObject (jsonRoot, OIC_JSON_SVC_NAME, jsonSvcArray = cJSON_CreateArray());
+        VERIFY_NON_NULL(TAG, jsonSvcArray, ERROR);
 
-    uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
-    VERIFY_NON_NULL(TAG, outPayload, ERROR);
+        while(svc)
+        {
+            char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};
+            uint32_t outLen = 0;
+            B64Result b64Ret = B64_OK;
 
-    cbor_encoder_init(&encoder, outPayload, cborLen, 0);
+            cJSON *jsonSvc = cJSON_CreateObject();
 
-    // Create SVC Array
-    cborEncoderResult = cbor_encoder_create_array(&encoder, &svcArray,
-                                                  svcElementsCount(svc));
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to Create SVC Array.");
+            // Service Device Identity
+            outLen = 0;
+            b64Ret = b64Encode(svc->svcdid.id, sizeof(OicUuid_t), base64Buff,
+                    sizeof(base64Buff), &outLen);
+            VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
+            cJSON_AddStringToObject(jsonSvc, OIC_JSON_SERVICE_DEVICE_ID, base64Buff );
 
-    while (svc)
-    {
-        CborEncoder svcMap = { {.ptr = NULL }, .end = 0};
-        cborEncoderResult = cbor_encoder_create_map(&svcArray, &svcMap, SVC_MAP_SIZE);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to Create SVC Map.");
-
-        // Service Device Identity
-        cborEncoderResult = cbor_encode_text_string(&svcMap, OIC_JSON_SERVICE_DEVICE_ID,
-            strlen(OIC_JSON_SERVICE_DEVICE_ID));
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to Add SVC Device Id.");
-        cborEncoderResult = cbor_encode_byte_string(&svcMap, (uint8_t *)svc->svcdid.id,
-            sizeof(svc->svcdid.id));
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to ");
-
-        // Service Type
-        cborEncoderResult = cbor_encode_text_string(&svcMap, OIC_JSON_SERVICE_TYPE,
-            strlen(OIC_JSON_SERVICE_TYPE));
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to Add SVC Serv Type Tag.");
-        cborEncoderResult = cbor_encode_int(&svcMap, svc->svct);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to Add SVC Serv Type Value.");
-
-        // Owners
-        cborEncoderResult = cbor_encode_text_string(&svcMap, OIC_JSON_OWNERS_NAME,
-            strlen(OIC_JSON_OWNERS_NAME));
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to Add SVC Owners Tag.");
-        CborEncoder owners = { {.ptr = NULL }, .end = 0 };
-        cborEncoderResult = cbor_encoder_create_array(&svcMap, &owners, svc->ownersLen);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to Add SVC Array.");
-        for (size_t i = 0; i < svc->ownersLen; i++)
-        {
-            cborEncoderResult = cbor_encode_byte_string(&owners, (uint8_t *)svc->owners[i].id,
-                sizeof(svc->owners[i].id));
-            VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to Add SVC Owners Value.");
-        }
-        cborEncoderResult = cbor_encoder_close_container(&svcMap, &owners);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to Close SVC Array.");
+            // Service Type
+            cJSON_AddNumberToObject (jsonSvc, OIC_JSON_SERVICE_TYPE, svc->svct);
 
-        cborEncoderResult = cbor_encoder_close_container(&svcArray, &svcMap);
-        VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to Close SVC Map.");
+            // Owners
+            cJSON *jsonOwnrArray = NULL;
+            cJSON_AddItemToObject (jsonSvc, OIC_JSON_OWNERS_NAME, jsonOwnrArray = cJSON_CreateArray());
+            VERIFY_NON_NULL(TAG, jsonOwnrArray, ERROR);
+            for (unsigned int i = 0; i < svc->ownersLen; i++)
+            {
+                outLen = 0;
 
-        svc = svc->next;
-    }
+                b64Ret = b64Encode(svc->owners[i].id, sizeof(((OicUuid_t*)0)->id), base64Buff,
+                        sizeof(base64Buff), &outLen);
+                VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
 
-    cborEncoderResult = cbor_encoder_close_container(&encoder, &svcArray);
-    VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed to Close SVC Array.");
+                cJSON_AddItemToArray (jsonOwnrArray, cJSON_CreateString(base64Buff));
+            }
 
-    *cborPayload = outPayload;
-    *cborSize = encoder.ptr - outPayload;
-    ret = OC_STACK_OK;
+            // Attach current svc node to Svc Array
+            cJSON_AddItemToArray(jsonSvcArray, jsonSvc);
+            svc = svc->next;
+        }
 
-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 = SVCToCBORPayload(svc, cborPayload, &cborLen);
+        jsonStr = cJSON_PrintUnformatted(jsonRoot);
     }
 
-    if (CborNoError != cborEncoderResult)
+exit:
+    if (jsonRoot)
     {
-        OICFree(outPayload);
-        outPayload = NULL;
-        *cborSize = 0;
-        *cborPayload = NULL;
-        ret = OC_STACK_ERROR;
+        cJSON_Delete(jsonRoot);
     }
-
-    return ret;
+    return jsonStr;
 }
 
-OCStackResult CBORPayloadToSVC(const uint8_t *cborPayload, size_t size,
-                               OicSecSvc_t **secSvc)
+/*
+ * This internal method converts JSON SVC into binary SVC.
+ */
+OicSecSvc_t * JSONToSvcBin(const char * jsonStr)
 {
-    if (NULL == cborPayload || NULL == secSvc || NULL != *secSvc)
-    {
-        return OC_STACK_INVALID_PARAM;
-    }
-
-    *secSvc = NULL;
-
     OCStackResult ret = OC_STACK_ERROR;
+    OicSecSvc_t * headSvc = NULL;
+    OicSecSvc_t * prevSvc = NULL;
+    cJSON *jsonRoot = NULL;
+    cJSON *jsonSvcArray = NULL;
 
-    CborValue svcCbor = { .parser = NULL };
-    CborParser parser = { .end = NULL };
-    CborError cborFindResult = CborNoError;
-    int cborLen = size;
-    if (0 == size)
-    {
-       cborLen = CBOR_SIZE;
-    }
-    cbor_parser_init(cborPayload, cborLen, 0, &parser, &svcCbor);
+    VERIFY_NON_NULL(TAG, jsonStr, ERROR);
 
-    OicSecSvc_t *headSvc = NULL;
+    jsonRoot = cJSON_Parse(jsonStr);
+    VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
 
-    CborValue svcArray = { .parser = NULL };
-    cborFindResult = cbor_value_enter_container(&svcCbor, &svcArray);
-    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Enter SVC Array.");
+    jsonSvcArray = cJSON_GetObjectItem(jsonRoot, OIC_JSON_SVC_NAME);
+    VERIFY_NON_NULL(TAG, jsonSvcArray, INFO);
 
-    while (cbor_value_is_valid(&svcArray))
+    if (cJSON_Array == jsonSvcArray->type)
     {
-        CborValue svcMap = { .parser = NULL };
-        cborFindResult = cbor_value_enter_container(&svcArray, &svcMap);
-        VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Enter SVC Map.");
-
-        OicSecSvc_t *svc = (OicSecSvc_t *) OICCalloc(1, sizeof(OicSecSvc_t));
-        VERIFY_NON_NULL(TAG, svc, ERROR);
+        int numSvc = cJSON_GetArraySize(jsonSvcArray);
+        int idx = 0;
 
-        while (cbor_value_is_valid(&svcMap))
+        VERIFY_SUCCESS(TAG, numSvc > 0, INFO);
+        do
         {
-            char* name = NULL;
-            size_t len = 0;
-            cborFindResult = cbor_value_dup_text_string(&svcMap, &name, &len, NULL);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Find Name.");
-            cborFindResult = cbor_value_advance(&svcMap);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Advance.");
+            cJSON *jsonSvc = cJSON_GetArrayItem(jsonSvcArray, idx);
+            VERIFY_NON_NULL(TAG, jsonSvc, ERROR);
 
-            CborType type = cbor_value_get_type(&svcMap);
+            OicSecSvc_t *svc = (OicSecSvc_t*)OICCalloc(1, sizeof(OicSecSvc_t));
+            VERIFY_NON_NULL(TAG, svc, ERROR);
 
-            // Service Device Identity
-            if (0 == strcmp(OIC_JSON_SERVICE_DEVICE_ID, name))
+            headSvc = (headSvc) ? headSvc : svc;
+            if (prevSvc)
             {
-                uint8_t *subjectId = NULL;
-                cborFindResult = cbor_value_dup_byte_string(&svcMap, &subjectId, &len, NULL);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Find SubjectId.");
-                memcpy(svc->svcdid.id, subjectId, len);
-                OICFree(subjectId);
+                prevSvc->next = svc;
             }
+
+            cJSON *jsonObj = NULL;
+
+            unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
+            uint32_t outLen = 0;
+            B64Result b64Ret = B64_OK;
+
+            // Service Device Identity
+            jsonObj = cJSON_GetObjectItem(jsonSvc, OIC_JSON_SERVICE_DEVICE_ID);
+            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+            VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
+            outLen = 0;
+            b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff,
+                        sizeof(base64Buff), &outLen);
+            VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(svc->svcdid.id)), ERROR);
+            memcpy(svc->svcdid.id, base64Buff, outLen);
+
             // Service Type
-            if (0 == strcmp(OIC_JSON_SERVICE_TYPE, name))
+            jsonObj = cJSON_GetObjectItem(jsonSvc, OIC_JSON_SERVICE_TYPE);
+            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+            VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
+            svc->svct = (OicSecSvcType_t)jsonObj->valueint;
+
+            // Resource Owners
+            jsonObj = cJSON_GetObjectItem(jsonSvc, OIC_JSON_OWNERS_NAME);
+            VERIFY_NON_NULL(TAG, jsonObj, ERROR);
+            VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
+
+            svc->ownersLen = (size_t)cJSON_GetArraySize(jsonObj);
+            VERIFY_SUCCESS(TAG, svc->ownersLen > 0, ERROR);
+            svc->owners = (OicUuid_t*)OICCalloc(svc->ownersLen, sizeof(OicUuid_t));
+            VERIFY_NON_NULL(TAG, (svc->owners), ERROR);
+
+            size_t idxx = 0;
+            do
             {
-                cborFindResult = cbor_value_get_int(&svcMap, (int *) &svc->svct);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Find SVCT.");
-            }
+                cJSON *jsonOwnr = cJSON_GetArrayItem(jsonObj, idxx);
+                VERIFY_NON_NULL(TAG, jsonOwnr, ERROR);
+                VERIFY_SUCCESS(TAG, cJSON_String == jsonOwnr->type, ERROR);
 
-            // Owners -- Mandatory
-            if (0 == strcmp(OIC_JSON_OWNERS_NAME, name))
-            {
-                CborValue owners = { .parser = NULL };
-                cborFindResult = cbor_value_get_array_length(&svcMap, &svc->ownersLen);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Find Owner Len.");
-                cborFindResult = cbor_value_enter_container(&svcMap, &owners);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Enter Owner Array.");
-                int i = 0;
-                svc->owners = (OicUuid_t *)OICCalloc(svc->ownersLen, sizeof(*svc->owners));
-                VERIFY_NON_NULL(TAG, svc->owners, ERROR);
-                while (cbor_value_is_valid(&owners))
-                {
-                    uint8_t *owner = NULL;
-                    cborFindResult = cbor_value_dup_byte_string(&owners, &owner, &len, NULL);
-                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Find Owner Array Value.");
-                    cborFindResult = cbor_value_advance(&owners);
-                    VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Advance Owner Array.");
-                    memcpy(svc->owners[i].id, owner, len);
-                    OICFree(owner);
-                }
-            }
-            if (CborMapType != type  && cbor_value_is_valid(&svcMap))
-            {
-                cborFindResult = cbor_value_advance(&svcMap);
-                VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Advance SVC.");
-            }
-            OICFree(name);
-        }
+                outLen = 0;
+                b64Ret = b64Decode(jsonOwnr->valuestring, strlen(jsonOwnr->valuestring), base64Buff,
+                            sizeof(base64Buff), &outLen);
 
-        svc->next = NULL;
-        if (NULL == headSvc)
-        {
-            headSvc = svc;
-        }
-        else
-        {
-            OicSecSvc_t *temp = headSvc;
-            while (temp->next)
-            {
-                temp = temp->next;
-            }
-            temp->next = svc;
-        }
-        if (cbor_value_is_valid(&svcArray))
-        {
-            cborFindResult = cbor_value_advance(&svcArray);
-            VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed to Find Name.");
-        }
+                VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(svc->owners[idxx].id)),
+                                    ERROR);
+                memcpy(svc->owners[idxx].id, base64Buff, outLen);
+            } while ( ++idxx < svc->ownersLen);
+
+            prevSvc = svc;
+        } while( ++idx < numSvc);
     }
-    *secSvc = headSvc;
+
     ret = OC_STACK_OK;
 
 exit:
-    if (CborNoError != cborFindResult)
+    cJSON_Delete(jsonRoot);
+    if (OC_STACK_OK != ret)
     {
         DeleteSVCList(headSvc);
         headSvc = NULL;
-        ret = OC_STACK_ERROR;
     }
-    return ret;
+    return headSvc;
 }
 
-static OCEntityHandlerResult HandleSVCGetRequest(const OCEntityHandlerRequest * ehRequest)
+static OCEntityHandlerResult HandleSVCGetRequest (const OCEntityHandlerRequest * ehRequest)
 {
     // Convert SVC data into JSON for transmission
-    size_t size = 0;
-    uint8_t *cborSvc = NULL;
-    OCStackResult res =  SVCToCBORPayload(gSvc, &cborSvc, &size);
-    OCEntityHandlerResult ehRet = (res == OC_STACK_OK) ? OC_EH_OK : OC_EH_ERROR;
+    char* jsonStr = BinToSvcJSON(gSvc);
+
+    OCEntityHandlerResult ehRet = (jsonStr ? OC_EH_OK : OC_EH_ERROR);
 
     // Send response payload to request originator
-    SendSRMCBORResponse(ehRequest, ehRet, cborSvc);
+    SendSRMResponse(ehRequest, ehRet, jsonStr);
 
-    OICFree(cborSvc);
+    OICFree(jsonStr);
 
     OIC_LOG_V (DEBUG, TAG, "%s RetVal %d", __func__ , ehRet);
     return ehRet;
 }
 
-static OCEntityHandlerResult HandleSVCPostRequest(const OCEntityHandlerRequest * ehRequest)
+static OCEntityHandlerResult HandleSVCPostRequest (const OCEntityHandlerRequest * ehRequest)
 {
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
-    uint8_t *payload = ((OCSecurityPayload *) ehRequest->payload)->securityData1;;
-    if (payload)
+
+    // Convert JSON SVC data into binary. This will also validate the SVC data received.
+    OicSecSvc_t* newSvc = JSONToSvcBin(((OCSecurityPayload*)ehRequest->payload)->securityData);
+
+    if (newSvc)
     {
-        // Convert CBOR SVC data into SVC. This will also validate the SVC data received.
-        OicSecSvc_t *newSvc = NULL;
-        OCStackResult res =  CBORPayloadToSVC(payload, CBOR_SIZE, &newSvc);
-        if (newSvc && res == OC_STACK_OK)
+        // Append the new SVC to existing SVC
+        LL_APPEND(gSvc, newSvc);
+
+        // Convert SVC data into JSON for update to persistent storage
+        char *jsonStr = BinToSvcJSON(gSvc);
+        if (jsonStr)
         {
-            // Append the new SVC to existing SVC
-            LL_APPEND(gSvc, newSvc);
-
-            // Convert SVC data into JSON for update to persistent storage
-            size_t size = 0;
-            uint8_t *cborPayload = NULL;
-            res = SVCToCBORPayload(gSvc, &cborPayload, &size);
-            if (cborPayload && OC_STACK_OK == res &&
-                UpdateSecureResourceInPS(OIC_JSON_SVC_NAME, cborPayload, size) == OC_STACK_OK)
+            cJSON *jsonSvc = cJSON_Parse(jsonStr);
+            OICFree(jsonStr);
+
+            if ((jsonSvc) &&
+                (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_SVC_NAME, jsonSvc)))
             {
                 ehRet = OC_EH_RESOURCE_CREATED;
             }
-            OICFree(cborPayload);
+            cJSON_Delete(jsonSvc);
         }
     }
 
     // Send payload to request originator
-    SendSRMCBORResponse(ehRequest, ehRet, NULL);
+    SendSRMResponse(ehRequest, ehRet, NULL);
 
     OIC_LOG_V (DEBUG, TAG, "%s RetVal %d", __func__ , ehRet);
     return ehRet;
 }
 
-/**
+/*
  * This internal method is the entity handler for SVC resources and
  * will handle REST request (GET/PUT/POST/DEL) for them.
  */
-static OCEntityHandlerResult SVCEntityHandler(OCEntityHandlerFlag flag,
-                                              OCEntityHandlerRequest * ehRequest,
-                                              void* callbackParameter)
+OCEntityHandlerResult SVCEntityHandler (OCEntityHandlerFlag flag,
+                                        OCEntityHandlerRequest * ehRequest,
+                                        void* callbackParameter)
 {
     (void) callbackParameter;
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
@@ -389,54 +308,51 @@ static OCEntityHandlerResult SVCEntityHandler(OCEntityHandlerFlag flag,
 
             default:
                 ehRet = OC_EH_ERROR;
-                SendSRMCBORResponse(ehRequest, ehRet, NULL);
+                SendSRMResponse(ehRequest, ehRet, NULL);
         }
     }
 
     return ehRet;
 }
 
-/**
+/*
  * This internal method is used to create '/oic/sec/svc' resource.
  */
-static OCStackResult CreateSVCResource()
+OCStackResult CreateSVCResource()
 {
-    OCStackResult ret = OCCreateResource(&gSvcHandle,
-                                         OIC_RSRC_TYPE_SEC_SVC,
-                                         OIC_MI_DEF,
-                                         OIC_RSRC_SVC_URI,
-                                         SVCEntityHandler,
-                                         NULL,
-                                         OC_OBSERVABLE);
+    OCStackResult ret;
+
+    ret = OCCreateResource(&gSvcHandle,
+                           OIC_RSRC_TYPE_SEC_SVC,
+                           OIC_MI_DEF,
+                           OIC_RSRC_SVC_URI,
+                           SVCEntityHandler,
+                           NULL,
+                           OC_OBSERVABLE);
 
     if (OC_STACK_OK != ret)
     {
-        OIC_LOG(FATAL, TAG, "Unable to instantiate SVC resource");
+        OIC_LOG (FATAL, TAG, "Unable to instantiate SVC resource");
         DeInitSVCResource();
     }
     return ret;
 }
 
+
 OCStackResult InitSVCResource()
 {
     OCStackResult ret = OC_STACK_ERROR;
 
-    OIC_LOG_V(DEBUG, TAG, "Begin %s ", __func__ );
+    OIC_LOG_V (DEBUG, TAG, "Begin %s ", __func__ );
 
-    uint8_t *data = NULL;
-    size_t size = 0;
-    ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_SVC_NAME, &data, &size);
-    // If database read failed
-    if (ret != OC_STACK_OK)
-    {
-        OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
-    }
+    // Read SVC resource from PS
+    char* jsonSVRDatabase = GetSVRDatabase();
 
-    if (data)
+    if (jsonSVRDatabase)
     {
         // Convert JSON SVC into binary format
-        ret = CBORPayloadToSVC(data, size, &gSvc);
-        OICFree(data);
+        gSvc = JSONToSvcBin(jsonSVRDatabase);
+        OICFree(jsonSVRDatabase);
     }
 
     // Instantiate 'oic.sec.svc'
@@ -447,10 +363,15 @@ OCStackResult InitSVCResource()
         DeInitSVCResource();
     }
 
-    OIC_LOG_V(DEBUG, TAG, "%s RetVal %d", __func__ , ret);
+    OIC_LOG_V (DEBUG, TAG, "%s RetVal %d", __func__ , ret);
     return ret;
 }
 
+/**
+ * Perform cleanup for SVC resources.
+ *
+ * @retval  none
+ */
 void DeInitSVCResource()
 {
     OCDeleteResource(gSvcHandle);
@@ -459,3 +380,4 @@ void DeInitSVCResource()
     DeleteSVCList(gSvc);
     gSvc = NULL;
 }
+
index 884ffe5..be35bb3 100644 (file)
@@ -47,7 +47,6 @@ srmtest_env.PrependUnique(CPPPATH = [
 #              '../../../../extlibs/tinydtls/',
                '../include'
                ])
-
 srmtest_env.AppendUnique(CXXFLAGS = ['-std=c++0x', '-Wall', '-pthread'])
 srmtest_env.AppendUnique(LIBS = ['-lpthread'])
 srmtest_env.AppendUnique(LIBPATH = [env.get('BUILD_DIR')])
@@ -70,7 +69,6 @@ if not env.get('RELEASE'):
 # Source files and Targets
 ######################################################################
 unittest = srmtest_env.Program('unittest', ['aclresourcetest.cpp',
-                                            'amaclresourcetest.cpp',
                                             'pstatresource.cpp',
                                             'doxmresource.cpp',
                                             'policyengine.cpp',
@@ -85,9 +83,7 @@ unittest = srmtest_env.Program('unittest', ['aclresourcetest.cpp',
 Alias("test", [unittest])
 
 unittest_src_dir = src_dir + '/resource/csdk/security/unittest/'
-unittest_build_dir = env.get('BUILD_DIR') + 'resource/csdk/security/unittest'
-
-srmtest_env.AppendUnique(CPPDEFINES = ['SECURITY_BUILD_UNITTEST_DIR='+unittest_build_dir])
+unittest_build_dir = env.get('BUILD_DIR') +'/resource/csdk/security/unittest'
 
 srmtest_env.Alias("install", srmtest_env.Install( unittest_build_dir,
     unittest_src_dir + 'oic_unittest.json'))
@@ -96,13 +92,6 @@ srmtest_env.Alias("install", srmtest_env.Install( unittest_build_dir,
 srmtest_env.Alias("install", srmtest_env.Install( unittest_build_dir,
     unittest_src_dir + 'oic_unittest_default_acl.json'))
 
-srmtest_env.Alias("install", srmtest_env.Install( unittest_build_dir,
-    unittest_src_dir + 'oic_unittest.dat'))
-srmtest_env.Alias("install", srmtest_env.Install( unittest_build_dir,
-    unittest_src_dir + 'oic_unittest_acl1.dat'))
-srmtest_env.Alias("install", srmtest_env.Install( unittest_build_dir,
-    unittest_src_dir + 'oic_unittest_default_acl.dat'))
-
 env.AppendTarget('test')
 if env.get('TEST') == '1':
        target_os = env.get('TARGET_OS')
@@ -116,3 +105,4 @@ if env.get('TEST') == '1':
                srmtest_env.AppendENVPath('LD_LIBRARY_PATH', ['./extlibs/gtest/gtest-1.7.0/lib/.libs'])
                ut = srmtest_env.Command ('ut', None, out_dir + '/resource/csdk/security/unittest/unittest')
                AlwaysBuild ('ut')
+
index b70f5a4..74fb3c5 100644 (file)
 #include <linux/limits.h>
 #include <sys/stat.h>
 #include "ocstack.h"
-#include "psinterface.h"
 #include "ocpayload.h"
 #include "oic_malloc.h"
 #include "oic_string.h"
+#include "cJSON.h"
 #include "cainterface.h"
 #include "secureresourcemanager.h"
 #include "securevirtualresourcetypes.h"
 #include "srmtestcommon.h"
 #include "srmutility.h"
 #include "logger.h"
-#include "doxmresource.h"
-#include "ocpayload.h"
-#include "ocpayloadcbor.h"
-#include "payload_logging.h"
-#include "security_internals.h"
 
 using namespace std;
 
 #define TAG  "SRM-ACL-UT"
 
-// These paths match jenkins build configuration.
-const char* DEFAULT_ACL_FILE_NAME = "/oic_unittest_default_acl.dat";
-const char* ACL1_FILE_NAME = "/oic_unittest_acl1.dat";
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+extern char * BinToAclJSON(const OicSecAcl_t * acl);
+extern OicSecAcl_t * JSONToAclBin(const char * jsonStr);
+extern void DeleteACLList(OicSecAcl_t* acl);
+OCStackResult  GetDefaultACL(OicSecAcl_t** defaultAcl);
+OCEntityHandlerResult ACLEntityHandler (OCEntityHandlerFlag flag,
+                                        OCEntityHandlerRequest * ehRequest);
+#ifdef __cplusplus
+}
+#endif
 
-#define NUM_ACE_FOR_WILDCARD_IN_ACL1_DAT (1)
+const char* JSON_FILE_NAME = "oic_unittest.json";
+const char* DEFAULT_ACL_JSON_FILE_NAME = "oic_unittest_default_acl.json";
+const char* ACL1_JSON_FILE_NAME = "oic_unittest_acl1.json";
 
-TEST(ACLResourceTest, CBORDefaultACLConversion)
-{
-    OicSecAcl_t *defaultAcl = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
-    ASSERT_TRUE(defaultAcl != NULL);
-    uint8_t defaultAclSub[] = { 0x2a };
-    memcpy(defaultAcl->subject.id, defaultAclSub, sizeof(defaultAclSub));
-    defaultAcl->permission = 2;
-    const char *defaulAclRsrc[] = { "/oic/res", "/oic/d", "/oic/p", "/oic/res/types/d",
-            "/oic/ad", "/oic/sec/acl", "/oic/sec/doxm", "/oic/sec/pstat"};
-    defaultAcl->resourcesLen = 8;
-    defaultAcl->resources = (char **)OICCalloc(defaultAcl->resourcesLen, sizeof(char *));
-    ASSERT_TRUE(defaultAcl->resources != NULL);
-    for (size_t i = 0 ; i < defaultAcl->resourcesLen; i++)
-    {
-        defaultAcl->resources[i] = OICStrdup(defaulAclRsrc[i]);
-        ASSERT_TRUE(defaultAcl->resources[i] != NULL);
-    }
-    defaultAcl->ownersLen = 1;
-    uint8_t defaultAclOwnrs[] = {0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32,
-        0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32};
-    defaultAcl->owners = (OicUuid_t *)OICCalloc(1, sizeof(OicUuid_t));
-    ASSERT_TRUE(defaultAcl->owners != NULL);
-    memcpy(defaultAcl->owners[0].id, defaultAclOwnrs, sizeof(defaultAclOwnrs));
-
-    size_t defaultAclSize = 0;
-    uint8_t *defaultPsStorage = NULL;
-    EXPECT_EQ(OC_STACK_OK, AclToCBORPayload(defaultAcl, &defaultPsStorage, &defaultAclSize));
-    ASSERT_TRUE(defaultPsStorage != NULL);
-    EXPECT_NE(0, defaultAclSize);
-
-    // This creates a default file oic_svr_db.dat, which is then needed by unit test.
-    CborEncoder encoder = { 0, 0, 0, 0};
-    const size_t cborSize = 255;
-    uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborSize);
-    ASSERT_TRUE(outPayload != NULL);
-    cbor_encoder_init(&encoder, outPayload, cborSize, 0);
-    CborEncoder map = { 0, 0, 0, 0 };
-    CborError cborEncoderResult = cbor_encoder_create_map(&encoder, &map, CborIndefiniteLength);
-    EXPECT_EQ(CborNoError, cborEncoderResult);
-    cborEncoderResult = cbor_encode_text_string(&map, OIC_JSON_ACL_NAME, sizeof(OIC_JSON_ACL_NAME) - 1);
-    EXPECT_EQ(CborNoError, cborEncoderResult);
-    cborEncoderResult = cbor_encode_byte_string(&map, defaultPsStorage, defaultAclSize);
-    EXPECT_EQ(CborNoError, cborEncoderResult);
-    cborEncoderResult = cbor_encoder_close_container(&encoder, &map);
-    EXPECT_EQ(CborNoError, cborEncoderResult);
-}
+#define NUM_ACE_FOR_WILDCARD_IN_ACL1_JSON (2)
 
-TEST(ACLResourceTest, CBORACLConversion)
+// JSON Marshalling Tests
+TEST(ACLResourceTest, JSONMarshallingTests)
 {
-    OicSecAcl_t *secAcl = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
-    ASSERT_TRUE(secAcl != NULL);
-    uint8_t subjectBytes[] = { 0x2a };
-    memcpy(secAcl->subject.id, subjectBytes, sizeof(subjectBytes));
-    secAcl->permission = 2;
-    const char *rsrc[] = { "/oic/res", "/oic/d", "/oic/p", "/oic/res/types/d",
-                           "/oic/ad", "/oic/sec/acl"};
-    secAcl->resourcesLen = 6;
-    secAcl->resources = (char **)OICCalloc(secAcl->resourcesLen, sizeof(char *));
-    ASSERT_TRUE(secAcl->resources != NULL);
-    for (size_t i = 0 ; i < secAcl->resourcesLen; i++)
+    char *jsonStr1 = ReadFile(ACL1_JSON_FILE_NAME);
+    if (jsonStr1)
     {
-        secAcl->resources[i] = OICStrdup(rsrc[i]);
-        ASSERT_TRUE(secAcl->resources[i] != NULL);
+        cJSON_Minify(jsonStr1);
+        /* Workaround : cJSON_Minify does not remove all the unwanted characters
+         from the end. Here is an attempt to remove those characters */
+        int len = strlen(jsonStr1);
+        while (len > 0)
+        {
+            if (jsonStr1[--len] == '}')
+            {
+                break;
+            }
+        }
+        jsonStr1[len + 1] = 0;
 
-    }
-    secAcl->ownersLen = 1;
-    uint8_t ownrs[] = {0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32,
-        0x32, 0x32, 0x32, 0x32, 0x32, 0x32};
-    secAcl->owners = (OicUuid_t *)OICCalloc(1, sizeof(OicUuid_t));
-    ASSERT_TRUE(secAcl->owners != NULL);
-    memcpy(secAcl->owners[0].id, ownrs, sizeof(ownrs));
-
-    OicSecAcl_t *secAcl1 = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
-    ASSERT_TRUE(secAcl1 != NULL);
-    memcpy(secAcl1->subject.id, subjectBytes, sizeof(subjectBytes));
-    secAcl1->permission = 6;
-    const char *rsrc1[] = { "/oic/sec/doxm", "/oic/sec/pstat"};
-    secAcl1->resourcesLen = 2;
-    secAcl1->resources = (char **)OICCalloc(secAcl1->resourcesLen, sizeof(char *));
-    ASSERT_TRUE(secAcl1->resources != NULL);
-    for (size_t i = 0 ; i < secAcl1->resourcesLen; i++)
-    {
-        secAcl1->resources[i] = OICStrdup(rsrc1[i]);
-        ASSERT_TRUE(secAcl1->resources[i] != NULL);
-    }
-    secAcl1->ownersLen = 1;
-    secAcl1->owners = (OicUuid_t *)OICCalloc(1, sizeof(OicUuid_t));
-    ASSERT_TRUE(secAcl1->owners != NULL);
-    memcpy(secAcl1->owners[0].id, ownrs, sizeof(ownrs));
-    secAcl->next = secAcl1;
-
-    OicSecAcl_t *secAcl2 = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
-    ASSERT_TRUE(secAcl2 != NULL);
-    uint8_t subjectBytes1[] = {0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31,
-        0x31, 0x31, 0x31, 0x31, 0x31, 0x31, 0x31};
-    memcpy(secAcl2->subject.id, subjectBytes1, sizeof(subjectBytes1));
-    secAcl2->permission = 255;
-    const char *rsrc2[] = {"/oic/light", "/oic/fan" };
-    secAcl2->resourcesLen = 2;
-    secAcl2->resources = (char **)OICCalloc(secAcl2->resourcesLen, sizeof(char *));
-    ASSERT_TRUE(secAcl2->resources != NULL);
-    for (size_t i = 0 ; i < secAcl2->resourcesLen; i++)
-    {
-        secAcl2->resources[i] = OICStrdup(rsrc2[i]);
-        ASSERT_TRUE(secAcl2->resources[i] != NULL);
-    }
-    secAcl2->ownersLen = 1;
-    secAcl2->owners = (OicUuid_t *)OICCalloc(1, sizeof(OicUuid_t));
-    ASSERT_TRUE(secAcl2->owners != NULL);
-    memcpy(secAcl2->owners[0].id, ownrs, sizeof(ownrs));
-    secAcl1->next = secAcl2;
-
-    OicSecAcl_t *secAcl3 = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
-    ASSERT_TRUE(secAcl3 != NULL);
-    uint8_t subjectBytes2[] = {0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33,
-                               0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x33};
-    memcpy(secAcl3->subject.id, subjectBytes2, sizeof(subjectBytes2));
-    secAcl3->permission = 255;
-    const char *rsrc3[] = {"/oic/light", "/oic/garage" };
-    secAcl3->resourcesLen = 2;
-    secAcl3->resources = (char **)OICCalloc(secAcl3->resourcesLen, sizeof(char *));
-    ASSERT_TRUE(secAcl3->resources != NULL);
-    for (size_t i = 0 ; i < secAcl3->resourcesLen; i++)
-    {
-        secAcl3->resources[i] = OICStrdup(rsrc3[i]);
-        ASSERT_TRUE(secAcl3->resources[i] != NULL);
-    }
-    secAcl3->ownersLen = 2;
-    secAcl3->owners = (OicUuid_t *)OICCalloc(2, sizeof(OicUuid_t));
-    ASSERT_TRUE(secAcl3->owners != NULL);
-    memcpy(secAcl3->owners[0].id, ownrs, sizeof(ownrs));
-    uint8_t ownrs1[] = {0x34, 0x34, 0x34, 0x34, 0x34, 0x34, 0x34, 0x34, 0x34, 0x34,
-                        0x34, 0x34, 0x34, 0x34, 0x34, 0x34};
-    memcpy(secAcl3->owners[1].id, ownrs1, sizeof(ownrs1));
-    secAcl2->next = secAcl3;
-    secAcl3->next = NULL;
-
-    size_t size = 0;
-    uint8_t *psStorage = NULL;
-    EXPECT_EQ(OC_STACK_OK, AclToCBORPayload(secAcl, &psStorage, &size));
-    ASSERT_TRUE(NULL != psStorage);
-    OicSecAcl_t *acl = CBORPayloadToAcl(psStorage, size);
-    ASSERT_TRUE(NULL != acl);
-    EXPECT_EQ(2, acl->permission);
-    EXPECT_EQ(6 , acl->resourcesLen);
-    EXPECT_STREQ("/oic/res", acl->resources[0]);
-    EXPECT_EQ(1, acl->ownersLen);
-}
+        OicSecAcl_t * acl = JSONToAclBin(jsonStr1);
+        EXPECT_TRUE(NULL != acl);
 
-//InitResource Tests
-TEST(ACLResourceTest, InitAclResource)
-{
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, InitACLResource());
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, DeInitACLResource());
+        char * jsonStr2 = BinToAclJSON(acl);
+        EXPECT_TRUE(NULL != jsonStr2);
+
+        EXPECT_STREQ(jsonStr1, jsonStr2);
+
+        OICFree(jsonStr1);
+        OICFree(jsonStr2);
+        DeleteACLList(acl);
+    }
 }
 
 // Default ACL tests
 TEST(ACLResourceTest, GetDefaultACLTests)
 {
-    uint8_t *payload = NULL;
-    size_t size = 0;
-
-    ASSERT_TRUE(ReadCBORFile(DEFAULT_ACL_FILE_NAME, &payload, &size));
-    ASSERT_TRUE(payload != NULL);
+    // Read default ACL from the file
+    char *jsonStr = ReadFile(DEFAULT_ACL_JSON_FILE_NAME);
+    if (jsonStr)
+    {
+        OicSecAcl_t * acl = JSONToAclBin(jsonStr);
+        EXPECT_TRUE(NULL != acl);
 
-    OicSecAcl_t *psAcl = CBORPayloadToAcl(payload, size);
-    ASSERT_TRUE(psAcl != NULL);
+        // Invoke API to generate default ACL
+        OicSecAcl_t * defaultAcl = NULL;
+        OCStackResult ret = GetDefaultACL(&defaultAcl);
+        EXPECT_TRUE(NULL == defaultAcl);
 
-    OicSecAcl_t *acl = NULL;
-    EXPECT_EQ(OC_STACK_OK, GetDefaultACL(&acl));
-    ASSERT_TRUE(acl != NULL);
+        EXPECT_TRUE(OC_STACK_ERROR == ret);
 
-    // Verify if the SRM generated default ACL matches with unit test default
-    if (acl && psAcl)
-    {
-        EXPECT_TRUE(memcmp(&(acl->subject), &(psAcl->subject), sizeof(OicUuid_t)) == 0);
-        EXPECT_EQ(acl->resourcesLen, psAcl->resourcesLen);
-        for (size_t i = 0; i < acl->resourcesLen; i++)
+        // Verify if the SRM generated default ACL matches with unit test default
+        if (acl && defaultAcl)
         {
-            EXPECT_EQ(strlen(acl->resources[i]), strlen(psAcl->resources[i]));
-            EXPECT_TRUE(memcmp(acl->resources[i], psAcl->resources[i],
-                            strlen(acl->resources[i])) == 0);
+            EXPECT_TRUE(memcmp(&(acl->subject), &(defaultAcl->subject), sizeof(OicUuid_t)) == 0);
+            EXPECT_EQ(acl->resourcesLen, defaultAcl->resourcesLen);
+            for (size_t i = 0; i < acl->resourcesLen; i++)
+            {
+                EXPECT_EQ(strlen(acl->resources[i]), strlen(defaultAcl->resources[i]));
+                EXPECT_TRUE(
+                        memcmp(acl->resources[i], defaultAcl->resources[i],
+                                strlen(acl->resources[i])) == 0);
+            }
+            EXPECT_EQ(acl->permission, defaultAcl->permission);
         }
-        EXPECT_EQ(acl->permission, psAcl->permission);
-    }
 
-    DeleteACLList(psAcl);
-    DeleteACLList(acl);
-    DeInitACLResource();
-    OICFree(payload);
+        // Perform cleanup
+        DeleteACLList(acl);
+        DeleteACLList(defaultAcl);
+        OICFree(jsonStr);
+    }
 }
 
+
 // 'POST' ACL tests
 TEST(ACLResourceTest, ACLPostTest)
 {
-    // Read an ACL from the file
-    uint8_t *payload = NULL;
-    size_t size = 0;
+    OCEntityHandlerRequest ehReq =  OCEntityHandlerRequest();
 
-    ASSERT_TRUE(ReadCBORFile(ACL1_FILE_NAME, &payload, &size));
-    ASSERT_TRUE(NULL != payload);
-
-    OCSecurityPayload *securityPayload = OCSecurityPayloadCBORCreate(payload);
-    ASSERT_TRUE(NULL != securityPayload);
+    // Read an ACL from the file
+    char *jsonStr = ReadFile(ACL1_JSON_FILE_NAME);
+    if (jsonStr)
+    {
+        static OCPersistentStorage ps = OCPersistentStorage();
 
-    static OCPersistentStorage ps = OCPersistentStorage();
-    SetPersistentHandler(&ps, true);
+        SetPersistentHandler(&ps, true);
 
-    // Create Entity Handler POST request payload
-    OCEntityHandlerRequest ehReq = OCEntityHandlerRequest();
-    ehReq.method = OC_REST_POST;
-    ehReq.payload = (OCPayload *) securityPayload;
+        // Create Entity Handler POST request payload
+        ehReq.method = OC_REST_POST;
+        ehReq.payload = (OCPayload*)OCSecurityPayloadCreate(jsonStr);
 
-    OCEntityHandlerResult ehRet = ACLEntityHandler(OC_REQUEST_FLAG, &ehReq, NULL);
-    EXPECT_EQ(OC_EH_ERROR, ehRet);
+        OCEntityHandlerResult ehRet = ACLEntityHandler(OC_REQUEST_FLAG, &ehReq);
+        EXPECT_TRUE(OC_EH_ERROR == ehRet);
 
-    OicSecAcl_t *acl = CBORPayloadToAcl(payload, size);
-    ASSERT_TRUE(NULL != acl);
+        // Convert JSON into OicSecAcl_t for verification
+        OicSecAcl_t * acl = JSONToAclBin(jsonStr);
+        EXPECT_TRUE(NULL != acl);
 
-    // Verify if SRM contains ACL for the subject
-    OicSecAcl_t *savePtr = NULL;
-    const OicSecAcl_t* subjectAcl = GetACLResourceData(&(acl->subject), &savePtr);
-    ASSERT_TRUE(NULL == subjectAcl);
+        // Verify if SRM contains ACL for the subject
+        OicSecAcl_t* savePtr = NULL;
+        const OicSecAcl_t* subjectAcl = GetACLResourceData(&(acl->subject), &savePtr);
+        EXPECT_TRUE(NULL != subjectAcl);
 
-    // Perform cleanup
-    OICFree(payload);
-    DeleteACLList(acl);
-    DeInitACLResource();
+        // Perform cleanup
+        DeleteACLList(acl);
+        DeInitACLResource();
+        OCPayloadDestroy(ehReq.payload);
+        OICFree(jsonStr);
+    }
 }
 
+
 // GetACLResource tests
 TEST(ACLResourceTest, GetACLResourceTests)
 {
-    // Read an ACL from the file
-    static OCPersistentStorage ps = OCPersistentStorage();
-    SetPersistentHandler(&ps, true);
-
-    uint8_t *payload = NULL;
-    size_t size = 0;
+    // gAcl is a pointer to the the global ACL used by SRM
+    extern OicSecAcl_t  *gAcl;
 
-    ASSERT_TRUE(ReadCBORFile(ACL1_FILE_NAME, &payload, &size));
-    ASSERT_TRUE(payload != NULL);
-
-    OicSecAcl_t *defaultPsAcl = CBORPayloadToAcl(payload, size);
-    ASSERT_TRUE(defaultPsAcl != NULL);
-
-    OicSecAcl_t *acl1 = NULL;
-    EXPECT_EQ(OC_STACK_OK, GetDefaultACL(&acl1));
-    ASSERT_TRUE(acl1 != NULL);
-    EXPECT_EQ(OC_STACK_OK, SetDefaultACL(acl1));
+    // Read an ACL from the file
+    char *jsonStr = ReadFile(ACL1_JSON_FILE_NAME);
+    if (jsonStr)
+    {
+        gAcl = JSONToAclBin(jsonStr);
+        EXPECT_TRUE(NULL != gAcl);
 
-    // Verify that ACL file contains 2 ACE entries for 'WILDCARD' subject
-    const OicSecAcl_t *acl = NULL;
-    OicSecAcl_t *savePtr = NULL;
-    OicUuid_t subject = WILDCARD_SUBJECT_ID;
-    int count = 0;
+        // Verify that ACL file contains 2 ACE entries for 'WILDCARD' subject
+        const OicSecAcl_t* acl = NULL;
+        OicSecAcl_t* savePtr = NULL;
+        OicUuid_t subject = WILDCARD_SUBJECT_ID;
+        int count = 0;
 
-    do
-    {
-        acl = GetACLResourceData(&subject, &savePtr);
-        count = (NULL != acl) ? count + 1 : count;
-    } while (acl != NULL);
+        do
+        {
+            acl = GetACLResourceData(&subject, &savePtr);
+            count = (NULL != acl) ? count + 1 : count;
+        } while (acl != NULL);
 
-    EXPECT_EQ(count, NUM_ACE_FOR_WILDCARD_IN_ACL1_DAT);
+        EXPECT_EQ(count, NUM_ACE_FOR_WILDCARD_IN_ACL1_JSON);
 
-    /* Perform cleanup */
-    OICFree(payload);
-    DeleteACLList(defaultPsAcl);
-    DeInitACLResource();
+        /* Perform cleanup */
+        DeleteACLList(gAcl);
+        gAcl = NULL;
+        OICFree(jsonStr);
+    }
 }
 
 static OCStackResult  populateAcl(OicSecAcl_t *acl,  int numRsrc)
 {
-     OCStackResult ret = OC_STACK_ERROR;
+    OCStackResult ret = OC_STACK_ERROR;
     memcpy(acl->subject.id, "2222222222222222", sizeof(acl->subject.id));
     acl->resourcesLen = (size_t)numRsrc;
     acl->resources = (char**)OICCalloc(acl->resourcesLen, sizeof(char*));
@@ -354,150 +237,158 @@ exit:
 //'DELETE' ACL test
 TEST(ACLResourceTest, ACLDeleteWithSingleResourceTest)
 {
-    //Populate ACL
+    OCEntityHandlerRequest ehReq = OCEntityHandlerRequest();
+    static OCPersistentStorage ps = OCPersistentStorage();
+    char *jsonStr = NULL;
     OicSecAcl_t acl = OicSecAcl_t();
-    EXPECT_EQ(OC_STACK_OK, populateAcl(&acl, 1));
+    OicSecAcl_t* savePtr = NULL;
+    const OicSecAcl_t* subjectAcl1 = NULL;
+    const OicSecAcl_t* subjectAcl2 = NULL;
+    OCEntityHandlerResult ehRet = OC_EH_ERROR;
+    char query[] = "sub=MjIyMjIyMjIyMjIyMjIyMg==;rsrc=/a/led";
 
-    //GET CBOR POST payload
-    size_t size = 0;
-    uint8_t  *payload = NULL;
-    EXPECT_EQ(OC_STACK_OK, AclToCBORPayload(&acl, &payload, &size));
-    ASSERT_TRUE(NULL != payload);
+    SetPersistentHandler(&ps, true);
 
-    // Security Payload
-    OCSecurityPayload *securityPayload = OCSecurityPayloadCBORCreate(payload);
-    ASSERT_TRUE(NULL != securityPayload);
+    //Populate ACL
+    VERIFY_SUCCESS(TAG, (OC_STACK_OK == populateAcl(&acl, 1)), ERROR);
 
-    static OCPersistentStorage ps = OCPersistentStorage();
-    SetPersistentHandler(&ps, true);
+    //GET json POST payload
+    jsonStr = BinToAclJSON(&acl);
+    VERIFY_NON_NULL(TAG, jsonStr, ERROR);
 
     // Create Entity Handler POST request payload
-    OCEntityHandlerRequest ehReq = OCEntityHandlerRequest();
-    ehReq.payload = (OCPayload *) securityPayload;
     ehReq.method = OC_REST_POST;
-    OCEntityHandlerResult ehRet = OC_EH_ERROR;
-    ehRet = ACLEntityHandler(OC_REQUEST_FLAG, &ehReq, NULL);
-    EXPECT_EQ(OC_EH_RESOURCE_CREATED, ehRet);
+    ehReq.payload = (OCPayload*)OCSecurityPayloadCreate(jsonStr);
+    ehRet = ACLEntityHandler(OC_REQUEST_FLAG, &ehReq);
+    EXPECT_TRUE(OC_EH_ERROR == ehRet);
 
     // Verify if SRM contains ACE for the subject
-    OicSecAcl_t* savePtr = NULL;
-    const OicSecAcl_t* subjectAcl1 = GetACLResourceData(&acl.subject, &savePtr);
-    ASSERT_TRUE(NULL != subjectAcl1);
+    savePtr = NULL;
+    subjectAcl1 = GetACLResourceData(&acl.subject, &savePtr);
+    EXPECT_TRUE(NULL != subjectAcl1);
 
     // Create Entity Handler DELETE request
     ehReq.method = OC_REST_DELETE;
-    char query[] = "sub=2222222222222222;rsrc=/a/led";
-    ehReq.query = (char *)OICMalloc(strlen(query)+1);
-    ASSERT_TRUE(NULL !=  ehReq.query);
+    ehReq.query = (char*)OICMalloc(strlen(query)+1);
+    VERIFY_NON_NULL(TAG, ehReq.query, ERROR);
     OICStrcpy(ehReq.query, strlen(query)+1, query);
-    ehRet = ACLEntityHandler(OC_REQUEST_FLAG, &ehReq, NULL);
-    // This returns error as WILDARD is used as a subject query.
-    EXPECT_EQ(OC_EH_RESOURCE_DELETED, ehRet);
+    ehRet = ACLEntityHandler(OC_REQUEST_FLAG, &ehReq);
+    EXPECT_TRUE(OC_EH_ERROR == ehRet);
 
     // Verify if SRM has deleted ACE for the subject
     savePtr = NULL;
-    const OicSecAcl_t* subjectAcl2 = GetACLResourceData(&acl.subject, &savePtr);
-    ASSERT_TRUE(NULL == subjectAcl2);
+    subjectAcl2 = GetACLResourceData(&acl.subject, &savePtr);
+    EXPECT_TRUE(NULL == subjectAcl2);
 
+exit:
     // Perform cleanup
-    DeInitACLResource();
+    if(NULL != subjectAcl1)
+    {
+        DeInitACLResource();
+    }
+    OCPayloadDestroy(ehReq.payload);
     OICFree(ehReq.query);
-    OICFree(payload);
+    OICFree(jsonStr);
+
 }
 
 TEST(ACLResourceTest, ACLDeleteWithMultiResourceTest)
 {
-    //Populate ACL
+    OCEntityHandlerRequest ehReq = OCEntityHandlerRequest();
+    static OCPersistentStorage ps = OCPersistentStorage();
     OicSecAcl_t acl = OicSecAcl_t();
-    EXPECT_EQ(OC_STACK_OK, populateAcl(&acl, 2));
+    char *jsonStr = NULL;
+    OicSecAcl_t* savePtr = NULL;
+    const OicSecAcl_t* subjectAcl1 = NULL;
+    const OicSecAcl_t* subjectAcl2 = NULL;
+    OCEntityHandlerResult ehRet = OC_EH_ERROR;
+    char query[] = "sub=MjIyMjIyMjIyMjIyMjIyMg==;rsrc=/a/led";
 
-    //GET CBOR POST payload
-    size_t size = 0;
-    uint8_t *payload = NULL;
-    EXPECT_EQ(OC_STACK_OK, AclToCBORPayload(&acl, &payload, &size));
-    ASSERT_TRUE(NULL != payload);
+    SetPersistentHandler(&ps, true);
 
-    // Security Payload
-    OCSecurityPayload *securityPayload = OCSecurityPayloadCBORCreate(payload);
-    ASSERT_TRUE(NULL!= securityPayload);
+    //Populate ACL
+    VERIFY_SUCCESS(TAG, (OC_STACK_OK == populateAcl(&acl, 2)), ERROR);
 
-    static OCPersistentStorage ps = OCPersistentStorage();
-    SetPersistentHandler(&ps, true);
+    //GET json POST payload
+    jsonStr = BinToAclJSON(&acl);
+    VERIFY_NON_NULL(TAG, jsonStr, ERROR);
 
     // Create Entity Handler POST request payload
-    OCEntityHandlerRequest ehReq = OCEntityHandlerRequest();
     ehReq.method = OC_REST_POST;
-    ehReq.payload = (OCPayload *)securityPayload;
-    OCEntityHandlerResult ehRet = ACLEntityHandler(OC_REQUEST_FLAG, &ehReq, NULL);
-    EXPECT_EQ(OC_EH_RESOURCE_CREATED, ehRet);
+    ehReq.payload = (OCPayload*)OCSecurityPayloadCreate(jsonStr);
+    ehRet = ACLEntityHandler(OC_REQUEST_FLAG, &ehReq);
+    EXPECT_TRUE(OC_EH_ERROR == ehRet);
 
     // Verify if SRM contains ACE for the subject with two resources
-    OicSecAcl_t* savePtr = NULL;
-    const OicSecAcl_t* subjectAcl1 = GetACLResourceData(&acl.subject, &savePtr);
-    ASSERT_TRUE(NULL != subjectAcl1);
-    EXPECT_EQ(2, subjectAcl1->resourcesLen);
+    savePtr = NULL;
+    subjectAcl1 = GetACLResourceData(&acl.subject, &savePtr);
+    VERIFY_NON_NULL(TAG, subjectAcl1, ERROR);
+    EXPECT_TRUE(subjectAcl1->resourcesLen == 2);
 
     // Create Entity Handler DELETE request
     ehReq.method = OC_REST_DELETE;
-    char query[] = "sub=2222222222222222;rsrc=/a/led";
-    ehReq.query = (char *)OICMalloc(strlen(query)+1);
-    ASSERT_TRUE(NULL != ehReq.query);
+    ehReq.query = (char*)OICMalloc(strlen(query)+1);
+    VERIFY_NON_NULL(TAG, ehReq.query, ERROR);
     OICStrcpy(ehReq.query, strlen(query)+1, query);
 
-    ehRet = ACLEntityHandler(OC_REQUEST_FLAG, &ehReq, NULL);
-    EXPECT_EQ(OC_EH_RESOURCE_DELETED, ehRet);
+    ehRet = ACLEntityHandler(OC_REQUEST_FLAG, &ehReq);
+    EXPECT_TRUE(OC_EH_ERROR == ehRet);
 
     // Verify if SRM contains ACL for the subject but only with one resource
     savePtr = NULL;
-    const OicSecAcl_t* subjectAcl2 = GetACLResourceData(&acl.subject, &savePtr);
-    ASSERT_TRUE(NULL != subjectAcl2);
-    EXPECT_EQ(1, subjectAcl2->resourcesLen);
+    subjectAcl2 = GetACLResourceData(&acl.subject, &savePtr);
+    VERIFY_NON_NULL(TAG, subjectAcl2, ERROR);
+    EXPECT_TRUE(subjectAcl2->resourcesLen == 1);
 
+exit:
     // Perform cleanup
-    DeInitACLResource();
+    if(NULL != subjectAcl1)
+    {
+        DeInitACLResource();
+    }
+    OCPayloadDestroy(ehReq.payload);
     OICFree(ehReq.query);
-    OICFree(payload);
+    OICFree(jsonStr);
 }
 
 //'GET' with query ACL test
+
 TEST(ACLResourceTest, ACLGetWithQueryTest)
 {
-    //Populate ACL
+    OCEntityHandlerRequest ehReq = OCEntityHandlerRequest();
+    static OCPersistentStorage ps = OCPersistentStorage();
     OicSecAcl_t acl = OicSecAcl_t();
-    EXPECT_EQ(OC_STACK_OK, populateAcl(&acl, 1));
+    char *jsonStr = NULL;
+    OCEntityHandlerResult ehRet = OC_EH_ERROR;
+    char query[] = "sub=MjIyMjIyMjIyMjIyMjIyMg==;rsrc=/a/led";
 
-    //GET CBOR POST payload
-    size_t size = 0;
-    uint8_t *payload = NULL;
-    EXPECT_EQ(OC_STACK_OK, AclToCBORPayload(&acl, &payload, &size));
-    ASSERT_TRUE(NULL != payload);
+    SetPersistentHandler(&ps, true);
 
-    // Security Payload
-    OCSecurityPayload *securityPayload = OCSecurityPayloadCBORCreate(payload);
-    ASSERT_TRUE(NULL != securityPayload);
+    //Populate ACL
+    VERIFY_SUCCESS(TAG, (OC_STACK_OK == populateAcl(&acl, 1)), ERROR);
 
-    static OCPersistentStorage ps = OCPersistentStorage();
-    SetPersistentHandler(&ps, true);
+    //GET json POST payload
+    jsonStr = BinToAclJSON(&acl);
+    VERIFY_NON_NULL(TAG, jsonStr, ERROR);
 
     //Create Entity Handler POST request payload
-    OCEntityHandlerRequest ehReq = OCEntityHandlerRequest();
     ehReq.method = OC_REST_POST;
-    ehReq.payload = (OCPayload *)securityPayload;
-    OCEntityHandlerResult ehRet = ACLEntityHandler(OC_REQUEST_FLAG, &ehReq, NULL);
-    EXPECT_EQ(OC_EH_RESOURCE_CREATED, ehRet);
+    ehReq.payload = (OCPayload*)OCSecurityPayloadCreate(jsonStr);
+    ehRet = ACLEntityHandler(OC_REQUEST_FLAG, &ehReq);
+    EXPECT_TRUE(OC_EH_ERROR == ehRet);
 
     //Create Entity Handler GET request wit query
-    ehReq.method = OC_REST_GET;
-    char query[] = "sub=2222222222222222;rsrc=/a/led";
+    ehReq.method =  OC_REST_GET;
     ehReq.query = (char*)OICMalloc(strlen(query)+1);
-    ASSERT_TRUE(NULL != ehReq.query);
+    VERIFY_NON_NULL(TAG, ehReq.query, ERROR);
     OICStrcpy(ehReq.query, strlen(query)+1, query);
 
-    ehRet = ACLEntityHandler(OC_REQUEST_FLAG, &ehReq, NULL);
-    EXPECT_EQ(OC_EH_OK, ehRet);
+    ehRet = ACLEntityHandler(OC_REQUEST_FLAG, &ehReq);
+    EXPECT_TRUE(OC_EH_OK == ehRet);
 
+exit:
     // Perform cleanup
-    DeInitACLResource();
+    OCPayloadDestroy(ehReq.payload);
     OICFree(ehReq.query);
-    OICFree(payload);
+    OICFree(jsonStr);
 }
diff --git a/resource/csdk/security/unittest/amaclresourcetest.cpp b/resource/csdk/security/unittest/amaclresourcetest.cpp
deleted file mode 100644 (file)
index e819f38..0000000
+++ /dev/null
@@ -1,204 +0,0 @@
-//******************************************************************
-//
-// Copyright 2015 Samsung Electronics All Rights Reserved.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-//      http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-//
-//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
-
-#include "gtest/gtest.h"
-#include "cainterface.h"
-#include "ocstack.h"
-#include "ocpayload.h"
-#include "oic_malloc.h"
-#include "oic_string.h"
-#include "payload_logging.h"
-#include "psinterface.h"
-#include "secureresourcemanager.h"
-#include "securevirtualresourcetypes.h"
-#include "srmresourcestrings.h"
-#include "srmutility.h"
-#include "amaclresource.h"
-#include "security_internals.h"
-
-using namespace std;
-
-#define TAG  "SRM-AMACL-UT"
-
-TEST(AMACLResourceTest, CBORAMACLConversion)
-{
-    OicSecAmacl_t *secAmacl = (OicSecAmacl_t *) OICCalloc(1, sizeof(*secAmacl));
-    ASSERT_TRUE(NULL != secAmacl);
-    uint8_t amss[] = {0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35,
-        0x35, 0x35, 0x35, 0x35, 0x35, 0x35};
-    uint8_t amss1[] = {0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
-        0x36, 0x36, 0x36, 0x36, 0x36, 0x36};
-    secAmacl->amssLen = 2;
-    secAmacl->amss = (OicUuid_t *)OICCalloc(secAmacl->amssLen, sizeof(*secAmacl->amss));
-    if (!secAmacl->amss)
-    {
-        OICFree(secAmacl);
-    }
-    ASSERT_TRUE(NULL != secAmacl->amss);
-    memcpy(secAmacl->amss[0].id, amss, sizeof(amss));
-    memcpy(secAmacl->amss[1].id, amss1, sizeof(amss1));
-
-    const char *rsrc[] = { "/a/led", "/a/fan"};
-    secAmacl->resourcesLen = 2;
-    secAmacl->resources = (char **)OICCalloc(secAmacl->resourcesLen,
-                          sizeof(*secAmacl->resources));
-    if (!secAmacl->resources)
-    {
-        OICFree(secAmacl->amss);
-        OICFree(secAmacl);
-    }
-    ASSERT_TRUE(NULL != secAmacl->resources);
-    for (size_t i = 0 ; i < secAmacl->resourcesLen; i++)
-    {
-        secAmacl->resources[i] = OICStrdup(rsrc[i]);
-        ASSERT_TRUE(NULL != secAmacl->resources[i]);
-    }
-    secAmacl->ownersLen = 1;
-    uint8_t ownrs[] = {0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32, 0x32,
-        0x32, 0x32, 0x32, 0x32, 0x32, 0x32};
-    secAmacl->owners = (OicUuid_t *)OICCalloc(1, sizeof(*secAmacl->owners));
-    if (!secAmacl->owners)
-    {
-        OICFree(secAmacl->resources);
-        OICFree(secAmacl->amss);
-        OICFree(secAmacl);
-    }
-    ASSERT_TRUE(NULL != secAmacl->owners);
-    memcpy(secAmacl->owners[0].id, ownrs, sizeof(ownrs));
-
-    OicSecAmacl_t *secAmacl1 = (OicSecAmacl_t *) OICCalloc(1, sizeof(*secAmacl1));
-    if (!secAmacl1)
-    {
-        OICFree(secAmacl->owners);
-        OICFree(secAmacl->resources);
-        OICFree(secAmacl->amss);
-        OICFree(secAmacl);
-    }
-    ASSERT_TRUE(NULL != secAmacl1);
-    secAmacl1->amssLen = 2;
-    secAmacl1->amss = (OicUuid_t *)OICCalloc(2, sizeof(*secAmacl1->amss));
-    if (!secAmacl1->amss)
-    {
-        OICFree(secAmacl->owners);
-        OICFree(secAmacl->resources);
-        OICFree(secAmacl->amss);
-        OICFree(secAmacl);
-        OICFree(secAmacl1);
-    }
-    ASSERT_TRUE(NULL != secAmacl1->amss);
-    memcpy(secAmacl1->amss[0].id, amss, sizeof(amss));
-    memcpy(secAmacl1->amss[1].id, amss1, sizeof(amss1));
-
-    const char *rsrc1[] = { "/b/led", "/b/fan"};
-    secAmacl1->resourcesLen = 2;
-    secAmacl1->resources = (char **)OICCalloc(secAmacl1->resourcesLen,
-                            sizeof(*secAmacl1->resources));
-    if (!secAmacl1->resources)
-    {
-        OICFree(secAmacl->owners);
-        OICFree(secAmacl->resources);
-        OICFree(secAmacl->amss);
-        OICFree(secAmacl);
-        OICFree(secAmacl1->amss);
-        OICFree(secAmacl1);
-    }
-    ASSERT_TRUE(NULL != secAmacl1->resources);
-    for (size_t i = 0 ; i < secAmacl1->resourcesLen; i++)
-    {
-        secAmacl1->resources[i] = OICStrdup(rsrc1[i]);
-        ASSERT_TRUE(NULL != secAmacl1->resources[i]);
-    }
-    secAmacl1->ownersLen = 1;
-    secAmacl1->owners = (OicUuid_t *)OICCalloc(1, sizeof(*secAmacl1->owners));
-    if (!secAmacl1->owners)
-    {
-        OICFree(secAmacl->owners);
-        OICFree(secAmacl->resources);
-        OICFree(secAmacl->amss);
-        OICFree(secAmacl);
-        OICFree(secAmacl1->resources);
-        OICFree(secAmacl1->amss);
-        OICFree(secAmacl1);
-    }
-    ASSERT_TRUE(NULL != secAmacl1->owners);
-    memcpy(secAmacl1->owners[0].id, ownrs, sizeof(ownrs));
-    secAmacl1->next = NULL;
-    secAmacl->next = secAmacl1;
-
-    size_t size = 0;
-    uint8_t *psStorage = NULL;
-    EXPECT_EQ(OC_STACK_OK, AmaclToCBORPayload(secAmacl, &psStorage, &size));
-    if (!psStorage)
-    {
-        OICFree(secAmacl->owners);
-        OICFree(secAmacl->resources);
-        OICFree(secAmacl->amss);
-        OICFree(secAmacl);
-        OICFree(secAmacl1->owners);
-        OICFree(secAmacl1->resources);
-        OICFree(secAmacl1->amss);
-        OICFree(secAmacl1);
-    }
-    ASSERT_TRUE(NULL != psStorage);
-
-    OicSecAmacl_t *amacl = NULL;
-    EXPECT_EQ(OC_STACK_OK, CBORPayloadToAmacl(psStorage, size, &amacl));
-    if (!amacl)
-    {
-        OICFree(secAmacl->owners);
-        OICFree(secAmacl->resources);
-        OICFree(secAmacl->amss);
-        OICFree(secAmacl);
-        OICFree(secAmacl1->owners);
-        OICFree(secAmacl1->resources);
-        OICFree(secAmacl1->amss);
-        OICFree(secAmacl1);
-        OICFree(psStorage);
-    }
-    ASSERT_TRUE(NULL != amacl);
-
-    EXPECT_EQ(secAmacl->amssLen, amacl->amssLen);
-    EXPECT_EQ(sizeof(secAmacl->amss[0].id), sizeof(amacl->amss[0].id));
-    EXPECT_EQ(sizeof(secAmacl->amss[1].id), sizeof(amacl->amss[1].id));
-    EXPECT_STREQ(secAmacl->resources[0], amacl->resources[0]);
-    EXPECT_STREQ(secAmacl->resources[1], amacl->resources[1]);
-    EXPECT_EQ(secAmacl->resourcesLen, amacl->resourcesLen);
-    EXPECT_EQ(secAmacl->ownersLen, amacl->ownersLen);
-    EXPECT_EQ(*secAmacl->owners[0].id, *amacl->owners[0].id);
-
-    EXPECT_EQ(secAmacl->next->amssLen, amacl->next->amssLen);
-    EXPECT_EQ(sizeof(secAmacl->next->amss[0].id), sizeof(amacl->next->amss[0].id));
-    EXPECT_STREQ(secAmacl->next->resources[0], amacl->next->resources[0]);
-    EXPECT_STREQ(secAmacl->next->resources[1], amacl->next->resources[1]);
-    EXPECT_EQ(secAmacl->next->resourcesLen, amacl->next->resourcesLen);
-    EXPECT_EQ(secAmacl->next->ownersLen, amacl->next->ownersLen);
-    EXPECT_EQ(*secAmacl->next->owners[0].id, *amacl->next->owners[0].id);
-
-    OICFree(secAmacl->owners);
-    OICFree(secAmacl->resources);
-    OICFree(secAmacl->amss);
-    OICFree(secAmacl);
-    OICFree(secAmacl1->owners);
-    OICFree(secAmacl1->resources);
-    OICFree(secAmacl1->amss);
-    OICFree(secAmacl1);
-    OICFree(psStorage);
-    OICFree(amacl);
-}
index 4c4e0c9..dd62f15 100644 (file)
@@ -1,5 +1,3 @@
-//******************************************************************
-//
 // Copyright 2015 Intel Mobile Communications GmbH All Rights Reserved.
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #include "gtest/gtest.h"
-#include "logger.h"
-#include "ocpayload.h"
 #include "ocstack.h"
-#include "oic_malloc.h"
-#include "oic_string.h"
+#include "ocpayload.h"
 #include "resourcemanager.h"
-#include "credresource.h"
 #include "securevirtualresourcetypes.h"
+#include "credresource.h"
+#include "oic_malloc.h"
+#include "oic_string.h"
 #include "srmtestcommon.h"
 #include "srmutility.h"
-#include "psinterface.h"
-#include "security_internals.h"
+#include "logger.h"
 
 #define TAG "SRM-CRED-UT"
 
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+//Declare Cred resource methods for testing
+OCStackResult CreateCredResource();
+OCEntityHandlerResult CredEntityHandler (OCEntityHandlerFlag flag,
+                OCEntityHandlerRequest * ehRequest);
+char * BinToCredJSON(const OicSecCred_t * pstat);
+OicSecCred_t * JSONToCredBin(const char * jsonStr);
+void InitSecCredInstance(OicSecCred_t * cred);
+void DeleteCredList(OicSecCred_t* cred);
+const OicSecCred_t* GetCredResourceData(const OicUuid_t* subject);
+
+#ifdef __cplusplus
+}
+#endif
+
+
 OicSecCred_t * getCredList()
 {
+
+    OicSecCred_t * cred = NULL;
     size_t sz = 0;
-    OicSecCred_t *cred = (OicSecCred_t *)OICCalloc(1, sizeof(*cred));
+
+    cred = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
     VERIFY_NON_NULL(TAG, cred, ERROR);
     cred->credId = 1234;
     OICStrcpy((char *)cred->subject.id, sizeof(cred->subject.id), "subject1");
@@ -52,14 +70,15 @@ OicSecCred_t * getCredList()
 #endif
 
     cred->credType = SYMMETRIC_PAIR_WISE_KEY;
-    cred->privateData.data = (uint8_t *)OICCalloc(1, strlen("My private Key11") + 1);
+    cred->privateData.data = (char *)OICCalloc(1, strlen("My private Key11") + 1);
     VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
-    OICStrcpy((char *)cred->privateData.data, strlen("My private Key11")+1,"My private Key11");
+    OICStrcpy(cred->privateData.data, strlen("My private Key11")+1,"My private Key11");
     cred->ownersLen = 1;
-    cred->owners = (OicUuid_t *)OICCalloc(cred->ownersLen, sizeof(*cred->owners));
+    cred->owners = (OicUuid_t*)OICCalloc(cred->ownersLen, sizeof(OicUuid_t));
     VERIFY_NON_NULL(TAG, cred->owners, ERROR);
     OICStrcpy((char *)cred->owners[0].id, sizeof(cred->owners[0].id), "ownersId11");
-    cred->next = (OicSecCred_t*)OICCalloc(1, sizeof(*cred->next));
+
+    cred->next = (OicSecCred_t*)OICCalloc(1, sizeof(OicSecCred_t));
     VERIFY_NON_NULL(TAG, cred->next, ERROR);
     cred->next->credId = 5678;
     OICStrcpy((char *)cred->next->subject.id, sizeof(cred->next->subject.id), "subject2");
@@ -68,9 +87,9 @@ OicSecCred_t * getCredList()
 #endif
     cred->next->credType = SYMMETRIC_PAIR_WISE_KEY;
     sz = strlen("My private Key21") + 1;
-    cred->next->privateData.data = (uint8_t *)OICCalloc(1, sz);
+    cred->next->privateData.data = (char *)OICCalloc(1, sz);
     VERIFY_NON_NULL(TAG, cred->next->privateData.data, ERROR);
-    OICStrcpy((char *)cred->next->privateData.data, sz, "My private Key21");
+    OICStrcpy(cred->next->privateData.data, sz,"My private Key21");
 #if 0
     sz = strlen("My Public Key123") + 1
     cred->next->publicData.data = (char *)OICCalloc(1, sz);
@@ -78,7 +97,7 @@ OicSecCred_t * getCredList()
     OICStrcpy(cred->next->publicData.data, sz,"My Public Key123");
 #endif
     cred->next->ownersLen = 2;
-    cred->next->owners = (OicUuid_t *)OICCalloc(cred->next->ownersLen, sizeof(*cred->next->owners));
+    cred->next->owners = (OicUuid_t*)OICCalloc(cred->next->ownersLen, sizeof(OicUuid_t));
     VERIFY_NON_NULL(TAG, cred->next->owners, ERROR);
     OICStrcpy((char *)cred->next->owners[0].id, sizeof(cred->next->owners[0].id), "ownersId21");
     OICStrcpy((char *)cred->next->owners[1].id, sizeof(cred->next->owners[1].id), "ownersId22");
@@ -99,7 +118,7 @@ static void printCred(const OicSecCred_t * cred)
     EXPECT_TRUE(NULL != cred);
 
     const OicSecCred_t *credTmp1 = NULL;
-    for (credTmp1 = cred; credTmp1; credTmp1 = credTmp1->next)
+    for(credTmp1 = cred; credTmp1; credTmp1 = credTmp1->next)
     {
         OIC_LOG_V(INFO, TAG, "\ncred->credId = %d", credTmp1->credId);
         OIC_LOG_V(INFO, TAG, "cred->subject.id = %s", credTmp1->subject.id);
@@ -121,78 +140,68 @@ static void printCred(const OicSecCred_t * cred)
 }
 
  //InitCredResource Tests
-TEST(CredResourceTest, InitCredResource)
+TEST(InitCredResourceTest, InitCredResource)
 {
     EXPECT_EQ(OC_STACK_INVALID_PARAM, InitCredResource());
 }
 
 //DeInitCredResource Tests
-TEST(CredResourceTest, DeInitCredResource)
+TEST(DeInitCredResourceTest, DeInitCredResource)
 {
     EXPECT_EQ(OC_STACK_INVALID_PARAM, DeInitCredResource());
 }
 
 //CreateCredResource Tests
-TEST(CredResourceTest, CreateCredResource)
+TEST(CreateCredResourceTest, CreateCredResource)
 {
     EXPECT_EQ(OC_STACK_INVALID_PARAM, CreateCredResource());
 }
 
  //CredEntityHandler Tests
-TEST(CredResourceTest, CredEntityHandlerWithDummyRequest)
+TEST(CredEntityHandlerTest, CredEntityHandlerWithDummyRequest)
 {
     OCEntityHandlerRequest req;
     EXPECT_EQ(OC_EH_ERROR,
-            CredEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req, NULL));
+            CredEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req));
 }
 
-TEST(CredResourceTest, CredEntityHandlerWithNULLRequest)
+TEST(CredEntityHandlerTest, CredEntityHandlerWithNULLRequest)
 {
     EXPECT_EQ(OC_EH_ERROR,
-            CredEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, NULL, NULL));
+            CredEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, NULL));
 }
 
-TEST(CredResourceTest, CredEntityHandlerInvalidFlag)
+TEST(CredEntityHandlerTest, CredEntityHandlerInvalidFlag)
 {
     OCEntityHandlerRequest req;
     EXPECT_EQ(OC_EH_ERROR,
-            CredEntityHandler(OCEntityHandlerFlag::OC_OBSERVE_FLAG, &req, NULL));
+            CredEntityHandler(OCEntityHandlerFlag::OC_OBSERVE_FLAG, &req));
 }
 
 //Cred DELETE request
-TEST(CredResourceTest, CredEntityHandlerDeleteTest)
+TEST(CredEntityHandlerTest, CredEntityHandlerDeleteTest)
 {
     OCEntityHandlerRequest ehReq =  OCEntityHandlerRequest();
     static OCPersistentStorage ps =  OCPersistentStorage();
     const OicSecCred_t* subjectCred1 = NULL;
     const OicSecCred_t* subjectCred2 = NULL;
+    char *jsonStr = NULL;
     OCEntityHandlerResult ehRet = OC_EH_ERROR;
-    char query[] = "sub=subject1";
+    char query[] = "sub=c3ViamVjdDE=";
 
     SetPersistentHandler(&ps, true);
 
     OicSecCred_t *cred = getCredList();
-    ASSERT_TRUE(NULL != cred);
+    VERIFY_NON_NULL(TAG, cred, ERROR);
 
-    uint8_t *payload = NULL;
-    size_t size = 0;
-    EXPECT_EQ(OC_STACK_OK, CredToCBORPayload(cred, &payload, &size));
-    if (!payload)
-    {
-        DeleteCredList(cred);
-    }
-    ASSERT_TRUE(NULL != payload);
+    jsonStr = BinToCredJSON(cred);
+    VERIFY_NON_NULL(TAG, jsonStr, ERROR);
 
     // Create Entity Handler POST request payload
     ehReq.method = OC_REST_POST;
-    ehReq.payload = (OCPayload *)OCSecurityPayloadCBORCreate(payload);
-    if (!ehReq.payload)
-    {
-        OICFree(payload);
-        DeleteCredList(cred);
-    }
-    ASSERT_TRUE( NULL != ehReq.payload);
-    EXPECT_EQ(OC_EH_ERROR, CredEntityHandler(OC_REQUEST_FLAG, &ehReq, NULL));
+    ehReq.payload = (OCPayload*)OCSecurityPayloadCreate(jsonStr);
+    ehRet = CredEntityHandler(OC_REQUEST_FLAG, &ehReq);
+    EXPECT_TRUE(OC_EH_ERROR == ehRet);
 
     // Verify if SRM contains Credential for the subject
     subjectCred1 = GetCredResourceData(&cred->subject);
@@ -200,129 +209,96 @@ TEST(CredResourceTest, CredEntityHandlerDeleteTest)
 
    // Create Entity Handler DELETE request
    ehReq.method = OC_REST_DELETE;
-   ehReq.query = (char *)OICCalloc(1, strlen(query)+1);
-   if (!ehReq.query)
-   {
-       OICFree(payload);
-       DeleteCredList(cred);
-   }
-   ASSERT_TRUE(NULL != ehReq.query);
+   ehReq.query = (char*)OICMalloc(strlen(query)+1);
+   VERIFY_NON_NULL(TAG, ehReq.query, ERROR);
    OICStrcpy(ehReq.query, strlen(query)+1, query);
 
-   ehRet = CredEntityHandler(OC_REQUEST_FLAG, &ehReq, NULL);
-   EXPECT_EQ(OC_EH_ERROR, ehRet);
+   ehRet = CredEntityHandler(OC_REQUEST_FLAG, &ehReq);
+   EXPECT_TRUE(OC_EH_ERROR == ehRet);
 
    // Verify if SRM has deleted ACE for the subject
    subjectCred2 = GetCredResourceData(&cred->subject);
    EXPECT_TRUE(NULL == subjectCred2);
 
+exit:
    // Perform cleanup
    OICFree(ehReq.query);
-   OICFree(payload);
-   if (NULL != cred)
+   OICFree(jsonStr);
+   OCPayloadDestroy(ehReq.payload);
+   if(NULL != cred)
    {
        DeInitCredResource();
        DeleteCredList(cred);
    }
 }
 
-TEST(CredResourceTest, CredToCBORPayloadNULL)
+//BinToCredJSON Tests
+TEST(BinToCredJSONTest, BinToCredJSONNullCred)
 {
-    OicSecCred_t *cred = getCredList();
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CredToCBORPayload(NULL, NULL, 0));
-    size_t size = 0;
-    uint8_t *cborPayload = (uint8_t *) OICCalloc(1, 10);
-    if (!cborPayload)
-    {
-        DeleteCredList(cred);
-    }
-    ASSERT_TRUE(NULL != cborPayload);
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CredToCBORPayload(cred, &cborPayload, &size));
-    OICFree(cborPayload);
-    cborPayload = NULL;
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CredToCBORPayload(NULL, &cborPayload, &size));
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CredToCBORPayload(cred, &cborPayload, 0));
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CredToCBORPayload(cred, NULL, &size));
-    DeleteCredList(cred);
+    char* value = BinToCredJSON(NULL);
+    EXPECT_TRUE(value == NULL);
 }
 
-TEST(CredResourceTest, CredToCBORPayloadVALID)
+TEST(BinToCredJSONTest, BinToCredJSONValidCred)
 {
-    uint8_t* payload = NULL;
-    size_t size = 0;
-    OicSecCred_t *cred = getCredList();
+    char* json = NULL;
+    OicSecCred_t * cred = getCredList();
 
-    EXPECT_EQ(OC_STACK_OK, CredToCBORPayload(cred, &payload, &size));
-    if (!payload)
-    {
-        DeleteCredList(cred);
-    }
-    ASSERT_TRUE(NULL != payload);
+    json = BinToCredJSON(cred);
 
+    OIC_LOG_V(INFO, TAG, "BinToCredJSON:%s\n", json);
+    EXPECT_TRUE(json != NULL);
     DeleteCredList(cred);
-    OICFree(payload);
+    OICFree(json);
 }
 
-TEST(CredResourceTest, CBORPayloadToCredVALID)
+//JSONToCredBin Tests
+TEST(JSONToCredBinTest, JSONToCredBinValidJSON)
 {
-    OicSecCred_t *cred1 = getCredList();
+    OicSecCred_t* cred1 = getCredList();
+    char* json = BinToCredJSON(cred1);
 
-    uint8_t *payload = NULL;
-    size_t size = 0;
-    EXPECT_EQ(OC_STACK_OK, CredToCBORPayload(cred1, &payload, &size));
+    EXPECT_TRUE(json != NULL);
+    OicSecCred_t *cred2 = JSONToCredBin(json);
+    EXPECT_TRUE(cred2 != NULL);
     DeleteCredList(cred1);
-    ASSERT_TRUE(NULL != payload);
-
-    OicSecCred_t *cred2 = NULL;
-    EXPECT_EQ(OC_STACK_OK, CBORPayloadToCred(payload, size, &cred2));
-    OICFree(payload);
-    ASSERT_TRUE(cred2 != NULL);
+    DeleteCredList(cred2);
+    OICFree(json);
 }
 
-TEST(CredResourceTest, CBORPayloadToCredNULL)
+TEST(JSONToCredBinTest, JSONToCredBinNullJSON)
 {
-    OicSecCred_t *cred = NULL;
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CBORPayloadToCred(NULL, 0, NULL));
-    uint8_t *cborPayload = (uint8_t *) OICCalloc(1, 10);
-    ASSERT_TRUE(NULL != cborPayload);
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CBORPayloadToCred(NULL, 0, &cred));
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CBORPayloadToCred(cborPayload, 0, NULL));
-    cred = getCredList();
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CBORPayloadToCred(cborPayload, 0, &cred));
-    DeleteCredList(cred);
-    OICFree(cborPayload);
+    OicSecCred_t *cred = JSONToCredBin(NULL);
+    EXPECT_TRUE(cred == NULL);
 }
 
 //GetCredResourceData Test
-TEST(CredResourceTest, GetCredResourceDataNULLSubject)
+TEST(CredGetResourceDataTest, GetCredResourceDataNULLSubject)
 {
-    EXPECT_EQ(NULL, GetCredResourceData(NULL));
+    EXPECT_TRUE(NULL == GetCredResourceData(NULL));
 }
 
-TEST(CredResourceTest, GenerateCredentialValidInput)
+TEST(CredGenerateCredentialTest, GenerateCredentialValidInput)
 {
     OicUuid_t owners[1];
-    OICStrcpy((char *)owners[0].id, strlen("ownersId21"), "ownersId21");
+    OICStrcpy((char *)owners[0].id, sizeof(owners[0].id), "ownersId21");
 
     OicUuid_t subject = {{0}};
-    OICStrcpy((char *)subject.id, strlen("subject11"), "subject11");
+    OICStrcpy((char *)subject.id, sizeof(subject.id), "subject11");
 
     char privateKey[] = "My private Key11";
-    uint8_t *pk = (uint8_t *)OICCalloc(1, strlen(privateKey));
-    OICStrcpy((char *)pk, sizeof(pk), privateKey);
 
     OicSecCred_t * cred  = NULL;
 
     cred = GenerateCredential(&subject, SYMMETRIC_PAIR_WISE_KEY, NULL,
-                              pk, 1, owners);
+                             privateKey, 1, owners);
     printCred(cred);
 
-    ASSERT_TRUE(NULL != cred);
+    EXPECT_TRUE(NULL != cred);
     DeleteCredList(cred);
-    OICFree(pk);
 }
 
-TEST(CredResourceTest, GenerateAndAddCredentialValidInput)
+TEST(GenerateAndAddCredentialTest, GenerateAndAddCredentialValidInput)
 {
     OicUuid_t owners[1];
     OICStrcpy((char *)owners[0].id, sizeof(owners[0].id), "ownersId11");
@@ -331,36 +307,34 @@ TEST(CredResourceTest, GenerateAndAddCredentialValidInput)
     OICStrcpy((char *)subject.id, sizeof(subject.id), "subject11");
 
     char privateKey[] = "My private Key11";
-    uint8_t *pk = (uint8_t *)OICCalloc(1, strlen(privateKey));
-    OICStrcpy((char *)pk, sizeof(pk), privateKey);
 
-    OicSecCred_t *cred1  = NULL;
-    OicSecCred_t *headCred = NULL;
+    OicSecCred_t * cred1  = NULL;
+    OicSecCred_t * headCred = NULL;
 
     cred1 = GenerateCredential(&subject, SYMMETRIC_PAIR_WISE_KEY, NULL,
-                               pk, 1, owners);
+                                 privateKey, 1, owners);
 
-    EXPECT_EQ(OC_STACK_OK, AddCredential(cred1));
+    EXPECT_EQ(OC_STACK_ERROR, AddCredential(cred1));
     headCred = cred1;
 
     OICStrcpy((char *)owners[0].id, sizeof(owners[0].id), "ownersId22");
     OICStrcpy((char *)subject.id, sizeof(subject.id), "subject22");
     cred1 = GenerateCredential(&subject, SYMMETRIC_PAIR_WISE_KEY, NULL,
-                               pk, 1, owners);
-    EXPECT_EQ(OC_STACK_OK, AddCredential(cred1));
+                                     privateKey, 1, owners);
+    EXPECT_EQ(OC_STACK_ERROR, AddCredential(cred1));
 
     OICStrcpy((char *)owners[0].id, sizeof(owners[0].id), "ownersId33");
     OICStrcpy((char *)subject.id, sizeof(subject.id), "subject33");
     cred1 = GenerateCredential(&subject, SYMMETRIC_PAIR_WISE_KEY, NULL,
-                                pk, 1, owners);
-    EXPECT_EQ(OC_STACK_OK, AddCredential(cred1));
+                                     privateKey, 1, owners);
+    EXPECT_EQ(OC_STACK_ERROR, AddCredential(cred1));
 
     const OicSecCred_t* credList = GetCredResourceData(&headCred->subject);
 
     printCred(credList);
 
     DeleteCredList(headCred);
-    OICFree(pk);
+
 }
 
 #if 0
@@ -370,3 +344,5 @@ TEST(CredGetResourceDataTest, GetCredResourceDataValidSubject)
     EXPECT_TRUE(NULL != GetCredResourceData(cred->subject));
 }
 #endif
+
+
index e1bda00..f303030 100644 (file)
@@ -1,5 +1,3 @@
-//******************************************************************
-//
 // Copyright 2015 Intel Mobile Communications GmbH All Rights Reserved.
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #include "gtest/gtest.h"
 #include "ocstack.h"
-#include "ocserverrequest.h"
-#include "oic_string.h"
-#include "oic_malloc.h"
 #include "resourcemanager.h"
 #include "securevirtualresourcetypes.h"
 #include "srmresourcestrings.h"
 #include "doxmresource.h"
-#include "security_internals.h"
+#include "ocserverrequest.h"
+#include "oic_string.h"
+#include "oic_malloc.h"
+#include "logger.h"
 
 #define TAG  "SRM-DOXM"
 
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+
+//Declare Doxm resource methods for testing
+OCStackResult CreateDoxmResource();
+OCEntityHandlerResult DoxmEntityHandler (OCEntityHandlerFlag flag,
+                OCEntityHandlerRequest * ehRequest);
+char * BinToDoxmJSON(const OicSecDoxm_t * doxm);
+OicSecDoxm_t * JSONToDoxmBin(const char * jsonStr);
+void InitSecDoxmInstance(OicSecDoxm_t * doxm);
+OCEntityHandlerResult HandleDoxmPostRequest (const OCEntityHandlerRequest * ehRequest);
+void DeleteDoxmBinData(OicSecDoxm_t* doxm);
+OCEntityHandlerResult HandleDoxmGetRequest (const OCEntityHandlerRequest * ehRequest);
+#ifdef __cplusplus
+}
+#endif
+
+
 OicSecDoxm_t * getBinDoxm()
 {
-    OicSecDoxm_t *doxm = (OicSecDoxm_t *)OICCalloc(1, sizeof(*doxm));
-    if (!doxm)
+    OicSecDoxm_t * doxm = (OicSecDoxm_t*)OICCalloc(1, sizeof(OicSecDoxm_t));
+    if(!doxm)
     {
         return NULL;
     }
     doxm->oxmTypeLen =  1;
-    doxm->oxmType = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(*doxm->oxmType));
-    if (!doxm->oxmType)
+    doxm->oxmType    = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(char *));
+    if(!doxm->oxmType)
     {
         OICFree(doxm);
         return NULL;
     }
-    doxm->oxmType[0] = (char *) OICMalloc(strlen(OXM_JUST_WORKS) + 1);
-    if (!doxm->oxmType[0])
+    doxm->oxmType[0] = (char*)OICMalloc(strlen(OXM_JUST_WORKS) + 1);
+    if(!doxm->oxmType[0])
     {
         OICFree(doxm->oxmType);
         OICFree(doxm);
@@ -70,134 +88,109 @@ OicSecDoxm_t * getBinDoxm()
     doxm->owned      = true;
     //TODO: Need more clarification on deviceIDFormat field type.
     //doxm.deviceIDFormat = URN;
-
-    uint8_t deviceId[] = {0x64, 0x65, 0x76, 0x69, 0x63, 0x65, 0x49, 0x64};
-    memcpy(doxm->deviceID.id, deviceId, sizeof(deviceId));
-    uint8_t ownerId[] = {0x6f, 0x77, 0x6e, 0x65, 0x72, 0x73, 0x49, 0x64};
-    memcpy(doxm->owner.id, ownerId, sizeof(ownerId));
+    OICStrcpy((char *) doxm->deviceID.id, strlen("deviceId") + 1, "deviceId");
+    OICStrcpy((char *) doxm->owner.id, strlen("ownersId") + 1, "ownersId");
     return doxm;
 }
 
  //InitDoxmResource Tests
-TEST(DoxmResourceTest, InitDoxmResource)
+TEST(InitDoxmResourceTest, InitDoxmResource)
 {
     EXPECT_EQ(OC_STACK_INVALID_PARAM, InitDoxmResource());
 }
 
 //DeInitDoxmResource Tests
-TEST(DoxmResourceTest, DeInitDoxmResource)
+TEST(DeInitDoxmResourceTest, DeInitDoxmResource)
 {
     EXPECT_EQ(OC_STACK_ERROR, DeInitDoxmResource());
 }
 
 //CreateDoxmResource Tests
-TEST(DoxmResourceTest, CreateDoxmResource)
+TEST(CreateDoxmResourceTest, CreateDoxmResource)
 {
     EXPECT_EQ(OC_STACK_INVALID_PARAM, CreateDoxmResource());
 }
 
  //DoxmEntityHandler Tests
-TEST(DoxmResourceTest, DoxmEntityHandlerWithDummyRequest)
+TEST(DoxmEntityHandlerTest, DoxmEntityHandlerWithDummyRequest)
 {
     OCEntityHandlerRequest req;
-    EXPECT_EQ(OC_EH_ERROR, DoxmEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req, NULL));
+    EXPECT_EQ(OC_EH_ERROR, DoxmEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req));
 }
 
-TEST(DoxmResourceTest, DoxmEntityHandlerWithNULLRequest)
+TEST(DoxmEntityHandlerTest, DoxmEntityHandlerWithNULLRequest)
 {
-    EXPECT_EQ(OC_EH_ERROR, DoxmEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, NULL, NULL));
+    EXPECT_EQ(OC_EH_ERROR, DoxmEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, NULL));
 }
 
-TEST(DoxmResourceTest, DoxmEntityHandlerInvalidFlag)
+TEST(DoxmEntityHandlerTest, DoxmEntityHandlerInvalidFlag)
 {
     OCEntityHandlerRequest req;
-    EXPECT_EQ(OC_EH_ERROR, DoxmEntityHandler(OCEntityHandlerFlag::OC_OBSERVE_FLAG, &req, NULL));
+    EXPECT_EQ(OC_EH_ERROR, DoxmEntityHandler(OCEntityHandlerFlag::OC_OBSERVE_FLAG, &req));
 }
 
-TEST(DoxmResourceTest, DoxmEntityHandlerValidRequest)
+TEST(DoxmEntityHandlerTest, DoxmEntityHandlerValidRequest)
 {
     EXPECT_EQ(OC_STACK_INVALID_PARAM, InitDoxmResource());
     char query[] = "oxm=0;owned=false;owner=owner1";
     OCEntityHandlerRequest req = OCEntityHandlerRequest();
     req.method = OC_REST_GET;
     req.query = OICStrdup(query);
-    EXPECT_EQ(OC_EH_ERROR, DoxmEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req, NULL));
+    EXPECT_EQ(OC_EH_ERROR, DoxmEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req));
 
     OICFree(req.query);
 }
 
-TEST(DoxmResourceTest, DoxmEntityHandlerDeviceIdQuery)
+TEST(DoxmEntityHandlerTest, DoxmEntityHandlerDeviceIdQuery)
 {
     EXPECT_EQ(OC_STACK_INVALID_PARAM, InitDoxmResource());
-    char query[] = "deviceid=2222222222222222";
+    char query[] = "deviceid=MjIyMjIyMjIyMjIyMjIyMg==";
     OCEntityHandlerRequest req = OCEntityHandlerRequest();
     req.method = OC_REST_GET;
     req.query = OICStrdup(query);
-    EXPECT_EQ(OC_EH_ERROR, DoxmEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req, NULL));
+    EXPECT_EQ(OC_EH_ERROR, DoxmEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req));
 
     OICFree(req.query);
 }
 
-TEST(DoxmResourceTest, DoxmToCBORPayloadNULL)
+//BinToDoxmJSON Tests
+TEST(BinToDoxmJSONTest, BinToDoxmJSONNullDoxm)
 {
-    OicSecDoxm_t *doxm =  getBinDoxm();
-    size_t size = 10;
-    uint8_t *payload = NULL;
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, DoxmToCBORPayload(NULL, NULL, 0));
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, DoxmToCBORPayload(doxm, NULL, &size));
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, DoxmToCBORPayload(doxm, &payload, 0));
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, DoxmToCBORPayload(NULL, &payload, &size));
-    DeleteDoxmBinData(doxm);
+    char* value = BinToDoxmJSON(NULL);
+    EXPECT_TRUE(value == NULL);
 }
 
-TEST(DoxmResourceTest, DoxmToCBORPayloadVALID)
+TEST(BinToDoxmJSONTest, BinToDoxmJSONValidDoxm)
 {
-    OicSecDoxm_t *doxm =  getBinDoxm();
+    OicSecDoxm_t * doxm =  getBinDoxm();
 
-    uint8_t *payload = NULL;
-    size_t size = 0;
-    EXPECT_EQ(OC_STACK_OK, DoxmToCBORPayload(doxm, &payload, &size));
-    EXPECT_TRUE(payload != NULL);
+    char * json = BinToDoxmJSON(doxm);
+    OIC_LOG_V(INFO, TAG, "BinToDoxmJSON:%s", json);
+    EXPECT_TRUE(json != NULL);
 
     DeleteDoxmBinData(doxm);
-    OICFree(payload);
+    OICFree(json);
 }
 
-//CBORPayloadToDoxm Tests
-TEST(DoxmResourceTest, CBORPayloadToDoxmNULL)
+//JSONToDoxmBin Tests
+TEST(JSONToDoxmBinTest, JSONToDoxmBinValidJSON)
 {
-    OicSecDoxm_t *doxm = NULL;
-    uint8_t *cborPayload = (uint8_t *)OICCalloc(1, sizeof(10));
-    size_t size = 10;
-    ASSERT_TRUE(NULL != cborPayload);
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CBORPayloadToDoxm(NULL, 0, NULL));
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CBORPayloadToDoxm(NULL, size, &doxm));
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CBORPayloadToDoxm(cborPayload, size, NULL));
-    OICFree(cborPayload);
+    OicSecDoxm_t * doxm1 =  getBinDoxm();
+    char * json = BinToDoxmJSON(doxm1);
+    EXPECT_TRUE(json != NULL);
+
+    OicSecDoxm_t *doxm2 = JSONToDoxmBin(json);
+    EXPECT_TRUE(doxm2 != NULL);
+
+    DeleteDoxmBinData(doxm1);
+    DeleteDoxmBinData(doxm2);
+    OICFree(json);
 }
 
-TEST(DoxmResourceTest, CBORPayloadToDoxmVALID)
+TEST(JSONToDoxmBinTest, JSONToDoxmBinNullJSON)
 {
-    OicSecDoxm_t *doxm =  getBinDoxm();
-    uint8_t *payload = NULL;
-    size_t size = 0;
-    EXPECT_EQ(OC_STACK_OK, DoxmToCBORPayload(doxm, &payload, &size));
-    EXPECT_TRUE(payload != NULL);
-
-    OicSecDoxm_t *doxmSec = NULL;
-    EXPECT_EQ(OC_STACK_OK, CBORPayloadToDoxm(payload, size, &doxmSec));
-    ASSERT_TRUE(doxmSec != NULL);
-    EXPECT_EQ(doxmSec->oxmTypeLen, doxm->oxmTypeLen);
-    EXPECT_STREQ(doxmSec->oxmType[0], doxm->oxmType[0]);
-    EXPECT_EQ(doxmSec->oxmLen, doxm->oxmLen);
-    EXPECT_EQ(doxmSec->oxm[0], doxm->oxm[0]);
-    EXPECT_EQ(doxmSec->oxmSel, doxm->oxmSel);
-    EXPECT_EQ(doxmSec->sct, doxm->sct);
-    EXPECT_EQ(doxmSec->owned, doxm->owned);
-
-    DeleteDoxmBinData(doxmSec);
-    DeleteDoxmBinData(doxm);
-    OICFree(payload);
+    OicSecDoxm_t *doxm = JSONToDoxmBin(NULL);
+    EXPECT_TRUE(doxm == NULL);
 }
 
 #if 0
diff --git a/resource/csdk/security/unittest/oic_unittest.dat b/resource/csdk/security/unittest/oic_unittest.dat
deleted file mode 100644 (file)
index cba91d0..0000000
Binary files a/resource/csdk/security/unittest/oic_unittest.dat and /dev/null differ
diff --git a/resource/csdk/security/unittest/oic_unittest_acl1.dat b/resource/csdk/security/unittest/oic_unittest_acl1.dat
deleted file mode 100644 (file)
index 14c6db7..0000000
Binary files a/resource/csdk/security/unittest/oic_unittest_acl1.dat and /dev/null differ
index 91ee7b4..a179c2c 100644 (file)
@@ -1,26 +1,53 @@
-[
-  {
-    "sub":"Kg",
-    "rsrc":["/oic/res","/oic/d","/oic/p","/oic/res/types/d","/oic/ad","/oic/sec/acl"],
-    "perms":2,
-    "ownrs":["MjIyMjIyMjIyMjIyMjIyMg"]
-  },
-  {
-    "sub":"Kg",
-    "rsrc":["/oic/sec/doxm","/oic/sec/pstat"],
-    "perms":6,
-    "ownrs":["MjIyMjIyMjIyMjIyMjIyMg"]
-  },
-  {
-    "sub":"MTExMTExMTExMTExMTExMQ",
-    "rsrc":["/oic/light","/oic/fan"],
-    "perms":255,
-    "ownrs":["MjIyMjIyMjIyMjIyMjIyMg"]
-  },
-  {
-    "sub":"MzMzMzMzMzMzMzMzMzMzMw",
-    "rsrc":["/oic/light","/oic/garage"],
-    "perms":255,
-    "ownrs":["MjIyMjIyMjIyMjIyMjIyMg","NDQ0NDQ0NDQ0NDQ0NDQ0NA"]
-  }
-]
+{
+    "acl": [
+        {
+            "sub": "Kg==",
+            "rsrc": [
+                "/oic/res",
+                "/oic/d",
+                "/oic/p",
+                "/oic/res/types/d",
+                "/oic/ad",
+                "/oic/sec/acl"
+                       ],
+                       "perms": 2,
+                       "ownrs" : [
+                               "MjIyMjIyMjIyMjIyMjIyMg=="
+                       ]
+               },
+        {
+            "sub": "Kg==",
+            "rsrc": [
+                "/oic/sec/doxm",
+                "/oic/sec/pstat"
+                       ],
+                       "perms": 6,
+                       "ownrs" : [
+                               "MjIyMjIyMjIyMjIyMjIyMg=="
+                       ]
+               },
+        {
+            "sub": "MTExMTExMTExMTExMTExMQ==",
+            "rsrc": [
+                               "/oic/light",
+                               "/oic/fan"
+                       ],
+                       "perms": 255,
+                       "ownrs" : [
+                               "MjIyMjIyMjIyMjIyMjIyMg=="
+                       ]
+               },
+               {
+            "sub": "MzMzMzMzMzMzMzMzMzMzMw==",
+            "rsrc": [
+                               "/oic/light",
+                               "/oic/garage"
+                       ],
+                       "perms": 255,
+                       "ownrs" : [
+                               "MjIyMjIyMjIyMjIyMjIyMg==",
+                "NDQ0NDQ0NDQ0NDQ0NDQ0NA=="
+                       ]
+               }
+       ]
+}
diff --git a/resource/csdk/security/unittest/oic_unittest_default_acl.dat b/resource/csdk/security/unittest/oic_unittest_default_acl.dat
deleted file mode 100644 (file)
index f284271..0000000
Binary files a/resource/csdk/security/unittest/oic_unittest_default_acl.dat and /dev/null differ
index 96d9170..7f3d449 100644 (file)
@@ -1,8 +1,21 @@
-[
-  {
-    "sub":"Kg",
-    "rsrc":["/oic/res","/oic/d","/oic/p","/oic/res/types/d","/oic/ad","/oic/sec/acl","/oic/sec/doxm","/oic/sec/pstat"],
-    "perms":2,
-    "ownrs":["MjIyMjIyMjIyMjIyMjIyMg"]
-  }
-]
+{
+    "acl": [
+        {
+            "sub": "Kg==",
+            "rsrc": [
+                "/oic/res",
+                "/oic/d",
+                "/oic/p",
+                "/oic/res/types/d",
+                "/oic/ad",
+                "/oic/sec/acl",
+                "/oic/sec/doxm",
+                "/oic/sec/pstat"
+                       ],
+                       "perms": 2,
+                       "ownrs" : [
+                               "MjIyMjIyMjIyMjIyMjIyMg=="
+                       ]
+               }
+       ]
+}
index 16999bc..03c8a68 100644 (file)
 //
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
-#include <unistd.h>
 #include "gtest/gtest.h"
-
-#include "ocpayload.h"
 #include "ocstack.h"
+#include "resourcemanager.h"
+#include "pstatresource.h"
 #include "oic_malloc.h"
+#include "cJSON.h"
+#include "base64.h"
 #include "cainterface.h"
-#include "resourcemanager.h"
 #include "secureresourcemanager.h"
-#include "pstatresource.h"
-#include "security_internals.h"
+#include "srmtestcommon.h"
+#include "ocpayload.h"
+#include <unistd.h>
+#ifdef __cplusplus
+extern "C" {
+#endif
+//Declare Provision status resource methods for testing
+OCStackResult CreatePstatResource();
+OCEntityHandlerResult PstatEntityHandler (OCEntityHandlerFlag flag,
+                                        OCEntityHandlerRequest * ehRequest);
+char * BinToPstatJSON(const OicSecPstat_t * pstat);
+OicSecPstat_t * JSONToPstatBin(const char * jsonStr);
+const char* UNIT_TEST_JSON_FILE_NAME = "oic_unittest.json";
+#ifdef __cplusplus
+}
+#endif
 
-// InitPstatResource Tests
-TEST(PstatResourceTest, InitPstatResource)
+//InitPstatResource Tests
+TEST(InitPstatResourceTest, InitPstatResource)
 {
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, InitPstatResource());
+    EXPECT_EQ(OC_STACK_INVALID_PARAM,  InitPstatResource());
 }
 
-// DeInitPstatResource Tests
-TEST(PstatResourceTest, DeInitPstatResource)
+
+//DeInitPstatResource Tests
+TEST(DeInitPstatResourceTest, DeInitPstatResource)
 {
     EXPECT_EQ(OC_STACK_INVALID_PARAM, DeInitPstatResource());
 }
 
 //CreatePstatResource Tests
-TEST(PstatResourceTest, CreatePstatResource)
+TEST(CreatePstatResourceTest, CreatePstatResource)
 {
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CreatePstatResource());
+    EXPECT_EQ(OC_STACK_INVALID_PARAM,  CreatePstatResource());
 }
 
 //PstatEntityHandler Tests
-TEST(PstatResourceTest, PstatEntityHandlerWithDummyRequest)
+TEST(PstatEntityHandlerTest, PstatEntityHandlerWithDummyRequest)
 {
     OCEntityHandlerRequest req;
     EXPECT_EQ(OC_EH_ERROR, PstatEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req));
 }
 
-TEST(PstatResourceTest, PstatEntityHandlerWithPostRequest)
+TEST(PstatEntityHandlerTest, PstatEntityHandlerWithPostRequest)
 {
-    OicSecPstat_t *defaultPstat = (OicSecPstat_t *) OICCalloc(1, sizeof(*defaultPstat));
-    ASSERT_TRUE(defaultPstat != NULL);
-    defaultPstat->isOp = false;
-    uint8_t deviceId[] = {0x64, 0x65, 0x76, 0x69, 0x63, 0x65, 0x69, 0x64, 0x00,
-                          0x00, 0x00, 0x00, 0x00, 0x18, 0x5a, 0x9f};
-    memcpy(defaultPstat->deviceID.id, deviceId, sizeof(deviceId));
-    EXPECT_EQ(sizeof(defaultPstat->deviceID.id), sizeof(deviceId));
-    defaultPstat->commitHash = 1234;
-    defaultPstat->cm = (OicSecDpm_t) 63;
-    defaultPstat->tm = (OicSecDpm_t) 48;
-    defaultPstat->om = (OicSecDpom_t) 0;
-    defaultPstat->smLen = 2;
-    defaultPstat->sm = (OicSecDpom_t *)OICCalloc(defaultPstat->smLen, sizeof(*defaultPstat->sm));
-    ASSERT_TRUE(defaultPstat->sm != NULL);
-    defaultPstat->sm[0] = (OicSecDpom_t) 3;
-    defaultPstat->sm[1] = (OicSecDpom_t) 1;
-    size_t size = 0;
-    uint8_t *cbor = NULL;
-    EXPECT_EQ(OC_STACK_OK, PstatToCBORPayload(defaultPstat, &cbor, &size));
-    DeletePstatBinData(defaultPstat);
-    ASSERT_TRUE(cbor != NULL);
-
     OCEntityHandlerRequest req;
     req.method = OC_REST_POST;
-    req.payload = (OCPayload *) OCSecurityPayloadCBORCreate(cbor);
+    req.payload = reinterpret_cast<OCPayload*>(
+            OCSecurityPayloadCreate("{ \"pstat\": { \"tm\": 0, \"om\": 3 }}"));
     EXPECT_EQ(OC_EH_ERROR, PstatEntityHandler(OCEntityHandlerFlag::OC_REQUEST_FLAG, &req));
     OCPayloadDestroy(req.payload);
 }
 
-TEST(PstatResourceTest, PstatEntityHandlerInvalidRequest)
+TEST(PstatEntityHandlerTest, PstatEntityHandlerInvalidRequest)
 {
     EXPECT_EQ(OC_EH_ERROR, PstatEntityHandler(OCEntityHandlerFlag::OC_OBSERVE_FLAG, NULL));
 }
 
-TEST(PstatResourceTest, PstatToCBORPayloadNULL)
+//BinToJSON Tests
+TEST(BinToJSONTest, BinToNullJSON)
 {
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, PstatToCBORPayload(NULL, NULL, 0));
-    // Case when cbor payload is NULL
-    OicSecPstat_t pstat;
-    size_t size = 10;
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, PstatToCBORPayload(&pstat, NULL, &size));
-    uint8_t *cborPayload = (uint8_t *) OICCalloc(1, size);
-    ASSERT_TRUE(NULL != cborPayload);
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, PstatToCBORPayload(&pstat, &cborPayload, &size));
-    OICFree(cborPayload);
-    cborPayload = NULL;
-    // Case when pstat is zero.
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, PstatToCBORPayload(NULL, &cborPayload, &size));
-    // Case when size is 0.
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, PstatToCBORPayload(&pstat, &cborPayload, 0));
-    OICFree(cborPayload);
+    char* value = BinToPstatJSON(NULL);
+    EXPECT_TRUE(value == NULL);
 }
 
-TEST(PstatResourceTest, CBORPayloadToPstat)
+TEST(JSONToBinTest, NullJSONToBin)
 {
-    EXPECT_EQ(OC_STACK_INVALID_PARAM, CBORPayloadToPstat(NULL, 0, NULL));
+    OicSecPstat_t *pstat1 = JSONToPstatBin(NULL);
+    EXPECT_TRUE(pstat1 == NULL);
 }
 
-TEST(PstatResourceTest, PstatToCBORPayloadAndCBORPayloadToPstat)
+TEST(MarshalingAndUnMarshalingTest, BinToPstatJSONAndJSONToPstatBin)
 {
+    const char* id = "ZGV2aWNlaWQAAAAAABhanw==";
     OicSecPstat_t pstat;
     pstat.cm = NORMAL;
     pstat.commitHash = 0;
-    uint8_t deviceId[] = {0x64, 0x65, 0x76, 0x69, 0x63, 0x65, 0x69, 0x64, 0x00,
-                          0x00, 0x00, 0x00, 0x00, 0x18, 0x5a, 0x9f};
-    memcpy(pstat.deviceID.id, deviceId, sizeof(deviceId));
+    uint32_t outLen = 0;
+    unsigned char base64Buff[sizeof(((OicUuid_t*) 0)->id)] = {};
+    EXPECT_EQ(B64_OK, b64Decode(id, strlen(id), base64Buff, sizeof(base64Buff), &outLen));
+    memcpy(pstat.deviceID.id, base64Buff, outLen);
     pstat.isOp = true;
     pstat.tm = NORMAL;
     pstat.om = SINGLE_SERVICE_CLIENT_DRIVEN;
     pstat.smLen = 2;
-    pstat.sm = (OicSecDpom_t*)OICCalloc(pstat.smLen, sizeof(pstat.sm));
-    ASSERT_TRUE(NULL != pstat.sm);
+    pstat.sm = (OicSecDpom_t*)OICCalloc(pstat.smLen, sizeof(OicSecDpom_t));
+    if(!pstat.sm)
+    {
+        FAIL() << "Failed to allocate the pstat.sm";
+    }
     pstat.sm[0] = SINGLE_SERVICE_CLIENT_DRIVEN;
     pstat.sm[1] = SINGLE_SERVICE_SERVER_DRIVEN;
-
-    size_t size = 0;
-    uint8_t *cbor = NULL;
-    EXPECT_EQ(OC_STACK_OK, PstatToCBORPayload(&pstat, &cbor, &size));
-    if (!cbor)
+    char* jsonPstat = BinToPstatJSON(&pstat);
+    if(!jsonPstat)
     {
         OICFree(pstat.sm);
-        FAIL() << "Failed to convert PstatToCBORPayload";
+        FAIL() << "Failed to convert BinToPstatJSON";
         return;
     }
-    ASSERT_TRUE(NULL != cbor);
-    OicSecPstat_t *pstat1 = NULL;
-    EXPECT_EQ(OC_STACK_OK, CBORPayloadToPstat(cbor, size, &pstat1));
-    ASSERT_TRUE(NULL != pstat1);
-    EXPECT_EQ(pstat.commitHash, pstat1->commitHash);
-    EXPECT_EQ(pstat.isOp, pstat1->isOp);
-    EXPECT_EQ(pstat.tm, pstat1->tm);
-    EXPECT_EQ(pstat.om, pstat1->om);
-    EXPECT_EQ(pstat.smLen, pstat1->smLen);
-    EXPECT_EQ(pstat.sm[0], pstat1->sm[0]);
-    EXPECT_EQ(pstat.sm[1], pstat1->sm[1]);
-
-    DeletePstatBinData(pstat1);
-    OICFree(cbor);
+    printf("BinToJSON Dump:\n%s\n\n", jsonPstat);
+    EXPECT_TRUE(jsonPstat != NULL);
+    OicSecPstat_t *pstat1 = JSONToPstatBin(jsonPstat);
+    EXPECT_TRUE(pstat1 != NULL);
+    if(pstat1)
+    {
+        OICFree(pstat1->sm);
+    }
+    OICFree(pstat1);
+    OICFree(jsonPstat);
     OICFree(pstat.sm);
 }
+
+TEST(PstatTests, JSONMarshalliingTests)
+{
+    char *jsonStr1 = ReadFile(UNIT_TEST_JSON_FILE_NAME);
+    if (NULL != jsonStr1)
+    {
+        cJSON_Minify(jsonStr1);
+        /* Workaround : cJSON_Minify does not remove all the unwanted characters
+         from the end. Here is an attempt to remove those characters */
+        int len = strlen(jsonStr1);
+        while (len > 0)
+        {
+            if (jsonStr1[--len] == '}')
+            {
+                break;
+            }
+        }
+        jsonStr1[len + 1] = 0;
+
+        OicSecPstat_t* pstat = JSONToPstatBin(jsonStr1);
+        EXPECT_TRUE(NULL != pstat);
+
+        char* jsonStr2 = BinToPstatJSON(pstat);
+        EXPECT_STRNE(jsonStr1, jsonStr2);
+
+        OICFree(jsonStr1);
+        OICFree(jsonStr2);
+        OICFree(pstat);
+   }
+    else
+    {
+        printf("Please copy %s into unittest folder\n", UNIT_TEST_JSON_FILE_NAME);
+    }
+}
index 8e8f186..6f51329 100644 (file)
 #include "gtest/gtest.h"
 #include "oic_malloc.h"
 #include "ocstack.h"
-#include <stdlib.h>
 
-#define STRINGIZE2(x) #x
-#define STRINGIZE(x) STRINGIZE2(x)
-
-// TODO: Remove this, once all cbor related are completed.
 char* ReadFile(const char* filename)
 {
 
@@ -59,61 +54,6 @@ char* ReadFile(const char* filename)
     return data;
 }
 
-bool ReadCBORFile(const char* filename, uint8_t **data, size_t *size)
-{
-    bool status = false;
-    if (!data || !size)
-    {
-        printf("Passed parameter are INVALID \n");
-        return status;
-    }
-    int len = strlen(STRINGIZE(SECURITY_BUILD_UNITTEST_DIR)) + strlen(filename) + 1;
-    char *filepath = (char *)OICCalloc(1, len);
-    if (!filepath)
-    {
-        printf("filepath memory allocation failed. \n");
-        return false;
-    }
-    int ret = snprintf(filepath, len, "%s%s", STRINGIZE(SECURITY_BUILD_UNITTEST_DIR), filename);
-    printf("Root build path: %s \n", filepath);
-
-    if (ret == len-1)
-    {
-        FILE *fp = fopen(filepath, "rb");
-        if (fp)
-        {
-            struct stat st;
-            if (stat(filepath, &st) == 0)
-            {
-                *data = (uint8_t *)OICMalloc(st.st_size);
-                if (*data)
-                {
-                    if (fread(*data, 1, st.st_size, fp) != (size_t)st.st_size)
-                    {
-                        printf("Error in reading file %s\n", filename);
-                    }
-                    else
-                    {
-                        *size = st.st_size;
-                        status = true;
-                    }
-                }
-            }
-            fclose(fp);
-        }
-        else
-        {
-            printf("Unable to open %s file\n", filepath);
-        }
-    }
-    else
-    {
-        printf("Filepath copy failed.\n");
-    }
-    OICFree(filepath);
-    return status;
-}
-
 void SetPersistentHandler(OCPersistentStorage *ps, bool set)
 {
     if (set)
index bf1b571..1a8685e 100644 (file)
@@ -22,7 +22,6 @@
 #define IOTVT_SRM_TEST_COMMON_H
 
 char* ReadFile(const char* filename);
-bool ReadCBORFile(const char* filename, uint8_t **payload, size_t *size);
 void SetPersistentHandler(OCPersistentStorage *ps, bool set);
 
 #endif //IOTVT_SRM_TEST_COMMON_H
index 8d4553f..5c3f75e 100644 (file)
 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
 
 #include "gtest/gtest.h"
+#include <pwd.h>
+#include <grp.h>
+#include <linux/limits.h>
+#include <sys/stat.h>
 #include "ocstack.h"
 #include "oic_malloc.h"
+#include "cJSON.h"
 #include "cainterface.h"
 #include "secureresourcemanager.h"
 #include "securevirtualresourcetypes.h"
 #include "srmresourcestrings.h"
 #include "svcresource.h"
 #include "srmtestcommon.h"
-#include "security_internals.h"
 
 using namespace std;
 
-#define NUM_SVC_IN_CBOR_DB (2)
+#ifdef __cplusplus
+extern "C" {
+#endif
+extern char * BinToSvcJSON(const OicSecSvc_t * svc);
+extern OicSecSvc_t * JSONToSvcBin(const char * jsonStr);
+extern void DeleteSVCList(OicSecSvc_t* svc);
+#ifdef __cplusplus
+}
+#endif
 
-TEST(SVCResourceTest, CBORConversionTests)
-{
-    OicSecSvc_t *svc1 = (OicSecSvc_t *) OICCalloc(1, sizeof(*svc1));
-    ASSERT_TRUE(NULL != svc1);
-    uint8_t svcdid[] = {0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35,
-                        0x35, 0x35, 0x35, 0x35, 0x35, 0x35, 0x35};
-    memcpy(svc1->svcdid.id, svcdid, sizeof(svcdid));
-    ASSERT_EQ(sizeof(svc1->svcdid.id), sizeof(svcdid));
+static const char* JSON_FILE_NAME = "oic_unittest.json";
 
-    svc1->svct = (OicSecSvcType_t) 1;
-    uint8_t owners[] = {0x39, 0x39, 0x39, 0x39, 0x39, 0x39, 0x39, 0x39, 0x39,
-                        0x39, 0x39, 0x39, 0x39, 0x39, 0x39, 0x39};
-    svc1->ownersLen = 1;
-    svc1->owners = (OicUuid_t *)OICCalloc(svc1->ownersLen, sizeof(*svc1->owners));
-    ASSERT_TRUE(NULL != svc1->owners);
-    memcpy(svc1->owners[0].id, owners, sizeof(owners));
-    ASSERT_EQ(sizeof(svc1->owners[0].id), sizeof(owners));
+#define NUM_SVC_IN_JSON_DB (2)
 
-    svc1->next = (OicSecSvc_t *) OICCalloc(1, sizeof(*svc1->next));
-    ASSERT_TRUE(svc1->next != NULL);
-    memcpy(svc1->next->svcdid.id, svcdid, sizeof(svcdid));
-    ASSERT_EQ(sizeof(svc1->next->svcdid.id), sizeof(svcdid));
-    svc1->next->svct = (OicSecSvcType_t) 1;
-    uint8_t owners1[] = {0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
-                        0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36};
-    svc1->next->ownersLen = 1;
-    svc1->next->owners = (OicUuid_t *)OICCalloc(svc1->next->ownersLen,
-                                                sizeof(*svc1->next->owners));
-    ASSERT_TRUE(NULL != svc1->next->owners);
-    memcpy(svc1->next->owners[0].id, owners1, sizeof(owners1));
-    svc1->next->next = NULL;
 
-    size_t size = 0;
-    uint8_t *psStorage = NULL;
-    EXPECT_EQ(OC_STACK_OK, SVCToCBORPayload(svc1, &psStorage, &size));
-    ASSERT_TRUE(NULL != psStorage);
+// JSON Marshalling Tests
+TEST(SVCResourceTest, JSONMarshallingTests)
+{
+    char *jsonStr1 = ReadFile(JSON_FILE_NAME);
+    if (jsonStr1)
+    {
+        OicSecSvc_t * svc = JSONToSvcBin(jsonStr1);
+        EXPECT_TRUE(NULL != svc);
 
-    OicSecSvc_t *svc = NULL;
-    EXPECT_EQ(OC_STACK_OK, CBORPayloadToSVC(psStorage, size, &svc));
-    ASSERT_TRUE(NULL != svc);
+        int cnt = 0;
+        OicSecSvc_t * tempSvc = svc;
+        while(tempSvc)
+        {
 
-    int cnt = 0;
-    OicSecSvc_t *tempSvc = svc;
-    while (tempSvc)
-    {
-        EXPECT_EQ(ACCESS_MGMT_SERVICE, tempSvc->svct);
-        cnt++;
-        tempSvc = tempSvc->next;
-    }
-    EXPECT_EQ(NUM_SVC_IN_CBOR_DB, cnt);
+            EXPECT_EQ(tempSvc->svct, ACCESS_MGMT_SERVICE);
+            cnt++;
+            tempSvc = tempSvc->next;
+        }
+        EXPECT_EQ(cnt, NUM_SVC_IN_JSON_DB);
+
+        char * jsonStr2 = BinToSvcJSON(svc);
+        EXPECT_TRUE(NULL != jsonStr2);
 
-    OICFree(psStorage);
-    DeleteSVCList(svc);
-    DeleteSVCList(svc1);
+        OICFree(jsonStr1);
+        OICFree(jsonStr2);
+        DeleteSVCList(svc);
+    }
 }
+
old mode 100755 (executable)
new mode 100644 (file)
index 88f0d95..789d5d7
@@ -219,9 +219,7 @@ void OCRepPayloadDestroy(OCRepPayload* payload);
 // Discovery Payload
 OCDiscoveryPayload* OCDiscoveryPayloadCreate();
 
-// TODO: Remove OCSecurityPayloadCBORCreate once all cbor changes land.
 OCSecurityPayload* OCSecurityPayloadCreate(const char* securityData);
-OCSecurityPayload* OCSecurityPayloadCBORCreate(const uint8_t* securityData);
 void OCSecurityPayloadDestroy(OCSecurityPayload* payload);
 
 void OCDiscoveryPayloadAddResource(OCDiscoveryPayload* payload, const OCResource* res,
index fc162c1..330b524 100644 (file)
@@ -1194,7 +1194,6 @@ typedef struct
 {
     OCPayload base;
     char* securityData;
-    uint8_t *securityData1;
 } OCSecurityPayload;
 
 #ifdef WITH_PRESENCE
old mode 100755 (executable)
new mode 100644 (file)
index 5e0d727..030b1c8
@@ -1289,7 +1289,6 @@ OCDiscoveryPayload* OCDiscoveryPayloadCreate()
     return payload;
 }
 
-//TODO : Remove this once all cbor changes land.
 OCSecurityPayload* OCSecurityPayloadCreate(const char* securityData)
 {
     OCSecurityPayload* payload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
@@ -1305,31 +1304,14 @@ OCSecurityPayload* OCSecurityPayloadCreate(const char* securityData)
     return payload;
 }
 
-// TODO : To convert this to OCSecurityPayloadCreate once all cbor changes land.
-OCSecurityPayload* OCSecurityPayloadCBORCreate(const uint8_t* securityData)
-{
-    OCSecurityPayload* payload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
-
-    if (!payload)
-    {
-        return NULL;
-    }
-
-    payload->base.type = PAYLOAD_TYPE_SECURITY;
-    payload->securityData1 = (uint8_t *)securityData;
-
-    return payload;
-}
-
 void OCSecurityPayloadDestroy(OCSecurityPayload* payload)
 {
     if (!payload)
     {
         return;
     }
-    // Remove this once all cbor changes land.
+
     OICFree(payload->securityData);
-    OICFree(payload->securityData1);
     OICFree(payload);
 }
 
index 9a3ff2c..946cdd9 100644 (file)
@@ -186,15 +186,12 @@ static int64_t OCConvertSecurityPayload(OCSecurityPayload* payload, uint8_t* out
                                       (size_t)(strlen(payload->securityData)));
         VERIFY_CBOR_SUCCESS(TAG, err, "Encoding security data");
     }
-    else if (!payload->securityData && !payload->securityData1)
+    else
     {
         err |= cbor_encode_null(&map);
         VERIFY_CBOR_SUCCESS(TAG, err, "Encoding security data");
     }
-    else if (payload->securityData1)
-    {
-        err = err | cbor_encode_byte_string(&encoder, payload->securityData1, *size);
-    }
+
     err |= cbor_encoder_close_container(&encoder, &map);
     VERIFY_CBOR_SUCCESS(TAG, err, "Closing security map");
 exit:
old mode 100755 (executable)
new mode 100644 (file)
index ad076d0..a89c441
@@ -102,15 +102,14 @@ void OCFreeOCStringLL(OCStringLL* ll);
 
 static OCStackResult OCParseSecurityPayload(OCPayload** outPayload, CborValue* rootValue)
 {
-    OCStackResult ret = OC_STACK_INVALID_PARAM;
-    *outPayload = NULL;
-    char *securityData = NULL;
-    uint8_t *securityData1 = NULL;
+    OCStackResult ret = OC_STACK_ERROR;
     CborError err;
+    char *securityData = NULL;
+    CborValue strVal;
+
     VERIFY_PARAM_NON_NULL(TAG, outPayload, "Invalid parameter outPayload");
     VERIFY_PARAM_NON_NULL(TAG, rootValue, "Invalid parameter rootValue");
-
-    CborValue strVal;
+    *outPayload = NULL;
 
     err = cbor_value_enter_container(rootValue, &strVal);
     VERIFY_CBOR_SUCCESS(TAG, err, "Failed entering container");
@@ -124,14 +123,6 @@ static OCStackResult OCParseSecurityPayload(OCPayload** outPayload, CborValue* r
         VERIFY_PARAM_NON_NULL(TAG, *outPayload, "Invalid cbor");
         ret = OC_STACK_OK;
     }
-    else if (cbor_value_is_byte_string(&strVal))
-    {
-        size_t len = 0;
-        err = cbor_value_dup_byte_string(&strVal, &securityData1, &len, NULL);
-        VERIFY_CBOR_SUCCESS(TAG, err, "Failed reading security data");
-        *outPayload = (OCPayload *)OCSecurityPayloadCBORCreate(securityData1);
-        VERIFY_PARAM_NON_NULL(TAG, *outPayload, "Failed Creating Security Cbor.");
-    }
     else if(cbor_value_is_valid(&strVal))
     {
         ret = OC_STACK_OK;
@@ -143,7 +134,6 @@ static OCStackResult OCParseSecurityPayload(OCPayload** outPayload, CborValue* r
 
 exit:
     OICFree(securityData);
-    OICFree(securityData1);
     return ret;
 }
 
old mode 100755 (executable)
new mode 100644 (file)
index ad2f40b..8fb7905
@@ -65,5 +65,5 @@ ocprovision = ocprovision_env.SharedLibrary('ocprovision', ocprovision_src)
 ocprovision_env.InstallTarget(ocprovision, 'libocprovision')
 ocprovision_env.UserInstallTargetLib(ocprovision, 'libocprovision')
 
-if target_os in ['linux', 'tizen']:
+if target_os in ['linux']:
     SConscript('examples/SConscript')