Imported Upstream version 1.1.1
[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 <stdio.h>
21 #include <string.h>
22 #include <stdint.h>
23 #include <unistd.h>
24
25 #include "ocprovisioningmanager.h"
26 #include "secureresourceprovider.h"
27 #include "logger.h"
28 #include "oic_malloc.h"
29 #include "aclresource.h"
30 #include "pstatresource.h"
31 #include "srmresourcestrings.h"
32 #include "credresource.h"
33 #include "doxmresource.h"
34 #include "pconfresource.h"
35 #include "credentialgenerator.h"
36 #include "cainterface.h"
37 #include "cJSON.h"
38 #include "pmtypes.h"
39 #include "pmutility.h"
40 #include "provisioningdatabasemanager.h"
41 #include "base64.h"
42 #include "utlist.h"
43 #include "ocpayload.h"
44
45 #ifdef __WITH_X509__
46 #include "crlresource.h"
47 #endif // WITH_X509__
48
49 #define TAG "SRPAPI"
50
51 /**
52  * Macro to verify argument is not equal to NULL.
53  * eg: VERIFY_NON_NULL(TAG, ptrData, ERROR,OC_STACK_ERROR);
54  */
55 #define VERIFY_NON_NULL(tag, arg, logLevel, retValue) { if (NULL == (arg)) \
56             { OIC_LOG((logLevel), tag, #arg " is NULL"); return retValue; } }
57
58 /**
59  * Macro to verify success of operation.
60  * eg: VERIFY_SUCCESS(TAG, OC_STACK_OK == foo(), ERROR, OC_STACK_ERROR);
61  */
62 #define VERIFY_SUCCESS(tag, op, logLevel, retValue) { if (!(op)) \
63             {OIC_LOG((logLevel), tag, #op " failed!!"); return retValue;} }
64
65 /**
66  * Structure to carry credential data to callback.
67  */
68 typedef struct CredentialData CredentialData_t;
69 struct CredentialData
70 {
71     void *ctx;                                  /**< Pointer to user context.**/
72     const OCProvisionDev_t *deviceInfo1;        /**< Pointer to OCProvisionDev_t.**/
73     const OCProvisionDev_t *deviceInfo2;        /**< Pointer to OCProvisionDev_t.**/
74     OicSecCred_t *credInfo;                     /**< Pointer to OicSecCred_t.**/
75     OicSecCred_t *credInfoFirst;                /**< Pointer to OicSecCred_t.**/
76     OCProvisionResultCB resultCallback;         /**< Pointer to result callback.**/
77     OCProvisionResult_t *resArr;                /**< Result array.**/
78     int numOfResults;                           /**< Number of results in result array.**/
79 };
80
81 /**
82  * Structure to carry ACL provision API data to callback.
83  */
84 typedef struct ACLData ACLData_t;
85 struct ACLData
86 {
87     void *ctx;                                  /**< Pointer to user context.**/
88     const OCProvisionDev_t *deviceInfo;         /**< Pointer to PMDevInfo_t.**/
89     OCProvisionResultCB resultCallback;         /**< Pointer to result callback.**/
90     OCProvisionResult_t *resArr;                /**< Result array.**/
91     int numOfResults;                           /**< Number of results in result array.**/
92 };
93
94 // Structure to carry get security resource APIs data to callback.
95 typedef struct GetSecData GetSecData_t;
96 struct GetSecData {
97     void *ctx;
98     const OCProvisionDev_t *deviceInfo;         /**< Pointer to PMDevInfo_t.**/
99     OCProvisionResultCB resultCallback;         /**< Pointer to result callback.**/
100     OCProvisionResult_t *resArr;                /**< Result array.**/
101     int numOfResults;                        /**< Number of results in result array.**/
102 };
103
104 /**
105  * Structure to carry PCONF provision API data to callback.
106  */
107 typedef struct PconfData PconfData_t;
108 struct PconfData
109 {
110     void *ctx;                                  /**< Pointer to user context.**/
111     const OCProvisionDev_t *deviceInfo;         /**< Pointer to PMDevInfo_t.**/
112     OCProvisionResultCB resultCallback;         /**< Pointer to result callback.**/
113     OCProvisionResult_t *resArr;                /**< Result array.**/
114     int numOfResults;                           /**< Number of results in result array.**/
115 };
116
117 // Enum type index for unlink callback.
118 typedef enum {
119     IDX_FIRST_DEVICE_RES = 0, // index for resulf of the first device
120     IDX_SECOND_DEVICE_RES,    // index for result of the second device
121     IDX_DB_UPDATE_RES         // index for result of updating provisioning database.
122 } IdxUnlinkRes_t;
123
124 // Structure to carry unlink APIs data to callback.
125 typedef struct UnlinkData UnlinkData_t;
126 struct UnlinkData {
127     void *ctx;
128     OCProvisionDev_t* unlinkDev;             /**< Pointer to OCProvisionDev_t to be unlinked.**/
129     OCProvisionResult_t* unlinkRes;          /**< Result array.**/
130     OCProvisionResultCB resultCallback;      /**< Pointer to result callback.**/
131     int numOfResults;                        /**< Number of results in result array.**/
132 };
133
134 //Example of DELETE cred request -> coaps://0.0.0.0:5684/oic/sec/cred?sub=(BASE64 ENCODED UUID)
135 const char * SRP_FORM_DELETE_CREDENTIAL = "coaps://[%s]:%d%s?%s=%s";
136
137 // Structure to carry remove APIs data to callback.
138 typedef struct RemoveData RemoveData_t;
139 struct RemoveData {
140     void *ctx;
141     OCProvisionDev_t* revokeTargetDev;      /**< Device which is going to be revoked..**/
142     OCProvisionDev_t* linkedDevList;        /**< A list of devices which have invalid credential.**/
143     OCProvisionResult_t* removeRes;         /**< Result array.**/
144     OCProvisionResultCB resultCallback;     /**< Pointer to result callback.**/
145     size_t numOfResults;                    /**< Number of results in result array.**/
146     size_t sizeOfResArray;
147     bool hasError;
148 };
149
150 /**
151  * Function prototype
152  */
153 static OCStackResult provisionCredentials(const OicSecCred_t *cred,
154         const OCProvisionDev_t *deviceInfo, CredentialData_t *credData,
155         OCClientResponseHandler responseHandler);
156
157
158 /**
159  * Internal function to update result in result array.
160  */
161 static void registerResultForCredProvisioning(CredentialData_t *credData,
162                                               OCStackResult stackresult, int cause)
163 {
164
165    OIC_LOG_V(INFO,TAG,"value of credData->numOfResults is %d",credData->numOfResults);
166    if(1 == cause)
167    {
168        memcpy(credData->resArr[(credData->numOfResults)].deviceId.id,
169               credData->deviceInfo1->doxm->deviceID.id,UUID_LENGTH);
170    }
171    else
172    {
173        memcpy(credData->resArr[(credData->numOfResults)].deviceId.id,
174               credData->deviceInfo2->doxm->deviceID.id,UUID_LENGTH);
175    }
176    credData->resArr[(credData->numOfResults)].res = stackresult;
177    ++(credData->numOfResults);
178 }
179
180 /**
181  * Callback handler for handling callback of provisioning device 2.
182  *
183  * @param[in] ctx             ctx value passed to callback from calling function.
184  * @param[in] UNUSED          handle to an invocation
185  * @param[in] clientResponse  Response from queries to remote servers.
186  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
187  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
188  */
189 static OCStackApplicationResult provisionCredentialCB2(void *ctx, OCDoHandle UNUSED,
190                                                        OCClientResponse *clientResponse)
191 {
192     VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
193     CredentialData_t *credData = (CredentialData_t *) ctx;
194     (void)UNUSED;
195
196     OCProvisionResultCB resultCallback = credData->resultCallback;
197     OIC_LOG(INFO, TAG, "provisionCredentialCB2 called");
198     if (clientResponse)
199     {
200         if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
201         {
202             registerResultForCredProvisioning(credData, OC_STACK_RESOURCE_CHANGED, 2);
203             OCStackResult res =  PDMLinkDevices(&credData->deviceInfo1->doxm->deviceID,
204                     &credData->deviceInfo2->doxm->deviceID);
205             if (OC_STACK_OK != res)
206             {
207                 OIC_LOG(ERROR, TAG, "Error occured on PDMLinkDevices");
208                 return OC_STACK_DELETE_TRANSACTION;
209             }
210             OIC_LOG(INFO, TAG, "Link created successfully");
211
212             ((OCProvisionResultCB)(resultCallback))(credData->ctx, credData->numOfResults,
213                                                     credData->resArr,
214                                                     false);
215              OICFree(credData->resArr);
216              OICFree(credData);
217              return OC_STACK_DELETE_TRANSACTION;
218         }
219
220     }
221     OIC_LOG(INFO, TAG, "provisionCredentialCB2 received Null clientResponse");
222     registerResultForCredProvisioning(credData, OC_STACK_ERROR, 2);
223     ((OCProvisionResultCB)(resultCallback))(credData->ctx, credData->numOfResults,
224                                             credData->resArr,
225                                             true);
226     OICFree(credData->resArr);
227     OICFree(credData);
228     return OC_STACK_DELETE_TRANSACTION;
229 }
230
231 /**
232  * Callback handler for handling callback of provisioning device 1.
233  *
234  * @param[in] ctx             ctx value passed to callback from calling function.
235  * @param[in] UNUSED          handle to an invocation
236  * @param[in] clientResponse  Response from queries to remote servers.
237  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
238  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
239  */
240 static OCStackApplicationResult provisionCredentialCB1(void *ctx, OCDoHandle UNUSED,
241                                                        OCClientResponse *clientResponse)
242 {
243     VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
244     (void)UNUSED;
245     CredentialData_t* credData = (CredentialData_t*) ctx;
246     OICFree(credData->credInfoFirst);
247     const OCProvisionDev_t *deviceInfo = credData->deviceInfo2;
248     OicSecCred_t *credInfo = credData->credInfo;
249     const OCProvisionResultCB resultCallback = credData->resultCallback;
250     if (clientResponse)
251     {
252         if (OC_STACK_RESOURCE_CHANGED == clientResponse->result)
253         {
254             // send credentials to second device
255             registerResultForCredProvisioning(credData, OC_STACK_RESOURCE_CHANGED,1);
256             OCStackResult res = provisionCredentials(credInfo, deviceInfo, credData,
257                     provisionCredentialCB2);
258             DeleteCredList(credInfo);
259             if (OC_STACK_OK != res)
260             {
261                 registerResultForCredProvisioning(credData, res,2);
262                 ((OCProvisionResultCB)(resultCallback))(credData->ctx, credData->numOfResults,
263                                                         credData->resArr,
264                                                         true);
265                 OICFree(credData->resArr);
266                 OICFree(credData);
267                 credData = NULL;
268             }
269         }
270         else
271         {
272             registerResultForCredProvisioning(credData, OC_STACK_ERROR,1);
273             ((OCProvisionResultCB)(resultCallback))(credData->ctx, credData->numOfResults,
274                                                     credData->resArr,
275                                                     true);
276             OICFree(credData->resArr);
277             OICFree(credData);
278             credData = NULL;
279         }
280     }
281     else
282     {
283         OIC_LOG(INFO, TAG, "provisionCredentialCB received Null clientResponse for first device");
284         registerResultForCredProvisioning(credData, OC_STACK_ERROR,1);
285        ((OCProvisionResultCB)(resultCallback))(credData->ctx, credData->numOfResults,
286                                                      credData->resArr,
287                                                      true);
288         DeleteCredList(credInfo);
289         OICFree(credData->resArr);
290         OICFree(credData);
291         credData = NULL;
292     }
293     return OC_STACK_DELETE_TRANSACTION;
294 }
295
296
297
298 /**
299  * Internal function for handling credential generation and sending credential to resource server.
300  *
301  * @param[in] cred Instance of cred resource.
302  * @param[in] deviceInfo information about device to which credential is to be provisioned.
303  * @param[in] responseHandler callbak called by OC stack when request API receives response.
304  * @return  OC_STACK_OK in case of success and other value otherwise.
305  */
306 static OCStackResult provisionCredentials(const OicSecCred_t *cred,
307         const OCProvisionDev_t *deviceInfo, CredentialData_t *credData,
308         OCClientResponseHandler responseHandler)
309 {
310     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
311     if (!secPayload)
312     {
313         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
314         return OC_STACK_NO_MEMORY;
315     }
316     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
317     int secureFlag = 0;
318     OCStackResult res = CredToCBORPayload(cred, &secPayload->securityData,
319                                           &secPayload->payloadSize, secureFlag);
320     if((OC_STACK_OK != res) && (NULL == secPayload->securityData))
321     {
322         OCPayloadDestroy((OCPayload *)secPayload);
323         OIC_LOG(ERROR, TAG, "Failed to CredToCBORPayload");
324         return OC_STACK_NO_MEMORY;
325     }
326
327     OIC_LOG(DEBUG, TAG, "Created payload for Cred:");
328     OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
329     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
330     if(!PMGenerateQuery(true,
331                         deviceInfo->endpoint.addr,
332                         deviceInfo->securePort,
333                         deviceInfo->connType,
334                         query, sizeof(query), OIC_RSRC_CRED_URI))
335     {
336         OIC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
337         return OC_STACK_ERROR;
338     }
339     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
340
341     OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
342     cbData.cb = responseHandler;
343     cbData.context = (void *) credData;
344     cbData.cd = NULL;
345
346     OCDoHandle handle = NULL;
347     OCMethod method = OC_REST_POST;
348     OCStackResult ret = OCDoResource(&handle, method, query, 0, (OCPayload*)secPayload,
349             deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
350     OIC_LOG_V(INFO, TAG, "OCDoResource::Credential provisioning returned : %d",ret);
351     if (ret != OC_STACK_OK)
352     {
353         OIC_LOG(ERROR, TAG, "OCStack resource error");
354         return ret;
355     }
356     return OC_STACK_OK;
357 }
358
359 #ifdef __WITH_X509__
360 /**
361  * Structure to carry certificate data to callback.
362  */
363 typedef struct CertificateData CertData_t;
364 struct CertificateData
365 {
366     void *ctx;                                  /**< Pointer to user context.**/
367     const OCProvisionDev_t *deviceInfo;        /**< Pointer to OCProvisionDev_t.**/
368     OicSecCred_t *credInfo;                     /**< Pointer to OicSecCred_t.**/
369     OCProvisionResultCB resultCallback;         /**< Pointer to result callback.**/
370     OCProvisionResult_t *resArr;                /**< Result array.**/
371     int numOfResults;                           /**< Number of results in result array.**/
372 };
373
374 /**
375  * Structure to carry CRL provision API data to callback.
376  */
377 typedef struct CRLData CRLData_t;
378 struct CRLData
379 {
380     void *ctx;                                  /**< Pointer to user context.**/
381     const OCProvisionDev_t *deviceInfo;         /**< Pointer to PMDevInfo_t.**/
382     OCProvisionResultCB resultCallback;         /**< Pointer to result callback.**/
383     OCProvisionResult_t *resArr;                /**< Result array.**/
384     int numOfResults;                           /**< Number of results in result array.**/
385 };
386
387 /**
388  * Internal function to update result in result array.
389  */
390 static void registerResultForCertProvisioning(CertData_t *certData,
391                                               OCStackResult stackresult)
392 {
393
394    OIC_LOG_V(INFO,TAG,"value of credData->numOfResults is %d",certData->numOfResults);
395    memcpy(certData->resArr[(certData->numOfResults)].deviceId.id,
396           certData->deviceInfo->doxm->deviceID.id,UUID_LENGTH);
397    certData->resArr[(certData->numOfResults)].res = stackresult;
398    ++(certData->numOfResults);
399 }
400
401 /**
402  * Internal Function to store results in result array during ACL provisioning.
403  */
404 static void registerResultForCRLProvisioning(CRLData_t *crlData,
405                                              OCStackResult stackresult)
406 {
407    OIC_LOG_V(INFO, TAG, "Inside registerResultForCRLProvisioning crlData->numOfResults is %d\n",
408                        crlData->numOfResults);
409    memcpy(crlData->resArr[(crlData->numOfResults)].deviceId.id,
410           crlData->deviceInfo->doxm->deviceID.id, UUID_LENGTH);
411    crlData->resArr[(crlData->numOfResults)].res = stackresult;
412    ++(crlData->numOfResults);
413 }
414
415
416 /**
417  * Callback handler of SRPProvisionCRL.
418  *
419  * @param[in] ctx             ctx value passed to callback from calling function.
420  * @param[in] UNUSED          handle to an invocation
421  * @param[in] clientResponse  Response from queries to remote servers.
422  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
423  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
424  */
425 static OCStackApplicationResult SRPProvisionCRLCB(void *ctx, OCDoHandle UNUSED,
426                                                   OCClientResponse *clientResponse)
427 {
428     OIC_LOG_V(INFO, TAG, "Inside SRPProvisionCRLCB.");
429     (void)UNUSED;
430     VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
431     CRLData_t *crlData = (CRLData_t*)ctx;
432     OCProvisionResultCB resultCallback = crlData->resultCallback;
433
434     if (clientResponse)
435     {
436         if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
437         {
438             registerResultForCRLProvisioning(crlData, OC_STACK_RESOURCE_CHANGED);
439             ((OCProvisionResultCB)(resultCallback))(crlData->ctx, crlData->numOfResults,
440                                                     crlData->resArr,
441                                                     false);
442              OICFree(crlData->resArr);
443              OICFree(crlData);
444              return OC_STACK_DELETE_TRANSACTION;
445         }
446     }
447     registerResultForCRLProvisioning(crlData, OC_STACK_ERROR);
448     ((OCProvisionResultCB)(resultCallback))(crlData->ctx, crlData->numOfResults,
449                                             crlData->resArr,
450                                             true);
451     OIC_LOG_V(ERROR, TAG, "SRPProvisionCRLCB received Null clientResponse");
452     OICFree(crlData->resArr);
453     OICFree(crlData);
454     return OC_STACK_DELETE_TRANSACTION;
455 }
456
457 OCStackResult SRPProvisionCRL(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
458         OicSecCrl_t *crl, OCProvisionResultCB resultCallback)
459 {
460     VERIFY_NON_NULL(TAG, selectedDeviceInfo, ERROR,  OC_STACK_INVALID_PARAM);
461     VERIFY_NON_NULL(TAG, crl, ERROR,  OC_STACK_INVALID_PARAM);
462     VERIFY_NON_NULL(TAG, resultCallback, ERROR,  OC_STACK_INVALID_CALLBACK);
463
464     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
465     if (!secPayload)
466     {
467         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
468         return OC_STACK_NO_MEMORY;
469     }
470
471     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
472     OCStackResult res = CrlToCBORPayload(crl, &secPayload->securityData, &secPayload->payloadSize);
473     if((OC_STACK_OK != res) && (NULL == secPayload->securityData))
474     {
475         OICFree(secPayload);
476         OIC_LOG(ERROR, TAG, "Failed to BinToCrlJSON");
477         return OC_STACK_NO_MEMORY;
478     }
479     OIC_LOG(DEBUG, TAG, "Created payload for CRL:");
480     OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
481
482     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
483     if(!PMGenerateQuery(true,
484                         selectedDeviceInfo->endpoint.addr,
485                         selectedDeviceInfo->securePort,
486                         selectedDeviceInfo->connType,
487                         query, sizeof(query), OIC_RSRC_CRL_URI))
488     {
489         OIC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
490         OCPayloadDestroy((OCPayload *)secPayload);
491         return OC_STACK_ERROR;
492     }
493     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
494
495     OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};
496     cbData.cb = &SRPProvisionCRLCB;
497     CRLData_t *crlData = (CRLData_t *) OICCalloc(1, sizeof(CRLData_t));
498     if (crlData == NULL)
499     {
500         OCPayloadDestroy((OCPayload *)secPayload);
501         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
502         return OC_STACK_NO_MEMORY;
503     }
504
505     crlData->deviceInfo = selectedDeviceInfo;
506     crlData->resultCallback = resultCallback;
507     crlData->numOfResults=0;
508     crlData->ctx = ctx;
509
510     crlData->resArr = (OCProvisionResult_t*)OICCalloc(1, sizeof(OCProvisionResult_t));
511     if (crlData->resArr == NULL)
512     {
513         OCPayloadDestroy((OCPayload *)secPayload);
514         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
515         return OC_STACK_NO_MEMORY;
516     }
517
518     cbData.context = (void *)crlData;
519     cbData.cd = NULL;
520     OCMethod method = OC_REST_POST;
521     OCDoHandle handle = NULL;
522     OIC_LOG(DEBUG, TAG, "Sending CRL info to resource server");
523
524     OCStackResult ret = OCDoResource(&handle, method, query,
525             &selectedDeviceInfo->endpoint, (OCPayload*)secPayload,
526             selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
527
528     if (ret != OC_STACK_OK)
529     {
530         OICFree(crlData->resArr);
531         OICFree(crlData);
532     }
533
534     return ret;
535 }
536
537 /**
538  * Internal function for handling credential generation and sending cretificate credential.
539  *
540  * @param[in] cred Instance of cred resource.
541  * @param[in] deviceInfo information about device to which credential is to be provisioned.
542  * @param[in] responseHandler callbak called by OC stack when request API receives response.
543  * @return  OC_STACK_OK in case of success and other value otherwise.
544  */
545 static OCStackResult provisionCertCred(const OicSecCred_t *cred,
546         const OCProvisionDev_t *deviceInfo, CertData_t *certData,
547         OCClientResponseHandler responseHandler)
548 {
549     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
550     if(!secPayload)
551     {
552         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
553         return OC_STACK_NO_MEMORY;
554     }
555     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
556     int secureFlag = 0;
557     OCStackResult res = CredToCBORPayload(cred, &secPayload->securityData,
558         &secPayload->payloadSize, secureFlag);
559
560     if ((OC_STACK_OK != res) || (NULL == secPayload->securityData))
561     {
562         OICFree(secPayload);
563         OIC_LOG(ERROR, TAG, "Failed to CredToCBORPayload");
564         return OC_STACK_NO_MEMORY;
565     }
566
567     OIC_LOG(DEBUG, TAG, "Created payload for Cred:");
568     OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
569     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
570     if(!PMGenerateQuery(true,
571                         deviceInfo->endpoint.addr,
572                         deviceInfo->securePort,
573                         deviceInfo->connType,
574                         query, sizeof(query), OIC_RSRC_CRED_URI))
575     {
576         OIC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
577         OCPayloadDestroy((OCPayload *)secPayload);
578         return OC_STACK_ERROR;
579     }
580     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
581
582     OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
583     cbData.cb = responseHandler;
584     cbData.context = (void *) certData;
585     cbData.cd = NULL;
586
587     OCDoHandle handle = NULL;
588     OCMethod method = OC_REST_POST;
589     OCStackResult ret = OCDoResource(&handle, method, query, 0, (OCPayload*)secPayload,
590             deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
591     OIC_LOG_V(INFO, TAG, "OCDoResource::Certificate provisioning returned : %d",ret);
592     if (ret != OC_STACK_OK)
593     {
594         OIC_LOG(ERROR, TAG, "OCStack resource error");
595     }
596
597     return ret;
598 }
599
600 /**
601  * Callback handler for handling callback of certificate provisioning device.
602  *
603  * @param[in] ctx             ctx value passed to callback from calling function.
604  * @param[in] UNUSED          handle to an invocation
605  * @param[in] clientResponse  Response from queries to remote servers.
606  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
607  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
608  */
609 static OCStackApplicationResult provisionCertCB(void *ctx, OCDoHandle UNUSED,
610                                                        OCClientResponse *clientResponse)
611 {
612     VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
613     CertData_t *certData = (CertData_t *) ctx;
614     (void)UNUSED;
615
616     OCProvisionResultCB resultCallback = certData->resultCallback;
617     OIC_LOG(INFO, TAG, "provisionCertCred called");
618     if (clientResponse)
619     {
620         if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
621         {
622             registerResultForCertProvisioning(certData, OC_STACK_RESOURCE_CHANGED);
623             ((OCProvisionResultCB)(resultCallback))(certData->ctx, certData->numOfResults,
624                                                     certData->resArr,
625                                                     false);
626              OICFree(certData->resArr);
627              OICFree(certData);
628              return OC_STACK_DELETE_TRANSACTION;
629         }
630
631     }
632     OIC_LOG(INFO, TAG, "provisionCertCredCB received Null clientResponse");
633     registerResultForCertProvisioning(certData, OC_STACK_ERROR);
634     ((OCProvisionResultCB)(resultCallback))(certData->ctx, certData->numOfResults,
635                                             certData->resArr,
636                                             true);
637     OICFree(certData->resArr);
638     OICFree(certData);
639     return OC_STACK_DELETE_TRANSACTION;
640 }
641 #endif // __WITH_X509__
642
643 OCStackResult SRPProvisionCredentials(void *ctx, OicSecCredType_t type, size_t keySize,
644                                       const OCProvisionDev_t *pDev1,
645                                       const OCProvisionDev_t *pDev2,
646                                       OCProvisionResultCB resultCallback)
647 {
648     VERIFY_NON_NULL(TAG, pDev1, ERROR,  OC_STACK_INVALID_PARAM);
649     if (SYMMETRIC_PAIR_WISE_KEY == type)
650     {
651         VERIFY_NON_NULL(TAG, pDev2, ERROR,  OC_STACK_INVALID_PARAM);
652     }
653     if (!resultCallback)
654     {
655         OIC_LOG(INFO, TAG, "SRPUnlinkDevices : NULL Callback");
656         return OC_STACK_INVALID_CALLBACK;
657     }
658     if (SYMMETRIC_PAIR_WISE_KEY == type &&
659         0 == memcmp(&pDev1->doxm->deviceID, &pDev2->doxm->deviceID, sizeof(OicUuid_t)))
660     {
661         OIC_LOG(INFO, TAG, "SRPUnlinkDevices : Same device ID");
662         return OC_STACK_INVALID_PARAM;
663     }
664
665     if (SYMMETRIC_PAIR_WISE_KEY == type &&
666        !(OWNER_PSK_LENGTH_128 == keySize || OWNER_PSK_LENGTH_256 == keySize))
667     {
668         OIC_LOG(INFO, TAG, "Invalid key size");
669         return OC_STACK_INVALID_PARAM;
670     }
671
672     OIC_LOG(INFO, TAG, "In SRPProvisionCredentials");
673
674     if (SYMMETRIC_PAIR_WISE_KEY == type)
675     {
676         bool linkExisits = true;
677         OCStackResult res = PDMIsLinkExists(&pDev1->doxm->deviceID, &pDev2->doxm->deviceID, &linkExisits);
678
679         if (res != OC_STACK_OK)
680         {
681             OIC_LOG(ERROR, TAG, "Internal error occured");
682             return res;
683         }
684         if (linkExisits)
685         {
686             OIC_LOG(ERROR, TAG, "Link already exists");
687             return OC_STACK_INVALID_PARAM;
688         }
689     }
690
691     OicUuid_t provTooldeviceID =   {{0,}};
692     if (OC_STACK_OK != GetDoxmDeviceID(&provTooldeviceID))
693     {
694         OIC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
695         return OC_STACK_ERROR;
696     }
697     OIC_LOG(INFO, TAG, "retrieved deviceid");
698     switch (type)
699     {
700         case SYMMETRIC_PAIR_WISE_KEY:
701         {
702             const OCProvisionDev_t *firstDevice = pDev1;
703             const OCProvisionDev_t *secondDevice = pDev2;
704
705             OicSecCred_t *firstCred = NULL;
706             OicSecCred_t *secondCred = NULL;
707             OCStackResult res = PMGeneratePairWiseCredentials(type, keySize, &provTooldeviceID,
708                     &firstDevice->doxm->deviceID, &secondDevice->doxm->deviceID,
709                     &firstCred, &secondCred);
710             VERIFY_SUCCESS(TAG, (res==OC_STACK_OK), ERROR, OC_STACK_ERROR);
711             OIC_LOG(INFO, TAG, "Credentials generated successfully");
712             CredentialData_t *credData =
713                 (CredentialData_t *) OICCalloc(1, sizeof(CredentialData_t));
714             if (NULL == credData)
715             {
716                 OICFree(firstCred);
717                 OICFree(secondCred);
718                 OIC_LOG(ERROR, TAG, "Memory allocation problem");
719                 return OC_STACK_NO_MEMORY;
720             }
721             credData->deviceInfo1 = firstDevice;
722             credData->deviceInfo2 = secondDevice;
723             credData->credInfo = secondCred;
724             credData->ctx = ctx;
725             credData->credInfoFirst = firstCred;
726             credData->numOfResults = 0;
727             credData->resultCallback = resultCallback;
728             // first call to provision creds to device1.
729             // second call to provision creds to device2.
730             int noOfRiCalls = 2;
731             credData->resArr =
732                 (OCProvisionResult_t*)OICCalloc(noOfRiCalls, sizeof(OCProvisionResult_t));
733             if (NULL == credData->resArr)
734             {
735                 OICFree(firstCred);
736                 OICFree(secondCred);
737                 OICFree(credData);
738                 OIC_LOG(ERROR, TAG, "Memory allocation problem");
739                 return OC_STACK_NO_MEMORY;
740             }
741             res = provisionCredentials(firstCred, firstDevice, credData, &provisionCredentialCB1);
742             if (OC_STACK_OK != res)
743             {
744                 DeleteCredList(firstCred);
745                 DeleteCredList(secondCred);
746                 OICFree(credData->resArr);
747                 OICFree(credData);
748             }
749             OIC_LOG_V(INFO, TAG, "provisionCredentials returned: %d",res);
750             VERIFY_SUCCESS(TAG, (res==OC_STACK_OK), ERROR, OC_STACK_ERROR);
751             return res;
752         }
753 #ifdef __WITH_X509__
754         case SIGNED_ASYMMETRIC_KEY:
755         {
756             const OCProvisionDev_t *firstDevice = pDev1;
757             OicSecCred_t *cred = NULL;
758             OCStackResult res = PMGenerateCertificateCredentials(&provTooldeviceID,
759                                                                 &firstDevice->doxm->deviceID,&cred);
760             VERIFY_SUCCESS(TAG, (res==OC_STACK_OK), ERROR, OC_STACK_ERROR);
761             OIC_LOG(INFO, TAG, "Certificate credentials generated successfully");
762             CertData_t *certData = (CertData_t *) OICCalloc(1, sizeof(CertData_t));
763             if (NULL == certData)
764             {
765                 OICFree(cred);
766                 OIC_LOG(ERROR, TAG, "Memory allocation problem");
767                 return OC_STACK_NO_MEMORY;
768             }
769
770             certData->deviceInfo = firstDevice;
771             certData->ctx = ctx;
772             certData->credInfo = cred;
773             certData->numOfResults = 0;
774             certData->resultCallback = resultCallback;
775
776             certData->resArr = (OCProvisionResult_t*)OICCalloc(1, sizeof(OCProvisionResult_t));
777             if (NULL == certData->resArr)
778             {
779                 DeleteCredList(cred);
780                 OICFree(certData);
781                 OIC_LOG(ERROR, TAG, "Memory allocation problem");
782                 return OC_STACK_NO_MEMORY;
783             }
784
785             res = provisionCertCred(cred, firstDevice, certData, &provisionCertCB);
786             if (OC_STACK_OK != res)
787             {
788                 OICFree(certData->resArr);
789                 OICFree(certData);
790             }
791             DeleteCredList(cred);
792             OIC_LOG_V(INFO, TAG, "provisionCertCredentials returned: %d",res);
793
794             return res;
795         }
796 #endif
797         default:
798         {
799             OIC_LOG(ERROR, TAG, "Invalid option.");
800             return OC_STACK_INVALID_PARAM;
801         }
802     }
803     return OC_STACK_ERROR;
804 }
805
806 /**
807  * Internal Function to store results in result array during ACL provisioning.
808  */
809 static void registerResultForACLProvisioning(ACLData_t *aclData,
810                                              OCStackResult stackresult)
811 {
812    OIC_LOG_V(INFO, TAG, "Inside registerResultForACLProvisioning aclData->numOfResults is %d\n",
813                        aclData->numOfResults);
814    memcpy(aclData->resArr[(aclData->numOfResults)].deviceId.id,
815           aclData->deviceInfo->doxm->deviceID.id, UUID_LENGTH);
816    aclData->resArr[(aclData->numOfResults)].res = stackresult;
817    ++(aclData->numOfResults);
818 }
819
820 /**
821  * Callback handler of SRPProvisionACL.
822  *
823  * @param[in] ctx             ctx value passed to callback from calling function.
824  * @param[in] UNUSED          handle to an invocation
825  * @param[in] clientResponse  Response from queries to remote servers.
826  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
827  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
828  */
829 static OCStackApplicationResult SRPProvisionACLCB(void *ctx, OCDoHandle UNUSED,
830                                                   OCClientResponse *clientResponse)
831 {
832     OIC_LOG_V(INFO, TAG, "Inside SRPProvisionACLCB.");
833     (void)UNUSED;
834     VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
835     ACLData_t *aclData = (ACLData_t*)ctx;
836     OCProvisionResultCB resultCallback = aclData->resultCallback;
837
838     if (clientResponse)
839     {
840         if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
841         {
842             registerResultForACLProvisioning(aclData, OC_STACK_RESOURCE_CHANGED);
843             ((OCProvisionResultCB)(resultCallback))(aclData->ctx, aclData->numOfResults,
844                                                     aclData->resArr,
845                                                     false);
846              OICFree(aclData->resArr);
847              OICFree(aclData);
848              return OC_STACK_DELETE_TRANSACTION;
849         }
850     }
851     registerResultForACLProvisioning(aclData, OC_STACK_ERROR);
852     ((OCProvisionResultCB)(resultCallback))(aclData->ctx, aclData->numOfResults,
853                                             aclData->resArr,
854                                             true);
855     OIC_LOG_V(ERROR, TAG, "SRPProvisionACLCB received Null clientResponse");
856     OICFree(aclData->resArr);
857     OICFree(aclData);
858     return OC_STACK_DELETE_TRANSACTION;
859 }
860
861 OCStackResult SRPProvisionACL(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
862         OicSecAcl_t *acl, OCProvisionResultCB resultCallback)
863 {
864     VERIFY_NON_NULL(TAG, selectedDeviceInfo, ERROR,  OC_STACK_INVALID_PARAM);
865     VERIFY_NON_NULL(TAG, acl, ERROR,  OC_STACK_INVALID_PARAM);
866     VERIFY_NON_NULL(TAG, resultCallback, ERROR,  OC_STACK_INVALID_CALLBACK);
867
868     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
869     if(!secPayload)
870     {
871         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
872         return OC_STACK_NO_MEMORY;
873     }
874     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
875     if(OC_STACK_OK != AclToCBORPayload(acl, &secPayload->securityData, &secPayload->payloadSize))
876     {
877         OCPayloadDestroy((OCPayload *)secPayload);
878         OIC_LOG(ERROR, TAG, "Failed to AclToCBORPayload");
879         return OC_STACK_NO_MEMORY;
880     }
881     OIC_LOG(DEBUG, TAG, "Created payload for ACL:");
882     OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
883
884     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
885     if(!PMGenerateQuery(true,
886                         selectedDeviceInfo->endpoint.addr,
887                         selectedDeviceInfo->securePort,
888                         selectedDeviceInfo->connType,
889                         query, sizeof(query), OIC_RSRC_ACL_URI))
890     {
891         OIC_LOG(ERROR, TAG, "DeviceDiscoveryHandler : Failed to generate query");
892         return OC_STACK_ERROR;
893     }
894     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
895
896     OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};
897     cbData.cb = &SRPProvisionACLCB;
898     ACLData_t *aclData = (ACLData_t *) OICCalloc(1, sizeof(ACLData_t));
899     if (aclData == NULL)
900     {
901         OCPayloadDestroy((OCPayload *)secPayload);
902         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
903         return OC_STACK_NO_MEMORY;
904     }
905     aclData->deviceInfo = selectedDeviceInfo;
906     aclData->resultCallback = resultCallback;
907     aclData->numOfResults=0;
908     aclData->ctx = ctx;
909     // call to provision ACL to device1.
910     int noOfRiCalls = 1;
911     aclData->resArr = (OCProvisionResult_t*)OICCalloc(noOfRiCalls, sizeof(OCProvisionResult_t));
912     if (aclData->resArr == NULL)
913     {
914         OICFree(aclData);
915         OCPayloadDestroy((OCPayload *)secPayload);
916         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
917         return OC_STACK_NO_MEMORY;
918     }
919     cbData.context = (void *)aclData;
920     cbData.cd = NULL;
921     OCMethod method = OC_REST_POST;
922     OCDoHandle handle = NULL;
923     OIC_LOG(DEBUG, TAG, "Sending ACL info to resource server");
924     OCStackResult ret = OCDoResource(&handle, method, query,
925             &selectedDeviceInfo->endpoint, (OCPayload*)secPayload,
926             selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
927     if (ret != OC_STACK_OK)
928     {
929         OICFree(aclData->resArr);
930         OICFree(aclData);
931     }
932     VERIFY_SUCCESS(TAG, (OC_STACK_OK == ret), ERROR, OC_STACK_ERROR);
933     return OC_STACK_OK;
934 }
935
936 /**
937  * Internal Function to store results in result array during Direct-Pairing provisioning.
938  */
939 static void registerResultForDirectPairingProvisioning(PconfData_t *pconfData,
940                                              OCStackResult stackresult)
941 {
942    OIC_LOG_V(INFO, TAG, "Inside registerResultForDirectPairingProvisioning "
943            "pconfData->numOfResults is %d\n", pconfData->numOfResults);
944    memcpy(pconfData->resArr[(pconfData->numOfResults)].deviceId.id,
945           pconfData->deviceInfo->doxm->deviceID.id, UUID_LENGTH);
946    pconfData->resArr[(pconfData->numOfResults)].res = stackresult;
947    ++(pconfData->numOfResults);
948 }
949
950 /**
951  * Callback handler of SRPProvisionDirectPairing.
952  *
953  * @param[in] ctx             ctx value passed to callback from calling function.
954  * @param[in] UNUSED          handle to an invocation
955  * @param[in] clientResponse  Response from queries to remote servers.
956  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
957  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
958  */
959 static OCStackApplicationResult SRPProvisionDirectPairingCB(void *ctx, OCDoHandle UNUSED,
960                                                   OCClientResponse *clientResponse)
961 {
962     OIC_LOG_V(INFO, TAG, "Inside SRPProvisionDirectPairingCB.");
963     (void)UNUSED;
964     VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
965     PconfData_t *pconfData = (PconfData_t*)ctx;
966     OCProvisionResultCB resultCallback = pconfData->resultCallback;
967
968     if (clientResponse)
969     {
970         if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
971         {
972             registerResultForDirectPairingProvisioning(pconfData, OC_STACK_OK);
973             ((OCProvisionResultCB)(resultCallback))(pconfData->ctx, pconfData->numOfResults,
974                                                     pconfData->resArr,
975                                                     false);
976              OICFree(pconfData->resArr);
977              OICFree(pconfData);
978              return OC_STACK_DELETE_TRANSACTION;
979         }
980     }
981     registerResultForDirectPairingProvisioning(pconfData, OC_STACK_ERROR);
982     ((OCProvisionResultCB)(resultCallback))(pconfData->ctx, pconfData->numOfResults,
983                                             pconfData->resArr,
984                                             true);
985     OIC_LOG_V(ERROR, TAG, "SRPProvisionDirectPairingCB received Null clientResponse");
986     OICFree(pconfData->resArr);
987     OICFree(pconfData);
988     return OC_STACK_DELETE_TRANSACTION;
989 }
990
991 OCStackResult SRPProvisionDirectPairing(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
992         OicSecPconf_t *pconf, OCProvisionResultCB resultCallback)
993 {
994     VERIFY_NON_NULL(TAG, selectedDeviceInfo, ERROR,  OC_STACK_INVALID_PARAM);
995     VERIFY_NON_NULL(TAG, pconf, ERROR,  OC_STACK_INVALID_PARAM);
996     VERIFY_NON_NULL(TAG, resultCallback, ERROR,  OC_STACK_INVALID_CALLBACK);
997
998     // check direct-pairing capability
999     if (true != selectedDeviceInfo->doxm->dpc)
1000     {
1001         OIC_LOG(ERROR, TAG, "Resouce server does not have Direct-Pairing Capability ");
1002         return OC_STACK_UNAUTHORIZED_REQ;
1003     }
1004
1005     OicUuid_t provTooldeviceID =   {.id={0}};
1006     if (OC_STACK_OK != GetDoxmDeviceID(&provTooldeviceID))
1007     {
1008         OIC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
1009         return OC_STACK_ERROR;
1010     }
1011     memcpy(&pconf->rownerID, &provTooldeviceID, sizeof(OicUuid_t));
1012
1013     OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1014     if(!secPayload)
1015     {
1016         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1017         return OC_STACK_NO_MEMORY;
1018     }
1019     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1020
1021     if (OC_STACK_OK != PconfToCBORPayload(pconf, &(secPayload->securityData),
1022                 &(secPayload->payloadSize)))
1023     {
1024         OCPayloadDestroy((OCPayload*)secPayload);
1025         OIC_LOG(ERROR, TAG, "Failed to PconfToCborPayload");
1026         return OC_STACK_NO_MEMORY;
1027     }
1028     OIC_LOG(DEBUG, TAG, "Created payload for pconf set");
1029     OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1030
1031
1032     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1033     if(!PMGenerateQuery(true,
1034                 selectedDeviceInfo->endpoint.addr,
1035                 selectedDeviceInfo->securePort,
1036                 selectedDeviceInfo->connType,
1037                 query, sizeof(query), OIC_RSRC_PCONF_URI))
1038     {
1039         OIC_LOG(ERROR, TAG, "SRPProvisionDirectPairing : Failed to generate query");
1040         return OC_STACK_ERROR;
1041     }
1042     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1043
1044     OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};
1045     cbData.cb = &SRPProvisionDirectPairingCB;
1046     PconfData_t *pconfData = (PconfData_t *) OICCalloc(1, sizeof(PconfData_t));
1047     if (NULL == pconfData)
1048     {
1049         OCPayloadDestroy((OCPayload*)secPayload);
1050         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
1051         return OC_STACK_NO_MEMORY;
1052     }
1053     pconfData->deviceInfo = selectedDeviceInfo;
1054     pconfData->resultCallback = resultCallback;
1055     pconfData->numOfResults=0;
1056     pconfData->ctx = ctx;
1057     // call to provision PCONF to device1.
1058     int noOfRiCalls = 1;
1059     pconfData->resArr = (OCProvisionResult_t*)OICCalloc(noOfRiCalls, sizeof(OCProvisionResult_t));
1060     if (NULL == pconfData->resArr)
1061     {
1062         OICFree(pconfData);
1063         OCPayloadDestroy((OCPayload*)secPayload);
1064         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
1065         return OC_STACK_NO_MEMORY;
1066     }
1067     cbData.context = (void *)pconfData;
1068     cbData.cd = NULL;
1069     OCMethod method = OC_REST_POST;
1070     OCDoHandle handle = NULL;
1071     OIC_LOG(DEBUG, TAG, "Sending PCONF info to resource server");
1072     OCStackResult ret = OCDoResource(&handle, method, query,
1073             &selectedDeviceInfo->endpoint, (OCPayload*)secPayload,
1074             selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1075     if (OC_STACK_OK != ret)
1076     {
1077         OICFree(pconfData->resArr);
1078         OICFree(pconfData);
1079     }
1080     VERIFY_SUCCESS(TAG, (OC_STACK_OK == ret), ERROR, OC_STACK_ERROR);
1081     return OC_STACK_OK;
1082 }
1083
1084 static void DeleteUnlinkData_t(UnlinkData_t *unlinkData)
1085 {
1086     if (unlinkData)
1087     {
1088         OICFree(unlinkData->unlinkDev);
1089         OICFree(unlinkData->unlinkRes);
1090         OICFree(unlinkData);
1091     }
1092 }
1093
1094 static void registerResultForUnlinkDevices(UnlinkData_t *unlinkData, OCStackResult stackresult,
1095                                            IdxUnlinkRes_t idx)
1096 {
1097     if (NULL != unlinkData)
1098     {
1099         OIC_LOG_V(INFO, TAG, "Inside registerResultForUnlinkDevices unlinkData->numOfResults is %d\n",
1100                             unlinkData->numOfResults);
1101         OIC_LOG_V(INFO, TAG, "Stack result :: %d", stackresult);
1102
1103         OicUuid_t *pUuid = &unlinkData->unlinkRes[(unlinkData->numOfResults)].deviceId;
1104
1105         // Set result in the result array according to the position (devNum).
1106         if (idx != IDX_DB_UPDATE_RES)
1107         {
1108             memcpy(pUuid->id, unlinkData->unlinkDev[idx].doxm->deviceID.id, sizeof(pUuid->id));
1109         }
1110         else
1111         {   // When deivce ID is 000... this means it's the result of database update.
1112             memset(pUuid->id, 0, sizeof(pUuid->id));
1113         }
1114         unlinkData->unlinkRes[(unlinkData->numOfResults)].res = stackresult;
1115         ++(unlinkData->numOfResults);
1116         OIC_LOG (INFO, TAG, "Out registerResultForUnlinkDevices");
1117     }
1118 }
1119
1120 static OCStackResult SendDeleteCredentialRequest(void* ctx,
1121                                                  OCClientResponseHandler respHandler,
1122                                                  const OCProvisionDev_t* revokedDev,
1123                                                  const OCProvisionDev_t* destDev)
1124 {
1125     OIC_LOG(DEBUG, TAG, "IN SendDeleteCredentialRequest");
1126
1127     if (NULL == ctx || NULL == respHandler || NULL == revokedDev || NULL == destDev)
1128     {
1129         return OC_STACK_INVALID_PARAM;
1130     }
1131
1132     char *subID = NULL;
1133     OCStackResult ret = ConvertUuidToStr(&revokedDev->doxm->deviceID, &subID);
1134     if(OC_STACK_OK != ret)
1135     {
1136         OIC_LOG(ERROR, TAG, "SendDeleteCredentialRequest : Failed to canonical UUID encoding");
1137         return OC_STACK_ERROR;
1138     }
1139
1140     char reqBuf[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1141     int snRet = 0;
1142                     //coaps://0.0.0.0:5684/oic/sec/cred?subjectid=(Canonical ENCODED UUID)
1143     snRet = snprintf(reqBuf, sizeof(reqBuf), SRP_FORM_DELETE_CREDENTIAL, destDev->endpoint.addr,
1144                      destDev->securePort, OIC_RSRC_CRED_URI, OIC_JSON_SUBJECTID_NAME, subID);
1145     OICFree(subID);
1146     if (snRet < 0)
1147     {
1148         OIC_LOG_V(ERROR, TAG, "SendDeleteCredentialRequest : Error (snprintf) %d\n", snRet);
1149         return OC_STACK_ERROR;
1150     }
1151     else if ((size_t)snRet >= sizeof(reqBuf))
1152     {
1153         OIC_LOG_V(ERROR, TAG, "SendDeleteCredentialRequest : Truncated (snprintf) %d\n", snRet);
1154         return OC_STACK_ERROR;
1155     }
1156
1157     OCCallbackData cbData;
1158     memset(&cbData, 0, sizeof(cbData));
1159     cbData.context = ctx;
1160     cbData.cb = respHandler;
1161     cbData.cd = NULL;
1162     OIC_LOG_V(INFO, TAG, "URI: %s",reqBuf);
1163
1164     OIC_LOG(DEBUG, TAG, "Sending remove credential request to resource server");
1165
1166     ret = OCDoResource(NULL, OC_REST_DELETE, reqBuf,
1167                                      &destDev->endpoint, NULL,
1168                                      CT_ADAPTER_IP, OC_HIGH_QOS, &cbData, NULL, 0);
1169     if (OC_STACK_OK != ret)
1170     {
1171         OIC_LOG_V(ERROR, TAG, "SendDeleteCredentialRequest : Error in OCDoResource %d", ret);
1172     }
1173     OIC_LOG(DEBUG, TAG, "OUT SendDeleteCredentialRequest");
1174
1175     return ret;
1176 }
1177
1178 static OCStackResult SendDeleteACLRequest(void* ctx,
1179                                                  OCClientResponseHandler respHandler,
1180                                                  const OCProvisionDev_t* revokedDev,
1181                                                  const OCProvisionDev_t* destDev)
1182 {
1183     OIC_LOG(DEBUG, TAG, "IN SendDeleteACLRequest");
1184
1185     if (NULL == ctx || NULL == respHandler || NULL == revokedDev || NULL == destDev)
1186     {
1187         return OC_STACK_INVALID_PARAM;
1188     }
1189
1190     char *subID = NULL;
1191     OCStackResult ret = ConvertUuidToStr(&revokedDev->doxm->deviceID, &subID);
1192     if(OC_STACK_OK != ret)
1193     {
1194         OIC_LOG(ERROR, TAG, "SendDeleteACLRequest : Failed to canonical UUID encoding");
1195         return OC_STACK_ERROR;
1196     }
1197
1198     char reqBuf[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1199     int snRet = 0;
1200                     //coaps://0.0.0.0:5684/oic/sec/acl?subjectuuid=(Canonical ENCODED UUID)
1201     snRet = snprintf(reqBuf, sizeof(reqBuf), SRP_FORM_DELETE_CREDENTIAL, destDev->endpoint.addr,
1202                      destDev->securePort, OIC_RSRC_ACL_URI, OIC_JSON_SUBJECTID_NAME, subID);
1203     OICFree(subID);
1204     if (snRet < 0)
1205     {
1206         OIC_LOG_V(ERROR, TAG, "SendDeleteACLRequest : Error (snprintf) %d\n", snRet);
1207         return OC_STACK_ERROR;
1208     }
1209     else if ((size_t)snRet >= sizeof(reqBuf))
1210     {
1211         OIC_LOG_V(ERROR, TAG, "SendDeleteACLRequest : Truncated (snprintf) %d\n", snRet);
1212         return OC_STACK_ERROR;
1213     }
1214
1215     OCCallbackData cbData;
1216     memset(&cbData, 0, sizeof(cbData));
1217     cbData.context = ctx;
1218     cbData.cb = respHandler;
1219     cbData.cd = NULL;
1220     OIC_LOG_V(INFO, TAG, "URI: %s",reqBuf);
1221
1222     OIC_LOG(DEBUG, TAG, "Sending remove ACL request to resource server");
1223
1224     ret = OCDoResource(NULL, OC_REST_DELETE, reqBuf,
1225                                      &destDev->endpoint, NULL,
1226                                      CT_ADAPTER_IP, OC_HIGH_QOS, &cbData, NULL, 0);
1227     if (OC_STACK_OK != ret)
1228     {
1229         OIC_LOG_V(ERROR, TAG, "SendDeleteACLRequest : Error in OCDoResource %d", ret);
1230     }
1231     OIC_LOG(DEBUG, TAG, "OUT SendDeleteACLRequest");
1232
1233     return ret;
1234 }
1235
1236 /**
1237  * Callback handler of unlink second device.
1238  *
1239  * @param[in] ctx             ctx value passed to callback from calling function.
1240  * @param[in] handle          handle to an invocation
1241  * @param[in] clientResponse  Response from queries to remote servers.
1242  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction and
1243  *          OC_STACK_KEEP_TRANSACTION to keep it.
1244  */
1245 static OCStackApplicationResult SRPUnlinkDevice2CB(void *unlinkCtx, OCDoHandle handle,
1246         OCClientResponse *clientResponse)
1247 {
1248     (void) handle;
1249     OIC_LOG(DEBUG, TAG, "IN SRPUnlinkDevice2CB");
1250     VERIFY_NON_NULL(TAG, unlinkCtx, ERROR, OC_STACK_DELETE_TRANSACTION);
1251     UnlinkData_t* unlinkData = (UnlinkData_t*)unlinkCtx;
1252
1253     if (clientResponse)
1254     {
1255         OIC_LOG(DEBUG, TAG, "Valid client response for device 2");
1256         registerResultForUnlinkDevices(unlinkData, clientResponse->result, IDX_SECOND_DEVICE_RES);
1257
1258         if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
1259         {
1260             OIC_LOG(DEBUG, TAG, "Credential of device2 revoked");
1261         }
1262         else
1263         {
1264             OIC_LOG(ERROR, TAG, "Unable to delete credential information from device 2");
1265             unlinkData->resultCallback(unlinkData->ctx,
1266                                        unlinkData->numOfResults, unlinkData->unlinkRes, true);
1267             goto error;
1268         }
1269     }
1270     else
1271     {
1272         registerResultForUnlinkDevices(unlinkData, OC_STACK_INVALID_REQUEST_HANDLE,
1273                                        IDX_SECOND_DEVICE_RES);
1274         unlinkData->resultCallback(unlinkData->ctx,
1275                                    unlinkData->numOfResults, unlinkData->unlinkRes, true);
1276         OIC_LOG(ERROR, TAG, "SRPUnlinkDevice2CB received Null clientResponse");
1277         goto error;
1278     }
1279
1280     //Update provisioning DB when succes case.
1281     if (OC_STACK_OK != PDMUnlinkDevices(&unlinkData->unlinkDev[0].doxm->deviceID,
1282                                        &unlinkData->unlinkDev[1].doxm->deviceID))
1283     {
1284         OIC_LOG(FATAL, TAG, "All requests are successfully done but update provisioning DB FAILED.");
1285         registerResultForUnlinkDevices(unlinkData, OC_STACK_INCONSISTENT_DB, IDX_DB_UPDATE_RES);
1286         unlinkData->resultCallback(unlinkData->ctx,
1287                                    unlinkData->numOfResults, unlinkData->unlinkRes, true);
1288         goto error;
1289     }
1290     unlinkData->resultCallback(unlinkData->ctx, unlinkData->numOfResults, unlinkData->unlinkRes,
1291                                false);
1292
1293 error:
1294     DeleteUnlinkData_t(unlinkData);
1295     OIC_LOG(DEBUG, TAG, "OUT SRPUnlinkDevice2CB");
1296     return OC_STACK_DELETE_TRANSACTION;
1297
1298 }
1299
1300 /**
1301  * Callback handler of unlink first device.
1302  *
1303  * @param[in] ctx             ctx value passed to callback from calling function.
1304  * @param[in] handle          handle to an invocation
1305  * @param[in] clientResponse  Response from queries to remote servers.
1306  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction and
1307  *          OC_STACK_KEEP_TRANSACTION to keep it.
1308  */
1309 static OCStackApplicationResult SRPUnlinkDevice1CB(void *unlinkCtx, OCDoHandle handle,
1310         OCClientResponse *clientResponse)
1311 {
1312     OIC_LOG_V(INFO, TAG, "Inside SRPUnlinkDevice1CB ");
1313     VERIFY_NON_NULL(TAG, unlinkCtx, ERROR, OC_STACK_DELETE_TRANSACTION);
1314     UnlinkData_t* unlinkData = (UnlinkData_t*)unlinkCtx;
1315     (void) handle;
1316
1317     if (clientResponse)
1318     {
1319         OIC_LOG(DEBUG, TAG, "Valid client response for device 1");
1320         registerResultForUnlinkDevices(unlinkData, clientResponse->result, IDX_FIRST_DEVICE_RES);
1321
1322         if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
1323         {
1324             OIC_LOG(DEBUG, TAG, "Credential of device 1 is revoked");
1325
1326             // Second revocation request to second device.
1327             OCStackResult res = SendDeleteCredentialRequest((void*)unlinkData, &SRPUnlinkDevice2CB,
1328                                                     &unlinkData->unlinkDev[0],
1329                                                     &unlinkData->unlinkDev[1] /*Dest*/);
1330             OIC_LOG_V(DEBUG, TAG, "Credential revocation request device 2, result :: %d",res);
1331             if (OC_STACK_OK != res)
1332             {
1333                  OIC_LOG(ERROR, TAG, "Error while sending revocation request for device 2");
1334                  registerResultForUnlinkDevices(unlinkData, OC_STACK_INVALID_REQUEST_HANDLE,
1335                                                 IDX_SECOND_DEVICE_RES);
1336                  unlinkData->resultCallback(unlinkData->ctx,
1337                                             unlinkData->numOfResults, unlinkData->unlinkRes, true);
1338                  goto error;
1339             }
1340             else
1341             {
1342                 OIC_LOG(DEBUG, TAG, "Request for credential revocation successfully sent");
1343                 return OC_STACK_DELETE_TRANSACTION;
1344             }
1345         }
1346         else
1347         {
1348             OIC_LOG(ERROR, TAG, "Unable to delete credential information from device 1");
1349
1350             unlinkData->resultCallback(unlinkData->ctx, unlinkData->numOfResults,
1351                                             unlinkData->unlinkRes, true);
1352             goto error;
1353         }
1354     }
1355     else
1356     {
1357         OIC_LOG(DEBUG, TAG, "Invalid response from server");
1358         registerResultForUnlinkDevices(unlinkData, OC_STACK_INVALID_REQUEST_HANDLE,
1359                                        IDX_FIRST_DEVICE_RES );
1360         unlinkData->resultCallback(unlinkData->ctx,
1361                                    unlinkData->numOfResults, unlinkData->unlinkRes,
1362                                    true);
1363         OIC_LOG(ERROR, TAG, "SRPUnlinkDevice1CB received Null clientResponse");
1364     }
1365
1366 error:
1367     OIC_LOG_V(INFO, TAG, "Out SRPUnlinkDevice1CB");
1368     DeleteUnlinkData_t(unlinkData);
1369     return OC_STACK_DELETE_TRANSACTION;
1370 }
1371
1372 /*
1373 * Function to unlink devices.
1374 * This function will remove the credential & relationship between the two devices.
1375 *
1376 * @param[in] ctx Application context would be returned in result callback
1377 * @param[in] pTargetDev1 first device information to be unlinked.
1378 * @param[in] pTargetDev2 second device information to be unlinked.
1379 * @param[in] resultCallback callback provided by API user, callback will be called when
1380 *            device unlink is finished.
1381  * @return  OC_STACK_OK in case of success and other value otherwise.
1382 */
1383 OCStackResult SRPUnlinkDevices(void* ctx,
1384                                const OCProvisionDev_t* pTargetDev1,
1385                                const OCProvisionDev_t* pTargetDev2,
1386                                OCProvisionResultCB resultCallback)
1387 {
1388     OIC_LOG(INFO, TAG, "IN SRPUnlinkDevices");
1389
1390     if (!pTargetDev1 || !pTargetDev2 || !pTargetDev1->doxm || !pTargetDev2->doxm)
1391     {
1392         OIC_LOG(INFO, TAG, "SRPUnlinkDevices : NULL parameters");
1393         return OC_STACK_INVALID_PARAM;
1394     }
1395     if (!resultCallback)
1396     {
1397         OIC_LOG(INFO, TAG, "SRPUnlinkDevices : NULL Callback");
1398         return OC_STACK_INVALID_CALLBACK;
1399     }
1400     if (0 == memcmp(&pTargetDev1->doxm->deviceID, &pTargetDev2->doxm->deviceID, sizeof(OicUuid_t)))
1401     {
1402         OIC_LOG(INFO, TAG, "SRPUnlinkDevices : Same device ID");
1403         return OC_STACK_INVALID_PARAM;
1404     }
1405
1406     OIC_LOG(INFO, TAG, "Unlinking following devices: ");
1407     PMPrintOCProvisionDev(pTargetDev1);
1408     PMPrintOCProvisionDev(pTargetDev2);
1409
1410     // Mark the link status stale
1411     OCStackResult res = PDMSetLinkStale(&pTargetDev1->doxm->deviceID, &pTargetDev2->doxm->deviceID);
1412     if (OC_STACK_OK != res)
1413     {
1414         OIC_LOG(FATAL, TAG, "unable to update DB. Try again.");
1415         return res;
1416     }
1417
1418     UnlinkData_t* unlinkData = (UnlinkData_t*)OICCalloc(1, sizeof(UnlinkData_t));
1419     VERIFY_NON_NULL(TAG, unlinkData, ERROR, OC_STACK_NO_MEMORY);
1420
1421     //Initialize unlink data
1422     unlinkData->ctx = ctx;
1423     unlinkData->unlinkDev = (OCProvisionDev_t*)OICCalloc(2, sizeof(OCProvisionDev_t));
1424     if (NULL == unlinkData->unlinkDev)
1425     {
1426         OIC_LOG(ERROR, TAG, "Memory allocation failed");
1427         res = OC_STACK_NO_MEMORY;
1428         goto error;
1429     }
1430
1431     unlinkData->unlinkRes = (OCProvisionResult_t*)OICCalloc(3, sizeof(OCProvisionResult_t));
1432     if (NULL == unlinkData->unlinkRes)
1433     {
1434         OIC_LOG(ERROR, TAG, "Memory allocation failed");
1435         res = OC_STACK_NO_MEMORY;
1436         goto error;
1437     }
1438
1439     memcpy(&unlinkData->unlinkDev[0], pTargetDev1, sizeof(OCProvisionDev_t));
1440     memcpy(&unlinkData->unlinkDev[1], pTargetDev2, sizeof(OCProvisionDev_t));
1441
1442     unlinkData->numOfResults = 0;
1443     unlinkData->resultCallback = resultCallback;
1444
1445     res = SendDeleteCredentialRequest((void*)unlinkData, &SRPUnlinkDevice1CB,
1446                                        &unlinkData->unlinkDev[1], &unlinkData->unlinkDev[0]);
1447     if (OC_STACK_OK != res)
1448     {
1449         OIC_LOG(ERROR, TAG, "SRPUnlinkDevices : SendDeleteCredentialRequest failed");
1450         goto error;
1451     }
1452
1453     return res;
1454
1455 error:
1456     OIC_LOG(INFO, TAG, "OUT SRPUnlinkDevices");
1457     DeleteUnlinkData_t(unlinkData);
1458     return res;
1459 }
1460
1461 static void DeleteRemoveData_t(RemoveData_t* pRemoveData)
1462 {
1463     if (pRemoveData)
1464     {
1465         OICFree(pRemoveData->revokeTargetDev);
1466         OCDeleteDiscoveredDevices(pRemoveData->linkedDevList);
1467         OICFree(pRemoveData->removeRes);
1468         OICFree(pRemoveData);
1469     }
1470 }
1471
1472 static void registerResultForRemoveDevice(RemoveData_t *removeData, OicUuid_t *pLinkedDevId,
1473                                           OCStackResult stackresult, bool hasError)
1474 {
1475     OIC_LOG_V(INFO, TAG, "Inside registerResultForRemoveDevice removeData->numOfResults is %zu\n",
1476                          removeData->numOfResults + 1);
1477     if (pLinkedDevId)
1478     {
1479         memcpy(removeData->removeRes[(removeData->numOfResults)].deviceId.id,
1480                &pLinkedDevId->id, sizeof(pLinkedDevId->id));
1481     }
1482     else
1483     {
1484         memset(removeData->removeRes[(removeData->numOfResults)].deviceId.id,
1485                0, sizeof(pLinkedDevId->id) );
1486     }
1487     removeData->removeRes[(removeData->numOfResults)].res = stackresult;
1488     removeData->hasError = hasError;
1489     ++(removeData->numOfResults);
1490
1491     // If we get suffcient result from linked devices, we have to call user callback and do free
1492     if (removeData->sizeOfResArray == removeData->numOfResults)
1493     {
1494         if(!removeData->hasError)
1495         {
1496             // Remove device info from prvisioning database
1497             if (OC_STACK_OK != PDMDeleteDevice(&removeData->revokeTargetDev->doxm->deviceID))
1498             {
1499                 OIC_LOG(ERROR, TAG, "ResultForRemoveDevice : Failed to remove device in PDM.");
1500                 removeData->hasError = true;
1501             }
1502         }
1503         removeData->resultCallback(removeData->ctx, removeData->numOfResults, removeData->removeRes,
1504                                    removeData->hasError);
1505         DeleteRemoveData_t(removeData);
1506     }
1507  }
1508
1509 static void registerResultForResetDevice(RemoveData_t *removeData, OicUuid_t *pLinkedDevId,
1510                                           OCStackResult stackresult, bool hasError)
1511 {
1512     OIC_LOG_V(INFO, TAG, "Inside registerResultForResetDevice removeData->numOfResults is %zu\n",
1513                          removeData->numOfResults + 1);
1514     if (pLinkedDevId)
1515     {
1516         memcpy(removeData->removeRes[(removeData->numOfResults)].deviceId.id,
1517                &pLinkedDevId->id, sizeof(pLinkedDevId->id));
1518     }
1519     else
1520     {
1521         memset(removeData->removeRes[(removeData->numOfResults)].deviceId.id,
1522                0, sizeof(pLinkedDevId->id) );
1523     }
1524     removeData->removeRes[(removeData->numOfResults)].res = stackresult;
1525     removeData->hasError = hasError;
1526     ++(removeData->numOfResults);
1527
1528     // If we get suffcient result from linked devices, we have to call user callback and do free
1529     if (removeData->sizeOfResArray == removeData->numOfResults)
1530     {
1531         removeData->resultCallback(removeData->ctx, removeData->numOfResults, removeData->removeRes,
1532                                    removeData->hasError);
1533         DeleteRemoveData_t(removeData);
1534     }
1535 }
1536
1537 /**
1538  * Callback handler of unlink first device.
1539  *
1540  * @param[in] ctx             ctx value passed to callback from calling function.
1541  * @param[in] handle          handle to an invocation
1542  * @param[in] clientResponse  Response from queries to remote servers.
1543  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
1544  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
1545  */
1546 static OCStackApplicationResult SRPRemoveDeviceCB(void *delDevCtx, OCDoHandle handle,
1547         OCClientResponse *clientResponse)
1548 {
1549     //Update the delete credential into delete device context
1550     //Save the deleted status in delDevCtx
1551     (void)handle;
1552     OIC_LOG_V(INFO, TAG, "Inside SRPRemoveDeviceCB.");
1553     VERIFY_NON_NULL(TAG, delDevCtx, ERROR, OC_STACK_DELETE_TRANSACTION);
1554     OCStackResult res = OC_STACK_ERROR;
1555
1556     RemoveData_t* removeData = (RemoveData_t*)delDevCtx;
1557
1558     if (clientResponse)
1559     {
1560         OicUuid_t revDevUuid = {.id={0}};
1561         if(UUID_LENGTH == clientResponse->identity.id_length)
1562         {
1563             memcpy(revDevUuid.id, clientResponse->identity.id, sizeof(revDevUuid.id));
1564             if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
1565             {
1566                 res = PDMUnlinkDevices(&removeData->revokeTargetDev->doxm->deviceID, &revDevUuid);
1567                 if (OC_STACK_OK != res)
1568                 {
1569                     OIC_LOG(ERROR, TAG, "PDMSetLinkStale() FAIL: PDB is an obsolete one.");
1570                            registerResultForRemoveDevice(removeData, &revDevUuid,
1571                            OC_STACK_INCONSISTENT_DB, true);
1572
1573                     return OC_STACK_DELETE_TRANSACTION;
1574                 }
1575
1576                 registerResultForRemoveDevice(removeData, &revDevUuid,
1577                                               OC_STACK_RESOURCE_DELETED, false);
1578             }
1579             else
1580             {
1581                 registerResultForRemoveDevice(removeData, &revDevUuid,
1582                                               clientResponse->result, true);
1583                 OIC_LOG(ERROR, TAG, "Unexpected result from DELETE credential request!");
1584             }
1585         }
1586         else
1587         {
1588             OIC_LOG_V(WARNING, TAG, "Incorrect length of device UUID was sent from %s:%d",
1589                      clientResponse->devAddr.addr, clientResponse->devAddr.port);
1590
1591             if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
1592             {
1593                 /**
1594                   * Since server's credential was deleted,
1595                   * register result as OC_STACK_INCONSISTENT_DB with NULL UUID.
1596                   */
1597                 OIC_LOG_V(ERROR, TAG, "But server's credential was deleted.");
1598                 registerResultForRemoveDevice(removeData, NULL, OC_STACK_INCONSISTENT_DB, true);
1599             }
1600             else
1601             {
1602                 registerResultForRemoveDevice(removeData, NULL, clientResponse->result, true);
1603             }
1604         }
1605     }
1606     else
1607     {
1608         registerResultForRemoveDevice(removeData, NULL, OC_STACK_ERROR, true);
1609         OIC_LOG(ERROR, TAG, "SRPRemoveDevices received Null clientResponse");
1610     }
1611
1612
1613     return OC_STACK_DELETE_TRANSACTION;
1614 }
1615
1616 /**
1617  * Callback handler of reset device.
1618  *
1619  * @param[in] ctx             ctx value passed to callback from calling function.
1620  * @param[in] handle          handle to an invocation
1621  * @param[in] clientResponse  Response from queries to remote servers.
1622  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
1623  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
1624  */
1625 static OCStackApplicationResult SRPSyncDeviceCredCB(void *delDevCtx, OCDoHandle handle,
1626         OCClientResponse *clientResponse)
1627 {
1628     //Update the delete credential into delete device context
1629     //Save the deleted status in delDevCtx
1630     (void)handle;
1631     OIC_LOG_V(INFO, TAG, "Inside SRPSyncDeviceCredCB.");
1632     VERIFY_NON_NULL(TAG, delDevCtx, ERROR, OC_STACK_DELETE_TRANSACTION);
1633     OCStackResult res = OC_STACK_ERROR;
1634
1635     RemoveData_t* removeData = (RemoveData_t*)delDevCtx;
1636     OCProvisionDev_t * pTargetDev = PMCloneOCProvisionDev(removeData->revokeTargetDev);
1637     OCProvisionResultCB resultCallback = removeData->resultCallback;
1638     if (clientResponse)
1639     {
1640         OicUuid_t revDevUuid = {.id={0}};
1641         if(UUID_LENGTH == clientResponse->identity.id_length)
1642         {
1643             memcpy(revDevUuid.id, clientResponse->identity.id, sizeof(revDevUuid.id));
1644             if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
1645             {
1646                 res = PDMUnlinkDevices(&removeData->revokeTargetDev->doxm->deviceID, &revDevUuid);
1647                 if (OC_STACK_OK != res)
1648                 {
1649                     OIC_LOG(ERROR, TAG, "PDMSetLinkStale() FAIL: PDB is an obsolete one.");
1650                            registerResultForResetDevice(removeData, &revDevUuid,
1651                            OC_STACK_INCONSISTENT_DB, true);
1652
1653                     return OC_STACK_DELETE_TRANSACTION;
1654                 }
1655
1656                 registerResultForResetDevice(removeData, &revDevUuid,
1657                                               OC_STACK_RESOURCE_DELETED, false);
1658             }
1659             else
1660             {
1661                 registerResultForResetDevice(removeData, &revDevUuid,
1662                                               clientResponse->result, false);
1663                 OIC_LOG(ERROR, TAG, "Unexpected result from DELETE credential request!");
1664             }
1665         }
1666         else
1667         {
1668             OIC_LOG_V(WARNING, TAG, "Incorrect length of device UUID was sent from %s:%d",
1669                      clientResponse->devAddr.addr, clientResponse->devAddr.port);
1670
1671             if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
1672             {
1673                 /**
1674                   * Since server's credential was deleted,
1675                   * register result as OC_STACK_INCONSISTENT_DB with NULL UUID.
1676                   */
1677                 OIC_LOG_V(ERROR, TAG, "But server's credential was deleted.");
1678                 registerResultForResetDevice(removeData, NULL, OC_STACK_INCONSISTENT_DB, true);
1679             }
1680             else
1681             {
1682                 registerResultForResetDevice(removeData, NULL, clientResponse->result, true);
1683             }
1684         }
1685     }
1686     else
1687     {
1688         registerResultForResetDevice(removeData, NULL, OC_STACK_ERROR, true);
1689         OIC_LOG(ERROR, TAG, "SRPSyncDevice received Null clientResponse");
1690     }
1691
1692     SRPResetDevice(pTargetDev, resultCallback);
1693
1694     return OC_STACK_DELETE_TRANSACTION;
1695 }
1696
1697 /**
1698  * Callback handler of reset device sync-up
1699  *
1700  * @param[in] ctx             ctx value passed to callback from calling function.
1701  * @param[in] handle          handle to an invocation
1702  * @param[in] clientResponse  Response from queries to remote servers.
1703  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
1704  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
1705  */
1706 static OCStackApplicationResult SRPSyncDeviceACLCB(void *ctx, OCDoHandle handle,
1707         OCClientResponse *clientResponse)
1708 {
1709     return OC_STACK_DELETE_TRANSACTION;
1710 }
1711
1712 /**
1713  * Callback handler of device remote reset.
1714  *
1715  * @param[in] ctx             ctx value passed to callback from calling function.
1716  * @param[in] handle          handle to an invocation
1717  * @param[in] clientResponse  Response from queries to remote servers.
1718  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
1719  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
1720  */
1721 static OCStackApplicationResult SRPResetDeviceCB(void *ctx, OCDoHandle handle,
1722         OCClientResponse *clientResponse)
1723 {
1724     OIC_LOG(DEBUG, TAG, "IN SRPResetDeviceCB");
1725     if(OC_STACK_OK == clientResponse->result)
1726     {
1727         OIC_LOG(DEBUG, TAG, "Change Target Device Pstat Cm SUCCEEDED");
1728     }
1729
1730     // Delete Cred and ACL related to the target device.
1731     const OicSecCred_t *cred = NULL;
1732     OCProvisionDev_t * pTargetDev = (OCProvisionDev_t *)ctx;
1733     cred = GetCredResourceData(&pTargetDev->doxm->deviceID);
1734     if (cred == NULL)
1735     {
1736         OIC_LOG(ERROR, TAG, "OCResetDevice : Failed to get credential of target device.");
1737         goto error;
1738     }
1739
1740     OCStackResult res = RemoveCredential(&cred->subject);
1741     if (res != OC_STACK_RESOURCE_DELETED && res != OC_STACK_NO_RESOURCE)
1742     {
1743         OIC_LOG(ERROR, TAG, "OCResetDevice : Failed to remove credential.");
1744         goto error;
1745     }
1746
1747     res = RemoveACE(&cred->subject, NULL);
1748     if (res != OC_STACK_RESOURCE_DELETED && res != OC_STACK_NO_RESOURCE)
1749     {
1750         OIC_LOG(ERROR, TAG, "OCResetDevice : Failed to remove ACL.");
1751         goto error;
1752     }
1753     if (OC_STACK_OK != PDMDeleteDevice(&pTargetDev->doxm->deviceID))
1754     {
1755         OIC_LOG(ERROR, TAG, "OCResetDevice : Failed to delete device from PDM");
1756     }
1757
1758     //Close the DTLS session of the reset device.
1759     CAEndpoint_t* endpoint = (CAEndpoint_t *)&clientResponse->devAddr;
1760     CAResult_t caResult = CACloseDtlsSession(endpoint);
1761     if(CA_STATUS_OK != caResult)
1762     {
1763         OIC_LOG_V(WARNING, TAG, "OCResetDevice : Failed to close DTLS session : %d", caResult);
1764     }
1765
1766     /**
1767      * If there is no linked device, PM does not send any request.
1768      * So we should directly invoke the result callback to inform the result of OCResetDevice.
1769      */
1770     if(OC_STACK_NO_RESOURCE == res)
1771     {
1772         res = OC_STACK_OK;
1773     }
1774
1775 error:
1776     OICFree(pTargetDev);
1777     return OC_STACK_DELETE_TRANSACTION;
1778
1779 }
1780
1781 static OCStackResult GetListofDevToReqDeleteCred(const OCProvisionDev_t* pRevokeTargetDev,
1782                                                  OCProvisionDev_t* pOwnedDevList,
1783                                                  OCUuidList_t* pLinkedUuidList,
1784                                                  OCProvisionDev_t** ppLinkedDevList,
1785                                                  size_t *numOfLinkedDev)
1786 {
1787     // pOwnedDevList could be NULL. It means no alived and owned device now.
1788     if (pRevokeTargetDev == NULL || pLinkedUuidList == NULL ||\
1789         ppLinkedDevList == NULL || numOfLinkedDev == NULL)
1790     {
1791         return OC_STACK_INVALID_PARAM;
1792     }
1793
1794     size_t cnt = 0;
1795     OCUuidList_t *curUuid = NULL, *tmpUuid = NULL;
1796     LL_FOREACH_SAFE(pLinkedUuidList, curUuid, tmpUuid)
1797     {
1798         // Mark the link status stale.
1799         OCStackResult res = PDMSetLinkStale(&curUuid->dev, &pRevokeTargetDev->doxm->deviceID);
1800         if (OC_STACK_OK != res)
1801         {
1802             OIC_LOG(FATAL, TAG, "PDMSetLinkStale() FAIL: PDB is an obsolete one.");
1803             return OC_STACK_INCONSISTENT_DB;
1804         }
1805
1806         if (pOwnedDevList)
1807         {
1808             // If this linked device is alive (power-on), add the deivce to the list.
1809             OCProvisionDev_t *curDev = NULL, *tmpDev = NULL;
1810             LL_FOREACH_SAFE(pOwnedDevList, curDev, tmpDev)
1811             {
1812                 if (memcmp(curDev->doxm->deviceID.id, curUuid->dev.id, sizeof(curUuid->dev.id)) == 0)
1813                 {
1814                     OCProvisionDev_t* targetDev = PMCloneOCProvisionDev(curDev);
1815                     if (NULL == targetDev)
1816                     {
1817                         OIC_LOG(ERROR, TAG, "SRPRemoveDevice : Cloning OCProvisionDev_t Failed.");
1818                         return OC_STACK_NO_MEMORY;
1819                     }
1820
1821                     LL_PREPEND(*ppLinkedDevList, targetDev);
1822                     cnt++;
1823                     break;
1824                 }
1825             }
1826         }
1827     }
1828     *numOfLinkedDev = cnt;
1829     return OC_STACK_OK;
1830 }
1831
1832 /*
1833 * Function to device revocation
1834 * This function will remove credential of target device from all devices in subnet.
1835 *
1836 * @param[in] ctx Application context would be returned in result callback
1837 * @param[in] waitTimeForOwnedDeviceDiscovery Maximum wait time for owned device discovery.(seconds)
1838 * @param[in] pTargetDev Device information to be revoked.
1839 * @param[in] resultCallback callback provided by API user, callback will be called when
1840 *            credential revocation is finished.
1841 * @return  OC_STACK_OK in case of success and other value otherwise.
1842 *          If OC_STACK_OK is returned, the caller of this API should wait for callback.
1843 *          OC_STACK_CONTINUE means operation is success but no request is need to be initiated.
1844 */
1845 OCStackResult SRPRemoveDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDiscovery,
1846                              const OCProvisionDev_t* pTargetDev, OCProvisionResultCB resultCallback)
1847 {
1848     OIC_LOG(INFO, TAG, "IN SRPRemoveDevice");
1849
1850     if (!pTargetDev  || 0 == waitTimeForOwnedDeviceDiscovery)
1851     {
1852         OIC_LOG(INFO, TAG, "SRPRemoveDevice : NULL parameters");
1853         return OC_STACK_INVALID_PARAM;
1854     }
1855     if (!resultCallback)
1856     {
1857         OIC_LOG(INFO, TAG, "SRPRemoveDevice : NULL Callback");
1858         return OC_STACK_INVALID_CALLBACK;
1859     }
1860
1861     // Declare variables in here to handle error cases with goto statement.
1862     OCProvisionDev_t* pOwnedDevList = NULL;
1863     OCProvisionDev_t* pLinkedDevList = NULL;
1864     RemoveData_t* removeData = NULL;
1865
1866     //1. Find all devices that has a credential of the revoked device
1867     OCUuidList_t* pLinkedUuidList = NULL;
1868     size_t numOfDevices = 0;
1869     OCStackResult res = OC_STACK_ERROR;
1870     res = PDMGetLinkedDevices(&pTargetDev->doxm->deviceID, &pLinkedUuidList, &numOfDevices);
1871     if (OC_STACK_OK != res)
1872     {
1873         OIC_LOG(ERROR, TAG, "SRPRemoveDevice : Failed to get linked devices information");
1874         return res;
1875     }
1876     // if there is no related device, we can skip further process.
1877     if (0 == numOfDevices)
1878     {
1879         OIC_LOG(DEBUG, TAG, "SRPRemoveDevice : No linked device found.");
1880         res = OC_STACK_CONTINUE;
1881         goto error;
1882     }
1883
1884     //2. Find owned device from the network
1885     res = PMDeviceDiscovery(waitTimeForOwnedDeviceDiscovery, true, &pOwnedDevList);
1886     if (OC_STACK_OK != res)
1887     {
1888         OIC_LOG(ERROR, TAG, "SRPRemoveDevice : Failed to PMDeviceDiscovery");
1889         goto error;
1890     }
1891
1892     //3. Make a list of devices to send DELETE credential request
1893     //   by comparing owned devices from provisioning database with mutlicast discovery result.
1894     size_t numOfLinkedDev = 0;
1895     res = GetListofDevToReqDeleteCred(pTargetDev, pOwnedDevList, pLinkedUuidList,
1896                                       &pLinkedDevList, &numOfLinkedDev);
1897     if (OC_STACK_OK != res)
1898     {
1899         OIC_LOG(ERROR, TAG, "SRPRemoveDevice : GetListofDevToReqDeleteCred() failed");
1900         goto error;
1901     }
1902     if (0 == numOfLinkedDev) // This case means, there is linked device but it's not alive now.
1903     {                       // So we don't have to send request message.
1904         OIC_LOG(DEBUG, TAG, "SRPRemoveDevice : No alived & linked device found.");
1905         res = OC_STACK_CONTINUE;
1906         goto error;
1907     }
1908
1909     // 4. Prepare RemoveData Context data.
1910     removeData = (RemoveData_t*)OICCalloc(1, sizeof(RemoveData_t));
1911     if (!removeData)
1912     {
1913         OIC_LOG(ERROR, TAG, "SRPRemoveDevices : Failed to memory allocation");
1914         res = OC_STACK_NO_MEMORY;
1915         goto error;
1916     }
1917
1918     removeData->revokeTargetDev = PMCloneOCProvisionDev(pTargetDev);
1919     if (!removeData->revokeTargetDev)
1920     {
1921         OIC_LOG(ERROR, TAG, "SRPRemoveDevices : PMCloneOCProvisionDev Failed");
1922         res = OC_STACK_NO_MEMORY;
1923         goto error;
1924     }
1925
1926     removeData->removeRes =
1927         (OCProvisionResult_t*)OICCalloc(numOfLinkedDev, sizeof(OCProvisionResult_t));
1928     if (!removeData->removeRes)
1929     {
1930         OIC_LOG(ERROR, TAG, "SRPRemoveDevices : Failed to memory allocation");
1931         res = OC_STACK_NO_MEMORY;
1932         goto error;
1933     }
1934
1935     removeData->ctx = ctx;
1936     removeData->linkedDevList = pLinkedDevList;
1937     removeData->resultCallback = resultCallback;
1938     removeData->numOfResults = 0;
1939     removeData->sizeOfResArray = numOfLinkedDev;
1940     removeData->hasError = false;
1941
1942     // 5. Send DELETE credential request to linked devices.
1943     OCProvisionDev_t *curDev = NULL, *tmpDev = NULL;
1944     OCStackResult totalRes = OC_STACK_ERROR;  /* variable for checking request is sent or not */
1945     LL_FOREACH_SAFE(pLinkedDevList, curDev, tmpDev)
1946     {
1947         res = SendDeleteCredentialRequest((void*)removeData, &SRPRemoveDeviceCB,
1948                                            removeData->revokeTargetDev, curDev);
1949         if (OC_STACK_OK != res)
1950         {
1951             OIC_LOG_V(ERROR, TAG, "SRPRemoveDevice : Fail to send the DELETE credential request to\
1952                      %s:%u", curDev->endpoint.addr, curDev->endpoint.port);
1953         }
1954         else
1955         {
1956             totalRes = OC_STACK_OK; // This means at least one request is successfully sent.
1957         }
1958     }
1959
1960     PDMDestoryOicUuidLinkList(pLinkedUuidList); //TODO: Modify API name to have unified convention.
1961     PMDeleteDeviceList(pOwnedDevList);
1962     OIC_LOG(INFO, TAG, "OUT SRPRemoveDevice");
1963
1964     return totalRes; // Caller of this API should wait callback if totalRes == OC_STACK_OK.
1965
1966 error:
1967     PDMDestoryOicUuidLinkList(pLinkedUuidList);
1968     PMDeleteDeviceList(pOwnedDevList);
1969     PMDeleteDeviceList(pLinkedDevList);
1970     if (removeData)
1971     {
1972         OICFree(removeData->revokeTargetDev);
1973         OICFree(removeData->removeRes);
1974         OICFree(removeData);
1975     }
1976     OIC_LOG(INFO, TAG, "OUT ERROR case SRPRemoveDevice");
1977     return res;
1978 }
1979
1980 /*
1981 * Function to device revocation
1982 * This function will remove credential of target device from all devices in subnet.
1983 *
1984 * @param[in] ctx Application context would be returned in result callback
1985 * @param[in] pOwnedDevList List of owned devices
1986 * @param[in] pTargetDev Device information to be revoked.
1987 * @param[in] resultCallback callback provided by API user, callback will be called when
1988 *            credential revocation is finished.
1989 * @return  OC_STACK_OK in case of success and other value otherwise.
1990 *          If OC_STACK_OK is returned, the caller of this API should wait for callback.
1991 *          OC_STACK_CONTINUE means operation is success but no request is need to be initiated.
1992 */
1993 OCStackResult SRPRemoveDeviceWithoutDiscovery(void* ctx, const OCProvisionDev_t* pOwnedDevList,
1994                              const OCProvisionDev_t* pTargetDev, OCProvisionResultCB resultCallback)
1995 {
1996     OIC_LOG(INFO, TAG, "IN SRPRemoveDeviceWithoutDiscovery");
1997
1998     if (!pTargetDev  || !pOwnedDevList)
1999     {
2000         OIC_LOG(INFO, TAG, "SRPRemoveDeviceWithoutDiscovery : NULL parameters");
2001         return OC_STACK_INVALID_PARAM;
2002     }
2003     if (!resultCallback)
2004     {
2005         OIC_LOG(INFO, TAG, "SRPRemoveDeviceWithoutDiscovery : NULL Callback");
2006         return OC_STACK_INVALID_CALLBACK;
2007     }
2008
2009     // Declare variables in here to handle error cases with goto statement.
2010     OCProvisionDev_t* pLinkedDevList = NULL;
2011     RemoveData_t* removeData = NULL;
2012
2013     //1. Find all devices that has a credential of the revoked device
2014     OCUuidList_t* pLinkedUuidList = NULL;
2015     size_t numOfDevices = 0;
2016     OCStackResult res = OC_STACK_ERROR;
2017     res = PDMGetLinkedDevices(&pTargetDev->doxm->deviceID, &pLinkedUuidList, &numOfDevices);
2018     if (OC_STACK_OK != res)
2019     {
2020         OIC_LOG(ERROR, TAG, "SRPRemoveDeviceWithoutDiscovery : Failed to get linked devices information");
2021         return res;
2022     }
2023     // if there is no related device, we can skip further process.
2024     if (0 == numOfDevices)
2025     {
2026         OIC_LOG(DEBUG, TAG, "SRPRemoveDeviceWithoutDiscovery : No linked device found.");
2027         res = OC_STACK_CONTINUE;
2028         goto error;
2029     }
2030
2031     //2. Make a list of devices to send DELETE credential request
2032     //   by comparing owned devices from provisioning database with mutlicast discovery result.
2033     size_t numOfLinkedDev = 0;
2034     res = GetListofDevToReqDeleteCred(pTargetDev, pOwnedDevList, pLinkedUuidList,
2035                                       &pLinkedDevList, &numOfLinkedDev);
2036     if (OC_STACK_OK != res)
2037     {
2038         OIC_LOG(ERROR, TAG, "SRPRemoveDeviceWithoutDiscovery : GetListofDevToReqDeleteCred() failed");
2039         goto error;
2040     }
2041     if (0 == numOfLinkedDev) // This case means, there is linked device but it's not alive now.
2042     {                       // So we don't have to send request message.
2043         OIC_LOG(DEBUG, TAG, "SRPRemoveDeviceWithoutDiscovery : No alived & linked device found.");
2044         res = OC_STACK_CONTINUE;
2045         goto error;
2046     }
2047
2048     // 3. Prepare RemoveData Context data.
2049     removeData = (RemoveData_t*)OICCalloc(1, sizeof(RemoveData_t));
2050     if (!removeData)
2051     {
2052         OIC_LOG(ERROR, TAG, "SRPRemoveDeviceWithoutDiscovery : Failed to memory allocation");
2053         res = OC_STACK_NO_MEMORY;
2054         goto error;
2055     }
2056
2057     removeData->revokeTargetDev = PMCloneOCProvisionDev(pTargetDev);
2058     if (!removeData->revokeTargetDev)
2059     {
2060         OIC_LOG(ERROR, TAG, "SRPRemoveDeviceWithoutDiscovery : PMCloneOCProvisionDev Failed");
2061         res = OC_STACK_NO_MEMORY;
2062         goto error;
2063     }
2064
2065     removeData->removeRes =
2066         (OCProvisionResult_t*)OICCalloc(numOfLinkedDev, sizeof(OCProvisionResult_t));
2067     if (!removeData->removeRes)
2068     {
2069         OIC_LOG(ERROR, TAG, "SRPRemoveDeviceWithoutDiscovery : Failed to memory allocation");
2070         res = OC_STACK_NO_MEMORY;
2071         goto error;
2072     }
2073
2074     removeData->ctx = ctx;
2075     removeData->linkedDevList = pLinkedDevList;
2076     removeData->resultCallback = resultCallback;
2077     removeData->numOfResults = 0;
2078     removeData->sizeOfResArray = numOfLinkedDev;
2079     removeData->hasError = false;
2080
2081     // 5. Send DELETE credential request to linked devices.
2082     OCProvisionDev_t *curDev = NULL, *tmpDev = NULL;
2083     OCStackResult totalRes = OC_STACK_ERROR;  /* variable for checking request is sent or not */
2084     LL_FOREACH_SAFE(pLinkedDevList, curDev, tmpDev)
2085     {
2086         res = SendDeleteCredentialRequest((void*)removeData, &SRPRemoveDeviceCB,
2087                                            removeData->revokeTargetDev, curDev);
2088         if (OC_STACK_OK != res)
2089         {
2090             OIC_LOG_V(ERROR, TAG, "SRPRemoveDeviceWithoutDiscovery : Fail to send the DELETE credential request to\
2091                      %s:%u", curDev->endpoint.addr, curDev->endpoint.port);
2092         }
2093         else
2094         {
2095             totalRes = OC_STACK_OK; // This means at least one request is successfully sent.
2096         }
2097     }
2098
2099     PDMDestoryOicUuidLinkList(pLinkedUuidList); //TODO: Modify API name to have unified convention.
2100     OIC_LOG(INFO, TAG, "OUT SRPRemoveDeviceWithoutDiscovery");
2101
2102     return totalRes; // Caller of this API should wait callback if totalRes == OC_STACK_OK.
2103
2104 error:
2105     PDMDestoryOicUuidLinkList(pLinkedUuidList);
2106     PMDeleteDeviceList(pLinkedDevList);
2107     if (removeData)
2108     {
2109         OICFree(removeData->revokeTargetDev);
2110         OICFree(removeData->removeRes);
2111         OICFree(removeData);
2112     }
2113     OIC_LOG(INFO, TAG, "OUT ERROR case SRPRemoveDeviceWithoutDiscovery");
2114     return res;
2115 }
2116
2117 /*
2118  * Function to sync-up credential and ACL of the target device.
2119  * This function will remove credential and ACL of target device from all devices in subnet.
2120  *
2121  * @param[in] ctx Application context would be returned in result callback
2122  * @param[in] waitTimeForOwnedDeviceDiscovery Maximum wait time for owned device discovery.(seconds)
2123  * @param[in] pTargetDev Device information to be revoked.
2124  * @param[in] resultCallback callback provided by API user, callback will be called when
2125  *            credential revocation is finished.
2126  *            when there is an error, this user callback is called immediately.
2127  * @return OC_STACK_OK in case of success and other value otherwise.
2128  *         If OC_STACK_OK is returned, the caller of this API should wait for callback.
2129  *         OC_STACK_CONTINUE means operation is success but no request is need to be initiated.
2130  */
2131 OCStackResult SRPSyncDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDiscovery,
2132                          const OCProvisionDev_t* pTargetDev, OCProvisionResultCB resultCallback)
2133 {
2134     OIC_LOG(INFO, TAG, "IN SRPSyncDevice");
2135     if (!pTargetDev  || 0 == waitTimeForOwnedDeviceDiscovery)
2136     {
2137         OIC_LOG(INFO, TAG, "SRPSyncDevice : NULL parameters");
2138         return OC_STACK_INVALID_PARAM;
2139     }
2140     if (!resultCallback)
2141     {
2142         OIC_LOG(INFO, TAG, "SRPSyncDevice : NULL Callback");
2143         return OC_STACK_INVALID_CALLBACK;
2144     }
2145
2146     // Declare variables in here to handle error cases with goto statement.
2147     OCProvisionDev_t* pOwnedDevList = NULL;
2148     OCProvisionDev_t* pLinkedDevList = NULL;
2149     RemoveData_t* removeData = NULL;
2150
2151     //1. Find all devices that has a credential of the revoked device
2152     OCUuidList_t* pLinkedUuidList = NULL;
2153     size_t numOfDevices = 0;
2154     OCStackResult res = OC_STACK_ERROR;
2155     res = PDMGetLinkedDevices(&pTargetDev->doxm->deviceID, &pLinkedUuidList, &numOfDevices);
2156     if (OC_STACK_OK != res)
2157     {
2158         OIC_LOG(ERROR, TAG, "SRPSyncDevice : Failed to get linked devices information");
2159         return res;
2160     }
2161     // if there is no related device, we can skip further process.
2162     if (0 == numOfDevices)
2163     {
2164         OIC_LOG(DEBUG, TAG, "SRPSyncDevice : No linked device found.");
2165         res = OC_STACK_CONTINUE;
2166         goto error;
2167     }
2168
2169     //2. Find owned device from the network
2170     res = PMDeviceDiscovery(waitTimeForOwnedDeviceDiscovery, true, &pOwnedDevList);
2171     if (OC_STACK_OK != res)
2172     {
2173         OIC_LOG(ERROR, TAG, "SRPSyncDevice : Failed to PMDeviceDiscovery");
2174         goto error;
2175     }
2176
2177     //3. Make a list of devices to send DELETE credential request
2178     //   by comparing owned devices from provisioning database with mutlicast discovery result.
2179     size_t numOfLinkedDev = 0;
2180     res = GetListofDevToReqDeleteCred(pTargetDev, pOwnedDevList, pLinkedUuidList,
2181                                       &pLinkedDevList, &numOfLinkedDev);
2182     if (OC_STACK_OK != res)
2183     {
2184         OIC_LOG(ERROR, TAG, "SRPSyncDevice : GetListofDevToReqDeleteCred() failed");
2185         goto error;
2186     }
2187     if (0 == numOfLinkedDev) // This case means, there is linked device but it's not alive now.
2188     {                       // So we don't have to send request message.
2189         OIC_LOG(DEBUG, TAG, "SRPSyncDevice : No alived & linked device found.");
2190         res = OC_STACK_CONTINUE;
2191         goto error;
2192     }
2193
2194     // 4. Prepare RemoveData Context data.
2195     removeData = (RemoveData_t*)OICCalloc(1, sizeof(RemoveData_t));
2196     if (!removeData)
2197     {
2198         OIC_LOG(ERROR, TAG, "SRPSyncDevice : Failed to memory allocation");
2199         res = OC_STACK_NO_MEMORY;
2200         goto error;
2201     }
2202
2203     removeData->revokeTargetDev = PMCloneOCProvisionDev(pTargetDev);
2204     if (!removeData->revokeTargetDev)
2205     {
2206         OIC_LOG(ERROR, TAG, "SRPSyncDevice : PMCloneOCProvisionDev Failed");
2207         res = OC_STACK_NO_MEMORY;
2208         goto error;
2209     }
2210
2211     removeData->removeRes =
2212         (OCProvisionResult_t*)OICCalloc(numOfLinkedDev, sizeof(OCProvisionResult_t));
2213     if (!removeData->removeRes)
2214     {
2215         OIC_LOG(ERROR, TAG, "SRPSyncDevice : Failed to allocate memory");
2216         res = OC_STACK_NO_MEMORY;
2217         goto error;
2218     }
2219
2220     removeData->ctx = ctx;
2221     removeData->linkedDevList = pLinkedDevList;
2222     removeData->resultCallback = resultCallback;
2223     removeData->numOfResults = 0;
2224     removeData->sizeOfResArray = numOfLinkedDev;
2225     removeData->hasError = false;
2226
2227     // 5. Send DELETE credential request to linked devices.
2228     OCProvisionDev_t *curDev = NULL, *tmpDev = NULL;
2229     OCStackResult totalRes = OC_STACK_ERROR;  /* variable for checking request is sent or not */
2230     LL_FOREACH_SAFE(pLinkedDevList, curDev, tmpDev)
2231     {
2232         res = SendDeleteACLRequest((void*)removeData, &SRPSyncDeviceACLCB,
2233                                            removeData->revokeTargetDev, curDev);
2234         if (OC_STACK_OK != res)
2235         {
2236             OIC_LOG_V(ERROR, TAG, "SRPSyncDevice : Fail to send the DELETE ACL request to\
2237                      %s:%u", curDev->endpoint.addr, curDev->endpoint.port);
2238             goto error;
2239         }
2240         res = SendDeleteCredentialRequest((void*)removeData, &SRPSyncDeviceCredCB,
2241                                            removeData->revokeTargetDev, curDev);
2242         if (OC_STACK_OK != res)
2243         {
2244             OIC_LOG_V(ERROR, TAG, "SRPSyncDevice : Fail to send the DELETE credential request to\
2245                      %s:%u", curDev->endpoint.addr, curDev->endpoint.port);
2246             totalRes = OC_STACK_ERROR;
2247         }
2248         else
2249         {
2250             totalRes = OC_STACK_OK; // This means at least one request is successfully sent.
2251         }
2252     }
2253
2254     PDMDestoryOicUuidLinkList(pLinkedUuidList); //TODO: Modify API name to have unified convention.
2255     PMDeleteDeviceList(pOwnedDevList);
2256     OIC_LOG(INFO, TAG, "OUT SRPSyncDevice");
2257
2258     return totalRes; // Caller of this API should wait callback if totalRes == OC_STACK_OK.
2259
2260 error:
2261     PDMDestoryOicUuidLinkList(pLinkedUuidList);
2262     PMDeleteDeviceList(pOwnedDevList);
2263     PMDeleteDeviceList(pLinkedDevList);
2264     if (removeData)
2265     {
2266         OICFree(removeData->revokeTargetDev);
2267         OICFree(removeData->removeRes);
2268         OICFree(removeData);
2269     }
2270     OIC_LOG(INFO, TAG, "OUT ERROR case SRPSyncDevice");
2271     return res;
2272 }
2273
2274 /*
2275  * Function for remote reset
2276  * This function will send pstat PUT message to the target device to initiate remote reset.
2277  *
2278  * @param[in] pTargetDev Device information to be revoked.
2279  * @param[in] resultCallback callback provided by API user, callback will be called when
2280  *            credential revocation is finished.
2281  *            when there is an error, this user callback is called immediately.
2282  * @return OC_STACK_OK in case of success and other value otherwise.
2283  *         If OC_STACK_OK is returned, the caller of this API should wait for callback.
2284  *         OC_STACK_CONTINUE means operation is success but no request is need to be initiated.
2285  */
2286 OCStackResult SRPResetDevice(const OCProvisionDev_t* pTargetDev,
2287         OCProvisionResultCB resultCallback)
2288 {
2289     OIC_LOG(INFO, TAG, "IN SRPResetDevice");
2290     if (!pTargetDev)
2291     {
2292         OIC_LOG(INFO, TAG, "SRPResetDevice : NULL parameters");
2293         return OC_STACK_INVALID_PARAM;
2294     }
2295     if (!resultCallback)
2296     {
2297         OIC_LOG(INFO, TAG, "SRPResetDevice : NULL Callback");
2298         return OC_STACK_INVALID_CALLBACK;
2299     }
2300
2301     OCStackResult res = OC_STACK_ERROR;
2302     OicSecPstat_t * pstat = (OicSecPstat_t *) OICCalloc(1, sizeof(OicSecPstat_t));
2303     if (!pstat)
2304     {
2305         OIC_LOG(ERROR, TAG, "Failed to allocate memory");
2306         return OC_STACK_NO_MEMORY;
2307     }
2308
2309     pstat->cm = RESET;
2310     pstat->isOp = false;
2311     memcpy(pstat->deviceID.id, pTargetDev->doxm->deviceID.id, sizeof(OicUuid_t));
2312     pstat->tm = TAKE_OWNER;
2313     pstat->om = (OicSecDpom_t)(SINGLE_SERVICE_SERVER_DRIVEN | MULTIPLE_SERVICE_CLIENT_DRIVEN);
2314     pstat->smLen = 1;
2315     pstat->sm = (OicSecDpom_t *) OICCalloc(pstat->smLen, sizeof(OicSecDpom_t));
2316     if (NULL == pstat->sm)
2317     {
2318         OIC_LOG(ERROR, TAG, "Failed to allocate memory");
2319         OICFree(pstat);
2320         return OC_STACK_NO_MEMORY;
2321     }
2322     pstat->sm[0] = (OicSecDpom_t)(SINGLE_SERVICE_SERVER_DRIVEN | MULTIPLE_SERVICE_CLIENT_DRIVEN);
2323
2324     OCSecurityPayload * secPayload = (OCSecurityPayload *) OICCalloc(1, sizeof(OCSecurityPayload));
2325     if (!secPayload)
2326     {
2327         OIC_LOG(ERROR, TAG, "Failed to allocate memory");
2328         res = OC_STACK_NO_MEMORY;
2329         goto error;
2330     }
2331     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
2332
2333     if (OC_STACK_OK != PstatToCBORPayload(pstat, &(secPayload->securityData),
2334                 &(secPayload->payloadSize), true))
2335     {
2336         OCPayloadDestroy((OCPayload *) secPayload);
2337         OIC_LOG(ERROR, TAG, "Failed to PstatToCBORPayload");
2338         res = OC_STACK_NO_MEMORY;
2339         goto error;
2340     }
2341     OIC_LOG(DEBUG, TAG, "Created payload for pstat set");
2342     OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
2343
2344     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
2345     if (!PMGenerateQuery(true,
2346                 pTargetDev->endpoint.addr,
2347                 pTargetDev->securePort,
2348                 pTargetDev->connType,
2349                 query, sizeof(query), OIC_RSRC_PSTAT_URI))
2350     {
2351         OIC_LOG(ERROR, TAG, "SRPResetDevice : Failed to generate query");
2352         OCPayloadDestroy((OCPayload *) secPayload);
2353         res = OC_STACK_ERROR;
2354         goto error;
2355     }
2356     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
2357
2358     OCProvisionDev_t * targetDev = PMCloneOCProvisionDev(pTargetDev);
2359     OCCallbackData cbData = { .context = NULL, .cb = NULL, .cd = NULL };
2360     cbData.cb = &SRPResetDeviceCB;
2361     cbData.context = (void *) targetDev;
2362     cbData.cd = NULL;
2363     OCMethod method = OC_REST_POST;
2364     OCDoHandle handle = NULL;
2365     OIC_LOG(DEBUG, TAG, "Sending PSTAT info to resource server");
2366     res = OCDoResource(&handle, method, query,
2367             &targetDev->endpoint, (OCPayload *)secPayload,
2368             targetDev->connType, OC_LOW_QOS, &cbData, NULL, 0);\
2369     if (OC_STACK_OK != res)
2370     {
2371         OIC_LOG(ERROR, TAG, "OCStack resource error");
2372     }
2373
2374 error:
2375     OICFree(pstat->sm);
2376     OICFree(pstat);
2377     OIC_LOG(INFO, TAG, "OUT SRPResetDevice");
2378     return res;
2379 }
2380
2381 /**
2382  * Internal Function to store results in result array during GetCredResourceCB.
2383  */
2384 static void registerResultForGetCredResourceCB(GetSecData_t *GetSecData,
2385                                              OCStackResult stackresult)
2386 {
2387    OIC_LOG_V(INFO, TAG, "Inside registerResultForGetCredResourceCB "
2388            "GetSecData->numOfResults is %d\n", GetSecData->numOfResults);
2389    memcpy(GetSecData->resArr[(GetSecData->numOfResults)].deviceId.id,
2390           GetSecData->deviceInfo->doxm->deviceID.id, UUID_LENGTH);
2391    GetSecData->resArr[(GetSecData->numOfResults)].res = stackresult;
2392    ++(GetSecData->numOfResults);
2393 }
2394
2395 /**
2396  * Callback handler of SRPGetCredResource.
2397  *
2398  * @param[in] ctx             ctx value passed to callback from calling function.
2399  * @param[in] UNUSED          handle to an invocation
2400  * @param[in] clientResponse  Response from queries to remote servers.
2401  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
2402  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
2403  */
2404 static OCStackApplicationResult SRPGetCredResourceCB(void *ctx, OCDoHandle UNUSED,
2405                                                   OCClientResponse *clientResponse)
2406 {
2407     OIC_LOG_V(INFO, TAG, "Inside SRPGetCredResourceCB.");
2408     (void)UNUSED;
2409     VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
2410     GetSecData_t *GetSecData = (GetSecData_t*)ctx;
2411     OCProvisionResultCB resultCallback = GetSecData->resultCallback;
2412
2413     if (clientResponse)
2414     {
2415         if(OC_STACK_OK == clientResponse->result)
2416         {
2417             uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData;
2418             size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
2419
2420             OIC_LOG_BUFFER(DEBUG, TAG, payload, size);
2421
2422             registerResultForGetCredResourceCB(GetSecData, OC_STACK_OK);
2423             ((OCProvisionResultCB)(resultCallback))(GetSecData->ctx, GetSecData->numOfResults,
2424                                                     GetSecData->resArr,
2425                                                     false);
2426              OICFree(GetSecData->resArr);
2427              OICFree(GetSecData);
2428
2429             return OC_STACK_DELETE_TRANSACTION;
2430         }
2431     }
2432     registerResultForGetCredResourceCB(GetSecData, OC_STACK_OK);
2433     ((OCProvisionResultCB)(resultCallback))(GetSecData->ctx, GetSecData->numOfResults,
2434                                             GetSecData->resArr,
2435                                             false);
2436     OIC_LOG_V(ERROR, TAG, "SRPGetCredResourceCB received Null clientResponse");
2437     OICFree(GetSecData->resArr);
2438     OICFree(GetSecData);
2439
2440     return OC_STACK_DELETE_TRANSACTION;
2441 }
2442
2443
2444 OCStackResult SRPGetCredResource(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
2445         OCProvisionResultCB resultCallback)
2446 {
2447     VERIFY_NON_NULL(TAG, selectedDeviceInfo, ERROR,  OC_STACK_INVALID_PARAM);
2448     VERIFY_NON_NULL(TAG, resultCallback, ERROR,  OC_STACK_INVALID_CALLBACK);
2449
2450     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
2451     if(!PMGenerateQuery(true,
2452                         selectedDeviceInfo->endpoint.addr,
2453                         selectedDeviceInfo->securePort,
2454                         selectedDeviceInfo->connType,
2455                         query, sizeof(query), OIC_RSRC_CRED_URI))
2456     {
2457         OIC_LOG(ERROR, TAG, "SRPGetCredResource : Failed to generate query");
2458         return OC_STACK_ERROR;
2459     }
2460     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
2461
2462     OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};
2463     cbData.cb = &SRPGetCredResourceCB;
2464     GetSecData_t* GetSecData = (GetSecData_t*)OICCalloc(1, sizeof(GetSecData_t));
2465     if (NULL == GetSecData)
2466     {
2467         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
2468         return OC_STACK_NO_MEMORY;
2469     }
2470     GetSecData->deviceInfo = selectedDeviceInfo;
2471     GetSecData->resultCallback = resultCallback;
2472     GetSecData->numOfResults=0;
2473     GetSecData->ctx = ctx;
2474
2475     int noOfRiCalls = 1;
2476     GetSecData->resArr = (OCProvisionResult_t*)OICCalloc(noOfRiCalls, sizeof(OCProvisionResult_t));
2477     if (NULL == GetSecData->resArr)
2478     {
2479         OICFree(GetSecData);
2480         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
2481         return OC_STACK_NO_MEMORY;
2482     }
2483     cbData.context = (void *)GetSecData;
2484     cbData.cd = NULL;
2485     OCMethod method = OC_REST_GET;
2486     OCDoHandle handle = NULL;
2487     OIC_LOG(DEBUG, TAG, "Sending Get Cred to  resource server");
2488     OCStackResult ret = OCDoResource(&handle, method, query, NULL, NULL,
2489             selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
2490     if (OC_STACK_OK != ret)
2491     {
2492         OIC_LOG(ERROR, TAG, "OCStack resource error");
2493         OICFree(GetSecData->resArr);
2494         OICFree(GetSecData);
2495     }
2496     VERIFY_SUCCESS(TAG, (OC_STACK_OK == ret), ERROR, OC_STACK_ERROR);
2497     OIC_LOG(DEBUG, TAG, "OUT SRPGetCredResource");
2498
2499     return OC_STACK_OK;
2500 }
2501
2502 /**
2503  * Internal Function to store results in result array during GetACLResourceCB.
2504  */
2505 static void registerResultForGetACLResourceCB(GetSecData_t *GetSecData,
2506                                              OCStackResult stackresult)
2507 {
2508    OIC_LOG_V(INFO, TAG, "Inside registerResultForGetACLResourceCB "
2509            "GetSecData->numOfResults is %d\n", GetSecData->numOfResults);
2510    memcpy(GetSecData->resArr[(GetSecData->numOfResults)].deviceId.id,
2511           GetSecData->deviceInfo->doxm->deviceID.id, UUID_LENGTH);
2512    GetSecData->resArr[(GetSecData->numOfResults)].res = stackresult;
2513    ++(GetSecData->numOfResults);
2514 }
2515
2516 /**
2517  * Callback handler of SRPGetACLResource.
2518  *
2519  * @param[in] ctx             ctx value passed to callback from calling function.
2520  * @param[in] UNUSED          handle to an invocation
2521  * @param[in] clientResponse  Response from queries to remote servers.
2522  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
2523  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
2524  */
2525 static OCStackApplicationResult SRPGetACLResourceCB(void *ctx, OCDoHandle UNUSED,
2526                                                   OCClientResponse *clientResponse)
2527 {
2528     OIC_LOG_V(INFO, TAG, "Inside SRPGetACLResourceCB.");
2529     (void)UNUSED;
2530     VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
2531     GetSecData_t *GetSecData = (GetSecData_t*)ctx;
2532     OCProvisionResultCB resultCallback = GetSecData->resultCallback;
2533
2534     if (clientResponse)
2535     {
2536         if(OC_STACK_OK == clientResponse->result)
2537         {
2538             uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData;
2539             size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
2540
2541             OIC_LOG_BUFFER(DEBUG, TAG, payload, size);
2542
2543             registerResultForGetACLResourceCB(GetSecData, OC_STACK_OK);
2544             ((OCProvisionResultCB)(resultCallback))(GetSecData->ctx, GetSecData->numOfResults,
2545                                                     GetSecData->resArr,
2546                                                     false);
2547              OICFree(GetSecData->resArr);
2548              OICFree(GetSecData);
2549
2550             return OC_STACK_DELETE_TRANSACTION;
2551         }
2552     }
2553     registerResultForGetACLResourceCB(GetSecData, OC_STACK_OK);
2554     ((OCProvisionResultCB)(resultCallback))(GetSecData->ctx, GetSecData->numOfResults,
2555                                             GetSecData->resArr,
2556                                             false);
2557     OIC_LOG_V(ERROR, TAG, "SRPGetACLResourceCB received Null clientResponse");
2558     OICFree(GetSecData->resArr);
2559     OICFree(GetSecData);
2560
2561     return OC_STACK_DELETE_TRANSACTION;
2562 }
2563
2564
2565 OCStackResult SRPGetACLResource(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
2566         OCProvisionResultCB resultCallback)
2567 {
2568     VERIFY_NON_NULL(TAG, selectedDeviceInfo, ERROR,  OC_STACK_INVALID_PARAM);
2569     VERIFY_NON_NULL(TAG, resultCallback, ERROR,  OC_STACK_INVALID_CALLBACK);
2570
2571     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
2572     if(!PMGenerateQuery(true,
2573                         selectedDeviceInfo->endpoint.addr,
2574                         selectedDeviceInfo->securePort,
2575                         selectedDeviceInfo->connType,
2576                         query, sizeof(query), OIC_RSRC_ACL_URI))
2577     {
2578         OIC_LOG(ERROR, TAG, "SRPGetACLResource : Failed to generate query");
2579         return OC_STACK_ERROR;
2580     }
2581     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
2582
2583     OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};
2584     cbData.cb = &SRPGetACLResourceCB;
2585     GetSecData_t* GetSecData = (GetSecData_t*)OICCalloc(1, sizeof(GetSecData_t));
2586     if (NULL == GetSecData)
2587     {
2588         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
2589         return OC_STACK_NO_MEMORY;
2590     }
2591     GetSecData->deviceInfo = selectedDeviceInfo;
2592     GetSecData->resultCallback = resultCallback;
2593     GetSecData->numOfResults=0;
2594     GetSecData->ctx = ctx;
2595
2596     int noOfRiCalls = 1;
2597     GetSecData->resArr = (OCProvisionResult_t*)OICCalloc(noOfRiCalls, sizeof(OCProvisionResult_t));
2598     if (NULL == GetSecData->resArr)
2599     {
2600         OICFree(GetSecData);
2601         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
2602         return OC_STACK_NO_MEMORY;
2603     }
2604     cbData.context = (void *)GetSecData;
2605     cbData.cd = NULL;
2606     OCMethod method = OC_REST_GET;
2607     OCDoHandle handle = NULL;
2608     OIC_LOG(DEBUG, TAG, "Sending Get ACL to resource server");
2609     OCStackResult ret = OCDoResource(&handle, method, query, NULL, NULL,
2610             selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
2611     if (OC_STACK_OK != ret)
2612     {
2613         OIC_LOG(ERROR, TAG, "OCStack resource error");
2614         OICFree(GetSecData->resArr);
2615         OICFree(GetSecData);
2616     }
2617     VERIFY_SUCCESS(TAG, (OC_STACK_OK == ret), ERROR, OC_STACK_ERROR);
2618     OIC_LOG(DEBUG, TAG, "OUT SRPGetACLResource");
2619
2620     return OC_STACK_OK;
2621 }