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