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 DEV_STATUS_ON "DEV_STATUS_ON"
54 #define DEV_STATUS_OFF "DEV_STATUS_OFF"
56 #define DISCOVERY_TIMEOUT 5
60 DeviceList_t pUnownedDevList, pOwnedDevList;
61 static int transferDevIdx, ask = 1;
63 static FILE* client_open(const char *UNUSED_PARAM, const char *mode)
66 return fopen(JSON_DB_PATH, mode);
71 std::cout << "\nChoose an option:"<<std::endl;
72 std::cout << " 1. UnOwned Device discovery"<<std::endl;
73 std::cout << " 2. Owned Device discovery"<<std::endl;
74 std::cout << " 3. Ownership transfer"<<std::endl;
75 std::cout << " 4. Provision ACL"<<std::endl;
76 std::cout << " 5. Provision Credentials"<<std::endl;
77 std::cout << " 6. Credential & ACL provisioning b/w two devices"<<std::endl;
78 std::cout << " 7. Unlink Devices"<<std::endl;
79 std::cout << " 8. Remove Device"<<std::endl;
80 std::cout << " 9. Get Linked Devices"<<std::endl;
81 std::cout << " 10. Get Device Status"<<std::endl;
82 std::cout << " 11. Exit loop"<<std::endl;
85 void moveTransferredDevice()
87 pOwnedDevList.push_back(pUnownedDevList[transferDevIdx]);
88 pUnownedDevList.erase(pUnownedDevList.begin() + transferDevIdx);
91 void InputPinCB(char* pinBuf, size_t bufSize)
95 std::cout <<"INPUT PIN : ";
98 OICStrcpy(pinBuf, bufSize, ptr.c_str());
103 void printUuid(OicUuid_t uuid)
105 for (int i = 0; i < UUID_LENGTH; i++)
107 std::cout <<std::hex << uuid.id[i] << " ";
109 std::cout<<std::endl;
112 void ownershipTransferCB(PMResultList_t *result, int hasError)
116 std::cout << "Error!!! in OwnershipTransfer"<<std::endl;
120 std::cout<< "\nTransferred Ownership successfuly for device : ";
121 printUuid(result->at(0).deviceId);
124 moveTransferredDevice();
129 void printStatus(int status)
131 static std::map<int, std::string> devStatus = {{1<<0, DEV_STATUS_ON}, {1<<1, DEV_STATUS_OFF}};
133 std::cout <<devStatus[status] <<std::endl;
136 void printDevices(DeviceList_t &list)
138 for (unsigned int i = 0; i < list.size(); i++ )
140 std::cout << "Device "<< i+1 <<" ID: ";
141 std::cout << list[i]->getDeviceID() << " From IP: ";
142 std::cout << list[i]->getDevAddr() << std::endl;
147 * Callback function for provisioning ACL, Credentials.
149 * @param[in] result Result list
150 * @param[in] hasError indicates if the result has error
152 void provisionCB(PMResultList_t *result, int hasError)
156 std::cout << "Error in provisioning operation!"<<std::endl;
160 std::cout<< "\nReceived provisioning results: ";
161 for (unsigned int i = 0; i < result->size(); i++)
163 std::cout << "Result is = " << result->at(i).res <<" for device ";
164 printUuid(result->at(i).deviceId);
174 * Ask user with which devices it wants to make further actions.
175 * All possible error checks included.
176 * Default behavior in case if only one options leaves are included too.
177 * Expect that user count devices from 1, f.e. 1st, 2nd, 3rd, etc
178 * Use DeviceList_t instead of devicesCount because of print devices info
180 * @param[in] list owned devices list.
181 * @param[out] out device number array.
182 * @param[in] count how many device numbers need to read.
183 * @return 0 in case of success and other value otherwise.
185 int readDeviceNumber(DeviceList_t &list, int count, int *out)
187 if (out == NULL || count <= 0)
189 std::cout << "Error! Please put valid input parameters" << std::endl;
193 int devicesCount = list.size();
195 //Print current list of owned devices
196 std::cout <<"Owned devices, count = " << devicesCount << std::endl;
199 if (devicesCount < count)
201 std::cout << "You can't proceed with selected action because Owned devices count ( ";
202 std::cout << devicesCount << " ) are less then required devices ( " << count << " ).";
203 std::cout << "You may need to discover devices again" << std::endl;
207 std::cout << "Select " << count << " device(s) for provisioning" << std::endl;
209 for (int curr = 0; curr < count; curr++)
211 //select last device by default if only 1 option exist
212 //from user's point of view device counting starts from 1,
213 //so 1st, 2nd, 3rd, etc devices
214 if ((curr == count - 1) && (devicesCount == count))
217 for (int i = 0; i < curr; i++)
222 out[curr] = (count*(count+1))/2 - sum;
224 std::cout << "Device " << curr + 1 << " : " << out[curr];
225 std::cout << " - selected automatically (because no other options exist)" << std::endl;
230 std::cout << "Device " << curr + 1 << " : ";
233 if (choice < 1 || choice > devicesCount)
235 std::cout << "Error! You should enter valid device number!" << std::endl;
239 //check that user doesn't select the same device twice
240 for (int i = 0; i < curr; i++)
242 if (out[i] == choice)
244 std::cout << "Error! You cannot select the same device twice!" << std::endl;
252 //Users count devices from 1, so 1st, 2nd, 3rd, etc device
253 //But deviceList array start index is 0, so need to decrease all numbers to 1
254 for (int i = 0; i < count; i++) out[i] -= 1;
260 * Perform cleanup for ACL
263 static void deleteACL(OicSecAcl_t *acl)
267 /* Clean Resources */
268 for (unsigned int i = 0; i < (acl)->resourcesLen; i++)
270 OICFree((acl)->resources[i]);
272 OICFree((acl)->resources);
275 OICFree((acl)->owners);
277 /* Clean ACL node itself */
278 /* Required only if acl was created in heap */
284 * Calculate ACL permission from string to bit
286 * @param[in] temp_psm Input data of ACL permission string
287 * @param[in,out] pms The pointer of ACL permission value
288 * @return 0 on success otherwise -1.
290 static int CalculateAclPermission(const char *temp_pms, uint16_t *pms)
294 if (NULL == temp_pms || NULL == pms)
299 while (temp_pms[i] != '\0')
348 * Get the ACL property from user
350 * @param[in] ACL Datastructure to save user inputs
351 * @return 0 on success otherwise -1.
353 static int InputACL(OicSecAcl_t *acl)
356 char *temp_id, *temp_rsc, *temp_pms;
358 printf("******************************************************************************\n");
359 printf("-Set ACL policy for target device\n");
360 printf("******************************************************************************\n");
362 printf("-URN identifying the subject\n");
363 printf("ex) 1111-1111-1111-1111 (16 Numbers except to '-')\n");
364 printf("Subject : ");
365 ret = scanf("%19ms", &temp_id);
369 for (int i = 0, j = 0; temp_id[i] != '\0'; i++)
371 if (DASH != temp_id[i])
372 acl->subject.id[j++] = temp_id[i];
378 printf("Error while input\n");
383 printf("Num. of Resource : ");
384 ret = scanf("%zu", &acl->resourcesLen);
385 printf("-URI of resource\n");
386 printf("ex)/oic/sh/temp/0 (Max_URI_Length: 64 Byte )\n");
387 acl->resources = (char **)OICCalloc(acl->resourcesLen, sizeof(char *));
388 if (NULL == acl->resources)
390 OIC_LOG(ERROR, TAG, "Error while memory allocation");
393 for (size_t i = 0; i < acl->resourcesLen; i++)
395 printf("[%zu]Resource : ", i + 1);
396 ret = scanf("%64ms", &temp_rsc);
399 printf("Error while input\n");
403 acl->resources[i] = OICStrdup(temp_rsc);
405 if (NULL == acl->resources[i])
407 OIC_LOG(ERROR, TAG, "Error while memory allocation");
414 printf("-Set the permission(C,R,U,D,N)\n");
415 printf("ex) CRUDN, CRU_N,..(5 Charaters)\n");
416 printf("Permission : ");
417 ret = scanf("%5ms", &temp_pms);
420 printf("Error while input\n");
423 ret = CalculateAclPermission(temp_pms, &(acl->permission));
428 printf("Num. of Rowner : ");
429 ret = scanf("%zu", &acl->ownersLen);
430 printf("-URN identifying the rowner\n");
431 printf("ex) 1111-1111-1111-1111 (16 Numbers except to '-')\n");
432 acl->owners = (OicUuid_t *)OICCalloc(acl->ownersLen, sizeof(OicUuid_t));
433 if (NULL == acl->owners)
435 OIC_LOG(ERROR, TAG, "Error while memory allocation");
438 for (size_t i = 0; i < acl->ownersLen; i++)
440 printf("[%zu]Rowner : ", i + 1);
441 ret = scanf("%19ms", &temp_id);
444 printf("Error while input\n");
448 for (int k = 0, j = 0; temp_id[k] != '\0'; k++)
450 if (DASH != temp_id[k])
452 acl->owners[i].id[j++] = temp_id[k];
460 static int InputCredentials(Credential &cred)
466 std::cout << "Select credential type from following values:" << std::endl;
467 std::cout << "1: symmetric pair-wise key" << std::endl;
468 std::cout << "2: symmetric group key" << std::endl;
469 std::cout << "4: asymmetric key" << std::endl;
470 std::cout << "8: signed asymmetric key (aka certificate)" << std::endl;
471 std::cout << "16: PIN /password" << std::endl;
472 std::cout << "Your choice: ";
478 cred.setCredentialType(static_cast<OicSecCredType_t>(choice));
479 choice = 0; //validation of the accepted choice.
485 std::cout << "selected type is not supported yet" << std::endl;
488 std::cout << "Error! Please select valid credential type" << std::endl;
491 } while(0 != choice);
493 std::cout << "Please enter key size (valid size is 128 or 256) :";
498 cred.setCredentialKeySize(OWNER_PSK_LENGTH_128);
500 else if(256 == choice)
502 cred.setCredentialKeySize(OWNER_PSK_LENGTH_256);
506 std::cout << "Error! Please enter valid key size!" << std::endl;
515 OCPersistentStorage ps {client_open, fread, fwrite, fclose, unlink };
517 // Create PlatformConfig object
519 OC::ServiceType::InProc,
523 OC::QualityOfService::LowQos,
527 OCPlatform::Configure(cfg);
532 OicSecAcl_t *acl1 = nullptr, *acl2 = nullptr;
533 if (OCSecure::provisionInit("") != OC_STACK_OK)
535 std::cout <<"PM Init failed"<< std::endl;
539 for (int out = 0; !out;)
563 //Secure resource discovery.
565 pUnownedDevList.clear();
566 std::cout << "Started discovery..." <<std::endl;
567 OCStackResult result = OCSecure::discoverUnownedDevices(DISCOVERY_TIMEOUT,
569 if (result != OC_STACK_OK)
571 std::cout<< "!!Error - UnOwned Discovery failed."<<std::endl;
573 else if (pUnownedDevList.size())
575 std::cout <<"Found secure devices, count = " <<
576 pUnownedDevList.size() << std::endl;
577 printDevices(pUnownedDevList);
581 std::cout <<"No Secure devices found"<<std::endl;
587 pOwnedDevList.clear();
588 std::cout << "Started discovery..." <<std::endl;
589 OCStackResult result = OCSecure::discoverOwnedDevices(DISCOVERY_TIMEOUT,
591 if (result != OC_STACK_OK)
593 std::cout<< "!!Error - Owned Discovery failed."<<std::endl;
595 else if (pOwnedDevList.size())
597 std::cout <<"Found owned devices, count = " <<
598 pOwnedDevList.size() << std::endl;
599 printDevices(pOwnedDevList);
603 std::cout <<"No Secure devices found"<<std::endl;
611 if (!pUnownedDevList.size())
613 std::cout <<"There are no more Unowned devices"<<std::endl;
617 for (unsigned int i = 0; i < pUnownedDevList.size(); i++ )
619 std::cout << i+1 << ": "<< pUnownedDevList[i]->getDeviceID();
620 std::cout << " From IP:" << pUnownedDevList[i]->getDevAddr() <<std::endl;
623 std::cout <<"Select device number: "<<std::endl;
625 if (devNum > pUnownedDevList.size())
627 std::cout <<"Invalid device number"<<std::endl;
630 transferDevIdx = devNum - 1;
632 //register callbacks for JUST WORKS and PIN methods
633 std::cout <<"Registering OTM Methods: 1. JUST WORKS and 2. PIN"<<std::endl;
636 OTMCallbackData_t justWorksCBData;
637 justWorksCBData.loadSecretCB = LoadSecretJustWorksCallback;
638 justWorksCBData.createSecureSessionCB =
639 CreateSecureSessionJustWorksCallback;
640 justWorksCBData.createSelectOxmPayloadCB =
641 CreateJustWorksSelectOxmPayload;
642 justWorksCBData.createOwnerTransferPayloadCB =
643 CreateJustWorksOwnerTransferPayload;
644 OCSecure::setOwnerTransferCallbackData(OIC_JUST_WORKS,
645 &justWorksCBData, NULL);
649 OTMCallbackData_t pinBasedCBData;
650 pinBasedCBData.loadSecretCB = InputPinCodeCallback;
651 pinBasedCBData.createSecureSessionCB =
652 CreateSecureSessionRandomPinCallbak;
653 pinBasedCBData.createSelectOxmPayloadCB =
654 CreatePinBasedSelectOxmPayload;
655 pinBasedCBData.createOwnerTransferPayloadCB =
656 CreatePinBasedOwnerTransferPayload;
657 OCSecure::setOwnerTransferCallbackData(OIC_RANDOM_DEVICE_PIN,
658 &pinBasedCBData, InputPinCB);
662 std::cout << "Transfering ownership for : "<<
663 pUnownedDevList[devNum-1]->getDeviceID()<<std::endl;
664 if (pUnownedDevList[devNum-1]->doOwnershipTransfer(ownershipTransferCB)
667 std::cout<<"OwnershipTransferCallback is failed"<<std::endl;
672 case 4: //Provision ACL
676 if (0 != readDeviceNumber(pOwnedDevList, 1, &index)) break;
678 std::cout << "Provision ACL for : "<<
679 pOwnedDevList[index]->getDeviceID()<< std::endl;
681 acl1 = (OicSecAcl_t *)OICCalloc(1,sizeof(OicSecAcl_t));
684 OIC_LOG(ERROR, TAG, "Error while memory allocation");
688 std::cout << "Please input ACL for selected device: " << std::endl;
689 if (0 != InputACL(acl1))
696 if (pOwnedDevList[index]->provisionACL(acl1, provisionCB) != OC_STACK_OK)
699 std::cout <<"provisionACL is failed"<< std::endl;
703 case 5: //Provision Credentials
707 if (0 != readDeviceNumber(pOwnedDevList, 2, devices)) break;
709 int first = devices[0];
710 int second = devices[1];
712 std::cout << "Provision Credentials to devices: "<<
713 pOwnedDevList[first]->getDeviceID();
714 std::cout << " and "<< pOwnedDevList[second]->getDeviceID() << std::endl;
716 Credential cred( NO_SECURITY_MODE ,0);
717 std::cout << "Please input credentials for selected devices: " << std::endl;
718 if (0 != InputCredentials(cred))
723 if (pOwnedDevList[first]->provisionCredentials(cred,
724 *pOwnedDevList[second].get(), provisionCB) != OC_STACK_OK)
727 std::cout <<"provisionCredentials is failed"<< std::endl;
731 case 6: //Provision ACL & Creds b/w two devices.
735 if (0 != readDeviceNumber(pOwnedDevList, 2, devices)) break;
737 int first = devices[0];
738 int second = devices[1];
740 std::cout << "Provision pairwise devices: "<<
741 pOwnedDevList[first]->getDeviceID();
742 std::cout << " and "<< pOwnedDevList[second]->getDeviceID() << std::endl;
744 Credential cred( NO_SECURITY_MODE, 0);
745 std::cout << "Please input credentials for selected devices: " << std::endl;
746 if (0 != InputCredentials(cred))
749 acl1 = (OicSecAcl_t *)OICCalloc(1,sizeof(OicSecAcl_t));
752 OIC_LOG(ERROR, TAG, "Error while memory allocation");
756 std::cout << "Please input ACL for selected device: " << std::endl;
757 if (0 != InputACL(acl1))
762 acl2 = (OicSecAcl_t *)OICCalloc(1,sizeof(OicSecAcl_t));
765 OIC_LOG(ERROR, TAG, "Error while memory allocation");
769 std::cout << "Please input ACL for selected device: " << std::endl;
770 if (0 != InputACL(acl2))
777 if (pOwnedDevList[first]->provisionPairwiseDevices(cred, acl1,
778 *pOwnedDevList[second].get(), acl2, provisionCB) != OC_STACK_OK)
781 std::cout <<"provisionPairwiseDevices is failed"<< std::endl;
785 case 7: //Unlink Devices
789 if (0 != readDeviceNumber(pOwnedDevList, 2, devices)) break;
791 int first = devices[0];
792 int second = devices[1];
794 std::cout << "Unlink devices: "<< pOwnedDevList[first]->getDeviceID();
795 std::cout << " and "<< pOwnedDevList[second]->getDeviceID() << std::endl;
799 if (pOwnedDevList[first]->unlinkDevices(*pOwnedDevList[second].get(),
800 provisionCB) != OC_STACK_OK)
803 std::cout <<"unlinkDevice is failed"<< std::endl;
807 case 8: //Remove Device
811 if (0 != readDeviceNumber(pOwnedDevList, 1, &index)) break;
813 std::cout << "Remove Device: "<< pOwnedDevList[index]->getDeviceID()<< std::endl;
817 if (pOwnedDevList[index]->removeDevice(DISCOVERY_TIMEOUT, provisionCB)
821 std::cout <<"removeDevice is failed"<< std::endl;
825 case 9: //Get Linked devices
827 UuidList_t linkedUuid;
830 if (!pOwnedDevList.size())
832 std::cout <<"There are no Owned devices yet,"
833 " may need to discover"<<std::endl;
837 for (unsigned int i = 0; i < pOwnedDevList.size(); i++ )
839 std::cout << i+1 << ": "<< pOwnedDevList[i]->getDeviceID() <<" From IP:";
840 std::cout << pOwnedDevList[i]->getDevAddr() <<std::endl;
843 std::cout <<"Select device number: "<<std::endl;
845 if (devNum > pOwnedDevList.size())
847 std::cout <<"Invalid device number"<<std::endl;
851 if(pOwnedDevList[devNum -1]->getLinkedDevices(linkedUuid) == OC_STACK_OK)
853 if (!linkedUuid.size())
855 std::cout <<"No devices are linked to "<<
856 pOwnedDevList[devNum -1]->getDeviceID() << std::endl;
858 //display the Linked devices (UUIDs)
859 for(unsigned int i = 0; i < linkedUuid.size(); i++)
861 printUuid(linkedUuid[i]);
866 std::cout <<"Error! in getLinkedDevices"<<std::endl;
870 case 10: //Get device' status
872 DeviceList_t unownedList, ownedList;
874 if (OCSecure::getDevInfoFromNetwork(DISCOVERY_TIMEOUT, ownedList,
875 unownedList) == OC_STACK_OK)
877 std::cout <<"Owned Device' status for" <<std::endl;
878 for (unsigned int i = 0; i < ownedList.size(); i++ )
880 std::cout << "Device "<<i+1 <<" ID: '";
881 std::cout << ownedList[i]->getDeviceID() << "' From IP: ";
882 std::cout << ownedList[i]->getDevAddr() << " Status: ";
883 printStatus(ownedList[i]->getDeviceStatus());
885 std::cout <<"\nUnOwned Device' status for" <<std::endl;
886 for (unsigned int i = 0; i < unownedList.size(); i++ )
888 std::cout << "Device "<<i+1 <<" ID: '";
889 std::cout << unownedList[i]->getDeviceID() << "' From IP: ";
890 std::cout << unownedList[i]->getDevAddr() << " Status: ";
891 printStatus(unownedList[i]->getDeviceStatus());
905 catch(OCException& e)
907 oclog() << "Exception in main: "<<e.what();