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