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