Update snapshot(2018-01-10)
[platform/upstream/iotivity.git] / resource / csdk / security / provisioning / src / ocprovisioningmanager.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 <stdint.h>
21 #include <stdio.h>
22 #include <string.h>
23 #include "ocprovisioningmanager.h"
24 #include "pmutility.h"
25 #include "srmutility.h"
26 #include "ownershiptransfermanager.h"
27 #ifdef MULTIPLE_OWNER
28 #include "multipleownershiptransfermanager.h"
29 #endif //MULTIPLE_OWNER
30 #include "oic_malloc.h"
31 #include "logger.h"
32 #include "secureresourceprovider.h"
33 #include "provisioningdatabasemanager.h"
34 #include "credresource.h"
35 #include "utlist.h"
36 #include "aclresource.h" //Note: SRM internal header
37 #include "pconfresource.h"
38 #include "psinterface.h"
39 #include "srmresourcestrings.h"
40
41 #define TAG "OIC_OCPMAPI"
42
43 typedef struct Linkdata Linkdata_t;
44 struct Linkdata
45 {
46     void *ctx;
47     const OCProvisionDev_t *pDev1;
48     OicSecAcl_t *pDev1Acl;
49     const OCProvisionDev_t *pDev2;
50     OicSecAcl_t *pDev2Acl;
51     OCProvisionResult_t *resArr;
52     int numOfResults;
53     int currentCountResults;
54     OCProvisionResultCB resultCallback;
55
56 };
57
58 #ifdef MULTIPLE_OWNER
59 typedef struct ProvPreconfPINCtx ProvPreconfPINCtx_t;
60 struct ProvPreconfPINCtx
61 {
62     void *ctx;
63     const OCProvisionDev_t *devInfo;
64     const char* pin;
65     size_t pinLen;
66     OCProvisionResultCB resultCallback;
67 };
68 #endif //MULTIPLE_OWNER
69
70 /**
71  * The function is responsible for initializaton of the provisioning manager. It will load
72  * provisioning database which have owned device's list and their linked status.
73  * TODO: In addition, if there is a device(s) which has not up-to-date credentials, this function will
74  * automatically try to update the deivce(s).
75  *
76  * @param[in] dbPath file path of the sqlite3 db
77  *
78  * @return OC_STACK_OK in case of success and other value otherwise.
79  */
80 OCStackResult OCInitPM(const char* dbPath)
81 {
82     return PDMInit(dbPath);
83 }
84
85 void OCTerminatePM()
86 {
87     OTMTerminate();
88 }
89
90 OCStackResult OCPDMCleanupForTimeout()
91 {
92     return PDMDeleteDeviceWithState(PDM_DEVICE_INIT);
93 }
94
95 /**
96  * The function is responsible for discovery of owned/unowned device is specified endpoint/deviceID.
97  * And this function will only return the specified device's response.
98  *
99  * @param[in] timeout Timeout in seconds, value till which function will listen to responses from
100  *                    server before returning the device.
101  * @param[in] deviceID         deviceID of target device.
102  * @param[out] ppFoundDevice     OCProvisionDev_t of found device
103  * @return OTM_SUCCESS in case of success and other value otherwise.
104  */
105 OCStackResult OCDiscoverSingleDevice(unsigned short timeout, const OicUuid_t* deviceID,
106                              OCProvisionDev_t **ppFoundDevice)
107 {
108     if( NULL == ppFoundDevice || NULL != *ppFoundDevice || 0 == timeout || NULL == deviceID)
109     {
110         return OC_STACK_INVALID_PARAM;
111     }
112
113     return PMSingleDeviceDiscovery(timeout, deviceID, ppFoundDevice);
114 }
115
116 /**
117  * The function is responsible for discovery of owned/unowned device is specified endpoint/deviceID.
118  * And this function will only return the specified device's response.
119  *
120  * @param[in] timeout Timeout in seconds, value till which function will listen to responses from
121  *                    server before returning the device.
122  * @param[in] deviceID         deviceID of target device.
123  * @param[in] hostAddress       MAC address of target device.
124  * @param[in] connType       ConnectivityType for discovery.
125  * @param[out] ppFoundDevice     OCProvisionDev_t of found device.
126  * @return OTM_SUCCESS in case of success and other value otherwise.
127  */
128 OCStackResult OCDiscoverSingleDeviceInUnicast(unsigned short timeout, const OicUuid_t* deviceID,
129                              const char* hostAddress, OCConnectivityType connType,
130                              OCProvisionDev_t **ppFoundDevice)
131 {
132     if( NULL == ppFoundDevice || NULL != *ppFoundDevice || 0 == timeout || NULL == deviceID ||
133             NULL == hostAddress)
134     {
135         OIC_LOG(ERROR, TAG, "OCDiscoverSingleDeviceInUnicast : Invalid Parameter");
136         return OC_STACK_INVALID_PARAM;
137     }
138
139     return PMSingleDeviceDiscoveryInUnicast(timeout, deviceID, hostAddress, connType,
140             ppFoundDevice);
141 }
142
143 /**
144  * The function is responsible for discovery of device is current subnet. It will list
145  * all the device in subnet which are not yet owned. Please call OCInit with OC_CLIENT_SERVER as
146  * OCMode.
147  *
148  * @param[in] timeout Timeout in seconds, value till which function will listen to responses from
149  *                    server before returning the list of devices.
150  * @param[out] ppList List of candidate devices to be provisioned
151  * @return OTM_SUCCESS in case of success and other value otherwise.
152  */
153 OCStackResult OCDiscoverUnownedDevices(unsigned short timeout, OCProvisionDev_t **ppList)
154 {
155     if( ppList == NULL || *ppList != NULL || 0 == timeout)
156     {
157         return OC_STACK_INVALID_PARAM;
158     }
159
160     return PMDeviceDiscovery(timeout, false, ppList);
161 }
162
163 /**
164  * The function is responsible for discovery of owned device is current subnet. It will list
165  * all the device in subnet which are owned by calling provisioning client.
166  *
167  * @param[in] timeout Timeout in seconds, value till which function will listen to responses from
168  *                    server before returning the list of devices.
169  * @param[out] ppList List of device owned by provisioning tool.
170  * @return OTM_SUCCESS in case of success and other value otherwise.
171  */
172 OCStackResult OCDiscoverOwnedDevices(unsigned short timeout, OCProvisionDev_t **ppList)
173 {
174     if( ppList == NULL || *ppList != NULL || 0 == timeout)
175     {
176         return OC_STACK_INVALID_PARAM;
177     }
178
179     return PMDeviceDiscovery(timeout, true, ppList);
180 }
181
182 #ifdef MULTIPLE_OWNER
183 /**
184  * The function is responsible for discovery of MOT enabled device is current subnet.
185  *
186  * @param[in] timeout Timeout in seconds, value till which function will listen to responses from
187  *                    server before returning the list of devices.
188  * @param[out] ppList List of MOT enabled devices.
189  * @return OC_STACK_OK in case of success and other value otherwise.
190  */
191 OCStackResult OCDiscoverMultipleOwnerEnabledDevices(unsigned short timeout, OCProvisionDev_t **ppList)
192 {
193     if( ppList == NULL || *ppList != NULL || 0 == timeout)
194     {
195         return OC_STACK_INVALID_PARAM;
196     }
197
198     return PMMultipleOwnerDeviceDiscovery(timeout, false, ppList);
199 }
200
201 /**
202  * The function is responsible for discovery of Multiple Owned device is current subnet.
203  *
204  * @param[in] timeout Timeout in seconds, value till which function will listen to responses from
205  *                    server before returning the list of devices.
206  * @param[out] ppList List of Multiple Owned devices.
207  * @return OC_STACK_OK in case of success and other value otherwise.
208  */
209 OCStackResult OCDiscoverMultipleOwnedDevices(unsigned short timeout, OCProvisionDev_t **ppList)
210 {
211     if( ppList == NULL || *ppList != NULL || 0 == timeout)
212     {
213         return OC_STACK_INVALID_PARAM;
214     }
215
216     return PMMultipleOwnerDeviceDiscovery(timeout, true, ppList);
217 }
218
219
220 /**
221  * API to add preconfigured PIN to local SVR DB.
222  *
223  * @param[in] targetDeviceInfo Selected target device.
224  * @param[in] preconfigPin Preconfig PIN which is used while multiple owner authentication
225  * @param[in] preconfigPinLen Byte length of preconfigPin
226  *
227  * @return OC_STACK_OK in case of success and other value otherwise.
228  */
229 OCStackResult OCAddPreconfigPin(const OCProvisionDev_t *targetDeviceInfo,
230                                 const char *preconfigPin,
231                                 size_t preconfigPinLen)
232 {
233     return MOTAddPreconfigPIN(targetDeviceInfo, preconfigPin, preconfigPinLen);
234 }
235
236
237 OCStackResult OCDoMultipleOwnershipTransfer(void* ctx,
238                                       OCProvisionDev_t *targetDevices,
239                                       OCProvisionResultCB resultCallback)
240 {
241     if( NULL == targetDevices )
242     {
243         return OC_STACK_INVALID_PARAM;
244     }
245     if (NULL == resultCallback)
246     {
247         OIC_LOG(INFO, TAG, "OCDoOwnershipTransfer : NULL Callback");
248         return OC_STACK_INVALID_CALLBACK;
249     }
250     return MOTDoOwnershipTransfer(ctx, targetDevices, resultCallback);
251 }
252
253 OCStackResult OCRemoveSubOwner(void* ctx,
254                                 const OCProvisionDev_t *targetDeviceInfo,
255                                 const OicUuid_t* subOwner,
256                                 OCProvisionResultCB resultCallback)
257 {
258     if (NULL == targetDeviceInfo || NULL == subOwner)
259     {
260         OIC_LOG_V(ERROR, TAG, "%s : NULL Param", __func__);
261         return OC_STACK_INVALID_PARAM;
262     }
263     if (NULL == resultCallback)
264     {
265         OIC_LOG_V(ERROR, TAG, "%s : NULL Callback", __func__);
266         return OC_STACK_INVALID_CALLBACK;
267     }
268
269     return MOTRemoveSubOwner(ctx, targetDeviceInfo, subOwner, resultCallback);
270 }
271
272 OCStackResult OCRemoveAllSubOwner(void* ctx,
273                                 const OCProvisionDev_t *targetDeviceInfo,
274                                 OCProvisionResultCB resultCallback)
275 {
276     if (NULL == targetDeviceInfo)
277     {
278         OIC_LOG_V(ERROR, TAG, "%s : NULL Param", __func__);
279         return OC_STACK_INVALID_PARAM;
280     }
281     if (NULL == resultCallback)
282     {
283         OIC_LOG_V(ERROR, TAG, "%s : NULL Callback", __func__);
284         return OC_STACK_INVALID_CALLBACK;
285     }
286
287     return MOTRemoveSubOwner(ctx, targetDeviceInfo, &WILDCARD_SUBJECT_ID, resultCallback);
288 }
289
290
291 #endif //MULTIPLE_OWNER
292
293 /**
294  * API to register for particular OxM.
295  *
296  * @param[in] Ownership transfer method.
297  * @param[in] Implementation of callback functions for owership transfer.
298  * @return  OC_STACK_OK in case of success and other value otherwise.
299  */
300 OCStackResult OCSetOwnerTransferCallbackData(OicSecOxm_t oxm, OTMCallbackData_t* callbackData)
301 {
302     if(NULL == callbackData)
303     {
304         return OC_STACK_INVALID_CALLBACK ;
305     }
306
307     return OTMSetOwnershipTransferCallbackData(oxm, callbackData);
308 }
309
310 /**
311  * API to set a allow status of OxM
312  *
313  * @param[in] oxm Owership transfer method (ref. OicSecOxm_t)
314  * @param[in] allowStatus allow status (true = allow, false = not allow)
315  *
316  * @return OC_STACK_OK in case of success and other value otherwise.
317  */
318 OCStackResult OCSetOxmAllowStatus(const OicSecOxm_t oxm, const bool allowStatus)
319 {
320     return OTMSetOxmAllowStatus(oxm, allowStatus);
321 }
322
323 OCStackResult OCDoOwnershipTransfer(void* ctx,
324                                       OCProvisionDev_t *targetDevices,
325                                       OCProvisionResultCB resultCallback)
326 {
327     if( NULL == targetDevices )
328     {
329         return OC_STACK_INVALID_PARAM;
330     }
331     if (!resultCallback)
332     {
333         OIC_LOG(INFO, TAG, "OCDoOwnershipTransfer : NULL Callback");
334         return OC_STACK_INVALID_CALLBACK;
335     }
336     return OTMDoOwnershipTransfer(ctx, targetDevices, resultCallback);
337 }
338
339 /**
340  * This function deletes memory allocated to linked list created by OCDiscover_XXX_Devices API.
341  *
342  * @param[in] pList Pointer to OCProvisionDev_t which should be deleted.
343  */
344 void OCDeleteDiscoveredDevices(OCProvisionDev_t *pList)
345 {
346     PMDeleteDeviceList(pList);
347 }
348
349 /**
350  * this function sends ACL information to resource.
351  *
352  * @param[in] ctx Application context would be returned in result callback.
353  * @param[in] selectedDeviceInfo Selected target device.
354  * @param[in] acl ACL to provision.
355  * @param[in] resultCallback callback provided by API user, callback will be called when provisioning
356               request recieves a response from resource server.
357  * @return  OC_STACK_OK in case of success and other value otherwise.
358  */
359 OCStackResult OCProvisionACL(void* ctx, const OCProvisionDev_t *selectedDeviceInfo, OicSecAcl_t *acl,
360                              OCProvisionResultCB resultCallback)
361 {
362     return SRPProvisionACL(ctx, selectedDeviceInfo, acl, resultCallback);
363 }
364
365 /**
366  * function to save ACL which has several ACE into Acl of SVR.
367  *
368  * @param acl ACL to be saved in Acl of SVR.
369  * @return  OC_STACK_OK in case of success and other value otherwise.
370  */
371 OCStackResult OCSaveACL(const OicSecAcl_t* acl)
372 {
373     return SRPSaveACL(acl);
374 }
375
376 /**
377  * this function requests CRED information to resource.
378  *
379  * @param[in] ctx Application context would be returned in result callback.
380  * @param[in] selectedDeviceInfo Selected target device.
381  * @param[in] resultCallback callback provided by API user, callback will be called when provisioning
382               request recieves a response from resource server.
383  * @return  OC_STACK_OK in case of success and other value otherwise.
384  */
385 OCStackResult OCGetCredResource(void* ctx, const OCProvisionDev_t *selectedDeviceInfo,
386                              OCProvisionResultCB resultCallback)
387 {
388     return SRPGetCredResource(ctx, selectedDeviceInfo, resultCallback);
389 }
390
391 /**
392  * this function requests ACL information to resource.
393  *
394  * @param[in] ctx Application context would be returned in result callback.
395  * @param[in] selectedDeviceInfo Selected target device.
396  * @param[in] resultCallback callback provided by API user, callback will be called when provisioning
397               request recieves a response from resource server.
398  * @return  OC_STACK_OK in case of success and other value otherwise.
399  */
400 OCStackResult OCGetACLResource(void* ctx, const OCProvisionDev_t *selectedDeviceInfo,
401                              OCProvisionResultCB resultCallback)
402 {
403     return SRPGetACLResource(ctx, selectedDeviceInfo, resultCallback);
404 }
405
406
407 OCStackResult OCReadTrustCertChain(uint16_t credId, uint8_t **trustCertChain,
408                                      size_t *chainSize)
409 {
410     return SRPReadTrustCertChain(credId, trustCertChain, chainSize);
411 }
412 /**
413  * function to provision credential to devices.
414  *
415  * @param[in] ctx Application context would be returned in result callback.
416  * @param[in] type Type of credentials to be provisioned to the device.
417  * @param[in] pDev1 Pointer to OCProvisionDev_t instance,respresenting resource to be provsioned.
418    @param[in] pDev2 Pointer to OCProvisionDev_t instance,respresenting resource to be provsioned.
419  * @param[in] resultCallback callback provided by API user, callback will be called when
420  *            provisioning request recieves a response from first resource server.
421  * @return  OC_STACK_OK in case of success and other value otherwise.
422  */
423 OCStackResult OCProvisionCredentials(void *ctx, OicSecCredType_t type, size_t keySize,
424                                       const OCProvisionDev_t *pDev1,
425                                       const OCProvisionDev_t *pDev2,
426                                       OCProvisionResultCB resultCallback)
427 {
428     return SRPProvisionCredentials(ctx, type, keySize,
429                                       pDev1, pDev2, resultCallback);
430
431 }
432
433 /**
434  * this function sends Direct-Pairing Configuration to a device.
435  *
436  * @param[in] ctx Application context would be returned in result callback.
437  * @param[in] selectedDeviceInfo Selected target device.
438  * @param[in] pconf PCONF pointer.
439  * @param[in] resultCallback callback provided by API user, callback will be called when provisioning
440               request recieves a response from resource server.
441  * @return  OC_STACK_OK in case of success and other value otherwise.
442  */
443 OCStackResult OCProvisionDirectPairing(void* ctx, const OCProvisionDev_t *selectedDeviceInfo, OicSecPconf_t *pconf,
444                              OCProvisionResultCB resultCallback)
445 {
446     return SRPProvisionDirectPairing(ctx, selectedDeviceInfo, pconf, resultCallback);
447 }
448
449 #ifdef MULTIPLE_OWNER
450 static void AddPreconfPinOxMCB(void* ctx, int nOfRes, OCProvisionResult_t *arr, bool hasError)
451 {
452     ProvPreconfPINCtx_t* provCtx = (ProvPreconfPINCtx_t*)ctx;
453     if(provCtx)
454     {
455         OCStackResult res = MOTProvisionPreconfigPIN(provCtx->ctx, provCtx->devInfo, provCtx->pin, provCtx->pinLen, provCtx->resultCallback);
456         if(OC_STACK_OK != res)
457         {
458             arr->res = res;
459             provCtx->resultCallback(provCtx->ctx, nOfRes, arr, true);
460         }
461     }
462 }
463
464 OCStackResult OCProvisionPreconfigPin(void *ctx,
465                                       OCProvisionDev_t *targetDeviceInfo,
466                                       const char *preconfigPin,
467                                       size_t preconfigPinLen,
468                                       OCProvisionResultCB resultCallback)
469 {
470     if( NULL == targetDeviceInfo || NULL == preconfigPin || 0 == preconfigPinLen )
471     {
472         return OC_STACK_INVALID_PARAM;
473     }
474     if (NULL == resultCallback)
475     {
476         OIC_LOG(INFO, TAG, "OCProvisionPreconfigPinCredential : NULL Callback");
477         return OC_STACK_INVALID_CALLBACK;
478     }
479
480     ProvPreconfPINCtx_t* provCtx = (ProvPreconfPINCtx_t*)OICCalloc(1, sizeof(ProvPreconfPINCtx_t));
481     if(NULL == provCtx)
482     {
483         return OC_STACK_NO_MEMORY;
484     }
485     provCtx->ctx = ctx;
486     provCtx->devInfo = targetDeviceInfo;
487     provCtx->pin = preconfigPin;
488     provCtx->pinLen = preconfigPinLen;
489     provCtx->resultCallback = resultCallback;
490     /*
491      * First of all, update OxMs to support preconfigured PIN OxM.
492      * In case of Preconfigured PIN OxM already supported on the server side,
493      * MOTAddMOTMethod API will be send POST Cred request.
494      * In case of Preconfigure PIN OxM not exist on the server side,
495      * the MOTAddMOTMethod API will be send POST doxm request to update OxMs and then send POST Cred request.
496      */
497     return MOTAddMOTMethod((void*)provCtx, targetDeviceInfo, OIC_PRECONFIG_PIN, AddPreconfPinOxMCB);
498 }
499 #endif //MULTIPLE_OWNER
500
501 /*
502 * Function to unlink devices.
503 * This function will remove the credential & relationship between the two devices.
504 *
505 * @param[in] ctx Application context would be returned in result callback
506 * @param[in] pTargetDev1 first device information to be unlinked.
507 * @param[in] pTargetDev2 second device information to be unlinked.
508 * @param[in] resultCallback callback provided by API user, callback will be called when
509 *            device unlink is finished.
510  * @return  OC_STACK_OK in case of success and other value otherwise.
511 */
512 OCStackResult OCUnlinkDevices(void* ctx,
513                               const OCProvisionDev_t* pTargetDev1,
514                               const OCProvisionDev_t* pTargetDev2,
515                               OCProvisionResultCB resultCallback)
516 {
517     OIC_LOG(INFO, TAG, "IN OCUnlinkDevices");
518     OCUuidList_t* idList = NULL;
519     size_t numOfDev = 0;
520
521     if (!pTargetDev1 || !pTargetDev2 || !pTargetDev1->doxm || !pTargetDev2->doxm)
522     {
523         OIC_LOG(ERROR, TAG, "OCUnlinkDevices : NULL parameters");
524         return OC_STACK_INVALID_PARAM;
525     }
526     if (!resultCallback)
527     {
528         OIC_LOG(INFO, TAG, "OCUnlinkDevices : NULL Callback");
529         return OC_STACK_INVALID_CALLBACK;
530     }
531     if (0 == memcmp(&pTargetDev1->doxm->deviceID, &pTargetDev2->doxm->deviceID, sizeof(OicUuid_t)))
532     {
533         OIC_LOG(INFO, TAG, "OCUnlinkDevices : Same device ID");
534         return OC_STACK_INVALID_PARAM;
535     }
536
537     // Get linked devices with the first device.
538     OCStackResult res = PDMGetLinkedDevices(&(pTargetDev1->doxm->deviceID), &idList, &numOfDev);
539     if (OC_STACK_OK != res)
540     {
541         OIC_LOG(ERROR, TAG, "OCUnlinkDevices : PDMgetOwnedDevices failed");
542         goto error;
543     }
544     if (1 > numOfDev)
545     {
546         OIC_LOG(DEBUG, TAG, "OCUnlinkDevices : Can not find linked devices");
547         res = OC_STACK_INVALID_PARAM; // Input devices are not linked, No request is made
548         goto error;
549     }
550
551     // Check the linked devices contains the second device. If yes send credential DELETE request.
552     OCUuidList_t* curDev = idList;
553     while (NULL != curDev)
554     {
555         if (memcmp(pTargetDev2->doxm->deviceID.id, curDev->dev.id, sizeof(curDev->dev.id)) == 0)
556         {
557             res = SRPUnlinkDevices(ctx, pTargetDev1, pTargetDev2, resultCallback);
558             if (OC_STACK_OK != res)
559             {
560                 OIC_LOG(ERROR, TAG, "OCUnlinkDevices : Failed to unlink devices.");
561             }
562             goto error;
563         }
564         curDev = curDev->next;
565     }
566     OIC_LOG(DEBUG, TAG, "No matched pair found from provisioning database");
567     res = OC_STACK_INVALID_PARAM; // Input devices are not linked, No request is made
568
569 error:
570     OIC_LOG(INFO, TAG, "OUT OCUnlinkDevices");
571
572     PDMDestoryOicUuidLinkList(idList);
573     return res;
574 }
575
576 static OCStackResult RemoveDeviceInfoFromLocal(const OCProvisionDev_t* pTargetDev)
577 {
578     // Remove credential of revoked device from SVR database
579     OCStackResult res = OC_STACK_ERROR;
580     const OicSecCred_t *cred = NULL;
581
582     OIC_LOG(DEBUG, TAG, "IN RemoveDeviceInfoFromLocal");
583     cred = GetCredResourceData(&pTargetDev->doxm->deviceID);
584     if (NULL != cred)
585     {
586         res = RemoveCredential(&cred->subject);
587         if (res != OC_STACK_RESOURCE_DELETED)
588         {
589             OIC_LOG(ERROR, TAG, "RemoveDeviceInfoFromLocal : Failed to remove credential.");
590             goto error;
591         }
592     }
593     /**
594      * Change the device status as stale status.
595      * If all request are successed, this device information will be deleted.
596      */
597     res = PDMSetDeviceState(&pTargetDev->doxm->deviceID, PDM_DEVICE_STALE);
598     if (res != OC_STACK_OK)
599     {
600         OIC_LOG(WARNING, TAG, "OCRemoveDevice : Failed to set device status as stale");
601     }
602
603     // TODO: We need to add new mechanism to clean up the stale state of the device.
604
605     // Close the DTLS session of the removed device.
606     CAResult_t caResult = CAcloseSslConnectionUsingUuid(pTargetDev->doxm->deviceID.id
607                                                         , sizeof(pTargetDev->doxm->deviceID.id));
608     if(CA_STATUS_OK != caResult)
609     {
610         OIC_LOG_V(WARNING, TAG, "OCRemoveDevice : Failed to close (D)TLS session : %d", caResult);
611     }
612     OIC_LOG(DEBUG, TAG, "OUT RemoveDeviceInfoFromLocal");
613 error:
614     return res;
615 }
616
617 /*
618 * Function to device revocation
619 * This function will remove credential of target device from all devices in subnet.
620 *
621 * @param[in] ctx Application context would be returned in result callback
622 * @param[in] waitTimeForOwnedDeviceDiscovery Maximum wait time for owned device discovery.(seconds)
623 * @param[in] pTargetDev Device information to be revoked.
624 * @param[in] resultCallback callback provided by API user, callback will be called when
625 *            credential revocation is finished.
626  * @return  OC_STACK_OK in case of success and other value otherwise.
627 */
628 OCStackResult OCRemoveDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDiscovery,
629                             const OCProvisionDev_t* pTargetDev,
630                             OCProvisionResultCB resultCallback)
631 {
632     OIC_LOG(INFO, TAG, "IN OCRemoveDevice");
633     OCStackResult res = OC_STACK_ERROR;
634     if (!pTargetDev || 0 == waitTimeForOwnedDeviceDiscovery)
635     {
636         OIC_LOG(INFO, TAG, "OCRemoveDevice : Invalied parameters");
637         return OC_STACK_INVALID_PARAM;
638     }
639     if (!resultCallback)
640     {
641         OIC_LOG(INFO, TAG, "OCRemoveDevice : NULL Callback");
642         return OC_STACK_INVALID_CALLBACK;
643     }
644
645     // Send DELETE requests to linked devices
646     OCStackResult resReq = OC_STACK_ERROR; // Check that we have to wait callback or not.
647     resReq = SRPRemoveDevice(ctx, waitTimeForOwnedDeviceDiscovery, pTargetDev, resultCallback);
648     if (OC_STACK_OK != resReq)
649     {
650         if (OC_STACK_CONTINUE == resReq)
651         {
652             OIC_LOG(DEBUG, TAG, "OCRemoveDevice : Revoked device has no linked device except PT.");
653         }
654         else
655         {
656             OIC_LOG(ERROR, TAG, "OCRemoveDevice : Failed to invoke SRPRemoveDevice");
657             res = resReq;
658             goto error;
659         }
660     }
661
662     res = RemoveDeviceInfoFromLocal(pTargetDev);
663     if(OC_STACK_OK != res)
664     {
665         OIC_LOG(ERROR, TAG, "Filed to remove the device information from local.");
666         goto error;
667     }
668
669     if(OC_STACK_CONTINUE == resReq)
670     {
671         /**
672           * If there is no linked device, PM does not send any request.
673           * So we should directly invoke the result callback to inform the result of OCRemoveDevice.
674           */
675         if(resultCallback)
676         {
677             resultCallback(ctx, 0, NULL, false);
678         }
679         res = OC_STACK_OK;
680     }
681
682 error:
683     OIC_LOG(INFO, TAG, "OUT OCRemoveDevice");
684     return res;
685 }
686
687 /*
688 * Function to device revocation
689 * This function will remove credential of target device from all devices in subnet.
690 *
691 * @param[in] ctx Application context would be returned in result callback
692 * @param[in] waitTimeForOwnedDeviceDiscovery Maximum wait time for owned device discovery.(seconds)
693 * @param[in] pTargetDev Device information to be revoked.
694 * @param[in] resultCallback callback provided by API user, callback will be called when
695 *            credential revocation is finished.
696  * @return  OC_STACK_OK in case of success and other value otherwise.
697 */
698 OCStackResult OCRemoveDeviceWithUuid(void* ctx, unsigned short waitTimeForOwnedDeviceDiscovery,
699                             const OicUuid_t* pTargetUuid,
700                             OCProvisionResultCB resultCallback)
701 {
702     OIC_LOG(INFO, TAG, "IN OCRemoveDeviceWithUuid");
703
704     OCStackResult res = OC_STACK_ERROR;
705     OCProvisionDev_t* pTargetDev = NULL;
706     bool discoverdFlag = false;
707     OCProvisionDev_t* pOwnedDevList = NULL;
708     OCStackResult resReq = OC_STACK_CONTINUE;
709
710     if (!pTargetUuid || 0 == waitTimeForOwnedDeviceDiscovery)
711     {
712         OIC_LOG(INFO, TAG, "OCRemoveDeviceWithUuid : Invalied parameters");
713         return OC_STACK_INVALID_PARAM;
714     }
715     if (!resultCallback)
716     {
717         OIC_LOG(INFO, TAG, "OCRemoveDeviceWithUuid : NULL Callback");
718         return OC_STACK_INVALID_CALLBACK;
719     }
720
721     char* strUuid = NULL;
722     if(OC_STACK_OK != ConvertUuidToStr(pTargetUuid, &strUuid))
723     {
724         OIC_LOG(WARNING, TAG, "Failed to covert UUID to String.");
725         goto error;
726     }
727
728     //Generate OCProvisionDev_t instance to use when target device not found on the network.
729     //In this case, the device id required only.
730     pTargetDev = (OCProvisionDev_t*)OICCalloc(1, sizeof(OCProvisionDev_t));
731     if(NULL == pTargetDev)
732     {
733         OIC_LOG(ERROR, TAG, "Failed to allocate memory.");
734         res = OC_STACK_NO_MEMORY;
735         goto error;
736     }
737     pTargetDev->doxm = (OicSecDoxm_t*)OICCalloc(1, sizeof(OicSecDoxm_t));
738     if(NULL == pTargetDev->doxm)
739     {
740         OIC_LOG(ERROR, TAG, "Failed to allocate memory.");
741         res = OC_STACK_NO_MEMORY;
742         goto error;
743     }
744     memcpy(pTargetDev->doxm->deviceID.id, pTargetUuid->id, sizeof(pTargetUuid->id));
745
746     OCUuidList_t* linkedDevices = NULL;
747     size_t numOfLinkedDevices = 0;
748     res = PDMGetLinkedDevices(pTargetUuid, &linkedDevices, &numOfLinkedDevices);
749     if(OC_STACK_OK != res)
750     {
751         OIC_LOG(ERROR, TAG, "Error in PDMGetLinkedDevices");
752         goto error;
753     }
754     PDMDestoryOicUuidLinkList(linkedDevices);
755
756     //If there is no linked devices, device revocation step can be skipped.
757     if(0 != numOfLinkedDevices)
758     {
759         OIC_LOG_V(INFO, TAG, "[%s] linked with other devices.", strUuid);
760         //2. Find owned device from the network
761         res = PMDeviceDiscovery(waitTimeForOwnedDeviceDiscovery, true, &pOwnedDevList);
762         if (OC_STACK_OK != res)
763         {
764             OIC_LOG(ERROR, TAG, "OCRemoveDeviceWithUuid : Failed to PMDeviceDiscovery");
765             goto error;
766         }
767
768         OCProvisionDev_t* tempDev = NULL;
769         LL_FOREACH(pOwnedDevList, tempDev)
770         {
771             if(memcmp(&tempDev->doxm->deviceID.id, pTargetUuid->id, sizeof(pTargetUuid->id)) == 0)
772             {
773                 break;
774             }
775         }
776
777         if(NULL == tempDev)
778         {
779             OIC_LOG_V(WARNING, TAG, "Can not find [%s] on the network.", strUuid);
780             OIC_LOG_V(WARNING, TAG, "[%s]'s information will be deleted from local and other devices.", strUuid);
781         }
782         else
783         {
784             OICFree(pTargetDev->doxm);
785             OICFree(pTargetDev);
786             pTargetDev = tempDev;
787             discoverdFlag = true;
788             OIC_LOG_V(INFO, TAG, "[%s] is dectected on the network.", strUuid);
789         }
790
791         OIC_LOG_V(INFO, TAG, "Trying [%s] revocation.", strUuid);
792
793         // Send DELETE requests to linked devices
794         resReq = SRPRemoveDeviceWithoutDiscovery(ctx, pOwnedDevList, pTargetDev, resultCallback);
795         if (OC_STACK_OK != resReq)
796         {
797             if (OC_STACK_CONTINUE == resReq)
798             {
799                 OIC_LOG(INFO, TAG, "OCRemoveDeviceWithUuid : Revoked device has no linked device except PT.");
800             }
801             else
802             {
803                 OIC_LOG(ERROR, TAG, "OCRemoveDeviceWithUuid : Failed to invoke SRPRemoveDevice");
804                 res = resReq;
805                 goto error;
806             }
807         }
808     }
809     else
810     {
811         OIC_LOG_V(INFO, TAG, "There is no linked devices with [%s]", strUuid);
812         OIC_LOG(INFO, TAG, "Device discovery and SRPRemoveDevice will be skipped.");
813     }
814
815     res = RemoveDeviceInfoFromLocal(pTargetDev);
816     if(OC_STACK_OK != res)
817     {
818         OIC_LOG(ERROR, TAG, "OCRemoveDeviceWithUuid : Filed to remove the device information from local.");
819         goto error;
820     }
821
822     if(OC_STACK_CONTINUE == resReq)
823     {
824         /**
825           * If there is no linked device, PM does not send any request.
826           * So we should directly invoke the result callback to inform the result of OCRemoveDevice.
827           */
828         if(resultCallback)
829         {
830             resultCallback(ctx, 0, NULL, false);
831         }
832         res = OC_STACK_OK;
833     }
834
835 error:
836     OICFree(strUuid);
837     PMDeleteDeviceList(pOwnedDevList);
838     if(pTargetDev && false == discoverdFlag)
839     {
840         OICFree(pTargetDev->doxm);
841         OICFree(pTargetDev);
842     }
843     OIC_LOG(INFO, TAG, "OUT OCRemoveDeviceWithUuid");
844     return res;
845 }
846
847 /*
848  * Function to reset the target device.
849  * This function will remove credential and ACL of target device from all devices in subnet.
850  *
851  * @param[in] ctx Application context would be returned in result callback
852  * @param[in] waitTimeForOwnedDeviceDiscovery Maximum wait time for owned device discovery.(seconds)
853  * @param[in] pTargetDev Device information to be revoked.
854  * @param[in] resultCallback callback provided by API user, callback will be called when
855  *            credential revocation is finished.
856  * @return  OC_STACK_OK in case of success and other value otherwise.
857  */
858 OCStackResult OCResetDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDiscovery,
859                             const OCProvisionDev_t* pTargetDev,
860                             OCProvisionResultCB resultCallback,
861                             OCClientContextDeleter deleteCallback)
862 {
863     OIC_LOG(INFO, TAG, "IN OCResetDevice");
864     OCStackResult res = OC_STACK_ERROR;
865     if (!pTargetDev || 0 == waitTimeForOwnedDeviceDiscovery)
866     {
867         OIC_LOG(INFO, TAG, "OCResetDevice : Invalid parameters");
868         return OC_STACK_INVALID_PARAM;
869     }
870     if (!deleteCallback || !resultCallback)
871     {
872         OIC_LOG(INFO, TAG, "OCResetDevice : NULL Callback");
873         return OC_STACK_INVALID_CALLBACK;
874     }
875
876     // Send DELETE requests to linked devices
877     res = SRPSyncDevice(ctx, waitTimeForOwnedDeviceDiscovery, pTargetDev, resultCallback);
878     if (OC_STACK_CONTINUE == res)
879     {
880         OIC_LOG(DEBUG, TAG, "OCResetDevice : Target device has no linked device except PT.");
881         if(resultCallback)
882         {
883             resultCallback(ctx, 0, NULL, false);
884         }
885         SRPResetDevice(pTargetDev, deleteCallback);
886         res = OC_STACK_OK;
887     }
888     else if(OC_STACK_OK != res)
889     {
890         OIC_LOG(ERROR, TAG, "OCResetDevice : Failed to invoke SRPSyncDevice");
891     }
892     OIC_LOG(INFO, TAG, "OUT OCResetDevice");
893     return res;
894 }
895
896 /**
897  * This function resets SVR DB to its factory setting.
898  *
899  * @return OC_STACK_OK in case of successful reset and other value otherwise.
900  */
901 OCStackResult OCResetSVRDB(void)
902 {
903     return ResetSecureResourceInPS();
904 }
905
906 /**
907  * This function configures SVR DB as self-ownership.
908  *
909  *@return OC_STACK_OK in case of successful configue and other value otherwise.
910  */
911 OCStackResult OCConfigSelfOwnership(void)
912 {
913     return ConfigSelfOwnership();
914 }
915
916 /**
917  * Internal Function to update result in link result array.
918  */
919 static void UpdateLinkResults(Linkdata_t *link, int device, OCStackResult stackresult)
920 {
921
922     OIC_LOG_V(INFO,TAG,"value of link->currentCountResults is %d",link->currentCountResults);
923     if (1 == device)
924     {
925         memcpy(link->resArr[(link->currentCountResults)].deviceId.id, link->pDev1->doxm->deviceID.id,UUID_LENGTH);
926     }
927     else
928     {
929         memcpy(link->resArr[(link->currentCountResults)].deviceId.id, link->pDev2->doxm->deviceID.id,UUID_LENGTH);
930     }
931     link->resArr[(link->currentCountResults)].res = stackresult;
932     ++(link->currentCountResults);
933
934 }
935
936 /**
937  * Callback to handle ACL provisioning for device 2.
938  */
939 static void AclProv2CB(void* ctx, int nOfRes, OCProvisionResult_t *arr, bool hasError)
940 {
941
942     if (NULL == ctx)
943     {
944         OIC_LOG(ERROR,TAG,"Context is Null in ACLProv 2");
945         return;
946     }
947     (void)nOfRes;
948     Linkdata_t *link = (Linkdata_t*)ctx;
949     OCProvisionResultCB resultCallback = link->resultCallback;
950
951
952     if (hasError)
953     {
954         UpdateLinkResults(link, 2,arr[0].res);
955         OIC_LOG(ERROR,TAG,"Error occured while ACL provisioning device 1");
956         ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
957                                                 link->resArr,
958                                                 true);
959         OICFree(link->resArr);
960         OICFree(link) ;
961         return;
962     }
963     UpdateLinkResults(link, 2, arr[0].res);
964    ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
965                                            link->resArr,
966                                            false);
967     OICFree(link->resArr);
968     OICFree(link);
969     return;
970 }
971
972 /**
973  * Callback to handle ACL provisioning for device 1
974  */
975 static void AclProv1CB(void* ctx, int nOfRes, OCProvisionResult_t *arr, bool hasError)
976 {
977
978     if (NULL == ctx)
979     {
980         OIC_LOG(ERROR,TAG,"Context is Null in ACLProv1");
981         return;
982     }
983     (void)nOfRes;
984     Linkdata_t *link = (Linkdata_t*)ctx;
985     OCProvisionResultCB resultCallback = link->resultCallback;
986
987     if (hasError)
988     {
989         OIC_LOG(ERROR,TAG,"Error occured while ACL provisioning device 1");
990         UpdateLinkResults(link, 1, arr[0].res);
991         ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
992                                                 link->resArr,
993                                                 true);
994         OICFree(link->resArr);
995         OICFree(link);
996         return;
997     }
998     UpdateLinkResults(link, 1, arr[0].res);
999     if (NULL != link->pDev2Acl)
1000     {
1001         OCStackResult res =  SRPProvisionACL(ctx, link->pDev2, link->pDev2Acl, &AclProv2CB);
1002         if (OC_STACK_OK!=res)
1003         {
1004              UpdateLinkResults(link, 2, res);
1005              ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
1006                                                      link->resArr,
1007                                                      true);
1008
1009         }
1010     }
1011     else
1012     {
1013         ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
1014                                                 link->resArr,
1015                                                 false);
1016         OICFree(link->resArr);
1017         OICFree(link);
1018     }
1019
1020     return;
1021 }
1022
1023 /**
1024  * Callback to handle credential provisioning.
1025  */
1026 static void ProvisionCredsCB(void* ctx, int nOfRes, OCProvisionResult_t *arr, bool hasError)
1027 {
1028     if (NULL == ctx)
1029     {
1030         OIC_LOG(ERROR,TAG,"Error occured while credential provisioning");
1031         return;
1032     }
1033     Linkdata_t *link = (Linkdata_t*)ctx;
1034     OCProvisionResultCB resultCallback = link->resultCallback;
1035     OIC_LOG_V(INFO, TAG, "has error returned %d",hasError);
1036     UpdateLinkResults(link, 1, arr[0].res);
1037     UpdateLinkResults(link, 2, arr[1].res);
1038     if (hasError)
1039     {
1040         OIC_LOG(ERROR,TAG,"Error occured while credential provisioning");
1041         ((OCProvisionResultCB)(resultCallback))(link->ctx, nOfRes,
1042                                                 link->resArr,
1043                                                 true);
1044          OICFree(link->resArr);
1045          OICFree(link);
1046          return;
1047     }
1048     if (NULL != link->pDev1Acl)
1049     {
1050
1051         OCStackResult res =  SRPProvisionACL(ctx, link->pDev1, link->pDev1Acl, &AclProv1CB);
1052         if (OC_STACK_OK!=res)
1053         {
1054              OIC_LOG(ERROR, TAG, "Error while provisioning ACL for device 1");
1055              UpdateLinkResults(link, 1, res);
1056              ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
1057                                                      link->resArr,
1058                                                      true);
1059               OICFree(link->resArr);
1060               OICFree(link);
1061         }
1062     }
1063     else if (NULL!=link->pDev2Acl)
1064     {
1065         OIC_LOG(ERROR, TAG, "ACL for device 1 is NULL");
1066         OCStackResult res =  SRPProvisionACL(ctx, link->pDev2, link->pDev2Acl, &AclProv2CB);
1067         if (OC_STACK_OK!=res)
1068         {
1069              OIC_LOG(ERROR, TAG, "Error while provisioning ACL for device 2");
1070               UpdateLinkResults(link, 2, res);
1071              ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
1072                                                      link->resArr,
1073                                                      true);
1074               OICFree(link->resArr);
1075               OICFree(link);
1076         }
1077     }
1078     else
1079     {
1080         OIC_LOG(INFO, TAG, "ACLs of both devices are NULL");
1081         ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
1082                                                 link->resArr,
1083                                                 false);
1084         OICFree(link->resArr);
1085         OICFree(link);
1086     }
1087     return;
1088 }
1089 /**
1090  * function to provision credentials between two devices and ACLs for the devices who act as a server.
1091  *
1092  * @param[in] ctx Application context would be returned in result callback.
1093  * @param[in] type Type of credentials to be provisioned to the device.
1094  * @param[in] pDev1 Pointer to OCProvisionDev_t instance,respresenting resource to be provsioned.
1095  * @param[in] acl ACL for device 1. If this is not required set NULL.
1096  * @param[in] pDev2 Pointer to OCProvisionDev_t instance,respresenting resource to be provsioned.
1097  * @param[in] acl ACL for device 2. If this is not required set NULL.
1098  * @param[in] resultCallback callback provided by API user, callback will be called when
1099  *            provisioning request recieves a response from first resource server.
1100  * @return  OC_STACK_OK in case of success and other value otherwise.
1101  */
1102 OCStackResult OCProvisionPairwiseDevices(void* ctx, OicSecCredType_t type, size_t keySize,
1103                                          const OCProvisionDev_t *pDev1, OicSecAcl_t *pDev1Acl,
1104                                          const OCProvisionDev_t *pDev2, OicSecAcl_t *pDev2Acl,
1105                                          OCProvisionResultCB resultCallback)
1106 {
1107
1108     if (!pDev1 || !pDev2 || !pDev1->doxm || !pDev2->doxm)
1109     {
1110         OIC_LOG(ERROR, TAG, "OCProvisionPairwiseDevices : Invalid parameters");
1111         return OC_STACK_INVALID_PARAM;
1112     }
1113     if (!resultCallback)
1114     {
1115         OIC_LOG(INFO, TAG, "OCProvisionPairwiseDevices : NULL Callback");
1116         return OC_STACK_INVALID_CALLBACK;
1117     }
1118     if (!(keySize == OWNER_PSK_LENGTH_128 || keySize == OWNER_PSK_LENGTH_256))
1119     {
1120         OIC_LOG(INFO, TAG, "OCProvisionPairwiseDevices : Invalid key size");
1121         return OC_STACK_INVALID_PARAM;
1122     }
1123     if (0 == memcmp(&pDev1->doxm->deviceID, &pDev2->doxm->deviceID, sizeof(OicUuid_t)))
1124     {
1125         OIC_LOG(INFO, TAG, "OCProvisionPairwiseDevices : Same device ID");
1126         return OC_STACK_INVALID_PARAM;
1127     }
1128
1129     OIC_LOG(DEBUG, TAG, "Checking link in DB");
1130     bool linkExists = true;
1131     OCStackResult res = PDMIsLinkExists(&pDev1->doxm->deviceID, &pDev2->doxm->deviceID, &linkExists);
1132     if(res != OC_STACK_OK)
1133     {
1134         OIC_LOG(ERROR, TAG, "Internal Error Occured");
1135         return res;
1136     }
1137     if (linkExists)
1138     {
1139         OIC_LOG(ERROR, TAG, "Link already exists");
1140         return OC_STACK_INVALID_PARAM;
1141     }
1142
1143     int noOfResults = 2; // Initial Value
1144     if (NULL != pDev1Acl)
1145     {
1146         ++noOfResults;
1147     }
1148     if (NULL != pDev2Acl)
1149     {
1150        ++noOfResults;
1151     }
1152     Linkdata_t *link = (Linkdata_t*) OICMalloc(sizeof(Linkdata_t));
1153     if (!link)
1154     {
1155         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1156         return OC_STACK_NO_MEMORY;
1157     }
1158     OIC_LOG_V(INFO,TAG, "Maximum no od results %d",noOfResults);
1159
1160     link->pDev1 = pDev1;
1161     link->pDev1Acl = pDev1Acl;
1162     link->pDev2 = pDev2;
1163     link->pDev2Acl = pDev2Acl;
1164     link->ctx = ctx;
1165     // 1 call for each device for credential provisioning. implict call by SRPProvisioning credential
1166     // 1 call for ACL provisioning for device 1 and 1 call for ACL provisioning for device 2.
1167     link->numOfResults = noOfResults;
1168     link->resultCallback = resultCallback;
1169     link->currentCountResults = 0;
1170     link->resArr = (OCProvisionResult_t*) OICMalloc(sizeof(OCProvisionResult_t)*noOfResults);
1171     res = SRPProvisionCredentials(link, type, keySize,
1172                                      pDev1, pDev2, &ProvisionCredsCB);
1173     if (res != OC_STACK_OK)
1174     {
1175         OICFree(link->resArr);
1176         OICFree(link);
1177     }
1178     return res;
1179
1180 }
1181
1182 OCStackResult OCGetDevInfoFromNetwork(unsigned short waittime,
1183                                        OCProvisionDev_t** pOwnedDevList,
1184                                        OCProvisionDev_t** pUnownedDevList)
1185 {
1186     //TODO will be replaced by more efficient logic
1187     if (pOwnedDevList == NULL || *pOwnedDevList != NULL || pUnownedDevList == NULL
1188          || *pUnownedDevList != NULL || 0 == waittime)
1189     {
1190         return OC_STACK_INVALID_PARAM;
1191     }
1192
1193     // Code for unowned discovery
1194     OCProvisionDev_t *unownedDevice = NULL;
1195     OCStackResult res =  OCDiscoverUnownedDevices(waittime/2, &unownedDevice);
1196     if (OC_STACK_OK != res)
1197     {
1198         OIC_LOG(ERROR,TAG, "Error in unowned discovery");
1199         return res;
1200     }
1201
1202     // Code for owned discovery
1203     OCProvisionDev_t *ownedDevice = NULL;
1204     res =  OCDiscoverOwnedDevices(waittime/2, &ownedDevice);
1205     if (OC_STACK_OK != res)
1206     {
1207         OIC_LOG(ERROR,TAG, "Error in owned discovery");
1208         PMDeleteDeviceList(unownedDevice);
1209         return res;
1210     }
1211
1212     // Code to get list of all the owned devices.
1213     OCUuidList_t *uuidList = NULL;
1214     size_t numOfDevices = 0;
1215     res =  PDMGetOwnedDevices(&uuidList, &numOfDevices);
1216     if (OC_STACK_OK != res)
1217     {
1218         OIC_LOG(ERROR, TAG, "Error while getting info from DB");
1219         PMDeleteDeviceList(unownedDevice);
1220         PMDeleteDeviceList(ownedDevice);
1221         return res;
1222     }
1223
1224     // Code to compare devices in unowned list and deviceid from DB
1225     // (In case of hard reset of the device)
1226     OCProvisionDev_t* pUnownedList = unownedDevice;
1227     while (pUnownedList && uuidList)
1228     {
1229         OCUuidList_t *tmp1 = NULL,*tmp2=NULL;
1230         LL_FOREACH_SAFE(uuidList, tmp1, tmp2)
1231         {
1232             if(0 == memcmp(tmp1->dev.id, pUnownedList->doxm->deviceID.id,
1233                             sizeof(pUnownedList->doxm->deviceID.id)))
1234             {
1235                 OIC_LOG_V(INFO, TAG, "OCGetDevInfoFromNetwork : \
1236                             Removing device id = %s in PDM and dat.", pUnownedList->doxm->deviceID.id);
1237                 if (OC_STACK_OK != PDMDeleteDevice(&pUnownedList->doxm->deviceID))
1238                 {
1239                     OIC_LOG(ERROR, TAG, "OCGetDevInfoFromNetwork : \
1240                             Failed to remove device in PDM.");
1241                 }
1242                 //remove the cred entry from dat file
1243                 if (OC_STACK_OK != RemoveDeviceInfoFromLocal(pUnownedList))
1244                 {
1245                     OIC_LOG(ERROR, TAG, "OCGetDevInfoFromNetwork : \
1246                             Failed to remove cred entry device in dat file.");
1247                 }
1248                 LL_DELETE(uuidList, tmp1);
1249                 OICFree(tmp1);
1250             }
1251         }
1252         pUnownedList = pUnownedList->next;
1253     }
1254     // Code to compare devices in owned list and deviceid from DB.
1255     OCProvisionDev_t* pCurDev = ownedDevice;
1256     size_t deleteCnt = 0;
1257     while (pCurDev)
1258     {
1259         if(true == PMDeleteFromUUIDList(&uuidList, &pCurDev->doxm->deviceID))
1260         {
1261             deleteCnt++;
1262         }
1263         pCurDev = pCurDev->next;
1264     }
1265     // If there is no remaind device in uuidList, we have to assign NULL to prevent free.
1266     if (deleteCnt == numOfDevices)
1267     {
1268         uuidList = NULL;
1269     }
1270     // Code to add information of the devices which are currently off in owned list.
1271     OCUuidList_t *powerOffDeviceList = uuidList;
1272     while (powerOffDeviceList)
1273     {
1274         OCProvisionDev_t *ptr = (OCProvisionDev_t *)OICCalloc(1, sizeof (OCProvisionDev_t));
1275         if (NULL == ptr)
1276         {
1277             OIC_LOG(ERROR,TAG,"Fail to allocate memory");
1278             PMDeleteDeviceList(unownedDevice);
1279             PMDeleteDeviceList(ownedDevice);
1280             OCDeleteUuidList(uuidList);
1281             return OC_STACK_NO_MEMORY;
1282         }
1283
1284         ptr->doxm = (OicSecDoxm_t*)OICCalloc(1, sizeof(OicSecDoxm_t));
1285         if (NULL == ptr->doxm)
1286         {
1287             OIC_LOG(ERROR,TAG,"Fail to allocate memory");
1288             PMDeleteDeviceList(unownedDevice);
1289             PMDeleteDeviceList(ownedDevice);
1290             OCDeleteUuidList(uuidList);
1291             OICFree(ptr);
1292             return OC_STACK_NO_MEMORY;
1293         }
1294
1295         memcpy(ptr->doxm->deviceID.id, powerOffDeviceList->dev.id, sizeof(ptr->doxm->deviceID.id));
1296
1297         ptr->devStatus = DEV_STATUS_OFF;
1298         LL_PREPEND(ownedDevice, ptr);
1299         powerOffDeviceList = powerOffDeviceList->next;
1300
1301     }
1302     OCDeleteUuidList(uuidList);
1303     *pOwnedDevList = ownedDevice;
1304     *pUnownedDevList = unownedDevice;
1305     return OC_STACK_OK;
1306 }
1307
1308 OCStackResult OCGetLinkedStatus(const OicUuid_t* uuidOfDevice, OCUuidList_t** uuidList,
1309                                  size_t* numOfDevices)
1310 {
1311     return PDMGetLinkedDevices(uuidOfDevice, uuidList, numOfDevices);
1312 }
1313
1314 void OCDeleteUuidList(OCUuidList_t* pList)
1315 {
1316     PDMDestoryOicUuidLinkList(pList);
1317 }
1318
1319 /**
1320  * This function deletes ACL data.
1321  *
1322  * @param pAcl Pointer to OicSecAcl_t structure.
1323  */
1324 void OCDeleteACLList(OicSecAcl_t* pAcl)
1325 {
1326     DeleteACLList(pAcl);
1327 }
1328
1329 /**
1330  * This function deletes PDACL data.
1331  *
1332  * @param pPdAcl Pointer to OicSecPdAcl_t structure.
1333  */
1334 void OCDeletePdAclList(OicSecPdAcl_t* pPdAcl)
1335 {
1336     FreePdAclList(pPdAcl);
1337 }
1338
1339 #ifdef MULTIPLE_OWNER
1340 /**
1341  * API to update 'doxm.mom' to resource server.
1342  *
1343  * @param[in] targetDeviceInfo Selected target device.
1344  * @param[in] momType Mode of multiple ownership transfer (ref. oic.sec.mom)
1345  * @param[in] resultCallback callback provided by API user, callback will be called when
1346  *            POST 'mom' request recieves a response from resource server.
1347  * @return OC_STACK_OK in case of success and other value otherwise.
1348  */
1349 OCStackResult OCChangeMOTMode(void *ctx, const OCProvisionDev_t *targetDeviceInfo,
1350                             const OicSecMomType_t momType, OCProvisionResultCB resultCallback)
1351 {
1352     return MOTChangeMode(ctx, targetDeviceInfo, momType, resultCallback);
1353 }
1354
1355 /**
1356  * API to update 'doxm.oxmsel' to resource server.
1357  *
1358  * @param[in] targetDeviceInfo Selected target device.
1359   * @param[in] oxmSelValue Method of multiple ownership transfer (ref. oic.sec.oxm)
1360  * @param[in] resultCallback callback provided by API user, callback will be called when
1361  *            POST 'oxmsel' request recieves a response from resource server.
1362  * @return OC_STACK_OK in case of success and other value otherwise.
1363  */
1364 OCStackResult OCSelectMOTMethod(void *ctx, const OCProvisionDev_t *targetDeviceInfo,
1365                                  const OicSecOxm_t oxmSelValue, OCProvisionResultCB resultCallback)
1366 {
1367     return MOTSelectMOTMethod(ctx, targetDeviceInfo, oxmSelValue, resultCallback);
1368 }
1369 #endif //MULTIPLE_OWNER
1370
1371 /**
1372  * Function to select appropriate security provisioning method.
1373  *
1374  * @param[in] supportedMethods   Array of supported methods
1375  * @param[in] numberOfMethods   number of supported methods
1376  * @param[out]  selectedMethod         Selected methods
1377  * @param[in] ownerType type of owner device (SUPER_OWNER or SUB_OWNER)
1378  * @return  OC_STACK_OK on success
1379  */
1380 OCStackResult OCSelectOwnershipTransferMethod(const OicSecOxm_t *supportedMethods,
1381         size_t numberOfMethods, OicSecOxm_t *selectedMethod, OwnerType_t ownerType)
1382 {
1383     return OTMSelectOwnershipTransferMethod(supportedMethods, numberOfMethods,
1384                                             selectedMethod, ownerType);
1385 }
1386
1387 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1388 /**
1389  * function to provision Trust certificate chain to devices.
1390  *
1391  * @param[in] ctx Application context would be returned in result callback.
1392  * @param[in] type Type of credentials to be provisioned to the device.
1393  * @param[in] credId CredId of trust certificate chain to be provisioned to the device.
1394  * @param[in] selectedDeviceInfo Pointer to OCProvisionDev_t instance,respresenting resource to be provsioned.
1395  * @param[in] resultCallback callback provided by API user, callback will be called when
1396  *            provisioning request recieves a response from first resource server.
1397  * @return  OC_STACK_OK in case of success and other value otherwise.
1398  */
1399 OCStackResult OCProvisionTrustCertChain(void *ctx, OicSecCredType_t type, uint16_t credId,
1400                                       const OCProvisionDev_t *selectedDeviceInfo,
1401                                       OCProvisionResultCB resultCallback)
1402 {
1403     return SRPProvisionTrustCertChain(ctx, type, credId,
1404                                       selectedDeviceInfo, resultCallback);
1405 }
1406
1407 /**
1408  * function to save Trust certificate chain into Cred of SVR.
1409  *
1410  * @param[in] trustCertChain Trust certificate chain to be saved in Cred of SVR.
1411  * @param[in] chainSize Size of trust certificate chain to be saved in Cred of SVR
1412  * @param[in] encodingType Encoding type of trust certificate chain to be saved in Cred of SVR
1413  * @param[out] credId CredId of saved trust certificate chain in Cred of SVR.
1414  * @return  OC_STACK_OK in case of success and other value otherwise.
1415  */
1416 OCStackResult OCSaveTrustCertChain(uint8_t *trustCertChain, size_t chainSize,
1417                                     OicEncodingType_t encodingType, uint16_t *credId)
1418 {
1419     return SRPSaveTrustCertChain(trustCertChain, chainSize, encodingType, credId);
1420 }
1421
1422 /**
1423  * function to register notifier for Trustcertchain change.
1424  *
1425  * @param[in] ctx user context.
1426  * @param[in] TrustCertChainChangeCB notification callback fucntion.
1427  * @return    OC_STACK_OK in case of success and other value otherwise.
1428  */
1429 OCStackResult OCRegisterTrustCertChainNotifier(void *ctx, TrustCertChainChangeCB Callback)
1430 {
1431     return SRPRegisterTrustCertChainNotifier(ctx, Callback);
1432 }
1433
1434 /**
1435  * function to de-register notifier for Trustcertchain change.
1436  */
1437 void OCRemoveTrustCertChainNotifier()
1438 {
1439     SRPRemoveTrustCertChainNotifier();
1440 }
1441
1442 /**
1443  * This function sets the callback to utilize peer certificate information
1444  */
1445 OCStackResult OCSetPeerCertCallback(void *ctx, PeerCertCallback peerCertCallback)
1446 {
1447     CAResult_t ret;
1448
1449     OIC_LOG_V(DEBUG, TAG, "IN %s", __func__);
1450     ret = CAsetPeerCertCallback(ctx, peerCertCallback);
1451     if (CA_STATUS_OK != ret)
1452     {
1453         OIC_LOG_V(ERROR, TAG, "CAsetPeerCertCallback() Failed(%d)", ret);
1454         return OC_STACK_ERROR;
1455     }
1456     OIC_LOG_V(DEBUG, TAG, "OUT %s", __func__);
1457
1458     return OC_STACK_OK;
1459 }
1460
1461 #endif // __WITH_DTLS__ || __WITH_TLS__
1462