a46843fffc555580ae92926e2e9e2e3b63d644d4
[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     SRPResetDevice(pTargetDev, localResultCallback);
847     while(g_reset && maxWait)
848     {
849         sleep(1);
850         maxWait--;
851     }
852
853     if(OC_STACK_CONTINUE == resReq)
854     {
855         resultCallback(ctx, 0, NULL, false);
856         res = OC_STACK_OK;
857     }
858
859     res = RemoveDeviceInfoFromLocal(pTargetDev);
860     if(OC_STACK_OK != res)
861     {
862         OIC_LOG(ERROR, TAG, "OCRemoveDeviceWithUuid : Failed to remove the device information from local.");
863         goto error;
864     }
865 error:
866     OICFree(strUuid);
867     PMDeleteDeviceList(pOwnedDevList);
868     if(pTargetDev && false == discoverdFlag)
869     {
870         OICFree(pTargetDev->doxm);
871         OICFree(pTargetDev);
872     }
873     OIC_LOG(INFO, TAG, "OUT OCRemoveDeviceWithUuid");
874     return res;
875 }
876
877 /*
878  * Function to reset the target device.
879  * This function will remove credential and ACL of target device from all devices in subnet.
880  *
881  * @param[in] ctx Application context would be returned in result callback
882  * @param[in] waitTimeForOwnedDeviceDiscovery Maximum wait time for owned device discovery.(seconds)
883  * @param[in] pTargetDev Device information to be revoked.
884  * @param[in] resultCallback callback provided by API user, callback will be called when
885  *            credential revocation is finished.
886  * @return  OC_STACK_OK in case of success and other value otherwise.
887  */
888 OCStackResult OCResetDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDiscovery,
889                             const OCProvisionDev_t* pTargetDev,
890                             OCProvisionResultCB resultCallback,
891                             OCClientContextDeleter deleteCallback)
892 {
893     OIC_LOG(INFO, TAG, "IN OCResetDevice");
894     OCStackResult res = OC_STACK_ERROR;
895     if (!pTargetDev || 0 == waitTimeForOwnedDeviceDiscovery)
896     {
897         OIC_LOG(INFO, TAG, "OCResetDevice : Invalid parameters");
898         return OC_STACK_INVALID_PARAM;
899     }
900     if (!deleteCallback || !resultCallback)
901     {
902         OIC_LOG(INFO, TAG, "OCResetDevice : NULL Callback");
903         return OC_STACK_INVALID_CALLBACK;
904     }
905
906     // Send DELETE requests to linked devices
907     res = SRPSyncDevice(ctx, waitTimeForOwnedDeviceDiscovery, pTargetDev, resultCallback);
908     if (OC_STACK_CONTINUE == res)
909     {
910         OIC_LOG(DEBUG, TAG, "OCResetDevice : Target device has no linked device except PT.");
911         if(resultCallback)
912         {
913             resultCallback(ctx, 0, NULL, false);
914         }
915         SRPResetDevice(pTargetDev, deleteCallback);
916         res = OC_STACK_OK;
917     }
918     else if(OC_STACK_OK != res)
919     {
920         OIC_LOG(ERROR, TAG, "OCResetDevice : Failed to invoke SRPSyncDevice");
921     }
922     OIC_LOG(INFO, TAG, "OUT OCResetDevice");
923     return res;
924 }
925
926 /**
927  * This function resets SVR DB to its factory setting.
928  *
929  * @return OC_STACK_OK in case of successful reset and other value otherwise.
930  */
931 OCStackResult OCResetSVRDB(void)
932 {
933     return ResetSecureResourceInPS();
934 }
935
936 /**
937  * This function configures SVR DB as self-ownership.
938  *
939  *@return OC_STACK_OK in case of successful configue and other value otherwise.
940  */
941 OCStackResult OCConfigSelfOwnership(void)
942 {
943     return ConfigSelfOwnership();
944 }
945
946 /**
947  * Internal Function to update result in link result array.
948  */
949 static void UpdateLinkResults(Linkdata_t *link, int device, OCStackResult stackresult)
950 {
951
952     OIC_LOG_V(INFO,TAG,"value of link->currentCountResults is %d",link->currentCountResults);
953     if (1 == device)
954     {
955         memcpy(link->resArr[(link->currentCountResults)].deviceId.id, link->pDev1->doxm->deviceID.id,UUID_LENGTH);
956     }
957     else
958     {
959         memcpy(link->resArr[(link->currentCountResults)].deviceId.id, link->pDev2->doxm->deviceID.id,UUID_LENGTH);
960     }
961     link->resArr[(link->currentCountResults)].res = stackresult;
962     ++(link->currentCountResults);
963
964 }
965
966 /**
967  * Callback to handle ACL provisioning for device 2.
968  */
969 static void AclProv2CB(void* ctx, int nOfRes, OCProvisionResult_t *arr, bool hasError)
970 {
971
972     if (NULL == ctx)
973     {
974         OIC_LOG(ERROR,TAG,"Context is Null in ACLProv 2");
975         return;
976     }
977     (void)nOfRes;
978     Linkdata_t *link = (Linkdata_t*)ctx;
979     OCProvisionResultCB resultCallback = link->resultCallback;
980
981
982     if (hasError)
983     {
984         UpdateLinkResults(link, 2,arr[0].res);
985         OIC_LOG(ERROR,TAG,"Error occured while ACL provisioning device 1");
986         ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
987                                                 link->resArr,
988                                                 true);
989         OICFree(link->resArr);
990         OICFree(link) ;
991         return;
992     }
993     UpdateLinkResults(link, 2, arr[0].res);
994    ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
995                                            link->resArr,
996                                            false);
997     OICFree(link->resArr);
998     OICFree(link);
999     return;
1000 }
1001
1002 /**
1003  * Callback to handle ACL provisioning for device 1
1004  */
1005 static void AclProv1CB(void* ctx, int nOfRes, OCProvisionResult_t *arr, bool hasError)
1006 {
1007
1008     if (NULL == ctx)
1009     {
1010         OIC_LOG(ERROR,TAG,"Context is Null in ACLProv1");
1011         return;
1012     }
1013     (void)nOfRes;
1014     Linkdata_t *link = (Linkdata_t*)ctx;
1015     OCProvisionResultCB resultCallback = link->resultCallback;
1016
1017     if (hasError)
1018     {
1019         OIC_LOG(ERROR,TAG,"Error occured while ACL provisioning device 1");
1020         UpdateLinkResults(link, 1, arr[0].res);
1021         ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
1022                                                 link->resArr,
1023                                                 true);
1024         OICFree(link->resArr);
1025         OICFree(link);
1026         return;
1027     }
1028     UpdateLinkResults(link, 1, arr[0].res);
1029     if (NULL != link->pDev2Acl)
1030     {
1031         OCStackResult res =  SRPProvisionACL(ctx, link->pDev2, link->pDev2Acl, &AclProv2CB);
1032         if (OC_STACK_OK!=res)
1033         {
1034              UpdateLinkResults(link, 2, res);
1035              ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
1036                                                      link->resArr,
1037                                                      true);
1038
1039         }
1040     }
1041     else
1042     {
1043         ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
1044                                                 link->resArr,
1045                                                 false);
1046         OICFree(link->resArr);
1047         OICFree(link);
1048     }
1049
1050     return;
1051 }
1052
1053 /**
1054  * Callback to handle credential provisioning.
1055  */
1056 static void ProvisionCredsCB(void* ctx, int nOfRes, OCProvisionResult_t *arr, bool hasError)
1057 {
1058     if (NULL == ctx)
1059     {
1060         OIC_LOG(ERROR,TAG,"Error occured while credential provisioning");
1061         return;
1062     }
1063     Linkdata_t *link = (Linkdata_t*)ctx;
1064     OCProvisionResultCB resultCallback = link->resultCallback;
1065     OIC_LOG_V(INFO, TAG, "has error returned %d",hasError);
1066     UpdateLinkResults(link, 1, arr[0].res);
1067     UpdateLinkResults(link, 2, arr[1].res);
1068     if (hasError)
1069     {
1070         OIC_LOG(ERROR,TAG,"Error occured while credential provisioning");
1071         ((OCProvisionResultCB)(resultCallback))(link->ctx, nOfRes,
1072                                                 link->resArr,
1073                                                 true);
1074          OICFree(link->resArr);
1075          OICFree(link);
1076          return;
1077     }
1078     if (NULL != link->pDev1Acl)
1079     {
1080
1081         OCStackResult res =  SRPProvisionACL(ctx, link->pDev1, link->pDev1Acl, &AclProv1CB);
1082         if (OC_STACK_OK!=res)
1083         {
1084              OIC_LOG(ERROR, TAG, "Error while provisioning ACL for device 1");
1085              UpdateLinkResults(link, 1, res);
1086              ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
1087                                                      link->resArr,
1088                                                      true);
1089               OICFree(link->resArr);
1090               OICFree(link);
1091         }
1092     }
1093     else if (NULL!=link->pDev2Acl)
1094     {
1095         OIC_LOG(ERROR, TAG, "ACL for device 1 is NULL");
1096         OCStackResult res =  SRPProvisionACL(ctx, link->pDev2, link->pDev2Acl, &AclProv2CB);
1097         if (OC_STACK_OK!=res)
1098         {
1099              OIC_LOG(ERROR, TAG, "Error while provisioning ACL for device 2");
1100               UpdateLinkResults(link, 2, res);
1101              ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
1102                                                      link->resArr,
1103                                                      true);
1104               OICFree(link->resArr);
1105               OICFree(link);
1106         }
1107     }
1108     else
1109     {
1110         OIC_LOG(INFO, TAG, "ACLs of both devices are NULL");
1111         ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
1112                                                 link->resArr,
1113                                                 false);
1114         OICFree(link->resArr);
1115         OICFree(link);
1116     }
1117     return;
1118 }
1119 /**
1120  * function to provision credentials between two devices and ACLs for the devices who act as a server.
1121  *
1122  * @param[in] ctx Application context would be returned in result callback.
1123  * @param[in] type Type of credentials to be provisioned to the device.
1124  * @param[in] pDev1 Pointer to OCProvisionDev_t instance,respresenting resource to be provsioned.
1125  * @param[in] acl ACL for device 1. If this is not required set NULL.
1126  * @param[in] pDev2 Pointer to OCProvisionDev_t instance,respresenting resource to be provsioned.
1127  * @param[in] acl ACL for device 2. If this is not required set NULL.
1128  * @param[in] resultCallback callback provided by API user, callback will be called when
1129  *            provisioning request recieves a response from first resource server.
1130  * @return  OC_STACK_OK in case of success and other value otherwise.
1131  */
1132 OCStackResult OCProvisionPairwiseDevices(void* ctx, OicSecCredType_t type, size_t keySize,
1133                                          const OCProvisionDev_t *pDev1, OicSecAcl_t *pDev1Acl,
1134                                          const OCProvisionDev_t *pDev2, OicSecAcl_t *pDev2Acl,
1135                                          OCProvisionResultCB resultCallback)
1136 {
1137
1138     if (!pDev1 || !pDev2 || !pDev1->doxm || !pDev2->doxm)
1139     {
1140         OIC_LOG(ERROR, TAG, "OCProvisionPairwiseDevices : Invalid parameters");
1141         return OC_STACK_INVALID_PARAM;
1142     }
1143     if (!resultCallback)
1144     {
1145         OIC_LOG(INFO, TAG, "OCProvisionPairwiseDevices : NULL Callback");
1146         return OC_STACK_INVALID_CALLBACK;
1147     }
1148     if (!(keySize == OWNER_PSK_LENGTH_128 || keySize == OWNER_PSK_LENGTH_256))
1149     {
1150         OIC_LOG(INFO, TAG, "OCProvisionPairwiseDevices : Invalid key size");
1151         return OC_STACK_INVALID_PARAM;
1152     }
1153     if (0 == memcmp(&pDev1->doxm->deviceID, &pDev2->doxm->deviceID, sizeof(OicUuid_t)))
1154     {
1155         OIC_LOG(INFO, TAG, "OCProvisionPairwiseDevices : Same device ID");
1156         return OC_STACK_INVALID_PARAM;
1157     }
1158
1159     OIC_LOG(DEBUG, TAG, "Checking link in DB");
1160     bool linkExists = true;
1161     OCStackResult res = PDMIsLinkExists(&pDev1->doxm->deviceID, &pDev2->doxm->deviceID, &linkExists);
1162     if(res != OC_STACK_OK)
1163     {
1164         OIC_LOG(ERROR, TAG, "Internal Error Occured");
1165         return res;
1166     }
1167     if (linkExists)
1168     {
1169         OIC_LOG(ERROR, TAG, "Link already exists");
1170         return OC_STACK_INVALID_PARAM;
1171     }
1172
1173     int noOfResults = 2; // Initial Value
1174     if (NULL != pDev1Acl)
1175     {
1176         ++noOfResults;
1177     }
1178     if (NULL != pDev2Acl)
1179     {
1180        ++noOfResults;
1181     }
1182     Linkdata_t *link = (Linkdata_t*) OICMalloc(sizeof(Linkdata_t));
1183     if (!link)
1184     {
1185         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1186         return OC_STACK_NO_MEMORY;
1187     }
1188     OIC_LOG_V(INFO,TAG, "Maximum no od results %d",noOfResults);
1189
1190     link->pDev1 = pDev1;
1191     link->pDev1Acl = pDev1Acl;
1192     link->pDev2 = pDev2;
1193     link->pDev2Acl = pDev2Acl;
1194     link->ctx = ctx;
1195     // 1 call for each device for credential provisioning. implict call by SRPProvisioning credential
1196     // 1 call for ACL provisioning for device 1 and 1 call for ACL provisioning for device 2.
1197     link->numOfResults = noOfResults;
1198     link->resultCallback = resultCallback;
1199     link->currentCountResults = 0;
1200     link->resArr = (OCProvisionResult_t*) OICMalloc(sizeof(OCProvisionResult_t)*noOfResults);
1201     res = SRPProvisionCredentials(link, type, keySize,
1202                                      pDev1, pDev2, &ProvisionCredsCB);
1203     if (res != OC_STACK_OK)
1204     {
1205         OICFree(link->resArr);
1206         OICFree(link);
1207     }
1208     return res;
1209
1210 }
1211
1212 OCStackResult OCGetDevInfoFromNetwork(unsigned short waittime,
1213                                        OCProvisionDev_t** pOwnedDevList,
1214                                        OCProvisionDev_t** pUnownedDevList)
1215 {
1216     //TODO will be replaced by more efficient logic
1217     if (pOwnedDevList == NULL || *pOwnedDevList != NULL || pUnownedDevList == NULL
1218          || *pUnownedDevList != NULL || 0 == waittime)
1219     {
1220         return OC_STACK_INVALID_PARAM;
1221     }
1222
1223     // Code for unowned discovery
1224     OCProvisionDev_t *unownedDevice = NULL;
1225     OCStackResult res =  OCDiscoverUnownedDevices(waittime/2, &unownedDevice);
1226     if (OC_STACK_OK != res)
1227     {
1228         OIC_LOG(ERROR,TAG, "Error in unowned discovery");
1229         return res;
1230     }
1231
1232     // Code for owned discovery
1233     OCProvisionDev_t *ownedDevice = NULL;
1234     res =  OCDiscoverOwnedDevices(waittime/2, &ownedDevice);
1235     if (OC_STACK_OK != res)
1236     {
1237         OIC_LOG(ERROR,TAG, "Error in owned discovery");
1238         PMDeleteDeviceList(unownedDevice);
1239         return res;
1240     }
1241
1242     // Code to get list of all the owned devices.
1243     OCUuidList_t *uuidList = NULL;
1244     size_t numOfDevices = 0;
1245     res =  PDMGetOwnedDevices(&uuidList, &numOfDevices);
1246     if (OC_STACK_OK != res)
1247     {
1248         OIC_LOG(ERROR, TAG, "Error while getting info from DB");
1249         PMDeleteDeviceList(unownedDevice);
1250         PMDeleteDeviceList(ownedDevice);
1251         return res;
1252     }
1253
1254     // Code to compare devices in unowned list and deviceid from DB
1255     // (In case of hard reset of the device)
1256     OCProvisionDev_t* pUnownedList = unownedDevice;
1257     while (pUnownedList && uuidList)
1258     {
1259         OCUuidList_t *tmp1 = NULL,*tmp2=NULL;
1260         LL_FOREACH_SAFE(uuidList, tmp1, tmp2)
1261         {
1262             if(0 == memcmp(tmp1->dev.id, pUnownedList->doxm->deviceID.id,
1263                             sizeof(pUnownedList->doxm->deviceID.id)))
1264             {
1265                 OIC_LOG_V(INFO, TAG, "OCGetDevInfoFromNetwork : \
1266                             Removing device id = %s in PDM and dat.", pUnownedList->doxm->deviceID.id);
1267                 if (OC_STACK_OK != PDMDeleteDevice(&pUnownedList->doxm->deviceID))
1268                 {
1269                     OIC_LOG(ERROR, TAG, "OCGetDevInfoFromNetwork : \
1270                             Failed to remove device in PDM.");
1271                 }
1272                 //remove the cred entry from dat file
1273                 if (OC_STACK_OK != RemoveDeviceInfoFromLocal(pUnownedList))
1274                 {
1275                     OIC_LOG(ERROR, TAG, "OCGetDevInfoFromNetwork : \
1276                             Failed to remove cred entry device in dat file.");
1277                 }
1278                 LL_DELETE(uuidList, tmp1);
1279                 OICFree(tmp1);
1280             }
1281         }
1282         pUnownedList = pUnownedList->next;
1283     }
1284     // Code to compare devices in owned list and deviceid from DB.
1285     OCProvisionDev_t* pCurDev = ownedDevice;
1286     size_t deleteCnt = 0;
1287     while (pCurDev)
1288     {
1289         if(true == PMDeleteFromUUIDList(&uuidList, &pCurDev->doxm->deviceID))
1290         {
1291             deleteCnt++;
1292         }
1293         pCurDev = pCurDev->next;
1294     }
1295     // If there is no remaind device in uuidList, we have to assign NULL to prevent free.
1296     if (deleteCnt == numOfDevices)
1297     {
1298         uuidList = NULL;
1299     }
1300     // Code to add information of the devices which are currently off in owned list.
1301     OCUuidList_t *powerOffDeviceList = uuidList;
1302     while (powerOffDeviceList)
1303     {
1304         OCProvisionDev_t *ptr = (OCProvisionDev_t *)OICCalloc(1, sizeof (OCProvisionDev_t));
1305         if (NULL == ptr)
1306         {
1307             OIC_LOG(ERROR,TAG,"Fail to allocate memory");
1308             PMDeleteDeviceList(unownedDevice);
1309             PMDeleteDeviceList(ownedDevice);
1310             OCDeleteUuidList(uuidList);
1311             return OC_STACK_NO_MEMORY;
1312         }
1313
1314         ptr->doxm = (OicSecDoxm_t*)OICCalloc(1, sizeof(OicSecDoxm_t));
1315         if (NULL == ptr->doxm)
1316         {
1317             OIC_LOG(ERROR,TAG,"Fail to allocate memory");
1318             PMDeleteDeviceList(unownedDevice);
1319             PMDeleteDeviceList(ownedDevice);
1320             OCDeleteUuidList(uuidList);
1321             OICFree(ptr);
1322             return OC_STACK_NO_MEMORY;
1323         }
1324
1325         memcpy(ptr->doxm->deviceID.id, powerOffDeviceList->dev.id, sizeof(ptr->doxm->deviceID.id));
1326
1327         ptr->devStatus = DEV_STATUS_OFF;
1328         LL_PREPEND(ownedDevice, ptr);
1329         powerOffDeviceList = powerOffDeviceList->next;
1330
1331     }
1332     OCDeleteUuidList(uuidList);
1333     *pOwnedDevList = ownedDevice;
1334     *pUnownedDevList = unownedDevice;
1335     return OC_STACK_OK;
1336 }
1337
1338 OCStackResult OCGetLinkedStatus(const OicUuid_t* uuidOfDevice, OCUuidList_t** uuidList,
1339                                  size_t* numOfDevices)
1340 {
1341     return PDMGetLinkedDevices(uuidOfDevice, uuidList, numOfDevices);
1342 }
1343
1344 void OCDeleteUuidList(OCUuidList_t* pList)
1345 {
1346     PDMDestoryOicUuidLinkList(pList);
1347 }
1348
1349 /**
1350  * This function deletes ACL data.
1351  *
1352  * @param pAcl Pointer to OicSecAcl_t structure.
1353  */
1354 void OCDeleteACLList(OicSecAcl_t* pAcl)
1355 {
1356     DeleteACLList(pAcl);
1357 }
1358
1359 /**
1360  * This function deletes PDACL data.
1361  *
1362  * @param pPdAcl Pointer to OicSecPdAcl_t structure.
1363  */
1364 void OCDeletePdAclList(OicSecPdAcl_t* pPdAcl)
1365 {
1366     FreePdAclList(pPdAcl);
1367 }
1368
1369 #ifdef MULTIPLE_OWNER
1370 /**
1371  * API to update 'doxm.mom' to resource server.
1372  *
1373  * @param[in] targetDeviceInfo Selected target device.
1374  * @param[in] momType Mode of multiple ownership transfer (ref. oic.sec.mom)
1375  * @param[in] resultCallback callback provided by API user, callback will be called when
1376  *            POST 'mom' request recieves a response from resource server.
1377  * @return OC_STACK_OK in case of success and other value otherwise.
1378  */
1379 OCStackResult OCChangeMOTMode(void *ctx, const OCProvisionDev_t *targetDeviceInfo,
1380                             const OicSecMomType_t momType, OCProvisionResultCB resultCallback)
1381 {
1382     return MOTChangeMode(ctx, targetDeviceInfo, momType, resultCallback);
1383 }
1384
1385 /**
1386  * API to update 'doxm.oxmsel' to resource server.
1387  *
1388  * @param[in] targetDeviceInfo Selected target device.
1389   * @param[in] oxmSelValue Method of multiple ownership transfer (ref. oic.sec.oxm)
1390  * @param[in] resultCallback callback provided by API user, callback will be called when
1391  *            POST 'oxmsel' request recieves a response from resource server.
1392  * @return OC_STACK_OK in case of success and other value otherwise.
1393  */
1394 OCStackResult OCSelectMOTMethod(void *ctx, const OCProvisionDev_t *targetDeviceInfo,
1395                                  const OicSecOxm_t oxmSelValue, OCProvisionResultCB resultCallback)
1396 {
1397     return MOTSelectMOTMethod(ctx, targetDeviceInfo, oxmSelValue, resultCallback);
1398 }
1399 #endif //MULTIPLE_OWNER
1400
1401 /**
1402  * Function to select appropriate security provisioning method.
1403  *
1404  * @param[in] supportedMethods   Array of supported methods
1405  * @param[in] numberOfMethods   number of supported methods
1406  * @param[out]  selectedMethod         Selected methods
1407  * @param[in] ownerType type of owner device (SUPER_OWNER or SUB_OWNER)
1408  * @return  OC_STACK_OK on success
1409  */
1410 OCStackResult OCSelectOwnershipTransferMethod(const OicSecOxm_t *supportedMethods,
1411         size_t numberOfMethods, OicSecOxm_t *selectedMethod, OwnerType_t ownerType)
1412 {
1413     return OTMSelectOwnershipTransferMethod(supportedMethods, numberOfMethods,
1414                                             selectedMethod, ownerType);
1415 }
1416
1417 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1418 /**
1419  * function to provision Trust certificate chain to devices.
1420  *
1421  * @param[in] ctx Application context would be returned in result callback.
1422  * @param[in] type Type of credentials to be provisioned to the device.
1423  * @param[in] credId CredId of trust certificate chain to be provisioned to the device.
1424  * @param[in] selectedDeviceInfo Pointer to OCProvisionDev_t instance,respresenting resource to be provsioned.
1425  * @param[in] resultCallback callback provided by API user, callback will be called when
1426  *            provisioning request recieves a response from first resource server.
1427  * @return  OC_STACK_OK in case of success and other value otherwise.
1428  */
1429 OCStackResult OCProvisionTrustCertChain(void *ctx, OicSecCredType_t type, uint16_t credId,
1430                                       const OCProvisionDev_t *selectedDeviceInfo,
1431                                       OCProvisionResultCB resultCallback)
1432 {
1433     return SRPProvisionTrustCertChain(ctx, type, credId,
1434                                       selectedDeviceInfo, resultCallback);
1435 }
1436
1437 /**
1438  * function to save Trust certificate chain into Cred of SVR.
1439  *
1440  * @param[in] trustCertChain Trust certificate chain to be saved in Cred of SVR.
1441  * @param[in] chainSize Size of trust certificate chain to be saved in Cred of SVR
1442  * @param[in] encodingType Encoding type of trust certificate chain to be saved in Cred of SVR
1443  * @param[out] credId CredId of saved trust certificate chain in Cred of SVR.
1444  * @return  OC_STACK_OK in case of success and other value otherwise.
1445  */
1446 OCStackResult OCSaveTrustCertChain(uint8_t *trustCertChain, size_t chainSize,
1447                                     OicEncodingType_t encodingType, uint16_t *credId)
1448 {
1449     return SRPSaveTrustCertChain(trustCertChain, chainSize, encodingType, credId);
1450 }
1451
1452 /**
1453  * function to register notifier for Trustcertchain change.
1454  *
1455  * @param[in] ctx user context.
1456  * @param[in] TrustCertChainChangeCB notification callback fucntion.
1457  * @return    OC_STACK_OK in case of success and other value otherwise.
1458  */
1459 OCStackResult OCRegisterTrustCertChainNotifier(void *ctx, TrustCertChainChangeCB Callback)
1460 {
1461     return SRPRegisterTrustCertChainNotifier(ctx, Callback);
1462 }
1463
1464 /**
1465  * function to de-register notifier for Trustcertchain change.
1466  */
1467 void OCRemoveTrustCertChainNotifier()
1468 {
1469     SRPRemoveTrustCertChainNotifier();
1470 }
1471
1472 /**
1473  * This function sets the callback to utilize peer certificate information
1474  */
1475 OCStackResult OCSetPeerCertCallback(void *ctx, PeerCertCallback peerCertCallback)
1476 {
1477     CAResult_t ret;
1478
1479     OIC_LOG_V(DEBUG, TAG, "IN %s", __func__);
1480     ret = CAsetPeerCertCallback(ctx, peerCertCallback);
1481     if (CA_STATUS_OK != ret)
1482     {
1483         OIC_LOG_V(ERROR, TAG, "CAsetPeerCertCallback() Failed(%d)", ret);
1484         return OC_STACK_ERROR;
1485     }
1486     OIC_LOG_V(DEBUG, TAG, "OUT %s", __func__);
1487
1488     return OC_STACK_OK;
1489 }
1490
1491 #endif // __WITH_DTLS__ || __WITH_TLS__
1492