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