Update snapshot(2018-01-17)
[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 OCStackResult OCDoCustomOwnershipTransfer(void* ctx,
340                                             OCProvisionDev_t *selectedDevice,
341                                             OCProvisionResultCB resultCallback,
342                                             const OicSecOxm_t method)
343 {
344     if( NULL == selectedDevice )
345     {
346         return OC_STACK_INVALID_PARAM;
347     }
348     if (!resultCallback)
349     {
350         OIC_LOG(INFO, TAG, "OCDoCustomOwnershipTransfer : NULL Callback");
351         return OC_STACK_INVALID_CALLBACK;
352     }
353     return OTMDoCustomOwnershipTransfer(ctx, selectedDevice, resultCallback, method);
354 }
355
356 /**
357  * This function deletes memory allocated to linked list created by OCDiscover_XXX_Devices API.
358  *
359  * @param[in] pList Pointer to OCProvisionDev_t which should be deleted.
360  */
361 void OCDeleteDiscoveredDevices(OCProvisionDev_t *pList)
362 {
363     PMDeleteDeviceList(pList);
364 }
365
366 /**
367  * this function sends ACL information to resource.
368  *
369  * @param[in] ctx Application context would be returned in result callback.
370  * @param[in] selectedDeviceInfo Selected target device.
371  * @param[in] acl ACL to provision.
372  * @param[in] resultCallback callback provided by API user, callback will be called when provisioning
373               request recieves a response from resource server.
374  * @return  OC_STACK_OK in case of success and other value otherwise.
375  */
376 OCStackResult OCProvisionACL(void* ctx, const OCProvisionDev_t *selectedDeviceInfo, OicSecAcl_t *acl,
377                              OCProvisionResultCB resultCallback)
378 {
379     return SRPProvisionACL(ctx, selectedDeviceInfo, acl, resultCallback);
380 }
381
382 /**
383  * function to save ACL which has several ACE into Acl of SVR.
384  *
385  * @param acl ACL to be saved in Acl of SVR.
386  * @return  OC_STACK_OK in case of success and other value otherwise.
387  */
388 OCStackResult OCSaveACL(const OicSecAcl_t* acl)
389 {
390     return SRPSaveACL(acl);
391 }
392
393 /**
394  * this function requests CRED information to resource.
395  *
396  * @param[in] ctx Application context would be returned in result callback.
397  * @param[in] selectedDeviceInfo Selected target device.
398  * @param[in] resultCallback callback provided by API user, callback will be called when provisioning
399               request recieves a response from resource server.
400  * @return  OC_STACK_OK in case of success and other value otherwise.
401  */
402 OCStackResult OCGetCredResource(void* ctx, const OCProvisionDev_t *selectedDeviceInfo,
403                              OCProvisionResultCB resultCallback)
404 {
405     return SRPGetCredResource(ctx, selectedDeviceInfo, resultCallback);
406 }
407
408 /**
409  * this function requests ACL information to resource.
410  *
411  * @param[in] ctx Application context would be returned in result callback.
412  * @param[in] selectedDeviceInfo Selected target device.
413  * @param[in] resultCallback callback provided by API user, callback will be called when provisioning
414               request recieves a response from resource server.
415  * @return  OC_STACK_OK in case of success and other value otherwise.
416  */
417 OCStackResult OCGetACLResource(void* ctx, const OCProvisionDev_t *selectedDeviceInfo,
418                              OCProvisionResultCB resultCallback)
419 {
420     return SRPGetACLResource(ctx, selectedDeviceInfo, resultCallback);
421 }
422
423
424 OCStackResult OCReadTrustCertChain(uint16_t credId, uint8_t **trustCertChain,
425                                      size_t *chainSize)
426 {
427     return SRPReadTrustCertChain(credId, trustCertChain, chainSize);
428 }
429 /**
430  * function to provision credential to devices.
431  *
432  * @param[in] ctx Application context would be returned in result callback.
433  * @param[in] type Type of credentials to be provisioned to the device.
434  * @param[in] pDev1 Pointer to OCProvisionDev_t instance,respresenting resource to be provsioned.
435    @param[in] pDev2 Pointer to OCProvisionDev_t instance,respresenting resource to be provsioned.
436  * @param[in] resultCallback callback provided by API user, callback will be called when
437  *            provisioning request recieves a response from first resource server.
438  * @return  OC_STACK_OK in case of success and other value otherwise.
439  */
440 OCStackResult OCProvisionCredentials(void *ctx, OicSecCredType_t type, size_t keySize,
441                                       const OCProvisionDev_t *pDev1,
442                                       const OCProvisionDev_t *pDev2,
443                                       OCProvisionResultCB resultCallback)
444 {
445     return SRPProvisionCredentials(ctx, type, keySize,
446                                       pDev1, pDev2, resultCallback);
447
448 }
449
450 /**
451  * this function sends Direct-Pairing Configuration to a device.
452  *
453  * @param[in] ctx Application context would be returned in result callback.
454  * @param[in] selectedDeviceInfo Selected target device.
455  * @param[in] pconf PCONF pointer.
456  * @param[in] resultCallback callback provided by API user, callback will be called when provisioning
457               request recieves a response from resource server.
458  * @return  OC_STACK_OK in case of success and other value otherwise.
459  */
460 OCStackResult OCProvisionDirectPairing(void* ctx, const OCProvisionDev_t *selectedDeviceInfo, OicSecPconf_t *pconf,
461                              OCProvisionResultCB resultCallback)
462 {
463     return SRPProvisionDirectPairing(ctx, selectedDeviceInfo, pconf, resultCallback);
464 }
465
466 #ifdef MULTIPLE_OWNER
467 static void AddPreconfPinOxMCB(void* ctx, int nOfRes, OCProvisionResult_t *arr, bool hasError)
468 {
469     ProvPreconfPINCtx_t* provCtx = (ProvPreconfPINCtx_t*)ctx;
470     if(provCtx)
471     {
472         OCStackResult res = MOTProvisionPreconfigPIN(provCtx->ctx, provCtx->devInfo, provCtx->pin, provCtx->pinLen, provCtx->resultCallback);
473         if(OC_STACK_OK != res)
474         {
475             arr->res = res;
476             provCtx->resultCallback(provCtx->ctx, nOfRes, arr, true);
477         }
478     }
479 }
480
481 OCStackResult OCProvisionPreconfigPin(void *ctx,
482                                       OCProvisionDev_t *targetDeviceInfo,
483                                       const char *preconfigPin,
484                                       size_t preconfigPinLen,
485                                       OCProvisionResultCB resultCallback)
486 {
487     if( NULL == targetDeviceInfo || NULL == preconfigPin || 0 == preconfigPinLen )
488     {
489         return OC_STACK_INVALID_PARAM;
490     }
491     if (NULL == resultCallback)
492     {
493         OIC_LOG(INFO, TAG, "OCProvisionPreconfigPinCredential : NULL Callback");
494         return OC_STACK_INVALID_CALLBACK;
495     }
496
497     ProvPreconfPINCtx_t* provCtx = (ProvPreconfPINCtx_t*)OICCalloc(1, sizeof(ProvPreconfPINCtx_t));
498     if(NULL == provCtx)
499     {
500         return OC_STACK_NO_MEMORY;
501     }
502     provCtx->ctx = ctx;
503     provCtx->devInfo = targetDeviceInfo;
504     provCtx->pin = preconfigPin;
505     provCtx->pinLen = preconfigPinLen;
506     provCtx->resultCallback = resultCallback;
507     /*
508      * First of all, update OxMs to support preconfigured PIN OxM.
509      * In case of Preconfigured PIN OxM already supported on the server side,
510      * MOTAddMOTMethod API will be send POST Cred request.
511      * In case of Preconfigure PIN OxM not exist on the server side,
512      * the MOTAddMOTMethod API will be send POST doxm request to update OxMs and then send POST Cred request.
513      */
514     return MOTAddMOTMethod((void*)provCtx, targetDeviceInfo, OIC_PRECONFIG_PIN, AddPreconfPinOxMCB);
515 }
516 #endif //MULTIPLE_OWNER
517
518 /*
519 * Function to unlink devices.
520 * This function will remove the credential & relationship between the two devices.
521 *
522 * @param[in] ctx Application context would be returned in result callback
523 * @param[in] pTargetDev1 first device information to be unlinked.
524 * @param[in] pTargetDev2 second device information to be unlinked.
525 * @param[in] resultCallback callback provided by API user, callback will be called when
526 *            device unlink is finished.
527  * @return  OC_STACK_OK in case of success and other value otherwise.
528 */
529 OCStackResult OCUnlinkDevices(void* ctx,
530                               const OCProvisionDev_t* pTargetDev1,
531                               const OCProvisionDev_t* pTargetDev2,
532                               OCProvisionResultCB resultCallback)
533 {
534     OIC_LOG(INFO, TAG, "IN OCUnlinkDevices");
535     OCUuidList_t* idList = NULL;
536     size_t numOfDev = 0;
537
538     if (!pTargetDev1 || !pTargetDev2 || !pTargetDev1->doxm || !pTargetDev2->doxm)
539     {
540         OIC_LOG(ERROR, TAG, "OCUnlinkDevices : NULL parameters");
541         return OC_STACK_INVALID_PARAM;
542     }
543     if (!resultCallback)
544     {
545         OIC_LOG(INFO, TAG, "OCUnlinkDevices : NULL Callback");
546         return OC_STACK_INVALID_CALLBACK;
547     }
548     if (0 == memcmp(&pTargetDev1->doxm->deviceID, &pTargetDev2->doxm->deviceID, sizeof(OicUuid_t)))
549     {
550         OIC_LOG(INFO, TAG, "OCUnlinkDevices : Same device ID");
551         return OC_STACK_INVALID_PARAM;
552     }
553
554     // Get linked devices with the first device.
555     OCStackResult res = PDMGetLinkedDevices(&(pTargetDev1->doxm->deviceID), &idList, &numOfDev);
556     if (OC_STACK_OK != res)
557     {
558         OIC_LOG(ERROR, TAG, "OCUnlinkDevices : PDMgetOwnedDevices failed");
559         goto error;
560     }
561     if (1 > numOfDev)
562     {
563         OIC_LOG(DEBUG, TAG, "OCUnlinkDevices : Can not find linked devices");
564         res = OC_STACK_INVALID_PARAM; // Input devices are not linked, No request is made
565         goto error;
566     }
567
568     // Check the linked devices contains the second device. If yes send credential DELETE request.
569     OCUuidList_t* curDev = idList;
570     while (NULL != curDev)
571     {
572         if (memcmp(pTargetDev2->doxm->deviceID.id, curDev->dev.id, sizeof(curDev->dev.id)) == 0)
573         {
574             res = SRPUnlinkDevices(ctx, pTargetDev1, pTargetDev2, resultCallback);
575             if (OC_STACK_OK != res)
576             {
577                 OIC_LOG(ERROR, TAG, "OCUnlinkDevices : Failed to unlink devices.");
578             }
579             goto error;
580         }
581         curDev = curDev->next;
582     }
583     OIC_LOG(DEBUG, TAG, "No matched pair found from provisioning database");
584     res = OC_STACK_INVALID_PARAM; // Input devices are not linked, No request is made
585
586 error:
587     OIC_LOG(INFO, TAG, "OUT OCUnlinkDevices");
588
589     PDMDestoryOicUuidLinkList(idList);
590     return res;
591 }
592
593 static OCStackResult RemoveDeviceInfoFromLocal(const OCProvisionDev_t* pTargetDev)
594 {
595     // Remove credential of revoked device from SVR database
596     OCStackResult res = OC_STACK_ERROR;
597     const OicSecCred_t *cred = NULL;
598
599     OIC_LOG(DEBUG, TAG, "IN RemoveDeviceInfoFromLocal");
600     cred = GetCredResourceData(&pTargetDev->doxm->deviceID);
601     if (NULL != cred)
602     {
603         res = RemoveCredential(&cred->subject);
604         if (res != OC_STACK_RESOURCE_DELETED)
605         {
606             OIC_LOG(ERROR, TAG, "RemoveDeviceInfoFromLocal : Failed to remove credential.");
607             goto error;
608         }
609     }
610     /**
611      * Change the device status as stale status.
612      * If all request are successed, this device information will be deleted.
613      */
614     res = PDMSetDeviceState(&pTargetDev->doxm->deviceID, PDM_DEVICE_STALE);
615     if (res != OC_STACK_OK)
616     {
617         OIC_LOG(WARNING, TAG, "OCRemoveDevice : Failed to set device status as stale");
618     }
619
620     // TODO: We need to add new mechanism to clean up the stale state of the device.
621
622     // Close the DTLS session of the removed device.
623     CAResult_t caResult = CAcloseSslConnectionUsingUuid(pTargetDev->doxm->deviceID.id
624                                                         , sizeof(pTargetDev->doxm->deviceID.id));
625     if(CA_STATUS_OK != caResult)
626     {
627         OIC_LOG_V(WARNING, TAG, "OCRemoveDevice : Failed to close (D)TLS session : %d", caResult);
628     }
629     OIC_LOG(DEBUG, TAG, "OUT RemoveDeviceInfoFromLocal");
630 error:
631     return res;
632 }
633
634 /*
635 * Function to device revocation
636 * This function will remove credential of target device from all devices in subnet.
637 *
638 * @param[in] ctx Application context would be returned in result callback
639 * @param[in] waitTimeForOwnedDeviceDiscovery Maximum wait time for owned device discovery.(seconds)
640 * @param[in] pTargetDev Device information to be revoked.
641 * @param[in] resultCallback callback provided by API user, callback will be called when
642 *            credential revocation is finished.
643  * @return  OC_STACK_OK in case of success and other value otherwise.
644 */
645 OCStackResult OCRemoveDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDiscovery,
646                             const OCProvisionDev_t* pTargetDev,
647                             OCProvisionResultCB resultCallback)
648 {
649     OIC_LOG(INFO, TAG, "IN OCRemoveDevice");
650     OCStackResult res = OC_STACK_ERROR;
651     if (!pTargetDev || 0 == waitTimeForOwnedDeviceDiscovery)
652     {
653         OIC_LOG(INFO, TAG, "OCRemoveDevice : Invalied parameters");
654         return OC_STACK_INVALID_PARAM;
655     }
656     if (!resultCallback)
657     {
658         OIC_LOG(INFO, TAG, "OCRemoveDevice : NULL Callback");
659         return OC_STACK_INVALID_CALLBACK;
660     }
661
662     // Send DELETE requests to linked devices
663     OCStackResult resReq = OC_STACK_ERROR; // Check that we have to wait callback or not.
664     resReq = SRPRemoveDevice(ctx, waitTimeForOwnedDeviceDiscovery, pTargetDev, resultCallback);
665     if (OC_STACK_OK != resReq)
666     {
667         if (OC_STACK_CONTINUE == resReq)
668         {
669             OIC_LOG(DEBUG, TAG, "OCRemoveDevice : Revoked device has no linked device except PT.");
670         }
671         else
672         {
673             OIC_LOG(ERROR, TAG, "OCRemoveDevice : Failed to invoke SRPRemoveDevice");
674             res = resReq;
675             goto error;
676         }
677     }
678
679     res = RemoveDeviceInfoFromLocal(pTargetDev);
680     if(OC_STACK_OK != res)
681     {
682         OIC_LOG(ERROR, TAG, "Filed to remove the device information from local.");
683         goto error;
684     }
685
686     if(OC_STACK_CONTINUE == resReq)
687     {
688         /**
689           * If there is no linked device, PM does not send any request.
690           * So we should directly invoke the result callback to inform the result of OCRemoveDevice.
691           */
692         if(resultCallback)
693         {
694             resultCallback(ctx, 0, NULL, false);
695         }
696         res = OC_STACK_OK;
697     }
698
699 error:
700     OIC_LOG(INFO, TAG, "OUT OCRemoveDevice");
701     return res;
702 }
703
704 /*
705 * Function to device revocation
706 * This function will remove credential of target device from all devices in subnet.
707 *
708 * @param[in] ctx Application context would be returned in result callback
709 * @param[in] waitTimeForOwnedDeviceDiscovery Maximum wait time for owned device discovery.(seconds)
710 * @param[in] pTargetDev Device information to be revoked.
711 * @param[in] resultCallback callback provided by API user, callback will be called when
712 *            credential revocation is finished.
713  * @return  OC_STACK_OK in case of success and other value otherwise.
714 */
715 OCStackResult OCRemoveDeviceWithUuid(void* ctx, unsigned short waitTimeForOwnedDeviceDiscovery,
716                             const OicUuid_t* pTargetUuid,
717                             OCProvisionResultCB resultCallback)
718 {
719     OIC_LOG(INFO, TAG, "IN OCRemoveDeviceWithUuid");
720
721     OCStackResult res = OC_STACK_ERROR;
722     OCProvisionDev_t* pTargetDev = NULL;
723     bool discoverdFlag = false;
724     OCProvisionDev_t* pOwnedDevList = NULL;
725     OCStackResult resReq = OC_STACK_CONTINUE;
726
727     if (!pTargetUuid || 0 == waitTimeForOwnedDeviceDiscovery)
728     {
729         OIC_LOG(INFO, TAG, "OCRemoveDeviceWithUuid : Invalied parameters");
730         return OC_STACK_INVALID_PARAM;
731     }
732     if (!resultCallback)
733     {
734         OIC_LOG(INFO, TAG, "OCRemoveDeviceWithUuid : NULL Callback");
735         return OC_STACK_INVALID_CALLBACK;
736     }
737
738     char* strUuid = NULL;
739     if(OC_STACK_OK != ConvertUuidToStr(pTargetUuid, &strUuid))
740     {
741         OIC_LOG(WARNING, TAG, "Failed to covert UUID to String.");
742         goto error;
743     }
744
745     //Generate OCProvisionDev_t instance to use when target device not found on the network.
746     //In this case, the device id required only.
747     pTargetDev = (OCProvisionDev_t*)OICCalloc(1, sizeof(OCProvisionDev_t));
748     if(NULL == pTargetDev)
749     {
750         OIC_LOG(ERROR, TAG, "Failed to allocate memory.");
751         res = OC_STACK_NO_MEMORY;
752         goto error;
753     }
754     pTargetDev->doxm = (OicSecDoxm_t*)OICCalloc(1, sizeof(OicSecDoxm_t));
755     if(NULL == pTargetDev->doxm)
756     {
757         OIC_LOG(ERROR, TAG, "Failed to allocate memory.");
758         res = OC_STACK_NO_MEMORY;
759         goto error;
760     }
761     memcpy(pTargetDev->doxm->deviceID.id, pTargetUuid->id, sizeof(pTargetUuid->id));
762
763     OCUuidList_t* linkedDevices = NULL;
764     size_t numOfLinkedDevices = 0;
765     res = PDMGetLinkedDevices(pTargetUuid, &linkedDevices, &numOfLinkedDevices);
766     if(OC_STACK_OK != res)
767     {
768         OIC_LOG(ERROR, TAG, "Error in PDMGetLinkedDevices");
769         goto error;
770     }
771     PDMDestoryOicUuidLinkList(linkedDevices);
772
773     //If there is no linked devices, device revocation step can be skipped.
774     if(0 != numOfLinkedDevices)
775     {
776         OIC_LOG_V(INFO, TAG, "[%s] linked with other devices.", strUuid);
777         //2. Find owned device from the network
778         res = PMDeviceDiscovery(waitTimeForOwnedDeviceDiscovery, true, &pOwnedDevList);
779         if (OC_STACK_OK != res)
780         {
781             OIC_LOG(ERROR, TAG, "OCRemoveDeviceWithUuid : Failed to PMDeviceDiscovery");
782             goto error;
783         }
784
785         OCProvisionDev_t* tempDev = NULL;
786         LL_FOREACH(pOwnedDevList, tempDev)
787         {
788             if(memcmp(&tempDev->doxm->deviceID.id, pTargetUuid->id, sizeof(pTargetUuid->id)) == 0)
789             {
790                 break;
791             }
792         }
793
794         if(NULL == tempDev)
795         {
796             OIC_LOG_V(WARNING, TAG, "Can not find [%s] on the network.", strUuid);
797             OIC_LOG_V(WARNING, TAG, "[%s]'s information will be deleted from local and other devices.", strUuid);
798         }
799         else
800         {
801             OICFree(pTargetDev->doxm);
802             OICFree(pTargetDev);
803             pTargetDev = tempDev;
804             discoverdFlag = true;
805             OIC_LOG_V(INFO, TAG, "[%s] is dectected on the network.", strUuid);
806         }
807
808         OIC_LOG_V(INFO, TAG, "Trying [%s] revocation.", strUuid);
809
810         // Send DELETE requests to linked devices
811         resReq = SRPRemoveDeviceWithoutDiscovery(ctx, pOwnedDevList, pTargetDev, resultCallback);
812         if (OC_STACK_OK != resReq)
813         {
814             if (OC_STACK_CONTINUE == resReq)
815             {
816                 OIC_LOG(INFO, TAG, "OCRemoveDeviceWithUuid : Revoked device has no linked device except PT.");
817             }
818             else
819             {
820                 OIC_LOG(ERROR, TAG, "OCRemoveDeviceWithUuid : Failed to invoke SRPRemoveDevice");
821                 res = resReq;
822                 goto error;
823             }
824         }
825     }
826     else
827     {
828         OIC_LOG_V(INFO, TAG, "There is no linked devices with [%s]", strUuid);
829         OIC_LOG(INFO, TAG, "Device discovery and SRPRemoveDevice will be skipped.");
830     }
831
832     res = RemoveDeviceInfoFromLocal(pTargetDev);
833     if(OC_STACK_OK != res)
834     {
835         OIC_LOG(ERROR, TAG, "OCRemoveDeviceWithUuid : Filed to remove the device information from local.");
836         goto error;
837     }
838
839     if(OC_STACK_CONTINUE == resReq)
840     {
841         /**
842           * If there is no linked device, PM does not send any request.
843           * So we should directly invoke the result callback to inform the result of OCRemoveDevice.
844           */
845         if(resultCallback)
846         {
847             resultCallback(ctx, 0, NULL, false);
848         }
849         res = OC_STACK_OK;
850     }
851
852 error:
853     OICFree(strUuid);
854     PMDeleteDeviceList(pOwnedDevList);
855     if(pTargetDev && false == discoverdFlag)
856     {
857         OICFree(pTargetDev->doxm);
858         OICFree(pTargetDev);
859     }
860     OIC_LOG(INFO, TAG, "OUT OCRemoveDeviceWithUuid");
861     return res;
862 }
863
864 /*
865  * Function to reset the target device.
866  * This function will remove credential and ACL of target device from all devices in subnet.
867  *
868  * @param[in] ctx Application context would be returned in result callback
869  * @param[in] waitTimeForOwnedDeviceDiscovery Maximum wait time for owned device discovery.(seconds)
870  * @param[in] pTargetDev Device information to be revoked.
871  * @param[in] resultCallback callback provided by API user, callback will be called when
872  *            credential revocation is finished.
873  * @return  OC_STACK_OK in case of success and other value otherwise.
874  */
875 OCStackResult OCResetDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDiscovery,
876                             const OCProvisionDev_t* pTargetDev,
877                             OCProvisionResultCB resultCallback,
878                             OCClientContextDeleter deleteCallback)
879 {
880     OIC_LOG(INFO, TAG, "IN OCResetDevice");
881     OCStackResult res = OC_STACK_ERROR;
882     if (!pTargetDev || 0 == waitTimeForOwnedDeviceDiscovery)
883     {
884         OIC_LOG(INFO, TAG, "OCResetDevice : Invalid parameters");
885         return OC_STACK_INVALID_PARAM;
886     }
887     if (!deleteCallback || !resultCallback)
888     {
889         OIC_LOG(INFO, TAG, "OCResetDevice : NULL Callback");
890         return OC_STACK_INVALID_CALLBACK;
891     }
892
893     // Send DELETE requests to linked devices
894     res = SRPSyncDevice(ctx, waitTimeForOwnedDeviceDiscovery, pTargetDev, resultCallback);
895     if (OC_STACK_CONTINUE == res)
896     {
897         OIC_LOG(DEBUG, TAG, "OCResetDevice : Target device has no linked device except PT.");
898         if(resultCallback)
899         {
900             resultCallback(ctx, 0, NULL, false);
901         }
902         SRPResetDevice(pTargetDev, deleteCallback);
903         res = OC_STACK_OK;
904     }
905     else if(OC_STACK_OK != res)
906     {
907         OIC_LOG(ERROR, TAG, "OCResetDevice : Failed to invoke SRPSyncDevice");
908     }
909     OIC_LOG(INFO, TAG, "OUT OCResetDevice");
910     return res;
911 }
912
913 /**
914  * This function resets SVR DB to its factory setting.
915  *
916  * @return OC_STACK_OK in case of successful reset and other value otherwise.
917  */
918 OCStackResult OCResetSVRDB(void)
919 {
920     return ResetSecureResourceInPS();
921 }
922
923 /**
924  * This function configures SVR DB as self-ownership.
925  *
926  *@return OC_STACK_OK in case of successful configue and other value otherwise.
927  */
928 OCStackResult OCConfigSelfOwnership(void)
929 {
930     return ConfigSelfOwnership();
931 }
932
933 /**
934  * Internal Function to update result in link result array.
935  */
936 static void UpdateLinkResults(Linkdata_t *link, int device, OCStackResult stackresult)
937 {
938
939     OIC_LOG_V(INFO,TAG,"value of link->currentCountResults is %d",link->currentCountResults);
940     if (1 == device)
941     {
942         memcpy(link->resArr[(link->currentCountResults)].deviceId.id, link->pDev1->doxm->deviceID.id,UUID_LENGTH);
943     }
944     else
945     {
946         memcpy(link->resArr[(link->currentCountResults)].deviceId.id, link->pDev2->doxm->deviceID.id,UUID_LENGTH);
947     }
948     link->resArr[(link->currentCountResults)].res = stackresult;
949     ++(link->currentCountResults);
950
951 }
952
953 /**
954  * Callback to handle ACL provisioning for device 2.
955  */
956 static void AclProv2CB(void* ctx, int nOfRes, OCProvisionResult_t *arr, bool hasError)
957 {
958
959     if (NULL == ctx)
960     {
961         OIC_LOG(ERROR,TAG,"Context is Null in ACLProv 2");
962         return;
963     }
964     (void)nOfRes;
965     Linkdata_t *link = (Linkdata_t*)ctx;
966     OCProvisionResultCB resultCallback = link->resultCallback;
967
968
969     if (hasError)
970     {
971         UpdateLinkResults(link, 2,arr[0].res);
972         OIC_LOG(ERROR,TAG,"Error occured while ACL provisioning device 1");
973         ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
974                                                 link->resArr,
975                                                 true);
976         OICFree(link->resArr);
977         OICFree(link) ;
978         return;
979     }
980     UpdateLinkResults(link, 2, arr[0].res);
981    ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
982                                            link->resArr,
983                                            false);
984     OICFree(link->resArr);
985     OICFree(link);
986     return;
987 }
988
989 /**
990  * Callback to handle ACL provisioning for device 1
991  */
992 static void AclProv1CB(void* ctx, int nOfRes, OCProvisionResult_t *arr, bool hasError)
993 {
994
995     if (NULL == ctx)
996     {
997         OIC_LOG(ERROR,TAG,"Context is Null in ACLProv1");
998         return;
999     }
1000     (void)nOfRes;
1001     Linkdata_t *link = (Linkdata_t*)ctx;
1002     OCProvisionResultCB resultCallback = link->resultCallback;
1003
1004     if (hasError)
1005     {
1006         OIC_LOG(ERROR,TAG,"Error occured while ACL provisioning device 1");
1007         UpdateLinkResults(link, 1, arr[0].res);
1008         ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
1009                                                 link->resArr,
1010                                                 true);
1011         OICFree(link->resArr);
1012         OICFree(link);
1013         return;
1014     }
1015     UpdateLinkResults(link, 1, arr[0].res);
1016     if (NULL != link->pDev2Acl)
1017     {
1018         OCStackResult res =  SRPProvisionACL(ctx, link->pDev2, link->pDev2Acl, &AclProv2CB);
1019         if (OC_STACK_OK!=res)
1020         {
1021              UpdateLinkResults(link, 2, res);
1022              ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
1023                                                      link->resArr,
1024                                                      true);
1025
1026         }
1027     }
1028     else
1029     {
1030         ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
1031                                                 link->resArr,
1032                                                 false);
1033         OICFree(link->resArr);
1034         OICFree(link);
1035     }
1036
1037     return;
1038 }
1039
1040 /**
1041  * Callback to handle credential provisioning.
1042  */
1043 static void ProvisionCredsCB(void* ctx, int nOfRes, OCProvisionResult_t *arr, bool hasError)
1044 {
1045     if (NULL == ctx)
1046     {
1047         OIC_LOG(ERROR,TAG,"Error occured while credential provisioning");
1048         return;
1049     }
1050     Linkdata_t *link = (Linkdata_t*)ctx;
1051     OCProvisionResultCB resultCallback = link->resultCallback;
1052     OIC_LOG_V(INFO, TAG, "has error returned %d",hasError);
1053     UpdateLinkResults(link, 1, arr[0].res);
1054     UpdateLinkResults(link, 2, arr[1].res);
1055     if (hasError)
1056     {
1057         OIC_LOG(ERROR,TAG,"Error occured while credential provisioning");
1058         ((OCProvisionResultCB)(resultCallback))(link->ctx, nOfRes,
1059                                                 link->resArr,
1060                                                 true);
1061          OICFree(link->resArr);
1062          OICFree(link);
1063          return;
1064     }
1065     if (NULL != link->pDev1Acl)
1066     {
1067
1068         OCStackResult res =  SRPProvisionACL(ctx, link->pDev1, link->pDev1Acl, &AclProv1CB);
1069         if (OC_STACK_OK!=res)
1070         {
1071              OIC_LOG(ERROR, TAG, "Error while provisioning ACL for device 1");
1072              UpdateLinkResults(link, 1, res);
1073              ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
1074                                                      link->resArr,
1075                                                      true);
1076               OICFree(link->resArr);
1077               OICFree(link);
1078         }
1079     }
1080     else if (NULL!=link->pDev2Acl)
1081     {
1082         OIC_LOG(ERROR, TAG, "ACL for device 1 is NULL");
1083         OCStackResult res =  SRPProvisionACL(ctx, link->pDev2, link->pDev2Acl, &AclProv2CB);
1084         if (OC_STACK_OK!=res)
1085         {
1086              OIC_LOG(ERROR, TAG, "Error while provisioning ACL for device 2");
1087               UpdateLinkResults(link, 2, res);
1088              ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
1089                                                      link->resArr,
1090                                                      true);
1091               OICFree(link->resArr);
1092               OICFree(link);
1093         }
1094     }
1095     else
1096     {
1097         OIC_LOG(INFO, TAG, "ACLs of both devices are NULL");
1098         ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
1099                                                 link->resArr,
1100                                                 false);
1101         OICFree(link->resArr);
1102         OICFree(link);
1103     }
1104     return;
1105 }
1106 /**
1107  * function to provision credentials between two devices and ACLs for the devices who act as a server.
1108  *
1109  * @param[in] ctx Application context would be returned in result callback.
1110  * @param[in] type Type of credentials to be provisioned to the device.
1111  * @param[in] pDev1 Pointer to OCProvisionDev_t instance,respresenting resource to be provsioned.
1112  * @param[in] acl ACL for device 1. If this is not required set NULL.
1113  * @param[in] pDev2 Pointer to OCProvisionDev_t instance,respresenting resource to be provsioned.
1114  * @param[in] acl ACL for device 2. If this is not required set NULL.
1115  * @param[in] resultCallback callback provided by API user, callback will be called when
1116  *            provisioning request recieves a response from first resource server.
1117  * @return  OC_STACK_OK in case of success and other value otherwise.
1118  */
1119 OCStackResult OCProvisionPairwiseDevices(void* ctx, OicSecCredType_t type, size_t keySize,
1120                                          const OCProvisionDev_t *pDev1, OicSecAcl_t *pDev1Acl,
1121                                          const OCProvisionDev_t *pDev2, OicSecAcl_t *pDev2Acl,
1122                                          OCProvisionResultCB resultCallback)
1123 {
1124
1125     if (!pDev1 || !pDev2 || !pDev1->doxm || !pDev2->doxm)
1126     {
1127         OIC_LOG(ERROR, TAG, "OCProvisionPairwiseDevices : Invalid parameters");
1128         return OC_STACK_INVALID_PARAM;
1129     }
1130     if (!resultCallback)
1131     {
1132         OIC_LOG(INFO, TAG, "OCProvisionPairwiseDevices : NULL Callback");
1133         return OC_STACK_INVALID_CALLBACK;
1134     }
1135     if (!(keySize == OWNER_PSK_LENGTH_128 || keySize == OWNER_PSK_LENGTH_256))
1136     {
1137         OIC_LOG(INFO, TAG, "OCProvisionPairwiseDevices : Invalid key size");
1138         return OC_STACK_INVALID_PARAM;
1139     }
1140     if (0 == memcmp(&pDev1->doxm->deviceID, &pDev2->doxm->deviceID, sizeof(OicUuid_t)))
1141     {
1142         OIC_LOG(INFO, TAG, "OCProvisionPairwiseDevices : Same device ID");
1143         return OC_STACK_INVALID_PARAM;
1144     }
1145
1146     OIC_LOG(DEBUG, TAG, "Checking link in DB");
1147     bool linkExists = true;
1148     OCStackResult res = PDMIsLinkExists(&pDev1->doxm->deviceID, &pDev2->doxm->deviceID, &linkExists);
1149     if(res != OC_STACK_OK)
1150     {
1151         OIC_LOG(ERROR, TAG, "Internal Error Occured");
1152         return res;
1153     }
1154     if (linkExists)
1155     {
1156         OIC_LOG(ERROR, TAG, "Link already exists");
1157         return OC_STACK_INVALID_PARAM;
1158     }
1159
1160     int noOfResults = 2; // Initial Value
1161     if (NULL != pDev1Acl)
1162     {
1163         ++noOfResults;
1164     }
1165     if (NULL != pDev2Acl)
1166     {
1167        ++noOfResults;
1168     }
1169     Linkdata_t *link = (Linkdata_t*) OICMalloc(sizeof(Linkdata_t));
1170     if (!link)
1171     {
1172         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1173         return OC_STACK_NO_MEMORY;
1174     }
1175     OIC_LOG_V(INFO,TAG, "Maximum no od results %d",noOfResults);
1176
1177     link->pDev1 = pDev1;
1178     link->pDev1Acl = pDev1Acl;
1179     link->pDev2 = pDev2;
1180     link->pDev2Acl = pDev2Acl;
1181     link->ctx = ctx;
1182     // 1 call for each device for credential provisioning. implict call by SRPProvisioning credential
1183     // 1 call for ACL provisioning for device 1 and 1 call for ACL provisioning for device 2.
1184     link->numOfResults = noOfResults;
1185     link->resultCallback = resultCallback;
1186     link->currentCountResults = 0;
1187     link->resArr = (OCProvisionResult_t*) OICMalloc(sizeof(OCProvisionResult_t)*noOfResults);
1188     res = SRPProvisionCredentials(link, type, keySize,
1189                                      pDev1, pDev2, &ProvisionCredsCB);
1190     if (res != OC_STACK_OK)
1191     {
1192         OICFree(link->resArr);
1193         OICFree(link);
1194     }
1195     return res;
1196
1197 }
1198
1199 OCStackResult OCGetDevInfoFromNetwork(unsigned short waittime,
1200                                        OCProvisionDev_t** pOwnedDevList,
1201                                        OCProvisionDev_t** pUnownedDevList)
1202 {
1203     //TODO will be replaced by more efficient logic
1204     if (pOwnedDevList == NULL || *pOwnedDevList != NULL || pUnownedDevList == NULL
1205          || *pUnownedDevList != NULL || 0 == waittime)
1206     {
1207         return OC_STACK_INVALID_PARAM;
1208     }
1209
1210     // Code for unowned discovery
1211     OCProvisionDev_t *unownedDevice = NULL;
1212     OCStackResult res =  OCDiscoverUnownedDevices(waittime/2, &unownedDevice);
1213     if (OC_STACK_OK != res)
1214     {
1215         OIC_LOG(ERROR,TAG, "Error in unowned discovery");
1216         return res;
1217     }
1218
1219     // Code for owned discovery
1220     OCProvisionDev_t *ownedDevice = NULL;
1221     res =  OCDiscoverOwnedDevices(waittime/2, &ownedDevice);
1222     if (OC_STACK_OK != res)
1223     {
1224         OIC_LOG(ERROR,TAG, "Error in owned discovery");
1225         PMDeleteDeviceList(unownedDevice);
1226         return res;
1227     }
1228
1229     // Code to get list of all the owned devices.
1230     OCUuidList_t *uuidList = NULL;
1231     size_t numOfDevices = 0;
1232     res =  PDMGetOwnedDevices(&uuidList, &numOfDevices);
1233     if (OC_STACK_OK != res)
1234     {
1235         OIC_LOG(ERROR, TAG, "Error while getting info from DB");
1236         PMDeleteDeviceList(unownedDevice);
1237         PMDeleteDeviceList(ownedDevice);
1238         return res;
1239     }
1240
1241     // Code to compare devices in unowned list and deviceid from DB
1242     // (In case of hard reset of the device)
1243     OCProvisionDev_t* pUnownedList = unownedDevice;
1244     while (pUnownedList && uuidList)
1245     {
1246         OCUuidList_t *tmp1 = NULL,*tmp2=NULL;
1247         LL_FOREACH_SAFE(uuidList, tmp1, tmp2)
1248         {
1249             if(0 == memcmp(tmp1->dev.id, pUnownedList->doxm->deviceID.id,
1250                             sizeof(pUnownedList->doxm->deviceID.id)))
1251             {
1252                 OIC_LOG_V(INFO, TAG, "OCGetDevInfoFromNetwork : \
1253                             Removing device id = %s in PDM and dat.", pUnownedList->doxm->deviceID.id);
1254                 if (OC_STACK_OK != PDMDeleteDevice(&pUnownedList->doxm->deviceID))
1255                 {
1256                     OIC_LOG(ERROR, TAG, "OCGetDevInfoFromNetwork : \
1257                             Failed to remove device in PDM.");
1258                 }
1259                 //remove the cred entry from dat file
1260                 if (OC_STACK_OK != RemoveDeviceInfoFromLocal(pUnownedList))
1261                 {
1262                     OIC_LOG(ERROR, TAG, "OCGetDevInfoFromNetwork : \
1263                             Failed to remove cred entry device in dat file.");
1264                 }
1265                 LL_DELETE(uuidList, tmp1);
1266                 OICFree(tmp1);
1267             }
1268         }
1269         pUnownedList = pUnownedList->next;
1270     }
1271     // Code to compare devices in owned list and deviceid from DB.
1272     OCProvisionDev_t* pCurDev = ownedDevice;
1273     size_t deleteCnt = 0;
1274     while (pCurDev)
1275     {
1276         if(true == PMDeleteFromUUIDList(&uuidList, &pCurDev->doxm->deviceID))
1277         {
1278             deleteCnt++;
1279         }
1280         pCurDev = pCurDev->next;
1281     }
1282     // If there is no remaind device in uuidList, we have to assign NULL to prevent free.
1283     if (deleteCnt == numOfDevices)
1284     {
1285         uuidList = NULL;
1286     }
1287     // Code to add information of the devices which are currently off in owned list.
1288     OCUuidList_t *powerOffDeviceList = uuidList;
1289     while (powerOffDeviceList)
1290     {
1291         OCProvisionDev_t *ptr = (OCProvisionDev_t *)OICCalloc(1, sizeof (OCProvisionDev_t));
1292         if (NULL == ptr)
1293         {
1294             OIC_LOG(ERROR,TAG,"Fail to allocate memory");
1295             PMDeleteDeviceList(unownedDevice);
1296             PMDeleteDeviceList(ownedDevice);
1297             OCDeleteUuidList(uuidList);
1298             return OC_STACK_NO_MEMORY;
1299         }
1300
1301         ptr->doxm = (OicSecDoxm_t*)OICCalloc(1, sizeof(OicSecDoxm_t));
1302         if (NULL == ptr->doxm)
1303         {
1304             OIC_LOG(ERROR,TAG,"Fail to allocate memory");
1305             PMDeleteDeviceList(unownedDevice);
1306             PMDeleteDeviceList(ownedDevice);
1307             OCDeleteUuidList(uuidList);
1308             OICFree(ptr);
1309             return OC_STACK_NO_MEMORY;
1310         }
1311
1312         memcpy(ptr->doxm->deviceID.id, powerOffDeviceList->dev.id, sizeof(ptr->doxm->deviceID.id));
1313
1314         ptr->devStatus = DEV_STATUS_OFF;
1315         LL_PREPEND(ownedDevice, ptr);
1316         powerOffDeviceList = powerOffDeviceList->next;
1317
1318     }
1319     OCDeleteUuidList(uuidList);
1320     *pOwnedDevList = ownedDevice;
1321     *pUnownedDevList = unownedDevice;
1322     return OC_STACK_OK;
1323 }
1324
1325 OCStackResult OCGetLinkedStatus(const OicUuid_t* uuidOfDevice, OCUuidList_t** uuidList,
1326                                  size_t* numOfDevices)
1327 {
1328     return PDMGetLinkedDevices(uuidOfDevice, uuidList, numOfDevices);
1329 }
1330
1331 void OCDeleteUuidList(OCUuidList_t* pList)
1332 {
1333     PDMDestoryOicUuidLinkList(pList);
1334 }
1335
1336 /**
1337  * This function deletes ACL data.
1338  *
1339  * @param pAcl Pointer to OicSecAcl_t structure.
1340  */
1341 void OCDeleteACLList(OicSecAcl_t* pAcl)
1342 {
1343     DeleteACLList(pAcl);
1344 }
1345
1346 /**
1347  * This function deletes PDACL data.
1348  *
1349  * @param pPdAcl Pointer to OicSecPdAcl_t structure.
1350  */
1351 void OCDeletePdAclList(OicSecPdAcl_t* pPdAcl)
1352 {
1353     FreePdAclList(pPdAcl);
1354 }
1355
1356 #ifdef MULTIPLE_OWNER
1357 /**
1358  * API to update 'doxm.mom' to resource server.
1359  *
1360  * @param[in] targetDeviceInfo Selected target device.
1361  * @param[in] momType Mode of multiple ownership transfer (ref. oic.sec.mom)
1362  * @param[in] resultCallback callback provided by API user, callback will be called when
1363  *            POST 'mom' request recieves a response from resource server.
1364  * @return OC_STACK_OK in case of success and other value otherwise.
1365  */
1366 OCStackResult OCChangeMOTMode(void *ctx, const OCProvisionDev_t *targetDeviceInfo,
1367                             const OicSecMomType_t momType, OCProvisionResultCB resultCallback)
1368 {
1369     return MOTChangeMode(ctx, targetDeviceInfo, momType, resultCallback);
1370 }
1371
1372 /**
1373  * API to update 'doxm.oxmsel' to resource server.
1374  *
1375  * @param[in] targetDeviceInfo Selected target device.
1376   * @param[in] oxmSelValue Method of multiple ownership transfer (ref. oic.sec.oxm)
1377  * @param[in] resultCallback callback provided by API user, callback will be called when
1378  *            POST 'oxmsel' request recieves a response from resource server.
1379  * @return OC_STACK_OK in case of success and other value otherwise.
1380  */
1381 OCStackResult OCSelectMOTMethod(void *ctx, const OCProvisionDev_t *targetDeviceInfo,
1382                                  const OicSecOxm_t oxmSelValue, OCProvisionResultCB resultCallback)
1383 {
1384     return MOTSelectMOTMethod(ctx, targetDeviceInfo, oxmSelValue, resultCallback);
1385 }
1386 #endif //MULTIPLE_OWNER
1387
1388 /**
1389  * Function to select appropriate security provisioning method.
1390  *
1391  * @param[in] supportedMethods   Array of supported methods
1392  * @param[in] numberOfMethods   number of supported methods
1393  * @param[out]  selectedMethod         Selected methods
1394  * @param[in] ownerType type of owner device (SUPER_OWNER or SUB_OWNER)
1395  * @return  OC_STACK_OK on success
1396  */
1397 OCStackResult OCSelectOwnershipTransferMethod(const OicSecOxm_t *supportedMethods,
1398         size_t numberOfMethods, OicSecOxm_t *selectedMethod, OwnerType_t ownerType)
1399 {
1400     return OTMSelectOwnershipTransferMethod(supportedMethods, numberOfMethods,
1401                                             selectedMethod, ownerType);
1402 }
1403
1404 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1405 /**
1406  * function to provision Trust certificate chain to devices.
1407  *
1408  * @param[in] ctx Application context would be returned in result callback.
1409  * @param[in] type Type of credentials to be provisioned to the device.
1410  * @param[in] credId CredId of trust certificate chain to be provisioned to the device.
1411  * @param[in] selectedDeviceInfo Pointer to OCProvisionDev_t instance,respresenting resource to be provsioned.
1412  * @param[in] resultCallback callback provided by API user, callback will be called when
1413  *            provisioning request recieves a response from first resource server.
1414  * @return  OC_STACK_OK in case of success and other value otherwise.
1415  */
1416 OCStackResult OCProvisionTrustCertChain(void *ctx, OicSecCredType_t type, uint16_t credId,
1417                                       const OCProvisionDev_t *selectedDeviceInfo,
1418                                       OCProvisionResultCB resultCallback)
1419 {
1420     return SRPProvisionTrustCertChain(ctx, type, credId,
1421                                       selectedDeviceInfo, resultCallback);
1422 }
1423
1424 /**
1425  * function to save Trust certificate chain into Cred of SVR.
1426  *
1427  * @param[in] trustCertChain Trust certificate chain to be saved in Cred of SVR.
1428  * @param[in] chainSize Size of trust certificate chain to be saved in Cred of SVR
1429  * @param[in] encodingType Encoding type of trust certificate chain to be saved in Cred of SVR
1430  * @param[out] credId CredId of saved trust certificate chain in Cred of SVR.
1431  * @return  OC_STACK_OK in case of success and other value otherwise.
1432  */
1433 OCStackResult OCSaveTrustCertChain(uint8_t *trustCertChain, size_t chainSize,
1434                                     OicEncodingType_t encodingType, uint16_t *credId)
1435 {
1436     return SRPSaveTrustCertChain(trustCertChain, chainSize, encodingType, credId);
1437 }
1438
1439 /**
1440  * function to register notifier for Trustcertchain change.
1441  *
1442  * @param[in] ctx user context.
1443  * @param[in] TrustCertChainChangeCB notification callback fucntion.
1444  * @return    OC_STACK_OK in case of success and other value otherwise.
1445  */
1446 OCStackResult OCRegisterTrustCertChainNotifier(void *ctx, TrustCertChainChangeCB Callback)
1447 {
1448     return SRPRegisterTrustCertChainNotifier(ctx, Callback);
1449 }
1450
1451 /**
1452  * function to de-register notifier for Trustcertchain change.
1453  */
1454 void OCRemoveTrustCertChainNotifier()
1455 {
1456     SRPRemoveTrustCertChainNotifier();
1457 }
1458
1459 /**
1460  * This function sets the callback to utilize peer certificate information
1461  */
1462 OCStackResult OCSetPeerCertCallback(void *ctx, PeerCertCallback peerCertCallback)
1463 {
1464     CAResult_t ret;
1465
1466     OIC_LOG_V(DEBUG, TAG, "IN %s", __func__);
1467     ret = CAsetPeerCertCallback(ctx, peerCertCallback);
1468     if (CA_STATUS_OK != ret)
1469     {
1470         OIC_LOG_V(ERROR, TAG, "CAsetPeerCertCallback() Failed(%d)", ret);
1471         return OC_STACK_ERROR;
1472     }
1473     OIC_LOG_V(DEBUG, TAG, "OUT %s", __func__);
1474
1475     return OC_STACK_OK;
1476 }
1477
1478 #endif // __WITH_DTLS__ || __WITH_TLS__
1479