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