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 * *****************************************************************/
21 // Defining _POSIX_C_SOURCE macro with 199309L (or greater) as value
22 // causes header files to expose definitions
23 // corresponding to the POSIX.1b, Real-time extensions
24 // (IEEE Std 1003.1b-1993) specification
26 // For this specific file, see use of clock_gettime,
27 // Refer to http://pubs.opengroup.org/stage7tc1/functions/clock_gettime.html
28 // and to http://man7.org/linux/man-pages/man2/clock_gettime.2.html
29 #ifndef _POSIX_C_SOURCE
30 #define _POSIX_C_SOURCE 200809L
33 #include "iotivity_config.h"
40 #ifdef HAVE_SYS_TIME_H
47 #include "oic_malloc.h"
48 #include "oic_string.h"
50 #include "cainterface.h"
56 #include "srmresourcestrings.h"
57 #include "doxmresource.h"
58 #include "pstatresource.h"
59 #include "credresource.h"
60 #include "aclresource.h"
61 #include "ownershiptransfermanager.h"
62 #include "securevirtualresourcetypes.h"
63 #include "oxmjustworks.h"
65 #include "pmutility.h"
66 #include "srmutility.h"
67 #include "provisioningdatabasemanager.h"
68 #include "oxmrandompin.h"
69 #include "ocpayload.h"
70 #include "payload_logging.h"
75 * Array to store the callbacks for each owner transfer method.
77 static OTMCallbackData_t g_OTMDatas[OIC_OXM_COUNT];
80 * Variables for pointing the OTMContext to be used in the DTLS handshake result callback.
82 static OTMContext_t* g_otmCtx = NULL;
85 * Function to select appropriate provisioning method.
87 * @param[in] supportedMethods Array of supported methods
88 * @param[in] numberOfMethods number of supported methods
89 * @param[out] selectedMethod Selected methods
90 * @return OC_STACK_OK on success
92 static OCStackResult SelectProvisioningMethod(const OicSecOxm_t *supportedMethods,
93 size_t numberOfMethods, OicSecOxm_t *selectedMethod)
95 OIC_LOG(DEBUG, TAG, "IN SelectProvisioningMethod");
97 if(numberOfMethods == 0 || !supportedMethods)
99 OIC_LOG(WARNING, TAG, "Could not find a supported OxM.");
100 return OC_STACK_ERROR;
103 *selectedMethod = supportedMethods[0];
104 for(size_t i = 0; i < numberOfMethods; i++)
106 if(*selectedMethod < supportedMethods[i])
108 *selectedMethod = supportedMethods[i];
116 * Function to select operation mode.This function will return most secure common operation mode.
118 * @param[in] selectedDeviceInfo selected device information to performing provisioning.
119 * @param[out] selectedMode selected operation mode
120 * @return OC_STACK_OK on success
122 static void SelectOperationMode(const OCProvisionDev_t *selectedDeviceInfo,
123 OicSecDpom_t *selectedMode)
125 OIC_LOG(DEBUG, TAG, "IN SelectOperationMode");
126 *selectedMode = selectedDeviceInfo->pstat->sm[0];
127 OIC_LOG_V(DEBUG, TAG, "Selected Operation Mode = %d", *selectedMode);
131 * Function to start ownership transfer.
132 * This function will send the first request for provisioning,
133 * The next request message is sent from the response handler for this request.
135 * @param[in] ctx context value passed to callback from calling function.
136 * @param[in] selectedDevice selected device information to performing provisioning.
137 * @return OC_STACK_OK on success
139 static OCStackResult StartOwnershipTransfer(void* ctx, OCProvisionDev_t* selectedDevice);
142 * Function to update owner transfer mode
144 * @param[in] otmCtx Context value of ownership transfer.
145 * @return OC_STACK_OK on success
147 static OCStackResult PostOwnerTransferModeToResource(OTMContext_t* otmCtx);
150 * Function to send request to resource to get its pstat resource information.
152 * @param[in] otmCtx Context value of ownership transfer.
153 * @return OC_STACK_OK on success
155 static OCStackResult GetProvisioningStatusResource(OTMContext_t* otmCtx);
159 * Function to send uuid of owner device to new device.
160 * This function would update 'owner of doxm' as UUID for provisioning tool.
162 * @param[in] otmCtx Context value of ownership transfer.
163 * @return OC_STACK_OK on success
165 static OCStackResult PostOwnerUuid(OTMContext_t* otmCtx);
168 * Function to update the operation mode. As per the spec. Operation mode in client driven
169 * single service provisioning it will be updated to 0x3
171 * @param[in] otmCtx Context value of ownership transfer.
172 * @return OC_STACK_OK on success
174 static OCStackResult PostUpdateOperationMode(OTMContext_t* otmCtx);
177 * Function to update the owner credential to new device
179 * @param[in] otmCtx Context value of ownership transfer.
180 * @param[in] selectedOperationMode selected operation mode
181 * @return OC_STACK_OK on success
183 static OCStackResult PostOwnerCredential(OTMContext_t* otmCtx);
186 * Function to update the owner ACL to new device.
188 * @param[in] otmCtx Context value of ownership transfer.
189 * @return OC_STACK_OK on success
191 static OCStackResult PostOwnerAcl(OTMContext_t* otmCtx);
194 * Function to send ownerShip info.
195 * This function would update 'owned of doxm' as true.
197 * @param[in] otmCtx Context value of ownership transfer.
198 * @return OC_STACK_OK on success
200 static OCStackResult PostOwnershipInformation(OTMContext_t* otmCtx);
203 * Function to update pstat as Ready for provisioning.
204 * This function would update 'cm' from bx0000,0010 to bx0000,0000.
206 * @param[in] ctx context value passed to callback from calling function.
207 * @param[in] selectedDevice selected device information to performing provisioning.
208 * @return OC_STACK_OK on success
210 static OCStackResult PostProvisioningStatus(OTMContext_t* otmCtx);
213 * Function to update pstat as Ready for Normal Operation.
214 * This function would update 'isop' from false to true.
216 * @param[in] ctx context value passed to callback from calling function.
217 * @param[in] selectedDevice selected device information to performing provisioning.
218 * @return OC_STACK_OK on success
220 static OCStackResult PostNormalOperationStatus(OTMContext_t* otmCtx);
222 static bool IsComplete(OTMContext_t* otmCtx)
224 for(size_t i = 0; i < otmCtx->ctxResultArraySize; i++)
226 if(OC_STACK_CONTINUE == otmCtx->ctxResultArray[i].res)
236 * Function to save the result of provisioning.
238 * @param[in,out] otmCtx Context value of ownership transfer.
239 * @param[in] res result of provisioning
241 static void SetResult(OTMContext_t* otmCtx, const OCStackResult res)
243 OIC_LOG_V(DEBUG, TAG, "IN SetResult : %d ", res);
247 OIC_LOG(WARNING, TAG, "OTMContext is NULL");
251 if(otmCtx->selectedDeviceInfo)
253 //Revert psk_info callback and new deivce uuid in case of random PIN OxM
254 if(OIC_RANDOM_DEVICE_PIN == otmCtx->selectedDeviceInfo->doxm->oxmSel)
256 if(CA_STATUS_OK != CAregisterPskCredentialsHandler(GetDtlsPskCredentials))
258 OIC_LOG(WARNING, TAG, "Failed to revert is DTLS credential handler.");
260 OicUuid_t emptyUuid = { .id={0}};
261 SetUuidForRandomPinOxm(&emptyUuid);
264 for(size_t i = 0; i < otmCtx->ctxResultArraySize; i++)
266 if(memcmp(otmCtx->selectedDeviceInfo->doxm->deviceID.id,
267 otmCtx->ctxResultArray[i].deviceId.id, UUID_LENGTH) == 0)
269 otmCtx->ctxResultArray[i].res = res;
270 if(OC_STACK_OK != res)
272 otmCtx->ctxHasError = true;
279 //If all request is completed, invoke the user callback.
280 if(IsComplete(otmCtx))
282 otmCtx->ctxResultCallback(otmCtx->userCtx, otmCtx->ctxResultArraySize,
283 otmCtx->ctxResultArray, otmCtx->ctxHasError);
284 OICFree(otmCtx->ctxResultArray);
289 if(OC_STACK_OK != StartOwnershipTransfer(otmCtx,
290 otmCtx->selectedDeviceInfo->next))
292 OIC_LOG(ERROR, TAG, "Failed to StartOwnershipTransfer");
297 OIC_LOG(DEBUG, TAG, "OUT SetResult");
301 * Function to handle the handshake result in OTM.
302 * This function will be invoked after DTLS handshake
303 * @param endPoint [IN] The remote endpoint.
304 * @param errorInfo [IN] Error information from the endpoint.
307 void DTLSHandshakeCB(const CAEndpoint_t *endpoint, const CAErrorInfo_t *info)
309 if(NULL != g_otmCtx && NULL != g_otmCtx->selectedDeviceInfo &&
310 NULL != endpoint && NULL != info)
312 OIC_LOG_V(INFO, TAG, "Received status from remote device(%s:%d) : %d",
313 endpoint->addr, endpoint->port, info->result);
315 OicSecDoxm_t* newDevDoxm = g_otmCtx->selectedDeviceInfo->doxm;
317 if(NULL != newDevDoxm)
319 OicUuid_t emptyUuid = {.id={0}};
321 //Make sure the address matches.
322 if(strncmp(g_otmCtx->selectedDeviceInfo->endpoint.addr,
324 sizeof(endpoint->addr)) == 0 &&
325 g_otmCtx->selectedDeviceInfo->securePort == endpoint->port)
327 OCStackResult res = OC_STACK_ERROR;
329 //If temporal secure sesstion established successfully
330 if(CA_STATUS_OK == info->result &&
331 false == newDevDoxm->owned &&
332 memcmp(&(newDevDoxm->owner), &emptyUuid, sizeof(OicUuid_t)) == 0)
334 //Send request : POST /oic/sec/doxm [{... , "devowner":"PT's UUID"}]
335 res = PostOwnerUuid(g_otmCtx);
336 if(OC_STACK_OK != res)
338 OIC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to send owner information");
339 SetResult(g_otmCtx, res);
342 //In case of authentication failure
343 else if(CA_DTLS_AUTHENTICATION_FAILURE == info->result)
345 //in case of error from owner credential
346 if(memcmp(&(newDevDoxm->owner), &emptyUuid, sizeof(OicUuid_t)) != 0 &&
347 true == newDevDoxm->owned)
349 OIC_LOG(ERROR, TAG, "The owner credential may incorrect.");
351 if(OC_STACK_OK != RemoveCredential(&(newDevDoxm->deviceID)))
353 OIC_LOG(WARNING, TAG, "Failed to remove the invaild owner credential");
355 SetResult(g_otmCtx, OC_STACK_AUTHENTICATION_FAILURE);
357 //in case of error from wrong PIN, re-start the ownership transfer
358 else if(OIC_RANDOM_DEVICE_PIN == newDevDoxm->oxmSel)
360 OIC_LOG(ERROR, TAG, "The PIN number may incorrect.");
362 memcpy(&(newDevDoxm->owner), &emptyUuid, sizeof(OicUuid_t));
363 newDevDoxm->owned = false;
364 g_otmCtx->attemptCnt++;
366 if(WRONG_PIN_MAX_ATTEMP > g_otmCtx->attemptCnt)
368 res = StartOwnershipTransfer(g_otmCtx, g_otmCtx->selectedDeviceInfo);
369 if(OC_STACK_OK != res)
371 SetResult(g_otmCtx, res);
372 OIC_LOG(ERROR, TAG, "Failed to Re-StartOwnershipTransfer");
377 OIC_LOG(ERROR, TAG, "User has exceeded the number of authentication attempts.");
378 SetResult(g_otmCtx, OC_STACK_AUTHENTICATION_FAILURE);
383 OIC_LOG(ERROR, TAG, "Failed to establish secure session.");
384 SetResult(g_otmCtx, OC_STACK_AUTHENTICATION_FAILURE);
393 * Function to save ownerPSK at provisioning tool end.
395 * @param[in] selectedDeviceInfo selected device information to performing provisioning.
396 * @return OC_STACK_OK on success
398 static OCStackResult SaveOwnerPSK(OCProvisionDev_t *selectedDeviceInfo)
400 OIC_LOG(DEBUG, TAG, "IN SaveOwnerPSK");
402 OCStackResult res = OC_STACK_ERROR;
404 CAEndpoint_t endpoint;
405 memset(&endpoint, 0x00, sizeof(CAEndpoint_t));
406 OICStrcpy(endpoint.addr, MAX_ADDR_STR_SIZE_CA, selectedDeviceInfo->endpoint.addr);
407 endpoint.addr[MAX_ADDR_STR_SIZE_CA - 1] = '\0';
408 endpoint.port = selectedDeviceInfo->securePort;
409 endpoint.adapter = selectedDeviceInfo->endpoint.adapter;
411 OicUuid_t ptDeviceID = {.id={0}};
412 if (OC_STACK_OK != GetDoxmDeviceID(&ptDeviceID))
414 OIC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
418 uint8_t ownerPSK[OWNER_PSK_LENGTH_128] = {0};
419 OicSecKey_t ownerKey = {ownerPSK, OWNER_PSK_LENGTH_128};
421 //Generating OwnerPSK
422 CAResult_t pskRet = CAGenerateOwnerPSK(&endpoint,
423 (uint8_t *)GetOxmString(selectedDeviceInfo->doxm->oxmSel),
424 strlen(GetOxmString(selectedDeviceInfo->doxm->oxmSel)),
425 ptDeviceID.id, sizeof(ptDeviceID.id),
426 selectedDeviceInfo->doxm->deviceID.id, sizeof(selectedDeviceInfo->doxm->deviceID.id),
427 ownerPSK, OWNER_PSK_LENGTH_128);
429 if (CA_STATUS_OK == pskRet)
431 OIC_LOG(INFO, TAG,"ownerPSK dump:\n");
432 OIC_LOG_BUFFER(INFO, TAG,ownerPSK, OWNER_PSK_LENGTH_128);
433 //Generating new credential for provisioning tool
434 OicSecCred_t *cred = GenerateCredential(&selectedDeviceInfo->doxm->deviceID,
435 SYMMETRIC_PAIR_WISE_KEY, NULL,
436 &ownerKey, &ptDeviceID);
437 VERIFY_NON_NULL(TAG, cred, ERROR);
439 // TODO: Added as workaround. Will be replaced soon.
440 cred->privateData.encoding = OIC_ENCODING_RAW;
443 // NOTE: Test codes to use BASE64 encoded owner PSK.
444 uint32_t outSize = 0;
445 size_t b64BufSize = B64ENCODE_OUT_SAFESIZE((OWNER_PSK_LENGTH_128 + 1));
446 char* b64Buf = (uint8_t *)OICCalloc(1, b64BufSize);
447 VERIFY_NON_NULL(TAG, b64Buf, ERROR);
448 b64Encode(cred->privateData.data, cred->privateData.len, b64Buf, b64BufSize, &outSize);
450 OICFree( cred->privateData.data );
451 cred->privateData.data = (uint8_t *)OICCalloc(1, outSize + 1);
452 VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
454 strncpy(cred->privateData.data, b64Buf, outSize);
455 cred->privateData.data[outSize] = '\0';
456 cred->privateData.encoding = OIC_ENCODING_BASE64;
457 cred->privateData.len = outSize;
459 #endif //End of Test codes
461 //Finding previous ownerPSK.
462 const OicSecCred_t* credList = GetCredList();
463 OicSecCred_t* prevCred = NULL;
465 LL_FOREACH(credList, prevCred)
467 //OwnerPSK's type is SYMMETRIC_PAIR_WISE_KEY
468 if (SYMMETRIC_PAIR_WISE_KEY == prevCred->credType &&
469 0 == memcmp(prevCred->subject.id, cred->subject.id, sizeof(cred->subject.id)))
471 credId = prevCred->credId;
476 //If duplicate owner PSK is exists, remove it.
479 OIC_LOG(WARNING, TAG, "Duplicate OwnerPSK was detected.");
480 OIC_LOG(WARNING, TAG, "[Subject] : ");
481 OIC_LOG_BUFFER(WARNING, TAG, prevCred->subject.id, sizeof(prevCred->subject.id));
482 OIC_LOG_V(WARNING, TAG, "[Encoding Type] : %d", prevCred->privateData.encoding);
483 OIC_LOG(WARNING, TAG, "[Private Data] : ");
484 OIC_LOG_BUFFER(WARNING, TAG, prevCred->privateData.data, prevCred->privateData.len);
485 OIC_LOG(WARNING, TAG, "Previous OwnerPSK will be removed.");
487 res = RemoveCredentialByCredId(credId);
488 if(OC_STACK_RESOURCE_DELETED != res)
490 OIC_LOG(ERROR, TAG, "Failed to remove the previous OwnerPSK");
491 DeleteCredList(cred);
496 res = AddCredential(cred);
497 if(res != OC_STACK_OK)
499 DeleteCredList(cred);
505 OIC_LOG(ERROR, TAG, "CAGenerateOwnerPSK failed");
508 OIC_LOG(DEBUG, TAG, "OUT SaveOwnerPSK");
514 * Callback handler for OwnerShipTransferModeHandler API.
516 * @param[in] ctx ctx value passed to callback from calling function.
517 * @param[in] UNUSED handle to an invocation
518 * @param[in] clientResponse Response from queries to remote servers.
519 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
520 * and OC_STACK_KEEP_TRANSACTION to keep it.
522 static OCStackApplicationResult OwnerTransferModeHandler(void *ctx, OCDoHandle UNUSED,
523 OCClientResponse *clientResponse)
525 OIC_LOG(DEBUG, TAG, "IN OwnerTransferModeHandler");
527 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
528 VERIFY_NON_NULL(TAG, ctx, WARNING);
530 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
532 if (OC_STACK_RESOURCE_CHANGED == clientResponse->result)
534 OIC_LOG(INFO, TAG, "OwnerTransferModeHandler : response result = OC_STACK_OK");
535 //Send request : GET /oic/sec/pstat
536 OCStackResult res = GetProvisioningStatusResource(otmCtx);
537 if(OC_STACK_OK != res)
539 OIC_LOG(WARNING, TAG, "Failed to get pstat information");
540 SetResult(otmCtx, res);
545 OIC_LOG_V(WARNING, TAG, "OwnerTransferModeHandler : Client response is incorrect : %d",
546 clientResponse->result);
547 SetResult(otmCtx, clientResponse->result);
550 OIC_LOG(DEBUG, TAG, "OUT OwnerTransferModeHandler");
553 return OC_STACK_DELETE_TRANSACTION;
557 * Callback handler for ProvisioningStatusResouceHandler API.
559 * @param[in] ctx ctx value passed to callback from calling function.
560 * @param[in] UNUSED handle to an invocation
561 * @param[in] clientResponse Response from queries to remote servers.
562 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
563 * and OC_STACK_KEEP_TRANSACTION to keep it.
565 static OCStackApplicationResult ListMethodsHandler(void *ctx, OCDoHandle UNUSED,
566 OCClientResponse *clientResponse)
568 OIC_LOG(DEBUG, TAG, "IN ListMethodsHandler");
570 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
571 VERIFY_NON_NULL(TAG, ctx, WARNING);
573 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
575 if (OC_STACK_OK == clientResponse->result)
577 if (NULL == clientResponse->payload)
579 OIC_LOG(INFO, TAG, "Skiping Null payload");
580 SetResult(otmCtx, OC_STACK_ERROR);
581 return OC_STACK_DELETE_TRANSACTION;
584 if (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)
586 OIC_LOG(INFO, TAG, "Unknown payload type");
587 SetResult(otmCtx, OC_STACK_ERROR);
588 return OC_STACK_DELETE_TRANSACTION;
590 OicSecPstat_t* pstat = NULL;
591 OCStackResult result = CBORPayloadToPstat(
592 ((OCSecurityPayload*)clientResponse->payload)->securityData,
593 ((OCSecurityPayload*)clientResponse->payload)->payloadSize,
595 if(NULL == pstat || result != OC_STACK_OK)
597 OIC_LOG(ERROR, TAG, "Error while converting cbor to pstat.");
598 SetResult(otmCtx, OC_STACK_ERROR);
599 return OC_STACK_DELETE_TRANSACTION;
601 if(false == (TAKE_OWNER & pstat->cm))
603 OIC_LOG(ERROR, TAG, "Device pairing mode enabling owner transfer operations is disabled");
604 SetResult(otmCtx, OC_STACK_ERROR);
605 return OC_STACK_DELETE_TRANSACTION;
607 otmCtx->selectedDeviceInfo->pstat = pstat;
609 //Select operation mode (Currently supported SINGLE_SERVICE_CLIENT_DRIVEN only)
610 SelectOperationMode(otmCtx->selectedDeviceInfo, &(otmCtx->selectedDeviceInfo->pstat->om));
612 //Send request : POST /oic/sec/pstat [{"om":"bx11", .. }]
613 OCStackResult res = PostUpdateOperationMode(otmCtx);
614 if (OC_STACK_OK != res)
616 OIC_LOG(ERROR, TAG, "Error while updating operation mode.");
617 SetResult(otmCtx, res);
622 OIC_LOG_V(WARNING, TAG, "ListMethodsHandler : Client response is incorrect : %d",
623 clientResponse->result);
624 SetResult(otmCtx, clientResponse->result);
627 OIC_LOG(DEBUG, TAG, "OUT ListMethodsHandler");
629 return OC_STACK_DELETE_TRANSACTION;
633 * Response handler for update owner uuid request.
635 * @param[in] ctx ctx value passed to callback from calling function.
636 * @param[in] UNUSED handle to an invocation
637 * @param[in] clientResponse Response from queries to remote servers.
638 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
639 * and OC_STACK_KEEP_TRANSACTION to keep it.
641 static OCStackApplicationResult OwnerUuidUpdateHandler(void *ctx, OCDoHandle UNUSED,
642 OCClientResponse *clientResponse)
644 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
645 VERIFY_NON_NULL(TAG, ctx, WARNING);
647 OIC_LOG(DEBUG, TAG, "IN OwnerUuidUpdateHandler");
649 OCStackResult res = OC_STACK_OK;
650 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
652 if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
654 if(otmCtx && otmCtx->selectedDeviceInfo)
656 res = SaveOwnerPSK(otmCtx->selectedDeviceInfo);
657 if(OC_STACK_OK != res)
659 OIC_LOG(ERROR, TAG, "OwnerUuidUpdateHandler:Failed to owner PSK generation");
660 SetResult(otmCtx, res);
661 return OC_STACK_DELETE_TRANSACTION;
664 //POST owner credential to new device according to security spec B.
665 res = PostOwnerCredential(otmCtx);
666 if(OC_STACK_OK != res)
669 "OwnerUuidUpdateHandler:Failed to send PosT request for onwer credential");
670 SetResult(otmCtx, res);
671 return OC_STACK_DELETE_TRANSACTION;
677 res = clientResponse->result;
678 OIC_LOG_V(ERROR, TAG, "OwnerUuidHandler : Unexpected result %d", res);
679 SetResult(otmCtx, res);
682 OIC_LOG(DEBUG, TAG, "OUT OwnerUuidUpdateHandler");
685 return OC_STACK_DELETE_TRANSACTION;
689 * Response handler for update operation mode.
691 * @param[in] ctx ctx value passed to callback from calling function.
692 * @param[in] UNUSED handle to an invocation
693 * @param[in] clientResponse Response from queries to remote servers.
694 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
695 * and OC_STACK_KEEP_TRANSACTION to keep it.
697 static OCStackApplicationResult OperationModeUpdateHandler(void *ctx, OCDoHandle UNUSED,
698 OCClientResponse *clientResponse)
700 OIC_LOG(DEBUG, TAG, "IN OperationModeUpdateHandler");
702 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
703 VERIFY_NON_NULL(TAG, ctx, WARNING);
705 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
707 if (OC_STACK_RESOURCE_CHANGED == clientResponse->result)
709 OCStackResult res = OC_STACK_ERROR;
710 OicSecOxm_t selOxm = otmCtx->selectedDeviceInfo->doxm->oxmSel;
712 //Load secret for temporal secure session.
713 if(g_OTMDatas[selOxm].loadSecretCB)
715 res = g_OTMDatas[selOxm].loadSecretCB(otmCtx);
716 if(OC_STACK_OK != res)
718 OIC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to load secret");
719 SetResult(otmCtx, res);
720 return OC_STACK_DELETE_TRANSACTION;
724 //It will be used in handshake event handler
727 //Try DTLS handshake to generate secure session
728 if(g_OTMDatas[selOxm].createSecureSessionCB)
730 res = g_OTMDatas[selOxm].createSecureSessionCB(otmCtx);
731 if(OC_STACK_OK != res)
733 OIC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to create DTLS session");
734 SetResult(otmCtx, res);
735 return OC_STACK_DELETE_TRANSACTION;
741 OIC_LOG(ERROR, TAG, "Error while update operation mode");
742 SetResult(otmCtx, clientResponse->result);
745 OIC_LOG(DEBUG, TAG, "OUT OperationModeUpdateHandler");
748 return OC_STACK_DELETE_TRANSACTION;
752 * Response handler for update owner crendetial request.
754 * @param[in] ctx ctx value passed to callback from calling function.
755 * @param[in] UNUSED handle to an invocation
756 * @param[in] clientResponse Response from queries to remote servers.
757 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
758 * and OC_STACK_KEEP_TRANSACTION to keep it.
760 static OCStackApplicationResult OwnerCredentialHandler(void *ctx, OCDoHandle UNUSED,
761 OCClientResponse *clientResponse)
763 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
764 VERIFY_NON_NULL(TAG, ctx, WARNING);
766 OIC_LOG(DEBUG, TAG, "IN OwnerCredentialHandler");
768 OCStackResult res = OC_STACK_OK;
769 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
771 if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
773 if(otmCtx && otmCtx->selectedDeviceInfo)
775 //Close the temporal secure session to verify the owner credential
776 CAEndpoint_t* endpoint = (CAEndpoint_t *)&otmCtx->selectedDeviceInfo->endpoint;
777 endpoint->port = otmCtx->selectedDeviceInfo->securePort;
778 CAResult_t caResult = CA_STATUS_OK;
779 caResult = CAcloseSslConnection(endpoint);
781 if(CA_STATUS_OK != caResult)
783 OIC_LOG(ERROR, TAG, "Failed to close DTLS session");
784 SetResult(otmCtx, caResult);
785 return OC_STACK_DELETE_TRANSACTION;
789 * If we select NULL cipher,
790 * client will select appropriate cipher suite according to server's cipher-suite list.
792 // TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256 = 0xC037, /**< see RFC 5489 */
793 caResult = CASelectCipherSuite(0xC037, endpoint->adapter);
795 if(CA_STATUS_OK != caResult)
797 OIC_LOG(ERROR, TAG, "Failed to select TLS_NULL_WITH_NULL_NULL");
798 SetResult(otmCtx, caResult);
799 return OC_STACK_DELETE_TRANSACTION;
803 * in case of random PIN based OxM,
804 * revert get_psk_info callback of tinyDTLS to use owner credential.
806 if(OIC_RANDOM_DEVICE_PIN == otmCtx->selectedDeviceInfo->doxm->oxmSel)
808 OicUuid_t emptyUuid = { .id={0}};
809 SetUuidForRandomPinOxm(&emptyUuid);
811 caResult = CAregisterPskCredentialsHandler(GetDtlsPskCredentials);
813 if(CA_STATUS_OK != caResult)
815 OIC_LOG(ERROR, TAG, "Failed to revert DTLS credential handler.");
816 SetResult(otmCtx, OC_STACK_INVALID_CALLBACK);
817 return OC_STACK_DELETE_TRANSACTION;
821 otmCtx->selectedDeviceInfo->connType |= CT_FLAG_SECURE;
823 res = PostOwnerAcl(otmCtx);
824 if(OC_STACK_OK != res)
826 OIC_LOG(ERROR, TAG, "Failed to update owner ACL to new device");
827 SetResult(otmCtx, res);
828 return OC_STACK_DELETE_TRANSACTION;
834 res = clientResponse->result;
835 OIC_LOG_V(ERROR, TAG, "OwnerCredentialHandler : Unexpected result %d", res);
836 SetResult(otmCtx, res);
839 OIC_LOG(DEBUG, TAG, "OUT OwnerCredentialHandler");
842 return OC_STACK_DELETE_TRANSACTION;
846 * Response handler for update owner ACL request.
848 * @param[in] ctx ctx value passed to callback from calling function.
849 * @param[in] UNUSED handle to an invocation
850 * @param[in] clientResponse Response from queries to remote servers.
851 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
852 * and OC_STACK_KEEP_TRANSACTION to keep it.
854 static OCStackApplicationResult OwnerAclHandler(void *ctx, OCDoHandle UNUSED,
855 OCClientResponse *clientResponse)
857 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
858 VERIFY_NON_NULL(TAG, ctx, WARNING);
860 OIC_LOG(DEBUG, TAG, "IN OwnerAclHandler");
862 OCStackResult res = OC_STACK_OK;
863 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
865 if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
867 if(otmCtx && otmCtx->selectedDeviceInfo)
869 //POST /oic/sec/doxm [{ ..., "owned":"TRUE" }]
870 res = PostOwnershipInformation(otmCtx);
871 if(OC_STACK_OK != res)
873 OIC_LOG(ERROR, TAG, "Failed to update ownership information to new device");
874 SetResult(otmCtx, res);
880 res = clientResponse->result;
881 OIC_LOG_V(ERROR, TAG, "OwnerAclHandler : Unexpected result %d", res);
882 SetResult(otmCtx, res);
885 OIC_LOG(DEBUG, TAG, "OUT OwnerAclHandler");
888 return OC_STACK_DELETE_TRANSACTION;
893 * Response handler for update owner information request.
895 * @param[in] ctx ctx value passed to callback from calling function.
896 * @param[in] UNUSED handle to an invocation
897 * @param[in] clientResponse Response from queries to remote servers.
898 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
899 * and OC_STACK_KEEP_TRANSACTION to keep it.
901 static OCStackApplicationResult OwnershipInformationHandler(void *ctx, OCDoHandle UNUSED,
902 OCClientResponse *clientResponse)
904 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
905 VERIFY_NON_NULL(TAG, ctx, WARNING);
907 OIC_LOG(DEBUG, TAG, "IN OwnershipInformationHandler");
909 OCStackResult res = OC_STACK_OK;
910 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
912 if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
914 if(otmCtx && otmCtx->selectedDeviceInfo)
916 OIC_LOG(INFO, TAG, "Ownership transfer was successfully completed.");
917 OIC_LOG(INFO, TAG, "Set Ready for provisioning state .");
919 res = PostProvisioningStatus(otmCtx);
920 if(OC_STACK_OK != res)
922 OIC_LOG(ERROR, TAG, "Failed to update pstat");
923 SetResult(otmCtx, res);
929 res = clientResponse->result;
930 OIC_LOG_V(ERROR, TAG, "OwnershipInformationHandler : Unexpected result %d", res);
931 SetResult(otmCtx, res);
934 OIC_LOG(DEBUG, TAG, "OUT OwnershipInformationHandler");
937 return OC_STACK_DELETE_TRANSACTION;
941 * Response handler of update provisioning status.
943 * @param[in] ctx ctx value passed to callback from calling function.
944 * @param[in] UNUSED handle to an invocation
945 * @param[in] clientResponse Response from queries to remote servers.
946 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
947 * and OC_STACK_KEEP_TRANSACTION to keep it.
949 static OCStackApplicationResult ProvisioningStatusHandler(void *ctx, OCDoHandle UNUSED,
950 OCClientResponse *clientResponse)
952 OIC_LOG_V(INFO, TAG, "IN ProvisioningStatusHandler.");
954 VERIFY_NON_NULL(TAG, clientResponse, ERROR);
955 VERIFY_NON_NULL(TAG, ctx, ERROR);
957 OTMContext_t* otmCtx = (OTMContext_t*) ctx;
959 OCStackResult res = OC_STACK_OK;
961 if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
963 if(otmCtx && otmCtx->selectedDeviceInfo)
965 OIC_LOG(INFO, TAG, "Device state is in Ready for Provisionig.");
967 res = PostNormalOperationStatus(otmCtx);
968 if(OC_STACK_OK != res)
970 OIC_LOG(ERROR, TAG, "Failed to update pstat");
971 SetResult(otmCtx, res);
977 OIC_LOG_V(INFO, TAG, "Error occured in provisionDefaultACLCB :: %d\n",
978 clientResponse->result);
979 SetResult(otmCtx, clientResponse->result);
983 OIC_LOG_V(INFO, TAG, "OUT ProvisioningStatusHandler.");
984 return OC_STACK_DELETE_TRANSACTION;
988 * Response handler of update provisioning status to Ready for Normal..
990 * @param[in] ctx ctx value passed to callback from calling function.
991 * @param[in] UNUSED handle to an invocation
992 * @param[in] clientResponse Response from queries to remote servers.
993 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
994 * and OC_STACK_KEEP_TRANSACTION to keep it.
996 static OCStackApplicationResult ReadyForNomalStatusHandler(void *ctx, OCDoHandle UNUSED,
997 OCClientResponse *clientResponse)
999 OIC_LOG_V(INFO, TAG, "IN ReadyForNomalStatusHandler.");
1001 VERIFY_NON_NULL(TAG, clientResponse, ERROR);
1002 VERIFY_NON_NULL(TAG, ctx, ERROR);
1004 OTMContext_t* otmCtx = (OTMContext_t*) ctx;
1007 if (OC_STACK_RESOURCE_CHANGED == clientResponse->result)
1009 OIC_LOG(INFO, TAG, "Device state is in Ready for Normal Operation.");
1010 OCStackResult res = PDMAddDevice(&otmCtx->selectedDeviceInfo->doxm->deviceID);
1011 if (OC_STACK_OK == res)
1013 OIC_LOG_V(INFO, TAG, "Add device's UUID in PDM_DB");
1014 SetResult(otmCtx, OC_STACK_OK);
1015 return OC_STACK_DELETE_TRANSACTION;
1019 OIC_LOG(ERROR, TAG, "Ownership transfer is complete but adding information to DB is failed.");
1024 OIC_LOG_V(INFO, TAG, "Error occured in provisionDefaultACLCB :: %d\n",
1025 clientResponse->result);
1026 SetResult(otmCtx, clientResponse->result);
1030 OIC_LOG_V(INFO, TAG, "OUT ReadyForNomalStatusHandler.");
1031 return OC_STACK_DELETE_TRANSACTION;
1034 static OCStackResult PostOwnerCredential(OTMContext_t* otmCtx)
1036 OIC_LOG(DEBUG, TAG, "IN PostOwnerCredential");
1038 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1040 OIC_LOG(ERROR, TAG, "Invalid parameters");
1041 return OC_STACK_INVALID_PARAM;
1044 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1045 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1047 if(!PMGenerateQuery(true,
1048 deviceInfo->endpoint.addr, deviceInfo->securePort,
1049 deviceInfo->connType,
1050 query, sizeof(query), OIC_RSRC_CRED_URI))
1052 OIC_LOG(ERROR, TAG, "PostOwnerCredential : Failed to generate query");
1053 return OC_STACK_ERROR;
1055 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1056 OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1059 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1060 return OC_STACK_NO_MEMORY;
1063 //Generate owner credential for new device
1064 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1065 const OicSecCred_t* ownerCredential = GetCredResourceData(&(deviceInfo->doxm->deviceID));
1066 if(!ownerCredential)
1068 OIC_LOG(ERROR, TAG, "Can not find OwnerPSK.");
1069 return OC_STACK_NO_RESOURCE;
1072 OicUuid_t credSubjectId = {.id={0}};
1073 if(OC_STACK_OK == GetDoxmDeviceID(&credSubjectId))
1075 OicSecCred_t newCredential;
1076 memcpy(&newCredential, ownerCredential, sizeof(OicSecCred_t));
1077 newCredential.next = NULL;
1079 //Set subject ID as PT's ID
1080 memcpy(&(newCredential.subject), &credSubjectId, sizeof(OicUuid_t));
1082 //Fill private data as empty string
1083 newCredential.privateData.data = "";
1084 newCredential.privateData.len = 0;
1085 newCredential.privateData.encoding = ownerCredential->privateData.encoding;
1087 newCredential.publicData.data = NULL;
1088 newCredential.publicData.len = 0;
1091 //Send owner credential to new device : POST /oic/sec/cred [ owner credential ]
1092 if (OC_STACK_OK != CredToCBORPayload(&newCredential, &secPayload->securityData,
1093 &secPayload->payloadSize, secureFlag))
1095 OICFree(secPayload);
1096 OIC_LOG(ERROR, TAG, "Error while converting bin to cbor.");
1097 return OC_STACK_ERROR;
1099 OIC_LOG(DEBUG, TAG, "Cred Payload:");
1100 OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1102 OCCallbackData cbData;
1103 cbData.cb = &OwnerCredentialHandler;
1104 cbData.context = (void *)otmCtx;
1106 OCStackResult res = OCDoResource(NULL, OC_REST_POST, query,
1107 &deviceInfo->endpoint, (OCPayload*)secPayload,
1108 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1109 if (res != OC_STACK_OK)
1111 OIC_LOG(ERROR, TAG, "OCStack resource error");
1116 OIC_LOG(ERROR, TAG, "Failed to read DOXM device ID.");
1117 return OC_STACK_NO_RESOURCE;
1120 OIC_LOG(DEBUG, TAG, "OUT PostOwnerCredential");
1125 static OicSecAcl_t* GenerateOwnerAcl(const OicUuid_t* owner)
1127 OicSecAcl_t* ownerAcl = (OicSecAcl_t*)OICCalloc(1, sizeof(OicSecAcl_t));
1128 OicSecAce_t* ownerAce = (OicSecAce_t*)OICCalloc(1, sizeof(OicSecAce_t));
1129 OicSecRsrc_t* wildcardRsrc = (OicSecRsrc_t*)OICCalloc(1, sizeof(OicSecRsrc_t));
1130 if(NULL == ownerAcl || NULL == ownerAce || NULL == wildcardRsrc)
1132 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1135 LL_APPEND(ownerAcl->aces, ownerAce);
1136 LL_APPEND(ownerAce->resources, wildcardRsrc);
1138 //Set resource owner as PT
1139 memcpy(ownerAcl->rownerID.id, owner->id, sizeof(owner->id));
1141 //PT has full permission.
1142 ownerAce->permission = PERMISSION_FULL_CONTROL;
1144 //Set subject as PT's UUID
1145 memcpy(ownerAce->subjectuuid.id, owner->id, sizeof(owner->id));
1147 wildcardRsrc->href = OICStrdup(WILDCARD_RESOURCE_URI);
1148 if(NULL == wildcardRsrc->href)
1153 wildcardRsrc->interfaceLen = 1;
1154 wildcardRsrc->interfaces = (char**)OICMalloc(wildcardRsrc->interfaceLen * sizeof(char*));
1155 if(NULL == wildcardRsrc->interfaces)
1159 wildcardRsrc->interfaces[0] = OICStrdup(WILDCARD_RESOURCE_URI);
1160 if(NULL == wildcardRsrc->interfaces[0])
1165 wildcardRsrc->typeLen = 1;
1166 wildcardRsrc->types = (char**)OICMalloc(wildcardRsrc->typeLen * sizeof(char*));
1167 if(NULL == wildcardRsrc->types)
1171 wildcardRsrc->types[0] = OICStrdup(WILDCARD_RESOURCE_URI);
1172 if(NULL == wildcardRsrc->types[0])
1180 //in case of memory allocation failed, each resource should be removed individually.
1181 if(NULL == ownerAcl || NULL == ownerAce || NULL == wildcardRsrc)
1185 OICFree(wildcardRsrc);
1189 DeleteACLList(ownerAcl);
1195 * Function to update the owner ACL to new device.
1197 * @param[in] otmCtx Context value of ownership transfer.
1198 * @return OC_STACK_OK on success
1200 static OCStackResult PostOwnerAcl(OTMContext_t* otmCtx)
1202 OCStackResult res = OC_STACK_ERROR;
1203 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1204 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1205 OicSecAcl_t* ownerAcl = NULL;
1207 OIC_LOG(DEBUG, TAG, "IN PostOwnerAcl");
1209 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1211 OIC_LOG(ERROR, TAG, "Invalid parameters");
1212 return OC_STACK_INVALID_PARAM;
1215 if(!PMGenerateQuery(true,
1216 deviceInfo->endpoint.addr, deviceInfo->securePort,
1217 deviceInfo->connType,
1218 query, sizeof(query), OIC_RSRC_ACL_URI))
1220 OIC_LOG(ERROR, TAG, "Failed to generate query");
1221 return OC_STACK_ERROR;
1223 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1226 res = GetDoxmDeviceID(&ownerID);
1227 if(OC_STACK_OK != res)
1229 OIC_LOG(ERROR, TAG, "Failed to generate owner ACL");
1233 //Generate owner ACL for new device
1234 ownerAcl = GenerateOwnerAcl(&ownerID);
1235 if(NULL == ownerAcl)
1237 OIC_LOG(ERROR, TAG, "Failed to generate owner ACL");
1238 return OC_STACK_NO_MEMORY;
1241 //Generate ACL payload
1242 OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1245 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1246 res = OC_STACK_NO_MEMORY;
1250 res = AclToCBORPayload(ownerAcl, &secPayload->securityData, &secPayload->payloadSize);
1251 if (OC_STACK_OK != res)
1253 OICFree(secPayload);
1254 OIC_LOG(ERROR, TAG, "Error while converting bin to cbor.");
1257 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1259 OIC_LOG(DEBUG, TAG, "Owner ACL Payload:");
1260 OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1262 //Send owner ACL to new device : POST /oic/sec/cred [ owner credential ]
1263 OCCallbackData cbData;
1264 cbData.cb = &OwnerAclHandler;
1265 cbData.context = (void *)otmCtx;
1267 res = OCDoResource(NULL, OC_REST_POST, query,
1268 &deviceInfo->endpoint, (OCPayload*)secPayload,
1269 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1270 if (res != OC_STACK_OK)
1272 OIC_LOG(ERROR, TAG, "OCStack resource error");
1276 OIC_LOG(DEBUG, TAG, "OUT PostOwnerAcl");
1279 DeleteACLList(ownerAcl);
1284 static OCStackResult PostOwnerTransferModeToResource(OTMContext_t* otmCtx)
1286 OIC_LOG(DEBUG, TAG, "IN PostOwnerTransferModeToResource");
1288 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1290 OIC_LOG(ERROR, TAG, "Invalid parameters");
1291 return OC_STACK_INVALID_PARAM;
1294 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1295 OicSecOxm_t selectedOxm = deviceInfo->doxm->oxmSel;
1296 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1298 if(!PMGenerateQuery(false,
1299 deviceInfo->endpoint.addr, deviceInfo->endpoint.port,
1300 deviceInfo->connType,
1301 query, sizeof(query), OIC_RSRC_DOXM_URI))
1303 OIC_LOG(ERROR, TAG, "PostOwnerTransferModeToResource : Failed to generate query");
1304 return OC_STACK_ERROR;
1306 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1307 OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1310 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1311 return OC_STACK_NO_MEMORY;
1313 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1314 OCStackResult res = g_OTMDatas[selectedOxm].createSelectOxmPayloadCB(otmCtx,
1315 &secPayload->securityData, &secPayload->payloadSize);
1316 if (OC_STACK_OK != res && NULL == secPayload->securityData)
1318 OCPayloadDestroy((OCPayload *)secPayload);
1319 OIC_LOG(ERROR, TAG, "Error while converting bin to cbor");
1320 return OC_STACK_ERROR;
1323 OCCallbackData cbData;
1324 cbData.cb = &OwnerTransferModeHandler;
1325 cbData.context = (void *)otmCtx;
1327 res = OCDoResource(NULL, OC_REST_POST, query,
1328 &deviceInfo->endpoint, (OCPayload *)secPayload,
1329 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1330 if (res != OC_STACK_OK)
1332 OIC_LOG(ERROR, TAG, "OCStack resource error");
1335 OIC_LOG(DEBUG, TAG, "OUT PostOwnerTransferModeToResource");
1340 static OCStackResult GetProvisioningStatusResource(OTMContext_t* otmCtx)
1342 OIC_LOG(DEBUG, TAG, "IN GetProvisioningStatusResource");
1344 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1346 OIC_LOG(ERROR, TAG, "Invailed parameters");
1347 return OC_STACK_INVALID_PARAM;
1350 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1351 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1352 if(!PMGenerateQuery(false,
1353 deviceInfo->endpoint.addr, deviceInfo->endpoint.port,
1354 deviceInfo->connType,
1355 query, sizeof(query), OIC_RSRC_PSTAT_URI))
1357 OIC_LOG(ERROR, TAG, "GetProvisioningStatusResource : Failed to generate query");
1358 return OC_STACK_ERROR;
1360 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1362 OCCallbackData cbData;
1363 cbData.cb = &ListMethodsHandler;
1364 cbData.context = (void *)otmCtx;
1366 OCStackResult res = OCDoResource(NULL, OC_REST_GET, query, NULL, NULL,
1367 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1368 if (res != OC_STACK_OK)
1370 OIC_LOG(ERROR, TAG, "OCStack resource error");
1373 OIC_LOG(DEBUG, TAG, "OUT GetProvisioningStatusResource");
1378 static OCStackResult PostOwnerUuid(OTMContext_t* otmCtx)
1380 OIC_LOG(DEBUG, TAG, "IN PostOwnerUuid");
1382 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1384 OIC_LOG(ERROR, TAG, "Invailed parameters");
1385 return OC_STACK_INVALID_PARAM;
1388 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1389 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1390 if(!PMGenerateQuery(true,
1391 deviceInfo->endpoint.addr, deviceInfo->securePort,
1392 deviceInfo->connType,
1393 query, sizeof(query), OIC_RSRC_DOXM_URI))
1395 OIC_LOG(ERROR, TAG, "PostOwnerUuid : Failed to generate query");
1396 return OC_STACK_ERROR;
1398 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1400 //Post PT's uuid to new device
1401 OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1404 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1405 return OC_STACK_NO_MEMORY;
1407 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1408 OCStackResult res = g_OTMDatas[deviceInfo->doxm->oxmSel].createOwnerTransferPayloadCB(
1409 otmCtx, &secPayload->securityData, &secPayload->payloadSize);
1410 if (OC_STACK_OK != res && NULL == secPayload->securityData)
1412 OCPayloadDestroy((OCPayload *)secPayload);
1413 OIC_LOG(ERROR, TAG, "Error while converting doxm bin to cbor.");
1414 return OC_STACK_INVALID_PARAM;
1416 OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1418 OCCallbackData cbData;
1419 cbData.cb = &OwnerUuidUpdateHandler;
1420 cbData.context = (void *)otmCtx;
1423 res = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload *)secPayload,
1424 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1425 if (res != OC_STACK_OK)
1427 OIC_LOG(ERROR, TAG, "OCStack resource error");
1430 OIC_LOG(DEBUG, TAG, "OUT PostOwnerUuid");
1435 static OCStackResult PostOwnershipInformation(OTMContext_t* otmCtx)
1437 OIC_LOG(DEBUG, TAG, "IN PostOwnershipInformation");
1439 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1441 OIC_LOG(ERROR, TAG, "Invailed parameters");
1442 return OC_STACK_INVALID_PARAM;
1445 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1446 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1447 if(!PMGenerateQuery(true,
1448 deviceInfo->endpoint.addr, deviceInfo->securePort,
1449 deviceInfo->connType,
1450 query, sizeof(query), OIC_RSRC_DOXM_URI))
1452 OIC_LOG(ERROR, TAG, "PostOwnershipInformation : Failed to generate query");
1453 return OC_STACK_ERROR;
1455 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1457 //OwnershipInformationHandler
1458 OCSecurityPayload *secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1461 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1462 return OC_STACK_NO_MEMORY;
1465 otmCtx->selectedDeviceInfo->doxm->owned = true;
1467 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1468 OCStackResult res = DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm,
1469 &secPayload->securityData, &secPayload->payloadSize, true);
1470 if (OC_STACK_OK != res && NULL == secPayload->securityData)
1472 OCPayloadDestroy((OCPayload *)secPayload);
1473 OIC_LOG(ERROR, TAG, "Error while converting doxm bin to json");
1474 return OC_STACK_INVALID_PARAM;
1477 OCCallbackData cbData;
1478 cbData.cb = &OwnershipInformationHandler;
1479 cbData.context = (void *)otmCtx;
1482 res = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload*)secPayload,
1483 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1484 if (res != OC_STACK_OK)
1486 OIC_LOG(ERROR, TAG, "OCStack resource error");
1489 OIC_LOG(DEBUG, TAG, "OUT PostOwnershipInformation");
1494 static OCStackResult PostUpdateOperationMode(OTMContext_t* otmCtx)
1496 OIC_LOG(DEBUG, TAG, "IN PostUpdateOperationMode");
1498 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1500 return OC_STACK_INVALID_PARAM;
1503 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1504 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1505 if(!PMGenerateQuery(false,
1506 deviceInfo->endpoint.addr, deviceInfo->endpoint.port,
1507 deviceInfo->connType,
1508 query, sizeof(query), OIC_RSRC_PSTAT_URI))
1510 OIC_LOG(ERROR, TAG, "PostUpdateOperationMode : Failed to generate query");
1511 return OC_STACK_ERROR;
1513 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1515 OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1518 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1519 return OC_STACK_NO_MEMORY;
1521 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1522 OCStackResult res = PstatToCBORPayload(deviceInfo->pstat, &secPayload->securityData,
1523 &secPayload->payloadSize, true);
1524 if (OC_STACK_OK != res)
1526 OCPayloadDestroy((OCPayload *)secPayload);
1527 OIC_LOG(ERROR, TAG, "Error while converting pstat to cbor.");
1528 return OC_STACK_INVALID_PARAM;
1531 OCCallbackData cbData;
1532 cbData.cb = &OperationModeUpdateHandler;
1533 cbData.context = (void *)otmCtx;
1535 res = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload *)secPayload,
1536 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1537 if (res != OC_STACK_OK)
1539 OIC_LOG(ERROR, TAG, "OCStack resource error");
1542 OIC_LOG(DEBUG, TAG, "OUT PostUpdateOperationMode");
1547 static OCStackResult StartOwnershipTransfer(void* ctx, OCProvisionDev_t* selectedDevice)
1549 OIC_LOG(INFO, TAG, "IN StartOwnershipTransfer");
1550 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
1551 otmCtx->selectedDeviceInfo = selectedDevice;
1553 //Set to the lowest level OxM, and then find more higher level OxM.
1554 OCStackResult res = SelectProvisioningMethod(selectedDevice->doxm->oxm,
1555 selectedDevice->doxm->oxmLen,
1556 &selectedDevice->doxm->oxmSel);
1557 if(OC_STACK_OK != res)
1559 OIC_LOG(ERROR, TAG, "Failed to select the provisioning method");
1560 SetResult(otmCtx, res);
1563 OIC_LOG_V(DEBUG, TAG, "Selected provisoning method = %d", selectedDevice->doxm->oxmSel);
1565 //Send Req: POST /oic/sec/doxm [{..."OxmSel" :g_OTMDatas[Index of Selected OxM].OXMString,...}]
1566 res = PostOwnerTransferModeToResource(otmCtx);
1567 if(OC_STACK_OK != res)
1569 OIC_LOG(WARNING, TAG, "Failed to select the provisioning method");
1570 SetResult(otmCtx, res);
1574 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1575 //Register TLS event handler to catch the tls event while handshake
1576 if(CA_STATUS_OK != CAregisterSslHandshakeCallback(DTLSHandshakeCB))
1578 OIC_LOG(WARNING, TAG, "StartOwnershipTransfer : Failed to register TLS handshake callback.");
1580 #endif // __WITH_DTLS__ or __WITH_TLS__
1581 OIC_LOG(INFO, TAG, "OUT StartOwnershipTransfer");
1587 OCStackResult OTMSetOwnershipTransferCallbackData(OicSecOxm_t oxmType, OTMCallbackData_t* data)
1589 OIC_LOG(DEBUG, TAG, "IN OTMSetOwnerTransferCallbackData");
1593 OIC_LOG(ERROR, TAG, "OTMSetOwnershipTransferCallbackData : Invalid parameters");
1594 return OC_STACK_INVALID_PARAM;
1596 if(oxmType >= OIC_OXM_COUNT)
1598 OIC_LOG(INFO, TAG, "Unknow ownership transfer method");
1599 return OC_STACK_INVALID_PARAM;
1602 g_OTMDatas[oxmType].loadSecretCB= data->loadSecretCB;
1603 g_OTMDatas[oxmType].createSecureSessionCB = data->createSecureSessionCB;
1604 g_OTMDatas[oxmType].createSelectOxmPayloadCB = data->createSelectOxmPayloadCB;
1605 g_OTMDatas[oxmType].createOwnerTransferPayloadCB = data->createOwnerTransferPayloadCB;
1607 OIC_LOG(DEBUG, TAG, "OUT OTMSetOwnerTransferCallbackData");
1613 * NOTE : Unowned discovery should be done before performing OTMDoOwnershipTransfer
1615 OCStackResult OTMDoOwnershipTransfer(void* ctx,
1616 OCProvisionDev_t *selectedDevicelist,
1617 OCProvisionResultCB resultCallback)
1619 OIC_LOG(DEBUG, TAG, "IN OTMDoOwnershipTransfer");
1621 if (NULL == selectedDevicelist)
1623 return OC_STACK_INVALID_PARAM;
1625 if (NULL == resultCallback)
1627 return OC_STACK_INVALID_CALLBACK;
1630 OTMContext_t* otmCtx = (OTMContext_t*)OICCalloc(1,sizeof(OTMContext_t));
1633 OIC_LOG(ERROR, TAG, "Failed to create OTM Context");
1634 return OC_STACK_NO_MEMORY;
1636 otmCtx->ctxResultCallback = resultCallback;
1637 otmCtx->ctxHasError = false;
1638 otmCtx->userCtx = ctx;
1639 OCProvisionDev_t* pCurDev = selectedDevicelist;
1641 //Counting number of selected devices.
1642 otmCtx->ctxResultArraySize = 0;
1643 while(NULL != pCurDev)
1645 otmCtx->ctxResultArraySize++;
1646 pCurDev = pCurDev->next;
1649 otmCtx->ctxResultArray =
1650 (OCProvisionResult_t*)OICCalloc(otmCtx->ctxResultArraySize, sizeof(OCProvisionResult_t));
1651 if(NULL == otmCtx->ctxResultArray)
1653 OIC_LOG(ERROR, TAG, "OTMDoOwnershipTransfer : Failed to memory allocation");
1655 return OC_STACK_NO_MEMORY;
1657 pCurDev = selectedDevicelist;
1659 OCStackResult res = OC_STACK_OK;
1660 //Fill the device UUID for result array.
1661 for(size_t devIdx = 0; devIdx < otmCtx->ctxResultArraySize; devIdx++)
1663 //Checking duplication of Device ID.
1664 bool isDuplicate = true;
1665 res = PDMIsDuplicateDevice(&pCurDev->doxm->deviceID, &isDuplicate);
1666 if (OC_STACK_OK != res)
1672 bool isStale = false;
1673 res = PDMIsDeviceStale(&pCurDev->doxm->deviceID, &isStale);
1674 if(OC_STACK_OK != res)
1676 OIC_LOG(ERROR, TAG, "Internal error in PDMIsDeviceStale");
1681 OIC_LOG(INFO, TAG, "Detected duplicated UUID in stale status, "\
1682 "this UUID will be removed from PDM");
1684 res = PDMDeleteDevice(&pCurDev->doxm->deviceID);
1685 if(OC_STACK_OK != res)
1687 OIC_LOG(ERROR, TAG, "Internal error in PDMDeleteDevice");
1693 OIC_LOG(ERROR, TAG, "OTMDoOwnershipTransfer : Device UUID is duplicated");
1694 res = OC_STACK_INVALID_PARAM;
1698 memcpy(otmCtx->ctxResultArray[devIdx].deviceId.id,
1699 pCurDev->doxm->deviceID.id,
1701 otmCtx->ctxResultArray[devIdx].res = OC_STACK_CONTINUE;
1702 pCurDev = pCurDev->next;
1705 StartOwnershipTransfer(otmCtx, selectedDevicelist);
1707 OIC_LOG(DEBUG, TAG, "OUT OTMDoOwnershipTransfer");
1711 OICFree(otmCtx->ctxResultArray);
1716 OCStackResult PostProvisioningStatus(OTMContext_t* otmCtx)
1718 OIC_LOG(INFO, TAG, "IN PostProvisioningStatus");
1720 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1722 OIC_LOG(ERROR, TAG, "OTMContext is NULL");
1723 return OC_STACK_INVALID_PARAM;
1726 //Change the TAKE_OWNER bit of CM to 0.
1727 otmCtx->selectedDeviceInfo->pstat->cm &= (~TAKE_OWNER);
1729 OCSecurityPayload *secPayload = (OCSecurityPayload *)OICCalloc(1, sizeof(OCSecurityPayload));
1732 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1733 return OC_STACK_NO_MEMORY;
1735 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1736 if (OC_STACK_OK != PstatToCBORPayload(otmCtx->selectedDeviceInfo->pstat,
1737 &secPayload->securityData, &secPayload->payloadSize, true))
1739 OCPayloadDestroy((OCPayload *)secPayload);
1740 return OC_STACK_INVALID_JSON;
1742 OIC_LOG(DEBUG, TAG, "Created payload for chage to Provisiong state");
1743 OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1745 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1746 if(!PMGenerateQuery(true,
1747 otmCtx->selectedDeviceInfo->endpoint.addr,
1748 otmCtx->selectedDeviceInfo->securePort,
1749 otmCtx->selectedDeviceInfo->connType,
1750 query, sizeof(query), OIC_RSRC_PSTAT_URI))
1752 OIC_LOG(ERROR, TAG, "PostProvisioningStatus : Failed to generate query");
1753 return OC_STACK_ERROR;
1755 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1757 OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
1758 cbData.cb = &ProvisioningStatusHandler;
1759 cbData.context = (void*)otmCtx;
1761 OCStackResult ret = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload*)secPayload,
1762 otmCtx->selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1763 OIC_LOG_V(INFO, TAG, "OCDoResource returned: %d",ret);
1764 if (ret != OC_STACK_OK)
1766 OIC_LOG(ERROR, TAG, "OCStack resource error");
1769 OIC_LOG(INFO, TAG, "OUT PostProvisioningStatus");
1774 OCStackResult PostNormalOperationStatus(OTMContext_t* otmCtx)
1776 OIC_LOG(INFO, TAG, "IN PostNormalOperationStatus");
1778 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1780 OIC_LOG(ERROR, TAG, "OTMContext is NULL");
1781 return OC_STACK_INVALID_PARAM;
1785 otmCtx->selectedDeviceInfo->pstat->isOp = true;
1787 OCSecurityPayload *secPayload = (OCSecurityPayload *)OICCalloc(1, sizeof(OCSecurityPayload));
1790 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1791 return OC_STACK_NO_MEMORY;
1793 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1794 if (OC_STACK_OK != PstatToCBORPayload(otmCtx->selectedDeviceInfo->pstat,
1795 &secPayload->securityData, &secPayload->payloadSize, true))
1797 OCPayloadDestroy((OCPayload *)secPayload);
1798 return OC_STACK_INVALID_JSON;
1800 OIC_LOG(DEBUG, TAG, "Created payload for chage to Provisiong state");
1801 OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1803 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1804 if(!PMGenerateQuery(true,
1805 otmCtx->selectedDeviceInfo->endpoint.addr,
1806 otmCtx->selectedDeviceInfo->securePort,
1807 otmCtx->selectedDeviceInfo->connType,
1808 query, sizeof(query), OIC_RSRC_PSTAT_URI))
1810 OIC_LOG(ERROR, TAG, "PostNormalOperationStatus : Failed to generate query");
1811 return OC_STACK_ERROR;
1813 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1815 OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
1816 cbData.cb = &ReadyForNomalStatusHandler;
1817 cbData.context = (void*)otmCtx;
1819 OCStackResult ret = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload*)secPayload,
1820 otmCtx->selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1821 OIC_LOG_V(INFO, TAG, "OCDoResource returned: %d",ret);
1822 if (ret != OC_STACK_OK)
1824 OIC_LOG(ERROR, TAG, "OCStack resource error");
1827 OIC_LOG(INFO, TAG, "OUT PostNormalOperationStatus");