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