[IOT-1958] CR 22 State Specific Property Access for /pstat Resource
[platform/upstream/iotivity.git] / resource / csdk / security / provisioning / src / secureresourceprovider.c
1 /* *****************************************************************
2  *
3  * Copyright 2015 Samsung Electronics All Rights Reserved.
4  *
5  *
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *     http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  * *****************************************************************/
20 #include "iotivity_config.h"
21 #include <stdio.h>
22 #include <string.h>
23 #include <stdint.h>
24 #ifdef HAVE_UNISTD_H
25 #include <unistd.h>
26 #endif
27
28 #include "ocprovisioningmanager.h"
29 #include "secureresourceprovider.h"
30 #include "logger.h"
31 #include "oic_malloc.h"
32 #include "oic_string.h"
33 #include "aclresource.h"
34 #include "pstatresource.h"
35 #include "srmresourcestrings.h"
36 #include "credresource.h"
37 #include "csrresource.h"
38 #include "rolesresource.h"
39 #include "doxmresource.h"
40 #include "pconfresource.h"
41 #include "credentialgenerator.h"
42 #include "cainterface.h"
43 #include "oic_string.h"
44 #include "pmtypes.h"
45 #include "pmutility.h"
46 #include "srmutility.h"
47 #include "provisioningdatabasemanager.h"
48 #include "base64.h"
49 #include "utlist.h"
50 #include "ocpayload.h"
51 #include "srmutility.h"
52 #include "certhelpers.h"
53
54 #ifdef __WITH_DTLS__
55 #include "crlresource.h"
56 #endif
57
58 #define TAG "OIC_SRPAPI"
59
60 trustCertChainContext_t g_trustCertChainNotifier;
61
62 /**
63  * Structure to carry credential data to callback.
64  */
65 typedef struct CredentialData CredentialData_t;
66 struct CredentialData
67 {
68     void *ctx;                                  /**< Pointer to user context.**/
69     const OCProvisionDev_t *deviceInfo1;        /**< Pointer to OCProvisionDev_t.**/
70     const OCProvisionDev_t *deviceInfo2;        /**< Pointer to OCProvisionDev_t.**/
71     OicSecCred_t *credInfo;                     /**< Pointer to OicSecCred_t.**/
72     OicSecCred_t *credInfoFirst;                /**< Pointer to OicSecCred_t.**/
73     OCProvisionResultCB resultCallback;         /**< Pointer to result callback.**/
74     OCProvisionResult_t *resArr;                /**< Result array.**/
75     int numOfResults;                           /**< Number of results in result array.**/
76 };
77
78 /**
79  * Structure to carry ACL provision API data to callback.
80  */
81 typedef struct ACLData ACLData_t;
82 struct ACLData
83 {
84     void *ctx;                                  /**< Pointer to user context.**/
85     const OCProvisionDev_t *deviceInfo;         /**< Pointer to PMDevInfo_t.**/
86     OCProvisionResultCB resultCallback;         /**< Pointer to result callback.**/
87     OCProvisionResult_t *resArr;                /**< Result array.**/
88     int numOfResults;                           /**< Number of results in result array.**/
89 };
90
91 // Structure to carry get security resource APIs data to callback.
92 typedef struct GetSecData GetSecData_t;
93 struct GetSecData {
94     void *ctx;
95     const OCProvisionDev_t *deviceInfo;         /**< Pointer to PMDevInfo_t.**/
96     OCProvisionResultCB resultCallback;         /**< Pointer to result callback.**/
97     OCProvisionResult_t *resArr;                /**< Result array.**/
98     int numOfResults;                        /**< Number of results in result array.**/
99 };
100
101 typedef struct GetCsrData GetCsrData_t;
102 struct GetCsrData {
103     void *ctx;
104     const OCProvisionDev_t *deviceInfo;         /**< Pointer to PMDevInfo_t.**/
105     OCGetCSRResultCB resultCallback;            /**< Pointer to result callback.**/
106     OCPMGetCsrResult_t *resArr;                 /**< Result array.**/
107     size_t numOfResults;                        /**< Number of results in result array.**/
108 };
109
110 typedef struct GetRolesData GetRolesData_t;
111 struct GetRolesData {
112     void *ctx;                                  /**< User-provided context **/
113     const OCProvisionDev_t *deviceInfo;         /**< Pointer to PMDevInfo_t.**/
114     OCGetRolesResultCB resultCallback;          /**< Pointer to result callback.**/
115     OCPMGetRolesResult_t *resArr;               /**< Result array.**/
116     size_t numOfResults;                        /**< Number of results in result array.**/
117 };
118
119 /**
120  * Structure to carry PCONF provision API data to callback.
121  */
122 typedef struct PconfData PconfData_t;
123 struct PconfData
124 {
125     void *ctx;                                  /**< Pointer to user context.**/
126     const OCProvisionDev_t *deviceInfo;         /**< Pointer to PMDevInfo_t.**/
127     OCProvisionResultCB resultCallback;         /**< Pointer to result callback.**/
128     OCProvisionResult_t *resArr;                /**< Result array.**/
129     int numOfResults;                           /**< Number of results in result array.**/
130 };
131
132 // Enum type index for unlink callback.
133 typedef enum {
134     IDX_FIRST_DEVICE_RES = 0, // index for resulf of the first device
135     IDX_SECOND_DEVICE_RES,    // index for result of the second device
136     IDX_DB_UPDATE_RES         // index for result of updating provisioning database.
137 } IdxUnlinkRes_t;
138
139 // Structure to carry unlink APIs data to callback.
140 typedef struct UnlinkData UnlinkData_t;
141 struct UnlinkData {
142     void *ctx;
143     OCProvisionDev_t* unlinkDev;             /**< Pointer to OCProvisionDev_t to be unlinked.**/
144     OCProvisionResult_t* unlinkRes;          /**< Result array.**/
145     OCProvisionResultCB resultCallback;      /**< Pointer to result callback.**/
146     int numOfResults;                        /**< Number of results in result array.**/
147 };
148
149 //Example of DELETE cred request -> coaps://0.0.0.0:5684/oic/sec/cred?sub=(BASE64 ENCODED UUID)
150 const char * SRP_FORM_DELETE_CREDENTIAL = "coaps://[%s]:%d%s?%s=%s";
151 const char * SRP_FORM_DELETE_CREDENTIAL_TCP = "coaps+tcp://[%s]:%d%s?%s=%s";
152
153 // Structure to carry remove APIs data to callback.
154 typedef struct RemoveData RemoveData_t;
155 struct RemoveData {
156     void *ctx;
157     OCProvisionDev_t* revokeTargetDev;      /**< Device which is going to be revoked..**/
158     OCProvisionDev_t* linkedDevList;        /**< A list of devices which have invalid credential.**/
159     OCProvisionResult_t* removeRes;         /**< Result array.**/
160     OCProvisionResultCB resultCallback;     /**< Pointer to result callback.**/
161     size_t numOfResults;                    /**< Number of results in result array.**/
162     size_t sizeOfResArray;
163     bool hasError;
164 };
165
166 /**
167  * Function prototype
168  */
169 static OCStackResult provisionCredentials(OicSecCred_t *cred,
170         const OCProvisionDev_t *deviceInfo, CredentialData_t *credData,
171         OCClientResponseHandler responseHandler);
172
173 typedef enum {
174     DEVICE_1_FINISHED,
175     DEVICE_2_FINISHED,
176     DEVICE_LOCAL_FINISHED
177 } CredProvisioningResultCause_t;
178
179 /**
180  * Internal function to update result in result array.
181  */
182 static void registerResultForCredProvisioning(CredentialData_t *credData,
183                                               OCStackResult stackresult, CredProvisioningResultCause_t cause)
184 {
185    OCStackResult res = OC_STACK_ERROR;
186    OIC_LOG_V(INFO,TAG,"value of credData->numOfResults is %d",credData->numOfResults);
187    switch (cause)
188    {
189    case DEVICE_1_FINISHED:
190        memcpy(credData->resArr[(credData->numOfResults)].deviceId.id,
191               credData->deviceInfo1->doxm->deviceID.id,UUID_LENGTH);
192        break;
193    case DEVICE_2_FINISHED:
194        memcpy(credData->resArr[(credData->numOfResults)].deviceId.id,
195               credData->deviceInfo2->doxm->deviceID.id,UUID_LENGTH);
196        break;
197    case DEVICE_LOCAL_FINISHED:
198        res = GetDoxmDeviceID(&credData->resArr[(credData->numOfResults)].deviceId);
199        if (OC_STACK_OK != res)
200        {
201            OIC_LOG_V(WARNING, TAG, "%s: Could not retrieve own device ID to populate result for cred provisioning: %d", __func__, res);
202            memset(credData->resArr[(credData->numOfResults)].deviceId.id, 0, UUID_LENGTH);
203        }
204        break;
205    default:
206        assert(!"Unknown value for cause");
207        OIC_LOG_V(ERROR, TAG, "%s: unknown value of cause: %d", __func__, cause);
208        memset(credData->resArr[(credData->numOfResults)].deviceId.id, 0, UUID_LENGTH);
209        break;
210    }
211    credData->resArr[(credData->numOfResults)].res = stackresult;
212    ++(credData->numOfResults);
213 }
214
215 /**
216  * Callback handler for handling callback of provisioning device 2.
217  *
218  * @param[in] ctx             ctx value passed to callback from calling function.
219  * @param[in] UNUSED          handle to an invocation
220  * @param[in] clientResponse  Response from queries to remote servers.
221  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
222  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
223  */
224 static OCStackApplicationResult provisionCredentialCB2(void *ctx, OCDoHandle UNUSED,
225                                                        OCClientResponse *clientResponse)
226 {
227     VERIFY_NOT_NULL_RETURN(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
228     CredentialData_t *credData = (CredentialData_t *) ctx;
229     (void)UNUSED;
230
231     OCProvisionResultCB resultCallback = credData->resultCallback;
232     OIC_LOG(INFO, TAG, "provisionCredentialCB2 called");
233     if (clientResponse)
234     {
235         if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
236         {
237             registerResultForCredProvisioning(credData, OC_STACK_RESOURCE_CHANGED, DEVICE_2_FINISHED);
238             OCStackResult res =  PDMLinkDevices(&credData->deviceInfo1->doxm->deviceID,
239                     &credData->deviceInfo2->doxm->deviceID);
240             if (OC_STACK_OK != res)
241             {
242                 OIC_LOG(ERROR, TAG, "Error occured on PDMLinkDevices");
243                 return OC_STACK_DELETE_TRANSACTION;
244             }
245             OIC_LOG(INFO, TAG, "Link created successfully");
246
247             ((OCProvisionResultCB)(resultCallback))(credData->ctx, credData->numOfResults,
248                                                     credData->resArr,
249                                                     false);
250              OICFree(credData->resArr);
251              OICFree(credData);
252              return OC_STACK_DELETE_TRANSACTION;
253         }
254
255     }
256     OIC_LOG(INFO, TAG, "provisionCredentialCB2 received Null clientResponse");
257     registerResultForCredProvisioning(credData, OC_STACK_ERROR, DEVICE_2_FINISHED);
258     ((OCProvisionResultCB)(resultCallback))(credData->ctx, credData->numOfResults,
259                                             credData->resArr,
260                                             true);
261     OICFree(credData->resArr);
262     OICFree(credData);
263     return OC_STACK_DELETE_TRANSACTION;
264 }
265
266 /**
267  * Callback handler for handling callback of provisioning device 1.
268  *
269  * @param[in] ctx             ctx value passed to callback from calling function.
270  * @param[in] UNUSED          handle to an invocation
271  * @param[in] clientResponse  Response from queries to remote servers.
272  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
273  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
274  */
275 static OCStackApplicationResult provisionCredentialCB1(void *ctx, OCDoHandle UNUSED,
276                                                        OCClientResponse *clientResponse)
277 {
278     VERIFY_NOT_NULL_RETURN(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
279     (void)UNUSED;
280     CredentialData_t* credData = (CredentialData_t*) ctx;
281     OICFree(credData->credInfoFirst);
282     const OCProvisionDev_t *deviceInfo = credData->deviceInfo2;
283     OicSecCred_t *credInfo = credData->credInfo;
284     const OCProvisionResultCB resultCallback = credData->resultCallback;
285     if (clientResponse)
286     {
287         if (OC_STACK_RESOURCE_CHANGED == clientResponse->result)
288         {
289             // send credentials to second device
290             registerResultForCredProvisioning(credData, OC_STACK_RESOURCE_CHANGED, DEVICE_1_FINISHED);
291             OCStackResult res = provisionCredentials(credInfo, deviceInfo, credData,
292                     provisionCredentialCB2);
293             // If deviceInfo is NULL, this device is the second device. Don't delete the cred
294             // because provisionCredentials added it to the local cred store and it now owns
295             // the memory.
296             if ((NULL != deviceInfo) || (OC_STACK_OK != res))
297             {
298                 DeleteCredList(credInfo);
299             }
300             if (OC_STACK_OK != res)
301             {
302                 registerResultForCredProvisioning(credData, res,2);
303                 ((OCProvisionResultCB)(resultCallback))(credData->ctx, credData->numOfResults,
304                                                         credData->resArr,
305                                                         true);
306                 OICFree(credData->resArr);
307                 OICFree(credData);
308                 credData = NULL;
309             }
310         }
311         else
312         {
313             registerResultForCredProvisioning(credData, OC_STACK_ERROR, DEVICE_1_FINISHED);
314             ((OCProvisionResultCB)(resultCallback))(credData->ctx, credData->numOfResults,
315                                                     credData->resArr,
316                                                     true);
317             OICFree(credData->resArr);
318             OICFree(credData);
319             credData = NULL;
320         }
321     }
322     else
323     {
324         OIC_LOG(INFO, TAG, "provisionCredentialCB received Null clientResponse for first device");
325         registerResultForCredProvisioning(credData, OC_STACK_ERROR, DEVICE_1_FINISHED);
326        ((OCProvisionResultCB)(resultCallback))(credData->ctx, credData->numOfResults,
327                                                      credData->resArr,
328                                                      true);
329         DeleteCredList(credInfo);
330         OICFree(credData->resArr);
331         OICFree(credData);
332         credData = NULL;
333     }
334     return OC_STACK_DELETE_TRANSACTION;
335 }
336
337 /**
338  * Internal function for handling credential generation and sending credential to resource server.
339  *
340  * @param[in] cred Instance of cred resource.
341  * @param[in] deviceInfo information about device to which credential is to be provisioned.
342  * @param[in] responseHandler callbak called by OC stack when request API receives response.
343  * @return  OC_STACK_OK in case of success and other value otherwise.
344  */
345 static OCStackResult provisionCredentials(OicSecCred_t *cred,
346         const OCProvisionDev_t *deviceInfo, CredentialData_t *credData,
347         OCClientResponseHandler responseHandler)
348 {
349     OCStackResult res = OC_STACK_OK;
350
351     if (NULL != deviceInfo)
352     {
353         OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
354         if (!secPayload)
355         {
356             OIC_LOG(ERROR, TAG, "Failed to allocate memory");
357             return OC_STACK_NO_MEMORY;
358         }
359         secPayload->base.type = PAYLOAD_TYPE_SECURITY;
360         int secureFlag = 0;
361         res = CredToCBORPayload(cred, &secPayload->securityData, &secPayload->payloadSize, secureFlag);
362         if ((OC_STACK_OK != res) && (NULL == secPayload->securityData))
363         {
364             OCPayloadDestroy((OCPayload *)secPayload);
365             OIC_LOG(ERROR, TAG, "Failed to CredToCBORPayload");
366             return OC_STACK_NO_MEMORY;
367         }
368
369         OIC_LOG(DEBUG, TAG, "Created payload for Cred:");
370         OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
371         char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = { 0 };
372         if (!PMGenerateQuery(true,
373             deviceInfo->endpoint.addr,
374             deviceInfo->securePort,
375             deviceInfo->connType,
376             query, sizeof(query), OIC_RSRC_CRED_URI))
377         {
378             OIC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
379             OCPayloadDestroy((OCPayload *)secPayload);
380             return OC_STACK_ERROR;
381         }
382         OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
383
384         OCCallbackData cbData = { .context = NULL, .cb = NULL, .cd = NULL };
385         cbData.cb = responseHandler;
386         cbData.context = (void *)credData;
387         cbData.cd = NULL;
388
389         OCDoHandle handle = NULL;
390         OCMethod method = OC_REST_POST;
391         res = OCDoResource(&handle, method, query, 0, (OCPayload*)secPayload,
392             deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
393         OIC_LOG_V(INFO, TAG, "OCDoResource::Credential provisioning returned : %d", res);
394         if (res != OC_STACK_OK)
395         {
396             OIC_LOG(ERROR, TAG, "OCStack resource error");
397             return res;
398         }
399         return OC_STACK_OK;
400     }
401     else
402     {
403         /* Provision this credential to the local cred store. On success, the cred resource takes
404          * ownership of the memory. On failure, provisionCredentialCB1 will delete the cred object.
405          */
406         res = AddCredential(cred);
407         /* Call the result callback directly. */
408         registerResultForCredProvisioning(credData, OC_STACK_RESOURCE_CHANGED, DEVICE_LOCAL_FINISHED);
409         (credData->resultCallback)(credData->ctx, credData->numOfResults, credData->resArr, false);
410         return res;
411     }
412 }
413
414 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
415 /**
416  * Structure to carry certificate data to callback.
417  */
418 typedef struct CertificateData CertData_t;
419 struct CertificateData
420 {
421     void *ctx;                                  /**< Pointer to user context.**/
422     const OCProvisionDev_t *deviceInfo;        /**< Pointer to OCProvisionDev_t.**/
423     OicSecCred_t *credInfo;                     /**< Pointer to OicSecCred_t.**/
424     OCProvisionResultCB resultCallback;         /**< Pointer to result callback.**/
425     OCProvisionResult_t *resArr;                /**< Result array.**/
426     int numOfResults;                           /**< Number of results in result array.**/
427 };
428
429 /**
430  * Internal function to update result in result array.
431  */
432 static void registerResultForCertProvisioning(CertData_t *certData,
433                                               OCStackResult stackresult)
434 {
435
436    OIC_LOG_V(INFO,TAG,"value of credData->numOfResults is %d",certData->numOfResults);
437    memcpy(certData->resArr[(certData->numOfResults)].deviceId.id,
438           certData->deviceInfo->doxm->deviceID.id,UUID_LENGTH);
439    certData->resArr[(certData->numOfResults)].res = stackresult;
440    ++(certData->numOfResults);
441 }
442
443 OCStackResult SRPRegisterTrustCertChainNotifier(void *ctx, TrustCertChainChangeCB callback)
444 {
445     if (g_trustCertChainNotifier.callback)
446     {
447         OIC_LOG(ERROR, TAG, "Can't register Notifier, Unregister previous one");
448         return OC_STACK_ERROR;
449     }
450
451     g_trustCertChainNotifier.callback = callback;
452     g_trustCertChainNotifier.context = ctx;
453     return OC_STACK_OK;
454 }
455
456 void SRPRemoveTrustCertChainNotifier()
457 {
458     g_trustCertChainNotifier.callback = NULL;
459     g_trustCertChainNotifier.context = NULL;
460     return;
461 }
462
463 /**
464  * Callback handler for handling callback of certificate provisioning device.
465  *
466  * @param[in] ctx             ctx value passed to callback from calling function.
467  * @param[in] UNUSED          handle to an invocation
468  * @param[in] clientResponse  Response from queries to remote servers.
469  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
470  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
471  */
472 static OCStackApplicationResult provisionCertCB(void *ctx, OCDoHandle UNUSED,
473                                                        OCClientResponse *clientResponse)
474 {
475     VERIFY_NOT_NULL_RETURN(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
476     CertData_t *certData = (CertData_t *) ctx;
477     (void)UNUSED;
478
479     OCProvisionResultCB resultCallback = certData->resultCallback;
480     OIC_LOG(INFO, TAG, "provisionCertCB called");
481     if (clientResponse)
482     {
483         if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
484         {
485             registerResultForCertProvisioning(certData, OC_STACK_RESOURCE_CHANGED);
486             ((OCProvisionResultCB)(resultCallback))(certData->ctx, certData->numOfResults,
487                                                     certData->resArr,
488                                                     false);
489              OICFree(certData->resArr);
490              OICFree(certData);
491              return OC_STACK_DELETE_TRANSACTION;
492         }
493
494     }
495     OIC_LOG(INFO, TAG, "provisionCertCredCB received Null clientResponse");
496     registerResultForCertProvisioning(certData, OC_STACK_ERROR);
497     ((OCProvisionResultCB)(resultCallback))(certData->ctx, certData->numOfResults,
498                                             certData->resArr,
499                                             true);
500     OICFree(certData->resArr);
501     OICFree(certData);
502     return OC_STACK_DELETE_TRANSACTION;
503 }
504
505 static OCStackApplicationResult provisionCertificateCB(void *ctx, OCDoHandle UNUSED,
506     OCClientResponse *clientResponse)
507 {
508     // Just call the callback provided to SRProvisionCredentials
509     VERIFY_NOT_NULL_RETURN(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
510     CredentialData_t* credData = (CredentialData_t *)ctx;
511     (void)UNUSED;
512     bool hasError;
513
514     // We expect OC_STACK_RESOURCE_CHANGED, anything else is an error
515     if (clientResponse && (OC_STACK_RESOURCE_CHANGED == clientResponse->result))
516     {
517         hasError = false;
518     }
519     else
520     {
521         hasError = true;
522     }
523
524     OCProvisionResultCB resultCallback = credData->resultCallback;
525     VERIFY_NOT_NULL_RETURN(TAG, resultCallback, ERROR, OC_STACK_DELETE_TRANSACTION);
526
527     ((OCProvisionResultCB)(resultCallback))(credData->ctx, credData->numOfResults,
528         credData->resArr, hasError);
529
530     OICFree(credData);
531
532     return OC_STACK_DELETE_TRANSACTION;
533
534 }
535
536 OCStackResult SRPProvisionTrustCertChain(void *ctx, OicSecCredType_t type, uint16_t credId,
537         const OCProvisionDev_t *selectedDeviceInfo, OCProvisionResultCB resultCallback)
538 {
539     OIC_LOG(INFO, TAG, "IN SRPProvisionTrustCertChain");
540     VERIFY_NOT_NULL_RETURN(TAG, selectedDeviceInfo, ERROR,  OC_STACK_INVALID_PARAM);
541     VERIFY_NOT_NULL_RETURN(TAG, resultCallback, ERROR,  OC_STACK_INVALID_CALLBACK);
542     if (SIGNED_ASYMMETRIC_KEY != type)
543     {
544         OIC_LOG(INFO, TAG, "Invalid key type");
545         return OC_STACK_INVALID_PARAM;
546     }
547
548     OicSecCred_t *trustCertChainCred = GetCredEntryByCredId(credId);
549     if(NULL == trustCertChainCred)
550     {
551         OIC_LOG(ERROR, TAG, "Can not find matched Trust Cert. Chain.");
552         return OC_STACK_NO_RESOURCE;
553     }
554
555     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
556     if(!secPayload)
557     {
558         DeleteCredList(trustCertChainCred);
559         OIC_LOG(ERROR, TAG, "Failed to allocate memory");
560         return OC_STACK_NO_MEMORY;
561     }
562     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
563     int secureFlag = 1; /* Don't send the private key to the device, if it happens to be present */
564     if(OC_STACK_OK != CredToCBORPayload(trustCertChainCred, &secPayload->securityData, &secPayload->payloadSize, secureFlag))
565     {
566         DeleteCredList(trustCertChainCred);
567         OCPayloadDestroy((OCPayload *)secPayload);
568         OIC_LOG(ERROR, TAG, "Failed to CredToCBORPayload");
569         return OC_STACK_NO_MEMORY;
570     }
571     DeleteCredList(trustCertChainCred);
572     OIC_LOG(DEBUG, TAG, "Created payload for Cred:");
573     OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
574
575     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
576     if(!PMGenerateQuery(true,
577                         selectedDeviceInfo->endpoint.addr,
578                         selectedDeviceInfo->securePort,
579                         selectedDeviceInfo->connType,
580                         query, sizeof(query), OIC_RSRC_CRED_URI))
581     {
582         OIC_LOG(ERROR, TAG, "SRPProvisionTrustCertChain : Failed to generate query");
583         OCPayloadDestroy((OCPayload *)secPayload);
584         return OC_STACK_ERROR;
585     }
586     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
587
588     OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};
589     cbData.cb = &provisionCertCB;
590     CertData_t *certData = (CertData_t *) OICCalloc(1, sizeof(CertData_t));
591     if (NULL == certData)
592     {
593         OIC_LOG(ERROR, TAG, "Memory allocation problem");
594         OCPayloadDestroy((OCPayload *)secPayload);
595         return OC_STACK_NO_MEMORY;
596     }
597     certData->deviceInfo = selectedDeviceInfo;
598     certData->resultCallback = resultCallback;
599     certData->credInfo = NULL; //credInfo not used in the response handler
600     certData->numOfResults=0;
601     certData->ctx = ctx;
602
603     int noOfRiCalls = 1;
604     certData->resArr = (OCProvisionResult_t*)OICCalloc(noOfRiCalls, sizeof(OCProvisionResult_t));
605     if (certData->resArr == NULL)
606     {
607         OICFree(certData);
608         OCPayloadDestroy((OCPayload *)secPayload);
609         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
610         return OC_STACK_NO_MEMORY;
611     }
612     cbData.context = (void *)certData;
613     cbData.cd = NULL;
614     OCMethod method = OC_REST_POST;
615     OCDoHandle handle = NULL;
616     OIC_LOG(DEBUG, TAG, "Sending Cred info to resource server");
617     OCStackResult ret = OCDoResource(&handle, method, query,
618             &selectedDeviceInfo->endpoint, (OCPayload*)secPayload,
619             selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
620     if (ret != OC_STACK_OK)
621     {
622         OICFree(certData->resArr);
623         OICFree(certData);
624     }
625
626     VERIFY_SUCCESS_RETURN(TAG, (OC_STACK_OK == ret), ERROR, OC_STACK_ERROR);
627
628     OIC_LOG(INFO, TAG, "OUT SRPProvisionTrustCertChain");
629
630     return OC_STACK_OK;
631 }
632
633 OCStackResult SRPSaveTrustCertChain(const uint8_t *trustCertChain, size_t chainSize,
634                                             OicEncodingType_t encodingType, uint16_t *credId)
635 {
636     OIC_LOG(DEBUG, TAG, "IN SRPSaveTrustCertChain");
637     VERIFY_NOT_NULL_RETURN(TAG, trustCertChain, ERROR,  OC_STACK_INVALID_PARAM);
638     VERIFY_NOT_NULL_RETURN(TAG, credId, ERROR,  OC_STACK_INVALID_PARAM);
639
640     OCStackResult res = OC_STACK_ERROR;
641
642     OicSecCred_t *cred = (OicSecCred_t *)OICCalloc(1, sizeof(*cred));
643     VERIFY_NOT_NULL_RETURN(TAG, cred, ERROR, OC_STACK_NO_MEMORY);
644
645     res = GetDoxmDeviceID(&cred->subject);
646     if (OC_STACK_OK != res)
647     {
648         OIC_LOG(ERROR, TAG, "Can't get the device id(GetDoxmDeviceID)");
649         DeleteCredList(cred);
650         return res;
651     }
652
653     cred->credUsage= (char *)OICCalloc(1, strlen(TRUST_CA) + 1);
654     VERIFY_NOT_NULL_RETURN(TAG, cred->credUsage, ERROR, OC_STACK_NO_MEMORY);
655     OICStrcpy(cred->credUsage, strlen(TRUST_CA) + 1, TRUST_CA);
656
657     cred->credType = SIGNED_ASYMMETRIC_KEY;
658
659     if (encodingType == OIC_ENCODING_PEM)
660     {
661         cred->optionalData.data = (uint8_t *)OICCalloc(1, chainSize + 1);
662         VERIFY_NOT_NULL_RETURN(TAG, cred->optionalData.data, ERROR, OC_STACK_NO_MEMORY);
663         cred->optionalData.len = chainSize + 1;
664     }
665     else if (encodingType == OIC_ENCODING_DER)
666     {
667         cred->optionalData.data = (uint8_t *)OICCalloc(1, chainSize);
668         VERIFY_NOT_NULL_RETURN(TAG, cred->optionalData.data, ERROR, OC_STACK_NO_MEMORY);
669         cred->optionalData.len = chainSize;
670     }
671     else
672     {
673         OIC_LOG_V(ERROR, TAG, "Unknown encoding in %s", __func__);
674         DeleteCredList(cred);
675         return OC_STACK_INVALID_PARAM;
676     }
677     memcpy(cred->optionalData.data, trustCertChain, chainSize);
678     cred->optionalData.encoding = encodingType;
679     cred->optionalData.revstat = false;
680
681     res = AddCredential(cred);
682     if(res != OC_STACK_OK)
683     {
684         DeleteCredList(cred);
685         return res;
686     }
687     *credId = cred->credId;
688
689     if (g_trustCertChainNotifier.callback)
690     {
691         uint8_t *certChain = (uint8_t*)OICCalloc(1, sizeof(uint8_t) * chainSize);
692         VERIFY_NOT_NULL_RETURN(TAG, certChain, ERROR, OC_STACK_NO_MEMORY);
693         memcpy(certChain, trustCertChain, chainSize);
694         g_trustCertChainNotifier.callback(g_trustCertChainNotifier.context, *credId,
695                 certChain, chainSize);
696         OICFree(certChain);
697     }
698
699     OIC_LOG(DEBUG, TAG, "OUT SRPSaveTrustCertChain");
700
701     return res;
702 }
703
704 static OCStackResult saveCertChain(OicSecKey_t * cert, OicSecKey_t * key, uint16_t *credId, const char* usage)
705 {
706     OIC_LOG_V(DEBUG, TAG, "IN %s", __func__);
707     VERIFY_NOT_NULL_RETURN(TAG, cert, ERROR,  OC_STACK_INVALID_PARAM);
708     VERIFY_NOT_NULL_RETURN(TAG, cert->data, ERROR,  OC_STACK_INVALID_PARAM);
709     if (key != NULL)
710     {
711         /* Key is optional. */
712         VERIFY_NOT_NULL_RETURN(TAG, key->data, ERROR, OC_STACK_INVALID_PARAM);
713     }
714     VERIFY_NOT_NULL_RETURN(TAG, credId, ERROR,  OC_STACK_INVALID_PARAM);
715     VERIFY_NOT_NULL_RETURN(TAG, usage, ERROR, OC_STACK_INVALID_PARAM);
716
717     OCStackResult res = OC_STACK_ERROR;
718
719     OicSecCred_t *cred = (OicSecCred_t *)OICCalloc(1, sizeof(*cred));
720     VERIFY_NOT_NULL_RETURN(TAG, cred, ERROR, OC_STACK_NO_MEMORY);
721
722     OIC_LOG_V(DEBUG, TAG, "IN: %s", __func__);
723
724     res = GetDoxmDeviceID(&cred->subject);
725     if (OC_STACK_OK != res)
726     {
727         OIC_LOG(ERROR, TAG, "Can't get the device id(GetDoxmDeviceID)");
728         DeleteCredList(cred);
729         return res;
730     }
731
732     cred->credUsage= (char *)OICCalloc(1, strlen(usage) + 1);
733     VERIFY_NOT_NULL_RETURN(TAG, cred->credUsage, ERROR, OC_STACK_NO_MEMORY);
734     OICStrcpy(cred->credUsage, strlen(usage) + 1, usage);
735
736     cred->credType = SIGNED_ASYMMETRIC_KEY;
737
738     OicSecKey_t *publicData = &cred->publicData;
739     publicData->data = (uint8_t *)OICCalloc(1, cert->len);
740     VERIFY_NOT_NULL_RETURN(TAG, publicData->data, ERROR, OC_STACK_NO_MEMORY);
741     memcpy(publicData->data, cert->data, cert->len);
742     publicData->len = cert->len;
743     publicData->encoding = cert->encoding;
744
745     if (key != NULL)
746     {
747         OicSecKey_t *privateData = &cred->privateData;
748         privateData->data = (uint8_t *)OICCalloc(1, key->len);
749         VERIFY_NOT_NULL_RETURN(TAG, privateData->data, ERROR, OC_STACK_NO_MEMORY);
750         memcpy(privateData->data, key->data, key->len);
751         privateData->len = key->len;
752         privateData->encoding = key->encoding;
753     }
754
755     res = AddCredential(cred);
756     if(res != OC_STACK_OK)
757     {
758         DeleteCredList(cred);
759         return res;
760     }
761     *credId = cred->credId;
762
763     OIC_LOG_V(DEBUG, TAG, "OUT %s", __func__);
764
765     return res;
766 }
767
768 OCStackResult SRPSaveOwnCertChain(OicSecKey_t * cert, OicSecKey_t * key, uint16_t *credId)
769 {
770     return saveCertChain(cert, key, credId, PRIMARY_CERT);
771 }
772
773 OCStackResult SRPSaveOwnRoleCert(OicSecKey_t * cert, uint16_t *credId)
774 {
775     return saveCertChain(cert, NULL, credId, ROLE_CERT);
776 }
777
778 #endif // __WITH_DTLS__ || __WITH_TLS__
779
780 OCStackResult SRPProvisionCredentials(void *ctx, OicSecCredType_t type, size_t keySize,
781                                       const OCProvisionDev_t *pDev1,
782                                       const OCProvisionDev_t *pDev2,
783                                       const char* pemCert,
784                                       const OicSecRole_t *role1,
785                                       const OicSecRole_t *role2,
786                                       OCProvisionResultCB resultCallback)
787 {
788     VERIFY_NOT_NULL_RETURN(TAG, pDev1, ERROR,  OC_STACK_INVALID_PARAM);
789     if (!resultCallback)
790     {
791         OIC_LOG(INFO, TAG, "SRPProvisionCredentials: NULL Callback");
792         return OC_STACK_INVALID_CALLBACK;
793     }
794     if ((SYMMETRIC_PAIR_WISE_KEY == type) &&
795         (NULL != pDev2) &&
796         (0 == memcmp(&pDev1->doxm->deviceID, &pDev2->doxm->deviceID, sizeof(OicUuid_t))))
797     {
798         OIC_LOG(INFO, TAG, "SRPProvisionCredentials : Same device ID");
799         return OC_STACK_INVALID_PARAM;
800     }
801
802     if (SYMMETRIC_PAIR_WISE_KEY == type &&
803        !(OWNER_PSK_LENGTH_128 == keySize || OWNER_PSK_LENGTH_256 == keySize))
804     {
805         OIC_LOG(INFO, TAG, "Invalid key size");
806         return OC_STACK_INVALID_PARAM;
807     }
808
809     OIC_LOG(INFO, TAG, "In SRPProvisionCredentials");
810
811     if ((SYMMETRIC_PAIR_WISE_KEY == type) && (NULL != pDev2))
812     {
813         bool linkExisits = true;
814         OCStackResult res = PDMIsLinkExists(&pDev1->doxm->deviceID, &pDev2->doxm->deviceID, &linkExisits);
815
816         if (res != OC_STACK_OK)
817         {
818             OIC_LOG(ERROR, TAG, "Internal error occured");
819             return res;
820         }
821         if (linkExisits)
822         {
823             OIC_LOG(ERROR, TAG, "Link already exists");
824             return OC_STACK_INVALID_PARAM;
825         }
826     }
827
828     OicUuid_t provTooldeviceID =   {{0,}};
829     if (OC_STACK_OK != GetDoxmDeviceID(&provTooldeviceID))
830     {
831         OIC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
832         return OC_STACK_ERROR;
833     }
834     OIC_LOG(INFO, TAG, "retrieved deviceid");
835     switch (type)
836     {
837         case SYMMETRIC_PAIR_WISE_KEY:
838         {
839             const OCProvisionDev_t *firstDevice = pDev1;
840             const OCProvisionDev_t *secondDevice = pDev2;
841
842             OicSecCred_t *firstCred = NULL;
843             OicSecCred_t *secondCred = NULL;
844             OCStackResult res = PMGeneratePairWiseCredentials(type, keySize, &provTooldeviceID,
845                     &firstDevice->doxm->deviceID, (NULL != secondDevice) ? &secondDevice->doxm->deviceID : &provTooldeviceID,
846                     role1, role2,
847                     &firstCred, &secondCred);
848             VERIFY_SUCCESS_RETURN(TAG, (res==OC_STACK_OK), ERROR, OC_STACK_ERROR);
849             OIC_LOG(INFO, TAG, "Credentials generated successfully");
850             CredentialData_t *credData =
851                 (CredentialData_t *) OICCalloc(1, sizeof(CredentialData_t));
852             if (NULL == credData)
853             {
854                 OICFree(firstCred);
855                 OICFree(secondCred);
856                 OIC_LOG(ERROR, TAG, "Memory allocation problem");
857                 return OC_STACK_NO_MEMORY;
858             }
859             credData->deviceInfo1 = firstDevice;
860             credData->deviceInfo2 = secondDevice;
861             credData->credInfo = secondCred;
862             credData->ctx = ctx;
863             credData->credInfoFirst = firstCred;
864             credData->numOfResults = 0;
865             credData->resultCallback = resultCallback;
866             // first call to provision creds to device1.
867             // second call to provision creds to device2.
868             int noOfRiCalls = 2;
869             credData->resArr =
870                 (OCProvisionResult_t*)OICCalloc(noOfRiCalls, sizeof(OCProvisionResult_t));
871             if (NULL == credData->resArr)
872             {
873                 OICFree(firstCred);
874                 OICFree(secondCred);
875                 OICFree(credData);
876                 OIC_LOG(ERROR, TAG, "Memory allocation problem");
877                 return OC_STACK_NO_MEMORY;
878             }
879             res = provisionCredentials(firstCred, firstDevice, credData, &provisionCredentialCB1);
880             if (OC_STACK_OK != res)
881             {
882                 DeleteCredList(firstCred);
883                 DeleteCredList(secondCred);
884                 OICFree(credData->resArr);
885                 OICFree(credData);
886             }
887             OIC_LOG_V(INFO, TAG, "provisionCredentials returned: %d",res);
888             VERIFY_SUCCESS_RETURN(TAG, (res==OC_STACK_OK), ERROR, OC_STACK_ERROR);
889             return res;
890         }
891         case SIGNED_ASYMMETRIC_KEY:
892         {
893             /* pDev1 is the device to be provisioned, checked non-null above */
894             /* pDev2 is not used, should be NULL */
895             /* size param is not used. */
896             /* pemCert is the cerficiate to be provisioned */
897             VERIFY_NOT_NULL_RETURN(TAG, pemCert, ERROR, OC_STACK_INVALID_PARAM);
898
899             OicSecKey_t deviceCert = { 0 };
900             deviceCert.data = (uint8_t*) pemCert; /* Casting away const is OK here */
901             deviceCert.len = strlen(pemCert) + 1;
902             deviceCert.encoding = OIC_ENCODING_PEM;
903
904             /* Create a credential object */
905             OicSecCred_t* cred =  GenerateCredential(&pDev1->doxm->deviceID, SIGNED_ASYMMETRIC_KEY,
906                     &deviceCert, NULL, // oic.sec.cred.publicdata = deviceCert, .privatedata = NULL
907                     &provTooldeviceID, NULL); // rowner is the provisioning tool and no eowner
908             VERIFY_NOT_NULL_RETURN(TAG, cred, ERROR, OC_STACK_ERROR);
909
910             cred->publicData.encoding = OIC_ENCODING_PEM;
911
912             if (OCInternalIsValidRoleCertificate(deviceCert.data, deviceCert.len, NULL, NULL) == OC_STACK_OK)
913             {
914                 cred->credUsage = OICStrdup(ROLE_CERT);
915             }
916             else
917             {
918                 cred->credUsage = OICStrdup(PRIMARY_CERT);
919             }
920
921             /* Create credential data (used by the response handler provisionCertificateCB and freed there) */
922             CredentialData_t *credData = (CredentialData_t *)OICCalloc(1, sizeof(CredentialData_t));
923             if ((NULL == credData) || (NULL == cred->credUsage))
924             {
925                 DeleteCredList(cred);
926                 OIC_LOG(ERROR, TAG, "Memory allocation problem");
927                 return OC_STACK_NO_MEMORY;
928             }
929             credData->deviceInfo1 = pDev1;
930             credData->deviceInfo2 = NULL;
931             credData->credInfo = cred;
932             credData->ctx = ctx;
933             credData->credInfoFirst = cred;
934             credData->numOfResults = 0;
935             credData->resultCallback = resultCallback;
936             credData->resArr = NULL;
937
938             /* Note: the callback is of type OCClientResponseHandler, thin wrapper that calls resultCallback */
939             OCStackResult res = provisionCredentials(cred, pDev1, credData, &provisionCertificateCB);
940             if (res != OC_STACK_OK)
941             {
942                 OICFree(credData);
943             }
944
945             DeleteCredList(cred);
946             return OC_STACK_OK;
947         }
948         default:
949         {
950             OIC_LOG(ERROR, TAG, "Invalid option.");
951             return OC_STACK_INVALID_PARAM;
952         }
953     }
954 }
955
956 /**
957  * Internal Function to store results in result array during ACL provisioning.
958  */
959 static void registerResultForACLProvisioning(ACLData_t *aclData,
960                                              OCStackResult stackresult)
961 {
962    OIC_LOG_V(INFO, TAG, "Inside registerResultForACLProvisioning aclData->numOfResults is %d",
963                        aclData->numOfResults);
964    memcpy(aclData->resArr[(aclData->numOfResults)].deviceId.id,
965           aclData->deviceInfo->doxm->deviceID.id, UUID_LENGTH);
966    aclData->resArr[(aclData->numOfResults)].res = stackresult;
967    ++(aclData->numOfResults);
968 }
969
970 /**
971  * Callback handler of SRPProvisionACL.
972  *
973  * @param[in] ctx             ctx value passed to callback from calling function.
974  * @param[in] UNUSED          handle to an invocation
975  * @param[in] clientResponse  Response from queries to remote servers.
976  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
977  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
978  */
979 static OCStackApplicationResult SRPProvisionACLCB(void *ctx, OCDoHandle UNUSED,
980                                                   OCClientResponse *clientResponse)
981 {
982     OIC_LOG_V(INFO, TAG, "Inside SRPProvisionACLCB.");
983     (void)UNUSED;
984     VERIFY_NOT_NULL_RETURN(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
985     ACLData_t *aclData = (ACLData_t*)ctx;
986     OCProvisionResultCB resultCallback = aclData->resultCallback;
987
988     if (clientResponse)
989     {
990         if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
991         {
992             registerResultForACLProvisioning(aclData, OC_STACK_RESOURCE_CHANGED);
993             ((OCProvisionResultCB)(resultCallback))(aclData->ctx, aclData->numOfResults,
994                                                     aclData->resArr,
995                                                     false);
996              OICFree(aclData->resArr);
997              OICFree(aclData);
998              return OC_STACK_DELETE_TRANSACTION;
999         }
1000     }
1001     registerResultForACLProvisioning(aclData, OC_STACK_ERROR);
1002     ((OCProvisionResultCB)(resultCallback))(aclData->ctx, aclData->numOfResults,
1003                                             aclData->resArr,
1004                                             true);
1005     OIC_LOG_V(ERROR, TAG, "SRPProvisionACLCB received Null clientResponse");
1006     OICFree(aclData->resArr);
1007     OICFree(aclData);
1008     return OC_STACK_DELETE_TRANSACTION;
1009 }
1010
1011 OCStackResult SRPProvisionACL(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
1012         OicSecAcl_t *acl, OicSecAclVersion_t aclVersion, OCProvisionResultCB resultCallback)
1013 {
1014     VERIFY_NOT_NULL_RETURN(TAG, selectedDeviceInfo, ERROR,  OC_STACK_INVALID_PARAM);
1015     VERIFY_NOT_NULL_RETURN(TAG, acl, ERROR,  OC_STACK_INVALID_PARAM);
1016     VERIFY_NOT_NULL_RETURN(TAG, resultCallback, ERROR,  OC_STACK_INVALID_CALLBACK);
1017
1018     const char *uri = NULL;
1019
1020     switch (aclVersion)
1021     {
1022     case OIC_SEC_ACL_V1:
1023         uri = OIC_RSRC_ACL_URI;
1024         break;
1025     case OIC_SEC_ACL_V2:
1026         uri = OIC_RSRC_ACL2_URI;
1027         break;
1028     default:
1029         return OC_STACK_INVALID_PARAM;
1030     }
1031
1032     // if rowneruuid is empty, set it to device ID
1033     OicUuid_t emptyOwner = {.id = {0} };
1034     if (memcmp(&(acl->rownerID.id), &emptyOwner, UUID_IDENTITY_SIZE) == 0)
1035     {
1036         OIC_LOG(DEBUG, TAG, "Set Rowner to PT's deviceId, because Rowner of ACL is empty");
1037         OicUuid_t oicUuid;
1038
1039         if (OC_STACK_OK == GetDoxmDeviceID(&oicUuid))
1040         {
1041             memcpy(&(acl->rownerID.id), &oicUuid, UUID_IDENTITY_SIZE);
1042         }
1043         else
1044         {
1045             OIC_LOG(DEBUG, TAG, "Failed to set Rowner to PT's deviceID\
1046                 becuase it failed to retrieve Doxm DeviceID");
1047             return OC_STACK_ERROR;
1048         }
1049     }
1050
1051     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1052     if(!secPayload)
1053     {
1054         OIC_LOG(ERROR, TAG, "Failed to allocate memory");
1055         return OC_STACK_NO_MEMORY;
1056     }
1057     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1058     if(OC_STACK_OK != AclToCBORPayload(acl, aclVersion, &secPayload->securityData, &secPayload->payloadSize))
1059     {
1060         OCPayloadDestroy((OCPayload *)secPayload);
1061         OIC_LOG(ERROR, TAG, "Failed to AclToCBORPayload");
1062         return OC_STACK_NO_MEMORY;
1063     }
1064     OIC_LOG(DEBUG, TAG, "Created payload for ACL:");
1065     OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1066
1067     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1068     if(!PMGenerateQuery(true,
1069                         selectedDeviceInfo->endpoint.addr,
1070                         selectedDeviceInfo->securePort,
1071                         selectedDeviceInfo->connType,
1072                         query, sizeof(query), uri))
1073     {
1074         OIC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
1075         return OC_STACK_ERROR;
1076     }
1077     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1078
1079     OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};
1080     cbData.cb = &SRPProvisionACLCB;
1081     ACLData_t *aclData = (ACLData_t *) OICCalloc(1, sizeof(ACLData_t));
1082     if (aclData == NULL)
1083     {
1084         OCPayloadDestroy((OCPayload *)secPayload);
1085         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
1086         return OC_STACK_NO_MEMORY;
1087     }
1088     aclData->deviceInfo = selectedDeviceInfo;
1089     aclData->resultCallback = resultCallback;
1090     aclData->numOfResults=0;
1091     aclData->ctx = ctx;
1092     // call to provision ACL to device1.
1093     int noOfRiCalls = 1;
1094     aclData->resArr = (OCProvisionResult_t*)OICCalloc(noOfRiCalls, sizeof(OCProvisionResult_t));
1095     if (aclData->resArr == NULL)
1096     {
1097         OICFree(aclData);
1098         OCPayloadDestroy((OCPayload *)secPayload);
1099         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
1100         return OC_STACK_NO_MEMORY;
1101     }
1102     cbData.context = (void *)aclData;
1103     cbData.cd = NULL;
1104     OCMethod method = OC_REST_POST;
1105     OCDoHandle handle = NULL;
1106     OIC_LOG(DEBUG, TAG, "Sending ACL info to resource server");
1107     OCStackResult ret = OCDoResource(&handle, method, query,
1108             &selectedDeviceInfo->endpoint, (OCPayload*)secPayload,
1109             selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1110     if (ret != OC_STACK_OK)
1111     {
1112         OICFree(aclData->resArr);
1113         OICFree(aclData);
1114     }
1115     VERIFY_SUCCESS_RETURN(TAG, (OC_STACK_OK == ret), ERROR, OC_STACK_ERROR);
1116     return OC_STACK_OK;
1117 }
1118
1119 OCStackResult SRPSaveACL(const OicSecAcl_t *acl)
1120 {
1121     OIC_LOG(DEBUG, TAG, "IN SRPSaveACL");
1122     VERIFY_NOT_NULL_RETURN(TAG, acl, ERROR,  OC_STACK_INVALID_PARAM);
1123
1124     OCStackResult res =  InstallACL(acl);
1125
1126     OIC_LOG(DEBUG, TAG, "OUT SRPSaveACL");
1127     return res;
1128 }
1129
1130 /**
1131  * Internal Function to store results in result array during Direct-Pairing provisioning.
1132  */
1133 static void registerResultForDirectPairingProvisioning(PconfData_t *pconfData,
1134                                              OCStackResult stackresult)
1135 {
1136    OIC_LOG_V(INFO, TAG, "Inside registerResultForDirectPairingProvisioning "
1137            "pconfData->numOfResults is %d", pconfData->numOfResults);
1138    memcpy(pconfData->resArr[(pconfData->numOfResults)].deviceId.id,
1139           pconfData->deviceInfo->doxm->deviceID.id, UUID_LENGTH);
1140    pconfData->resArr[(pconfData->numOfResults)].res = stackresult;
1141    ++(pconfData->numOfResults);
1142 }
1143
1144 /**
1145  * Callback handler of SRPProvisionDirectPairing.
1146  *
1147  * @param[in] ctx             ctx value passed to callback from calling function.
1148  * @param[in] UNUSED          handle to an invocation
1149  * @param[in] clientResponse  Response from queries to remote servers.
1150  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
1151  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
1152  */
1153 static OCStackApplicationResult SRPProvisionDirectPairingCB(void *ctx, OCDoHandle UNUSED,
1154                                                   OCClientResponse *clientResponse)
1155 {
1156     OIC_LOG_V(INFO, TAG, "Inside SRPProvisionDirectPairingCB.");
1157     (void)UNUSED;
1158     VERIFY_NOT_NULL_RETURN(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
1159     PconfData_t *pconfData = (PconfData_t*)ctx;
1160     OCProvisionResultCB resultCallback = pconfData->resultCallback;
1161
1162     if (clientResponse)
1163     {
1164         if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
1165         {
1166             registerResultForDirectPairingProvisioning(pconfData, OC_STACK_OK);
1167             ((OCProvisionResultCB)(resultCallback))(pconfData->ctx, pconfData->numOfResults,
1168                                                     pconfData->resArr,
1169                                                     false);
1170              OICFree(pconfData->resArr);
1171              OICFree(pconfData);
1172              return OC_STACK_DELETE_TRANSACTION;
1173         }
1174     }
1175     registerResultForDirectPairingProvisioning(pconfData, OC_STACK_ERROR);
1176     ((OCProvisionResultCB)(resultCallback))(pconfData->ctx, pconfData->numOfResults,
1177                                             pconfData->resArr,
1178                                             true);
1179     OIC_LOG_V(ERROR, TAG, "SRPProvisionDirectPairingCB received Null clientResponse");
1180     OICFree(pconfData->resArr);
1181     OICFree(pconfData);
1182     return OC_STACK_DELETE_TRANSACTION;
1183 }
1184
1185 OCStackResult SRPProvisionDirectPairing(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
1186         OicSecPconf_t *pconf, OCProvisionResultCB resultCallback)
1187 {
1188     VERIFY_NOT_NULL_RETURN(TAG, selectedDeviceInfo, ERROR,  OC_STACK_INVALID_PARAM);
1189     VERIFY_NOT_NULL_RETURN(TAG, pconf, ERROR,  OC_STACK_INVALID_PARAM);
1190     VERIFY_NOT_NULL_RETURN(TAG, resultCallback, ERROR,  OC_STACK_INVALID_CALLBACK);
1191
1192     // check direct-pairing capability
1193     if (true != selectedDeviceInfo->doxm->dpc)
1194     {
1195         OIC_LOG(ERROR, TAG, "Resouce server does not have Direct-Pairing Capability ");
1196         return OC_STACK_UNAUTHORIZED_REQ;
1197     }
1198
1199     OicUuid_t provTooldeviceID =   {.id={0}};
1200     if (OC_STACK_OK != GetDoxmDeviceID(&provTooldeviceID))
1201     {
1202         OIC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
1203         return OC_STACK_ERROR;
1204     }
1205     memcpy(&pconf->rownerID, &provTooldeviceID, sizeof(OicUuid_t));
1206
1207     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1208     if(!secPayload)
1209     {
1210         OIC_LOG(ERROR, TAG, "Failed to allocate memory");
1211         return OC_STACK_NO_MEMORY;
1212     }
1213     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1214
1215     if (OC_STACK_OK != PconfToCBORPayload(pconf, &(secPayload->securityData),
1216                 &(secPayload->payloadSize)))
1217     {
1218         OCPayloadDestroy((OCPayload*)secPayload);
1219         OIC_LOG(ERROR, TAG, "Failed to PconfToCborPayload");
1220         return OC_STACK_NO_MEMORY;
1221     }
1222     OIC_LOG(DEBUG, TAG, "Created payload for pconf set");
1223     OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1224
1225     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1226     if(!PMGenerateQuery(true,
1227                 selectedDeviceInfo->endpoint.addr,
1228                 selectedDeviceInfo->securePort,
1229                 selectedDeviceInfo->connType,
1230                 query, sizeof(query), OIC_RSRC_PCONF_URI))
1231     {
1232         OIC_LOG(ERROR, TAG, "SRPProvisionDirectPairing : Failed to generate query");
1233         return OC_STACK_ERROR;
1234     }
1235     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1236
1237     OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};
1238     cbData.cb = &SRPProvisionDirectPairingCB;
1239     PconfData_t *pconfData = (PconfData_t *) OICCalloc(1, sizeof(PconfData_t));
1240     if (NULL == pconfData)
1241     {
1242         OCPayloadDestroy((OCPayload*)secPayload);
1243         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
1244         return OC_STACK_NO_MEMORY;
1245     }
1246     pconfData->deviceInfo = selectedDeviceInfo;
1247     pconfData->resultCallback = resultCallback;
1248     pconfData->numOfResults=0;
1249     pconfData->ctx = ctx;
1250     // call to provision PCONF to device1.
1251     int noOfRiCalls = 1;
1252     pconfData->resArr = (OCProvisionResult_t*)OICCalloc(noOfRiCalls, sizeof(OCProvisionResult_t));
1253     if (NULL == pconfData->resArr)
1254     {
1255         OICFree(pconfData);
1256         OCPayloadDestroy((OCPayload*)secPayload);
1257         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
1258         return OC_STACK_NO_MEMORY;
1259     }
1260     cbData.context = (void *)pconfData;
1261     cbData.cd = NULL;
1262     OCMethod method = OC_REST_POST;
1263     OCDoHandle handle = NULL;
1264     OIC_LOG(DEBUG, TAG, "Sending PCONF info to resource server");
1265     OCStackResult ret = OCDoResource(&handle, method, query,
1266             &selectedDeviceInfo->endpoint, (OCPayload*)secPayload,
1267             selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1268     if (OC_STACK_OK != ret)
1269     {
1270         OICFree(pconfData->resArr);
1271         OICFree(pconfData);
1272     }
1273     VERIFY_SUCCESS_RETURN(TAG, (OC_STACK_OK == ret), ERROR, OC_STACK_ERROR);
1274     return OC_STACK_OK;
1275 }
1276
1277 static void DeleteUnlinkData_t(UnlinkData_t *unlinkData)
1278 {
1279     if (unlinkData)
1280     {
1281         OICFree(unlinkData->unlinkDev);
1282         OICFree(unlinkData->unlinkRes);
1283         OICFree(unlinkData);
1284     }
1285 }
1286
1287 static void registerResultForUnlinkDevices(UnlinkData_t *unlinkData, OCStackResult stackresult,
1288                                            IdxUnlinkRes_t idx)
1289 {
1290     if (NULL != unlinkData)
1291     {
1292         OIC_LOG_V(INFO, TAG, "Inside registerResultForUnlinkDevices unlinkData->numOfResults is %d",
1293                             unlinkData->numOfResults);
1294         OIC_LOG_V(INFO, TAG, "Stack result :: %d", stackresult);
1295
1296         OicUuid_t *pUuid = &unlinkData->unlinkRes[(unlinkData->numOfResults)].deviceId;
1297
1298         // Set result in the result array according to the position (devNum).
1299         if (idx != IDX_DB_UPDATE_RES)
1300         {
1301             memcpy(pUuid->id, unlinkData->unlinkDev[idx].doxm->deviceID.id, sizeof(pUuid->id));
1302         }
1303         else
1304         {   // When deivce ID is 000... this means it's the result of database update.
1305             memset(pUuid->id, 0, sizeof(pUuid->id));
1306         }
1307         unlinkData->unlinkRes[(unlinkData->numOfResults)].res = stackresult;
1308         ++(unlinkData->numOfResults);
1309         OIC_LOG (INFO, TAG, "Out registerResultForUnlinkDevices");
1310     }
1311 }
1312
1313 static OCStackResult SendDeleteCredentialRequest(void* ctx,
1314                                                  OCClientResponseHandler respHandler,
1315                                                  const OCProvisionDev_t* revokedDev,
1316                                                  const OCProvisionDev_t* destDev)
1317 {
1318     OIC_LOG(DEBUG, TAG, "IN SendDeleteCredentialRequest");
1319
1320     if (NULL == ctx || NULL == respHandler || NULL == revokedDev || NULL == destDev)
1321     {
1322         return OC_STACK_INVALID_PARAM;
1323     }
1324
1325     char *subID = NULL;
1326     OCStackResult ret = ConvertUuidToStr(&revokedDev->doxm->deviceID, &subID);
1327     if(OC_STACK_OK != ret)
1328     {
1329         OIC_LOG(ERROR, TAG, "SendDeleteCredentialRequest : Failed to canonical UUID encoding");
1330         return OC_STACK_ERROR;
1331     }
1332
1333     char addressEncoded[CA_MAX_URI_LENGTH] = {0};
1334     OCStackResult result = OCEncodeAddressForRFC6874(addressEncoded,
1335                                                      sizeof(addressEncoded),
1336                                                      destDev->endpoint.addr);
1337     if (OC_STACK_OK != result)
1338     {
1339         OIC_LOG_V(ERROR, TAG, "SendDeleteCredentialRequest : encoding error %d", result);
1340         return OC_STACK_ERROR;
1341     }
1342
1343     char reqBuf[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1344     int snRet = 0;
1345                     //coaps://0.0.0.0:5684/oic/sec/cred?subjectid=(Canonical ENCODED UUID)
1346     const char *srpUri = SRP_FORM_DELETE_CREDENTIAL;
1347 #ifdef __WITH_TLS__
1348     if(CA_ADAPTER_TCP == destDev->endpoint.adapter)
1349     {
1350         srpUri = SRP_FORM_DELETE_CREDENTIAL_TCP;
1351     }
1352 #endif
1353
1354     snRet = snprintf(reqBuf, sizeof(reqBuf), srpUri, addressEncoded,
1355                      destDev->securePort, OIC_RSRC_CRED_URI, OIC_JSON_SUBJECTID_NAME, subID);
1356     OICFree(subID);
1357     if (snRet < 0)
1358     {
1359         OIC_LOG_V(ERROR, TAG, "SendDeleteCredentialRequest : Error (snprintf) %d", snRet);
1360         return OC_STACK_ERROR;
1361     }
1362     else if ((size_t)snRet >= sizeof(reqBuf))
1363     {
1364         OIC_LOG_V(ERROR, TAG, "SendDeleteCredentialRequest : Truncated (snprintf) %d", snRet);
1365         return OC_STACK_ERROR;
1366     }
1367
1368     OCCallbackData cbData;
1369     memset(&cbData, 0, sizeof(cbData));
1370     cbData.context = ctx;
1371     cbData.cb = respHandler;
1372     cbData.cd = NULL;
1373     OIC_LOG_V(INFO, TAG, "URI: %s",reqBuf);
1374
1375     OIC_LOG(DEBUG, TAG, "Sending remove credential request to resource server");
1376
1377     ret = OCDoResource(NULL, OC_REST_DELETE, reqBuf,
1378                                      &destDev->endpoint, NULL,
1379                                      CT_ADAPTER_IP, OC_HIGH_QOS, &cbData, NULL, 0);
1380     if (OC_STACK_OK != ret)
1381     {
1382         OIC_LOG_V(ERROR, TAG, "SendDeleteCredentialRequest : Error in OCDoResource %d", ret);
1383     }
1384     OIC_LOG(DEBUG, TAG, "OUT SendDeleteCredentialRequest");
1385
1386     return ret;
1387 }
1388
1389 static OCStackResult SendDeleteACLRequest(void* ctx,
1390                                                  OCClientResponseHandler respHandler,
1391                                                  const OCProvisionDev_t* revokedDev,
1392                                                  const OCProvisionDev_t* destDev)
1393 {
1394     OIC_LOG(DEBUG, TAG, "IN SendDeleteACLRequest");
1395
1396     if (NULL == ctx || NULL == respHandler || NULL == revokedDev || NULL == destDev)
1397     {
1398         return OC_STACK_INVALID_PARAM;
1399     }
1400
1401     char *subID = NULL;
1402     OCStackResult ret = ConvertUuidToStr(&revokedDev->doxm->deviceID, &subID);
1403     if(OC_STACK_OK != ret)
1404     {
1405         OIC_LOG(ERROR, TAG, "SendDeleteACLRequest : Failed to canonical UUID encoding");
1406         return OC_STACK_ERROR;
1407     }
1408
1409     char addressEncoded[CA_MAX_URI_LENGTH] = {0};
1410     OCStackResult result = OCEncodeAddressForRFC6874(addressEncoded,
1411                                                      sizeof(addressEncoded),
1412                                                      destDev->endpoint.addr);
1413     if (OC_STACK_OK != result)
1414     {
1415         OIC_LOG_V(ERROR, TAG, "SendDeleteCredentialRequest : encoding error %d", result);
1416         return OC_STACK_ERROR;
1417     }
1418
1419     char reqBuf[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1420     int snRet = 0;
1421                     //coaps://0.0.0.0:5684/oic/sec/acl?subjectuuid=(Canonical ENCODED UUID)
1422     snRet = snprintf(reqBuf, sizeof(reqBuf), SRP_FORM_DELETE_CREDENTIAL, addressEncoded,
1423                      destDev->securePort, OIC_RSRC_ACL_URI, OIC_JSON_SUBJECTID_NAME, subID);
1424     OICFree(subID);
1425     if (snRet < 0)
1426     {
1427         OIC_LOG_V(ERROR, TAG, "SendDeleteACLRequest : Error (snprintf) %d", snRet);
1428         return OC_STACK_ERROR;
1429     }
1430     else if ((size_t)snRet >= sizeof(reqBuf))
1431     {
1432         OIC_LOG_V(ERROR, TAG, "SendDeleteACLRequest : Truncated (snprintf) %d", snRet);
1433         return OC_STACK_ERROR;
1434     }
1435
1436     OCCallbackData cbData;
1437     memset(&cbData, 0, sizeof(cbData));
1438     cbData.context = ctx;
1439     cbData.cb = respHandler;
1440     cbData.cd = NULL;
1441     OIC_LOG_V(INFO, TAG, "URI: %s",reqBuf);
1442
1443     OIC_LOG(DEBUG, TAG, "Sending remove ACL request to resource server");
1444
1445     ret = OCDoResource(NULL, OC_REST_DELETE, reqBuf,
1446                                      &destDev->endpoint, NULL,
1447                                      CT_ADAPTER_IP, OC_HIGH_QOS, &cbData, NULL, 0);
1448     if (OC_STACK_OK != ret)
1449     {
1450         OIC_LOG_V(ERROR, TAG, "SendDeleteACLRequest : Error in OCDoResource %d", ret);
1451     }
1452     OIC_LOG(DEBUG, TAG, "OUT SendDeleteACLRequest");
1453
1454     return ret;
1455 }
1456
1457 /**
1458  * Callback handler of unlink second device.
1459  *
1460  * @param[in] ctx             ctx value passed to callback from calling function.
1461  * @param[in] handle          handle to an invocation
1462  * @param[in] clientResponse  Response from queries to remote servers.
1463  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction and
1464  *          OC_STACK_KEEP_TRANSACTION to keep it.
1465  */
1466 static OCStackApplicationResult SRPUnlinkDevice2CB(void *unlinkCtx, OCDoHandle handle,
1467         OCClientResponse *clientResponse)
1468 {
1469     (void) handle;
1470     OIC_LOG(DEBUG, TAG, "IN SRPUnlinkDevice2CB");
1471     VERIFY_NOT_NULL_RETURN(TAG, unlinkCtx, ERROR, OC_STACK_DELETE_TRANSACTION);
1472     UnlinkData_t* unlinkData = (UnlinkData_t*)unlinkCtx;
1473
1474     if (clientResponse)
1475     {
1476         OIC_LOG(DEBUG, TAG, "Valid client response for device 2");
1477         registerResultForUnlinkDevices(unlinkData, clientResponse->result, IDX_SECOND_DEVICE_RES);
1478
1479         if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
1480         {
1481             OIC_LOG(DEBUG, TAG, "Credential of device2 revoked");
1482         }
1483         else
1484         {
1485             OIC_LOG(ERROR, TAG, "Unable to delete credential information from device 2");
1486             unlinkData->resultCallback(unlinkData->ctx,
1487                                        unlinkData->numOfResults, unlinkData->unlinkRes, true);
1488             goto error;
1489         }
1490     }
1491     else
1492     {
1493         registerResultForUnlinkDevices(unlinkData, OC_STACK_INVALID_REQUEST_HANDLE,
1494                                        IDX_SECOND_DEVICE_RES);
1495         unlinkData->resultCallback(unlinkData->ctx,
1496                                    unlinkData->numOfResults, unlinkData->unlinkRes, true);
1497         OIC_LOG(ERROR, TAG, "SRPUnlinkDevice2CB received Null clientResponse");
1498         goto error;
1499     }
1500
1501     //Update provisioning DB when succes case.
1502     if (OC_STACK_OK != PDMUnlinkDevices(&unlinkData->unlinkDev[0].doxm->deviceID,
1503                                        &unlinkData->unlinkDev[1].doxm->deviceID))
1504     {
1505         OIC_LOG(FATAL, TAG, "All requests are successfully done but update provisioning DB FAILED.");
1506         registerResultForUnlinkDevices(unlinkData, OC_STACK_INCONSISTENT_DB, IDX_DB_UPDATE_RES);
1507         unlinkData->resultCallback(unlinkData->ctx,
1508                                    unlinkData->numOfResults, unlinkData->unlinkRes, true);
1509         goto error;
1510     }
1511     unlinkData->resultCallback(unlinkData->ctx, unlinkData->numOfResults, unlinkData->unlinkRes,
1512                                false);
1513
1514 error:
1515     DeleteUnlinkData_t(unlinkData);
1516     OIC_LOG(DEBUG, TAG, "OUT SRPUnlinkDevice2CB");
1517     return OC_STACK_DELETE_TRANSACTION;
1518
1519 }
1520
1521 /**
1522  * Callback handler of unlink first device.
1523  *
1524  * @param[in] ctx             ctx value passed to callback from calling function.
1525  * @param[in] handle          handle to an invocation
1526  * @param[in] clientResponse  Response from queries to remote servers.
1527  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction and
1528  *          OC_STACK_KEEP_TRANSACTION to keep it.
1529  */
1530 static OCStackApplicationResult SRPUnlinkDevice1CB(void *unlinkCtx, OCDoHandle handle,
1531         OCClientResponse *clientResponse)
1532 {
1533     OIC_LOG_V(INFO, TAG, "Inside SRPUnlinkDevice1CB ");
1534     VERIFY_NOT_NULL_RETURN(TAG, unlinkCtx, ERROR, OC_STACK_DELETE_TRANSACTION);
1535     UnlinkData_t* unlinkData = (UnlinkData_t*)unlinkCtx;
1536     (void) handle;
1537
1538     if (clientResponse)
1539     {
1540         OIC_LOG(DEBUG, TAG, "Valid client response for device 1");
1541         registerResultForUnlinkDevices(unlinkData, clientResponse->result, IDX_FIRST_DEVICE_RES);
1542
1543         if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
1544         {
1545             OIC_LOG(DEBUG, TAG, "Credential of device 1 is revoked");
1546
1547             // Second revocation request to second device.
1548             OCStackResult res = SendDeleteCredentialRequest((void*)unlinkData, &SRPUnlinkDevice2CB,
1549                                                     &unlinkData->unlinkDev[0],
1550                                                     &unlinkData->unlinkDev[1] /*Dest*/);
1551             OIC_LOG_V(DEBUG, TAG, "Credential revocation request device 2, result :: %d",res);
1552             if (OC_STACK_OK != res)
1553             {
1554                  OIC_LOG(ERROR, TAG, "Error while sending revocation request for device 2");
1555                  registerResultForUnlinkDevices(unlinkData, OC_STACK_INVALID_REQUEST_HANDLE,
1556                                                 IDX_SECOND_DEVICE_RES);
1557                  unlinkData->resultCallback(unlinkData->ctx,
1558                                             unlinkData->numOfResults, unlinkData->unlinkRes, true);
1559                  goto error;
1560             }
1561             else
1562             {
1563                 OIC_LOG(DEBUG, TAG, "Request for credential revocation successfully sent");
1564                 return OC_STACK_DELETE_TRANSACTION;
1565             }
1566         }
1567         else
1568         {
1569             OIC_LOG(ERROR, TAG, "Unable to delete credential information from device 1");
1570
1571             unlinkData->resultCallback(unlinkData->ctx, unlinkData->numOfResults,
1572                                             unlinkData->unlinkRes, true);
1573             goto error;
1574         }
1575     }
1576     else
1577     {
1578         OIC_LOG(DEBUG, TAG, "Invalid response from server");
1579         registerResultForUnlinkDevices(unlinkData, OC_STACK_INVALID_REQUEST_HANDLE,
1580                                        IDX_FIRST_DEVICE_RES );
1581         unlinkData->resultCallback(unlinkData->ctx,
1582                                    unlinkData->numOfResults, unlinkData->unlinkRes,
1583                                    true);
1584         OIC_LOG(ERROR, TAG, "SRPUnlinkDevice1CB received Null clientResponse");
1585     }
1586
1587 error:
1588     OIC_LOG_V(INFO, TAG, "Out SRPUnlinkDevice1CB");
1589     DeleteUnlinkData_t(unlinkData);
1590     return OC_STACK_DELETE_TRANSACTION;
1591 }
1592
1593 /*
1594 * Function to unlink devices.
1595 * This function will remove the credential & relationship between the two devices.
1596 *
1597 * @param[in] ctx Application context would be returned in result callback
1598 * @param[in] pTargetDev1 first device information to be unlinked.
1599 * @param[in] pTargetDev2 second device information to be unlinked.
1600 * @param[in] resultCallback callback provided by API user, callback will be called when
1601 *            device unlink is finished.
1602  * @return  OC_STACK_OK in case of success and other value otherwise.
1603 */
1604 OCStackResult SRPUnlinkDevices(void* ctx,
1605                                const OCProvisionDev_t* pTargetDev1,
1606                                const OCProvisionDev_t* pTargetDev2,
1607                                OCProvisionResultCB resultCallback)
1608 {
1609     OIC_LOG(INFO, TAG, "IN SRPUnlinkDevices");
1610
1611     if (!pTargetDev1 || !pTargetDev2 || !pTargetDev1->doxm || !pTargetDev2->doxm)
1612     {
1613         OIC_LOG(INFO, TAG, "SRPUnlinkDevices : NULL parameters");
1614         return OC_STACK_INVALID_PARAM;
1615     }
1616     if (!resultCallback)
1617     {
1618         OIC_LOG(INFO, TAG, "SRPUnlinkDevices : NULL Callback");
1619         return OC_STACK_INVALID_CALLBACK;
1620     }
1621     if (0 == memcmp(&pTargetDev1->doxm->deviceID, &pTargetDev2->doxm->deviceID, sizeof(OicUuid_t)))
1622     {
1623         OIC_LOG(INFO, TAG, "SRPUnlinkDevices : Same device ID");
1624         return OC_STACK_INVALID_PARAM;
1625     }
1626
1627     OIC_LOG(INFO, TAG, "Unlinking following devices: ");
1628     PMPrintOCProvisionDev(pTargetDev1);
1629     PMPrintOCProvisionDev(pTargetDev2);
1630
1631     // Mark the link status stale
1632     OCStackResult res = PDMSetLinkStale(&pTargetDev1->doxm->deviceID, &pTargetDev2->doxm->deviceID);
1633     if (OC_STACK_OK != res)
1634     {
1635         OIC_LOG(FATAL, TAG, "unable to update DB. Try again.");
1636         return res;
1637     }
1638
1639     UnlinkData_t* unlinkData = (UnlinkData_t*)OICCalloc(1, sizeof(UnlinkData_t));
1640     VERIFY_NOT_NULL_RETURN(TAG, unlinkData, ERROR, OC_STACK_NO_MEMORY);
1641
1642     //Initialize unlink data
1643     unlinkData->ctx = ctx;
1644     unlinkData->unlinkDev = (OCProvisionDev_t*)OICCalloc(2, sizeof(OCProvisionDev_t));
1645     if (NULL == unlinkData->unlinkDev)
1646     {
1647         OIC_LOG(ERROR, TAG, "Memory allocation failed");
1648         res = OC_STACK_NO_MEMORY;
1649         goto error;
1650     }
1651
1652     unlinkData->unlinkRes = (OCProvisionResult_t*)OICCalloc(3, sizeof(OCProvisionResult_t));
1653     if (NULL == unlinkData->unlinkRes)
1654     {
1655         OIC_LOG(ERROR, TAG, "Memory allocation failed");
1656         res = OC_STACK_NO_MEMORY;
1657         goto error;
1658     }
1659
1660     memcpy(&unlinkData->unlinkDev[0], pTargetDev1, sizeof(OCProvisionDev_t));
1661     memcpy(&unlinkData->unlinkDev[1], pTargetDev2, sizeof(OCProvisionDev_t));
1662
1663     unlinkData->numOfResults = 0;
1664     unlinkData->resultCallback = resultCallback;
1665
1666     res = SendDeleteCredentialRequest((void*)unlinkData, &SRPUnlinkDevice1CB,
1667                                        &unlinkData->unlinkDev[1], &unlinkData->unlinkDev[0]);
1668     if (OC_STACK_OK != res)
1669     {
1670         OIC_LOG(ERROR, TAG, "SRPUnlinkDevices : SendDeleteCredentialRequest failed");
1671         goto error;
1672     }
1673
1674     return res;
1675
1676 error:
1677     OIC_LOG(INFO, TAG, "OUT SRPUnlinkDevices");
1678     DeleteUnlinkData_t(unlinkData);
1679     return res;
1680 }
1681
1682 static void DeleteRemoveData_t(RemoveData_t* pRemoveData)
1683 {
1684     if (pRemoveData)
1685     {
1686         OICFree(pRemoveData->revokeTargetDev);
1687         OCDeleteDiscoveredDevices(pRemoveData->linkedDevList);
1688         OICFree(pRemoveData->removeRes);
1689         OICFree(pRemoveData);
1690     }
1691 }
1692
1693 static void registerResultForRemoveDevice(RemoveData_t *removeData, OicUuid_t *pLinkedDevId,
1694                                           OCStackResult stackresult, bool hasError)
1695 {
1696     OIC_LOG_V(INFO, TAG, "Inside registerResultForRemoveDevice removeData->numOfResults is %" PRIuPTR,
1697                          removeData->numOfResults + 1);
1698     if (pLinkedDevId)
1699     {
1700         memcpy(removeData->removeRes[(removeData->numOfResults)].deviceId.id,
1701                &pLinkedDevId->id, sizeof(pLinkedDevId->id));
1702     }
1703     else
1704     {
1705         memset(removeData->removeRes[(removeData->numOfResults)].deviceId.id,
1706                0, sizeof(pLinkedDevId->id) );
1707     }
1708     removeData->removeRes[(removeData->numOfResults)].res = stackresult;
1709     removeData->hasError = hasError;
1710     ++(removeData->numOfResults);
1711
1712     // If we get suffcient result from linked devices, we have to call user callback and do free
1713     if (removeData->sizeOfResArray == removeData->numOfResults)
1714     {
1715         if(!removeData->hasError)
1716         {
1717             // Remove device info from prvisioning database
1718             if (OC_STACK_OK != PDMDeleteDevice(&removeData->revokeTargetDev->doxm->deviceID))
1719             {
1720                 OIC_LOG(ERROR, TAG, "ResultForRemoveDevice : Failed to remove device in PDM.");
1721                 removeData->hasError = true;
1722             }
1723         }
1724         removeData->resultCallback(removeData->ctx, removeData->numOfResults, removeData->removeRes,
1725                                    removeData->hasError);
1726         DeleteRemoveData_t(removeData);
1727     }
1728  }
1729
1730 static void registerResultForResetDevice(RemoveData_t *removeData, OicUuid_t *pLinkedDevId,
1731                                           OCStackResult stackresult, bool hasError)
1732 {
1733     OIC_LOG_V(INFO, TAG, "Inside registerResultForResetDevice removeData->numOfResults is %" PRIuPTR,
1734                          removeData->numOfResults + 1);
1735     if (pLinkedDevId)
1736     {
1737         memcpy(removeData->removeRes[(removeData->numOfResults)].deviceId.id,
1738                &pLinkedDevId->id, sizeof(pLinkedDevId->id));
1739     }
1740     else
1741     {
1742         memset(removeData->removeRes[(removeData->numOfResults)].deviceId.id,
1743                0, sizeof(pLinkedDevId->id) );
1744     }
1745     removeData->removeRes[(removeData->numOfResults)].res = stackresult;
1746     removeData->hasError = hasError;
1747     ++(removeData->numOfResults);
1748
1749     // If we get suffcient result from linked devices, we have to call user callback and do free
1750     if (removeData->sizeOfResArray == removeData->numOfResults)
1751     {
1752         removeData->resultCallback(removeData->ctx, removeData->numOfResults, removeData->removeRes,
1753                                    removeData->hasError);
1754         DeleteRemoveData_t(removeData);
1755     }
1756 }
1757
1758 /**
1759  * Callback handler of unlink first device.
1760  *
1761  * @param[in] ctx             ctx value passed to callback from calling function.
1762  * @param[in] handle          handle to an invocation
1763  * @param[in] clientResponse  Response from queries to remote servers.
1764  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
1765  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
1766  */
1767 static OCStackApplicationResult SRPRemoveDeviceCB(void *delDevCtx, OCDoHandle handle,
1768         OCClientResponse *clientResponse)
1769 {
1770     //Update the delete credential into delete device context
1771     //Save the deleted status in delDevCtx
1772     (void)handle;
1773     OIC_LOG_V(INFO, TAG, "Inside SRPRemoveDeviceCB.");
1774     VERIFY_NOT_NULL_RETURN(TAG, delDevCtx, ERROR, OC_STACK_DELETE_TRANSACTION);
1775     OCStackResult res = OC_STACK_ERROR;
1776
1777     RemoveData_t* removeData = (RemoveData_t*)delDevCtx;
1778
1779     if (clientResponse)
1780     {
1781         OicUuid_t revDevUuid = {.id={0}};
1782         if(UUID_LENGTH == clientResponse->identity.id_length)
1783         {
1784             memcpy(revDevUuid.id, clientResponse->identity.id, sizeof(revDevUuid.id));
1785             if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
1786             {
1787                 res = PDMUnlinkDevices(&removeData->revokeTargetDev->doxm->deviceID, &revDevUuid);
1788                 if (OC_STACK_OK != res)
1789                 {
1790                     OIC_LOG(ERROR, TAG, "PDMSetLinkStale() FAIL: PDB is an obsolete one.");
1791                            registerResultForRemoveDevice(removeData, &revDevUuid,
1792                            OC_STACK_INCONSISTENT_DB, true);
1793
1794                     return OC_STACK_DELETE_TRANSACTION;
1795                 }
1796
1797                 registerResultForRemoveDevice(removeData, &revDevUuid,
1798                                               OC_STACK_RESOURCE_DELETED, false);
1799             }
1800             else
1801             {
1802                 registerResultForRemoveDevice(removeData, &revDevUuid,
1803                                               clientResponse->result, true);
1804                 OIC_LOG(ERROR, TAG, "Unexpected result from DELETE credential request!");
1805             }
1806         }
1807         else
1808         {
1809             OIC_LOG_V(WARNING, TAG, "Incorrect length of device UUID was sent from %s:%d",
1810                      clientResponse->devAddr.addr, clientResponse->devAddr.port);
1811
1812             if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
1813             {
1814                 /**
1815                   * Since server's credential was deleted,
1816                   * register result as OC_STACK_INCONSISTENT_DB with NULL UUID.
1817                   */
1818                 OIC_LOG_V(ERROR, TAG, "But server's credential was deleted.");
1819                 registerResultForRemoveDevice(removeData, NULL, OC_STACK_INCONSISTENT_DB, true);
1820             }
1821             else
1822             {
1823                 registerResultForRemoveDevice(removeData, NULL, clientResponse->result, true);
1824             }
1825         }
1826     }
1827     else
1828     {
1829         registerResultForRemoveDevice(removeData, NULL, OC_STACK_ERROR, true);
1830         OIC_LOG(ERROR, TAG, "SRPRemoveDevices received Null clientResponse");
1831     }
1832
1833     return OC_STACK_DELETE_TRANSACTION;
1834 }
1835
1836 /**
1837  * Callback handler of reset device.
1838  *
1839  * @param[in] ctx             ctx value passed to callback from calling function.
1840  * @param[in] handle          handle to an invocation
1841  * @param[in] clientResponse  Response from queries to remote servers.
1842  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
1843  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
1844  */
1845 static OCStackApplicationResult SRPSyncDeviceCredCB(void *delDevCtx, OCDoHandle handle,
1846         OCClientResponse *clientResponse)
1847 {
1848     //Update the delete credential into delete device context
1849     //Save the deleted status in delDevCtx
1850     (void)handle;
1851     OIC_LOG_V(INFO, TAG, "Inside SRPSyncDeviceCredCB.");
1852     VERIFY_NOT_NULL_RETURN(TAG, delDevCtx, ERROR, OC_STACK_DELETE_TRANSACTION);
1853     OCStackResult res = OC_STACK_ERROR;
1854
1855     RemoveData_t* removeData = (RemoveData_t*)delDevCtx;
1856     OCProvisionDev_t * pTargetDev = PMCloneOCProvisionDev(removeData->revokeTargetDev);
1857     OCProvisionResultCB resultCallback = removeData->resultCallback;
1858     if (clientResponse)
1859     {
1860         OicUuid_t revDevUuid = {.id={0}};
1861         if(UUID_LENGTH == clientResponse->identity.id_length)
1862         {
1863             memcpy(revDevUuid.id, clientResponse->identity.id, sizeof(revDevUuid.id));
1864             if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
1865             {
1866                 res = PDMUnlinkDevices(&removeData->revokeTargetDev->doxm->deviceID, &revDevUuid);
1867                 if (OC_STACK_OK != res)
1868                 {
1869                     OIC_LOG(ERROR, TAG, "PDMSetLinkStale() FAIL: PDB is an obsolete one.");
1870                            registerResultForResetDevice(removeData, &revDevUuid,
1871                            OC_STACK_INCONSISTENT_DB, true);
1872
1873                     return OC_STACK_DELETE_TRANSACTION;
1874                 }
1875
1876                 registerResultForResetDevice(removeData, &revDevUuid,
1877                                               OC_STACK_RESOURCE_DELETED, false);
1878             }
1879             else
1880             {
1881                 registerResultForResetDevice(removeData, &revDevUuid,
1882                                               clientResponse->result, false);
1883                 OIC_LOG(ERROR, TAG, "Unexpected result from DELETE credential request!");
1884             }
1885         }
1886         else
1887         {
1888             OIC_LOG_V(WARNING, TAG, "Incorrect length of device UUID was sent from %s:%d",
1889                      clientResponse->devAddr.addr, clientResponse->devAddr.port);
1890
1891             if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
1892             {
1893                 /**
1894                   * Since server's credential was deleted,
1895                   * register result as OC_STACK_INCONSISTENT_DB with NULL UUID.
1896                   */
1897                 OIC_LOG_V(ERROR, TAG, "But server's credential was deleted.");
1898                 registerResultForResetDevice(removeData, NULL, OC_STACK_INCONSISTENT_DB, true);
1899             }
1900             else
1901             {
1902                 registerResultForResetDevice(removeData, NULL, clientResponse->result, true);
1903             }
1904         }
1905     }
1906     else
1907     {
1908         registerResultForResetDevice(removeData, NULL, OC_STACK_ERROR, true);
1909         OIC_LOG(ERROR, TAG, "SRPSyncDevice received Null clientResponse");
1910     }
1911
1912     SRPResetDevice(pTargetDev, resultCallback);
1913
1914     return OC_STACK_DELETE_TRANSACTION;
1915 }
1916
1917 /**
1918  * Callback handler of reset device sync-up
1919  *
1920  * @param[in] ctx             ctx value passed to callback from calling function.
1921  * @param[in] handle          handle to an invocation
1922  * @param[in] clientResponse  Response from queries to remote servers.
1923  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
1924  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
1925  */
1926 static OCStackApplicationResult SRPSyncDeviceACLCB(void *ctx, OCDoHandle UNUSED,
1927         OCClientResponse *clientResponse)
1928 {
1929     (void)ctx;
1930     (void)UNUSED;
1931     (void)clientResponse;
1932     return OC_STACK_DELETE_TRANSACTION;
1933 }
1934
1935 /**
1936  * Callback handler of device remote reset.
1937  *
1938  * @param[in] ctx             ctx value passed to callback from calling function.
1939  * @param[in] UNUSED          handle to an invocation
1940  * @param[in] clientResponse  Response from queries to remote servers.
1941  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
1942  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
1943  */
1944 static OCStackApplicationResult SRPResetDeviceCB(void *ctx, OCDoHandle UNUSED,
1945         OCClientResponse *clientResponse)
1946 {
1947     OIC_LOG(DEBUG, TAG, "IN SRPResetDeviceCB");
1948     (void)UNUSED;
1949     if(OC_STACK_OK == clientResponse->result)
1950     {
1951         OIC_LOG(DEBUG, TAG, "Change Target Device Pstat Cm SUCCEEDED");
1952     }
1953
1954     // Delete Cred and ACL related to the target device.
1955     const OicSecCred_t *cred = NULL;
1956     OCProvisionDev_t * pTargetDev = (OCProvisionDev_t *)ctx;
1957     cred = GetCredResourceData(&pTargetDev->doxm->deviceID);
1958     if (cred == NULL)
1959     {
1960         OIC_LOG(ERROR, TAG, "OCResetDevice : Failed to get credential of target device.");
1961         goto error;
1962     }
1963
1964     OCStackResult res = RemoveCredential(&cred->subject);
1965     if (res != OC_STACK_RESOURCE_DELETED && res != OC_STACK_NO_RESOURCE)
1966     {
1967         OIC_LOG(ERROR, TAG, "OCResetDevice : Failed to remove credential.");
1968         goto error;
1969     }
1970
1971     res = RemoveACE(&cred->subject, NULL);
1972     if (res != OC_STACK_RESOURCE_DELETED && res != OC_STACK_NO_RESOURCE)
1973     {
1974         OIC_LOG(ERROR, TAG, "OCResetDevice : Failed to remove ACL.");
1975         goto error;
1976     }
1977     if (OC_STACK_OK != PDMDeleteDevice(&pTargetDev->doxm->deviceID))
1978     {
1979         OIC_LOG(ERROR, TAG, "OCResetDevice : Failed to delete device from PDM");
1980     }
1981
1982     //Close the DTLS session of the reset device.
1983     CAEndpoint_t* endpoint = (CAEndpoint_t *)&clientResponse->devAddr;
1984     CAResult_t caResult = CAcloseSslSession(endpoint);
1985     if(CA_STATUS_OK != caResult)
1986     {
1987         OIC_LOG_V(WARNING, TAG, "OCResetDevice : Failed to close DTLS session : %d", caResult);
1988     }
1989
1990     /**
1991      * If there is no linked device, PM does not send any request.
1992      * So we should directly invoke the result callback to inform the result of OCResetDevice.
1993      */
1994     if(OC_STACK_NO_RESOURCE == res)
1995     {
1996         res = OC_STACK_OK;
1997     }
1998
1999 error:
2000     OICFree(pTargetDev);
2001     return OC_STACK_DELETE_TRANSACTION;
2002
2003 }
2004
2005 static OCStackResult GetListofDevToReqDeleteCred(const OCProvisionDev_t* pRevokeTargetDev,
2006                                                  const OCProvisionDev_t* pOwnedDevList,
2007                                                  OCUuidList_t* pLinkedUuidList,
2008                                                  OCProvisionDev_t** ppLinkedDevList,
2009                                                  size_t *numOfLinkedDev)
2010 {
2011     // pOwnedDevList could be NULL. It means no alived and owned device now.
2012     if (pRevokeTargetDev == NULL || pLinkedUuidList == NULL ||\
2013         ppLinkedDevList == NULL || numOfLinkedDev == NULL)
2014     {
2015         return OC_STACK_INVALID_PARAM;
2016     }
2017
2018     size_t cnt = 0;
2019     OCUuidList_t *curUuid = NULL, *tmpUuid = NULL;
2020     LL_FOREACH_SAFE(pLinkedUuidList, curUuid, tmpUuid)
2021     {
2022         // Mark the link status stale.
2023         OCStackResult res = PDMSetLinkStale(&curUuid->dev, &pRevokeTargetDev->doxm->deviceID);
2024         if (OC_STACK_OK != res)
2025         {
2026             OIC_LOG(FATAL, TAG, "PDMSetLinkStale() FAIL: PDB is an obsolete one.");
2027             return OC_STACK_INCONSISTENT_DB;
2028         }
2029
2030         if (pOwnedDevList)
2031         {
2032             // If this linked device is alive (power-on), add the deivce to the list.
2033             const OCProvisionDev_t *curDev = NULL;
2034             const OCProvisionDev_t *tmpDev = NULL;
2035             LL_FOREACH_SAFE(pOwnedDevList, curDev, tmpDev)
2036             {
2037                 if (memcmp(curDev->doxm->deviceID.id, curUuid->dev.id, sizeof(curUuid->dev.id)) == 0)
2038                 {
2039                     OCProvisionDev_t* targetDev = PMCloneOCProvisionDev(curDev);
2040                     if (NULL == targetDev)
2041                     {
2042                         OIC_LOG(ERROR, TAG, "SRPRemoveDevice : Cloning OCProvisionDev_t Failed.");
2043                         return OC_STACK_NO_MEMORY;
2044                     }
2045
2046                     LL_PREPEND(*ppLinkedDevList, targetDev);
2047                     cnt++;
2048                     break;
2049                 }
2050             }
2051         }
2052     }
2053     *numOfLinkedDev = cnt;
2054     return OC_STACK_OK;
2055 }
2056
2057 /*
2058 * Function to device revocation
2059 * This function will remove credential of target device from all devices in subnet.
2060 *
2061 * @param[in] ctx Application context would be returned in result callback
2062 * @param[in] waitTimeForOwnedDeviceDiscovery Maximum wait time for owned device discovery.(seconds)
2063 * @param[in] pTargetDev Device information to be revoked.
2064 * @param[in] resultCallback callback provided by API user, callback will be called when
2065 *            credential revocation is finished.
2066 * @return  OC_STACK_OK in case of success and other value otherwise.
2067 *          If OC_STACK_OK is returned, the caller of this API should wait for callback.
2068 *          OC_STACK_CONTINUE means operation is success but no request is need to be initiated.
2069 */
2070 OCStackResult SRPRemoveDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDiscovery,
2071                              const OCProvisionDev_t* pTargetDev, OCProvisionResultCB resultCallback)
2072 {
2073     OIC_LOG(INFO, TAG, "IN SRPRemoveDevice");
2074
2075     if (!pTargetDev  || 0 == waitTimeForOwnedDeviceDiscovery)
2076     {
2077         OIC_LOG(INFO, TAG, "SRPRemoveDevice : NULL parameters");
2078         return OC_STACK_INVALID_PARAM;
2079     }
2080     if (!resultCallback)
2081     {
2082         OIC_LOG(INFO, TAG, "SRPRemoveDevice : NULL Callback");
2083         return OC_STACK_INVALID_CALLBACK;
2084     }
2085
2086     // Declare variables in here to handle error cases with goto statement.
2087     OCProvisionDev_t* pOwnedDevList = NULL;
2088     OCProvisionDev_t* pLinkedDevList = NULL;
2089     RemoveData_t* removeData = NULL;
2090
2091     //1. Find all devices that has a credential of the revoked device
2092     OCUuidList_t* pLinkedUuidList = NULL;
2093     size_t numOfDevices = 0;
2094     OCStackResult res = OC_STACK_ERROR;
2095     res = PDMGetLinkedDevices(&pTargetDev->doxm->deviceID, &pLinkedUuidList, &numOfDevices);
2096     if (OC_STACK_OK != res)
2097     {
2098         OIC_LOG(ERROR, TAG, "SRPRemoveDevice : Failed to get linked devices information");
2099         return res;
2100     }
2101     // if there is no related device, we can skip further process.
2102     if (0 == numOfDevices)
2103     {
2104         OIC_LOG(DEBUG, TAG, "SRPRemoveDevice : No linked device found.");
2105         res = OC_STACK_CONTINUE;
2106         goto error;
2107     }
2108
2109     //2. Find owned device from the network
2110     res = PMDeviceDiscovery(waitTimeForOwnedDeviceDiscovery, true, &pOwnedDevList);
2111     if (OC_STACK_OK != res)
2112     {
2113         OIC_LOG(ERROR, TAG, "SRPRemoveDevice : Failed to PMDeviceDiscovery");
2114         goto error;
2115     }
2116
2117     //3. Make a list of devices to send DELETE credential request
2118     //   by comparing owned devices from provisioning database with mutlicast discovery result.
2119     size_t numOfLinkedDev = 0;
2120     res = GetListofDevToReqDeleteCred(pTargetDev, pOwnedDevList, pLinkedUuidList,
2121                                       &pLinkedDevList, &numOfLinkedDev);
2122     if (OC_STACK_OK != res)
2123     {
2124         OIC_LOG(ERROR, TAG, "SRPRemoveDevice : GetListofDevToReqDeleteCred() failed");
2125         goto error;
2126     }
2127     if (0 == numOfLinkedDev) // This case means, there is linked device but it's not alive now.
2128     {                       // So we don't have to send request message.
2129         OIC_LOG(DEBUG, TAG, "SRPRemoveDevice : No alived & linked device found.");
2130         res = OC_STACK_CONTINUE;
2131         goto error;
2132     }
2133
2134     // 4. Prepare RemoveData Context data.
2135     removeData = (RemoveData_t*)OICCalloc(1, sizeof(RemoveData_t));
2136     if (!removeData)
2137     {
2138         OIC_LOG(ERROR, TAG, "SRPRemoveDevices : Failed to allocate memory");
2139         res = OC_STACK_NO_MEMORY;
2140         goto error;
2141     }
2142
2143     removeData->revokeTargetDev = PMCloneOCProvisionDev(pTargetDev);
2144     if (!removeData->revokeTargetDev)
2145     {
2146         OIC_LOG(ERROR, TAG, "SRPRemoveDevices : PMCloneOCProvisionDev Failed");
2147         res = OC_STACK_NO_MEMORY;
2148         goto error;
2149     }
2150
2151     removeData->removeRes =
2152         (OCProvisionResult_t*)OICCalloc(numOfLinkedDev, sizeof(OCProvisionResult_t));
2153     if (!removeData->removeRes)
2154     {
2155         OIC_LOG(ERROR, TAG, "SRPRemoveDevices : Failed to allocate memory");
2156         res = OC_STACK_NO_MEMORY;
2157         goto error;
2158     }
2159
2160     removeData->ctx = ctx;
2161     removeData->linkedDevList = pLinkedDevList;
2162     removeData->resultCallback = resultCallback;
2163     removeData->numOfResults = 0;
2164     removeData->sizeOfResArray = numOfLinkedDev;
2165     removeData->hasError = false;
2166
2167     // 5. Send DELETE credential request to linked devices.
2168     OCProvisionDev_t *curDev = NULL, *tmpDev = NULL;
2169     OCStackResult totalRes = OC_STACK_ERROR;  /* variable for checking request is sent or not */
2170     LL_FOREACH_SAFE(pLinkedDevList, curDev, tmpDev)
2171     {
2172         res = SendDeleteCredentialRequest((void*)removeData, &SRPRemoveDeviceCB,
2173                                            removeData->revokeTargetDev, curDev);
2174         if (OC_STACK_OK != res)
2175         {
2176             OIC_LOG_V(ERROR, TAG, "SRPRemoveDevice : Fail to send the DELETE credential request to\
2177                      %s:%u", curDev->endpoint.addr, curDev->endpoint.port);
2178         }
2179         else
2180         {
2181             totalRes = OC_STACK_OK; // This means at least one request is successfully sent.
2182         }
2183     }
2184
2185     PDMDestoryOicUuidLinkList(pLinkedUuidList); //TODO: Modify API name to have unified convention.
2186     PMDeleteDeviceList(pOwnedDevList);
2187     OIC_LOG(INFO, TAG, "OUT SRPRemoveDevice");
2188
2189     return totalRes; // Caller of this API should wait callback if totalRes == OC_STACK_OK.
2190
2191 error:
2192     PDMDestoryOicUuidLinkList(pLinkedUuidList);
2193     PMDeleteDeviceList(pOwnedDevList);
2194     PMDeleteDeviceList(pLinkedDevList);
2195     if (removeData)
2196     {
2197         OICFree(removeData->revokeTargetDev);
2198         OICFree(removeData->removeRes);
2199         OICFree(removeData);
2200     }
2201     OIC_LOG(INFO, TAG, "OUT ERROR case SRPRemoveDevice");
2202     return res;
2203 }
2204
2205 /*
2206 * Function to device revocation
2207 * This function will remove credential of target device from all devices in subnet.
2208 *
2209 * @param[in] ctx Application context would be returned in result callback
2210 * @param[in] pOwnedDevList List of owned devices
2211 * @param[in] pTargetDev Device information to be revoked.
2212 * @param[in] resultCallback callback provided by API user, callback will be called when
2213 *            credential revocation is finished.
2214 * @return  OC_STACK_OK in case of success and other value otherwise.
2215 *          If OC_STACK_OK is returned, the caller of this API should wait for callback.
2216 *          OC_STACK_CONTINUE means operation is success but no request is need to be initiated.
2217 */
2218 OCStackResult SRPRemoveDeviceWithoutDiscovery(void* ctx, const OCProvisionDev_t* pOwnedDevList,
2219                              const OCProvisionDev_t* pTargetDev, OCProvisionResultCB resultCallback)
2220 {
2221     OIC_LOG(INFO, TAG, "IN SRPRemoveDeviceWithoutDiscovery");
2222
2223     if (!pOwnedDevList)
2224     {
2225         OIC_LOG(WARNING, TAG, "SRPRemoveDeviceWithoutDiscovery : Owned Device List is empty");
2226         return OC_STACK_CONTINUE;
2227     }
2228     if (!pTargetDev)
2229     {
2230         OIC_LOG(INFO, TAG, "SRPRemoveDeviceWithoutDiscovery : NULL parameters");
2231         return OC_STACK_INVALID_PARAM;
2232     }
2233     if (!resultCallback)
2234     {
2235         OIC_LOG(INFO, TAG, "SRPRemoveDeviceWithoutDiscovery : NULL Callback");
2236         return OC_STACK_INVALID_CALLBACK;
2237     }
2238
2239     // Declare variables in here to handle error cases with goto statement.
2240     OCProvisionDev_t* pLinkedDevList = NULL;
2241     RemoveData_t* removeData = NULL;
2242
2243     //1. Find all devices that has a credential of the revoked device
2244     OCUuidList_t* pLinkedUuidList = NULL;
2245     size_t numOfDevices = 0;
2246     OCStackResult res = OC_STACK_ERROR;
2247     res = PDMGetLinkedDevices(&pTargetDev->doxm->deviceID, &pLinkedUuidList, &numOfDevices);
2248     if (OC_STACK_OK != res)
2249     {
2250         OIC_LOG(WARNING, TAG, "SRPRemoveDeviceWithoutDiscovery : Failed to get linked devices information");
2251         return OC_STACK_CONTINUE;
2252     }
2253     // if there is no related device, we can skip further process.
2254     if (0 == numOfDevices)
2255     {
2256         OIC_LOG(WARNING, TAG, "SRPRemoveDeviceWithoutDiscovery : No linked device found.");
2257         return OC_STACK_CONTINUE;
2258     }
2259
2260     //2. Make a list of devices to send DELETE credential request
2261     //   by comparing owned devices from provisioning database with mutlicast discovery result.
2262     size_t numOfLinkedDev = 0;
2263     res = GetListofDevToReqDeleteCred(pTargetDev, pOwnedDevList, pLinkedUuidList,
2264                                       &pLinkedDevList, &numOfLinkedDev);
2265     if (OC_STACK_OK != res)
2266     {
2267         OIC_LOG(ERROR, TAG, "SRPRemoveDeviceWithoutDiscovery : GetListofDevToReqDeleteCred() failed");
2268         goto error;
2269     }
2270     if (0 == numOfLinkedDev) // This case means, there is linked device but it's not alive now.
2271     {                       // So we don't have to send request message.
2272         OIC_LOG(DEBUG, TAG, "SRPRemoveDeviceWithoutDiscovery : No alived & linked device found.");
2273         return OC_STACK_CONTINUE;
2274     }
2275
2276     // 3. Prepare RemoveData Context data.
2277     removeData = (RemoveData_t*)OICCalloc(1, sizeof(RemoveData_t));
2278     if (!removeData)
2279     {
2280         OIC_LOG(ERROR, TAG, "SRPRemoveDeviceWithoutDiscovery : Failed to allocate memory");
2281         res = OC_STACK_NO_MEMORY;
2282         goto error;
2283     }
2284
2285     removeData->revokeTargetDev = PMCloneOCProvisionDev(pTargetDev);
2286     if (!removeData->revokeTargetDev)
2287     {
2288         OIC_LOG(ERROR, TAG, "SRPRemoveDeviceWithoutDiscovery : PMCloneOCProvisionDev Failed");
2289         res = OC_STACK_NO_MEMORY;
2290         goto error;
2291     }
2292
2293     removeData->removeRes =
2294         (OCProvisionResult_t*)OICCalloc(numOfLinkedDev, sizeof(OCProvisionResult_t));
2295     if (!removeData->removeRes)
2296     {
2297         OIC_LOG(ERROR, TAG, "SRPRemoveDeviceWithoutDiscovery : Failed to allocate memory");
2298         res = OC_STACK_NO_MEMORY;
2299         goto error;
2300     }
2301
2302     removeData->ctx = ctx;
2303     removeData->linkedDevList = pLinkedDevList;
2304     removeData->resultCallback = resultCallback;
2305     removeData->numOfResults = 0;
2306     removeData->sizeOfResArray = numOfLinkedDev;
2307     removeData->hasError = false;
2308
2309     // 5. Send DELETE credential request to linked devices.
2310     OCProvisionDev_t *curDev = NULL, *tmpDev = NULL;
2311     OCStackResult totalRes = OC_STACK_ERROR;  /* variable for checking request is sent or not */
2312     LL_FOREACH_SAFE(pLinkedDevList, curDev, tmpDev)
2313     {
2314         res = SendDeleteCredentialRequest((void*)removeData, &SRPRemoveDeviceCB,
2315                                            removeData->revokeTargetDev, curDev);
2316         if (OC_STACK_OK != res)
2317         {
2318             OIC_LOG_V(ERROR, TAG, "SRPRemoveDeviceWithoutDiscovery : Fail to send the DELETE credential request to\
2319                      %s:%u", curDev->endpoint.addr, curDev->endpoint.port);
2320         }
2321         else
2322         {
2323             totalRes = OC_STACK_OK; // This means at least one request is successfully sent.
2324         }
2325     }
2326
2327     PDMDestoryOicUuidLinkList(pLinkedUuidList); //TODO: Modify API name to have unified convention.
2328     OIC_LOG(INFO, TAG, "OUT SRPRemoveDeviceWithoutDiscovery");
2329
2330     return totalRes; // Caller of this API should wait callback if totalRes == OC_STACK_OK.
2331
2332 error:
2333     PDMDestoryOicUuidLinkList(pLinkedUuidList);
2334     PMDeleteDeviceList(pLinkedDevList);
2335     if (removeData)
2336     {
2337         OICFree(removeData->revokeTargetDev);
2338         OICFree(removeData->removeRes);
2339         OICFree(removeData);
2340     }
2341     OIC_LOG(INFO, TAG, "OUT ERROR case SRPRemoveDeviceWithoutDiscovery");
2342     return res;
2343 }
2344
2345 /*
2346  * Function to sync-up credential and ACL of the target device.
2347  * This function will remove credential and ACL of target device from all devices in subnet.
2348  *
2349  * @param[in] ctx Application context would be returned in result callback
2350  * @param[in] waitTimeForOwnedDeviceDiscovery Maximum wait time for owned device discovery.(seconds)
2351  * @param[in] pTargetDev Device information to be revoked.
2352  * @param[in] resultCallback callback provided by API user, callback will be called when
2353  *            credential revocation is finished.
2354  *            when there is an error, this user callback is called immediately.
2355  * @return OC_STACK_OK in case of success and other value otherwise.
2356  *         If OC_STACK_OK is returned, the caller of this API should wait for callback.
2357  *         OC_STACK_CONTINUE means operation is success but no request is need to be initiated.
2358  */
2359 OCStackResult SRPSyncDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDiscovery,
2360                          const OCProvisionDev_t* pTargetDev, OCProvisionResultCB resultCallback)
2361 {
2362     OIC_LOG(INFO, TAG, "IN SRPSyncDevice");
2363     if (!pTargetDev  || 0 == waitTimeForOwnedDeviceDiscovery)
2364     {
2365         OIC_LOG(INFO, TAG, "SRPSyncDevice : NULL parameters");
2366         return OC_STACK_INVALID_PARAM;
2367     }
2368     if (!resultCallback)
2369     {
2370         OIC_LOG(INFO, TAG, "SRPSyncDevice : NULL Callback");
2371         return OC_STACK_INVALID_CALLBACK;
2372     }
2373
2374     // Declare variables in here to handle error cases with goto statement.
2375     OCProvisionDev_t* pOwnedDevList = NULL;
2376     OCProvisionDev_t* pLinkedDevList = NULL;
2377     RemoveData_t* removeData = NULL;
2378
2379     //1. Find all devices that has a credential of the revoked device
2380     OCUuidList_t* pLinkedUuidList = NULL;
2381     size_t numOfDevices = 0;
2382     OCStackResult res = OC_STACK_ERROR;
2383     res = PDMGetLinkedDevices(&pTargetDev->doxm->deviceID, &pLinkedUuidList, &numOfDevices);
2384     if (OC_STACK_OK != res)
2385     {
2386         OIC_LOG(ERROR, TAG, "SRPSyncDevice : Failed to get linked devices information");
2387         return res;
2388     }
2389     // if there is no related device, we can skip further process.
2390     if (0 == numOfDevices)
2391     {
2392         OIC_LOG(DEBUG, TAG, "SRPSyncDevice : No linked device found.");
2393         res = OC_STACK_CONTINUE;
2394         goto error;
2395     }
2396
2397     //2. Find owned device from the network
2398     res = PMDeviceDiscovery(waitTimeForOwnedDeviceDiscovery, true, &pOwnedDevList);
2399     if (OC_STACK_OK != res)
2400     {
2401         OIC_LOG(ERROR, TAG, "SRPSyncDevice : Failed to PMDeviceDiscovery");
2402         goto error;
2403     }
2404
2405     //3. Make a list of devices to send DELETE credential request
2406     //   by comparing owned devices from provisioning database with mutlicast discovery result.
2407     size_t numOfLinkedDev = 0;
2408     res = GetListofDevToReqDeleteCred(pTargetDev, pOwnedDevList, pLinkedUuidList,
2409                                       &pLinkedDevList, &numOfLinkedDev);
2410     if (OC_STACK_OK != res)
2411     {
2412         OIC_LOG(ERROR, TAG, "SRPSyncDevice : GetListofDevToReqDeleteCred() failed");
2413         goto error;
2414     }
2415     if (0 == numOfLinkedDev) // This case means, there is linked device but it's not alive now.
2416     {                       // So we don't have to send request message.
2417         OIC_LOG(DEBUG, TAG, "SRPSyncDevice : No alived & linked device found.");
2418         res = OC_STACK_CONTINUE;
2419         goto error;
2420     }
2421
2422     // 4. Prepare RemoveData Context data.
2423     removeData = (RemoveData_t*)OICCalloc(1, sizeof(RemoveData_t));
2424     if (!removeData)
2425     {
2426         OIC_LOG(ERROR, TAG, "SRPSyncDevice : Failed to allocate memory");
2427         res = OC_STACK_NO_MEMORY;
2428         goto error;
2429     }
2430
2431     removeData->revokeTargetDev = PMCloneOCProvisionDev(pTargetDev);
2432     if (!removeData->revokeTargetDev)
2433     {
2434         OIC_LOG(ERROR, TAG, "SRPSyncDevice : PMCloneOCProvisionDev Failed");
2435         res = OC_STACK_NO_MEMORY;
2436         goto error;
2437     }
2438
2439     removeData->removeRes =
2440         (OCProvisionResult_t*)OICCalloc(numOfLinkedDev, sizeof(OCProvisionResult_t));
2441     if (!removeData->removeRes)
2442     {
2443         OIC_LOG(ERROR, TAG, "SRPSyncDevice : Failed to allocate memory");
2444         res = OC_STACK_NO_MEMORY;
2445         goto error;
2446     }
2447
2448     removeData->ctx = ctx;
2449     removeData->linkedDevList = pLinkedDevList;
2450     removeData->resultCallback = resultCallback;
2451     removeData->numOfResults = 0;
2452     removeData->sizeOfResArray = numOfLinkedDev;
2453     removeData->hasError = false;
2454
2455     // 5. Send DELETE credential request to linked devices.
2456     OCProvisionDev_t *curDev = NULL, *tmpDev = NULL;
2457     OCStackResult totalRes = OC_STACK_ERROR;  /* variable for checking request is sent or not */
2458     LL_FOREACH_SAFE(pLinkedDevList, curDev, tmpDev)
2459     {
2460         res = SendDeleteACLRequest((void*)removeData, &SRPSyncDeviceACLCB,
2461                                            removeData->revokeTargetDev, curDev);
2462         if (OC_STACK_OK != res)
2463         {
2464             OIC_LOG_V(ERROR, TAG, "SRPSyncDevice : Fail to send the DELETE ACL request to\
2465                      %s:%u", curDev->endpoint.addr, curDev->endpoint.port);
2466             goto error;
2467         }
2468         res = SendDeleteCredentialRequest((void*)removeData, &SRPSyncDeviceCredCB,
2469                                            removeData->revokeTargetDev, curDev);
2470         if (OC_STACK_OK != res)
2471         {
2472             OIC_LOG_V(ERROR, TAG, "SRPSyncDevice : Fail to send the DELETE credential request to\
2473                      %s:%u", curDev->endpoint.addr, curDev->endpoint.port);
2474             totalRes = OC_STACK_ERROR;
2475         }
2476         else
2477         {
2478             totalRes = OC_STACK_OK; // This means at least one request is successfully sent.
2479         }
2480     }
2481
2482     PDMDestoryOicUuidLinkList(pLinkedUuidList); //TODO: Modify API name to have unified convention.
2483     PMDeleteDeviceList(pOwnedDevList);
2484     OIC_LOG(INFO, TAG, "OUT SRPSyncDevice");
2485
2486     return totalRes; // Caller of this API should wait callback if totalRes == OC_STACK_OK.
2487
2488 error:
2489     PDMDestoryOicUuidLinkList(pLinkedUuidList);
2490     PMDeleteDeviceList(pOwnedDevList);
2491     PMDeleteDeviceList(pLinkedDevList);
2492     if (removeData)
2493     {
2494         OICFree(removeData->revokeTargetDev);
2495         OICFree(removeData->removeRes);
2496         OICFree(removeData);
2497     }
2498     OIC_LOG(INFO, TAG, "OUT ERROR case SRPSyncDevice");
2499     return res;
2500 }
2501
2502 /*
2503  * Function for remote reset
2504  * This function will send pstat PUT message to the target device to initiate remote reset.
2505  *
2506  * @param[in] pTargetDev Device information to be revoked.
2507  * @param[in] resultCallback callback provided by API user, callback will be called when
2508  *            credential revocation is finished.
2509  *            when there is an error, this user callback is called immediately.
2510  * @return OC_STACK_OK in case of success and other value otherwise.
2511  *         If OC_STACK_OK is returned, the caller of this API should wait for callback.
2512  *         OC_STACK_CONTINUE means operation is success but no request is need to be initiated.
2513  */
2514 OCStackResult SRPResetDevice(const OCProvisionDev_t* pTargetDev,
2515         OCProvisionResultCB resultCallback)
2516 {
2517     OIC_LOG(INFO, TAG, "IN SRPResetDevice");
2518     if (!pTargetDev)
2519     {
2520         OIC_LOG(INFO, TAG, "SRPResetDevice : NULL parameters");
2521         return OC_STACK_INVALID_PARAM;
2522     }
2523     if (!resultCallback)
2524     {
2525         OIC_LOG(INFO, TAG, "SRPResetDevice : NULL Callback");
2526         return OC_STACK_INVALID_CALLBACK;
2527     }
2528
2529     OCStackResult res = OC_STACK_ERROR;
2530     OicSecPstat_t * pstat = (OicSecPstat_t *) OICCalloc(1, sizeof(OicSecPstat_t));
2531     if (!pstat)
2532     {
2533         OIC_LOG(ERROR, TAG, "Failed to allocate memory");
2534         return OC_STACK_NO_MEMORY;
2535     }
2536
2537     pstat->dos.state = DOS_RESET; // Note [IOT-2052] in OCF 1.0 this is the only
2538                                   // value that needs to be set to cause RESET
2539     pstat->cm = RESET;
2540     pstat->isOp = false;
2541     pstat->tm = TAKE_OWNER;
2542     pstat->om = (OicSecDpom_t)(SINGLE_SERVICE_CLIENT_DRIVEN); // the only mode IoTivity supports currently
2543     pstat->smLen = 1;
2544     pstat->sm = (OicSecDpom_t *) OICCalloc(pstat->smLen, sizeof(OicSecDpom_t));
2545     if (NULL == pstat->sm)
2546     {
2547         OIC_LOG(ERROR, TAG, "Failed to allocate memory");
2548         OICFree(pstat);
2549         return OC_STACK_NO_MEMORY;
2550     }
2551     pstat->sm[0] = (OicSecDpom_t)(SINGLE_SERVICE_CLIENT_DRIVEN); // the only mode IoTivity supports currently
2552
2553     OCSecurityPayload * secPayload = (OCSecurityPayload *) OICCalloc(1, sizeof(OCSecurityPayload));
2554     if (!secPayload)
2555     {
2556         OIC_LOG(ERROR, TAG, "Failed to allocate memory");
2557         res = OC_STACK_NO_MEMORY;
2558         goto error;
2559     }
2560     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
2561
2562     // Note [IOT-2052] all the POST payloads in the provisioningclient app
2563     // should be updated to use the Partial payload APIs for the SVRs, so they
2564     // do not include read-only Properties for the Server device current
2565     // state.
2566     bool propertiesToInclude[PSTAT_PROPERTY_COUNT];
2567     memset(propertiesToInclude, 0, sizeof(propertiesToInclude));
2568     propertiesToInclude[PSTAT_DOS] = true;
2569
2570     if (OC_STACK_OK != PstatToCBORPayloadPartial(pstat, &(secPayload->securityData),
2571                 &(secPayload->payloadSize), propertiesToInclude))
2572     {
2573         OCPayloadDestroy((OCPayload *) secPayload);
2574         OIC_LOG(ERROR, TAG, "Failed to PstatToCBORPayload");
2575         res = OC_STACK_NO_MEMORY;
2576         goto error;
2577     }
2578     OIC_LOG(DEBUG, TAG, "Created payload for pstat set");
2579     OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
2580
2581     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
2582     if (!PMGenerateQuery(true,
2583                 pTargetDev->endpoint.addr,
2584                 pTargetDev->securePort,
2585                 pTargetDev->connType,
2586                 query, sizeof(query), OIC_RSRC_PSTAT_URI))
2587     {
2588         OIC_LOG(ERROR, TAG, "SRPResetDevice : Failed to generate query");
2589         OCPayloadDestroy((OCPayload *) secPayload);
2590         res = OC_STACK_ERROR;
2591         goto error;
2592     }
2593     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
2594
2595     OCCallbackData cbData = { .context = NULL, .cb = NULL, .cd = NULL };
2596     OCMethod method = OC_REST_POST;
2597     OCDoHandle handle = NULL;
2598     OCProvisionDev_t * targetDev = PMCloneOCProvisionDev(pTargetDev);
2599     if (NULL == targetDev)
2600     {
2601         OIC_LOG(ERROR, TAG, "target dev is null");
2602         res = OC_STACK_ERROR;
2603         goto error;
2604     }
2605     cbData.cb = &SRPResetDeviceCB;
2606     cbData.context = (void *) targetDev;
2607     cbData.cd = NULL;
2608     OIC_LOG(DEBUG, TAG, "Sending PSTAT info to resource server");
2609     res = OCDoResource(&handle, method, query,
2610             &targetDev->endpoint, (OCPayload *)secPayload,
2611             targetDev->connType, OC_LOW_QOS, &cbData, NULL, 0);\
2612     if (OC_STACK_OK != res)
2613     {
2614         OIC_LOG(ERROR, TAG, "OCStack resource error");
2615     }
2616
2617 error:
2618     OICFree(pstat->sm);
2619     OICFree(pstat);
2620     OIC_LOG(INFO, TAG, "OUT SRPResetDevice");
2621     return res;
2622 }
2623
2624 /**
2625  * Internal Function to store results in result array during GetCredResourceCB.
2626  */
2627 static void registerResultForGetCredResourceCB(GetSecData_t *GetSecData,
2628                                              OCStackResult stackresult)
2629 {
2630    OIC_LOG_V(INFO, TAG, "Inside registerResultForGetCredResourceCB "
2631            "GetSecData->numOfResults is %d", GetSecData->numOfResults);
2632    memcpy(GetSecData->resArr[(GetSecData->numOfResults)].deviceId.id,
2633           GetSecData->deviceInfo->doxm->deviceID.id, UUID_LENGTH);
2634    GetSecData->resArr[(GetSecData->numOfResults)].res = stackresult;
2635    ++(GetSecData->numOfResults);
2636 }
2637
2638 /**
2639  * Callback handler of SRPGetCredResource.
2640  *
2641  * @param[in] ctx             ctx value passed to callback from calling function.
2642  * @param[in] UNUSED          handle to an invocation
2643  * @param[in] clientResponse  Response from queries to remote servers.
2644  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
2645  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
2646  */
2647 static OCStackApplicationResult SRPGetCredResourceCB(void *ctx, OCDoHandle UNUSED,
2648                                                   OCClientResponse *clientResponse)
2649 {
2650     OIC_LOG_V(INFO, TAG, "Inside SRPGetCredResourceCB.");
2651     (void)UNUSED;
2652     VERIFY_NOT_NULL_RETURN(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
2653     GetSecData_t *GetSecData = (GetSecData_t*)ctx;
2654     OCProvisionResultCB resultCallback = GetSecData->resultCallback;
2655
2656     if (clientResponse)
2657     {
2658         if(OC_STACK_OK == clientResponse->result)
2659         {
2660             uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData;
2661             size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
2662
2663             OIC_LOG_BUFFER(DEBUG, TAG, payload, size);
2664             (void)size;
2665             (void)payload;
2666
2667             registerResultForGetCredResourceCB(GetSecData, OC_STACK_OK);
2668             ((OCProvisionResultCB)(resultCallback))(GetSecData->ctx, GetSecData->numOfResults,
2669                                                     GetSecData->resArr,
2670                                                     false);
2671              OICFree(GetSecData->resArr);
2672              OICFree(GetSecData);
2673
2674             return OC_STACK_DELETE_TRANSACTION;
2675         }
2676     }
2677     registerResultForGetCredResourceCB(GetSecData, OC_STACK_OK);
2678     ((OCProvisionResultCB)(resultCallback))(GetSecData->ctx, GetSecData->numOfResults,
2679                                             GetSecData->resArr,
2680                                             false);
2681     OIC_LOG_V(ERROR, TAG, "SRPGetCredResourceCB received Null clientResponse");
2682     OICFree(GetSecData->resArr);
2683     OICFree(GetSecData);
2684
2685     return OC_STACK_DELETE_TRANSACTION;
2686 }
2687
2688 OCStackResult SRPGetCredResource(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
2689         OCProvisionResultCB resultCallback)
2690 {
2691     VERIFY_NOT_NULL_RETURN(TAG, selectedDeviceInfo, ERROR,  OC_STACK_INVALID_PARAM);
2692     VERIFY_NOT_NULL_RETURN(TAG, resultCallback, ERROR,  OC_STACK_INVALID_CALLBACK);
2693
2694     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
2695     if(!PMGenerateQuery(true,
2696                         selectedDeviceInfo->endpoint.addr,
2697                         selectedDeviceInfo->securePort,
2698                         selectedDeviceInfo->connType,
2699                         query, sizeof(query), OIC_RSRC_CRED_URI))
2700     {
2701         OIC_LOG(ERROR, TAG, "SRPGetCredResource : Failed to generate query");
2702         return OC_STACK_ERROR;
2703     }
2704     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
2705
2706     OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};
2707     cbData.cb = &SRPGetCredResourceCB;
2708     GetSecData_t* GetSecData = (GetSecData_t*)OICCalloc(1, sizeof(GetSecData_t));
2709     if (NULL == GetSecData)
2710     {
2711         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
2712         return OC_STACK_NO_MEMORY;
2713     }
2714     GetSecData->deviceInfo = selectedDeviceInfo;
2715     GetSecData->resultCallback = resultCallback;
2716     GetSecData->numOfResults=0;
2717     GetSecData->ctx = ctx;
2718
2719     int noOfRiCalls = 1;
2720     GetSecData->resArr = (OCProvisionResult_t*)OICCalloc(noOfRiCalls, sizeof(OCProvisionResult_t));
2721     if (NULL == GetSecData->resArr)
2722     {
2723         OICFree(GetSecData);
2724         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
2725         return OC_STACK_NO_MEMORY;
2726     }
2727     cbData.context = (void *)GetSecData;
2728     cbData.cd = NULL;
2729     OCMethod method = OC_REST_GET;
2730     OCDoHandle handle = NULL;
2731     OIC_LOG(DEBUG, TAG, "Sending Get Cred to  resource server");
2732     OCStackResult ret = OCDoResource(&handle, method, query, NULL, NULL,
2733             selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
2734     if (OC_STACK_OK != ret)
2735     {
2736         OIC_LOG(ERROR, TAG, "OCStack resource error");
2737         OICFree(GetSecData->resArr);
2738         OICFree(GetSecData);
2739     }
2740     VERIFY_SUCCESS_RETURN(TAG, (OC_STACK_OK == ret), ERROR, OC_STACK_ERROR);
2741     OIC_LOG(DEBUG, TAG, "OUT SRPGetCredResource");
2742
2743     return OC_STACK_OK;
2744 }
2745
2746 /**
2747  * Internal Function to store results in result array during GetACLResourceCB.
2748  */
2749 static void registerResultForGetACLResourceCB(GetSecData_t *GetSecData,
2750                                              OCStackResult stackresult)
2751 {
2752    OIC_LOG_V(INFO, TAG, "Inside registerResultForGetACLResourceCB "
2753            "GetSecData->numOfResults is %d", GetSecData->numOfResults);
2754    memcpy(GetSecData->resArr[(GetSecData->numOfResults)].deviceId.id,
2755           GetSecData->deviceInfo->doxm->deviceID.id, UUID_LENGTH);
2756    GetSecData->resArr[(GetSecData->numOfResults)].res = stackresult;
2757    ++(GetSecData->numOfResults);
2758 }
2759
2760 /**
2761  * Callback handler of SRPGetACLResource.
2762  *
2763  * @param[in] ctx             ctx value passed to callback from calling function.
2764  * @param[in] UNUSED          handle to an invocation
2765  * @param[in] clientResponse  Response from queries to remote servers.
2766  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
2767  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
2768  */
2769 static OCStackApplicationResult SRPGetACLResourceCB(void *ctx, OCDoHandle UNUSED,
2770                                                   OCClientResponse *clientResponse)
2771 {
2772     OIC_LOG_V(INFO, TAG, "Inside SRPGetACLResourceCB.");
2773     (void)UNUSED;
2774     VERIFY_NOT_NULL_RETURN(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
2775     GetSecData_t *GetSecData = (GetSecData_t*)ctx;
2776     OCProvisionResultCB resultCallback = GetSecData->resultCallback;
2777
2778     if (clientResponse)
2779     {
2780         if(OC_STACK_OK == clientResponse->result)
2781         {
2782             uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData;
2783             size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
2784
2785             OIC_LOG_BUFFER(DEBUG, TAG, payload, size);
2786             (void)payload;
2787             (void)size;
2788
2789             registerResultForGetACLResourceCB(GetSecData, OC_STACK_OK);
2790             ((OCProvisionResultCB)(resultCallback))(GetSecData->ctx, GetSecData->numOfResults,
2791                                                     GetSecData->resArr,
2792                                                     false);
2793              OICFree(GetSecData->resArr);
2794              OICFree(GetSecData);
2795
2796             return OC_STACK_DELETE_TRANSACTION;
2797         }
2798     }
2799     registerResultForGetACLResourceCB(GetSecData, OC_STACK_OK);
2800     ((OCProvisionResultCB)(resultCallback))(GetSecData->ctx, GetSecData->numOfResults,
2801                                             GetSecData->resArr,
2802                                             false);
2803     OIC_LOG_V(ERROR, TAG, "SRPGetACLResourceCB received Null clientResponse");
2804     OICFree(GetSecData->resArr);
2805     OICFree(GetSecData);
2806
2807     return OC_STACK_DELETE_TRANSACTION;
2808 }
2809
2810 OCStackResult SRPGetACLResource(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
2811         OicSecAclVersion_t aclVersion, OCProvisionResultCB resultCallback)
2812 {
2813     VERIFY_NOT_NULL_RETURN(TAG, selectedDeviceInfo, ERROR,  OC_STACK_INVALID_PARAM);
2814     VERIFY_NOT_NULL_RETURN(TAG, resultCallback, ERROR,  OC_STACK_INVALID_CALLBACK);
2815
2816     const char *uri = NULL;
2817
2818     switch (aclVersion)
2819     {
2820     case OIC_SEC_ACL_V1:
2821         uri = OIC_RSRC_ACL_URI;
2822         break;
2823     case OIC_SEC_ACL_V2:
2824         uri = OIC_RSRC_ACL2_URI;
2825         break;
2826     default:
2827         return OC_STACK_INVALID_PARAM;
2828     }
2829
2830     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
2831     if(!PMGenerateQuery(true,
2832                         selectedDeviceInfo->endpoint.addr,
2833                         selectedDeviceInfo->securePort,
2834                         selectedDeviceInfo->connType,
2835                         query, sizeof(query), uri))
2836     {
2837         OIC_LOG(ERROR, TAG, "SRPGetACLResource : Failed to generate query");
2838         return OC_STACK_ERROR;
2839     }
2840     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
2841
2842     OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};
2843     cbData.cb = &SRPGetACLResourceCB;
2844     GetSecData_t* GetSecData = (GetSecData_t*)OICCalloc(1, sizeof(GetSecData_t));
2845     if (NULL == GetSecData)
2846     {
2847         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
2848         return OC_STACK_NO_MEMORY;
2849     }
2850     GetSecData->deviceInfo = selectedDeviceInfo;
2851     GetSecData->resultCallback = resultCallback;
2852     GetSecData->numOfResults=0;
2853     GetSecData->ctx = ctx;
2854
2855     int noOfRiCalls = 1;
2856     GetSecData->resArr = (OCProvisionResult_t*)OICCalloc(noOfRiCalls, sizeof(OCProvisionResult_t));
2857     if (NULL == GetSecData->resArr)
2858     {
2859         OICFree(GetSecData);
2860         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
2861         return OC_STACK_NO_MEMORY;
2862     }
2863     cbData.context = (void *)GetSecData;
2864     cbData.cd = NULL;
2865     OCMethod method = OC_REST_GET;
2866     OCDoHandle handle = NULL;
2867     OIC_LOG(DEBUG, TAG, "Sending Get ACL to resource server");
2868     OCStackResult ret = OCDoResource(&handle, method, query, NULL, NULL,
2869             selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
2870     if (OC_STACK_OK != ret)
2871     {
2872         OIC_LOG(ERROR, TAG, "OCStack resource error");
2873         OICFree(GetSecData->resArr);
2874         OICFree(GetSecData);
2875     }
2876     VERIFY_SUCCESS_RETURN(TAG, (OC_STACK_OK == ret), ERROR, OC_STACK_ERROR);
2877     OIC_LOG(DEBUG, TAG, "OUT SRPGetACLResource");
2878
2879     return OC_STACK_OK;
2880 }
2881
2882 /**
2883  * Internal Function to store results in result array during GetCSRResourceCB.
2884  */
2885 static void registerResultForGetCSRResourceCB(GetCsrData_t *getCsrData,
2886                                              OCStackResult stackresult,
2887                                              const uint8_t *payload,
2888                                              size_t payloadSize)
2889 {
2890     /* SRPGetCSRResource allocates the memory for getCsrData. When it calls this callback,
2891      * numOfResults points to the current entry we're filling out. Later when this structure
2892      * gets returned to the caller, that's when it actually reflects the number of
2893      * results returned.
2894      */
2895     OCPMGetCsrResult_t* currentEntry = &getCsrData->resArr[getCsrData->numOfResults];
2896     OIC_LOG_V(INFO, TAG, "Inside registerResultForGetCSRResourceCB "
2897         "getCsrData->numOfResults is %d\n", getCsrData->numOfResults);
2898     memcpy(currentEntry->deviceId.id,
2899         getCsrData->deviceInfo->doxm->deviceID.id, UUID_LENGTH);
2900     currentEntry->res = stackresult;
2901
2902     if (OC_STACK_OK == stackresult)
2903     {
2904         OCStackResult res = CBORPayloadToCSR(payload, payloadSize,
2905             &currentEntry->csr,
2906             &currentEntry->csrLen,
2907             &currentEntry->encoding);
2908         if (OC_STACK_OK != res)
2909         {
2910             currentEntry->res = res;
2911             currentEntry->csr = NULL;
2912             currentEntry->csrLen = 0;
2913             currentEntry->encoding = OIC_ENCODING_UNKNOW;
2914         }
2915     }
2916
2917     ++(getCsrData->numOfResults);
2918 }
2919
2920 /**
2921  * Callback handler of SRPGetCSRResource.
2922  *
2923  * @param[in] ctx             ctx value passed to callback from calling function.
2924  * @param[in] UNUSED          handle to an invocation
2925  * @param[in] clientResponse  Response from queries to remote servers.
2926  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
2927  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
2928  */
2929 static OCStackApplicationResult SRPGetCSRResourceCB(void *ctx, OCDoHandle UNUSED,
2930     OCClientResponse *clientResponse)
2931 {
2932     size_t i = 0;
2933     OIC_LOG_V(INFO, TAG, "IN %s", __func__);
2934     OC_UNUSED(UNUSED);
2935     VERIFY_NOT_NULL_RETURN(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
2936     GetCsrData_t *getCsrData = (GetCsrData_t*)ctx;
2937     OCGetCSRResultCB resultCallback = getCsrData->resultCallback;
2938
2939     if (clientResponse)
2940     {
2941         if (OC_STACK_OK == clientResponse->result)
2942         {
2943             uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData;
2944             size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
2945
2946             OIC_LOG_BUFFER(DEBUG, TAG, payload, size);
2947
2948             registerResultForGetCSRResourceCB(getCsrData, OC_STACK_OK, payload, size);
2949         }
2950     }
2951     else
2952     {
2953         registerResultForGetCSRResourceCB(getCsrData, OC_STACK_ERROR, NULL, 0);
2954     }
2955
2956     ((OCGetCSRResultCB)(resultCallback))(getCsrData->ctx, getCsrData->numOfResults,
2957         getCsrData->resArr,
2958         false);
2959     OIC_LOG_V(ERROR, TAG, "%s: received Null clientResponse", __func__);
2960     for (i = 0; i < getCsrData->numOfResults; i++)
2961     {
2962         OICFree(getCsrData->resArr[i].csr);
2963     }
2964     OICFree(getCsrData->resArr);
2965     OICFree(getCsrData);
2966     OIC_LOG_V(INFO, TAG, "OUT %s", __func__);
2967
2968     return OC_STACK_DELETE_TRANSACTION;
2969 }
2970
2971 OCStackResult SRPGetCSRResource(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
2972         OCGetCSRResultCB resultCallback)
2973 {
2974     VERIFY_NOT_NULL_RETURN(TAG, selectedDeviceInfo, ERROR,  OC_STACK_INVALID_PARAM);
2975     VERIFY_NOT_NULL_RETURN(TAG, resultCallback, ERROR,  OC_STACK_INVALID_CALLBACK);
2976
2977     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
2978     if (!PMGenerateQuery(true,
2979                         selectedDeviceInfo->endpoint.addr,
2980                         selectedDeviceInfo->securePort,
2981                         selectedDeviceInfo->connType,
2982                         query, sizeof(query), OIC_RSRC_CSR_URI))
2983     {
2984         OIC_LOG(ERROR, TAG, "SRPGetCSRResource : Failed to generate query");
2985         return OC_STACK_ERROR;
2986     }
2987     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
2988
2989     OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};
2990     cbData.cb = &SRPGetCSRResourceCB;
2991     GetCsrData_t* getCsrData = (GetCsrData_t*)OICCalloc(1, sizeof(GetCsrData_t));
2992     if (NULL == getCsrData)
2993     {
2994         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
2995         return OC_STACK_NO_MEMORY;
2996     }
2997     getCsrData->deviceInfo = selectedDeviceInfo;
2998     getCsrData->resultCallback = resultCallback;
2999     getCsrData->numOfResults=0;
3000     getCsrData->ctx = ctx;
3001
3002     int noOfRiCalls = 1;
3003     getCsrData->resArr = (OCPMGetCsrResult_t*)OICCalloc(noOfRiCalls, sizeof(OCPMGetCsrResult_t));
3004     if (NULL == getCsrData->resArr)
3005     {
3006         OICFree(getCsrData);
3007         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
3008         return OC_STACK_NO_MEMORY;
3009     }
3010     cbData.context = (void *)getCsrData;
3011     OCMethod method = OC_REST_GET;
3012     OCDoHandle handle = NULL;
3013     OIC_LOG(DEBUG, TAG, "Sending Get CSR to resource server");
3014     OCStackResult ret = OCDoResource(&handle, method, query, NULL, NULL,
3015             selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
3016     if (OC_STACK_OK != ret)
3017     {
3018         OIC_LOG(ERROR, TAG, "OCStack resource error");
3019         OICFree(getCsrData->resArr);
3020         OICFree(getCsrData);
3021     }
3022     OIC_LOG(DEBUG, TAG, "OUT SRPGetCSRResource");
3023
3024     return ret;
3025 }
3026
3027 /**
3028  * Internal Function to store results in result array during GetRolesResourceCB.
3029  */
3030 static void registerResultForGetRolesResourceCB(GetRolesData_t *getRolesData,
3031                                                 OCStackResult stackresult,
3032                                                 const uint8_t *payload,
3033                                                 size_t payloadSize)
3034 {
3035     /* SRPGetRolesResource allocates the memory for getRolesData. When it calls this callback,
3036      * numOfResults points to the current entry we're filling out. Later when this structure
3037      * gets returned to the caller, that's when it actually reflects the number of
3038      * results returned.
3039      */
3040     OCPMGetRolesResult_t* currentEntry = &getRolesData->resArr[getRolesData->numOfResults];
3041     OIC_LOG_V(INFO, TAG, "Inside registerResultForGetCSRResourceCB "
3042         "getRolesData->numOfResults is %d\n", getRolesData->numOfResults);
3043     memcpy(currentEntry->deviceId.id,
3044         getRolesData->deviceInfo->doxm->deviceID.id, UUID_LENGTH);
3045     currentEntry->res = stackresult;
3046     currentEntry->chainsLength = 0;
3047
3048     if (OC_STACK_OK == stackresult)
3049     {
3050         RoleCertChain_t *chains = NULL;
3051         OCStackResult res = CBORPayloadToRoles(payload, payloadSize, &chains);
3052         if (OC_STACK_OK != res)
3053         {
3054             currentEntry->res = res;
3055             currentEntry->chains = NULL;
3056         }
3057         else
3058         {
3059             RoleCertChain_t *curr = NULL;
3060             for (curr = chains; NULL != curr; curr = curr->next)
3061             {
3062                 currentEntry->chainsLength++;
3063             }
3064             currentEntry->chains = (OCPMRoleCertChain_t *)OICCalloc(currentEntry->chainsLength, sizeof(OCPMRoleCertChain_t));
3065             if (NULL == currentEntry->chains)
3066             {
3067                 OIC_LOG(ERROR, TAG, "No memory allocating role chains");
3068                 currentEntry->chainsLength = 0;
3069                 currentEntry->res = OC_STACK_NO_MEMORY;
3070             }
3071             else
3072             {
3073                 size_t i;
3074                 for (i = 0, curr = chains; NULL != curr; curr = curr->next, i++)
3075                 {
3076                     currentEntry->chains[i].credId = curr->credId;
3077                     /* Take ownership of the buffers from certificate and optData, rather than copy. */
3078                     currentEntry->chains[i].certificate = curr->certificate;
3079                     currentEntry->chains[i].optData = curr->optData;
3080
3081                     curr->certificate.data = NULL;
3082                     curr->certificate.len = 0;
3083                     curr->optData.data = NULL;
3084                     curr->optData.len = 0;
3085                 }
3086             }
3087             FreeRoleCertChainList(chains);
3088         }
3089     }
3090
3091     ++(getRolesData->numOfResults);
3092 }
3093
3094 /**
3095  * Callback handler of SRPGetRolesResource.
3096  *
3097  * @param[in] ctx             ctx value passed to callback from calling function.
3098  * @param[in] UNUSED          handle to an invocation
3099  * @param[in] clientResponse  Response from queries to remote servers.
3100  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
3101  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
3102  */
3103 static OCStackApplicationResult SRPGetRolesResourceCB(void *ctx, OCDoHandle handle,
3104                                                       OCClientResponse *clientResponse)
3105 {
3106     OIC_LOG(INFO, TAG, "Inside SRPGetRolesResourceCB.");
3107     OC_UNUSED(handle);
3108     VERIFY_NOT_NULL_RETURN(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
3109     GetRolesData_t *getRolesData = (GetRolesData_t*)ctx;
3110     OCGetRolesResultCB resultCallback = getRolesData->resultCallback;
3111
3112     if (clientResponse)
3113     {
3114         if (OC_STACK_OK == clientResponse->result)
3115         {
3116             uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData;
3117             size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
3118
3119             OIC_LOG_BUFFER(DEBUG, TAG, payload, size);
3120
3121             registerResultForGetRolesResourceCB(getRolesData, OC_STACK_OK, payload, size);
3122         }
3123     }
3124     else
3125     {
3126         OIC_LOG(ERROR, TAG, "SRPGetRolesResourceCB received Null clientResponse");
3127         registerResultForGetRolesResourceCB(getRolesData, OC_STACK_ERROR, NULL, 0);
3128     }
3129
3130     resultCallback(getRolesData->ctx, getRolesData->numOfResults,
3131                    getRolesData->resArr,
3132                    false);
3133     for (size_t i = 0; i < getRolesData->numOfResults; i++)
3134     {
3135         /* We took ownership of certificate.data and optData.data, so we must free them.
3136          * These are allocated internally by tinycbor, which uses malloc and free, so we call
3137          * free directly for those.
3138          */
3139         for (size_t j = 0; j < getRolesData->resArr[i].chainsLength; j++)
3140         {
3141             free(getRolesData->resArr[i].chains[j].certificate.data);
3142             free(getRolesData->resArr[i].chains[j].optData.data);
3143         }
3144         OICFree(getRolesData->resArr[i].chains);
3145     }
3146     OICFree(getRolesData->resArr);
3147     OICFree(getRolesData);
3148
3149     return OC_STACK_DELETE_TRANSACTION;
3150 }
3151
3152 OCStackResult SRPGetRolesResource(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
3153         OCGetRolesResultCB resultCallback)
3154 {
3155     VERIFY_NOT_NULL_RETURN(TAG, selectedDeviceInfo, ERROR,  OC_STACK_INVALID_PARAM);
3156     VERIFY_NOT_NULL_RETURN(TAG, resultCallback, ERROR,  OC_STACK_INVALID_CALLBACK);
3157
3158     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
3159     if (!PMGenerateQuery(true,
3160                         selectedDeviceInfo->endpoint.addr,
3161                         selectedDeviceInfo->securePort,
3162                         selectedDeviceInfo->connType,
3163                         query, sizeof(query), OIC_RSRC_ROLES_URI))
3164     {
3165         OIC_LOG(ERROR, TAG, "SRPGetRolesResource : Failed to generate query");
3166         return OC_STACK_ERROR;
3167     }
3168     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
3169
3170     OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};
3171     cbData.cb = &SRPGetRolesResourceCB;
3172     GetRolesData_t *getRolesData = (GetRolesData_t*)OICCalloc(1, sizeof(GetRolesData_t));
3173     if (NULL == getRolesData)
3174     {
3175         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
3176         return OC_STACK_NO_MEMORY;
3177     }
3178     getRolesData->deviceInfo = selectedDeviceInfo;
3179     getRolesData->resultCallback = resultCallback;
3180     getRolesData->numOfResults = 0;
3181     getRolesData->ctx = ctx;
3182
3183     getRolesData->resArr = (OCPMGetRolesResult_t*)OICCalloc(1, sizeof(OCPMGetRolesResult_t));
3184     if (NULL == getRolesData->resArr)
3185     {
3186         OICFree(getRolesData);
3187         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
3188         return OC_STACK_NO_MEMORY;
3189     }
3190     cbData.context = (void *)getRolesData;
3191     OCDoHandle handle = NULL;
3192     OIC_LOG(DEBUG, TAG, "Sending Get Roles to resource server");
3193     OCStackResult ret = OCDoResource(&handle, OC_REST_GET, query, NULL, NULL,
3194             selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
3195     if (OC_STACK_OK != ret)
3196     {
3197         OIC_LOG(ERROR, TAG, "OCStack resource error");
3198         OICFree(getRolesData->resArr);
3199         OICFree(getRolesData);
3200     }
3201     OIC_LOG(DEBUG, TAG, "OUT SRPGetRolesResource");
3202
3203     return ret;
3204 }
3205
3206 /**
3207  * Callback handler of SRPDeleteRoleCertificateByCredId.
3208  *
3209  * @param[in] ctx             ctx value passed to callback from calling function.
3210  * @param[in] UNUSED          handle to an invocation
3211  * @param[in] clientResponse  Response from queries to remote servers.
3212  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
3213  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
3214  */
3215 static OCStackApplicationResult SRPDeleteRoleCertificateCB(void *ctx, OCDoHandle UNUSED,
3216                                                            OCClientResponse *clientResponse)
3217 {
3218     OC_UNUSED(UNUSED);
3219     GetSecData_t *getSecData = (GetSecData_t *)ctx;
3220
3221     OIC_LOG(DEBUG, TAG, "SRPDeleteRoleCertificateCB IN");
3222
3223     if (NULL != clientResponse)
3224     {
3225         memcpy(getSecData->resArr[(getSecData->numOfResults)].deviceId.id,
3226             getSecData->deviceInfo->doxm->deviceID.id, UUID_LENGTH);
3227         getSecData->resArr[(getSecData->numOfResults)].res = clientResponse->result;
3228         ++(getSecData->numOfResults);
3229     }
3230
3231     OIC_LOG(DEBUG, TAG, "SRPDeleteRoleCertificateCB OUT");
3232
3233     return OC_STACK_DELETE_TRANSACTION;
3234 }
3235
3236 OCStackResult SRPDeleteRoleCertificateByCredId(void* ctx, const OCProvisionDev_t *selectedDeviceInfo,
3237                                                OCProvisionResultCB resultCallback, uint32_t credId)
3238 {
3239     VERIFY_NOT_NULL_RETURN(TAG, selectedDeviceInfo, ERROR,  OC_STACK_INVALID_PARAM);
3240     VERIFY_NOT_NULL_RETURN(TAG, resultCallback, ERROR,  OC_STACK_INVALID_CALLBACK);
3241
3242     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
3243     if (!PMGenerateQuery(true,
3244                         selectedDeviceInfo->endpoint.addr,
3245                         selectedDeviceInfo->securePort,
3246                         selectedDeviceInfo->connType,
3247                         query, sizeof(query), OIC_RSRC_ROLES_URI))
3248     {
3249         OIC_LOG(ERROR, TAG, "SRPDeleteRoleCertificateByCredId : Failed to generate query");
3250         return OC_STACK_ERROR;
3251     }
3252     size_t queryLen = strlen(query);
3253     int snRet = snprintf(query + queryLen, sizeof(query) - queryLen, "?credId=%u", credId);
3254
3255     if (0 > snRet)
3256     {
3257         OIC_LOG_V(ERROR, TAG, "snprintf returned error: %d", snRet);
3258         return OC_STACK_ERROR;
3259     }
3260     else if ((size_t)snRet >= (sizeof(query) - queryLen))
3261     {
3262         OIC_LOG_V(ERROR, TAG, "snprintf truncated");
3263         return OC_STACK_ERROR;
3264     }
3265
3266     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
3267
3268     OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};
3269     cbData.cb = &SRPDeleteRoleCertificateCB;
3270     GetSecData_t *getSecData = (GetSecData_t*)OICCalloc(1, sizeof(GetSecData_t));
3271     if (NULL == getSecData)
3272     {
3273         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
3274         return OC_STACK_NO_MEMORY;
3275     }
3276     getSecData->deviceInfo = selectedDeviceInfo;
3277     getSecData->resultCallback = resultCallback;
3278     getSecData->numOfResults = 0;
3279     getSecData->ctx = ctx;
3280
3281     getSecData->resArr = (OCProvisionResult_t*)OICCalloc(1, sizeof(OCProvisionResult_t));
3282     if (NULL == getSecData->resArr)
3283     {
3284         OICFree(getSecData);
3285         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
3286         return OC_STACK_NO_MEMORY;
3287     }
3288     cbData.context = (void *)getSecData;
3289     OCMethod method = OC_REST_DELETE;
3290     OCDoHandle handle = NULL;
3291     OIC_LOG(DEBUG, TAG, "Sending Delete Roles to resource server");
3292     OCStackResult ret = OCDoResource(&handle, method, query, NULL, NULL,
3293             selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
3294     if (OC_STACK_OK != ret)
3295     {
3296         OIC_LOG(ERROR, TAG, "OCStack resource error");
3297         OICFree(getSecData->resArr);
3298         OICFree(getSecData);
3299     }
3300     OIC_LOG(DEBUG, TAG, "OUT SRPGetRolesResource");
3301
3302     return ret;
3303 }
3304
3305 OCStackResult SRPReadTrustCertChain(uint16_t credId, uint8_t **trustCertChain,
3306                                      size_t *chainSize)
3307 {
3308     OIC_LOG(DEBUG, TAG, "IN SRPReadTrustCertChain");
3309
3310     OCStackResult res = OC_STACK_ERROR;
3311     int secureFlag = 0;
3312     OicSecCred_t* credData = GetCredEntryByCredId(credId);
3313     if(credData)
3314     {
3315         res = CredToCBORPayload((const OicSecCred_t*) credData, trustCertChain,
3316                                 chainSize, secureFlag);
3317         if(OC_STACK_OK != res)
3318         {
3319             OIC_LOG(INFO, TAG, "CredToCBORPayload failed");
3320         }
3321     }
3322     DeleteCredList(credData);
3323     return res;
3324 }