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