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