[IOT-1513] Incorrect URI construction
[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 "OIC_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 addressEncoded[CA_MAX_URI_LENGTH] = {0};
1209     OCStackResult result = OCEncodeAddressForRFC6874(addressEncoded,
1210                                                      sizeof(addressEncoded),
1211                                                      destDev->endpoint.addr);
1212     if (OC_STACK_OK != result)
1213     {
1214         OIC_LOG_V(ERROR, TAG, "SendDeleteCredentialRequest : encoding error %d\n", result);
1215         return OC_STACK_ERROR;
1216     }
1217
1218     char reqBuf[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1219     int snRet = 0;
1220                     //coaps://0.0.0.0:5684/oic/sec/cred?subjectid=(Canonical ENCODED UUID)
1221     char *srpUri = SRP_FORM_DELETE_CREDENTIAL;
1222 #ifdef __WITH_TLS__
1223     if(CA_ADAPTER_TCP == destDev->endpoint.adapter)
1224     {
1225         srpUri = SRP_FORM_DELETE_CREDENTIAL_TCP;
1226     }
1227 #endif
1228
1229     snRet = snprintf(reqBuf, sizeof(reqBuf), srpUri, addressEncoded,
1230                      destDev->securePort, OIC_RSRC_CRED_URI, OIC_JSON_SUBJECTID_NAME, subID);
1231     OICFree(subID);
1232     if (snRet < 0)
1233     {
1234         OIC_LOG_V(ERROR, TAG, "SendDeleteCredentialRequest : Error (snprintf) %d\n", snRet);
1235         return OC_STACK_ERROR;
1236     }
1237     else if ((size_t)snRet >= sizeof(reqBuf))
1238     {
1239         OIC_LOG_V(ERROR, TAG, "SendDeleteCredentialRequest : Truncated (snprintf) %d\n", snRet);
1240         return OC_STACK_ERROR;
1241     }
1242
1243     OCCallbackData cbData;
1244     memset(&cbData, 0, sizeof(cbData));
1245     cbData.context = ctx;
1246     cbData.cb = respHandler;
1247     cbData.cd = NULL;
1248     OIC_LOG_V(INFO, TAG, "URI: %s",reqBuf);
1249
1250     OIC_LOG(DEBUG, TAG, "Sending remove credential request to resource server");
1251
1252     ret = OCDoResource(NULL, OC_REST_DELETE, reqBuf,
1253                                      &destDev->endpoint, NULL,
1254                                      CT_ADAPTER_IP, OC_HIGH_QOS, &cbData, NULL, 0);
1255     if (OC_STACK_OK != ret)
1256     {
1257         OIC_LOG_V(ERROR, TAG, "SendDeleteCredentialRequest : Error in OCDoResource %d", ret);
1258     }
1259     OIC_LOG(DEBUG, TAG, "OUT SendDeleteCredentialRequest");
1260
1261     return ret;
1262 }
1263
1264 static OCStackResult SendDeleteACLRequest(void* ctx,
1265                                                  OCClientResponseHandler respHandler,
1266                                                  const OCProvisionDev_t* revokedDev,
1267                                                  const OCProvisionDev_t* destDev)
1268 {
1269     OIC_LOG(DEBUG, TAG, "IN SendDeleteACLRequest");
1270
1271     if (NULL == ctx || NULL == respHandler || NULL == revokedDev || NULL == destDev)
1272     {
1273         return OC_STACK_INVALID_PARAM;
1274     }
1275
1276     char *subID = NULL;
1277     OCStackResult ret = ConvertUuidToStr(&revokedDev->doxm->deviceID, &subID);
1278     if(OC_STACK_OK != ret)
1279     {
1280         OIC_LOG(ERROR, TAG, "SendDeleteACLRequest : Failed to canonical UUID encoding");
1281         return OC_STACK_ERROR;
1282     }
1283
1284     char addressEncoded[CA_MAX_URI_LENGTH] = {0};
1285     OCStackResult result = OCEncodeAddressForRFC6874(addressEncoded,
1286                                                      sizeof(addressEncoded),
1287                                                      destDev->endpoint.addr);
1288     if (OC_STACK_OK != result)
1289     {
1290         OIC_LOG_V(ERROR, TAG, "SendDeleteCredentialRequest : encoding error %d\n", result);
1291         return OC_STACK_ERROR;
1292     }
1293
1294
1295     char reqBuf[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1296     int snRet = 0;
1297                     //coaps://0.0.0.0:5684/oic/sec/acl?subjectuuid=(Canonical ENCODED UUID)
1298     snRet = snprintf(reqBuf, sizeof(reqBuf), SRP_FORM_DELETE_CREDENTIAL, addressEncoded,
1299                      destDev->securePort, OIC_RSRC_ACL_URI, OIC_JSON_SUBJECTID_NAME, subID);
1300     OICFree(subID);
1301     if (snRet < 0)
1302     {
1303         OIC_LOG_V(ERROR, TAG, "SendDeleteACLRequest : Error (snprintf) %d\n", snRet);
1304         return OC_STACK_ERROR;
1305     }
1306     else if ((size_t)snRet >= sizeof(reqBuf))
1307     {
1308         OIC_LOG_V(ERROR, TAG, "SendDeleteACLRequest : Truncated (snprintf) %d\n", snRet);
1309         return OC_STACK_ERROR;
1310     }
1311
1312     OCCallbackData cbData;
1313     memset(&cbData, 0, sizeof(cbData));
1314     cbData.context = ctx;
1315     cbData.cb = respHandler;
1316     cbData.cd = NULL;
1317     OIC_LOG_V(INFO, TAG, "URI: %s",reqBuf);
1318
1319     OIC_LOG(DEBUG, TAG, "Sending remove ACL request to resource server");
1320
1321     ret = OCDoResource(NULL, OC_REST_DELETE, reqBuf,
1322                                      &destDev->endpoint, NULL,
1323                                      CT_ADAPTER_IP, OC_HIGH_QOS, &cbData, NULL, 0);
1324     if (OC_STACK_OK != ret)
1325     {
1326         OIC_LOG_V(ERROR, TAG, "SendDeleteACLRequest : Error in OCDoResource %d", ret);
1327     }
1328     OIC_LOG(DEBUG, TAG, "OUT SendDeleteACLRequest");
1329
1330     return ret;
1331 }
1332
1333 /**
1334  * Callback handler of unlink second device.
1335  *
1336  * @param[in] ctx             ctx value passed to callback from calling function.
1337  * @param[in] handle          handle to an invocation
1338  * @param[in] clientResponse  Response from queries to remote servers.
1339  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction and
1340  *          OC_STACK_KEEP_TRANSACTION to keep it.
1341  */
1342 static OCStackApplicationResult SRPUnlinkDevice2CB(void *unlinkCtx, OCDoHandle handle,
1343         OCClientResponse *clientResponse)
1344 {
1345     (void) handle;
1346     OIC_LOG(DEBUG, TAG, "IN SRPUnlinkDevice2CB");
1347     VERIFY_NON_NULL(TAG, unlinkCtx, ERROR, OC_STACK_DELETE_TRANSACTION);
1348     UnlinkData_t* unlinkData = (UnlinkData_t*)unlinkCtx;
1349
1350     if (clientResponse)
1351     {
1352         OIC_LOG(DEBUG, TAG, "Valid client response for device 2");
1353         registerResultForUnlinkDevices(unlinkData, clientResponse->result, IDX_SECOND_DEVICE_RES);
1354
1355         if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
1356         {
1357             OIC_LOG(DEBUG, TAG, "Credential of device2 revoked");
1358         }
1359         else
1360         {
1361             OIC_LOG(ERROR, TAG, "Unable to delete credential information from device 2");
1362             unlinkData->resultCallback(unlinkData->ctx,
1363                                        unlinkData->numOfResults, unlinkData->unlinkRes, true);
1364             goto error;
1365         }
1366     }
1367     else
1368     {
1369         registerResultForUnlinkDevices(unlinkData, OC_STACK_INVALID_REQUEST_HANDLE,
1370                                        IDX_SECOND_DEVICE_RES);
1371         unlinkData->resultCallback(unlinkData->ctx,
1372                                    unlinkData->numOfResults, unlinkData->unlinkRes, true);
1373         OIC_LOG(ERROR, TAG, "SRPUnlinkDevice2CB received Null clientResponse");
1374         goto error;
1375     }
1376
1377     //Update provisioning DB when succes case.
1378     if (OC_STACK_OK != PDMUnlinkDevices(&unlinkData->unlinkDev[0].doxm->deviceID,
1379                                        &unlinkData->unlinkDev[1].doxm->deviceID))
1380     {
1381         OIC_LOG(FATAL, TAG, "All requests are successfully done but update provisioning DB FAILED.");
1382         registerResultForUnlinkDevices(unlinkData, OC_STACK_INCONSISTENT_DB, IDX_DB_UPDATE_RES);
1383         unlinkData->resultCallback(unlinkData->ctx,
1384                                    unlinkData->numOfResults, unlinkData->unlinkRes, true);
1385         goto error;
1386     }
1387     unlinkData->resultCallback(unlinkData->ctx, unlinkData->numOfResults, unlinkData->unlinkRes,
1388                                false);
1389
1390 error:
1391     DeleteUnlinkData_t(unlinkData);
1392     OIC_LOG(DEBUG, TAG, "OUT SRPUnlinkDevice2CB");
1393     return OC_STACK_DELETE_TRANSACTION;
1394
1395 }
1396
1397 /**
1398  * Callback handler of unlink first device.
1399  *
1400  * @param[in] ctx             ctx value passed to callback from calling function.
1401  * @param[in] handle          handle to an invocation
1402  * @param[in] clientResponse  Response from queries to remote servers.
1403  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction and
1404  *          OC_STACK_KEEP_TRANSACTION to keep it.
1405  */
1406 static OCStackApplicationResult SRPUnlinkDevice1CB(void *unlinkCtx, OCDoHandle handle,
1407         OCClientResponse *clientResponse)
1408 {
1409     OIC_LOG_V(INFO, TAG, "Inside SRPUnlinkDevice1CB ");
1410     VERIFY_NON_NULL(TAG, unlinkCtx, ERROR, OC_STACK_DELETE_TRANSACTION);
1411     UnlinkData_t* unlinkData = (UnlinkData_t*)unlinkCtx;
1412     (void) handle;
1413
1414     if (clientResponse)
1415     {
1416         OIC_LOG(DEBUG, TAG, "Valid client response for device 1");
1417         registerResultForUnlinkDevices(unlinkData, clientResponse->result, IDX_FIRST_DEVICE_RES);
1418
1419         if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
1420         {
1421             OIC_LOG(DEBUG, TAG, "Credential of device 1 is revoked");
1422
1423             // Second revocation request to second device.
1424             OCStackResult res = SendDeleteCredentialRequest((void*)unlinkData, &SRPUnlinkDevice2CB,
1425                                                     &unlinkData->unlinkDev[0],
1426                                                     &unlinkData->unlinkDev[1] /*Dest*/);
1427             OIC_LOG_V(DEBUG, TAG, "Credential revocation request device 2, result :: %d",res);
1428             if (OC_STACK_OK != res)
1429             {
1430                  OIC_LOG(ERROR, TAG, "Error while sending revocation request for device 2");
1431                  registerResultForUnlinkDevices(unlinkData, OC_STACK_INVALID_REQUEST_HANDLE,
1432                                                 IDX_SECOND_DEVICE_RES);
1433                  unlinkData->resultCallback(unlinkData->ctx,
1434                                             unlinkData->numOfResults, unlinkData->unlinkRes, true);
1435                  goto error;
1436             }
1437             else
1438             {
1439                 OIC_LOG(DEBUG, TAG, "Request for credential revocation successfully sent");
1440                 return OC_STACK_DELETE_TRANSACTION;
1441             }
1442         }
1443         else
1444         {
1445             OIC_LOG(ERROR, TAG, "Unable to delete credential information from device 1");
1446
1447             unlinkData->resultCallback(unlinkData->ctx, unlinkData->numOfResults,
1448                                             unlinkData->unlinkRes, true);
1449             goto error;
1450         }
1451     }
1452     else
1453     {
1454         OIC_LOG(DEBUG, TAG, "Invalid response from server");
1455         registerResultForUnlinkDevices(unlinkData, OC_STACK_INVALID_REQUEST_HANDLE,
1456                                        IDX_FIRST_DEVICE_RES );
1457         unlinkData->resultCallback(unlinkData->ctx,
1458                                    unlinkData->numOfResults, unlinkData->unlinkRes,
1459                                    true);
1460         OIC_LOG(ERROR, TAG, "SRPUnlinkDevice1CB received Null clientResponse");
1461     }
1462
1463 error:
1464     OIC_LOG_V(INFO, TAG, "Out SRPUnlinkDevice1CB");
1465     DeleteUnlinkData_t(unlinkData);
1466     return OC_STACK_DELETE_TRANSACTION;
1467 }
1468
1469 /*
1470 * Function to unlink devices.
1471 * This function will remove the credential & relationship between the two devices.
1472 *
1473 * @param[in] ctx Application context would be returned in result callback
1474 * @param[in] pTargetDev1 first device information to be unlinked.
1475 * @param[in] pTargetDev2 second device information to be unlinked.
1476 * @param[in] resultCallback callback provided by API user, callback will be called when
1477 *            device unlink is finished.
1478  * @return  OC_STACK_OK in case of success and other value otherwise.
1479 */
1480 OCStackResult SRPUnlinkDevices(void* ctx,
1481                                const OCProvisionDev_t* pTargetDev1,
1482                                const OCProvisionDev_t* pTargetDev2,
1483                                OCProvisionResultCB resultCallback)
1484 {
1485     OIC_LOG(INFO, TAG, "IN SRPUnlinkDevices");
1486
1487     if (!pTargetDev1 || !pTargetDev2 || !pTargetDev1->doxm || !pTargetDev2->doxm)
1488     {
1489         OIC_LOG(INFO, TAG, "SRPUnlinkDevices : NULL parameters");
1490         return OC_STACK_INVALID_PARAM;
1491     }
1492     if (!resultCallback)
1493     {
1494         OIC_LOG(INFO, TAG, "SRPUnlinkDevices : NULL Callback");
1495         return OC_STACK_INVALID_CALLBACK;
1496     }
1497     if (0 == memcmp(&pTargetDev1->doxm->deviceID, &pTargetDev2->doxm->deviceID, sizeof(OicUuid_t)))
1498     {
1499         OIC_LOG(INFO, TAG, "SRPUnlinkDevices : Same device ID");
1500         return OC_STACK_INVALID_PARAM;
1501     }
1502
1503     OIC_LOG(INFO, TAG, "Unlinking following devices: ");
1504     PMPrintOCProvisionDev(pTargetDev1);
1505     PMPrintOCProvisionDev(pTargetDev2);
1506
1507     // Mark the link status stale
1508     OCStackResult res = PDMSetLinkStale(&pTargetDev1->doxm->deviceID, &pTargetDev2->doxm->deviceID);
1509     if (OC_STACK_OK != res)
1510     {
1511         OIC_LOG(FATAL, TAG, "unable to update DB. Try again.");
1512         return res;
1513     }
1514
1515     UnlinkData_t* unlinkData = (UnlinkData_t*)OICCalloc(1, sizeof(UnlinkData_t));
1516     VERIFY_NON_NULL(TAG, unlinkData, ERROR, OC_STACK_NO_MEMORY);
1517
1518     //Initialize unlink data
1519     unlinkData->ctx = ctx;
1520     unlinkData->unlinkDev = (OCProvisionDev_t*)OICCalloc(2, sizeof(OCProvisionDev_t));
1521     if (NULL == unlinkData->unlinkDev)
1522     {
1523         OIC_LOG(ERROR, TAG, "Memory allocation failed");
1524         res = OC_STACK_NO_MEMORY;
1525         goto error;
1526     }
1527
1528     unlinkData->unlinkRes = (OCProvisionResult_t*)OICCalloc(3, sizeof(OCProvisionResult_t));
1529     if (NULL == unlinkData->unlinkRes)
1530     {
1531         OIC_LOG(ERROR, TAG, "Memory allocation failed");
1532         res = OC_STACK_NO_MEMORY;
1533         goto error;
1534     }
1535
1536     memcpy(&unlinkData->unlinkDev[0], pTargetDev1, sizeof(OCProvisionDev_t));
1537     memcpy(&unlinkData->unlinkDev[1], pTargetDev2, sizeof(OCProvisionDev_t));
1538
1539     unlinkData->numOfResults = 0;
1540     unlinkData->resultCallback = resultCallback;
1541
1542     res = SendDeleteCredentialRequest((void*)unlinkData, &SRPUnlinkDevice1CB,
1543                                        &unlinkData->unlinkDev[1], &unlinkData->unlinkDev[0]);
1544     if (OC_STACK_OK != res)
1545     {
1546         OIC_LOG(ERROR, TAG, "SRPUnlinkDevices : SendDeleteCredentialRequest failed");
1547         goto error;
1548     }
1549
1550     return res;
1551
1552 error:
1553     OIC_LOG(INFO, TAG, "OUT SRPUnlinkDevices");
1554     DeleteUnlinkData_t(unlinkData);
1555     return res;
1556 }
1557
1558 static void DeleteRemoveData_t(RemoveData_t* pRemoveData)
1559 {
1560     if (pRemoveData)
1561     {
1562         OICFree(pRemoveData->revokeTargetDev);
1563         OCDeleteDiscoveredDevices(pRemoveData->linkedDevList);
1564         OICFree(pRemoveData->removeRes);
1565         OICFree(pRemoveData);
1566     }
1567 }
1568
1569 static void registerResultForRemoveDevice(RemoveData_t *removeData, OicUuid_t *pLinkedDevId,
1570                                           OCStackResult stackresult, bool hasError)
1571 {
1572     OIC_LOG_V(INFO, TAG, "Inside registerResultForRemoveDevice removeData->numOfResults is %zu\n",
1573                          removeData->numOfResults + 1);
1574     if (pLinkedDevId)
1575     {
1576         memcpy(removeData->removeRes[(removeData->numOfResults)].deviceId.id,
1577                &pLinkedDevId->id, sizeof(pLinkedDevId->id));
1578     }
1579     else
1580     {
1581         memset(removeData->removeRes[(removeData->numOfResults)].deviceId.id,
1582                0, sizeof(pLinkedDevId->id) );
1583     }
1584     removeData->removeRes[(removeData->numOfResults)].res = stackresult;
1585     removeData->hasError = hasError;
1586     ++(removeData->numOfResults);
1587
1588     // If we get suffcient result from linked devices, we have to call user callback and do free
1589     if (removeData->sizeOfResArray == removeData->numOfResults)
1590     {
1591         if(!removeData->hasError)
1592         {
1593             // Remove device info from prvisioning database
1594             if (OC_STACK_OK != PDMDeleteDevice(&removeData->revokeTargetDev->doxm->deviceID))
1595             {
1596                 OIC_LOG(ERROR, TAG, "ResultForRemoveDevice : Failed to remove device in PDM.");
1597                 removeData->hasError = true;
1598             }
1599         }
1600         removeData->resultCallback(removeData->ctx, removeData->numOfResults, removeData->removeRes,
1601                                    removeData->hasError);
1602         DeleteRemoveData_t(removeData);
1603     }
1604  }
1605
1606 static void registerResultForResetDevice(RemoveData_t *removeData, OicUuid_t *pLinkedDevId,
1607                                           OCStackResult stackresult, bool hasError)
1608 {
1609     OIC_LOG_V(INFO, TAG, "Inside registerResultForResetDevice removeData->numOfResults is %zu\n",
1610                          removeData->numOfResults + 1);
1611     if (pLinkedDevId)
1612     {
1613         memcpy(removeData->removeRes[(removeData->numOfResults)].deviceId.id,
1614                &pLinkedDevId->id, sizeof(pLinkedDevId->id));
1615     }
1616     else
1617     {
1618         memset(removeData->removeRes[(removeData->numOfResults)].deviceId.id,
1619                0, sizeof(pLinkedDevId->id) );
1620     }
1621     removeData->removeRes[(removeData->numOfResults)].res = stackresult;
1622     removeData->hasError = hasError;
1623     ++(removeData->numOfResults);
1624
1625     // If we get suffcient result from linked devices, we have to call user callback and do free
1626     if (removeData->sizeOfResArray == removeData->numOfResults)
1627     {
1628         removeData->resultCallback(removeData->ctx, removeData->numOfResults, removeData->removeRes,
1629                                    removeData->hasError);
1630         DeleteRemoveData_t(removeData);
1631     }
1632 }
1633
1634 /**
1635  * Callback handler of unlink first device.
1636  *
1637  * @param[in] ctx             ctx value passed to callback from calling function.
1638  * @param[in] handle          handle to an invocation
1639  * @param[in] clientResponse  Response from queries to remote servers.
1640  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
1641  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
1642  */
1643 static OCStackApplicationResult SRPRemoveDeviceCB(void *delDevCtx, OCDoHandle handle,
1644         OCClientResponse *clientResponse)
1645 {
1646     //Update the delete credential into delete device context
1647     //Save the deleted status in delDevCtx
1648     (void)handle;
1649     OIC_LOG_V(INFO, TAG, "Inside SRPRemoveDeviceCB.");
1650     VERIFY_NON_NULL(TAG, delDevCtx, ERROR, OC_STACK_DELETE_TRANSACTION);
1651     OCStackResult res = OC_STACK_ERROR;
1652
1653     RemoveData_t* removeData = (RemoveData_t*)delDevCtx;
1654
1655     if (clientResponse)
1656     {
1657         OicUuid_t revDevUuid = {.id={0}};
1658         if(UUID_LENGTH == clientResponse->identity.id_length)
1659         {
1660             memcpy(revDevUuid.id, clientResponse->identity.id, sizeof(revDevUuid.id));
1661             if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
1662             {
1663                 res = PDMUnlinkDevices(&removeData->revokeTargetDev->doxm->deviceID, &revDevUuid);
1664                 if (OC_STACK_OK != res)
1665                 {
1666                     OIC_LOG(ERROR, TAG, "PDMSetLinkStale() FAIL: PDB is an obsolete one.");
1667                            registerResultForRemoveDevice(removeData, &revDevUuid,
1668                            OC_STACK_INCONSISTENT_DB, true);
1669
1670                     return OC_STACK_DELETE_TRANSACTION;
1671                 }
1672
1673                 registerResultForRemoveDevice(removeData, &revDevUuid,
1674                                               OC_STACK_RESOURCE_DELETED, false);
1675             }
1676             else
1677             {
1678                 registerResultForRemoveDevice(removeData, &revDevUuid,
1679                                               clientResponse->result, true);
1680                 OIC_LOG(ERROR, TAG, "Unexpected result from DELETE credential request!");
1681             }
1682         }
1683         else
1684         {
1685             OIC_LOG_V(WARNING, TAG, "Incorrect length of device UUID was sent from %s:%d",
1686                      clientResponse->devAddr.addr, clientResponse->devAddr.port);
1687
1688             if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
1689             {
1690                 /**
1691                   * Since server's credential was deleted,
1692                   * register result as OC_STACK_INCONSISTENT_DB with NULL UUID.
1693                   */
1694                 OIC_LOG_V(ERROR, TAG, "But server's credential was deleted.");
1695                 registerResultForRemoveDevice(removeData, NULL, OC_STACK_INCONSISTENT_DB, true);
1696             }
1697             else
1698             {
1699                 registerResultForRemoveDevice(removeData, NULL, clientResponse->result, true);
1700             }
1701         }
1702     }
1703     else
1704     {
1705         registerResultForRemoveDevice(removeData, NULL, OC_STACK_ERROR, true);
1706         OIC_LOG(ERROR, TAG, "SRPRemoveDevices received Null clientResponse");
1707     }
1708
1709
1710     return OC_STACK_DELETE_TRANSACTION;
1711 }
1712
1713 /**
1714  * Callback handler of reset device.
1715  *
1716  * @param[in] ctx             ctx value passed to callback from calling function.
1717  * @param[in] handle          handle to an invocation
1718  * @param[in] clientResponse  Response from queries to remote servers.
1719  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
1720  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
1721  */
1722 static OCStackApplicationResult SRPSyncDeviceCredCB(void *delDevCtx, OCDoHandle handle,
1723         OCClientResponse *clientResponse)
1724 {
1725     //Update the delete credential into delete device context
1726     //Save the deleted status in delDevCtx
1727     (void)handle;
1728     OIC_LOG_V(INFO, TAG, "Inside SRPSyncDeviceCredCB.");
1729     VERIFY_NON_NULL(TAG, delDevCtx, ERROR, OC_STACK_DELETE_TRANSACTION);
1730     OCStackResult res = OC_STACK_ERROR;
1731
1732     RemoveData_t* removeData = (RemoveData_t*)delDevCtx;
1733     OCProvisionDev_t * pTargetDev = PMCloneOCProvisionDev(removeData->revokeTargetDev);
1734     OCProvisionResultCB resultCallback = removeData->resultCallback;
1735     if (clientResponse)
1736     {
1737         OicUuid_t revDevUuid = {.id={0}};
1738         if(UUID_LENGTH == clientResponse->identity.id_length)
1739         {
1740             memcpy(revDevUuid.id, clientResponse->identity.id, sizeof(revDevUuid.id));
1741             if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
1742             {
1743                 res = PDMUnlinkDevices(&removeData->revokeTargetDev->doxm->deviceID, &revDevUuid);
1744                 if (OC_STACK_OK != res)
1745                 {
1746                     OIC_LOG(ERROR, TAG, "PDMSetLinkStale() FAIL: PDB is an obsolete one.");
1747                            registerResultForResetDevice(removeData, &revDevUuid,
1748                            OC_STACK_INCONSISTENT_DB, true);
1749
1750                     return OC_STACK_DELETE_TRANSACTION;
1751                 }
1752
1753                 registerResultForResetDevice(removeData, &revDevUuid,
1754                                               OC_STACK_RESOURCE_DELETED, false);
1755             }
1756             else
1757             {
1758                 registerResultForResetDevice(removeData, &revDevUuid,
1759                                               clientResponse->result, false);
1760                 OIC_LOG(ERROR, TAG, "Unexpected result from DELETE credential request!");
1761             }
1762         }
1763         else
1764         {
1765             OIC_LOG_V(WARNING, TAG, "Incorrect length of device UUID was sent from %s:%d",
1766                      clientResponse->devAddr.addr, clientResponse->devAddr.port);
1767
1768             if (OC_STACK_RESOURCE_DELETED == clientResponse->result)
1769             {
1770                 /**
1771                   * Since server's credential was deleted,
1772                   * register result as OC_STACK_INCONSISTENT_DB with NULL UUID.
1773                   */
1774                 OIC_LOG_V(ERROR, TAG, "But server's credential was deleted.");
1775                 registerResultForResetDevice(removeData, NULL, OC_STACK_INCONSISTENT_DB, true);
1776             }
1777             else
1778             {
1779                 registerResultForResetDevice(removeData, NULL, clientResponse->result, true);
1780             }
1781         }
1782     }
1783     else
1784     {
1785         registerResultForResetDevice(removeData, NULL, OC_STACK_ERROR, true);
1786         OIC_LOG(ERROR, TAG, "SRPSyncDevice received Null clientResponse");
1787     }
1788
1789     SRPResetDevice(pTargetDev, resultCallback);
1790
1791     return OC_STACK_DELETE_TRANSACTION;
1792 }
1793
1794 /**
1795  * Callback handler of reset device sync-up
1796  *
1797  * @param[in] ctx             ctx value passed to callback from calling function.
1798  * @param[in] handle          handle to an invocation
1799  * @param[in] clientResponse  Response from queries to remote servers.
1800  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
1801  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
1802  */
1803 static OCStackApplicationResult SRPSyncDeviceACLCB(void *ctx, OCDoHandle handle,
1804         OCClientResponse *clientResponse)
1805 {
1806     return OC_STACK_DELETE_TRANSACTION;
1807 }
1808
1809 /**
1810  * Callback handler of device remote reset.
1811  *
1812  * @param[in] ctx             ctx value passed to callback from calling function.
1813  * @param[in] handle          handle to an invocation
1814  * @param[in] clientResponse  Response from queries to remote servers.
1815  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
1816  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
1817  */
1818 static OCStackApplicationResult SRPResetDeviceCB(void *ctx, OCDoHandle handle,
1819         OCClientResponse *clientResponse)
1820 {
1821     OIC_LOG(DEBUG, TAG, "IN SRPResetDeviceCB");
1822     if(OC_STACK_OK == clientResponse->result)
1823     {
1824         OIC_LOG(DEBUG, TAG, "Change Target Device Pstat Cm SUCCEEDED");
1825     }
1826
1827     // Delete Cred and ACL related to the target device.
1828     const OicSecCred_t *cred = NULL;
1829     OCProvisionDev_t * pTargetDev = (OCProvisionDev_t *)ctx;
1830     cred = GetCredResourceData(&pTargetDev->doxm->deviceID);
1831     if (cred == NULL)
1832     {
1833         OIC_LOG(ERROR, TAG, "OCResetDevice : Failed to get credential of target device.");
1834         goto error;
1835     }
1836
1837     OCStackResult res = RemoveCredential(&cred->subject);
1838     if (res != OC_STACK_RESOURCE_DELETED && res != OC_STACK_NO_RESOURCE)
1839     {
1840         OIC_LOG(ERROR, TAG, "OCResetDevice : Failed to remove credential.");
1841         goto error;
1842     }
1843
1844     res = RemoveACE(&cred->subject, NULL);
1845     if (res != OC_STACK_RESOURCE_DELETED && res != OC_STACK_NO_RESOURCE)
1846     {
1847         OIC_LOG(ERROR, TAG, "OCResetDevice : Failed to remove ACL.");
1848         goto error;
1849     }
1850     if (OC_STACK_OK != PDMDeleteDevice(&pTargetDev->doxm->deviceID))
1851     {
1852         OIC_LOG(ERROR, TAG, "OCResetDevice : Failed to delete device from PDM");
1853     }
1854
1855     //Close the DTLS session of the reset device.
1856     CAEndpoint_t* endpoint = (CAEndpoint_t *)&clientResponse->devAddr;
1857     CAResult_t caResult = CAcloseSslSession(endpoint);
1858     if(CA_STATUS_OK != caResult)
1859     {
1860         OIC_LOG_V(WARNING, TAG, "OCResetDevice : Failed to close DTLS session : %d", caResult);
1861     }
1862
1863     /**
1864      * If there is no linked device, PM does not send any request.
1865      * So we should directly invoke the result callback to inform the result of OCResetDevice.
1866      */
1867     if(OC_STACK_NO_RESOURCE == res)
1868     {
1869         res = OC_STACK_OK;
1870     }
1871
1872 error:
1873     OICFree(pTargetDev);
1874     return OC_STACK_DELETE_TRANSACTION;
1875
1876 }
1877
1878 static OCStackResult GetListofDevToReqDeleteCred(const OCProvisionDev_t* pRevokeTargetDev,
1879                                                  OCProvisionDev_t* pOwnedDevList,
1880                                                  OCUuidList_t* pLinkedUuidList,
1881                                                  OCProvisionDev_t** ppLinkedDevList,
1882                                                  size_t *numOfLinkedDev)
1883 {
1884     // pOwnedDevList could be NULL. It means no alived and owned device now.
1885     if (pRevokeTargetDev == NULL || pLinkedUuidList == NULL ||\
1886         ppLinkedDevList == NULL || numOfLinkedDev == NULL)
1887     {
1888         return OC_STACK_INVALID_PARAM;
1889     }
1890
1891     size_t cnt = 0;
1892     OCUuidList_t *curUuid = NULL, *tmpUuid = NULL;
1893     LL_FOREACH_SAFE(pLinkedUuidList, curUuid, tmpUuid)
1894     {
1895         // Mark the link status stale.
1896         OCStackResult res = PDMSetLinkStale(&curUuid->dev, &pRevokeTargetDev->doxm->deviceID);
1897         if (OC_STACK_OK != res)
1898         {
1899             OIC_LOG(FATAL, TAG, "PDMSetLinkStale() FAIL: PDB is an obsolete one.");
1900             return OC_STACK_INCONSISTENT_DB;
1901         }
1902
1903         if (pOwnedDevList)
1904         {
1905             // If this linked device is alive (power-on), add the deivce to the list.
1906             OCProvisionDev_t *curDev = NULL, *tmpDev = NULL;
1907             LL_FOREACH_SAFE(pOwnedDevList, curDev, tmpDev)
1908             {
1909                 if (memcmp(curDev->doxm->deviceID.id, curUuid->dev.id, sizeof(curUuid->dev.id)) == 0)
1910                 {
1911                     OCProvisionDev_t* targetDev = PMCloneOCProvisionDev(curDev);
1912                     if (NULL == targetDev)
1913                     {
1914                         OIC_LOG(ERROR, TAG, "SRPRemoveDevice : Cloning OCProvisionDev_t Failed.");
1915                         return OC_STACK_NO_MEMORY;
1916                     }
1917
1918                     LL_PREPEND(*ppLinkedDevList, targetDev);
1919                     cnt++;
1920                     break;
1921                 }
1922             }
1923         }
1924     }
1925     *numOfLinkedDev = cnt;
1926     return OC_STACK_OK;
1927 }
1928
1929 /*
1930 * Function to device revocation
1931 * This function will remove credential of target device from all devices in subnet.
1932 *
1933 * @param[in] ctx Application context would be returned in result callback
1934 * @param[in] waitTimeForOwnedDeviceDiscovery Maximum wait time for owned device discovery.(seconds)
1935 * @param[in] pTargetDev Device information to be revoked.
1936 * @param[in] resultCallback callback provided by API user, callback will be called when
1937 *            credential revocation is finished.
1938 * @return  OC_STACK_OK in case of success and other value otherwise.
1939 *          If OC_STACK_OK is returned, the caller of this API should wait for callback.
1940 *          OC_STACK_CONTINUE means operation is success but no request is need to be initiated.
1941 */
1942 OCStackResult SRPRemoveDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDiscovery,
1943                              const OCProvisionDev_t* pTargetDev, OCProvisionResultCB resultCallback)
1944 {
1945     OIC_LOG(INFO, TAG, "IN SRPRemoveDevice");
1946
1947     if (!pTargetDev  || 0 == waitTimeForOwnedDeviceDiscovery)
1948     {
1949         OIC_LOG(INFO, TAG, "SRPRemoveDevice : NULL parameters");
1950         return OC_STACK_INVALID_PARAM;
1951     }
1952     if (!resultCallback)
1953     {
1954         OIC_LOG(INFO, TAG, "SRPRemoveDevice : NULL Callback");
1955         return OC_STACK_INVALID_CALLBACK;
1956     }
1957
1958     // Declare variables in here to handle error cases with goto statement.
1959     OCProvisionDev_t* pOwnedDevList = NULL;
1960     OCProvisionDev_t* pLinkedDevList = NULL;
1961     RemoveData_t* removeData = NULL;
1962
1963     //1. Find all devices that has a credential of the revoked device
1964     OCUuidList_t* pLinkedUuidList = NULL;
1965     size_t numOfDevices = 0;
1966     OCStackResult res = OC_STACK_ERROR;
1967     res = PDMGetLinkedDevices(&pTargetDev->doxm->deviceID, &pLinkedUuidList, &numOfDevices);
1968     if (OC_STACK_OK != res)
1969     {
1970         OIC_LOG(ERROR, TAG, "SRPRemoveDevice : Failed to get linked devices information");
1971         return res;
1972     }
1973     // if there is no related device, we can skip further process.
1974     if (0 == numOfDevices)
1975     {
1976         OIC_LOG(DEBUG, TAG, "SRPRemoveDevice : No linked device found.");
1977         res = OC_STACK_CONTINUE;
1978         goto error;
1979     }
1980
1981     //2. Find owned device from the network
1982     res = PMDeviceDiscovery(waitTimeForOwnedDeviceDiscovery, true, &pOwnedDevList);
1983     if (OC_STACK_OK != res)
1984     {
1985         OIC_LOG(ERROR, TAG, "SRPRemoveDevice : Failed to PMDeviceDiscovery");
1986         goto error;
1987     }
1988
1989     //3. Make a list of devices to send DELETE credential request
1990     //   by comparing owned devices from provisioning database with mutlicast discovery result.
1991     size_t numOfLinkedDev = 0;
1992     res = GetListofDevToReqDeleteCred(pTargetDev, pOwnedDevList, pLinkedUuidList,
1993                                       &pLinkedDevList, &numOfLinkedDev);
1994     if (OC_STACK_OK != res)
1995     {
1996         OIC_LOG(ERROR, TAG, "SRPRemoveDevice : GetListofDevToReqDeleteCred() failed");
1997         goto error;
1998     }
1999     if (0 == numOfLinkedDev) // This case means, there is linked device but it's not alive now.
2000     {                       // So we don't have to send request message.
2001         OIC_LOG(DEBUG, TAG, "SRPRemoveDevice : No alived & linked device found.");
2002         res = OC_STACK_CONTINUE;
2003         goto error;
2004     }
2005
2006     // 4. Prepare RemoveData Context data.
2007     removeData = (RemoveData_t*)OICCalloc(1, sizeof(RemoveData_t));
2008     if (!removeData)
2009     {
2010         OIC_LOG(ERROR, TAG, "SRPRemoveDevices : Failed to memory allocation");
2011         res = OC_STACK_NO_MEMORY;
2012         goto error;
2013     }
2014
2015     removeData->revokeTargetDev = PMCloneOCProvisionDev(pTargetDev);
2016     if (!removeData->revokeTargetDev)
2017     {
2018         OIC_LOG(ERROR, TAG, "SRPRemoveDevices : PMCloneOCProvisionDev Failed");
2019         res = OC_STACK_NO_MEMORY;
2020         goto error;
2021     }
2022
2023     removeData->removeRes =
2024         (OCProvisionResult_t*)OICCalloc(numOfLinkedDev, sizeof(OCProvisionResult_t));
2025     if (!removeData->removeRes)
2026     {
2027         OIC_LOG(ERROR, TAG, "SRPRemoveDevices : Failed to memory allocation");
2028         res = OC_STACK_NO_MEMORY;
2029         goto error;
2030     }
2031
2032     removeData->ctx = ctx;
2033     removeData->linkedDevList = pLinkedDevList;
2034     removeData->resultCallback = resultCallback;
2035     removeData->numOfResults = 0;
2036     removeData->sizeOfResArray = numOfLinkedDev;
2037     removeData->hasError = false;
2038
2039     // 5. Send DELETE credential request to linked devices.
2040     OCProvisionDev_t *curDev = NULL, *tmpDev = NULL;
2041     OCStackResult totalRes = OC_STACK_ERROR;  /* variable for checking request is sent or not */
2042     LL_FOREACH_SAFE(pLinkedDevList, curDev, tmpDev)
2043     {
2044         res = SendDeleteCredentialRequest((void*)removeData, &SRPRemoveDeviceCB,
2045                                            removeData->revokeTargetDev, curDev);
2046         if (OC_STACK_OK != res)
2047         {
2048             OIC_LOG_V(ERROR, TAG, "SRPRemoveDevice : Fail to send the DELETE credential request to\
2049                      %s:%u", curDev->endpoint.addr, curDev->endpoint.port);
2050         }
2051         else
2052         {
2053             totalRes = OC_STACK_OK; // This means at least one request is successfully sent.
2054         }
2055     }
2056
2057     PDMDestoryOicUuidLinkList(pLinkedUuidList); //TODO: Modify API name to have unified convention.
2058     PMDeleteDeviceList(pOwnedDevList);
2059     OIC_LOG(INFO, TAG, "OUT SRPRemoveDevice");
2060
2061     return totalRes; // Caller of this API should wait callback if totalRes == OC_STACK_OK.
2062
2063 error:
2064     PDMDestoryOicUuidLinkList(pLinkedUuidList);
2065     PMDeleteDeviceList(pOwnedDevList);
2066     PMDeleteDeviceList(pLinkedDevList);
2067     if (removeData)
2068     {
2069         OICFree(removeData->revokeTargetDev);
2070         OICFree(removeData->removeRes);
2071         OICFree(removeData);
2072     }
2073     OIC_LOG(INFO, TAG, "OUT ERROR case SRPRemoveDevice");
2074     return res;
2075 }
2076
2077 /*
2078 * Function to device revocation
2079 * This function will remove credential of target device from all devices in subnet.
2080 *
2081 * @param[in] ctx Application context would be returned in result callback
2082 * @param[in] pOwnedDevList List of owned devices
2083 * @param[in] pTargetDev Device information to be revoked.
2084 * @param[in] resultCallback callback provided by API user, callback will be called when
2085 *            credential revocation is finished.
2086 * @return  OC_STACK_OK in case of success and other value otherwise.
2087 *          If OC_STACK_OK is returned, the caller of this API should wait for callback.
2088 *          OC_STACK_CONTINUE means operation is success but no request is need to be initiated.
2089 */
2090 OCStackResult SRPRemoveDeviceWithoutDiscovery(void* ctx, const OCProvisionDev_t* pOwnedDevList,
2091                              const OCProvisionDev_t* pTargetDev, OCProvisionResultCB resultCallback)
2092 {
2093     OIC_LOG(INFO, TAG, "IN SRPRemoveDeviceWithoutDiscovery");
2094
2095     if (!pOwnedDevList)
2096     {
2097         OIC_LOG(WARNING, TAG, "SRPRemoveDeviceWithoutDiscovery : Owned Device List is empty");
2098         return OC_STACK_CONTINUE;
2099     }
2100     if (!pTargetDev)
2101     {
2102         OIC_LOG(INFO, TAG, "SRPRemoveDeviceWithoutDiscovery : NULL parameters");
2103         return OC_STACK_INVALID_PARAM;
2104     }
2105     if (!resultCallback)
2106     {
2107         OIC_LOG(INFO, TAG, "SRPRemoveDeviceWithoutDiscovery : NULL Callback");
2108         return OC_STACK_INVALID_CALLBACK;
2109     }
2110
2111     // Declare variables in here to handle error cases with goto statement.
2112     OCProvisionDev_t* pLinkedDevList = NULL;
2113     RemoveData_t* removeData = NULL;
2114
2115     //1. Find all devices that has a credential of the revoked device
2116     OCUuidList_t* pLinkedUuidList = NULL;
2117     size_t numOfDevices = 0;
2118     OCStackResult res = OC_STACK_ERROR;
2119     res = PDMGetLinkedDevices(&pTargetDev->doxm->deviceID, &pLinkedUuidList, &numOfDevices);
2120     if (OC_STACK_OK != res)
2121     {
2122         OIC_LOG(WARNING, TAG, "SRPRemoveDeviceWithoutDiscovery : Failed to get linked devices information");
2123         return OC_STACK_CONTINUE;
2124     }
2125     // if there is no related device, we can skip further process.
2126     if (0 == numOfDevices)
2127     {
2128         OIC_LOG(WARNING, TAG, "SRPRemoveDeviceWithoutDiscovery : No linked device found.");
2129         return OC_STACK_CONTINUE;
2130     }
2131
2132     //2. Make a list of devices to send DELETE credential request
2133     //   by comparing owned devices from provisioning database with mutlicast discovery result.
2134     size_t numOfLinkedDev = 0;
2135     res = GetListofDevToReqDeleteCred(pTargetDev, pOwnedDevList, pLinkedUuidList,
2136                                       &pLinkedDevList, &numOfLinkedDev);
2137     if (OC_STACK_OK != res)
2138     {
2139         OIC_LOG(ERROR, TAG, "SRPRemoveDeviceWithoutDiscovery : GetListofDevToReqDeleteCred() failed");
2140         goto error;
2141     }
2142     if (0 == numOfLinkedDev) // This case means, there is linked device but it's not alive now.
2143     {                       // So we don't have to send request message.
2144         OIC_LOG(DEBUG, TAG, "SRPRemoveDeviceWithoutDiscovery : No alived & linked device found.");
2145         return OC_STACK_CONTINUE;
2146     }
2147
2148     // 3. Prepare RemoveData Context data.
2149     removeData = (RemoveData_t*)OICCalloc(1, sizeof(RemoveData_t));
2150     if (!removeData)
2151     {
2152         OIC_LOG(ERROR, TAG, "SRPRemoveDeviceWithoutDiscovery : Failed to memory allocation");
2153         res = OC_STACK_NO_MEMORY;
2154         goto error;
2155     }
2156
2157     removeData->revokeTargetDev = PMCloneOCProvisionDev(pTargetDev);
2158     if (!removeData->revokeTargetDev)
2159     {
2160         OIC_LOG(ERROR, TAG, "SRPRemoveDeviceWithoutDiscovery : PMCloneOCProvisionDev Failed");
2161         res = OC_STACK_NO_MEMORY;
2162         goto error;
2163     }
2164
2165     removeData->removeRes =
2166         (OCProvisionResult_t*)OICCalloc(numOfLinkedDev, sizeof(OCProvisionResult_t));
2167     if (!removeData->removeRes)
2168     {
2169         OIC_LOG(ERROR, TAG, "SRPRemoveDeviceWithoutDiscovery : Failed to memory allocation");
2170         res = OC_STACK_NO_MEMORY;
2171         goto error;
2172     }
2173
2174     removeData->ctx = ctx;
2175     removeData->linkedDevList = pLinkedDevList;
2176     removeData->resultCallback = resultCallback;
2177     removeData->numOfResults = 0;
2178     removeData->sizeOfResArray = numOfLinkedDev;
2179     removeData->hasError = false;
2180
2181     // 5. Send DELETE credential request to linked devices.
2182     OCProvisionDev_t *curDev = NULL, *tmpDev = NULL;
2183     OCStackResult totalRes = OC_STACK_ERROR;  /* variable for checking request is sent or not */
2184     LL_FOREACH_SAFE(pLinkedDevList, curDev, tmpDev)
2185     {
2186         res = SendDeleteCredentialRequest((void*)removeData, &SRPRemoveDeviceCB,
2187                                            removeData->revokeTargetDev, curDev);
2188         if (OC_STACK_OK != res)
2189         {
2190             OIC_LOG_V(ERROR, TAG, "SRPRemoveDeviceWithoutDiscovery : Fail to send the DELETE credential request to\
2191                      %s:%u", curDev->endpoint.addr, curDev->endpoint.port);
2192         }
2193         else
2194         {
2195             totalRes = OC_STACK_OK; // This means at least one request is successfully sent.
2196         }
2197     }
2198
2199     PDMDestoryOicUuidLinkList(pLinkedUuidList); //TODO: Modify API name to have unified convention.
2200     OIC_LOG(INFO, TAG, "OUT SRPRemoveDeviceWithoutDiscovery");
2201
2202     return totalRes; // Caller of this API should wait callback if totalRes == OC_STACK_OK.
2203
2204 error:
2205     PDMDestoryOicUuidLinkList(pLinkedUuidList);
2206     PMDeleteDeviceList(pLinkedDevList);
2207     if (removeData)
2208     {
2209         OICFree(removeData->revokeTargetDev);
2210         OICFree(removeData->removeRes);
2211         OICFree(removeData);
2212     }
2213     OIC_LOG(INFO, TAG, "OUT ERROR case SRPRemoveDeviceWithoutDiscovery");
2214     return res;
2215 }
2216
2217 /*
2218  * Function to sync-up credential and ACL of the target device.
2219  * This function will remove credential and ACL of target device from all devices in subnet.
2220  *
2221  * @param[in] ctx Application context would be returned in result callback
2222  * @param[in] waitTimeForOwnedDeviceDiscovery Maximum wait time for owned device discovery.(seconds)
2223  * @param[in] pTargetDev Device information to be revoked.
2224  * @param[in] resultCallback callback provided by API user, callback will be called when
2225  *            credential revocation is finished.
2226  *            when there is an error, this user callback is called immediately.
2227  * @return OC_STACK_OK in case of success and other value otherwise.
2228  *         If OC_STACK_OK is returned, the caller of this API should wait for callback.
2229  *         OC_STACK_CONTINUE means operation is success but no request is need to be initiated.
2230  */
2231 OCStackResult SRPSyncDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDiscovery,
2232                          const OCProvisionDev_t* pTargetDev, OCProvisionResultCB resultCallback)
2233 {
2234     OIC_LOG(INFO, TAG, "IN SRPSyncDevice");
2235     if (!pTargetDev  || 0 == waitTimeForOwnedDeviceDiscovery)
2236     {
2237         OIC_LOG(INFO, TAG, "SRPSyncDevice : NULL parameters");
2238         return OC_STACK_INVALID_PARAM;
2239     }
2240     if (!resultCallback)
2241     {
2242         OIC_LOG(INFO, TAG, "SRPSyncDevice : NULL Callback");
2243         return OC_STACK_INVALID_CALLBACK;
2244     }
2245
2246     // Declare variables in here to handle error cases with goto statement.
2247     OCProvisionDev_t* pOwnedDevList = NULL;
2248     OCProvisionDev_t* pLinkedDevList = NULL;
2249     RemoveData_t* removeData = NULL;
2250
2251     //1. Find all devices that has a credential of the revoked device
2252     OCUuidList_t* pLinkedUuidList = NULL;
2253     size_t numOfDevices = 0;
2254     OCStackResult res = OC_STACK_ERROR;
2255     res = PDMGetLinkedDevices(&pTargetDev->doxm->deviceID, &pLinkedUuidList, &numOfDevices);
2256     if (OC_STACK_OK != res)
2257     {
2258         OIC_LOG(ERROR, TAG, "SRPSyncDevice : Failed to get linked devices information");
2259         return res;
2260     }
2261     // if there is no related device, we can skip further process.
2262     if (0 == numOfDevices)
2263     {
2264         OIC_LOG(DEBUG, TAG, "SRPSyncDevice : No linked device found.");
2265         res = OC_STACK_CONTINUE;
2266         goto error;
2267     }
2268
2269     //2. Find owned device from the network
2270     res = PMDeviceDiscovery(waitTimeForOwnedDeviceDiscovery, true, &pOwnedDevList);
2271     if (OC_STACK_OK != res)
2272     {
2273         OIC_LOG(ERROR, TAG, "SRPSyncDevice : Failed to PMDeviceDiscovery");
2274         goto error;
2275     }
2276
2277     //3. Make a list of devices to send DELETE credential request
2278     //   by comparing owned devices from provisioning database with mutlicast discovery result.
2279     size_t numOfLinkedDev = 0;
2280     res = GetListofDevToReqDeleteCred(pTargetDev, pOwnedDevList, pLinkedUuidList,
2281                                       &pLinkedDevList, &numOfLinkedDev);
2282     if (OC_STACK_OK != res)
2283     {
2284         OIC_LOG(ERROR, TAG, "SRPSyncDevice : GetListofDevToReqDeleteCred() failed");
2285         goto error;
2286     }
2287     if (0 == numOfLinkedDev) // This case means, there is linked device but it's not alive now.
2288     {                       // So we don't have to send request message.
2289         OIC_LOG(DEBUG, TAG, "SRPSyncDevice : No alived & linked device found.");
2290         res = OC_STACK_CONTINUE;
2291         goto error;
2292     }
2293
2294     // 4. Prepare RemoveData Context data.
2295     removeData = (RemoveData_t*)OICCalloc(1, sizeof(RemoveData_t));
2296     if (!removeData)
2297     {
2298         OIC_LOG(ERROR, TAG, "SRPSyncDevice : Failed to memory allocation");
2299         res = OC_STACK_NO_MEMORY;
2300         goto error;
2301     }
2302
2303     removeData->revokeTargetDev = PMCloneOCProvisionDev(pTargetDev);
2304     if (!removeData->revokeTargetDev)
2305     {
2306         OIC_LOG(ERROR, TAG, "SRPSyncDevice : PMCloneOCProvisionDev Failed");
2307         res = OC_STACK_NO_MEMORY;
2308         goto error;
2309     }
2310
2311     removeData->removeRes =
2312         (OCProvisionResult_t*)OICCalloc(numOfLinkedDev, sizeof(OCProvisionResult_t));
2313     if (!removeData->removeRes)
2314     {
2315         OIC_LOG(ERROR, TAG, "SRPSyncDevice : Failed to allocate memory");
2316         res = OC_STACK_NO_MEMORY;
2317         goto error;
2318     }
2319
2320     removeData->ctx = ctx;
2321     removeData->linkedDevList = pLinkedDevList;
2322     removeData->resultCallback = resultCallback;
2323     removeData->numOfResults = 0;
2324     removeData->sizeOfResArray = numOfLinkedDev;
2325     removeData->hasError = false;
2326
2327     // 5. Send DELETE credential request to linked devices.
2328     OCProvisionDev_t *curDev = NULL, *tmpDev = NULL;
2329     OCStackResult totalRes = OC_STACK_ERROR;  /* variable for checking request is sent or not */
2330     LL_FOREACH_SAFE(pLinkedDevList, curDev, tmpDev)
2331     {
2332         res = SendDeleteACLRequest((void*)removeData, &SRPSyncDeviceACLCB,
2333                                            removeData->revokeTargetDev, curDev);
2334         if (OC_STACK_OK != res)
2335         {
2336             OIC_LOG_V(ERROR, TAG, "SRPSyncDevice : Fail to send the DELETE ACL request to\
2337                      %s:%u", curDev->endpoint.addr, curDev->endpoint.port);
2338             goto error;
2339         }
2340         res = SendDeleteCredentialRequest((void*)removeData, &SRPSyncDeviceCredCB,
2341                                            removeData->revokeTargetDev, curDev);
2342         if (OC_STACK_OK != res)
2343         {
2344             OIC_LOG_V(ERROR, TAG, "SRPSyncDevice : Fail to send the DELETE credential request to\
2345                      %s:%u", curDev->endpoint.addr, curDev->endpoint.port);
2346             totalRes = OC_STACK_ERROR;
2347         }
2348         else
2349         {
2350             totalRes = OC_STACK_OK; // This means at least one request is successfully sent.
2351         }
2352     }
2353
2354     PDMDestoryOicUuidLinkList(pLinkedUuidList); //TODO: Modify API name to have unified convention.
2355     PMDeleteDeviceList(pOwnedDevList);
2356     OIC_LOG(INFO, TAG, "OUT SRPSyncDevice");
2357
2358     return totalRes; // Caller of this API should wait callback if totalRes == OC_STACK_OK.
2359
2360 error:
2361     PDMDestoryOicUuidLinkList(pLinkedUuidList);
2362     PMDeleteDeviceList(pOwnedDevList);
2363     PMDeleteDeviceList(pLinkedDevList);
2364     if (removeData)
2365     {
2366         OICFree(removeData->revokeTargetDev);
2367         OICFree(removeData->removeRes);
2368         OICFree(removeData);
2369     }
2370     OIC_LOG(INFO, TAG, "OUT ERROR case SRPSyncDevice");
2371     return res;
2372 }
2373
2374 /*
2375  * Function for remote reset
2376  * This function will send pstat PUT message to the target device to initiate remote reset.
2377  *
2378  * @param[in] pTargetDev Device information to be revoked.
2379  * @param[in] resultCallback callback provided by API user, callback will be called when
2380  *            credential revocation is finished.
2381  *            when there is an error, this user callback is called immediately.
2382  * @return OC_STACK_OK in case of success and other value otherwise.
2383  *         If OC_STACK_OK is returned, the caller of this API should wait for callback.
2384  *         OC_STACK_CONTINUE means operation is success but no request is need to be initiated.
2385  */
2386 OCStackResult SRPResetDevice(const OCProvisionDev_t* pTargetDev,
2387         OCProvisionResultCB resultCallback)
2388 {
2389     OIC_LOG(INFO, TAG, "IN SRPResetDevice");
2390     if (!pTargetDev)
2391     {
2392         OIC_LOG(INFO, TAG, "SRPResetDevice : NULL parameters");
2393         return OC_STACK_INVALID_PARAM;
2394     }
2395     if (!resultCallback)
2396     {
2397         OIC_LOG(INFO, TAG, "SRPResetDevice : NULL Callback");
2398         return OC_STACK_INVALID_CALLBACK;
2399     }
2400
2401     OCStackResult res = OC_STACK_ERROR;
2402     OicSecPstat_t * pstat = (OicSecPstat_t *) OICCalloc(1, sizeof(OicSecPstat_t));
2403     if (!pstat)
2404     {
2405         OIC_LOG(ERROR, TAG, "Failed to allocate memory");
2406         return OC_STACK_NO_MEMORY;
2407     }
2408
2409     pstat->cm = RESET;
2410     pstat->isOp = false;
2411     memcpy(pstat->deviceID.id, pTargetDev->doxm->deviceID.id, sizeof(OicUuid_t));
2412     pstat->tm = TAKE_OWNER;
2413     pstat->om = (OicSecDpom_t)(SINGLE_SERVICE_CLIENT_DRIVEN); // the only mode IoTivity supports currently
2414     pstat->smLen = 1;
2415     pstat->sm = (OicSecDpom_t *) OICCalloc(pstat->smLen, sizeof(OicSecDpom_t));
2416     if (NULL == pstat->sm)
2417     {
2418         OIC_LOG(ERROR, TAG, "Failed to allocate memory");
2419         OICFree(pstat);
2420         return OC_STACK_NO_MEMORY;
2421     }
2422     pstat->sm[0] = (OicSecDpom_t)(SINGLE_SERVICE_CLIENT_DRIVEN); // the only mode IoTivity supports currently
2423
2424     OCSecurityPayload * secPayload = (OCSecurityPayload *) OICCalloc(1, sizeof(OCSecurityPayload));
2425     if (!secPayload)
2426     {
2427         OIC_LOG(ERROR, TAG, "Failed to allocate memory");
2428         res = OC_STACK_NO_MEMORY;
2429         goto error;
2430     }
2431     secPayload->base.type = PAYLOAD_TYPE_SECURITY;
2432
2433     if (OC_STACK_OK != PstatToCBORPayload(pstat, &(secPayload->securityData),
2434                 &(secPayload->payloadSize), true))
2435     {
2436         OCPayloadDestroy((OCPayload *) secPayload);
2437         OIC_LOG(ERROR, TAG, "Failed to PstatToCBORPayload");
2438         res = OC_STACK_NO_MEMORY;
2439         goto error;
2440     }
2441     OIC_LOG(DEBUG, TAG, "Created payload for pstat set");
2442     OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
2443
2444     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
2445     if (!PMGenerateQuery(true,
2446                 pTargetDev->endpoint.addr,
2447                 pTargetDev->securePort,
2448                 pTargetDev->connType,
2449                 query, sizeof(query), OIC_RSRC_PSTAT_URI))
2450     {
2451         OIC_LOG(ERROR, TAG, "SRPResetDevice : Failed to generate query");
2452         OCPayloadDestroy((OCPayload *) secPayload);
2453         res = OC_STACK_ERROR;
2454         goto error;
2455     }
2456     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
2457
2458     OCCallbackData cbData = { .context = NULL, .cb = NULL, .cd = NULL };
2459     OCMethod method = OC_REST_POST;
2460     OCDoHandle handle = NULL;
2461     OCProvisionDev_t * targetDev = PMCloneOCProvisionDev(pTargetDev);
2462     if (NULL == targetDev)
2463     {
2464         OIC_LOG(ERROR, TAG, "target dev is null");
2465         res = OC_STACK_ERROR;
2466         goto error;
2467     }
2468     cbData.cb = &SRPResetDeviceCB;
2469     cbData.context = (void *) targetDev;
2470     cbData.cd = NULL;
2471     OIC_LOG(DEBUG, TAG, "Sending PSTAT info to resource server");
2472     res = OCDoResource(&handle, method, query,
2473             &targetDev->endpoint, (OCPayload *)secPayload,
2474             targetDev->connType, OC_LOW_QOS, &cbData, NULL, 0);\
2475     if (OC_STACK_OK != res)
2476     {
2477         OIC_LOG(ERROR, TAG, "OCStack resource error");
2478     }
2479
2480 error:
2481     OICFree(pstat->sm);
2482     OICFree(pstat);
2483     OIC_LOG(INFO, TAG, "OUT SRPResetDevice");
2484     return res;
2485 }
2486
2487 /**
2488  * Internal Function to store results in result array during GetCredResourceCB.
2489  */
2490 static void registerResultForGetCredResourceCB(GetSecData_t *GetSecData,
2491                                              OCStackResult stackresult)
2492 {
2493    OIC_LOG_V(INFO, TAG, "Inside registerResultForGetCredResourceCB "
2494            "GetSecData->numOfResults is %d\n", GetSecData->numOfResults);
2495    memcpy(GetSecData->resArr[(GetSecData->numOfResults)].deviceId.id,
2496           GetSecData->deviceInfo->doxm->deviceID.id, UUID_LENGTH);
2497    GetSecData->resArr[(GetSecData->numOfResults)].res = stackresult;
2498    ++(GetSecData->numOfResults);
2499 }
2500
2501 /**
2502  * Callback handler of SRPGetCredResource.
2503  *
2504  * @param[in] ctx             ctx value passed to callback from calling function.
2505  * @param[in] UNUSED          handle to an invocation
2506  * @param[in] clientResponse  Response from queries to remote servers.
2507  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
2508  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
2509  */
2510 static OCStackApplicationResult SRPGetCredResourceCB(void *ctx, OCDoHandle UNUSED,
2511                                                   OCClientResponse *clientResponse)
2512 {
2513     OIC_LOG_V(INFO, TAG, "Inside SRPGetCredResourceCB.");
2514     (void)UNUSED;
2515     VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
2516     GetSecData_t *GetSecData = (GetSecData_t*)ctx;
2517     OCProvisionResultCB resultCallback = GetSecData->resultCallback;
2518
2519     if (clientResponse)
2520     {
2521         if(OC_STACK_OK == clientResponse->result)
2522         {
2523             uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData;
2524             size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
2525
2526             OIC_LOG_BUFFER(DEBUG, TAG, payload, size);
2527
2528             registerResultForGetCredResourceCB(GetSecData, OC_STACK_OK);
2529             ((OCProvisionResultCB)(resultCallback))(GetSecData->ctx, GetSecData->numOfResults,
2530                                                     GetSecData->resArr,
2531                                                     false);
2532              OICFree(GetSecData->resArr);
2533              OICFree(GetSecData);
2534
2535             return OC_STACK_DELETE_TRANSACTION;
2536         }
2537     }
2538     registerResultForGetCredResourceCB(GetSecData, OC_STACK_OK);
2539     ((OCProvisionResultCB)(resultCallback))(GetSecData->ctx, GetSecData->numOfResults,
2540                                             GetSecData->resArr,
2541                                             false);
2542     OIC_LOG_V(ERROR, TAG, "SRPGetCredResourceCB received Null clientResponse");
2543     OICFree(GetSecData->resArr);
2544     OICFree(GetSecData);
2545
2546     return OC_STACK_DELETE_TRANSACTION;
2547 }
2548
2549
2550 OCStackResult SRPGetCredResource(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
2551         OCProvisionResultCB resultCallback)
2552 {
2553     VERIFY_NON_NULL(TAG, selectedDeviceInfo, ERROR,  OC_STACK_INVALID_PARAM);
2554     VERIFY_NON_NULL(TAG, resultCallback, ERROR,  OC_STACK_INVALID_CALLBACK);
2555
2556     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
2557     if(!PMGenerateQuery(true,
2558                         selectedDeviceInfo->endpoint.addr,
2559                         selectedDeviceInfo->securePort,
2560                         selectedDeviceInfo->connType,
2561                         query, sizeof(query), OIC_RSRC_CRED_URI))
2562     {
2563         OIC_LOG(ERROR, TAG, "SRPGetCredResource : Failed to generate query");
2564         return OC_STACK_ERROR;
2565     }
2566     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
2567
2568     OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};
2569     cbData.cb = &SRPGetCredResourceCB;
2570     GetSecData_t* GetSecData = (GetSecData_t*)OICCalloc(1, sizeof(GetSecData_t));
2571     if (NULL == GetSecData)
2572     {
2573         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
2574         return OC_STACK_NO_MEMORY;
2575     }
2576     GetSecData->deviceInfo = selectedDeviceInfo;
2577     GetSecData->resultCallback = resultCallback;
2578     GetSecData->numOfResults=0;
2579     GetSecData->ctx = ctx;
2580
2581     int noOfRiCalls = 1;
2582     GetSecData->resArr = (OCProvisionResult_t*)OICCalloc(noOfRiCalls, sizeof(OCProvisionResult_t));
2583     if (NULL == GetSecData->resArr)
2584     {
2585         OICFree(GetSecData);
2586         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
2587         return OC_STACK_NO_MEMORY;
2588     }
2589     cbData.context = (void *)GetSecData;
2590     cbData.cd = NULL;
2591     OCMethod method = OC_REST_GET;
2592     OCDoHandle handle = NULL;
2593     OIC_LOG(DEBUG, TAG, "Sending Get Cred to  resource server");
2594     OCStackResult ret = OCDoResource(&handle, method, query, NULL, NULL,
2595             selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
2596     if (OC_STACK_OK != ret)
2597     {
2598         OIC_LOG(ERROR, TAG, "OCStack resource error");
2599         OICFree(GetSecData->resArr);
2600         OICFree(GetSecData);
2601     }
2602     VERIFY_SUCCESS(TAG, (OC_STACK_OK == ret), ERROR, OC_STACK_ERROR);
2603     OIC_LOG(DEBUG, TAG, "OUT SRPGetCredResource");
2604
2605     return OC_STACK_OK;
2606 }
2607
2608 /**
2609  * Internal Function to store results in result array during GetACLResourceCB.
2610  */
2611 static void registerResultForGetACLResourceCB(GetSecData_t *GetSecData,
2612                                              OCStackResult stackresult)
2613 {
2614    OIC_LOG_V(INFO, TAG, "Inside registerResultForGetACLResourceCB "
2615            "GetSecData->numOfResults is %d\n", GetSecData->numOfResults);
2616    memcpy(GetSecData->resArr[(GetSecData->numOfResults)].deviceId.id,
2617           GetSecData->deviceInfo->doxm->deviceID.id, UUID_LENGTH);
2618    GetSecData->resArr[(GetSecData->numOfResults)].res = stackresult;
2619    ++(GetSecData->numOfResults);
2620 }
2621
2622 /**
2623  * Callback handler of SRPGetACLResource.
2624  *
2625  * @param[in] ctx             ctx value passed to callback from calling function.
2626  * @param[in] UNUSED          handle to an invocation
2627  * @param[in] clientResponse  Response from queries to remote servers.
2628  * @return  OC_STACK_DELETE_TRANSACTION to delete the transaction
2629  *          and  OC_STACK_KEEP_TRANSACTION to keep it.
2630  */
2631 static OCStackApplicationResult SRPGetACLResourceCB(void *ctx, OCDoHandle UNUSED,
2632                                                   OCClientResponse *clientResponse)
2633 {
2634     OIC_LOG_V(INFO, TAG, "Inside SRPGetACLResourceCB.");
2635     (void)UNUSED;
2636     VERIFY_NON_NULL(TAG, ctx, ERROR, OC_STACK_DELETE_TRANSACTION);
2637     GetSecData_t *GetSecData = (GetSecData_t*)ctx;
2638     OCProvisionResultCB resultCallback = GetSecData->resultCallback;
2639
2640     if (clientResponse)
2641     {
2642         if(OC_STACK_OK == clientResponse->result)
2643         {
2644             uint8_t *payload = ((OCSecurityPayload*)clientResponse->payload)->securityData;
2645             size_t size = ((OCSecurityPayload*)clientResponse->payload)->payloadSize;
2646
2647             OIC_LOG_BUFFER(DEBUG, TAG, payload, size);
2648
2649             registerResultForGetACLResourceCB(GetSecData, OC_STACK_OK);
2650             ((OCProvisionResultCB)(resultCallback))(GetSecData->ctx, GetSecData->numOfResults,
2651                                                     GetSecData->resArr,
2652                                                     false);
2653              OICFree(GetSecData->resArr);
2654              OICFree(GetSecData);
2655
2656             return OC_STACK_DELETE_TRANSACTION;
2657         }
2658     }
2659     registerResultForGetACLResourceCB(GetSecData, OC_STACK_OK);
2660     ((OCProvisionResultCB)(resultCallback))(GetSecData->ctx, GetSecData->numOfResults,
2661                                             GetSecData->resArr,
2662                                             false);
2663     OIC_LOG_V(ERROR, TAG, "SRPGetACLResourceCB received Null clientResponse");
2664     OICFree(GetSecData->resArr);
2665     OICFree(GetSecData);
2666
2667     return OC_STACK_DELETE_TRANSACTION;
2668 }
2669
2670
2671 OCStackResult SRPGetACLResource(void *ctx, const OCProvisionDev_t *selectedDeviceInfo,
2672         OCProvisionResultCB resultCallback)
2673 {
2674     VERIFY_NON_NULL(TAG, selectedDeviceInfo, ERROR,  OC_STACK_INVALID_PARAM);
2675     VERIFY_NON_NULL(TAG, resultCallback, ERROR,  OC_STACK_INVALID_CALLBACK);
2676
2677     char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
2678     if(!PMGenerateQuery(true,
2679                         selectedDeviceInfo->endpoint.addr,
2680                         selectedDeviceInfo->securePort,
2681                         selectedDeviceInfo->connType,
2682                         query, sizeof(query), OIC_RSRC_ACL_URI))
2683     {
2684         OIC_LOG(ERROR, TAG, "SRPGetACLResource : Failed to generate query");
2685         return OC_STACK_ERROR;
2686     }
2687     OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
2688
2689     OCCallbackData cbData =  {.context=NULL, .cb=NULL, .cd=NULL};
2690     cbData.cb = &SRPGetACLResourceCB;
2691     GetSecData_t* GetSecData = (GetSecData_t*)OICCalloc(1, sizeof(GetSecData_t));
2692     if (NULL == GetSecData)
2693     {
2694         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
2695         return OC_STACK_NO_MEMORY;
2696     }
2697     GetSecData->deviceInfo = selectedDeviceInfo;
2698     GetSecData->resultCallback = resultCallback;
2699     GetSecData->numOfResults=0;
2700     GetSecData->ctx = ctx;
2701
2702     int noOfRiCalls = 1;
2703     GetSecData->resArr = (OCProvisionResult_t*)OICCalloc(noOfRiCalls, sizeof(OCProvisionResult_t));
2704     if (NULL == GetSecData->resArr)
2705     {
2706         OICFree(GetSecData);
2707         OIC_LOG(ERROR, TAG, "Unable to allocate memory");
2708         return OC_STACK_NO_MEMORY;
2709     }
2710     cbData.context = (void *)GetSecData;
2711     cbData.cd = NULL;
2712     OCMethod method = OC_REST_GET;
2713     OCDoHandle handle = NULL;
2714     OIC_LOG(DEBUG, TAG, "Sending Get ACL to resource server");
2715     OCStackResult ret = OCDoResource(&handle, method, query, NULL, NULL,
2716             selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
2717     if (OC_STACK_OK != ret)
2718     {
2719         OIC_LOG(ERROR, TAG, "OCStack resource error");
2720         OICFree(GetSecData->resArr);
2721         OICFree(GetSecData);
2722     }
2723     VERIFY_SUCCESS(TAG, (OC_STACK_OK == ret), ERROR, OC_STACK_ERROR);
2724     OIC_LOG(DEBUG, TAG, "OUT SRPGetACLResource");
2725
2726     return OC_STACK_OK;
2727 }
2728
2729 OCStackResult SRPReadTrustCertChain(uint16_t credId, uint8_t **trustCertChain,
2730                                      size_t *chainSize)
2731 {
2732     OIC_LOG(DEBUG, TAG, "IN SRPReadTrustCertChain");
2733
2734     OCStackResult res = OC_STACK_ERROR;
2735     int secureFlag = 0;
2736     OicSecCred_t* credData = GetCredEntryByCredId(credId);
2737     if(credData)
2738     {
2739         res = CredToCBORPayload((const OicSecCred_t*) credData, trustCertChain,
2740                                 chainSize, secureFlag);
2741         if(OC_STACK_OK != res)
2742         {
2743             OIC_LOG(INFO, TAG, "CredToCBORPayload failed");
2744         }
2745     }
2746     DeleteCredList(credData);
2747     return res;
2748 }