Imported Upstream version 1.0.0
[platform/upstream/iotivity.git] / resource / csdk / security / provisioning / sample / provisioningclient.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
21 #include <stdio.h>
22 #include <string.h>
23 #include <unistd.h>
24
25 #include "logger.h"
26 #include "oic_malloc.h"
27 #include "oic_string.h"
28 #include "ocprovisioningmanager.h"
29 #include "oxmjustworks.h"
30 #include "oxmrandompin.h"
31 #include "securevirtualresourcetypes.h"
32 #include "srmutility.h"
33 #include "pmtypes.h"
34
35 #ifdef __cplusplus
36 extern "C"
37 {
38 #endif //__cplusplus
39
40 // declaration(s) for provisioning client using C-level provisioning API
41 // user input definition for main loop on provisioning client
42 #define _10_DISCOV_ALL_DEVS_    10
43 #define _11_DISCOV_UNOWN_DEVS_  11
44 #define _12_DISCOV_OWN_DEVS_    12
45 #define _20_REGIST_DEVS_        20
46 #define _30_PROVIS_PAIR_DEVS_   30
47 #define _31_PROVIS_CRED_        31
48 #define _32_PROVIS_ACL_         32
49 #define _33_CHECK_LINK_STATUS_  33
50 #define _40_UNLINK_PAIR_DEVS_   40
51 #define _50_REMOVE_SELEC_DEV_   50
52 #define _99_EXIT_PRVN_CLT_      99
53
54 #define ACL_RESRC_MAX_NUM   16
55 #define ACL_RESRC_MAX_LEN   128
56 #define ACL_PEMISN_CNT      5
57 #define DISCOVERY_TIMEOUT   10  // 10 sec
58 #define CALLBACK_TIMEOUT    60  // 1 min
59 #define TAG "provisioningclient"
60
61 static const char* ACL_PEMISN[5] = {"CREATE", "READ", "WRITE", "DELETE", "NOTIFY"};
62 static const char* SVR_DB_FILE_NAME = "oic_svr_db_client.json";
63         // '_' for separaing from the same constant variable in |srmresourcestrings.c|
64 static const char* PRVN_DB_FILE_NAME = "oic_prvn_mng.db";
65 // |g_ctx| means provision manager application context and
66 // the following, includes |un/own_list|, could be variables, which |g_ctx| has,
67 // for accessing all function(s) for these, they are declared on global domain
68 static const char* g_ctx = "Provision Manager Client Application Context";
69 static char* g_svr_fname;
70 static char* g_prvn_fname;
71 static OCProvisionDev_t* g_own_list;
72 static OCProvisionDev_t* g_unown_list;
73 static int g_own_cnt;
74 static int g_unown_cnt;
75 static bool g_doneCB;
76
77 // function declaration(s) for calling them before implementing
78 static OicSecAcl_t* createAcl(const int);
79 static OCProvisionDev_t* getDevInst(const OCProvisionDev_t*, const int);
80 static int printDevList(const OCProvisionDev_t*);
81 static size_t printUuidList(const OCUuidList_t*);
82 static int printResultList(const OCProvisionResult_t*, const int);
83 static void printUuid(const OicUuid_t*);
84 static FILE* fopen_prvnMng(const char*, const char*);
85 static int waitCallbackRet(void);
86 static int selectTwoDiffNum(int*, int*, const int, const char*);
87
88 // callback function(s) for provisioning client using C-level provisioning API
89 static void ownershipTransferCB(void* ctx, int nOfRes, OCProvisionResult_t* arr, bool hasError)
90 {
91     if(!hasError)
92     {
93         OC_LOG_V(INFO, TAG, "Ownership Transfer SUCCEEDED - ctx: %s", (char*) ctx);
94     }
95     else
96     {
97         OC_LOG_V(ERROR, TAG, "Ownership Transfer FAILED - ctx: %s", (char*) ctx);
98         printResultList((const OCProvisionResult_t*) arr, nOfRes);
99     }
100     g_doneCB = true;
101 }
102
103 static void provisionPairwiseCB(void* ctx, int nOfRes, OCProvisionResult_t* arr, bool hasError)
104 {
105     if(!hasError)
106     {
107         OC_LOG_V(INFO, TAG, "Provision Pairwise SUCCEEDED - ctx: %s", (char*) ctx);
108     }
109     else
110     {
111         OC_LOG_V(ERROR, TAG, "Provision Pairwise FAILED - ctx: %s", (char*) ctx);
112         printResultList((const OCProvisionResult_t*) arr, nOfRes);
113     }
114     g_doneCB = true;
115 }
116
117 static void provisionCredCB(void* ctx, int nOfRes, OCProvisionResult_t* arr, bool hasError)
118 {
119     if(!hasError)
120     {
121         OC_LOG_V(INFO, TAG, "Provision Credential SUCCEEDED - ctx: %s", (char*) ctx);
122     }
123     else
124     {
125         OC_LOG_V(ERROR, TAG, "Provision Credential FAILED - ctx: %s", (char*) ctx);
126         printResultList((const OCProvisionResult_t*) arr, nOfRes);
127     }
128     g_doneCB = true;
129 }
130
131 static void provisionAclCB(void* ctx, int nOfRes, OCProvisionResult_t* arr, bool hasError)
132 {
133     if(!hasError)
134     {
135         OC_LOG_V(INFO, TAG, "Provision ACL SUCCEEDED - ctx: %s", (char*) ctx);
136     }
137     else
138     {
139         OC_LOG_V(ERROR, TAG, "Provision ACL FAILED - ctx: %s", (char*) ctx);
140         printResultList((const OCProvisionResult_t*) arr, nOfRes);
141     }
142     g_doneCB = true;
143 }
144
145 static void unlinkDevicesCB(void* ctx, int nOfRes, OCProvisionResult_t* arr, bool hasError)
146 {
147     if(!hasError)
148     {
149         OC_LOG_V(INFO, TAG, "Unlink Devices SUCCEEDED - ctx: %s", (char*) ctx);
150     }
151     else
152     {
153         OC_LOG_V(ERROR, TAG, "Unlink Devices FAILED - ctx: %s", (char*) ctx);
154         printResultList((const OCProvisionResult_t*) arr, nOfRes);
155     }
156     g_doneCB = true;
157 }
158
159 static void removeDeviceCB(void* ctx, int nOfRes, OCProvisionResult_t* arr, bool hasError)
160 {
161     if(!hasError)
162     {
163         OC_LOG_V(INFO, TAG, "Remove Device SUCCEEDED - ctx: %s", (char*) ctx);
164     }
165     else
166     {
167         OC_LOG_V(ERROR, TAG, "Remove Device FAILED - ctx: %s", (char*) ctx);
168         printResultList((const OCProvisionResult_t*) arr, nOfRes);
169     }
170     g_doneCB = true;
171 }
172
173 static void inputPinCB(char* pin, size_t len)
174 {
175     if(!pin || OXM_RANDOM_PIN_SIZE>=len)
176     {
177         OC_LOG(ERROR, TAG, "inputPinCB invalid parameters");
178         return;
179     }
180
181     printf("   > INPUT PIN: ");
182     for(int ret=0; 1!=ret; )
183     {
184         ret = scanf("%8s", pin);
185         for( ; 0x20<=getchar(); );  // for removing overflow garbages
186                                     // '0x20<=code' is character region
187     }
188 }
189
190 // function(s) for provisioning client using C-level provisioning API
191 static int initProvisionClient(void)
192 {
193     // initialize persistent storage for SVR DB
194     static OCPersistentStorage pstStr =
195     {
196         .open = fopen_prvnMng,
197         .read = fread,
198         .write = fwrite,
199         .close = fclose,
200         .unlink = unlink
201     };
202     if(OC_STACK_OK != OCRegisterPersistentStorageHandler(&pstStr))
203     {
204         OC_LOG(ERROR, TAG, "OCRegisterPersistentStorageHandler error");
205         return -1;
206     }
207
208     // initialize OC stack and provisioning manager
209     if(OC_STACK_OK != OCInit(NULL, 0, OC_CLIENT_SERVER))
210     {
211         OC_LOG(ERROR, TAG, "OCStack init error");
212         return -1;
213     }
214
215     if (access(PRVN_DB_FILE_NAME, F_OK) != -1)
216     {
217         printf("************************************************************\n");
218         printf("************Provisioning DB file already exists.************\n");
219         printf("************************************************************\n");
220     }
221     else
222     {
223         printf("*************************************************************\n");
224         printf("************No provisioning DB file, creating new************\n");
225         printf("*************************************************************\n");
226     }
227
228     if(OC_STACK_OK != OCInitPM(PRVN_DB_FILE_NAME))
229     {
230         OC_LOG(ERROR, TAG, "OC_PM init error");
231         return -1;
232     }
233
234     // register callback function(s) to each OxM
235     OTMCallbackData_t otmcb =
236     {
237         .loadSecretCB = LoadSecretJustWorksCallback,
238         .createSecureSessionCB = CreateSecureSessionJustWorksCallback,
239         .createSelectOxmPayloadCB = CreateJustWorksSelectOxmPayload,
240         .createOwnerTransferPayloadCB = CreateJustWorksOwnerTransferPayload
241     };
242     if(OC_STACK_OK != OCSetOwnerTransferCallbackData(OIC_JUST_WORKS, &otmcb))
243     {
244         OC_LOG(ERROR, TAG, "OCSetOwnerTransferCallbackData error: OIC_JUST_WORKS");
245         return -1;
246     }
247     otmcb.loadSecretCB = InputPinCodeCallback;
248     otmcb.createSecureSessionCB = CreateSecureSessionRandomPinCallbak;
249     otmcb.createSelectOxmPayloadCB = CreatePinBasedSelectOxmPayload;
250     otmcb.createOwnerTransferPayloadCB = CreatePinBasedOwnerTransferPayload;
251     if(OC_STACK_OK != OCSetOwnerTransferCallbackData(OIC_RANDOM_DEVICE_PIN, &otmcb))
252     {
253         OC_LOG(ERROR, TAG, "OCSetOwnerTransferCallbackData error: OIC_RANDOM_DEVICE_PIN");
254         return -1;
255     }
256     SetInputPinCB(inputPinCB);
257
258     return 0;
259 }
260
261 static int discoverAllDevices(void)
262 {
263     // delete un/owned device lists before updating them
264     if(g_own_list)
265     {
266         OCDeleteDiscoveredDevices(g_own_list);
267         g_own_list = NULL;
268     }
269     if(g_unown_list)
270     {
271         OCDeleteDiscoveredDevices(g_unown_list);
272         g_unown_list = NULL;
273     }
274
275     // call |OCGetDevInfoFromNetwork| API actually
276     printf("   Discovering All Un/Owned Devices on Network..\n");
277     if(OC_STACK_OK != OCGetDevInfoFromNetwork(DISCOVERY_TIMEOUT, &g_own_list, &g_unown_list))
278     {
279         OC_LOG(ERROR, TAG, "OCGetDevInfoFromNetwork API error");
280         return -1;
281     }
282
283     // display the discovered un/owned lists
284     printf("   > Discovered Owned Devices\n");
285     g_own_cnt = printDevList(g_own_list);
286     printf("   > Discovered Unowned Devices\n");
287     g_unown_cnt = printDevList(g_unown_list);
288
289     return 0;
290 }
291
292
293 static int discoverUnownedDevices(void)
294 {
295     // delete unowned device list before updating it
296     if(g_unown_list)
297     {
298         OCDeleteDiscoveredDevices(g_unown_list);
299         g_unown_list = NULL;
300     }
301
302     // call |OCDiscoverUnownedDevices| API actually
303     printf("   Discovering Only Unowned Devices on Network..\n");
304     if(OC_STACK_OK != OCDiscoverUnownedDevices(DISCOVERY_TIMEOUT, &g_unown_list))
305     {
306         OC_LOG(ERROR, TAG, "OCDiscoverUnownedDevices API error");
307         return -1;
308     }
309
310     // display the discovered unowned list
311     printf("   > Discovered Unowned Devices\n");
312     g_unown_cnt = printDevList(g_unown_list);
313
314     return 0;
315 }
316
317 static int discoverOwnedDevices(void)
318 {
319     // delete owned device list before updating it
320     if(g_own_list)
321     {
322         OCDeleteDiscoveredDevices(g_own_list);
323         g_own_list = NULL;
324     }
325
326     // call |OCDiscoverOwnedDevices| API actually
327     printf("   Discovering Only Owned Devices on Network..\n");
328     if(OC_STACK_OK != OCDiscoverOwnedDevices(DISCOVERY_TIMEOUT, &g_own_list))
329     {
330         OC_LOG(ERROR, TAG, "OCDiscoverOwnedDevices API error");
331         return -1;
332     }
333
334     // display the discovered owned list
335     printf("   > Discovered Owned Devices\n");
336     g_own_cnt = printDevList(g_own_list);
337
338     return 0;
339 }
340
341 static int registerDevices(void)
342 {
343     // check |unown_list| for registering devices
344     if(!g_unown_list || 0>=g_unown_cnt)
345     {
346         printf("   > Unowned Device List, to Register Devices, is Empty\n");
347         printf("   > Please Discover Unowned Devices first, with [10|11] Menu\n");
348         return 0;  // normal case
349     }
350
351     // call |OCDoOwnershipTransfer| API actually
352     // calling this API with callback actually acts like blocking
353     // for error checking, the return value saved and printed
354     g_doneCB = false;
355     printf("   Registering All Discovered Unowned Devices..\n");
356     OCStackResult rst = OCDoOwnershipTransfer((void*) g_ctx, g_unown_list, ownershipTransferCB);
357     if(OC_STACK_OK != rst)
358     {
359         OC_LOG_V(ERROR, TAG, "OCDoOwnershipTransfer API error: %d", rst);
360         return -1;
361     }
362     if(waitCallbackRet())  // input |g_doneCB| flag implicitly
363     {
364         OC_LOG(ERROR, TAG, "OCProvisionCredentials callback error");
365         return -1;
366     }
367
368     // display the registered result
369     printf("   > Registered Discovered Unowned Devices\n");
370     printf("   > Please Discover Owned Devices for the Registered Result, with [10|12] Menu\n");
371
372     return 0;
373 }
374
375 static int provisionPairwise(void)
376 {
377     // check |own_list| for provisioning pairwise devices
378     if(!g_own_list || 2>g_own_cnt)
379     {
380         printf("   > Owned Device List, to Provision the Pairwise, is Empty\n");
381         printf("   > Please Register Unowned Devices first, with [20] Menu\n");
382         return 0;  // normal case
383     }
384
385     // select two devices for provisioning pairwise devices
386     int dev_num[2] = {0};
387     if(selectTwoDiffNum(&(dev_num[0]), &(dev_num[1]), g_own_cnt, "for Linking Devices"))
388     {
389         OC_LOG(ERROR, TAG, "selectTwoDiffNum error return");
390         return -1;  // not need to 'goto' |ERROR| before allocating |acl|
391     }
392
393     // create ACL(s) for each selected device
394     OicSecAcl_t* acl[2] = {0};
395     for(int i=0; 2>i; ++i)
396     {
397         acl[i] = createAcl(dev_num[i]);
398         if(!acl[i])
399         {
400             OC_LOG(ERROR, TAG, "createAcl error return");
401             goto PVPWS_ERROR;
402         }
403     }
404
405     // call |OCProvisionPairwiseDevices| API actually
406     // calling this API with callback actually acts like blocking
407     // for error checking, the return value saved and printed
408     g_doneCB = false;
409     printf("   Provisioning Selected Pairwise Devices..\n");
410     OCStackResult rst =
411             OCProvisionPairwiseDevices((void*) g_ctx,
412                     SYMMETRIC_PAIR_WISE_KEY, OWNER_PSK_LENGTH_128,
413                     getDevInst((const OCProvisionDev_t*) g_own_list, dev_num[0]), acl[0],
414                     getDevInst((const OCProvisionDev_t*) g_own_list, dev_num[1]), acl[1],
415                     provisionPairwiseCB);
416     if(OC_STACK_OK != rst)
417     {
418         OC_LOG_V(ERROR, TAG, "OCProvisionPairwiseDevices API error: %d", rst);
419         goto PVPWS_ERROR;
420     }
421     if(waitCallbackRet())  // input |g_doneCB| flag implicitly
422     {
423         OC_LOG(ERROR, TAG, "OCProvisionCredentials callback error");
424         goto PVPWS_ERROR;
425     }
426     OCDeleteACLList(acl[0]);
427     OCDeleteACLList(acl[1]);
428
429     // display the pairwise-provisioned result
430     printf("   > Provisioned Selected Pairwise Devices\n");
431     printf("   > Please Check Device's Status for the Linked Result, with [33] Menu\n");
432
433     return 0;
434
435 PVPWS_ERROR:
436     OCDeleteACLList(acl[0]);
437     OCDeleteACLList(acl[1]);
438     return -1;
439 }
440
441 static int provisionCred(void)
442 {
443     // check |own_list| for provisioning pairwise credentials
444     if(!g_own_list || 2>g_own_cnt)
445     {
446         printf("   > Owned Device List, to Provision Credentials, is Empty\n");
447         printf("   > Please Register Unowned Devices first, with [20] Menu\n");
448         return 0;  // normal case
449     }
450
451     // select two devices for provisioning pairwise credentials
452     int dev_num[2] = {0};
453     if(selectTwoDiffNum(&(dev_num[0]), &(dev_num[1]), g_own_cnt, "for Linking CRED(s)"))
454     {
455         OC_LOG(ERROR, TAG, "selectTwoDiffNum error return");
456         return -1;
457     }
458
459     printf("   Select PSK length..\n");
460     printf("   1 - 128bit(Default)\n");
461     printf("   2 - 256bit\n");
462     int sizeOption = 0;
463
464     for(int ret=0; 1!=ret; )
465     {
466          ret = scanf("%d",&sizeOption);
467          for( ; 0x20<=getchar(); );  // for removing overflow garbages
468                                     // '0x20<=code' is character region
469     }
470     size_t size = 0;
471
472     switch(sizeOption)
473     {
474         case 1:
475         {
476             size = OWNER_PSK_LENGTH_128;
477             break;
478         }
479         case 2:
480         {
481             size = OWNER_PSK_LENGTH_256;
482             break;
483         }
484         default:
485         {
486             size = OWNER_PSK_LENGTH_128;
487             break;
488         }
489     }
490
491
492     // call |OCProvisionCredentials| API actually
493     // calling this API with callback actually acts like blocking
494     // for error checking, the return value saved and printed
495     g_doneCB = false;
496     printf("   Provisioning Selected Pairwise Credentials..\n");
497     OCStackResult rst =
498             OCProvisionCredentials((void*) g_ctx,
499                     SYMMETRIC_PAIR_WISE_KEY, size,
500                     getDevInst((const OCProvisionDev_t*) g_own_list, dev_num[0]),
501                     getDevInst((const OCProvisionDev_t*) g_own_list, dev_num[1]),
502                     provisionCredCB);
503     if(OC_STACK_OK != rst)
504     {
505         OC_LOG_V(ERROR, TAG, "OCProvisionCredentials API error: %d", rst);
506         return -1;
507     }
508     if(waitCallbackRet())  // input |g_doneCB| flag implicitly
509     {
510         OC_LOG(ERROR, TAG, "OCProvisionCredentials callback error");
511         return -1;
512     }
513
514     // display the CRED-provisioned result
515     printf("   > Provisioned Selected Pairwise Crendentials\n");
516     printf("   > Please Check Device's Status for the Linked Result, with [33] Menu\n");
517
518     return 0;
519 }
520
521 static int provisionAcl(void)
522 {
523     // check |own_list| for provisioning access control list
524     if(!g_own_list || 1>g_own_cnt)
525     {
526         printf("   > Owned Device List, to Provision ACL, is Empty\n");
527         printf("   > Please Register Unowned Devices first, with [20] Menu\n");
528         return 0;  // normal case
529     }
530
531     // select device for provisioning access control list
532     int dev_num = 0;
533     for( ; ; )
534     {
535         printf("   > Enter Device Number, for Provisioning ACL: ");
536         for(int ret=0; 1!=ret; )
537         {
538             ret = scanf("%d", &dev_num);
539             for( ; 0x20<=getchar(); );  // for removing overflow garbages
540                                         // '0x20<=code' is character region
541         }
542         if(0<dev_num && g_own_cnt>=dev_num)
543         {
544             break;
545         }
546         printf("     Entered Wrong Number. Please Enter Again\n");
547     }
548
549     // create ACL for selected device
550     OicSecAcl_t* acl = NULL;
551     acl = createAcl(dev_num);
552     if(!acl)
553     {
554         OC_LOG(ERROR, TAG, "createAcl error return");
555         goto PVACL_ERROR;
556     }
557
558     // call |OCProvisionACL| API actually
559     // calling this API with callback actually acts like blocking
560     // for error checking, the return value saved and printed
561     g_doneCB = false;
562     printf("   Provisioning Selected ACL..\n");
563     OCStackResult rst =
564             OCProvisionACL((void*) g_ctx,
565                     getDevInst((const OCProvisionDev_t*) g_own_list, dev_num),
566                     acl, provisionAclCB);
567     if(OC_STACK_OK != rst)
568     {
569         OC_LOG_V(ERROR, TAG, "OCProvisionACL API error: %d", rst);
570         goto PVACL_ERROR;
571     }
572     if(waitCallbackRet())  // input |g_doneCB| flag implicitly
573     {
574         OC_LOG(ERROR, TAG, "OCProvisionCredentials callback error");
575         goto PVACL_ERROR;
576     }
577     OCDeleteACLList(acl);  // after here |acl| points nothing
578
579     // display the ACL-provisioned result
580     printf("   > Provisioned Selected ACL\n");
581
582     return 0;
583
584 PVACL_ERROR:
585     OCDeleteACLList(acl);  // after here |acl| points nothing
586     return -1;
587 }
588
589 static int checkLinkedStatus(void)
590 {
591     // check |own_list| for checking selected link status on PRVN DB
592     if(!g_own_list || 1>g_own_cnt)
593     {
594         printf("   > Owned Device List, to Check Linked Status on PRVN DB, is Empty\n");
595         printf("   > Please Register Unowned Devices first, with [20] Menu\n");
596         return 0;  // normal case
597     }
598
599     // select device for checking selected link status on PRVN DB
600     int dev_num = 0;
601     for( ; ; )
602     {
603         printf("   > Enter Device Number, for Checking Linked Status on PRVN DB: ");
604         for(int ret=0; 1!=ret; )
605         {
606             ret = scanf("%d", &dev_num);
607             for( ; 0x20<=getchar(); );  // for removing overflow garbages
608                                         // '0x20<=code' is character region
609         }
610         if(0<dev_num && g_own_cnt>=dev_num)
611         {
612             break;
613         }
614         printf("     Entered Wrong Number. Please Enter Again\n");
615     }
616
617     // call |OCGetLinkedStatus| API actually
618     printf("   Checking Selected Link Status on PRVN DB..\n");
619     OCUuidList_t* dvid_lst = NULL;
620     size_t dvid_cnt = 0;
621     if(OC_STACK_OK !=
622             OCGetLinkedStatus(
623                     &getDevInst((const OCProvisionDev_t*) g_own_list, dev_num)->doxm->deviceID,
624                     &dvid_lst, &dvid_cnt))  // allow empty list
625     {
626         OC_LOG(ERROR, TAG, "OCGetLinkedStatus API error");
627         goto CKLST_ERROR;
628     }
629
630     // display the linked status result
631     printf("   > Checked Selected Link Status on PRVN DB\n");
632     if(!dvid_lst || !dvid_cnt)  // |size_t| is unsigned
633     {
634         printf("     Linked Device List is Empty..\n");
635         return 0;  // normal case
636     }
637     if(dvid_cnt != printUuidList((const OCUuidList_t*) dvid_lst))
638     {
639         OC_LOG(ERROR, TAG, "printUuidList error return");
640         goto CKLST_ERROR;
641     }
642     OCDeleteUuidList(dvid_lst);
643
644     return 0;
645
646 CKLST_ERROR:
647     OCDeleteUuidList(dvid_lst);
648     return -1;
649 }
650
651 static int unlinkPairwise(void)
652 {
653     // check |own_list| for unlinking pairwise devices
654     if(!g_own_list || 2>g_own_cnt)
655     {
656         printf("   > Owned Device List, to Unlink the Pairwise, is Empty\n");
657         printf("   > Please Register Unowned Devices first, with [20] Menu\n");
658         return 0;  // normal case
659     }
660
661     // select two devices for unlinking pairwise devices
662     int dev_num[2] = {0};
663     if(selectTwoDiffNum(&(dev_num[0]), &(dev_num[1]), g_own_cnt, "for Unlinking Devices"))
664     {
665         OC_LOG(ERROR, TAG, "selectTwoDiffNum error return");
666         return -1;
667     }
668
669     // call |OCUnlinkDevices| API actually
670     // calling this API with callback actually acts like blocking
671     // for error checking, the return value saved and printed
672     g_doneCB = false;
673     printf("   Unlinking Selected Pairwise Devices..\n");
674     OCStackResult rst =
675             OCUnlinkDevices((void*) g_ctx,
676                     getDevInst((const OCProvisionDev_t*) g_own_list, dev_num[0]),
677                     getDevInst((const OCProvisionDev_t*) g_own_list, dev_num[1]),
678                     unlinkDevicesCB);
679     if(OC_STACK_OK != rst)
680     {
681         OC_LOG_V(ERROR, TAG, "OCUnlinkDevices API error: %d", rst);
682         return -1;
683     }
684     if(waitCallbackRet())  // input |g_doneCB| flag implicitly
685     {
686         OC_LOG(ERROR, TAG, "OCProvisionCredentials callback error");
687         return -1;
688     }
689
690     // display the pairwise-unlinked result
691     printf("   > Unlinked Selected Pairwise Devices\n");
692     printf("   > Please Check Device's Status for the Unlinked Result, with [33] Menu\n");
693
694     return 0;
695 }
696
697 static int removeDevice(void)
698 {
699     // check |own_list| for removing device
700     if(!g_own_list || 1>g_own_cnt)
701     {
702         printf("   > Owned Device List, to Remove Device, is Empty\n");
703         printf("   > Please Register Unowned Devices first, with [20] Menu\n");
704         return 0;  // normal case
705     }
706
707     // select device for removing it
708     int dev_num = 0;
709     for( ; ; )
710     {
711         printf("   > Enter Device Number, for Removing Device: ");
712         for(int ret=0; 1!=ret; )
713         {
714             ret = scanf("%d", &dev_num);
715             for( ; 0x20<=getchar(); );  // for removing overflow garbages
716                                         // '0x20<=code' is character region
717         }
718         if(0<dev_num && g_own_cnt>=dev_num)
719         {
720             break;
721         }
722         printf("     Entered Wrong Number. Please Enter Again\n");
723     }
724
725     // call |OCRemoveDevice| API actually
726     // calling this API with callback actually acts like blocking
727     // for error checking, the return value saved and printed
728     g_doneCB = false;
729     printf("   Removing Selected Owned Device..\n");
730     OCStackResult rst =
731             OCRemoveDevice((void*) g_ctx, DISCOVERY_TIMEOUT,
732                     getDevInst((const OCProvisionDev_t*) g_own_list, dev_num), removeDeviceCB);
733     if(OC_STACK_OK != rst)
734     {
735         OC_LOG_V(ERROR, TAG, "OCRemoveDevice API error: %d", rst);
736         return -1;
737     }
738     if(waitCallbackRet())  // input |g_doneCB| flag implicitly
739     {
740         OC_LOG(ERROR, TAG, "OCProvisionCredentials callback error");
741         return -1;
742     }
743
744     // display the removed result
745     printf("   > Removed Selected Owned Device\n");
746     printf("   > Please Discover Owned Devices for the Registered Result, with [10|12] Menu\n");
747
748     return 0;
749 }
750
751 static OicSecAcl_t* createAcl(const int dev_num)
752 {
753     if(0>=dev_num || g_own_cnt<dev_num)
754     {
755         OC_LOG(ERROR, TAG, "createAcl invalid parameters");
756         return NULL;  // not need to 'goto' |ERROR| before allocating |acl|
757     }
758
759     // allocate memory for |acl| struct
760     printf("   **** Create ACL for the Selected Device[%d]\n", dev_num);
761     OicSecAcl_t* acl = (OicSecAcl_t*) OICCalloc(1, sizeof(OicSecAcl_t));
762     if(!acl)
763     {
764         OC_LOG(ERROR, TAG, "createAcl: OICCalloc error return");
765         return NULL;  // not need to 'goto' |ERROR| before allocating |acl|
766     }
767
768     // enter |subject| device number
769     int num = 0;
770     for( ; ; )
771     {
772         printf("   > [A] Enter Subject Device Number: ");
773         for(int ret=0; 1!=ret; )
774         {
775             ret = scanf("%d", &num);
776             for( ; 0x20<=getchar(); );  // for removing overflow garbages
777                                         // '0x20<=code' is character region
778         }
779         if(num && g_own_cnt>=num && dev_num!=num)
780         {
781             break;
782         }
783         printf("     Entered Wrong Number. Please Enter Again\n");
784     }
785     memcpy(&acl->subject,
786             &getDevInst((const OCProvisionDev_t*) g_own_list, num)->doxm->deviceID,
787             UUID_LENGTH);  // not need |*sizeof(uint8_t)|
788
789     // enter number of |resources| in 'accessed' device
790     for( ; ; )
791     {
792         printf("   > [B] Enter Number of Accessed Resources (under 16): ");
793                 // '16' is |ACL_RESRC_MAX_NUM|
794         for(int ret=0; 1!=ret; )
795         {
796             ret = scanf("%zu", &acl->resourcesLen);
797             for( ; 0x20<=getchar(); );  // for removing overflow garbages
798                                         // '0x20<=code' is character region
799         }
800         if(acl->resourcesLen && ACL_RESRC_MAX_NUM>=acl->resourcesLen)
801                 // |acl->resourcesLen| is unsigned
802         {
803             break;
804         }
805         printf("     Entered Wrong Number. Please Enter under 16 Again\n");
806                 // '16' is |ACL_RESRC_MAX_NUM|
807     }
808
809     // enter actually each 'accessed' |resources| name
810     printf("         Enter Each Accessed Resource Name (each under 128 char)\n");
811             // '128' is ACL_RESRC_MAX_LEN
812     num = acl->resourcesLen;
813     acl->resources = (char**) OICCalloc(num, sizeof(char*));
814     if(!acl->resources)
815     {
816         OC_LOG(ERROR, TAG, "createAcl: OICCalloc error return");
817         goto CRACL_ERROR;
818     }
819     char rsrc_in[ACL_RESRC_MAX_LEN+1] = {0};  // '1' for null termination
820     for(int i=0; num>i; ++i)
821     {
822         printf("         Enter Accessed Resource[%d] Name: ", i+1);
823         for(int ret=0; 1!=ret; )
824         {
825             ret = scanf("%128s", rsrc_in);  // '128' is ACL_RESRC_MAX_LEN
826             for( ; 0x20<=getchar(); );  // for removing overflow garbages
827                                         // '0x20<=code' is character region
828         }
829         size_t len = strlen(rsrc_in)+1;  // '1' for null termination
830         char* rsrc = (char*) OICCalloc(len, sizeof(char));
831         if(!rsrc)
832         {
833             OC_LOG(ERROR, TAG, "createAcl: OICCalloc error return");
834             goto CRACL_ERROR;
835         }
836         OICStrcpy(rsrc, len, rsrc_in);
837         acl->resources[i] = rsrc;  // after here, |rsrc| points nothing
838     }
839
840     // enter |permission| for this access
841     printf("   > [C] Enter Permission for This Access\n");
842     uint16_t pmsn = PERMISSION_FULL_CONTROL;  // default full permission
843     uint16_t pmsn_msk = PERMISSION_CREATE;  // default permission mask
844     for(int i=0; ACL_PEMISN_CNT>i; ++i)
845     {
846         char ans = 0;
847         for( ; ; )
848         {
849             printf("         Enter %s Permission (y/n): ", ACL_PEMISN[i]);
850             for(int ret=0; 1!=ret; )
851             {
852                 ret = scanf("%c", &ans);
853                 for( ; 0x20<=getchar(); );  // for removing overflow garbages
854                                             // '0x20<=code' is character region
855             }
856             if('y'==ans || 'Y'==ans || 'n'==ans|| 'N'==ans)
857             {
858                 ans &= ~0x20;  // for masking lower case, 'y/n'
859                 break;
860             }
861             printf("         Entered Wrong Answer. Please Enter 'y/n' Again\n");
862         }
863         if('N' == ans)  // masked lower case, 'n'
864         {
865             pmsn -= pmsn_msk;
866         }
867         pmsn_msk <<= 1;
868     }
869     acl->permission = pmsn;
870
871     // enter |owner| device number
872     for( ; ; )
873     {
874         printf("   > [D] Enter Owner Device Number: ");
875         for(int ret=0; 1!=ret; )
876         {
877             ret = scanf("%d", &num);
878             for( ; 0x20<=getchar(); );  // for removing overflow garbages
879                                         // '0x20<=code' is character region
880         }
881         if(num && g_own_cnt>=num)
882         {
883             break;
884         }
885         printf("         Entered Wrong Number. Please Enter Again\n");
886     }
887     acl->ownersLen = 1;
888     acl->owners = (OicUuid_t*) OICCalloc(1, sizeof(OicUuid_t));
889     if(!acl->owners)
890     {
891         OC_LOG(ERROR, TAG, "createAcl: OICCalloc error return");
892         goto CRACL_ERROR;
893     }
894     memcpy(acl->owners,
895             &getDevInst((const OCProvisionDev_t*) g_own_list, num)->doxm->deviceID,
896             UUID_LENGTH);  // not need |*sizeof(uint8_t)|
897     printf("\n");
898
899     return acl;
900
901 CRACL_ERROR:
902     OCDeleteACLList(acl);  // after here |acl| points nothing
903     return NULL;
904 }
905
906 static OCProvisionDev_t* getDevInst(const OCProvisionDev_t* dev_lst, const int dev_num)
907 {
908     if(!dev_lst || 0>=dev_num)
909     {
910         printf("     Device List is Empty..\n");
911         return NULL;
912     }
913
914     OCProvisionDev_t* lst = (OCProvisionDev_t*) dev_lst;
915     for(int i=0; lst; )
916     {
917         if(dev_num == ++i)
918         {
919             return lst;
920         }
921         lst = lst->next;
922     }
923
924     return NULL;  // in here |lst| is always |NULL|
925 }
926
927 static int printDevList(const OCProvisionDev_t* dev_lst)
928 {
929     if(!dev_lst)
930     {
931         printf("     Device List is Empty..\n\n");
932         return 0;
933     }
934
935     OCProvisionDev_t* lst = (OCProvisionDev_t*) dev_lst;
936     int lst_cnt = 0;
937     for( ; lst; )
938     {
939         printf("     [%d] ", ++lst_cnt);
940         printUuid((const OicUuid_t*) &lst->doxm->deviceID);
941         printf("\n");
942         lst = lst->next;
943     }
944     printf("\n");
945
946     return lst_cnt;
947 }
948
949 static size_t printUuidList(const OCUuidList_t* uid_lst)
950 {
951     if(!uid_lst)
952     {
953         printf("     Device List is Empty..\n\n");
954         return 0;
955     }
956
957     OCUuidList_t* lst = (OCUuidList_t*) uid_lst;
958     size_t lst_cnt = 0;
959     for( ; lst; )
960     {
961         printf("     [%zu] ", ++lst_cnt);
962         printUuid((const OicUuid_t*) &lst->dev);
963         printf("\n");
964         lst = lst->next;
965     }
966     printf("\n");
967
968     return lst_cnt;
969 }
970
971 static int printResultList(const OCProvisionResult_t* rslt_lst, const int rslt_cnt)
972 {
973     if(!rslt_lst || 0>=rslt_cnt)
974     {
975         printf("     Device List is Empty..\n\n");
976         return 0;
977     }
978
979     int lst_cnt = 0;
980     for( ; rslt_cnt>lst_cnt; ++lst_cnt)
981     {
982         printf("     [%d] ", lst_cnt+1);
983         printUuid((const OicUuid_t*) &rslt_lst[lst_cnt].deviceId);
984         printf(" - result: %d\n", rslt_lst[lst_cnt].res);
985     }
986     printf("\n");
987
988     return lst_cnt;
989 }
990
991 static void printUuid(const OicUuid_t* uid)
992 {
993     for(int i=0; i<UUID_LENGTH; )
994     {
995         printf("%02X", (*uid).id[i++]);
996         if(i==4 || i==6 || i==8 || i==10)  // canonical format for UUID has '8-4-4-4-12'
997         {
998             printf("-");
999         }
1000     }
1001 }
1002
1003 static FILE* fopen_prvnMng(const char* path, const char* mode)
1004 {
1005     (void)path;  // unused |path| parameter
1006
1007     // input |g_svr_db_fname| internally by force, not using |path| parameter
1008     // because |OCPersistentStorage::open| is called |OCPersistentStorage| internally
1009     // with its own |SVR_DB_FILE_NAME|
1010     return fopen(SVR_DB_FILE_NAME, mode);
1011 }
1012
1013 static int waitCallbackRet(void)
1014 {
1015     for(int i=0; !g_doneCB && CALLBACK_TIMEOUT>i; ++i)
1016     {
1017         sleep(1);
1018         if(OC_STACK_OK != OCProcess())
1019         {
1020             OC_LOG(ERROR, TAG, "OCStack process error");
1021             return -1;
1022         }
1023     }
1024
1025     return 0;
1026 }
1027
1028 static int selectTwoDiffNum(int* a, int* b, const int max, const char* str)
1029 {
1030     if(!a || !b || 2>=max || !str)
1031     {
1032         return -1;
1033     }
1034
1035     for( ; ; )
1036     {
1037         for(int i=0; 2>i; ++i)
1038         {
1039             int* num = 0==i?a:b;
1040             for( ; ; )
1041             {
1042                 printf("   > Enter Device[%d] Number, %s: ", i+1, str);
1043                 for(int ret=0; 1!=ret; )
1044                 {
1045                     ret = scanf("%d", num);
1046                     for( ; 0x20<=getchar(); );  // for removing overflow garbages
1047                                                 // '0x20<=code' is character region
1048                 }
1049                 if(0<*num && max>=*num)
1050                 {
1051                     break;
1052                 }
1053                 printf("     Entered Wrong Number. Please Enter Again\n");
1054             }
1055         }
1056         if(*a != *b)
1057         {
1058             printf("\n");
1059             return 0;
1060         }
1061     }
1062
1063     return -1;
1064 }
1065
1066 static void printMenu(void)
1067 {
1068     printf("************************************************************\n");
1069     printf("****** OIC Provisioning Client with using C-level API ******\n");
1070     printf("************************************************************\n\n");
1071
1072     printf("** [A] DISCOVER DEVICES ON NETWORK\n");
1073     printf("** 10. Discover All Un/Owned Devices on Network\n");
1074     printf("** 11. Discover Only Unowned Devices on Network\n");
1075     printf("** 12. Discover Only Owned Devices on Network\n\n");
1076
1077     printf("** [B] REGISTER/OWN ALL DISCOVERED UNOWNED DEVICES\n");
1078     printf("** 20. Register/Own All Discovered Unowned Devices\n\n");
1079
1080     printf("** [C] PROVISION/LINK PAIRWISE THINGS\n");
1081     printf("** 30. Provision/Link Pairwise Things\n");
1082     printf("** 31. Provision Credentials for Pairwise Things\n");
1083     printf("** 32. Provision the Selected Access Control List(ACL)\n");
1084     printf("** 33. Check Linked Status of the Selected Device on PRVN DB\n\n");
1085
1086     printf("** [D] UNLINK PAIRWISE THINGS\n");
1087     printf("** 40. Unlink Pairwise Things\n\n");
1088
1089     printf("** [E] REMOVE THE SELECTED DEVICE\n");
1090     printf("** 50. Remove the Selected Device\n\n");
1091
1092     printf("** [F] EXIT PROVISIONING CLIENT\n");
1093     printf("** 99. Exit Provisionong Client\n\n");
1094
1095     printf("************************************************************\n\n");
1096 }
1097
1098 #if 0 // Code for enabling path configuration for PDB and SVR DBf
1099 static void printUsage(void)
1100 {
1101     printf("\n");
1102     printf("OIC Provisioning Client with using C-level API\n");
1103     printf("Usage: provisioningclient [option]...\n");
1104     printf("\n");
1105     printf("  -h                           print help for this provisioning client\n");
1106     printf("  -p=[prvn_db_file_path/name]  input PRVN DB file path and name\n");
1107     printf("                               if not exists, will load default DB file\n");
1108     printf("                               (default: |oic_prvn_mng.db| on working dir)\n");
1109     printf("                               (ex. -p=oic_prvn_mng.db)\n");
1110     printf("  -s=[svr_db_file_path/name]   input SVR DB file path and name\n");
1111     printf("                               if not exists, will load default DB file\n");
1112     printf("                               (default: |oic_svr_db_client.json| on working dir)\n");
1113     printf("                               (ex. -s=oic_svr_db_client.json)\n");
1114     printf("\n");
1115 }
1116 #endif
1117
1118 // main function for provisioning client using C-level provisioning API
1119 int main()
1120 {
1121     // initialize provisioning client
1122     if(initProvisionClient())
1123     {
1124         OC_LOG(ERROR, TAG, "ProvisionClient init error");
1125         goto PMCLT_ERROR;
1126     }
1127
1128     // main loop for provisioning manager
1129     int mn_num = 0;
1130     for( ; ; )
1131     {
1132         printf("\n");
1133         printMenu();
1134         printf(">> Enter Menu Number: ");
1135         for(int ret=0; 1!=ret; )
1136         {
1137             ret = scanf("%d", &mn_num);
1138             for( ; 0x20<=getchar(); );  // for removing overflow garbages
1139                                         // '0x20<=code' is character region
1140         }
1141         printf("\n");
1142         switch(mn_num)
1143         {
1144         case _10_DISCOV_ALL_DEVS_:
1145             if(discoverAllDevices())
1146             {
1147                 OC_LOG(ERROR, TAG, "_10_DISCOV_ALL_DEVS_: error");
1148             }
1149             break;
1150         case _11_DISCOV_UNOWN_DEVS_:
1151             if(discoverUnownedDevices())
1152             {
1153                 OC_LOG(ERROR, TAG, "_11_DISCOV_UNOWN_DEVS_: error");
1154             }
1155             break;
1156         case _12_DISCOV_OWN_DEVS_:
1157             if(discoverOwnedDevices())
1158             {
1159                 OC_LOG(ERROR, TAG, "_12_DISCOV_OWN_DEVS_: error");
1160             }
1161             break;
1162         case _20_REGIST_DEVS_:
1163             if(registerDevices())
1164             {
1165                 OC_LOG(ERROR, TAG, "_20_REGIST_DEVS_: error");
1166             }
1167             break;
1168         case _30_PROVIS_PAIR_DEVS_:
1169             if(provisionPairwise())
1170             {
1171                 OC_LOG(ERROR, TAG, "_30_PROVIS_PAIR_DEVS_: error");
1172             }
1173             break;
1174         case _31_PROVIS_CRED_:
1175             if(provisionCred())
1176             {
1177                 OC_LOG(ERROR, TAG, "_31_PROVIS_CRED_: error");
1178             }
1179             break;
1180         case _32_PROVIS_ACL_:
1181             if(provisionAcl())
1182             {
1183                 OC_LOG(ERROR, TAG, "_32_PROVIS_ACL_: error");
1184             }
1185             break;
1186         case _33_CHECK_LINK_STATUS_:
1187             if(checkLinkedStatus())
1188             {
1189                 OC_LOG(ERROR, TAG, "_33_CHECK_LINK_STATUS_: error");
1190             }
1191             break;
1192         case _40_UNLINK_PAIR_DEVS_:
1193             if(unlinkPairwise())
1194             {
1195                 OC_LOG(ERROR, TAG, "_40_UNLINK_PAIR_DEVS_: error");
1196             }
1197             break;
1198         case _50_REMOVE_SELEC_DEV_:
1199             if(removeDevice())
1200             {
1201                 OC_LOG(ERROR, TAG, "_50_REMOVE_SELEC_DEV_: error");
1202             }
1203             break;
1204         case _99_EXIT_PRVN_CLT_:
1205             goto PMCLT_ERROR;
1206         default:
1207             printf(">> Entered Wrong Number. Please Enter Again\n\n");
1208             break;
1209         }
1210     }
1211
1212 PMCLT_ERROR:
1213     if(OC_STACK_OK != OCStop())
1214     {
1215         OC_LOG(ERROR, TAG, "OCStack stop error");
1216     }
1217     OCDeleteDiscoveredDevices(g_own_list);  // after here |g_own_list| points nothing
1218     OCDeleteDiscoveredDevices(g_unown_list);  // after here |g_unown_list| points nothing
1219
1220     if(g_svr_fname)
1221     {
1222         OICFree(g_svr_fname);  // after here |g_svr_fname| points nothing
1223     }
1224     if(g_prvn_fname)
1225     {
1226         OICFree(g_prvn_fname);  // after here |g_prvn_fname| points nothing
1227     }
1228     return 0;  // always return normal case
1229 }
1230
1231 #ifdef __cplusplus
1232 }
1233 #endif //__cplusplus