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