1 /* *****************************************************************
3 * Copyright 2015 Samsung Electronics All Rights Reserved.
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
11 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 * *****************************************************************/
29 #include <condition_variable>
32 #include "oic_malloc.h"
33 #include "oic_string.h"
34 #include "OCPlatform.h"
36 #include "OCProvisioningManager.h"
37 #include "oxmjustworks.h"
38 #include "oxmrandompin.h"
40 #define MAX_URI_LENGTH (64)
41 #define MAX_PERMISSION_LENGTH (5)
48 #define PREDEFINED_TIMEOUT (10)
49 #define MAX_OWNED_DEVICE (10)
50 #define TAG "provisioningclient"
52 #define JSON_DB_PATH "./oic_svr_db_client.json"
53 #define DAT_DB_PATH "./oic_svr_db_client.dat"
54 #define DEV_STATUS_ON "DEV_STATUS_ON"
55 #define DEV_STATUS_OFF "DEV_STATUS_OFF"
57 #define DISCOVERY_TIMEOUT 5
61 DeviceList_t pUnownedDevList, pOwnedDevList;
62 static int transferDevIdx, ask = 1;
64 static FILE* client_open(const char *UNUSED_PARAM, const char *mode)
67 return fopen(DAT_DB_PATH, mode);
72 std::cout << "\nChoose an option:"<<std::endl;
73 std::cout << " 1. UnOwned Device discovery"<<std::endl;
74 std::cout << " 2. Owned Device discovery"<<std::endl;
75 std::cout << " 3. Ownership transfer"<<std::endl;
76 std::cout << " 4. Provision ACL"<<std::endl;
77 std::cout << " 5. Provision Credentials"<<std::endl;
78 std::cout << " 6. Credential & ACL provisioning b/w two devices"<<std::endl;
79 std::cout << " 7. Unlink Devices"<<std::endl;
80 std::cout << " 8. Remove Device"<<std::endl;
81 std::cout << " 9. Get Linked Devices"<<std::endl;
82 std::cout << " 10. Get Device Status"<<std::endl;
83 std::cout << " 11. Exit loop"<<std::endl;
86 void moveTransferredDevice()
88 pOwnedDevList.push_back(pUnownedDevList[transferDevIdx]);
89 pUnownedDevList.erase(pUnownedDevList.begin() + transferDevIdx);
92 void InputPinCB(char* pinBuf, size_t bufSize)
96 std::cout <<"INPUT PIN : ";
99 OICStrcpy(pinBuf, bufSize, ptr.c_str());
104 void printUuid(OicUuid_t uuid)
106 for (int i = 0; i < UUID_LENGTH; i++)
108 std::cout <<std::hex << uuid.id[i] << " ";
110 std::cout<<std::endl;
113 void ownershipTransferCB(PMResultList_t *result, int hasError)
117 std::cout << "Error!!! in OwnershipTransfer"<<std::endl;
121 std::cout<< "\nTransferred Ownership successfuly for device : ";
122 printUuid(result->at(0).deviceId);
125 moveTransferredDevice();
130 void printStatus(int status)
132 static std::map<int, std::string> devStatus = {{1<<0, DEV_STATUS_ON}, {1<<1, DEV_STATUS_OFF}};
134 std::cout <<devStatus[status] <<std::endl;
137 void printDevices(DeviceList_t &list)
139 for (unsigned int i = 0; i < list.size(); i++ )
141 std::cout << "Device "<< i+1 <<" ID: ";
142 std::cout << list[i]->getDeviceID() << " From IP: ";
143 std::cout << list[i]->getDevAddr() << std::endl;
148 * Callback function for provisioning ACL, Credentials.
150 * @param[in] result Result list
151 * @param[in] hasError indicates if the result has error
153 void provisionCB(PMResultList_t *result, int hasError)
157 std::cout << "Error in provisioning operation!"<<std::endl;
161 std::cout<< "\nReceived provisioning results: ";
162 for (unsigned int i = 0; i < result->size(); i++)
164 std::cout << "Result is = " << result->at(i).res <<" for device ";
165 printUuid(result->at(i).deviceId);
175 * Ask user with which devices it wants to make further actions.
176 * All possible error checks included.
177 * Default behavior in case if only one options leaves are included too.
178 * Expect that user count devices from 1, f.e. 1st, 2nd, 3rd, etc
179 * Use DeviceList_t instead of devicesCount because of print devices info
181 * @param[in] list owned devices list.
182 * @param[out] out device number array.
183 * @param[in] count how many device numbers need to read.
184 * @return 0 in case of success and other value otherwise.
186 int readDeviceNumber(DeviceList_t &list, int count, int *out)
188 if (out == NULL || count <= 0)
190 std::cout << "Error! Please put valid input parameters" << std::endl;
194 int devicesCount = list.size();
196 //Print current list of owned devices
197 std::cout <<"Owned devices, count = " << devicesCount << std::endl;
200 if (devicesCount < count)
202 std::cout << "You can't proceed with selected action because Owned devices count ( ";
203 std::cout << devicesCount << " ) are less then required devices ( " << count << " ).";
204 std::cout << "You may need to discover devices again" << std::endl;
208 std::cout << "Select " << count << " device(s) for provisioning" << std::endl;
210 for (int curr = 0; curr < count; curr++)
212 //select last device by default if only 1 option exist
213 //from user's point of view device counting starts from 1,
214 //so 1st, 2nd, 3rd, etc devices
215 if ((curr == count - 1) && (devicesCount == count))
218 for (int i = 0; i < curr; i++)
223 out[curr] = (count*(count+1))/2 - sum;
225 std::cout << "Device " << curr + 1 << " : " << out[curr];
226 std::cout << " - selected automatically (because no other options exist)" << std::endl;
231 std::cout << "Device " << curr + 1 << " : ";
234 if (choice < 1 || choice > devicesCount)
236 std::cout << "Error! You should enter valid device number!" << std::endl;
240 //check that user doesn't select the same device twice
241 for (int i = 0; i < curr; i++)
243 if (out[i] == choice)
245 std::cout << "Error! You cannot select the same device twice!" << std::endl;
253 //Users count devices from 1, so 1st, 2nd, 3rd, etc device
254 //But deviceList array start index is 0, so need to decrease all numbers to 1
255 for (int i = 0; i < count; i++) out[i] -= 1;
261 * Perform cleanup for ACL
264 static void deleteACL(OicSecAcl_t *acl)
268 /* Clean Resources */
269 for (unsigned int i = 0; i < (acl)->resourcesLen; i++)
271 OICFree((acl)->resources[i]);
273 OICFree((acl)->resources);
275 /* Clean ACL node itself */
276 /* Required only if acl was created in heap */
282 * Calculate ACL permission from string to bit
284 * @param[in] temp_psm Input data of ACL permission string
285 * @param[in,out] pms The pointer of ACL permission value
286 * @return 0 on success otherwise -1.
288 static int CalculateAclPermission(const char *temp_pms, uint16_t *pms)
292 if (NULL == temp_pms || NULL == pms)
297 while (temp_pms[i] != '\0')
346 * Get the ACL property from user
348 * @param[in] ACL Datastructure to save user inputs
349 * @return 0 on success otherwise -1.
351 static int InputACL(OicSecAcl_t *acl)
354 char *temp_id, *temp_rsc, *temp_pms;
356 printf("******************************************************************************\n");
357 printf("-Set ACL policy for target device\n");
358 printf("******************************************************************************\n");
360 printf("-URN identifying the subject\n");
361 printf("ex) 1111-1111-1111-1111 (16 Numbers except to '-')\n");
362 printf("Subject : ");
363 ret = scanf("%19ms", &temp_id);
367 for (int i = 0, j = 0; temp_id[i] != '\0'; i++)
369 if (DASH != temp_id[i])
370 acl->subject.id[j++] = temp_id[i];
376 printf("Error while input\n");
381 printf("Num. of Resource : ");
382 ret = scanf("%zu", &acl->resourcesLen);
383 if ((1 != ret) || (acl->resourcesLen <= 0 || acl->resourcesLen > 50))
385 printf("Error while input\n");
388 printf("-URI of resource\n");
389 printf("ex)/oic/sh/temp/0 (Max_URI_Length: 64 Byte )\n");
390 acl->resources = (char **)OICCalloc(acl->resourcesLen, sizeof(char *));
391 if (NULL == acl->resources)
393 OIC_LOG(ERROR, TAG, "Error while memory allocation");
396 for (size_t i = 0; i < acl->resourcesLen; i++)
398 printf("[%zu]Resource : ", i + 1);
399 ret = scanf("%64ms", &temp_rsc);
402 printf("Error while input\n");
406 acl->resources[i] = OICStrdup(temp_rsc);
408 if (NULL == acl->resources[i])
410 OIC_LOG(ERROR, TAG, "Error while memory allocation");
417 printf("-Set the permission(C,R,U,D,N)\n");
418 printf("ex) CRUDN, CRU_N,..(5 Charaters)\n");
419 printf("Permission : ");
420 ret = scanf("%5ms", &temp_pms);
423 printf("Error while input\n");
426 ret = CalculateAclPermission(temp_pms, &(acl->permission));
431 printf("-URN identifying the rowner\n");
432 printf("ex) 1111-1111-1111-1111 (16 Numbers except to '-')\n");
435 ret = scanf("%19ms", &temp_id);
438 printf("Error while input\n");
442 for (int k = 0, j = 0; temp_id[k] != '\0'; k++)
444 if (DASH != temp_id[k])
446 acl->rownerID.id[j++] = temp_id[k];
454 static int InputCredentials(Credential &cred)
460 std::cout << "Select credential type from following values:" << std::endl;
461 std::cout << "1: symmetric pair-wise key" << std::endl;
462 std::cout << "2: symmetric group key" << std::endl;
463 std::cout << "4: asymmetric key" << std::endl;
464 std::cout << "8: signed asymmetric key (aka certificate)" << std::endl;
465 std::cout << "16: PIN /password" << std::endl;
466 std::cout << "Your choice: ";
472 cred.setCredentialType(static_cast<OicSecCredType_t>(choice));
473 choice = 0; //validation of the accepted choice.
479 std::cout << "selected type is not supported yet" << std::endl;
482 std::cout << "Error! Please select valid credential type" << std::endl;
485 } while(0 != choice);
487 std::cout << "Please enter key size (valid size is 128 or 256) :";
492 cred.setCredentialKeySize(OWNER_PSK_LENGTH_128);
494 else if(256 == choice)
496 cred.setCredentialKeySize(OWNER_PSK_LENGTH_256);
500 std::cout << "Error! Please enter valid key size!" << std::endl;
509 OCPersistentStorage ps {client_open, fread, fwrite, fclose, unlink };
511 // Create PlatformConfig object
513 OC::ServiceType::InProc,
517 OC::QualityOfService::LowQos,
521 OCPlatform::Configure(cfg);
526 OicSecAcl_t *acl1 = nullptr, *acl2 = nullptr;
527 if (OCSecure::provisionInit("") != OC_STACK_OK)
529 std::cout <<"PM Init failed"<< std::endl;
533 for (int out = 0; !out;)
557 //Secure resource discovery.
559 pUnownedDevList.clear();
560 std::cout << "Started discovery..." <<std::endl;
561 OCStackResult result = OCSecure::discoverUnownedDevices(DISCOVERY_TIMEOUT,
563 if (result != OC_STACK_OK)
565 std::cout<< "!!Error - UnOwned Discovery failed."<<std::endl;
567 else if (pUnownedDevList.size())
569 std::cout <<"Found secure devices, count = " <<
570 pUnownedDevList.size() << std::endl;
571 printDevices(pUnownedDevList);
575 std::cout <<"No Secure devices found"<<std::endl;
581 pOwnedDevList.clear();
582 std::cout << "Started discovery..." <<std::endl;
583 OCStackResult result = OCSecure::discoverOwnedDevices(DISCOVERY_TIMEOUT,
585 if (result != OC_STACK_OK)
587 std::cout<< "!!Error - Owned Discovery failed."<<std::endl;
589 else if (pOwnedDevList.size())
591 std::cout <<"Found owned devices, count = " <<
592 pOwnedDevList.size() << std::endl;
593 printDevices(pOwnedDevList);
597 std::cout <<"No Secure devices found"<<std::endl;
605 if (!pUnownedDevList.size())
607 std::cout <<"There are no more Unowned devices"<<std::endl;
611 for (unsigned int i = 0; i < pUnownedDevList.size(); i++ )
613 std::cout << i+1 << ": "<< pUnownedDevList[i]->getDeviceID();
614 std::cout << " From IP:" << pUnownedDevList[i]->getDevAddr() <<std::endl;
617 std::cout <<"Select device number: "<<std::endl;
619 if (devNum > pUnownedDevList.size())
621 std::cout <<"Invalid device number"<<std::endl;
624 transferDevIdx = devNum - 1;
626 //register callbacks for JUST WORKS and PIN methods
627 std::cout <<"Registering OTM Methods: 1. JUST WORKS and 2. PIN"<<std::endl;
630 OTMCallbackData_t justWorksCBData;
631 justWorksCBData.loadSecretCB = LoadSecretJustWorksCallback;
632 justWorksCBData.createSecureSessionCB =
633 CreateSecureSessionJustWorksCallback;
634 justWorksCBData.createSelectOxmPayloadCB =
635 CreateJustWorksSelectOxmPayload;
636 justWorksCBData.createOwnerTransferPayloadCB =
637 CreateJustWorksOwnerTransferPayload;
638 OCSecure::setOwnerTransferCallbackData(OIC_JUST_WORKS,
639 &justWorksCBData, NULL);
643 OTMCallbackData_t pinBasedCBData;
644 pinBasedCBData.loadSecretCB = InputPinCodeCallback;
645 pinBasedCBData.createSecureSessionCB =
646 CreateSecureSessionRandomPinCallback;
647 pinBasedCBData.createSelectOxmPayloadCB =
648 CreatePinBasedSelectOxmPayload;
649 pinBasedCBData.createOwnerTransferPayloadCB =
650 CreatePinBasedOwnerTransferPayload;
651 OCSecure::setOwnerTransferCallbackData(OIC_RANDOM_DEVICE_PIN,
652 &pinBasedCBData, InputPinCB);
656 std::cout << "Transfering ownership for : "<<
657 pUnownedDevList[devNum-1]->getDeviceID()<<std::endl;
658 if (pUnownedDevList[devNum-1]->doOwnershipTransfer(ownershipTransferCB)
661 std::cout<<"OwnershipTransferCallback is failed"<<std::endl;
666 case 4: //Provision ACL
670 if (0 != readDeviceNumber(pOwnedDevList, 1, &index)) break;
672 std::cout << "Provision ACL for : "<<
673 pOwnedDevList[index]->getDeviceID()<< std::endl;
675 acl1 = (OicSecAcl_t *)OICCalloc(1,sizeof(OicSecAcl_t));
678 OIC_LOG(ERROR, TAG, "Error while memory allocation");
682 std::cout << "Please input ACL for selected device: " << std::endl;
683 if (0 != InputACL(acl1))
690 if (pOwnedDevList[index]->provisionACL(acl1, provisionCB) != OC_STACK_OK)
693 std::cout <<"provisionACL is failed"<< std::endl;
697 case 5: //Provision Credentials
701 if (0 != readDeviceNumber(pOwnedDevList, 2, devices)) break;
703 int first = devices[0];
704 int second = devices[1];
706 std::cout << "Provision Credentials to devices: "<<
707 pOwnedDevList[first]->getDeviceID();
708 std::cout << " and "<< pOwnedDevList[second]->getDeviceID() << std::endl;
710 Credential cred( NO_SECURITY_MODE ,0);
711 std::cout << "Please input credentials for selected devices: " << std::endl;
712 if (0 != InputCredentials(cred))
717 if (pOwnedDevList[first]->provisionCredentials(cred,
718 *pOwnedDevList[second].get(), provisionCB) != OC_STACK_OK)
721 std::cout <<"provisionCredentials is failed"<< std::endl;
725 case 6: //Provision ACL & Creds b/w two devices.
729 if (0 != readDeviceNumber(pOwnedDevList, 2, devices)) break;
731 int first = devices[0];
732 int second = devices[1];
734 std::cout << "Provision pairwise devices: "<<
735 pOwnedDevList[first]->getDeviceID();
736 std::cout << " and "<< pOwnedDevList[second]->getDeviceID() << std::endl;
738 Credential cred( NO_SECURITY_MODE, 0);
739 std::cout << "Please input credentials for selected devices: " << std::endl;
740 if (0 != InputCredentials(cred))
743 acl1 = (OicSecAcl_t *)OICCalloc(1,sizeof(OicSecAcl_t));
746 OIC_LOG(ERROR, TAG, "Error while memory allocation");
750 std::cout << "Please input ACL for selected device: " << std::endl;
751 if (0 != InputACL(acl1))
756 acl2 = (OicSecAcl_t *)OICCalloc(1,sizeof(OicSecAcl_t));
759 OIC_LOG(ERROR, TAG, "Error while memory allocation");
763 std::cout << "Please input ACL for selected device: " << std::endl;
764 if (0 != InputACL(acl2))
771 if (pOwnedDevList[first]->provisionPairwiseDevices(cred, acl1,
772 *pOwnedDevList[second].get(), acl2, provisionCB) != OC_STACK_OK)
775 std::cout <<"provisionPairwiseDevices is failed"<< std::endl;
779 case 7: //Unlink Devices
783 if (0 != readDeviceNumber(pOwnedDevList, 2, devices)) break;
785 int first = devices[0];
786 int second = devices[1];
788 std::cout << "Unlink devices: "<< pOwnedDevList[first]->getDeviceID();
789 std::cout << " and "<< pOwnedDevList[second]->getDeviceID() << std::endl;
793 if (pOwnedDevList[first]->unlinkDevices(*pOwnedDevList[second].get(),
794 provisionCB) != OC_STACK_OK)
797 std::cout <<"unlinkDevice is failed"<< std::endl;
801 case 8: //Remove Device
805 if (0 != readDeviceNumber(pOwnedDevList, 1, &index)) break;
807 std::cout << "Remove Device: "<< pOwnedDevList[index]->getDeviceID()<< std::endl;
811 if (pOwnedDevList[index]->removeDevice(DISCOVERY_TIMEOUT, provisionCB)
815 std::cout <<"removeDevice is failed"<< std::endl;
819 case 9: //Get Linked devices
821 UuidList_t linkedUuid;
824 if (!pOwnedDevList.size())
826 std::cout <<"There are no Owned devices yet,"
827 " may need to discover"<<std::endl;
831 for (unsigned int i = 0; i < pOwnedDevList.size(); i++ )
833 std::cout << i+1 << ": "<< pOwnedDevList[i]->getDeviceID() <<" From IP:";
834 std::cout << pOwnedDevList[i]->getDevAddr() <<std::endl;
837 std::cout <<"Select device number: "<<std::endl;
839 if (devNum > pOwnedDevList.size())
841 std::cout <<"Invalid device number"<<std::endl;
845 if(pOwnedDevList[devNum -1]->getLinkedDevices(linkedUuid) == OC_STACK_OK)
847 if (!linkedUuid.size())
849 std::cout <<"No devices are linked to "<<
850 pOwnedDevList[devNum -1]->getDeviceID() << std::endl;
852 //display the Linked devices (UUIDs)
853 for(unsigned int i = 0; i < linkedUuid.size(); i++)
855 printUuid(linkedUuid[i]);
860 std::cout <<"Error! in getLinkedDevices"<<std::endl;
864 case 10: //Get device' status
866 DeviceList_t unownedList, ownedList;
868 if (OCSecure::getDevInfoFromNetwork(DISCOVERY_TIMEOUT, ownedList,
869 unownedList) == OC_STACK_OK)
871 std::cout <<"Owned Device' status for" <<std::endl;
872 for (unsigned int i = 0; i < ownedList.size(); i++ )
874 std::cout << "Device "<<i+1 <<" ID: '";
875 std::cout << ownedList[i]->getDeviceID() << "' From IP: ";
876 std::cout << ownedList[i]->getDevAddr() << " Status: ";
877 printStatus(ownedList[i]->getDeviceStatus());
879 std::cout <<"\nUnOwned Device' status for" <<std::endl;
880 for (unsigned int i = 0; i < unownedList.size(); i++ )
882 std::cout << "Device "<<i+1 <<" ID: '";
883 std::cout << unownedList[i]->getDeviceID() << "' From IP: ";
884 std::cout << unownedList[i]->getDevAddr() << " Status: ";
885 printStatus(unownedList[i]->getDeviceStatus());
899 catch(OCException& e)
901 oclog() << "Exception in main: "<<e.what();