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