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