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