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