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