Merge remote-tracking branch 'origin/notification-service'
[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 #include "oic_malloc.h"
28 #include "logger.h"
29 #include "secureresourceprovider.h"
30 #include "provisioningdatabasemanager.h"
31 #include "credresource.h"
32 #include "utlist.h"
33 #include "aclresource.h" //Note: SRM internal header
34 #include "pconfresource.h"
35
36 #define TAG "OCPMAPI"
37
38 typedef struct Linkdata Linkdata_t;
39 struct Linkdata
40 {
41     void *ctx;
42     const OCProvisionDev_t *pDev1;
43     OicSecAcl_t *pDev1Acl;
44     const OCProvisionDev_t *pDev2;
45     OicSecAcl_t *pDev2Acl;
46     OCProvisionResult_t *resArr;
47     int numOfResults;
48     int currentCountResults;
49     OCProvisionResultCB resultCallback;
50
51 };
52
53 /**
54  * The function is responsible for initializaton of the provisioning manager. It will load
55  * provisioning database which have owned device's list and their linked status.
56  * TODO: In addition, if there is a device(s) which has not up-to-date credentials, this function will
57  * automatically try to update the deivce(s).
58  *
59  * @param[in] dbPath file path of the sqlite3 db
60  *
61  * @return OC_STACK_OK in case of success and other value otherwise.
62  */
63 OCStackResult OCInitPM(const char* dbPath)
64 {
65     return PDMInit(dbPath);
66 }
67
68 /**
69  * The function is responsible for discovery of owned/unowned device is specified endpoint.
70  * It will return when found one or more device even though timeout is not exceeded
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[in] host               address of target endpoint
75  * @param[in] connType           connectivity type of endpoint
76  * @param[out] ppList            List of device.
77  * @return OTM_SUCCESS in case of success and other value otherwise.
78  */
79 OCStackResult OCDiscoverSecureResource(unsigned short timeout, const char* host,
80                              OCConnectivityType connType, OCProvisionDev_t **ppList)
81 {
82     if( ppList == NULL || *ppList != NULL || 0 == timeout || host == NULL)
83     {
84         return OC_STACK_INVALID_PARAM;
85     }
86
87     return PMSingleDeviceDiscovery(timeout, host, connType, ppList);
88 }
89
90 /**
91  * The function is responsible for discovery of device is current subnet. It will list
92  * all the device in subnet which are not yet owned. Please call OCInit with OC_CLIENT_SERVER as
93  * OCMode.
94  *
95  * @param[in] timeout Timeout in seconds, value till which function will listen to responses from
96  *                    server before returning the list of devices.
97  * @param[out] ppList List of candidate devices to be provisioned
98  * @return OTM_SUCCESS in case of success and other value otherwise.
99  */
100 OCStackResult OCDiscoverUnownedDevices(unsigned short timeout, OCProvisionDev_t **ppList)
101 {
102     if( ppList == NULL || *ppList != NULL || 0 == timeout)
103     {
104         return OC_STACK_INVALID_PARAM;
105     }
106
107     return PMDeviceDiscovery(timeout, false, ppList);
108 }
109
110 /**
111  * The function is responsible for discovery of owned device is current subnet. It will list
112  * all the device in subnet which are owned by calling provisioning client.
113  *
114  * @param[in] timeout Timeout in seconds, value till which function will listen to responses from
115  *                    server before returning the list of devices.
116  * @param[out] ppList List of device owned by provisioning tool.
117  * @return OTM_SUCCESS in case of success and other value otherwise.
118  */
119 OCStackResult OCDiscoverOwnedDevices(unsigned short timeout, OCProvisionDev_t **ppList)
120 {
121     if( ppList == NULL || *ppList != NULL || 0 == timeout)
122     {
123         return OC_STACK_INVALID_PARAM;
124     }
125
126     return PMDeviceDiscovery(timeout, true, ppList);
127 }
128
129 /**
130  * API to register for particular OxM.
131  *
132  * @param[in] Ownership transfer method.
133  * @param[in] Implementation of callback functions for owership transfer.
134  * @return  OC_STACK_OK in case of success and other value otherwise.
135  */
136 OCStackResult OCSetOwnerTransferCallbackData(OicSecOxm_t oxm, OTMCallbackData_t* callbackData)
137 {
138     if(NULL == callbackData)
139     {
140         return OC_STACK_INVALID_CALLBACK ;
141     }
142
143     return OTMSetOwnershipTransferCallbackData(oxm, callbackData);
144 }
145
146 OCStackResult OCDoOwnershipTransfer(void* ctx,
147                                       OCProvisionDev_t *targetDevices,
148                                       OCProvisionResultCB resultCallback)
149 {
150     if( NULL == targetDevices )
151     {
152         return OC_STACK_INVALID_PARAM;
153     }
154     if (!resultCallback)
155     {
156         OIC_LOG(INFO, TAG, "OCDoOwnershipTransfer : NULL Callback");
157         return OC_STACK_INVALID_CALLBACK;
158     }
159     return OTMDoOwnershipTransfer(ctx, targetDevices, resultCallback);
160 }
161
162 /**
163  * This function deletes memory allocated to linked list created by OCDiscover_XXX_Devices API.
164  *
165  * @param[in] pList Pointer to OCProvisionDev_t which should be deleted.
166  */
167 void OCDeleteDiscoveredDevices(OCProvisionDev_t *pList)
168 {
169     PMDeleteDeviceList(pList);
170 }
171
172 /**
173  * this function sends ACL information to resource.
174  *
175  * @param[in] ctx Application context would be returned in result callback.
176  * @param[in] selectedDeviceInfo Selected target device.
177  * @param[in] acl ACL to provision.
178  * @param[in] resultCallback callback provided by API user, callback will be called when provisioning
179               request recieves a response from resource server.
180  * @return  OC_STACK_OK in case of success and other value otherwise.
181  */
182 OCStackResult OCProvisionACL(void* ctx, const OCProvisionDev_t *selectedDeviceInfo, OicSecAcl_t *acl,
183                              OCProvisionResultCB resultCallback)
184 {
185     return SRPProvisionACL(ctx, selectedDeviceInfo, acl, resultCallback);
186 }
187
188 /**
189  * this function requests CRED information to resource.
190  *
191  * @param[in] ctx Application context would be returned in result callback.
192  * @param[in] selectedDeviceInfo Selected target device.
193  * @param[in] resultCallback callback provided by API user, callback will be called when provisioning
194               request recieves a response from resource server.
195  * @return  OC_STACK_OK in case of success and other value otherwise.
196  */
197 OCStackResult OCGetCredResource(void* ctx, const OCProvisionDev_t *selectedDeviceInfo,
198                              OCProvisionResultCB resultCallback)
199 {
200     return SRPGetCredResource(ctx, selectedDeviceInfo, resultCallback);
201 }
202
203 /**
204  * this function requests ACL information to resource.
205  *
206  * @param[in] ctx Application context would be returned in result callback.
207  * @param[in] selectedDeviceInfo Selected target device.
208  * @param[in] resultCallback callback provided by API user, callback will be called when provisioning
209               request recieves a response from resource server.
210  * @return  OC_STACK_OK in case of success and other value otherwise.
211  */
212 OCStackResult OCGetACLResource(void* ctx, const OCProvisionDev_t *selectedDeviceInfo,
213                              OCProvisionResultCB resultCallback)
214 {
215     return SRPGetACLResource(ctx, selectedDeviceInfo, resultCallback);
216 }
217
218 /**
219  * function to provision credential to devices.
220  *
221  * @param[in] ctx Application context would be returned in result callback.
222  * @param[in] type Type of credentials to be provisioned to the device.
223  * @param[in] pDev1 Pointer to OCProvisionDev_t instance,respresenting resource to be provsioned.
224    @param[in] pDev2 Pointer to OCProvisionDev_t instance,respresenting resource to be provsioned.
225  * @param[in] resultCallback callback provided by API user, callback will be called when
226  *            provisioning request recieves a response from first resource server.
227  * @return  OC_STACK_OK in case of success and other value otherwise.
228  */
229 OCStackResult OCProvisionCredentials(void *ctx, OicSecCredType_t type, size_t keySize,
230                                       const OCProvisionDev_t *pDev1,
231                                       const OCProvisionDev_t *pDev2,
232                                       OCProvisionResultCB resultCallback)
233 {
234     return SRPProvisionCredentials(ctx, type, keySize,
235                                       pDev1, pDev2, resultCallback);
236
237 }
238
239 /**
240  * this function sends Direct-Pairing Configuration to a device.
241  *
242  * @param[in] ctx Application context would be returned in result callback.
243  * @param[in] selectedDeviceInfo Selected target device.
244  * @param[in] pconf PCONF pointer.
245  * @param[in] resultCallback callback provided by API user, callback will be called when provisioning
246               request recieves a response from resource server.
247  * @return  OC_STACK_OK in case of success and other value otherwise.
248  */
249 OCStackResult OCProvisionDirectPairing(void* ctx, const OCProvisionDev_t *selectedDeviceInfo, OicSecPconf_t *pconf,
250                              OCProvisionResultCB resultCallback)
251 {
252     return SRPProvisionDirectPairing(ctx, selectedDeviceInfo, pconf, resultCallback);
253 }
254
255 /*
256 * Function to unlink devices.
257 * This function will remove the credential & relationship between the two devices.
258 *
259 * @param[in] ctx Application context would be returned in result callback
260 * @param[in] pTargetDev1 first device information to be unlinked.
261 * @param[in] pTargetDev2 second device information to be unlinked.
262 * @param[in] resultCallback callback provided by API user, callback will be called when
263 *            device unlink is finished.
264  * @return  OC_STACK_OK in case of success and other value otherwise.
265 */
266 OCStackResult OCUnlinkDevices(void* ctx,
267                               const OCProvisionDev_t* pTargetDev1,
268                               const OCProvisionDev_t* pTargetDev2,
269                               OCProvisionResultCB resultCallback)
270 {
271     OIC_LOG(INFO, TAG, "IN OCUnlinkDevices");
272     OCUuidList_t* idList = NULL;
273     size_t numOfDev = 0;
274
275     if (!pTargetDev1 || !pTargetDev2 || !pTargetDev1->doxm || !pTargetDev2->doxm)
276     {
277         OIC_LOG(ERROR, TAG, "OCUnlinkDevices : NULL parameters");
278         return OC_STACK_INVALID_PARAM;
279     }
280     if (!resultCallback)
281     {
282         OIC_LOG(INFO, TAG, "OCUnlinkDevices : NULL Callback");
283         return OC_STACK_INVALID_CALLBACK;
284     }
285     if (0 == memcmp(&pTargetDev1->doxm->deviceID, &pTargetDev2->doxm->deviceID, sizeof(OicUuid_t)))
286     {
287         OIC_LOG(INFO, TAG, "OCUnlinkDevices : Same device ID");
288         return OC_STACK_INVALID_PARAM;
289     }
290
291     // Get linked devices with the first device.
292     OCStackResult res = PDMGetLinkedDevices(&(pTargetDev1->doxm->deviceID), &idList, &numOfDev);
293     if (OC_STACK_OK != res)
294     {
295         OIC_LOG(ERROR, TAG, "OCUnlinkDevices : PDMgetOwnedDevices failed");
296         goto error;
297     }
298     if (1 > numOfDev)
299     {
300         OIC_LOG(DEBUG, TAG, "OCUnlinkDevices : Can not find linked devices");
301         res = OC_STACK_INVALID_PARAM; // Input devices are not linked, No request is made
302         goto error;
303     }
304
305     // Check the linked devices contains the second device. If yes send credential DELETE request.
306     OCUuidList_t* curDev = idList;
307     while (NULL != curDev)
308     {
309         if (memcmp(pTargetDev2->doxm->deviceID.id, curDev->dev.id, sizeof(curDev->dev.id)) == 0)
310         {
311             res = SRPUnlinkDevices(ctx, pTargetDev1, pTargetDev2, resultCallback);
312             if (OC_STACK_OK != res)
313             {
314                 OIC_LOG(ERROR, TAG, "OCUnlinkDevices : Failed to unlink devices.");
315             }
316             goto error;
317         }
318         curDev = curDev->next;
319     }
320     OIC_LOG(DEBUG, TAG, "No matched pair found from provisioning database");
321     res = OC_STACK_INVALID_PARAM; // Input devices are not linked, No request is made
322
323 error:
324     OIC_LOG(INFO, TAG, "OUT OCUnlinkDevices");
325
326     PDMDestoryOicUuidLinkList(idList);
327     return res;
328 }
329
330 static OCStackResult RemoveDeviceInfoFromLocal(const OCProvisionDev_t* pTargetDev)
331 {
332     // Remove credential of revoked device from SVR database
333     OCStackResult res = OC_STACK_ERROR;
334     const OicSecCred_t *cred = NULL;
335     cred = GetCredResourceData(&pTargetDev->doxm->deviceID);
336     if (cred == NULL)
337     {
338         OIC_LOG(ERROR, TAG, "RemoveDeviceInfoFromLocal : Failed to get credential of remove device.");
339         goto error;
340     }
341
342     res = RemoveCredential(&cred->subject);
343     if (res != OC_STACK_RESOURCE_DELETED)
344     {
345         OIC_LOG(ERROR, TAG, "RemoveDeviceInfoFromLocal : Failed to remove credential.");
346         goto error;
347     }
348
349     /**
350      * Change the device status as stale status.
351      * If all request are successed, this device information will be deleted.
352      */
353     res = PDMSetDeviceStale(&pTargetDev->doxm->deviceID);
354     if (res != OC_STACK_OK)
355     {
356         OIC_LOG(ERROR, TAG, "OCRemoveDevice : Failed to set device status as stale");
357         goto error;
358     }
359
360     // TODO: We need to add new mechanism to clean up the stale state of the device.
361
362     //Close the DTLS session of the removed device.
363     CAEndpoint_t* endpoint = (CAEndpoint_t *)&pTargetDev->endpoint;
364     endpoint->port = pTargetDev->securePort;
365     CAResult_t caResult = CACloseDtlsSession(endpoint);
366     if(CA_STATUS_OK != caResult)
367     {
368         OIC_LOG_V(WARNING, TAG, "OCRemoveDevice : Failed to close DTLS session : %d", caResult);
369     }
370
371 error:
372     return res;
373 }
374
375 /*
376 * Function to device revocation
377 * This function will remove credential of target device from all devices in subnet.
378 *
379 * @param[in] ctx Application context would be returned in result callback
380 * @param[in] waitTimeForOwnedDeviceDiscovery Maximum wait time for owned device discovery.(seconds)
381 * @param[in] pTargetDev Device information to be revoked.
382 * @param[in] resultCallback callback provided by API user, callback will be called when
383 *            credential revocation is finished.
384  * @return  OC_STACK_OK in case of success and other value otherwise.
385 */
386 OCStackResult OCRemoveDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDiscovery,
387                             const OCProvisionDev_t* pTargetDev,
388                             OCProvisionResultCB resultCallback)
389 {
390     OIC_LOG(INFO, TAG, "IN OCRemoveDevice");
391     OCStackResult res = OC_STACK_ERROR;
392     if (!pTargetDev || 0 == waitTimeForOwnedDeviceDiscovery)
393     {
394         OIC_LOG(INFO, TAG, "OCRemoveDevice : Invalied parameters");
395         return OC_STACK_INVALID_PARAM;
396     }
397     if (!resultCallback)
398     {
399         OIC_LOG(INFO, TAG, "OCRemoveDevice : NULL Callback");
400         return OC_STACK_INVALID_CALLBACK;
401     }
402
403     // Send DELETE requests to linked devices
404     OCStackResult resReq = OC_STACK_ERROR; // Check that we have to wait callback or not.
405     resReq = SRPRemoveDevice(ctx, waitTimeForOwnedDeviceDiscovery, pTargetDev, resultCallback);
406     if (OC_STACK_OK != resReq)
407     {
408         if (OC_STACK_CONTINUE == resReq)
409         {
410             OIC_LOG(DEBUG, TAG, "OCRemoveDevice : Revoked device has no linked device except PT.");
411         }
412         else
413         {
414             OIC_LOG(ERROR, TAG, "OCRemoveDevice : Failed to invoke SRPRemoveDevice");
415             res = resReq;
416             goto error;
417         }
418     }
419
420     res = RemoveDeviceInfoFromLocal(pTargetDev);
421     if(OC_STACK_OK != res)
422     {
423         OIC_LOG(ERROR, TAG, "Filed to remove the device information from local.");
424         goto error;
425     }
426
427     if(OC_STACK_CONTINUE == resReq)
428     {
429         /**
430           * If there is no linked device, PM does not send any request.
431           * So we should directly invoke the result callback to inform the result of OCRemoveDevice.
432           */
433         if(resultCallback)
434         {
435             resultCallback(ctx, 0, NULL, false);
436         }
437         res = OC_STACK_OK;
438     }
439
440 error:
441     OIC_LOG(INFO, TAG, "OUT OCRemoveDevice");
442     return res;
443 }
444
445 /*
446 * Function to device revocation
447 * This function will remove credential of target device from all devices in subnet.
448 *
449 * @param[in] ctx Application context would be returned in result callback
450 * @param[in] waitTimeForOwnedDeviceDiscovery Maximum wait time for owned device discovery.(seconds)
451 * @param[in] pTargetDev Device information to be revoked.
452 * @param[in] resultCallback callback provided by API user, callback will be called when
453 *            credential revocation is finished.
454  * @return  OC_STACK_OK in case of success and other value otherwise.
455 */
456 OCStackResult OCRemoveDeviceWithUuid(void* ctx, unsigned short waitTimeForOwnedDeviceDiscovery,
457                             const OicUuid_t* pTargetUuid,
458                             OCProvisionResultCB resultCallback)
459 {
460     OIC_LOG(INFO, TAG, "IN OCRemoveDeviceWithUuid");
461
462     OCStackResult res = OC_STACK_ERROR;
463     OCProvisionDev_t* pTargetDev = NULL;
464     bool discoverdFlag = false;
465
466     if (!pTargetUuid || 0 == waitTimeForOwnedDeviceDiscovery)
467     {
468         OIC_LOG(INFO, TAG, "OCRemoveDeviceWithUuid : Invalied parameters");
469         return OC_STACK_INVALID_PARAM;
470     }
471     if (!resultCallback)
472     {
473         OIC_LOG(INFO, TAG, "OCRemoveDeviceWithUuid : NULL Callback");
474         return OC_STACK_INVALID_CALLBACK;
475     }
476
477     char* strUuid = NULL;
478     if(OC_STACK_OK != ConvertUuidToStr(pTargetUuid, &strUuid))
479     {
480         OIC_LOG(WARNING, TAG, "Failed to covert UUID to String.");
481         goto error;
482     }
483
484     OCProvisionDev_t* pOwnedDevList = NULL;
485     //2. Find owned device from the network
486     res = PMDeviceDiscovery(waitTimeForOwnedDeviceDiscovery, true, &pOwnedDevList);
487     if (OC_STACK_OK != res)
488     {
489         OIC_LOG(ERROR, TAG, "OCRemoveDeviceWithUuid : Failed to PMDeviceDiscovery");
490         goto error;
491     }
492
493     LL_FOREACH(pOwnedDevList, pTargetDev)
494     {
495         if(memcmp(&pTargetDev->doxm->deviceID.id, pTargetUuid->id, sizeof(pTargetUuid->id)) == 0)
496         {
497             break;
498         }
499     }
500
501     if(NULL == pTargetDev)
502     {
503         OIC_LOG_V(WARNING, TAG, "Can not find [%s] on the network.", strUuid);
504         OIC_LOG(WARNING, TAG, "Device information will be deleted from local and other devices.");
505
506         pTargetDev = (OCProvisionDev_t*)OICCalloc(1, sizeof(OCProvisionDev_t));
507         if(NULL == pTargetDev)
508         {
509             OIC_LOG(ERROR, TAG, "Failed to memory allocation.");
510             goto error;
511         }
512
513         pTargetDev->doxm = (OicSecDoxm_t*)OICCalloc(1, sizeof(OicSecDoxm_t));
514         if(NULL == pTargetDev->doxm)
515         {
516             OIC_LOG(ERROR, TAG, "Failed to memory allocation.");
517             goto error;
518         }
519
520         //in case of can't find target device, the device id required only.
521         memcpy(pTargetDev->doxm->deviceID.id, pTargetUuid->id, sizeof(pTargetUuid->id));
522     }
523     else
524     {
525         discoverdFlag = true;
526         OIC_LOG_V(INFO, TAG, "[%s] is dectected on the network.", strUuid);
527     }
528
529     OIC_LOG_V(INFO, TAG, "Trying [%s] revocation.", strUuid);
530
531     // Send DELETE requests to linked devices
532     OCStackResult resReq = OC_STACK_ERROR; // Check that we have to wait callback or not.
533     resReq = SRPRemoveDeviceWithoutDiscovery(ctx, pOwnedDevList, pTargetDev, resultCallback);
534     if (OC_STACK_OK != resReq)
535     {
536         if (OC_STACK_CONTINUE == resReq)
537         {
538             OIC_LOG(DEBUG, TAG, "OCRemoveDeviceWithUuid : Revoked device has no linked device except PT.");
539         }
540         else
541         {
542             OIC_LOG(ERROR, TAG, "OCRemoveDeviceWithUuid : Failed to invoke SRPRemoveDevice");
543             res = resReq;
544             goto error;
545         }
546     }
547
548     res = RemoveDeviceInfoFromLocal(pTargetDev);
549     if(OC_STACK_OK != res)
550     {
551         OIC_LOG(ERROR, TAG, "OCRemoveDeviceWithUuid : Filed to remove the device information from local.");
552         goto error;
553     }
554
555     if(OC_STACK_CONTINUE == resReq)
556     {
557         /**
558           * If there is no linked device, PM does not send any request.
559           * So we should directly invoke the result callback to inform the result of OCRemoveDevice.
560           */
561         if(resultCallback)
562         {
563             resultCallback(ctx, 0, NULL, false);
564         }
565         res = OC_STACK_OK;
566     }
567
568 error:
569     OICFree(strUuid);
570     PMDeleteDeviceList(pOwnedDevList);
571     if(pTargetDev && false == discoverdFlag)
572     {
573         OICFree(pTargetDev->doxm);
574         OICFree(pTargetDev);
575     }
576     OIC_LOG(INFO, TAG, "OUT OCRemoveDeviceWithUuid");
577     return res;
578 }
579
580 /*
581  * Function to reset the target device.
582  * This function will remove credential and ACL of target device from all devices in subnet.
583  *
584  * @param[in] ctx Application context would be returned in result callback
585  * @param[in] waitTimeForOwnedDeviceDiscovery Maximum wait time for owned device discovery.(seconds)
586  * @param[in] pTargetDev Device information to be revoked.
587  * @param[in] resultCallback callback provided by API user, callback will be called when
588  *            credential revocation is finished.
589  * @return  OC_STACK_OK in case of success and other value otherwise.
590  */
591 OCStackResult OCResetDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDiscovery,
592                             const OCProvisionDev_t* pTargetDev,
593                             OCProvisionResultCB resultCallback)
594 {
595     OIC_LOG(INFO, TAG, "IN OCResetDevice");
596     OCStackResult res = OC_STACK_ERROR;
597     if (!pTargetDev || 0 == waitTimeForOwnedDeviceDiscovery)
598     {
599         OIC_LOG(INFO, TAG, "OCResetDevice : Invalid parameters");
600         return OC_STACK_INVALID_PARAM;
601     }
602     if (!resultCallback)
603     {
604         OIC_LOG(INFO, TAG, "OCResetDevice : NULL Callback");
605         return OC_STACK_INVALID_CALLBACK;
606     }
607
608     // Send DELETE requests to linked devices
609     res = SRPSyncDevice(ctx, waitTimeForOwnedDeviceDiscovery, pTargetDev, resultCallback);
610     if (OC_STACK_CONTINUE == res)
611     {
612         OIC_LOG(DEBUG, TAG, "OCResetDevice : Target device has no linked device except PT.");
613         if(resultCallback)
614         {
615             resultCallback(ctx, 0, NULL, false);
616         }
617         SRPResetDevice(pTargetDev, resultCallback);
618         res = OC_STACK_OK;
619     }
620     else if(OC_STACK_OK != res)
621     {
622         OIC_LOG(ERROR, TAG, "OCResetDevice : Failed to invoke SRPSyncDevice");
623     }
624     OIC_LOG(INFO, TAG, "OUT OCResetDevice");
625     return res;
626 }
627
628 /**
629  * Internal Function to update result in link result array.
630  */
631 static void UpdateLinkResults(Linkdata_t *link, int device, OCStackResult stackresult)
632 {
633
634     OIC_LOG_V(INFO,TAG,"value of link->currentCountResults is %d",link->currentCountResults);
635     if (1 == device)
636     {
637         memcpy(link->resArr[(link->currentCountResults)].deviceId.id, link->pDev1->doxm->deviceID.id,UUID_LENGTH);
638     }
639     else
640     {
641         memcpy(link->resArr[(link->currentCountResults)].deviceId.id, link->pDev2->doxm->deviceID.id,UUID_LENGTH);
642     }
643     link->resArr[(link->currentCountResults)].res = stackresult;
644     ++(link->currentCountResults);
645
646 }
647
648 /**
649  * Callback to handle ACL provisioning for device 2.
650  */
651 static void AclProv2CB(void* ctx, int nOfRes, OCProvisionResult_t *arr, bool hasError)
652 {
653
654     if (NULL == ctx)
655     {
656         OIC_LOG(ERROR,TAG,"Context is Null in ACLProv 2");
657         return;
658     }
659     (void)nOfRes;
660     Linkdata_t *link = (Linkdata_t*)ctx;
661     OCProvisionResultCB resultCallback = link->resultCallback;
662
663
664     if (hasError)
665     {
666         UpdateLinkResults(link, 2,arr[0].res);
667         OIC_LOG(ERROR,TAG,"Error occured while ACL provisioning device 1");
668         ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
669                                                 link->resArr,
670                                                 true);
671         OICFree(link->resArr);
672         OICFree(link) ;
673         return;
674     }
675     UpdateLinkResults(link, 2, arr[0].res);
676    ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
677                                            link->resArr,
678                                            false);
679     OICFree(link->resArr);
680     OICFree(link);
681     return;
682 }
683
684 /**
685  * Callback to handle ACL provisioning for device 1
686  */
687 static void AclProv1CB(void* ctx, int nOfRes, OCProvisionResult_t *arr, bool hasError)
688 {
689
690     if (NULL == ctx)
691     {
692         OIC_LOG(ERROR,TAG,"Context is Null in ACLProv1");
693         return;
694     }
695     (void)nOfRes;
696     Linkdata_t *link = (Linkdata_t*)ctx;
697     OCProvisionResultCB resultCallback = link->resultCallback;
698
699     if (hasError)
700     {
701         OIC_LOG(ERROR,TAG,"Error occured while ACL provisioning device 1");
702         UpdateLinkResults(link, 1, arr[0].res);
703         ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
704                                                 link->resArr,
705                                                 true);
706         OICFree(link->resArr);
707         OICFree(link);
708         return;
709     }
710     UpdateLinkResults(link, 1, arr[0].res);
711     if (NULL != link->pDev2Acl)
712     {
713         OCStackResult res =  SRPProvisionACL(ctx, link->pDev2, link->pDev2Acl, &AclProv2CB);
714         if (OC_STACK_OK!=res)
715         {
716              UpdateLinkResults(link, 2, res);
717              ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
718                                                      link->resArr,
719                                                      true);
720
721         }
722     }
723     else
724     {
725         ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
726                                                 link->resArr,
727                                                 false);
728         OICFree(link->resArr);
729         OICFree(link);
730     }
731
732     return;
733 }
734
735 /**
736  * Callback to handle credential provisioning.
737  */
738 static void ProvisionCredsCB(void* ctx, int nOfRes, OCProvisionResult_t *arr, bool hasError)
739 {
740     if (NULL == ctx)
741     {
742         OIC_LOG(ERROR,TAG,"Error occured while credential provisioning");
743         return;
744     }
745     Linkdata_t *link = (Linkdata_t*)ctx;
746     OCProvisionResultCB resultCallback = link->resultCallback;
747     OIC_LOG_V(INFO, TAG, "has error returned %d",hasError);
748     UpdateLinkResults(link, 1, arr[0].res);
749     UpdateLinkResults(link, 2, arr[1].res);
750     if (hasError)
751     {
752         OIC_LOG(ERROR,TAG,"Error occured while credential provisioning");
753         ((OCProvisionResultCB)(resultCallback))(link->ctx, nOfRes,
754                                                 link->resArr,
755                                                 true);
756          OICFree(link->resArr);
757          OICFree(link);
758          return;
759     }
760     if (NULL != link->pDev1Acl)
761     {
762
763         OCStackResult res =  SRPProvisionACL(ctx, link->pDev1, link->pDev1Acl, &AclProv1CB);
764         if (OC_STACK_OK!=res)
765         {
766              OIC_LOG(ERROR, TAG, "Error while provisioning ACL for device 1");
767              UpdateLinkResults(link, 1, res);
768              ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
769                                                      link->resArr,
770                                                      true);
771               OICFree(link->resArr);
772               OICFree(link);
773         }
774     }
775     else if (NULL!=link->pDev2Acl)
776     {
777         OIC_LOG(ERROR, TAG, "ACL for device 1 is NULL");
778         OCStackResult res =  SRPProvisionACL(ctx, link->pDev2, link->pDev2Acl, &AclProv2CB);
779         if (OC_STACK_OK!=res)
780         {
781              OIC_LOG(ERROR, TAG, "Error while provisioning ACL for device 2");
782               UpdateLinkResults(link, 2, res);
783              ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
784                                                      link->resArr,
785                                                      true);
786               OICFree(link->resArr);
787               OICFree(link);
788         }
789     }
790     else
791     {
792         OIC_LOG(INFO, TAG, "ACLs of both devices are NULL");
793         ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
794                                                 link->resArr,
795                                                 false);
796         OICFree(link->resArr);
797         OICFree(link);
798     }
799     return;
800 }
801 /**
802  * function to provision credentials between two devices and ACLs for the devices who act as a server.
803  *
804  * @param[in] ctx Application context would be returned in result callback.
805  * @param[in] type Type of credentials to be provisioned to the device.
806  * @param[in] pDev1 Pointer to OCProvisionDev_t instance,respresenting resource to be provsioned.
807  * @param[in] acl ACL for device 1. If this is not required set NULL.
808  * @param[in] pDev2 Pointer to OCProvisionDev_t instance,respresenting resource to be provsioned.
809  * @param[in] acl ACL for device 2. If this is not required set NULL.
810  * @param[in] resultCallback callback provided by API user, callback will be called when
811  *            provisioning request recieves a response from first resource server.
812  * @return  OC_STACK_OK in case of success and other value otherwise.
813  */
814 OCStackResult OCProvisionPairwiseDevices(void* ctx, OicSecCredType_t type, size_t keySize,
815                                          const OCProvisionDev_t *pDev1, OicSecAcl_t *pDev1Acl,
816                                          const OCProvisionDev_t *pDev2, OicSecAcl_t *pDev2Acl,
817                                          OCProvisionResultCB resultCallback)
818 {
819
820     if (!pDev1 || !pDev2 || !pDev1->doxm || !pDev2->doxm)
821     {
822         OIC_LOG(ERROR, TAG, "OCProvisionPairwiseDevices : Invalid parameters");
823         return OC_STACK_INVALID_PARAM;
824     }
825     if (!resultCallback)
826     {
827         OIC_LOG(INFO, TAG, "OCProvisionPairwiseDevices : NULL Callback");
828         return OC_STACK_INVALID_CALLBACK;
829     }
830     if (!(keySize == OWNER_PSK_LENGTH_128 || keySize == OWNER_PSK_LENGTH_256))
831     {
832         OIC_LOG(INFO, TAG, "OCProvisionPairwiseDevices : Invalid key size");
833         return OC_STACK_INVALID_PARAM;
834     }
835     if (0 == memcmp(&pDev1->doxm->deviceID, &pDev2->doxm->deviceID, sizeof(OicUuid_t)))
836     {
837         OIC_LOG(INFO, TAG, "OCProvisionPairwiseDevices : Same device ID");
838         return OC_STACK_INVALID_PARAM;
839     }
840
841     OIC_LOG(DEBUG, TAG, "Checking link in DB");
842     bool linkExists = true;
843     OCStackResult res = PDMIsLinkExists(&pDev1->doxm->deviceID, &pDev2->doxm->deviceID, &linkExists);
844     if(res != OC_STACK_OK)
845     {
846         OIC_LOG(ERROR, TAG, "Internal Error Occured");
847         return res;
848     }
849     if (linkExists)
850     {
851         OIC_LOG(ERROR, TAG, "Link already exists");
852         return OC_STACK_INVALID_PARAM;
853     }
854
855     int noOfResults = 2; // Initial Value
856     if (NULL != pDev1Acl)
857     {
858         ++noOfResults;
859     }
860     if (NULL != pDev2Acl)
861     {
862        ++noOfResults;
863     }
864     Linkdata_t *link = (Linkdata_t*) OICMalloc(sizeof(Linkdata_t));
865     if (!link)
866     {
867         OIC_LOG(ERROR, TAG, "Failed to memory allocation");
868         return OC_STACK_NO_MEMORY;
869     }
870     OIC_LOG_V(INFO,TAG, "Maximum no od results %d",noOfResults);
871
872     link->pDev1 = pDev1;
873     link->pDev1Acl = pDev1Acl;
874     link->pDev2 = pDev2;
875     link->pDev2Acl = pDev2Acl;
876     link->ctx = ctx;
877     // 1 call for each device for credential provisioning. implict call by SRPProvisioning credential
878     // 1 call for ACL provisioning for device 1 and 1 call for ACL provisioning for device 2.
879     link->numOfResults = noOfResults;
880     link->resultCallback = resultCallback;
881     link->currentCountResults = 0;
882     link->resArr = (OCProvisionResult_t*) OICMalloc(sizeof(OCProvisionResult_t)*noOfResults);
883     res = SRPProvisionCredentials(link, type, keySize,
884                                      pDev1, pDev2, &ProvisionCredsCB);
885     if (res != OC_STACK_OK)
886     {
887         OICFree(link->resArr);
888         OICFree(link);
889     }
890     return res;
891
892 }
893
894 OCStackResult OCGetDevInfoFromNetwork(unsigned short waittime,
895                                        OCProvisionDev_t** pOwnedDevList,
896                                        OCProvisionDev_t** pUnownedDevList)
897 {
898     //TODO will be replaced by more efficient logic
899     if (pOwnedDevList == NULL || *pOwnedDevList != NULL || pUnownedDevList == NULL
900          || *pUnownedDevList != NULL || 0 == waittime)
901     {
902         return OC_STACK_INVALID_PARAM;
903     }
904
905     // Code for unowned discovery
906     OCProvisionDev_t *unownedDevice = NULL;
907     OCStackResult res =  OCDiscoverUnownedDevices(waittime/2, &unownedDevice);
908     if (OC_STACK_OK != res)
909     {
910         OIC_LOG(ERROR,TAG, "Error in unowned discovery");
911         return res;
912     }
913
914     // Code for owned discovery
915     OCProvisionDev_t *ownedDevice = NULL;
916     res =  OCDiscoverOwnedDevices(waittime/2, &ownedDevice);
917     if (OC_STACK_OK != res)
918     {
919         OIC_LOG(ERROR,TAG, "Error in owned discovery");
920         PMDeleteDeviceList(unownedDevice);
921         return res;
922     }
923
924     // Code to get list of all the owned devices.
925     OCUuidList_t *uuidList = NULL;
926     size_t numOfDevices = 0;
927     res =  PDMGetOwnedDevices(&uuidList, &numOfDevices);
928     if (OC_STACK_OK != res)
929     {
930         OIC_LOG(ERROR, TAG, "Error while getting info from DB");
931         PMDeleteDeviceList(unownedDevice);
932         PMDeleteDeviceList(ownedDevice);
933         return res;
934     }
935
936     // Code to compare devices in owned list and deviceid from DB.
937     OCProvisionDev_t* pCurDev = ownedDevice;
938     size_t deleteCnt = 0;
939     while (pCurDev)
940     {
941         if(true == PMDeleteFromUUIDList(&uuidList, &pCurDev->doxm->deviceID))
942         {
943             deleteCnt++;
944         }
945         pCurDev = pCurDev->next;
946     }
947     // If there is no remaind device in uuidList, we have to assign NULL to prevent free.
948     if (deleteCnt == numOfDevices)
949     {
950         uuidList = NULL;
951     }
952     // Code to add information of the devices which are currently off in owned list.
953     OCUuidList_t *powerOffDeviceList = uuidList;
954     while (powerOffDeviceList)
955     {
956         OCProvisionDev_t *ptr = (OCProvisionDev_t *)OICCalloc(1, sizeof (OCProvisionDev_t));
957         if (NULL == ptr)
958         {
959             OIC_LOG(ERROR,TAG,"Fail to allocate memory");
960             PMDeleteDeviceList(unownedDevice);
961             PMDeleteDeviceList(ownedDevice);
962             OCDeleteUuidList(uuidList);
963             return OC_STACK_NO_MEMORY;
964         }
965
966         ptr->doxm = (OicSecDoxm_t*)OICCalloc(1, sizeof(OicSecDoxm_t));
967         if (NULL == ptr->doxm)
968         {
969             OIC_LOG(ERROR,TAG,"Fail to allocate memory");
970             PMDeleteDeviceList(unownedDevice);
971             PMDeleteDeviceList(ownedDevice);
972             OCDeleteUuidList(uuidList);
973             OICFree(ptr);
974             return OC_STACK_NO_MEMORY;
975         }
976
977         memcpy(ptr->doxm->deviceID.id, powerOffDeviceList->dev.id, sizeof(ptr->doxm->deviceID.id));
978
979         ptr->devStatus = DEV_STATUS_OFF;
980         LL_PREPEND(ownedDevice, ptr);
981         powerOffDeviceList = powerOffDeviceList->next;
982
983     }
984     OCDeleteUuidList(uuidList);
985     *pOwnedDevList = ownedDevice;
986     *pUnownedDevList = unownedDevice;
987     return OC_STACK_OK;
988 }
989
990 OCStackResult OCGetLinkedStatus(const OicUuid_t* uuidOfDevice, OCUuidList_t** uuidList,
991                                  size_t* numOfDevices)
992 {
993     return PDMGetLinkedDevices(uuidOfDevice, uuidList, numOfDevices);
994 }
995
996 void OCDeleteUuidList(OCUuidList_t* pList)
997 {
998     PDMDestoryOicUuidLinkList(pList);
999 }
1000
1001 /**
1002  * This function deletes ACL data.
1003  *
1004  * @param pAcl Pointer to OicSecAcl_t structure.
1005  */
1006 void OCDeleteACLList(OicSecAcl_t* pAcl)
1007 {
1008     DeleteACLList(pAcl);
1009 }
1010
1011 /**
1012  * This function deletes PDACL data.
1013  *
1014  * @param pPdAcl Pointer to OicSecPdAcl_t structure.
1015  */
1016 void OCDeletePdAclList(OicSecPdAcl_t* pPdAcl)
1017 {
1018     FreePdAclList(pPdAcl);
1019 }
1020
1021
1022 #if defined(__WITH_X509__) || defined(__WITH_TLS__)
1023 /**
1024  * this function sends CRL information to resource.
1025  *
1026  * @param[in] ctx Application context would be returned in result callback.
1027  * @param[in] selectedDeviceInfo Selected target device.
1028  * @param[in] crl CRL to provision.
1029  * @param[in] resultCallback callback provided by API user, callback will be called when provisioning
1030               request recieves a response from resource server.
1031  * @return  OC_STACK_OK in case of success and other value otherwise.
1032  */
1033 OCStackResult OCProvisionCRL(void* ctx, const OCProvisionDev_t *selectedDeviceInfo, OicSecCrl_t *crl,
1034                              OCProvisionResultCB resultCallback)
1035 {
1036     return SRPProvisionCRL(ctx, selectedDeviceInfo, crl, resultCallback);
1037 }
1038
1039 /**
1040  * function to provision Trust certificate chain to devices.
1041  *
1042  * @param[in] ctx Application context would be returned in result callback.
1043  * @param[in] type Type of credentials to be provisioned to the device.
1044  * @param[in] credId CredId of trust certificate chain to be provisioned to the device.
1045  * @param[in] selectedDeviceInfo Pointer to OCProvisionDev_t instance,respresenting resource to be provsioned.
1046  * @param[in] resultCallback callback provided by API user, callback will be called when
1047  *            provisioning request recieves a response from first resource server.
1048  * @return  OC_STACK_OK in case of success and other value otherwise.
1049  */
1050 OCStackResult OCProvisionTrustCertChain(void *ctx, OicSecCredType_t type, uint16_t credId,
1051                                       const OCProvisionDev_t *selectedDeviceInfo,
1052                                       OCProvisionResultCB resultCallback)
1053 {
1054     return SRPProvisionTrustCertChain(ctx, type, credId,
1055                                       selectedDeviceInfo, resultCallback);
1056 }
1057
1058 /**
1059  * function to save Trust certificate chain into Cred of SVR.
1060  *
1061  * @param[in] trustCertChain Trust certificate chain to be saved in Cred of SVR.
1062  * @param[in] chainSize Size of trust certificate chain to be saved in Cred of SVR
1063  * @param[in] encodingType Encoding type of trust certificate chain to be saved in Cred of SVR
1064  * @param[out] credId CredId of saved trust certificate chain in Cred of SVR.
1065  * @return  OC_STACK_OK in case of success and other value otherwise.
1066  */
1067 OCStackResult OCSaveTrustCertChain(uint8_t *trustCertChain, size_t chainSize,
1068                                     OicEncodingType_t encodingType, uint16_t *credId)
1069 {
1070     return SRPSaveTrustCertChain(trustCertChain, chainSize, encodingType, credId);
1071 }
1072
1073 #endif // __WITH_X509__ || __WITH_TLS__
1074