4a463ca99628fb4a6a1de789d0389ebc632c1927
[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
32 #define TAG "OCPMAPI"
33
34 typedef struct Linkdata Linkdata_t;
35 struct Linkdata
36 {
37     void *ctx;
38     const OCProvisionDev_t *pDev1;
39     OicSecAcl_t *pDev1Acl;
40     const OCProvisionDev_t *pDev2;
41     OicSecAcl_t *pDev2Acl;
42     OCProvisionResult_t *resArr;
43     int numOfResults;
44     int currentCountResults;
45     OCProvisionResultCB resultCallback;
46
47 };
48
49 /**
50  * The function is responsible for initializaton of the provisioning manager. It will load
51  * provisioning database which have owned device's list and their linked status.
52  * TODO: In addition, if there is a device(s) which has not up-to-date credentials, this function will
53  * automatically try to update the deivce(s).
54  *
55  * @param[in] dbPath file path of the sqlite3 db
56  *
57  * @return OC_STACK_OK in case of success and other value otherwise.
58  */
59 OCStackResult OCInitPM(const char* dbPath)
60 {
61     return PDMInit(dbPath);
62 }
63
64 /**
65  * The function is responsible for discovery of device is current subnet. It will list
66  * all the device in subnet which are not yet owned. Please call OCInit with OC_CLIENT_SERVER as
67  * OCMode.
68  *
69  * @param[in] timeout Timeout in seconds, value till which function will listen to responses from
70  *                    client before returning the list of devices.
71  * @param[out] ppList List of candidate devices to be provisioned
72  * @return OTM_SUCCESS in case of success and other value otherwise.
73  */
74 OCStackResult OCDiscoverUnownedDevices(unsigned short timeout, OCProvisionDev_t **ppList)
75 {
76     if( ppList == NULL || *ppList != NULL)
77     {
78         return OC_STACK_INVALID_PARAM;
79     }
80
81     return PMDeviceDiscovery(timeout, false, ppList);
82 }
83
84 /**
85  * The function is responsible for discovery of owned device is current subnet. It will list
86  * all the device in subnet which are owned by calling provisioning client.
87  *
88  * @param[in] timeout Timeout in seconds, value till which function will listen to responses from
89  *                    client before returning the list of devices.
90  * @param[out] ppList List of device owned by provisioning tool.
91  * @return OTM_SUCCESS in case of success and other value otherwise.
92  */
93 OCStackResult OCDiscoverOwnedDevices(unsigned short timeout, OCProvisionDev_t **ppList)
94 {
95     if( ppList == NULL || *ppList != NULL)
96     {
97         return OC_STACK_INVALID_PARAM;
98     }
99
100     return PMDeviceDiscovery(timeout, true, ppList);
101 }
102
103 /**
104  * API to register for particular OxM.
105  *
106  * @param[in] Ownership transfer method.
107  * @param[in] Implementation of callback functions for owership transfer.
108  * @return  OC_STACK_OK in case of success and other value otherwise.
109  */
110 OCStackResult OCSetOwnerTransferCallbackData(OicSecOxm_t oxm, OTMCallbackData_t* callbackData)
111 {
112     if(NULL == callbackData)
113     {
114         return OC_STACK_INVALID_PARAM;
115     }
116
117     return OTMSetOwnershipTransferCallbackData(oxm, callbackData);
118 }
119
120 OCStackResult OCDoOwnershipTransfer(void* ctx,
121                                       OCProvisionDev_t *targetDevices,
122                                       OCProvisionResultCB resultCallback)
123 {
124     if( NULL == targetDevices )
125     {
126         return OC_STACK_INVALID_PARAM;
127     }
128
129     return OTMDoOwnershipTransfer(ctx, targetDevices, resultCallback);
130 }
131
132 /**
133  * This function deletes memory allocated to linked list created by OCDiscover_XXX_Devices API.
134  *
135  * @param[in] pList Pointer to OCProvisionDev_t which should be deleted.
136  */
137 void OCDeleteDiscoveredDevices(OCProvisionDev_t *pList)
138 {
139     PMDeleteDeviceList(pList);
140 }
141
142 /**
143  * this function sends ACL information to resource.
144  *
145  * @param[in] ctx Application context would be returned in result callback.
146  * @param[in] selectedDeviceInfo Selected target device.
147  * @param[in] acl ACL to provision.
148  * @param[in] resultCallback callback provided by API user, callback will be called when provisioning
149               request recieves a response from resource server.
150  * @return  OC_STACK_OK in case of success and other value otherwise.
151  */
152 OCStackResult OCProvisionACL(void* ctx, const OCProvisionDev_t *selectedDeviceInfo, OicSecAcl_t *acl,
153                              OCProvisionResultCB resultCallback)
154 {
155     return SRPProvisionACL(ctx, selectedDeviceInfo, acl, resultCallback);
156 }
157
158 /**
159  * function to provision credential to devices.
160  *
161  * @param[in] ctx Application context would be returned in result callback.
162  * @param[in] type Type of credentials to be provisioned to the device.
163  * @param[in] pDev1 Pointer to OCProvisionDev_t instance,respresenting resource to be provsioned.
164    @param[in] pDev2 Pointer to OCProvisionDev_t instance,respresenting resource to be provsioned.
165  * @param[in] resultCallback callback provided by API user, callback will be called when
166  *            provisioning request recieves a response from first resource server.
167  * @return  OC_STACK_OK in case of success and other value otherwise.
168  */
169 OCStackResult OCProvisionCredentials(void *ctx, OicSecCredType_t type, size_t keySize,
170                                       const OCProvisionDev_t *pDev1,
171                                       const OCProvisionDev_t *pDev2,
172                                       OCProvisionResultCB resultCallback)
173 {
174     return SRPProvisionCredentials(ctx, type, keySize,
175                                       pDev1, pDev2, resultCallback);
176
177 }
178
179 /*
180 * Function to unlink devices.
181 * This function will remove the credential & relationship between the two devices.
182 *
183 * @param[in] ctx Application context would be returned in result callback
184 * @param[in] pTargetDev1 first device information to be unlinked.
185 * @param[in] pTargetDev2 second device information to be unlinked.
186 * @param[in] resultCallback callback provided by API user, callback will be called when
187 *            device unlink is finished.
188  * @return  OC_STACK_OK in case of success and other value otherwise.
189 */
190 OCStackResult OCUnlinkDevices(void* ctx,
191                               const OCProvisionDev_t* pTargetDev1,
192                               const OCProvisionDev_t* pTargetDev2,
193                               OCProvisionResultCB resultCallback)
194 {
195     OC_LOG(INFO, TAG, "IN OCUnlinkDevices");
196     OCUuidList_t* idList = NULL;
197     size_t numOfDev = 0;
198
199     if (!pTargetDev1 || !pTargetDev2 || !resultCallback)
200     {
201         OC_LOG(ERROR, TAG, "OCUnlinkDevices : NULL parameters");
202         return OC_STACK_INVALID_PARAM;
203     }
204
205     // Get linked devices with the first device.
206     OCStackResult res = PDMGetLinkedDevices(&(pTargetDev1->doxm->deviceID), &idList, &numOfDev);
207     if (OC_STACK_OK != res)
208     {
209         OC_LOG(ERROR, TAG, "OCUnlinkDevices : PDMgetOwnedDevices failed");
210         goto error;
211     }
212     if (1 > numOfDev)
213     {
214         OC_LOG(DEBUG, TAG, "OCUnlinkDevices : Can not find linked devices");
215         res = OC_STACK_INVALID_PARAM; // Input devices are not linked, No request is made
216         goto error;
217     }
218
219     // Check the linked devices contains the second device. If yes send credential DELETE request.
220     OCUuidList_t* curDev = idList;
221     while (NULL != curDev)
222     {
223         if (memcmp(pTargetDev2->doxm->deviceID.id, curDev->dev.id, sizeof(curDev->dev.id)) == 0)
224         {
225             res = SRPUnlinkDevices(ctx, pTargetDev1, pTargetDev2, resultCallback);
226             if (OC_STACK_OK != res)
227             {
228                 OC_LOG(ERROR, TAG, "OCUnlinkDevices : Failed to unlink devices.");
229             }
230             goto error;
231         }
232         curDev = curDev->next;
233     }
234     OC_LOG(DEBUG, TAG, "No matched pair found from provisioning database");
235     res = OC_STACK_INVALID_PARAM; // Input devices are not linked, No request is made
236
237 error:
238     OC_LOG(INFO, TAG, "OUT OCUnlinkDevices");
239
240     PDMDestoryOicUuidLinkList(idList);
241     return res;
242 }
243
244 /*
245 * Function to device revocation
246 * This function will remove credential of target device from all devices in subnet.
247 *
248 * @param[in] ctx Application context would be returned in result callback
249 * @param[in] waitTimeForOwnedDeviceDiscovery Maximum wait time for owned device discovery.(seconds)
250 * @param[in] pTargetDev Device information to be revoked.
251 * @param[in] resultCallback callback provided by API user, callback will be called when
252 *            credential revocation is finished.
253  * @return  OC_STACK_OK in case of success and other value otherwise.
254 */
255 OCStackResult OCRemoveDevice(void* ctx, unsigned short waitTimeForOwnedDeviceDiscovery,
256                             const OCProvisionDev_t* pTargetDev,
257                             OCProvisionResultCB resultCallback)
258 {
259     OC_LOG(INFO, TAG, "IN OCRemoveDevice");
260     OCStackResult res = OC_STACK_ERROR;
261     if (!pTargetDev || !resultCallback || 0 == waitTimeForOwnedDeviceDiscovery)
262     {
263         OC_LOG(INFO, TAG, "OCRemoveDevice : Invalied parameters");
264         return OC_STACK_INVALID_PARAM;
265     }
266
267     // Send DELETE requests to linked devices
268     OCStackResult resReq = OC_STACK_ERROR; // Check that we have to wait callback or not.
269     resReq = SRPRemoveDevice(ctx, waitTimeForOwnedDeviceDiscovery, pTargetDev, resultCallback);
270     if (OC_STACK_OK != resReq)
271     {
272         if (OC_STACK_CONTINUE == resReq)
273         {
274             OC_LOG(DEBUG, TAG, "OCRemoveDevice : Revoked device has no linked device except PT.");
275         }
276         else
277         {
278             OC_LOG(ERROR, TAG, "OCRemoveDevice : Failed to invoke SRPRemoveDevice");
279             res = resReq;
280             goto error;
281         }
282     }
283
284     // Remove credential of revoked device from SVR database
285     const OicSecCred_t *cred = NULL;
286     cred = GetCredResourceData(&pTargetDev->doxm->deviceID);
287     if (cred == NULL)
288     {
289         OC_LOG(ERROR, TAG, "OCRemoveDevice : Failed to get credential of remove device.");
290         goto error;
291     }
292
293     res = RemoveCredential(&cred->subject);
294     if (res != OC_STACK_RESOURCE_DELETED)
295     {
296         OC_LOG(ERROR, TAG, "OCRemoveDevice : Failed to remove credential.");
297         goto error;
298     }
299
300     // Remove device info from prvisioning database.
301     res = PDMDeleteDevice(&pTargetDev->doxm->deviceID);
302     if (res != OC_STACK_OK)
303     {
304         OC_LOG(ERROR, TAG, "OCRemoveDevice : Failed to delete device in PDM.");
305         goto error;
306     }
307
308     // Check that we have to wait callback for DELETE request or not
309     res = resReq;
310
311 error:
312     OC_LOG(INFO, TAG, "OUT OCRemoveDevice");
313     return res;
314 }
315
316
317 /**
318  * Internal Function to update result in link result array.
319  */
320 static void UpdateLinkResults(Linkdata_t *link, int device, OCStackResult stackresult)
321 {
322
323     OC_LOG_V(INFO,TAG,"value of link->currentCountResults is %d",link->currentCountResults);
324     if (1 == device)
325     {
326         memcpy(link->resArr[(link->currentCountResults)].deviceId.id, link->pDev1->doxm->deviceID.id,UUID_LENGTH);
327     }
328     else
329     {
330         memcpy(link->resArr[(link->currentCountResults)].deviceId.id, link->pDev2->doxm->deviceID.id,UUID_LENGTH);
331     }
332     link->resArr[(link->currentCountResults)].res = stackresult;
333     ++(link->currentCountResults);
334
335 }
336
337 /**
338  * Callback to handle ACL provisioning for device 2.
339  */
340 static void AclProv2CB(void* ctx, int nOfRes, OCProvisionResult_t *arr, bool hasError)
341 {
342
343     if (NULL == ctx)
344     {
345         OC_LOG(ERROR,TAG,"Context is Null in ACLProv 2");
346         return;
347     }
348     (void)nOfRes;
349     Linkdata_t *link = (Linkdata_t*)ctx;
350     OCProvisionResultCB resultCallback = link->resultCallback;
351
352
353     if (hasError)
354     {
355         UpdateLinkResults(link, 2,arr[0].res);
356         OC_LOG(ERROR,TAG,"Error occured while ACL provisioning device 1");
357         ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
358                                                 link->resArr,
359                                                 true);
360         OICFree(link->resArr);
361         OICFree(link) ;
362         return;
363     }
364     UpdateLinkResults(link, 2, arr[0].res);
365    ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
366                                            link->resArr,
367                                            false);
368     OICFree(link->resArr);
369     OICFree(link);
370     return;
371 }
372
373 /**
374  * Callback to handle ACL provisioning for device 1
375  */
376 static void AclProv1CB(void* ctx, int nOfRes, OCProvisionResult_t *arr, bool hasError)
377 {
378
379     if (NULL == ctx)
380     {
381         OC_LOG(ERROR,TAG,"Context is Null in ACLProv1");
382         return;
383     }
384     (void)nOfRes;
385     Linkdata_t *link = (Linkdata_t*)ctx;
386     OCProvisionResultCB resultCallback = link->resultCallback;
387
388     if (hasError)
389     {
390         OC_LOG(ERROR,TAG,"Error occured while ACL provisioning device 1");
391         UpdateLinkResults(link, 1, arr[0].res);
392         ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
393                                                 link->resArr,
394                                                 true);
395         OICFree(link->resArr);
396         OICFree(link);
397         return;
398     }
399     UpdateLinkResults(link, 1, arr[0].res);
400     if (NULL != link->pDev2Acl)
401     {
402         OCStackResult res =  SRPProvisionACL(ctx, link->pDev2, link->pDev2Acl, &AclProv2CB);
403         if (OC_STACK_OK!=res)
404         {
405              UpdateLinkResults(link, 2, res);
406              ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
407                                                      link->resArr,
408                                                      true);
409
410         }
411     }
412     else
413     {
414         ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
415                                                 link->resArr,
416                                                 false);
417         OICFree(link->resArr);
418         OICFree(link);
419     }
420
421     return;
422 }
423
424 /**
425  * Callback to handle credential provisioning.
426  */
427 static void ProvisionCredsCB(void* ctx, int nOfRes, OCProvisionResult_t *arr, bool hasError)
428 {
429     if (NULL == ctx)
430     {
431         OC_LOG(ERROR,TAG,"Error occured while credential provisioning");
432         return;
433     }
434     Linkdata_t *link = (Linkdata_t*)ctx;
435     OCProvisionResultCB resultCallback = link->resultCallback;
436     OC_LOG_V(INFO, TAG, "has error returned %d",hasError);
437     UpdateLinkResults(link, 1, arr[0].res);
438     UpdateLinkResults(link, 2, arr[1].res);
439     if (hasError)
440     {
441         OC_LOG(ERROR,TAG,"Error occured while credential provisioning");
442         ((OCProvisionResultCB)(resultCallback))(link->ctx, nOfRes,
443                                                 link->resArr,
444                                                 true);
445          OICFree(link->resArr);
446          OICFree(link);
447          return;
448     }
449     if (NULL != link->pDev1Acl)
450     {
451
452         OCStackResult res =  SRPProvisionACL(ctx, link->pDev1, link->pDev1Acl, &AclProv1CB);
453         if (OC_STACK_OK!=res)
454         {
455              OC_LOG(ERROR, TAG, "Error while provisioning ACL for device 1");
456              UpdateLinkResults(link, 1, res);
457              ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
458                                                      link->resArr,
459                                                      true);
460               OICFree(link->resArr);
461               OICFree(link);
462         }
463     }
464     else if (NULL!=link->pDev2Acl)
465     {
466         OC_LOG(ERROR, TAG, "ACL for device 1 is NULL");
467         OCStackResult res =  SRPProvisionACL(ctx, link->pDev2, link->pDev2Acl, &AclProv2CB);
468         if (OC_STACK_OK!=res)
469         {
470              OC_LOG(ERROR, TAG, "Error while provisioning ACL for device 2");
471               UpdateLinkResults(link, 2, res);
472              ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
473                                                      link->resArr,
474                                                      true);
475               OICFree(link->resArr);
476               OICFree(link);
477         }
478     }
479     else
480     {
481         OC_LOG(INFO, TAG, "ACLs of both devices are NULL");
482         ((OCProvisionResultCB)(resultCallback))(link->ctx, link->currentCountResults,
483                                                 link->resArr,
484                                                 false);
485         OICFree(link->resArr);
486         OICFree(link);
487     }
488     return;
489 }
490 /**
491  * function to provision credentials between two devices and ACLs for the devices who act as a server.
492  *
493  * @param[in] ctx Application context would be returned in result callback.
494  * @param[in] type Type of credentials to be provisioned to the device.
495  * @param[in] pDev1 Pointer to OCProvisionDev_t instance,respresenting resource to be provsioned.
496  * @param[in] acl ACL for device 1. If this is not required set NULL.
497  * @param[in] pDev2 Pointer to OCProvisionDev_t instance,respresenting resource to be provsioned.
498  * @param[in] acl ACL for device 2. If this is not required set NULL.
499  * @param[in] resultCallback callback provided by API user, callback will be called when
500  *            provisioning request recieves a response from first resource server.
501  * @return  OC_STACK_OK in case of success and other value otherwise.
502  */
503 OCStackResult OCProvisionPairwiseDevices(void* ctx, OicSecCredType_t type, size_t keySize,
504                                          const OCProvisionDev_t *pDev1, OicSecAcl_t *pDev1Acl,
505                                          const OCProvisionDev_t *pDev2, OicSecAcl_t *pDev2Acl,
506                                          OCProvisionResultCB resultCallback)
507 {
508
509     if (!pDev1 || !pDev2 || !resultCallback)
510     {
511         OC_LOG(ERROR, TAG, "OCProvisionPairwiseDevices : Invalid parameters");
512         return OC_STACK_INVALID_PARAM;
513     }
514     if (!(keySize == OWNER_PSK_LENGTH_128 || keySize == OWNER_PSK_LENGTH_256))
515     {
516         OC_LOG(INFO, TAG, "OCProvisionPairwiseDevices : Invalid key size");
517         return OC_STACK_INVALID_PARAM;
518     }
519     int noOfResults = 2; // Initial Value
520     if (NULL!=pDev1Acl)
521     {
522         ++noOfResults;
523     }
524     if (NULL!=pDev2Acl)
525     {
526        ++noOfResults;
527     }
528     Linkdata_t *link = (Linkdata_t*) OICMalloc(sizeof(Linkdata_t));
529     if (!link)
530     {
531         OC_LOG(ERROR, TAG, "Failed to memory allocation");
532         return OC_STACK_NO_MEMORY;
533     }
534     OC_LOG_V(INFO,TAG, "Maximum no od results %d",noOfResults);
535
536     link->pDev1 = pDev1;
537     link->pDev1Acl = pDev1Acl;
538     link->pDev2 = pDev2;
539     link->pDev2Acl = pDev2Acl;
540     link->ctx = ctx;
541     // 1 call for each device for credential provisioning. implict call by SRPProvisioning credential
542     // 1 call for ACL provisioning for device 1 and 1 call for ACL provisioning for device 2.
543     link->numOfResults = noOfResults;
544     link->resultCallback = resultCallback;
545     link->currentCountResults = 0;
546     link->resArr = (OCProvisionResult_t*) OICMalloc(sizeof(OCProvisionResult_t)*noOfResults);
547     OCStackResult res = SRPProvisionCredentials(link, type, keySize,
548                                      pDev1, pDev2, &ProvisionCredsCB);
549     if (res != OC_STACK_OK)
550     {
551         OICFree(link->resArr);
552         OICFree(link);
553     }
554     return res;
555
556 }