Merge branch 'windows-port'
[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 "ownershiptransfermanager.h"
26 #include "oic_malloc.h"
27 #include "logger.h"
28 #include "secureresourceprovider.h"
29 #include "provisioningdatabasemanager.h"
30 #include "credresource.h"
31 #include "utlist.h"
32 #include "aclresource.h" //Note: SRM internal header
33 #include "pconfresource.h"
34
35 #define TAG "OCPMAPI"
36
37 typedef struct Linkdata Linkdata_t;
38 struct Linkdata
39 {
40     void *ctx;
41     const OCProvisionDev_t *pDev1;
42     OicSecAcl_t *pDev1Acl;
43     const OCProvisionDev_t *pDev2;
44     OicSecAcl_t *pDev2Acl;
45     OCProvisionResult_t *resArr;
46     int numOfResults;
47     int currentCountResults;
48     OCProvisionResultCB resultCallback;
49
50 };
51
52 /**
53  * The function is responsible for initializaton of the provisioning manager. It will load
54  * provisioning database which have owned device's list and their linked status.
55  * TODO: In addition, if there is a device(s) which has not up-to-date credentials, this function will
56  * automatically try to update the deivce(s).
57  *
58  * @param[in] dbPath file path of the sqlite3 db
59  *
60  * @return OC_STACK_OK in case of success and other value otherwise.
61  */
62 OCStackResult OCInitPM(const char* dbPath)
63 {
64     return PDMInit(dbPath);
65 }
66
67 /**
68  * The function is responsible for discovery of device is current subnet. It will list
69  * all the device in subnet which are not yet owned. Please call OCInit with OC_CLIENT_SERVER as
70  * OCMode.
71  *
72  * @param[in] timeout Timeout in seconds, value till which function will listen to responses from
73  *                    server before returning the list of devices.
74  * @param[out] ppList List of candidate devices to be provisioned
75  * @return OTM_SUCCESS in case of success and other value otherwise.
76  */
77 OCStackResult OCDiscoverUnownedDevices(unsigned short timeout, OCProvisionDev_t **ppList)
78 {
79     if( ppList == NULL || *ppList != NULL || 0 == timeout)
80     {
81         return OC_STACK_INVALID_PARAM;
82     }
83
84     return PMDeviceDiscovery(timeout, false, ppList);
85 }
86
87 /**
88  * The function is responsible for discovery of owned device is current subnet. It will list
89  * all the device in subnet which are owned by calling provisioning client.
90  *
91  * @param[in] timeout Timeout in seconds, value till which function will listen to responses from
92  *                    server before returning the list of devices.
93  * @param[out] ppList List of device owned by provisioning tool.
94  * @return OTM_SUCCESS in case of success and other value otherwise.
95  */
96 OCStackResult OCDiscoverOwnedDevices(unsigned short timeout, OCProvisionDev_t **ppList)
97 {
98     if( ppList == NULL || *ppList != NULL || 0 == timeout)
99     {
100         return OC_STACK_INVALID_PARAM;
101     }
102
103     return PMDeviceDiscovery(timeout, true, ppList);
104 }
105
106 /**
107  * API to register for particular OxM.
108  *
109  * @param[in] Ownership transfer method.
110  * @param[in] Implementation of callback functions for owership transfer.
111  * @return  OC_STACK_OK in case of success and other value otherwise.
112  */
113 OCStackResult OCSetOwnerTransferCallbackData(OicSecOxm_t oxm, OTMCallbackData_t* callbackData)
114 {
115     if(NULL == callbackData)
116     {
117         return OC_STACK_INVALID_CALLBACK ;
118     }
119
120     return OTMSetOwnershipTransferCallbackData(oxm, callbackData);
121 }
122
123 OCStackResult OCDoOwnershipTransfer(void* ctx,
124                                       OCProvisionDev_t *targetDevices,
125                                       OCProvisionResultCB resultCallback)
126 {
127     if( NULL == targetDevices )
128     {
129         return OC_STACK_INVALID_PARAM;
130     }
131     if (!resultCallback)
132     {
133         OIC_LOG(INFO, TAG, "OCDoOwnershipTransfer : NULL Callback");
134         return OC_STACK_INVALID_CALLBACK;
135     }
136     return OTMDoOwnershipTransfer(ctx, targetDevices, resultCallback);
137 }
138
139 /**
140  * This function deletes memory allocated to linked list created by OCDiscover_XXX_Devices API.
141  *
142  * @param[in] pList Pointer to OCProvisionDev_t which should be deleted.
143  */
144 void OCDeleteDiscoveredDevices(OCProvisionDev_t *pList)
145 {
146     PMDeleteDeviceList(pList);
147 }
148
149 /**
150  * this function sends ACL information to resource.
151  *
152  * @param[in] ctx Application context would be returned in result callback.
153  * @param[in] selectedDeviceInfo Selected target device.
154  * @param[in] acl ACL to provision.
155  * @param[in] resultCallback callback provided by API user, callback will be called when provisioning
156               request recieves a response from resource server.
157  * @return  OC_STACK_OK in case of success and other value otherwise.
158  */
159 OCStackResult OCProvisionACL(void* ctx, const OCProvisionDev_t *selectedDeviceInfo, OicSecAcl_t *acl,
160                              OCProvisionResultCB resultCallback)
161 {
162     return SRPProvisionACL(ctx, selectedDeviceInfo, acl, resultCallback);
163 }
164
165 /**
166  * this function requests CRED information to resource.
167  *
168  * @param[in] ctx Application context would be returned in result callback.
169  * @param[in] selectedDeviceInfo Selected target device.
170  * @param[in] resultCallback callback provided by API user, callback will be called when provisioning
171               request recieves a response from resource server.
172  * @return  OC_STACK_OK in case of success and other value otherwise.
173  */
174 OCStackResult OCGetCredResource(void* ctx, const OCProvisionDev_t *selectedDeviceInfo,
175                              OCProvisionResultCB resultCallback)
176 {
177     return SRPGetCredResource(ctx, selectedDeviceInfo, resultCallback);
178 }
179
180 /**
181  * this function requests ACL information to resource.
182  *
183  * @param[in] ctx Application context would be returned in result callback.
184  * @param[in] selectedDeviceInfo Selected target device.
185  * @param[in] resultCallback callback provided by API user, callback will be called when provisioning
186               request recieves a response from resource server.
187  * @return  OC_STACK_OK in case of success and other value otherwise.
188  */
189 OCStackResult OCGetACLResource(void* ctx, const OCProvisionDev_t *selectedDeviceInfo,
190                              OCProvisionResultCB resultCallback)
191 {
192     return SRPGetACLResource(ctx, selectedDeviceInfo, resultCallback);
193 }
194
195 /**
196  * function to provision credential to devices.
197  *
198  * @param[in] ctx Application context would be returned in result callback.
199  * @param[in] type Type of credentials to be provisioned to the device.
200  * @param[in] pDev1 Pointer to OCProvisionDev_t instance,respresenting resource to be provsioned.
201    @param[in] pDev2 Pointer to OCProvisionDev_t instance,respresenting resource to be provsioned.
202  * @param[in] resultCallback callback provided by API user, callback will be called when
203  *            provisioning request recieves a response from first resource server.
204  * @return  OC_STACK_OK in case of success and other value otherwise.
205  */
206 OCStackResult OCProvisionCredentials(void *ctx, OicSecCredType_t type, size_t keySize,
207                                       const OCProvisionDev_t *pDev1,
208                                       const OCProvisionDev_t *pDev2,
209                                       OCProvisionResultCB resultCallback)
210 {
211     return SRPProvisionCredentials(ctx, type, keySize,
212                                       pDev1, pDev2, resultCallback);
213
214 }
215
216 /**
217  * this function sends Direct-Pairing Configuration to a device.
218  *
219  * @param[in] ctx Application context would be returned in result callback.
220  * @param[in] selectedDeviceInfo Selected target device.
221  * @param[in] pconf PCONF pointer.
222  * @param[in] resultCallback callback provided by API user, callback will be called when provisioning
223               request recieves a response from resource server.
224  * @return  OC_STACK_OK in case of success and other value otherwise.
225  */
226 OCStackResult OCProvisionDirectPairing(void* ctx, const OCProvisionDev_t *selectedDeviceInfo, OicSecPconf_t *pconf,
227                              OCProvisionResultCB resultCallback)
228 {
229     return SRPProvisionDirectPairing(ctx, selectedDeviceInfo, pconf, resultCallback);
230 }
231
232 /*
233 * Function to unlink devices.
234 * This function will remove the credential & relationship between the two devices.
235 *
236 * @param[in] ctx Application context would be returned in result callback
237 * @param[in] pTargetDev1 first device information to be unlinked.
238 * @param[in] pTargetDev2 second device information to be unlinked.
239 * @param[in] resultCallback callback provided by API user, callback will be called when
240 *            device unlink is finished.
241  * @return  OC_STACK_OK in case of success and other value otherwise.
242 */
243 OCStackResult OCUnlinkDevices(void* ctx,
244                               const OCProvisionDev_t* pTargetDev1,
245                               const OCProvisionDev_t* pTargetDev2,
246                               OCProvisionResultCB resultCallback)
247 {
248     OIC_LOG(INFO, TAG, "IN OCUnlinkDevices");
249     OCUuidList_t* idList = NULL;
250     size_t numOfDev = 0;
251
252     if (!pTargetDev1 || !pTargetDev2 || !pTargetDev1->doxm || !pTargetDev2->doxm)
253     {
254         OIC_LOG(ERROR, TAG, "OCUnlinkDevices : NULL parameters");
255         return OC_STACK_INVALID_PARAM;
256     }
257     if (!resultCallback)
258     {
259         OIC_LOG(INFO, TAG, "OCUnlinkDevices : NULL Callback");
260         return OC_STACK_INVALID_CALLBACK;
261     }
262     if (0 == memcmp(&pTargetDev1->doxm->deviceID, &pTargetDev2->doxm->deviceID, sizeof(OicUuid_t)))
263     {
264         OIC_LOG(INFO, TAG, "OCUnlinkDevices : Same device ID");
265         return OC_STACK_INVALID_PARAM;
266     }
267
268     // Get linked devices with the first device.
269     OCStackResult res = PDMGetLinkedDevices(&(pTargetDev1->doxm->deviceID), &idList, &numOfDev);
270     if (OC_STACK_OK != res)
271     {
272         OIC_LOG(ERROR, TAG, "OCUnlinkDevices : PDMgetOwnedDevices failed");
273         goto error;
274     }
275     if (1 > numOfDev)
276     {
277         OIC_LOG(DEBUG, TAG, "OCUnlinkDevices : Can not find linked devices");
278         res = OC_STACK_INVALID_PARAM; // Input devices are not linked, No request is made
279         goto error;
280     }
281
282     // Check the linked devices contains the second device. If yes send credential DELETE request.
283     OCUuidList_t* curDev = idList;
284     while (NULL != curDev)
285     {
286         if (memcmp(pTargetDev2->doxm->deviceID.id, curDev->dev.id, sizeof(curDev->dev.id)) == 0)
287         {
288             res = SRPUnlinkDevices(ctx, pTargetDev1, pTargetDev2, resultCallback);
289             if (OC_STACK_OK != res)
290             {
291                 OIC_LOG(ERROR, TAG, "OCUnlinkDevices : Failed to unlink devices.");
292             }
293             goto error;
294         }
295         curDev = curDev->next;
296     }
297     OIC_LOG(DEBUG, TAG, "No matched pair found from provisioning database");
298     res = OC_STACK_INVALID_PARAM; // Input devices are not linked, No request is made
299
300 error:
301     OIC_LOG(INFO, TAG, "OUT OCUnlinkDevices");
302
303     PDMDestoryOicUuidLinkList(idList);
304     return res;
305 }
306
307 /*
308 * Function to device revocation
309 * This function will remove credential of target device from all devices in subnet.
310 *
311 * @param[in] ctx Application context would be returned in result callback
312 * @param[in] waitTimeForOwnedDeviceDiscovery Maximum wait time for owned device discovery.(seconds)
313 * @param[in] pTargetDev Device information to be revoked.
314 * @param[in] resultCallback callback provided by API user, callback will be called when
315 *            credential revocation is finished.
316  * @return  OC_STACK_OK in case of success and other value otherwise.
317 */
318 OCStackResult OCRemoveDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDiscovery,
319                             const OCProvisionDev_t* pTargetDev,
320                             OCProvisionResultCB resultCallback)
321 {
322     OIC_LOG(INFO, TAG, "IN OCRemoveDevice");
323     OCStackResult res = OC_STACK_ERROR;
324     if (!pTargetDev || 0 == waitTimeForOwnedDeviceDiscovery)
325     {
326         OIC_LOG(INFO, TAG, "OCRemoveDevice : Invalied parameters");
327         return OC_STACK_INVALID_PARAM;
328     }
329     if (!resultCallback)
330     {
331         OIC_LOG(INFO, TAG, "OCRemoveDevice : NULL Callback");
332         return OC_STACK_INVALID_CALLBACK;
333     }
334
335     // Send DELETE requests to linked devices
336     OCStackResult resReq = OC_STACK_ERROR; // Check that we have to wait callback or not.
337     resReq = SRPRemoveDevice(ctx, waitTimeForOwnedDeviceDiscovery, pTargetDev, resultCallback);
338     if (OC_STACK_OK != resReq)
339     {
340         if (OC_STACK_CONTINUE == resReq)
341         {
342             OIC_LOG(DEBUG, TAG, "OCRemoveDevice : Revoked device has no linked device except PT.");
343         }
344         else
345         {
346             OIC_LOG(ERROR, TAG, "OCRemoveDevice : Failed to invoke SRPRemoveDevice");
347             res = resReq;
348             goto error;
349         }
350     }
351
352     // Remove credential of revoked device from SVR database
353     const OicSecCred_t *cred = NULL;
354     cred = GetCredResourceData(&pTargetDev->doxm->deviceID);
355     if (cred == NULL)
356     {
357         OIC_LOG(ERROR, TAG, "OCRemoveDevice : Failed to get credential of remove device.");
358         goto error;
359     }
360
361     res = RemoveCredential(&cred->subject);
362     if (res != OC_STACK_RESOURCE_DELETED)
363     {
364         OIC_LOG(ERROR, TAG, "OCRemoveDevice : Failed to remove credential.");
365         goto error;
366     }
367
368     /**
369      * Change the device status as stale status.
370      * If all request are successed, this device information will be deleted.
371      */
372     res = PDMSetDeviceStale(&pTargetDev->doxm->deviceID);
373     if (res != OC_STACK_OK)
374     {
375         OIC_LOG(ERROR, TAG, "OCRemoveDevice : Failed to set device status as stale");
376         goto error;
377     }
378
379     // TODO: We need to add new mechanism to clean up the stale state of the device.
380
381     res = resReq;
382
383     //Close the DTLS session of the removed device.
384     CAEndpoint_t* endpoint = (CAEndpoint_t *)&pTargetDev->endpoint;
385     endpoint->port = pTargetDev->securePort;
386     CAResult_t caResult = CACloseDtlsSession(endpoint);
387     if(CA_STATUS_OK != caResult)
388     {
389         OIC_LOG_V(WARNING, TAG, "OCRemoveDevice : Failed to close DTLS session : %d", caResult);
390     }
391
392     /**
393      * If there is no linked device, PM does not send any request.
394      * So we should directly invoke the result callback to inform the result of OCRemoveDevice.
395      */
396     if(OC_STACK_CONTINUE == res)
397     {
398         if(resultCallback)
399         {
400             resultCallback(ctx, 0, NULL, false);
401         }
402         res = OC_STACK_OK;
403     }
404
405 error:
406     OIC_LOG(INFO, TAG, "OUT OCRemoveDevice");
407     return res;
408 }
409
410
411 /**
412  * Internal Function to update result in link result array.
413  */
414 static void UpdateLinkResults(Linkdata_t *link, int device, OCStackResult stackresult)
415 {
416
417     OIC_LOG_V(INFO,TAG,"value of link->currentCountResults is %d",link->currentCountResults);
418     if (1 == device)
419     {
420         memcpy(link->resArr[(link->currentCountResults)].deviceId.id, link->pDev1->doxm->deviceID.id,UUID_LENGTH);
421     }
422     else
423     {
424         memcpy(link->resArr[(link->currentCountResults)].deviceId.id, link->pDev2->doxm->deviceID.id,UUID_LENGTH);
425     }
426     link->resArr[(link->currentCountResults)].res = stackresult;
427     ++(link->currentCountResults);
428
429 }
430
431 /**
432  * Callback to handle ACL provisioning for device 2.
433  */
434 static void AclProv2CB(void* ctx, int nOfRes, OCProvisionResult_t *arr, bool hasError)
435 {
436
437     if (NULL == ctx)
438     {
439         OIC_LOG(ERROR,TAG,"Context is Null in ACLProv 2");
440         return;
441     }
442     (void)nOfRes;
443     Linkdata_t *link = (Linkdata_t*)ctx;
444     OCProvisionResultCB resultCallback = link->resultCallback;
445
446
447     if (hasError)
448     {
449         UpdateLinkResults(link, 2,arr[0].res);
450         OIC_LOG(ERROR,TAG,"Error occured while ACL provisioning device 1");
451         ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
452                                                 link->resArr,
453                                                 true);
454         OICFree(link->resArr);
455         OICFree(link) ;
456         return;
457     }
458     UpdateLinkResults(link, 2, arr[0].res);
459    ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
460                                            link->resArr,
461                                            false);
462     OICFree(link->resArr);
463     OICFree(link);
464     return;
465 }
466
467 /**
468  * Callback to handle ACL provisioning for device 1
469  */
470 static void AclProv1CB(void* ctx, int nOfRes, OCProvisionResult_t *arr, bool hasError)
471 {
472
473     if (NULL == ctx)
474     {
475         OIC_LOG(ERROR,TAG,"Context is Null in ACLProv1");
476         return;
477     }
478     (void)nOfRes;
479     Linkdata_t *link = (Linkdata_t*)ctx;
480     OCProvisionResultCB resultCallback = link->resultCallback;
481
482     if (hasError)
483     {
484         OIC_LOG(ERROR,TAG,"Error occured while ACL provisioning device 1");
485         UpdateLinkResults(link, 1, arr[0].res);
486         ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
487                                                 link->resArr,
488                                                 true);
489         OICFree(link->resArr);
490         OICFree(link);
491         return;
492     }
493     UpdateLinkResults(link, 1, arr[0].res);
494     if (NULL != link->pDev2Acl)
495     {
496         OCStackResult res =  SRPProvisionACL(ctx, link->pDev2, link->pDev2Acl, &AclProv2CB);
497         if (OC_STACK_OK!=res)
498         {
499              UpdateLinkResults(link, 2, res);
500              ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
501                                                      link->resArr,
502                                                      true);
503
504         }
505     }
506     else
507     {
508         ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
509                                                 link->resArr,
510                                                 false);
511         OICFree(link->resArr);
512         OICFree(link);
513     }
514
515     return;
516 }
517
518 /**
519  * Callback to handle credential provisioning.
520  */
521 static void ProvisionCredsCB(void* ctx, int nOfRes, OCProvisionResult_t *arr, bool hasError)
522 {
523     if (NULL == ctx)
524     {
525         OIC_LOG(ERROR,TAG,"Error occured while credential provisioning");
526         return;
527     }
528     Linkdata_t *link = (Linkdata_t*)ctx;
529     OCProvisionResultCB resultCallback = link->resultCallback;
530     OIC_LOG_V(INFO, TAG, "has error returned %d",hasError);
531     UpdateLinkResults(link, 1, arr[0].res);
532     UpdateLinkResults(link, 2, arr[1].res);
533     if (hasError)
534     {
535         OIC_LOG(ERROR,TAG,"Error occured while credential provisioning");
536         ((OCProvisionResultCB)(resultCallback))(link->ctx, nOfRes,
537                                                 link->resArr,
538                                                 true);
539          OICFree(link->resArr);
540          OICFree(link);
541          return;
542     }
543     if (NULL != link->pDev1Acl)
544     {
545
546         OCStackResult res =  SRPProvisionACL(ctx, link->pDev1, link->pDev1Acl, &AclProv1CB);
547         if (OC_STACK_OK!=res)
548         {
549              OIC_LOG(ERROR, TAG, "Error while provisioning ACL for device 1");
550              UpdateLinkResults(link, 1, res);
551              ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
552                                                      link->resArr,
553                                                      true);
554               OICFree(link->resArr);
555               OICFree(link);
556         }
557     }
558     else if (NULL!=link->pDev2Acl)
559     {
560         OIC_LOG(ERROR, TAG, "ACL for device 1 is NULL");
561         OCStackResult res =  SRPProvisionACL(ctx, link->pDev2, link->pDev2Acl, &AclProv2CB);
562         if (OC_STACK_OK!=res)
563         {
564              OIC_LOG(ERROR, TAG, "Error while provisioning ACL for device 2");
565               UpdateLinkResults(link, 2, res);
566              ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
567                                                      link->resArr,
568                                                      true);
569               OICFree(link->resArr);
570               OICFree(link);
571         }
572     }
573     else
574     {
575         OIC_LOG(INFO, TAG, "ACLs of both devices are NULL");
576         ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
577                                                 link->resArr,
578                                                 false);
579         OICFree(link->resArr);
580         OICFree(link);
581     }
582     return;
583 }
584 /**
585  * function to provision credentials between two devices and ACLs for the devices who act as a server.
586  *
587  * @param[in] ctx Application context would be returned in result callback.
588  * @param[in] type Type of credentials to be provisioned to the device.
589  * @param[in] pDev1 Pointer to OCProvisionDev_t instance,respresenting resource to be provsioned.
590  * @param[in] acl ACL for device 1. If this is not required set NULL.
591  * @param[in] pDev2 Pointer to OCProvisionDev_t instance,respresenting resource to be provsioned.
592  * @param[in] acl ACL for device 2. If this is not required set NULL.
593  * @param[in] resultCallback callback provided by API user, callback will be called when
594  *            provisioning request recieves a response from first resource server.
595  * @return  OC_STACK_OK in case of success and other value otherwise.
596  */
597 OCStackResult OCProvisionPairwiseDevices(void* ctx, OicSecCredType_t type, size_t keySize,
598                                          const OCProvisionDev_t *pDev1, OicSecAcl_t *pDev1Acl,
599                                          const OCProvisionDev_t *pDev2, OicSecAcl_t *pDev2Acl,
600                                          OCProvisionResultCB resultCallback)
601 {
602
603     if (!pDev1 || !pDev2 || !pDev1->doxm || !pDev2->doxm)
604     {
605         OIC_LOG(ERROR, TAG, "OCProvisionPairwiseDevices : Invalid parameters");
606         return OC_STACK_INVALID_PARAM;
607     }
608     if (!resultCallback)
609     {
610         OIC_LOG(INFO, TAG, "OCProvisionPairwiseDevices : NULL Callback");
611         return OC_STACK_INVALID_CALLBACK;
612     }
613     if (!(keySize == OWNER_PSK_LENGTH_128 || keySize == OWNER_PSK_LENGTH_256))
614     {
615         OIC_LOG(INFO, TAG, "OCProvisionPairwiseDevices : Invalid key size");
616         return OC_STACK_INVALID_PARAM;
617     }
618     if (0 == memcmp(&pDev1->doxm->deviceID, &pDev2->doxm->deviceID, sizeof(OicUuid_t)))
619     {
620         OIC_LOG(INFO, TAG, "OCProvisionPairwiseDevices : Same device ID");
621         return OC_STACK_INVALID_PARAM;
622     }
623
624     OIC_LOG(DEBUG, TAG, "Checking link in DB");
625     bool linkExists = true;
626     OCStackResult res = PDMIsLinkExists(&pDev1->doxm->deviceID, &pDev2->doxm->deviceID, &linkExists);
627     if(res != OC_STACK_OK)
628     {
629         OIC_LOG(ERROR, TAG, "Internal Error Occured");
630         return res;
631     }
632     if (linkExists)
633     {
634         OIC_LOG(ERROR, TAG, "Link already exists");
635         return OC_STACK_INVALID_PARAM;
636     }
637
638     int noOfResults = 2; // Initial Value
639     if (NULL != pDev1Acl)
640     {
641         ++noOfResults;
642     }
643     if (NULL != pDev2Acl)
644     {
645        ++noOfResults;
646     }
647     Linkdata_t *link = (Linkdata_t*) OICMalloc(sizeof(Linkdata_t));
648     if (!link)
649     {
650         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
651         return OC_STACK_NO_MEMORY;
652     }
653     OIC_LOG_V(INFO,TAG, "Maximum no od results %d",noOfResults);
654
655     link->pDev1 = pDev1;
656     link->pDev1Acl = pDev1Acl;
657     link->pDev2 = pDev2;
658     link->pDev2Acl = pDev2Acl;
659     link->ctx = ctx;
660     // 1 call for each device for credential provisioning. implict call by SRPProvisioning credential
661     // 1 call for ACL provisioning for device 1 and 1 call for ACL provisioning for device 2.
662     link->numOfResults = noOfResults;
663     link->resultCallback = resultCallback;
664     link->currentCountResults = 0;
665     link->resArr = (OCProvisionResult_t*) OICMalloc(sizeof(OCProvisionResult_t)*noOfResults);
666     res = SRPProvisionCredentials(link, type, keySize,
667                                      pDev1, pDev2, &ProvisionCredsCB);
668     if (res != OC_STACK_OK)
669     {
670         OICFree(link->resArr);
671         OICFree(link);
672     }
673     return res;
674
675 }
676
677 OCStackResult OCGetDevInfoFromNetwork(unsigned short waittime,
678                                        OCProvisionDev_t** pOwnedDevList,
679                                        OCProvisionDev_t** pUnownedDevList)
680 {
681     //TODO will be replaced by more efficient logic
682     if (pOwnedDevList == NULL || *pOwnedDevList != NULL || pUnownedDevList == NULL
683          || *pUnownedDevList != NULL || 0 == waittime)
684     {
685         return OC_STACK_INVALID_PARAM;
686     }
687
688     // Code for unowned discovery
689     OCProvisionDev_t *unownedDevice = NULL;
690     OCStackResult res =  OCDiscoverUnownedDevices(waittime/2, &unownedDevice);
691     if (OC_STACK_OK != res)
692     {
693         OIC_LOG(ERROR,TAG, "Error in unowned discovery");
694         return res;
695     }
696
697     // Code for owned discovery
698     OCProvisionDev_t *ownedDevice = NULL;
699     res =  OCDiscoverOwnedDevices(waittime/2, &ownedDevice);
700     if (OC_STACK_OK != res)
701     {
702         OIC_LOG(ERROR,TAG, "Error in owned discovery");
703         PMDeleteDeviceList(unownedDevice);
704         return res;
705     }
706
707     // Code to get list of all the owned devices.
708     OCUuidList_t *uuidList = NULL;
709     size_t numOfDevices = 0;
710     res =  PDMGetOwnedDevices(&uuidList, &numOfDevices);
711     if (OC_STACK_OK != res)
712     {
713         OIC_LOG(ERROR, TAG, "Error while getting info from DB");
714         PMDeleteDeviceList(unownedDevice);
715         PMDeleteDeviceList(ownedDevice);
716         return res;
717     }
718
719     // Code to compare devices in owned list and deviceid from DB.
720     OCProvisionDev_t* pCurDev = ownedDevice;
721     size_t deleteCnt = 0;
722     while (pCurDev)
723     {
724         if(true == PMDeleteFromUUIDList(uuidList, &pCurDev->doxm->deviceID))
725         {
726             deleteCnt++;
727         }
728         pCurDev = pCurDev->next;
729     }
730     // If there is no remaind device in uuidList, we have to assign NULL to prevent free.
731     if (deleteCnt == numOfDevices)
732     {
733         uuidList = NULL;
734     }
735     // Code to add information of the devices which are currently off in owned list.
736     OCUuidList_t *powerOffDeviceList = uuidList;
737     while (powerOffDeviceList)
738     {
739         OCProvisionDev_t *ptr = (OCProvisionDev_t *)OICCalloc(1, sizeof (OCProvisionDev_t));
740         if (NULL == ptr)
741         {
742             OIC_LOG(ERROR,TAG,"Fail to allocate memory");
743             PMDeleteDeviceList(unownedDevice);
744             PMDeleteDeviceList(ownedDevice);
745             OCDeleteUuidList(uuidList);
746             return OC_STACK_NO_MEMORY;
747         }
748
749         ptr->doxm = (OicSecDoxm_t*)OICCalloc(1, sizeof(OicSecDoxm_t));
750         if (NULL == ptr->doxm)
751         {
752             OIC_LOG(ERROR,TAG,"Fail to allocate memory");
753             PMDeleteDeviceList(unownedDevice);
754             PMDeleteDeviceList(ownedDevice);
755             OCDeleteUuidList(uuidList);
756             OICFree(ptr);
757             return OC_STACK_NO_MEMORY;
758         }
759
760         memcpy(ptr->doxm->deviceID.id, powerOffDeviceList->dev.id, sizeof(ptr->doxm->deviceID.id));
761
762         ptr->devStatus = DEV_STATUS_OFF;
763         LL_PREPEND(ownedDevice, ptr);
764         powerOffDeviceList = powerOffDeviceList->next;
765
766     }
767     OCDeleteUuidList(uuidList);
768     *pOwnedDevList = ownedDevice;
769     *pUnownedDevList = unownedDevice;
770     return OC_STACK_OK;
771 }
772
773 OCStackResult OCGetLinkedStatus(const OicUuid_t* uuidOfDevice, OCUuidList_t** uuidList,
774                                  size_t* numOfDevices)
775 {
776     return PDMGetLinkedDevices(uuidOfDevice, uuidList, numOfDevices);
777 }
778
779 void OCDeleteUuidList(OCUuidList_t* pList)
780 {
781     PDMDestoryOicUuidLinkList(pList);
782 }
783
784 /**
785  * This function deletes ACL data.
786  *
787  * @param pAcl Pointer to OicSecAcl_t structure.
788  */
789 void OCDeleteACLList(OicSecAcl_t* pAcl)
790 {
791     DeleteACLList(pAcl);
792 }
793
794 /**
795  * This function deletes PDACL data.
796  *
797  * @param pPdAcl Pointer to OicSecPdAcl_t structure.
798  */
799 void OCDeletePdAclList(OicSecPdAcl_t* pPdAcl)
800 {
801     FreePdAclList(pPdAcl);
802 }
803
804
805 #ifdef __WITH_X509__
806 /**
807  * this function sends CRL information to resource.
808  *
809  * @param[in] ctx Application context would be returned in result callback.
810  * @param[in] selectedDeviceInfo Selected target device.
811  * @param[in] crl CRL to provision.
812  * @param[in] resultCallback callback provided by API user, callback will be called when provisioning
813               request recieves a response from resource server.
814  * @return  OC_STACK_OK in case of success and other value otherwise.
815  */
816 OCStackResult OCProvisionCRL(void* ctx, const OCProvisionDev_t *selectedDeviceInfo, OicSecCrl_t *crl,
817                              OCProvisionResultCB resultCallback)
818 {
819     return SRPProvisionCRL(ctx, selectedDeviceInfo, crl, resultCallback);
820 }
821 #endif // __WITH_X509__
822