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"
55 #include "srmresourcestrings.h"
56 #include "doxmresource.h"
57 #include "pstatresource.h"
58 #include "credresource.h"
59 #include "aclresource.h"
60 #include "ownershiptransfermanager.h"
61 #include "securevirtualresourcetypes.h"
62 #include "oxmjustworks.h"
64 #include "pmutility.h"
65 #include "srmutility.h"
66 #include "provisioningdatabasemanager.h"
67 #include "oxmrandompin.h"
68 #include "ocpayload.h"
69 #include "payload_logging.h"
74 * Array to store the callbacks for each owner transfer method.
76 static OTMCallbackData_t g_OTMDatas[OIC_OXM_COUNT];
79 * Variables for pointing the OTMContext to be used in the DTLS handshake result callback.
81 static OTMContext_t* g_otmCtx = NULL;
84 * Function to select appropriate provisioning method.
86 * @param[in] supportedMethods Array of supported methods
87 * @param[in] numberOfMethods number of supported methods
88 * @param[out] selectedMethod Selected methods
89 * @return OC_STACK_OK on success
91 static OCStackResult SelectProvisioningMethod(const OicSecOxm_t *supportedMethods,
92 size_t numberOfMethods, OicSecOxm_t *selectedMethod)
94 OIC_LOG(DEBUG, TAG, "IN SelectProvisioningMethod");
96 if(numberOfMethods == 0 || !supportedMethods)
98 OIC_LOG(WARNING, TAG, "Could not find a supported OxM.");
99 return OC_STACK_ERROR;
102 *selectedMethod = supportedMethods[0];
103 for(size_t i = 0; i < numberOfMethods; i++)
105 if(*selectedMethod < supportedMethods[i])
107 *selectedMethod = supportedMethods[i];
115 * Function to select operation mode.This function will return most secure common operation mode.
117 * @param[in] selectedDeviceInfo selected device information to performing provisioning.
118 * @param[out] selectedMode selected operation mode
119 * @return OC_STACK_OK on success
121 static void SelectOperationMode(const OCProvisionDev_t *selectedDeviceInfo,
122 OicSecDpom_t *selectedMode)
124 OIC_LOG(DEBUG, TAG, "IN SelectOperationMode");
125 *selectedMode = selectedDeviceInfo->pstat->sm[0];
126 OIC_LOG_V(DEBUG, TAG, "Selected Operation Mode = %d", *selectedMode);
130 * Function to start ownership transfer.
131 * This function will send the first request for provisioning,
132 * The next request message is sent from the response handler for this request.
134 * @param[in] ctx context value passed to callback from calling function.
135 * @param[in] selectedDevice selected device information to performing provisioning.
136 * @return OC_STACK_OK on success
138 static OCStackResult StartOwnershipTransfer(void* ctx, OCProvisionDev_t* selectedDevice);
141 * Function to update owner transfer mode
143 * @param[in] otmCtx Context value of ownership transfer.
144 * @return OC_STACK_OK on success
146 static OCStackResult PostOwnerTransferModeToResource(OTMContext_t* otmCtx);
149 * Function to send request to resource to get its pstat resource information.
151 * @param[in] otmCtx Context value of ownership transfer.
152 * @return OC_STACK_OK on success
154 static OCStackResult GetProvisioningStatusResource(OTMContext_t* otmCtx);
158 * Function to send uuid of owner device to new device.
159 * This function would update 'owner of doxm' as UUID for provisioning tool.
161 * @param[in] otmCtx Context value of ownership transfer.
162 * @return OC_STACK_OK on success
164 static OCStackResult PostOwnerUuid(OTMContext_t* otmCtx);
167 * Function to update the operation mode. As per the spec. Operation mode in client driven
168 * single service provisioning it will be updated to 0x3
170 * @param[in] otmCtx Context value of ownership transfer.
171 * @return OC_STACK_OK on success
173 static OCStackResult PostUpdateOperationMode(OTMContext_t* otmCtx);
176 * Function to update the owner credential to new device
178 * @param[in] otmCtx Context value of ownership transfer.
179 * @param[in] selectedOperationMode selected operation mode
180 * @return OC_STACK_OK on success
182 static OCStackResult PostOwnerCredential(OTMContext_t* otmCtx);
185 * Function to send ownerShip info.
186 * This function would update 'owned of doxm' as true.
188 * @param[in] otmCtx Context value of ownership transfer.
189 * @return OC_STACK_OK on success
191 static OCStackResult PostOwnershipInformation(OTMContext_t* otmCtx);
194 * Function to update pstat as Ready for provisioning.
195 * This function would update 'cm' from bx0000,0010 to bx0000,0000.
197 * @param[in] ctx context value passed to callback from calling function.
198 * @param[in] selectedDevice selected device information to performing provisioning.
199 * @return OC_STACK_OK on success
201 static OCStackResult PostProvisioningStatus(OTMContext_t* otmCtx);
204 * Function to update pstat as Ready for Normal Operation.
205 * This function would update 'isop' from false to true.
207 * @param[in] ctx context value passed to callback from calling function.
208 * @param[in] selectedDevice selected device information to performing provisioning.
209 * @return OC_STACK_OK on success
211 static OCStackResult PostNormalOperationStatus(OTMContext_t* otmCtx);
213 static bool IsComplete(OTMContext_t* otmCtx)
215 for(size_t i = 0; i < otmCtx->ctxResultArraySize; i++)
217 if(OC_STACK_CONTINUE == otmCtx->ctxResultArray[i].res)
227 * Function to save the result of provisioning.
229 * @param[in,out] otmCtx Context value of ownership transfer.
230 * @param[in] res result of provisioning
232 static void SetResult(OTMContext_t* otmCtx, const OCStackResult res)
234 OIC_LOG_V(DEBUG, TAG, "IN SetResult : %d ", res);
238 OIC_LOG(WARNING, TAG, "OTMContext is NULL");
242 if(otmCtx->selectedDeviceInfo)
244 //Revert psk_info callback and new deivce uuid in case of random PIN OxM
245 if(OIC_RANDOM_DEVICE_PIN == otmCtx->selectedDeviceInfo->doxm->oxmSel)
247 if(CA_ADAPTER_IP == ((CAEndpoint_t*)(&otmCtx->selectedDeviceInfo->endpoint))->adapter)
249 if(CA_STATUS_OK != CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials))
251 OIC_LOG(WARNING, TAG, "Failed to register DTLS handshake callback.");
257 if(CA_STATUS_OK != CAregisterTlsCredentialsHandler(GetDtlsPskCredentials))
259 OIC_LOG(WARNING, TAG, "Failed to register TLS handshake callback.");
263 OicUuid_t emptyUuid = { .id={0}};
264 SetUuidForRandomPinOxm(&emptyUuid);
267 for(size_t i = 0; i < otmCtx->ctxResultArraySize; i++)
269 if(memcmp(otmCtx->selectedDeviceInfo->doxm->deviceID.id,
270 otmCtx->ctxResultArray[i].deviceId.id, UUID_LENGTH) == 0)
272 otmCtx->ctxResultArray[i].res = res;
273 if(OC_STACK_OK != res)
275 otmCtx->ctxHasError = true;
282 //If all request is completed, invoke the user callback.
283 if(IsComplete(otmCtx))
285 otmCtx->ctxResultCallback(otmCtx->userCtx, otmCtx->ctxResultArraySize,
286 otmCtx->ctxResultArray, otmCtx->ctxHasError);
287 OICFree(otmCtx->ctxResultArray);
292 if(OC_STACK_OK != StartOwnershipTransfer(otmCtx,
293 otmCtx->selectedDeviceInfo->next))
295 OIC_LOG(ERROR, TAG, "Failed to StartOwnershipTransfer");
300 OIC_LOG(DEBUG, TAG, "OUT SetResult");
304 * Function to handle the handshake result in OTM.
305 * This function will be invoked after DTLS handshake
306 * @param endPoint [IN] The remote endpoint.
307 * @param errorInfo [IN] Error information from the endpoint.
310 void DTLSHandshakeCB(const CAEndpoint_t *endpoint, const CAErrorInfo_t *info)
312 if(NULL != g_otmCtx && NULL != g_otmCtx->selectedDeviceInfo &&
313 NULL != endpoint && NULL != info)
315 OIC_LOG_V(INFO, TAG, "Received status from remote device(%s:%d) : %d",
316 endpoint->addr, endpoint->port, info->result);
318 OicSecDoxm_t* newDevDoxm = g_otmCtx->selectedDeviceInfo->doxm;
320 if(NULL != newDevDoxm)
322 OicUuid_t emptyUuid = {.id={0}};
324 //Make sure the address matches.
325 if(strncmp(g_otmCtx->selectedDeviceInfo->endpoint.addr,
327 sizeof(endpoint->addr)) == 0 &&
328 g_otmCtx->selectedDeviceInfo->securePort == endpoint->port)
330 OCStackResult res = OC_STACK_ERROR;
332 //If temporal secure sesstion established successfully
333 if(CA_STATUS_OK == info->result &&
334 false == newDevDoxm->owned &&
335 memcmp(&(newDevDoxm->owner), &emptyUuid, sizeof(OicUuid_t)) == 0)
337 //Send request : POST /oic/sec/doxm [{... , "devowner":"PT's UUID"}]
338 res = PostOwnerUuid(g_otmCtx);
339 if(OC_STACK_OK != res)
341 OIC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to send owner information");
342 SetResult(g_otmCtx, res);
345 //In case of authentication failure
346 else if(CA_DTLS_AUTHENTICATION_FAILURE == info->result)
348 //in case of error from owner credential
349 if(memcmp(&(newDevDoxm->owner), &emptyUuid, sizeof(OicUuid_t)) != 0 &&
350 true == newDevDoxm->owned)
352 OIC_LOG(ERROR, TAG, "The owner credential may incorrect.");
354 if(OC_STACK_OK != RemoveCredential(&(newDevDoxm->deviceID)))
356 OIC_LOG(WARNING, TAG, "Failed to remove the invaild owner credential");
358 SetResult(g_otmCtx, OC_STACK_AUTHENTICATION_FAILURE);
360 //in case of error from wrong PIN, re-start the ownership transfer
361 else if(OIC_RANDOM_DEVICE_PIN == newDevDoxm->oxmSel)
363 OIC_LOG(ERROR, TAG, "The PIN number may incorrect.");
365 memcpy(&(newDevDoxm->owner), &emptyUuid, sizeof(OicUuid_t));
366 newDevDoxm->owned = false;
367 g_otmCtx->attemptCnt++;
369 if(WRONG_PIN_MAX_ATTEMP > g_otmCtx->attemptCnt)
371 res = StartOwnershipTransfer(g_otmCtx, g_otmCtx->selectedDeviceInfo);
372 if(OC_STACK_OK != res)
374 SetResult(g_otmCtx, res);
375 OIC_LOG(ERROR, TAG, "Failed to Re-StartOwnershipTransfer");
380 OIC_LOG(ERROR, TAG, "User has exceeded the number of authentication attempts.");
381 SetResult(g_otmCtx, OC_STACK_AUTHENTICATION_FAILURE);
386 OIC_LOG(ERROR, TAG, "Failed to establish secure session.");
387 SetResult(g_otmCtx, OC_STACK_AUTHENTICATION_FAILURE);
396 * Function to save ownerPSK at provisioning tool end.
398 * @param[in] selectedDeviceInfo selected device information to performing provisioning.
399 * @return OC_STACK_OK on success
401 static OCStackResult SaveOwnerPSK(OCProvisionDev_t *selectedDeviceInfo)
403 OIC_LOG(DEBUG, TAG, "IN SaveOwnerPSK");
405 OCStackResult res = OC_STACK_ERROR;
407 CAEndpoint_t endpoint;
408 memset(&endpoint, 0x00, sizeof(CAEndpoint_t));
409 OICStrcpy(endpoint.addr, MAX_ADDR_STR_SIZE_CA, selectedDeviceInfo->endpoint.addr);
410 endpoint.addr[MAX_ADDR_STR_SIZE_CA - 1] = '\0';
411 endpoint.port = selectedDeviceInfo->securePort;
412 endpoint.adapter = selectedDeviceInfo->endpoint.adapter;
414 OicUuid_t ptDeviceID = {.id={0}};
415 if (OC_STACK_OK != GetDoxmDeviceID(&ptDeviceID))
417 OIC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
421 uint8_t ownerPSK[OWNER_PSK_LENGTH_128] = {0};
422 OicSecKey_t ownerKey = {ownerPSK, OWNER_PSK_LENGTH_128, OIC_ENCODING_UNKNOW};
424 //Generating OwnerPSK
425 CAResult_t pskRet = CAGenerateOwnerPSK(&endpoint,
426 (uint8_t *)GetOxmString(selectedDeviceInfo->doxm->oxmSel),
427 strlen(GetOxmString(selectedDeviceInfo->doxm->oxmSel)),
428 ptDeviceID.id, sizeof(ptDeviceID.id),
429 selectedDeviceInfo->doxm->deviceID.id, sizeof(selectedDeviceInfo->doxm->deviceID.id),
430 ownerPSK, OWNER_PSK_LENGTH_128);
432 if (CA_STATUS_OK == pskRet)
434 OIC_LOG(INFO, TAG,"ownerPSK dump:\n");
435 OIC_LOG_BUFFER(INFO, TAG,ownerPSK, OWNER_PSK_LENGTH_128);
436 //Generating new credential for provisioning tool
437 OicSecCred_t *cred = GenerateCredential(&selectedDeviceInfo->doxm->deviceID,
438 SYMMETRIC_PAIR_WISE_KEY, NULL,
439 &ownerKey, &ptDeviceID);
440 VERIFY_NON_NULL(TAG, cred, ERROR);
442 // TODO: Added as workaround. Will be replaced soon.
443 cred->privateData.encoding = OIC_ENCODING_RAW;
446 // NOTE: Test codes to use BASE64 encoded owner PSK.
447 uint32_t outSize = 0;
448 size_t b64BufSize = B64ENCODE_OUT_SAFESIZE((OWNER_PSK_LENGTH_128 + 1));
449 char* b64Buf = (uint8_t *)OICCalloc(1, b64BufSize);
450 VERIFY_NON_NULL(TAG, b64Buf, ERROR);
451 b64Encode(cred->privateData.data, cred->privateData.len, b64Buf, b64BufSize, &outSize);
453 OICFree( cred->privateData.data );
454 cred->privateData.data = (uint8_t *)OICCalloc(1, outSize + 1);
455 VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
457 strncpy(cred->privateData.data, b64Buf, outSize);
458 cred->privateData.data[outSize] = '\0';
459 cred->privateData.encoding = OIC_ENCODING_BASE64;
460 cred->privateData.len = outSize;
462 #endif //End of Test codes
464 res = AddCredential(cred);
465 if(res != OC_STACK_OK)
467 DeleteCredList(cred);
473 OIC_LOG(ERROR, TAG, "CAGenerateOwnerPSK failed");
476 OIC_LOG(DEBUG, TAG, "OUT SaveOwnerPSK");
482 * Callback handler for OwnerShipTransferModeHandler API.
484 * @param[in] ctx ctx value passed to callback from calling function.
485 * @param[in] UNUSED handle to an invocation
486 * @param[in] clientResponse Response from queries to remote servers.
487 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
488 * and OC_STACK_KEEP_TRANSACTION to keep it.
490 static OCStackApplicationResult OwnerTransferModeHandler(void *ctx, OCDoHandle UNUSED,
491 OCClientResponse *clientResponse)
493 OIC_LOG(DEBUG, TAG, "IN OwnerTransferModeHandler");
495 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
496 VERIFY_NON_NULL(TAG, ctx, WARNING);
498 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
500 if (OC_STACK_RESOURCE_CHANGED == clientResponse->result)
502 OIC_LOG(INFO, TAG, "OwnerTransferModeHandler : response result = OC_STACK_OK");
503 //Send request : GET /oic/sec/pstat
504 OCStackResult res = GetProvisioningStatusResource(otmCtx);
505 if(OC_STACK_OK != res)
507 OIC_LOG(WARNING, TAG, "Failed to get pstat information");
508 SetResult(otmCtx, res);
513 OIC_LOG_V(WARNING, TAG, "OwnerTransferModeHandler : Client response is incorrect : %d",
514 clientResponse->result);
515 SetResult(otmCtx, clientResponse->result);
518 OIC_LOG(DEBUG, TAG, "OUT OwnerTransferModeHandler");
521 return OC_STACK_DELETE_TRANSACTION;
525 * Callback handler for ProvisioningStatusResouceHandler API.
527 * @param[in] ctx ctx value passed to callback from calling function.
528 * @param[in] UNUSED handle to an invocation
529 * @param[in] clientResponse Response from queries to remote servers.
530 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
531 * and OC_STACK_KEEP_TRANSACTION to keep it.
533 static OCStackApplicationResult ListMethodsHandler(void *ctx, OCDoHandle UNUSED,
534 OCClientResponse *clientResponse)
536 OIC_LOG(DEBUG, TAG, "IN ListMethodsHandler");
538 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
539 VERIFY_NON_NULL(TAG, ctx, WARNING);
541 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
543 if (OC_STACK_OK == clientResponse->result)
545 if (NULL == clientResponse->payload)
547 OIC_LOG(INFO, TAG, "Skiping Null payload");
548 SetResult(otmCtx, OC_STACK_ERROR);
549 return OC_STACK_DELETE_TRANSACTION;
552 if (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)
554 OIC_LOG(INFO, TAG, "Unknown payload type");
555 SetResult(otmCtx, OC_STACK_ERROR);
556 return OC_STACK_DELETE_TRANSACTION;
558 OicSecPstat_t* pstat = NULL;
559 OCStackResult result = CBORPayloadToPstat(
560 ((OCSecurityPayload*)clientResponse->payload)->securityData,
561 ((OCSecurityPayload*)clientResponse->payload)->payloadSize,
563 if(NULL == pstat || result != OC_STACK_OK)
565 OIC_LOG(ERROR, TAG, "Error while converting cbor to pstat.");
566 SetResult(otmCtx, OC_STACK_ERROR);
567 return OC_STACK_DELETE_TRANSACTION;
569 if(false == (TAKE_OWNER & pstat->cm))
571 OIC_LOG(ERROR, TAG, "Device pairing mode enabling owner transfer operations is disabled");
572 SetResult(otmCtx, OC_STACK_ERROR);
573 return OC_STACK_DELETE_TRANSACTION;
575 otmCtx->selectedDeviceInfo->pstat = pstat;
577 //Select operation mode (Currently supported SINGLE_SERVICE_CLIENT_DRIVEN only)
578 SelectOperationMode(otmCtx->selectedDeviceInfo, &(otmCtx->selectedDeviceInfo->pstat->om));
580 //Send request : POST /oic/sec/pstat [{"om":"bx11", .. }]
581 OCStackResult res = PostUpdateOperationMode(otmCtx);
582 if (OC_STACK_OK != res)
584 OIC_LOG(ERROR, TAG, "Error while updating operation mode.");
585 SetResult(otmCtx, res);
590 OIC_LOG_V(WARNING, TAG, "ListMethodsHandler : Client response is incorrect : %d",
591 clientResponse->result);
592 SetResult(otmCtx, clientResponse->result);
595 OIC_LOG(DEBUG, TAG, "OUT ListMethodsHandler");
597 return OC_STACK_DELETE_TRANSACTION;
601 * Response handler for update owner uuid request.
603 * @param[in] ctx ctx value passed to callback from calling function.
604 * @param[in] UNUSED handle to an invocation
605 * @param[in] clientResponse Response from queries to remote servers.
606 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
607 * and OC_STACK_KEEP_TRANSACTION to keep it.
609 static OCStackApplicationResult OwnerUuidUpdateHandler(void *ctx, OCDoHandle UNUSED,
610 OCClientResponse *clientResponse)
612 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
613 VERIFY_NON_NULL(TAG, ctx, WARNING);
615 OIC_LOG(DEBUG, TAG, "IN OwnerUuidUpdateHandler");
617 OCStackResult res = OC_STACK_OK;
618 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
620 if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
622 if(otmCtx && otmCtx->selectedDeviceInfo)
624 res = SaveOwnerPSK(otmCtx->selectedDeviceInfo);
625 if(OC_STACK_OK != res)
627 OIC_LOG(ERROR, TAG, "OwnerUuidUpdateHandler:Failed to owner PSK generation");
628 SetResult(otmCtx, res);
629 return OC_STACK_DELETE_TRANSACTION;
632 //POST owner credential to new device according to security spec B.
633 res = PostOwnerCredential(otmCtx);
634 if(OC_STACK_OK != res)
637 "OwnerUuidUpdateHandler:Failed to send PosT request for onwer credential");
638 SetResult(otmCtx, res);
639 return OC_STACK_DELETE_TRANSACTION;
645 res = clientResponse->result;
646 OIC_LOG_V(ERROR, TAG, "OwnerUuidHandler : Unexpected result %d", res);
647 SetResult(otmCtx, res);
650 OIC_LOG(DEBUG, TAG, "OUT OwnerUuidUpdateHandler");
653 return OC_STACK_DELETE_TRANSACTION;
657 * Response handler for update operation mode.
659 * @param[in] ctx ctx value passed to callback from calling function.
660 * @param[in] UNUSED handle to an invocation
661 * @param[in] clientResponse Response from queries to remote servers.
662 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
663 * and OC_STACK_KEEP_TRANSACTION to keep it.
665 static OCStackApplicationResult OperationModeUpdateHandler(void *ctx, OCDoHandle UNUSED,
666 OCClientResponse *clientResponse)
668 OIC_LOG(DEBUG, TAG, "IN OperationModeUpdateHandler");
670 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
671 VERIFY_NON_NULL(TAG, ctx, WARNING);
673 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
675 if (OC_STACK_RESOURCE_CHANGED == clientResponse->result)
677 OCStackResult res = OC_STACK_ERROR;
678 OicSecOxm_t selOxm = otmCtx->selectedDeviceInfo->doxm->oxmSel;
680 //Load secret for temporal secure session.
681 if(g_OTMDatas[selOxm].loadSecretCB)
683 res = g_OTMDatas[selOxm].loadSecretCB(otmCtx);
684 if(OC_STACK_OK != res)
686 OIC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to load secret");
687 SetResult(otmCtx, res);
688 return OC_STACK_DELETE_TRANSACTION;
692 //It will be used in handshake event handler
695 //Try DTLS handshake to generate secure session
696 if(g_OTMDatas[selOxm].createSecureSessionCB)
698 res = g_OTMDatas[selOxm].createSecureSessionCB(otmCtx);
699 if(OC_STACK_OK != res)
701 OIC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to create DTLS session");
702 SetResult(otmCtx, res);
703 return OC_STACK_DELETE_TRANSACTION;
709 OIC_LOG(ERROR, TAG, "Error while update operation mode");
710 SetResult(otmCtx, clientResponse->result);
713 OIC_LOG(DEBUG, TAG, "OUT OperationModeUpdateHandler");
716 return OC_STACK_DELETE_TRANSACTION;
720 * Response handler for update owner crendetial request.
722 * @param[in] ctx ctx value passed to callback from calling function.
723 * @param[in] UNUSED handle to an invocation
724 * @param[in] clientResponse Response from queries to remote servers.
725 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
726 * and OC_STACK_KEEP_TRANSACTION to keep it.
728 static OCStackApplicationResult OwnerCredentialHandler(void *ctx, OCDoHandle UNUSED,
729 OCClientResponse *clientResponse)
731 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
732 VERIFY_NON_NULL(TAG, ctx, WARNING);
734 OIC_LOG(DEBUG, TAG, "IN OwnerCredentialHandler");
736 OCStackResult res = OC_STACK_OK;
737 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
739 if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
741 if(otmCtx && otmCtx->selectedDeviceInfo)
743 //Close the temporal secure session to verify the owner credential
744 CAEndpoint_t* endpoint = (CAEndpoint_t *)&otmCtx->selectedDeviceInfo->endpoint;
745 endpoint->port = otmCtx->selectedDeviceInfo->securePort;
746 CAResult_t caResult = CA_STATUS_OK;
747 if(CA_ADAPTER_IP == endpoint->adapter)
749 caResult = CACloseDtlsSession(endpoint);
754 caResult = CAcloseTlsConnection(endpoint);
757 if(CA_STATUS_OK != caResult)
759 OIC_LOG(ERROR, TAG, "Failed to close DTLS session");
760 SetResult(otmCtx, caResult);
761 return OC_STACK_DELETE_TRANSACTION;
765 * If we select NULL cipher,
766 * client will select appropriate cipher suite according to server's cipher-suite list.
768 if(CA_ADAPTER_IP == endpoint->adapter)
770 caResult = CASelectCipherSuite(TLS_NULL_WITH_NULL_NULL, endpoint->adapter);
774 // TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256 = 0xC037, /**< see RFC 5489 */
775 caResult = CASelectCipherSuite(0xC037, endpoint->adapter);
778 if(CA_STATUS_OK != caResult)
780 OIC_LOG(ERROR, TAG, "Failed to select TLS_NULL_WITH_NULL_NULL");
781 SetResult(otmCtx, caResult);
782 return OC_STACK_DELETE_TRANSACTION;
786 * in case of random PIN based OxM,
787 * revert get_psk_info callback of tinyDTLS to use owner credential.
789 if(OIC_RANDOM_DEVICE_PIN == otmCtx->selectedDeviceInfo->doxm->oxmSel)
791 OicUuid_t emptyUuid = { .id={0}};
792 SetUuidForRandomPinOxm(&emptyUuid);
794 if(CA_ADAPTER_IP == endpoint->adapter)
796 caResult = CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials);
801 caResult = CAregisterTlsCredentialsHandler(GetDtlsPskCredentials);
805 if(CA_STATUS_OK != caResult)
807 OIC_LOG(ERROR, TAG, "Failed to revert DTLS credential handler.");
808 SetResult(otmCtx, OC_STACK_INVALID_CALLBACK);
809 return OC_STACK_DELETE_TRANSACTION;
813 otmCtx->selectedDeviceInfo->connType |= CT_FLAG_SECURE;
815 //POST /oic/sec/doxm [{ ..., "owned":"TRUE" }]
816 res = PostOwnershipInformation(otmCtx);
817 if(OC_STACK_OK != res)
819 OIC_LOG(ERROR, TAG, "Failed to post ownership information to new device");
820 SetResult(otmCtx, res);
821 return OC_STACK_DELETE_TRANSACTION;
827 res = clientResponse->result;
828 OIC_LOG_V(ERROR, TAG, "OwnerCredentialHandler : Unexpected result %d", res);
829 SetResult(otmCtx, res);
832 OIC_LOG(DEBUG, TAG, "OUT OwnerCredentialHandler");
835 return OC_STACK_DELETE_TRANSACTION;
840 * Response handler for update owner information request.
842 * @param[in] ctx ctx value passed to callback from calling function.
843 * @param[in] UNUSED handle to an invocation
844 * @param[in] clientResponse Response from queries to remote servers.
845 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
846 * and OC_STACK_KEEP_TRANSACTION to keep it.
848 static OCStackApplicationResult OwnershipInformationHandler(void *ctx, OCDoHandle UNUSED,
849 OCClientResponse *clientResponse)
851 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
852 VERIFY_NON_NULL(TAG, ctx, WARNING);
854 OIC_LOG(DEBUG, TAG, "IN OwnershipInformationHandler");
856 OCStackResult res = OC_STACK_OK;
857 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
859 if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
861 if(otmCtx && otmCtx->selectedDeviceInfo)
863 OIC_LOG(INFO, TAG, "Ownership transfer was successfully completed.");
864 OIC_LOG(INFO, TAG, "Set Ready for provisioning state .");
866 res = PostProvisioningStatus(otmCtx);
867 if(OC_STACK_OK != res)
869 OIC_LOG(ERROR, TAG, "Failed to update pstat");
870 SetResult(otmCtx, res);
876 res = clientResponse->result;
877 OIC_LOG_V(ERROR, TAG, "OwnershipInformationHandler : Unexpected result %d", res);
878 SetResult(otmCtx, res);
881 OIC_LOG(DEBUG, TAG, "OUT OwnershipInformationHandler");
884 return OC_STACK_DELETE_TRANSACTION;
888 * Response handler of update provisioning status.
890 * @param[in] ctx ctx value passed to callback from calling function.
891 * @param[in] UNUSED handle to an invocation
892 * @param[in] clientResponse Response from queries to remote servers.
893 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
894 * and OC_STACK_KEEP_TRANSACTION to keep it.
896 static OCStackApplicationResult ProvisioningStatusHandler(void *ctx, OCDoHandle UNUSED,
897 OCClientResponse *clientResponse)
899 OIC_LOG_V(INFO, TAG, "IN ProvisioningStatusHandler.");
901 VERIFY_NON_NULL(TAG, clientResponse, ERROR);
902 VERIFY_NON_NULL(TAG, ctx, ERROR);
904 OTMContext_t* otmCtx = (OTMContext_t*) ctx;
906 OCStackResult res = OC_STACK_OK;
908 if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
910 if(otmCtx && otmCtx->selectedDeviceInfo)
912 OIC_LOG(INFO, TAG, "Device state is in Ready for Provisionig.");
914 res = PostNormalOperationStatus(otmCtx);
915 if(OC_STACK_OK != res)
917 OIC_LOG(ERROR, TAG, "Failed to update pstat");
918 SetResult(otmCtx, res);
924 OIC_LOG_V(INFO, TAG, "Error occured in provisionDefaultACLCB :: %d\n",
925 clientResponse->result);
926 SetResult(otmCtx, clientResponse->result);
930 OIC_LOG_V(INFO, TAG, "OUT ProvisioningStatusHandler.");
931 return OC_STACK_DELETE_TRANSACTION;
935 * Response handler of update provisioning status to Ready for Normal..
937 * @param[in] ctx ctx value passed to callback from calling function.
938 * @param[in] UNUSED handle to an invocation
939 * @param[in] clientResponse Response from queries to remote servers.
940 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
941 * and OC_STACK_KEEP_TRANSACTION to keep it.
943 static OCStackApplicationResult ReadyForNomalStatusHandler(void *ctx, OCDoHandle UNUSED,
944 OCClientResponse *clientResponse)
946 OIC_LOG_V(INFO, TAG, "IN ReadyForNomalStatusHandler.");
948 VERIFY_NON_NULL(TAG, clientResponse, ERROR);
949 VERIFY_NON_NULL(TAG, ctx, ERROR);
951 OTMContext_t* otmCtx = (OTMContext_t*) ctx;
954 if (OC_STACK_RESOURCE_CHANGED == clientResponse->result)
956 OIC_LOG(INFO, TAG, "Device state is in Ready for Normal Operation.");
957 OCStackResult res = PDMAddDevice(&otmCtx->selectedDeviceInfo->doxm->deviceID);
958 if (OC_STACK_OK == res)
960 OIC_LOG_V(INFO, TAG, "Add device's UUID in PDM_DB");
961 SetResult(otmCtx, OC_STACK_OK);
962 return OC_STACK_DELETE_TRANSACTION;
966 OIC_LOG(ERROR, TAG, "Ownership transfer is complete but adding information to DB is failed.");
971 OIC_LOG_V(INFO, TAG, "Error occured in provisionDefaultACLCB :: %d\n",
972 clientResponse->result);
973 SetResult(otmCtx, clientResponse->result);
977 OIC_LOG_V(INFO, TAG, "OUT ReadyForNomalStatusHandler.");
978 return OC_STACK_DELETE_TRANSACTION;
981 static OCStackResult PostOwnerCredential(OTMContext_t* otmCtx)
983 OIC_LOG(DEBUG, TAG, "IN PostOwnerCredential");
985 if(!otmCtx || !otmCtx->selectedDeviceInfo)
987 OIC_LOG(ERROR, TAG, "Invalid parameters");
988 return OC_STACK_INVALID_PARAM;
991 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
992 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
994 if(!PMGenerateQuery(true,
995 deviceInfo->endpoint.addr, deviceInfo->securePort,
996 deviceInfo->connType,
997 query, sizeof(query), OIC_RSRC_CRED_URI))
999 OIC_LOG(ERROR, TAG, "PostOwnerCredential : Failed to generate query");
1000 return OC_STACK_ERROR;
1002 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1003 OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1006 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1007 return OC_STACK_NO_MEMORY;
1010 //Generate owner credential for new device
1011 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1012 const OicSecCred_t* ownerCredential = GetCredResourceData(&(deviceInfo->doxm->deviceID));
1013 if(!ownerCredential)
1015 OIC_LOG(ERROR, TAG, "Can not find OwnerPSK.");
1016 return OC_STACK_NO_RESOURCE;
1019 OicUuid_t credSubjectId = {.id={0}};
1020 if(OC_STACK_OK == GetDoxmDeviceID(&credSubjectId))
1022 OicSecCred_t newCredential;
1023 memcpy(&newCredential, ownerCredential, sizeof(OicSecCred_t));
1024 newCredential.next = NULL;
1026 //Set subject ID as PT's ID
1027 memcpy(&(newCredential.subject), &credSubjectId, sizeof(OicUuid_t));
1029 //Fill private data as empty string
1030 newCredential.privateData.data = "";
1031 newCredential.privateData.len = 0;
1032 newCredential.privateData.encoding = ownerCredential->privateData.encoding;
1033 #ifdef __WITH_X509__
1034 newCredential.publicData.data = NULL;
1035 newCredential.publicData.len = 0;
1038 //Send owner credential to new device : POST /oic/sec/cred [ owner credential ]
1039 if (OC_STACK_OK != CredToCBORPayload(&newCredential, &secPayload->securityData,
1040 &secPayload->payloadSize, secureFlag))
1042 OICFree(secPayload);
1043 OIC_LOG(ERROR, TAG, "Error while converting bin to cbor.");
1044 return OC_STACK_ERROR;
1046 OIC_LOG(DEBUG, TAG, "Cred Payload:");
1047 OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1049 OCCallbackData cbData;
1050 cbData.cb = &OwnerCredentialHandler;
1051 cbData.context = (void *)otmCtx;
1053 OCStackResult res = OCDoResource(NULL, OC_REST_POST, query,
1054 &deviceInfo->endpoint, (OCPayload*)secPayload,
1055 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1056 if (res != OC_STACK_OK)
1058 OIC_LOG(ERROR, TAG, "OCStack resource error");
1063 OIC_LOG(ERROR, TAG, "Failed to read DOXM device ID.");
1064 return OC_STACK_NO_RESOURCE;
1067 OIC_LOG(DEBUG, TAG, "OUT PostOwnerCredential");
1072 static OCStackResult PostOwnerTransferModeToResource(OTMContext_t* otmCtx)
1074 OIC_LOG(DEBUG, TAG, "IN PostOwnerTransferModeToResource");
1076 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1078 OIC_LOG(ERROR, TAG, "Invalid parameters");
1079 return OC_STACK_INVALID_PARAM;
1082 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1083 OicSecOxm_t selectedOxm = deviceInfo->doxm->oxmSel;
1084 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1086 if(!PMGenerateQuery(false,
1087 deviceInfo->endpoint.addr, deviceInfo->endpoint.port,
1088 deviceInfo->connType,
1089 query, sizeof(query), OIC_RSRC_DOXM_URI))
1091 OIC_LOG(ERROR, TAG, "PostOwnerTransferModeToResource : Failed to generate query");
1092 return OC_STACK_ERROR;
1094 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1095 OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1098 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1099 return OC_STACK_NO_MEMORY;
1101 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1102 OCStackResult res = g_OTMDatas[selectedOxm].createSelectOxmPayloadCB(otmCtx,
1103 &secPayload->securityData, &secPayload->payloadSize);
1104 if (OC_STACK_OK != res && NULL == secPayload->securityData)
1106 OCPayloadDestroy((OCPayload *)secPayload);
1107 OIC_LOG(ERROR, TAG, "Error while converting bin to cbor");
1108 return OC_STACK_ERROR;
1111 OCCallbackData cbData;
1112 cbData.cb = &OwnerTransferModeHandler;
1113 cbData.context = (void *)otmCtx;
1115 res = OCDoResource(NULL, OC_REST_POST, query,
1116 &deviceInfo->endpoint, (OCPayload *)secPayload,
1117 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1118 if (res != OC_STACK_OK)
1120 OIC_LOG(ERROR, TAG, "OCStack resource error");
1123 OIC_LOG(DEBUG, TAG, "OUT PostOwnerTransferModeToResource");
1128 static OCStackResult GetProvisioningStatusResource(OTMContext_t* otmCtx)
1130 OIC_LOG(DEBUG, TAG, "IN GetProvisioningStatusResource");
1132 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1134 OIC_LOG(ERROR, TAG, "Invailed parameters");
1135 return OC_STACK_INVALID_PARAM;
1138 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1139 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1140 if(!PMGenerateQuery(false,
1141 deviceInfo->endpoint.addr, deviceInfo->endpoint.port,
1142 deviceInfo->connType,
1143 query, sizeof(query), OIC_RSRC_PSTAT_URI))
1145 OIC_LOG(ERROR, TAG, "GetProvisioningStatusResource : Failed to generate query");
1146 return OC_STACK_ERROR;
1148 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1150 OCCallbackData cbData;
1151 cbData.cb = &ListMethodsHandler;
1152 cbData.context = (void *)otmCtx;
1154 OCStackResult res = OCDoResource(NULL, OC_REST_GET, query, NULL, NULL,
1155 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1156 if (res != OC_STACK_OK)
1158 OIC_LOG(ERROR, TAG, "OCStack resource error");
1161 OIC_LOG(DEBUG, TAG, "OUT GetProvisioningStatusResource");
1166 static OCStackResult PostOwnerUuid(OTMContext_t* otmCtx)
1168 OIC_LOG(DEBUG, TAG, "IN PostOwnerUuid");
1170 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1172 OIC_LOG(ERROR, TAG, "Invailed parameters");
1173 return OC_STACK_INVALID_PARAM;
1176 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1177 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1178 if(!PMGenerateQuery(true,
1179 deviceInfo->endpoint.addr, deviceInfo->securePort,
1180 deviceInfo->connType,
1181 query, sizeof(query), OIC_RSRC_DOXM_URI))
1183 OIC_LOG(ERROR, TAG, "PostOwnerUuid : Failed to generate query");
1184 return OC_STACK_ERROR;
1186 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1188 //Post PT's uuid to new device
1189 OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1192 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1193 return OC_STACK_NO_MEMORY;
1195 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1196 OCStackResult res = g_OTMDatas[deviceInfo->doxm->oxmSel].createOwnerTransferPayloadCB(
1197 otmCtx, &secPayload->securityData, &secPayload->payloadSize);
1198 if (OC_STACK_OK != res && NULL == secPayload->securityData)
1200 OCPayloadDestroy((OCPayload *)secPayload);
1201 OIC_LOG(ERROR, TAG, "Error while converting doxm bin to cbor.");
1202 return OC_STACK_INVALID_PARAM;
1204 OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1206 OCCallbackData cbData;
1207 cbData.cb = &OwnerUuidUpdateHandler;
1208 cbData.context = (void *)otmCtx;
1211 res = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload *)secPayload,
1212 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1213 if (res != OC_STACK_OK)
1215 OIC_LOG(ERROR, TAG, "OCStack resource error");
1218 OIC_LOG(DEBUG, TAG, "OUT PostOwnerUuid");
1223 static OCStackResult PostOwnershipInformation(OTMContext_t* otmCtx)
1225 OIC_LOG(DEBUG, TAG, "IN PostOwnershipInformation");
1227 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1229 OIC_LOG(ERROR, TAG, "Invailed parameters");
1230 return OC_STACK_INVALID_PARAM;
1233 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1234 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1235 if(!PMGenerateQuery(true,
1236 deviceInfo->endpoint.addr, deviceInfo->securePort,
1237 deviceInfo->connType,
1238 query, sizeof(query), OIC_RSRC_DOXM_URI))
1240 OIC_LOG(ERROR, TAG, "PostOwnershipInformation : Failed to generate query");
1241 return OC_STACK_ERROR;
1243 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1245 //OwnershipInformationHandler
1246 OCSecurityPayload *secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1249 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1250 return OC_STACK_NO_MEMORY;
1253 otmCtx->selectedDeviceInfo->doxm->owned = true;
1255 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1256 OCStackResult res = DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm,
1257 &secPayload->securityData, &secPayload->payloadSize, true);
1258 if (OC_STACK_OK != res && NULL == secPayload->securityData)
1260 OCPayloadDestroy((OCPayload *)secPayload);
1261 OIC_LOG(ERROR, TAG, "Error while converting doxm bin to json");
1262 return OC_STACK_INVALID_PARAM;
1265 OCCallbackData cbData;
1266 cbData.cb = &OwnershipInformationHandler;
1267 cbData.context = (void *)otmCtx;
1270 res = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload*)secPayload,
1271 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1272 if (res != OC_STACK_OK)
1274 OIC_LOG(ERROR, TAG, "OCStack resource error");
1277 OIC_LOG(DEBUG, TAG, "OUT PostOwnershipInformation");
1282 static OCStackResult PostUpdateOperationMode(OTMContext_t* otmCtx)
1284 OIC_LOG(DEBUG, TAG, "IN PostUpdateOperationMode");
1286 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1288 return OC_STACK_INVALID_PARAM;
1291 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1292 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1293 if(!PMGenerateQuery(false,
1294 deviceInfo->endpoint.addr, deviceInfo->endpoint.port,
1295 deviceInfo->connType,
1296 query, sizeof(query), OIC_RSRC_PSTAT_URI))
1298 OIC_LOG(ERROR, TAG, "PostUpdateOperationMode : Failed to generate query");
1299 return OC_STACK_ERROR;
1301 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1303 OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1306 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1307 return OC_STACK_NO_MEMORY;
1309 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1310 OCStackResult res = PstatToCBORPayload(deviceInfo->pstat, &secPayload->securityData,
1311 &secPayload->payloadSize, true);
1312 if (OC_STACK_OK != res)
1314 OCPayloadDestroy((OCPayload *)secPayload);
1315 OIC_LOG(ERROR, TAG, "Error while converting pstat to cbor.");
1316 return OC_STACK_INVALID_PARAM;
1319 OCCallbackData cbData;
1320 cbData.cb = &OperationModeUpdateHandler;
1321 cbData.context = (void *)otmCtx;
1323 res = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload *)secPayload,
1324 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1325 if (res != OC_STACK_OK)
1327 OIC_LOG(ERROR, TAG, "OCStack resource error");
1330 OIC_LOG(DEBUG, TAG, "OUT PostUpdateOperationMode");
1335 static OCStackResult StartOwnershipTransfer(void* ctx, OCProvisionDev_t* selectedDevice)
1337 OIC_LOG(INFO, TAG, "IN StartOwnershipTransfer");
1338 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
1339 otmCtx->selectedDeviceInfo = selectedDevice;
1341 //Set to the lowest level OxM, and then find more higher level OxM.
1342 OCStackResult res = SelectProvisioningMethod(selectedDevice->doxm->oxm,
1343 selectedDevice->doxm->oxmLen,
1344 &selectedDevice->doxm->oxmSel);
1345 if(OC_STACK_OK != res)
1347 OIC_LOG(ERROR, TAG, "Failed to select the provisioning method");
1348 SetResult(otmCtx, res);
1351 OIC_LOG_V(DEBUG, TAG, "Selected provisoning method = %d", selectedDevice->doxm->oxmSel);
1353 //Send Req: POST /oic/sec/doxm [{..."OxmSel" :g_OTMDatas[Index of Selected OxM].OXMString,...}]
1354 res = PostOwnerTransferModeToResource(otmCtx);
1355 if(OC_STACK_OK != res)
1357 OIC_LOG(WARNING, TAG, "Failed to select the provisioning method");
1358 SetResult(otmCtx, res);
1362 //Register DTLS event handler to catch the dtls event while handshake
1363 if(CA_ADAPTER_IP == ((CAEndpoint_t*)(&otmCtx->selectedDeviceInfo->endpoint))->adapter)
1365 if(CA_STATUS_OK != CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials))
1367 OIC_LOG(WARNING, TAG, "Failed to register DTLS handshake callback.");
1373 if(CA_STATUS_OK != CAregisterTlsCredentialsHandler(GetDtlsPskCredentials))
1375 OIC_LOG(WARNING, TAG, "Failed to register TLS handshake callback.");
1380 OIC_LOG(INFO, TAG, "OUT StartOwnershipTransfer");
1386 OCStackResult OTMSetOwnershipTransferCallbackData(OicSecOxm_t oxmType, OTMCallbackData_t* data)
1388 OIC_LOG(DEBUG, TAG, "IN OTMSetOwnerTransferCallbackData");
1392 OIC_LOG(ERROR, TAG, "OTMSetOwnershipTransferCallbackData : Invalid parameters");
1393 return OC_STACK_INVALID_PARAM;
1395 if(oxmType >= OIC_OXM_COUNT)
1397 OIC_LOG(INFO, TAG, "Unknow ownership transfer method");
1398 return OC_STACK_INVALID_PARAM;
1401 g_OTMDatas[oxmType].loadSecretCB= data->loadSecretCB;
1402 g_OTMDatas[oxmType].createSecureSessionCB = data->createSecureSessionCB;
1403 g_OTMDatas[oxmType].createSelectOxmPayloadCB = data->createSelectOxmPayloadCB;
1404 g_OTMDatas[oxmType].createOwnerTransferPayloadCB = data->createOwnerTransferPayloadCB;
1406 OIC_LOG(DEBUG, TAG, "OUT OTMSetOwnerTransferCallbackData");
1412 * NOTE : Unowned discovery should be done before performing OTMDoOwnershipTransfer
1414 OCStackResult OTMDoOwnershipTransfer(void* ctx,
1415 OCProvisionDev_t *selectedDevicelist,
1416 OCProvisionResultCB resultCallback)
1418 OIC_LOG(DEBUG, TAG, "IN OTMDoOwnershipTransfer");
1420 if (NULL == selectedDevicelist)
1422 return OC_STACK_INVALID_PARAM;
1424 if (NULL == resultCallback)
1426 return OC_STACK_INVALID_CALLBACK;
1429 OTMContext_t* otmCtx = (OTMContext_t*)OICCalloc(1,sizeof(OTMContext_t));
1432 OIC_LOG(ERROR, TAG, "Failed to create OTM Context");
1433 return OC_STACK_NO_MEMORY;
1435 otmCtx->ctxResultCallback = resultCallback;
1436 otmCtx->ctxHasError = false;
1437 otmCtx->userCtx = ctx;
1438 OCProvisionDev_t* pCurDev = selectedDevicelist;
1440 //Counting number of selected devices.
1441 otmCtx->ctxResultArraySize = 0;
1442 while(NULL != pCurDev)
1444 otmCtx->ctxResultArraySize++;
1445 pCurDev = pCurDev->next;
1448 otmCtx->ctxResultArray =
1449 (OCProvisionResult_t*)OICCalloc(otmCtx->ctxResultArraySize, sizeof(OCProvisionResult_t));
1450 if(NULL == otmCtx->ctxResultArray)
1452 OIC_LOG(ERROR, TAG, "OTMDoOwnershipTransfer : Failed to memory allocation");
1454 return OC_STACK_NO_MEMORY;
1456 pCurDev = selectedDevicelist;
1458 OCStackResult res = OC_STACK_OK;
1459 //Fill the device UUID for result array.
1460 for(size_t devIdx = 0; devIdx < otmCtx->ctxResultArraySize; devIdx++)
1462 //Checking duplication of Device ID.
1463 bool isDuplicate = true;
1464 res = PDMIsDuplicateDevice(&pCurDev->doxm->deviceID, &isDuplicate);
1465 if (OC_STACK_OK != res)
1471 bool isStale = false;
1472 res = PDMIsDeviceStale(&pCurDev->doxm->deviceID, &isStale);
1473 if(OC_STACK_OK != res)
1475 OIC_LOG(ERROR, TAG, "Internal error in PDMIsDeviceStale");
1480 OIC_LOG(INFO, TAG, "Detected duplicated UUID in stale status, "\
1481 "this UUID will be removed from PDM");
1483 res = PDMDeleteDevice(&pCurDev->doxm->deviceID);
1484 if(OC_STACK_OK != res)
1486 OIC_LOG(ERROR, TAG, "Internal error in PDMDeleteDevice");
1492 OIC_LOG(ERROR, TAG, "OTMDoOwnershipTransfer : Device UUID is duplicated");
1493 res = OC_STACK_INVALID_PARAM;
1497 memcpy(otmCtx->ctxResultArray[devIdx].deviceId.id,
1498 pCurDev->doxm->deviceID.id,
1500 otmCtx->ctxResultArray[devIdx].res = OC_STACK_CONTINUE;
1501 pCurDev = pCurDev->next;
1504 StartOwnershipTransfer(otmCtx, selectedDevicelist);
1506 OIC_LOG(DEBUG, TAG, "OUT OTMDoOwnershipTransfer");
1510 OICFree(otmCtx->ctxResultArray);
1515 OCStackResult PostProvisioningStatus(OTMContext_t* otmCtx)
1517 OIC_LOG(INFO, TAG, "IN PostProvisioningStatus");
1519 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1521 OIC_LOG(ERROR, TAG, "OTMContext is NULL");
1522 return OC_STACK_INVALID_PARAM;
1525 //Change the TAKE_OWNER bit of CM to 0.
1526 otmCtx->selectedDeviceInfo->pstat->cm &= (~TAKE_OWNER);
1528 OCSecurityPayload *secPayload = (OCSecurityPayload *)OICCalloc(1, sizeof(OCSecurityPayload));
1531 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1532 return OC_STACK_NO_MEMORY;
1534 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1535 if (OC_STACK_OK != PstatToCBORPayload(otmCtx->selectedDeviceInfo->pstat,
1536 &secPayload->securityData, &secPayload->payloadSize, true))
1538 OCPayloadDestroy((OCPayload *)secPayload);
1539 return OC_STACK_INVALID_JSON;
1541 OIC_LOG(DEBUG, TAG, "Created payload for chage to Provisiong state");
1542 OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1544 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1545 if(!PMGenerateQuery(true,
1546 otmCtx->selectedDeviceInfo->endpoint.addr,
1547 otmCtx->selectedDeviceInfo->securePort,
1548 otmCtx->selectedDeviceInfo->connType,
1549 query, sizeof(query), OIC_RSRC_PSTAT_URI))
1551 OIC_LOG(ERROR, TAG, "PostProvisioningStatus : Failed to generate query");
1552 return OC_STACK_ERROR;
1554 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1556 OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
1557 cbData.cb = &ProvisioningStatusHandler;
1558 cbData.context = (void*)otmCtx;
1560 OCStackResult ret = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload*)secPayload,
1561 otmCtx->selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1562 OIC_LOG_V(INFO, TAG, "OCDoResource returned: %d",ret);
1563 if (ret != OC_STACK_OK)
1565 OIC_LOG(ERROR, TAG, "OCStack resource error");
1568 OIC_LOG(INFO, TAG, "OUT PostProvisioningStatus");
1573 OCStackResult PostNormalOperationStatus(OTMContext_t* otmCtx)
1575 OIC_LOG(INFO, TAG, "IN PostNormalOperationStatus");
1577 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1579 OIC_LOG(ERROR, TAG, "OTMContext is NULL");
1580 return OC_STACK_INVALID_PARAM;
1584 otmCtx->selectedDeviceInfo->pstat->isOp = true;
1586 OCSecurityPayload *secPayload = (OCSecurityPayload *)OICCalloc(1, sizeof(OCSecurityPayload));
1589 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1590 return OC_STACK_NO_MEMORY;
1592 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1593 if (OC_STACK_OK != PstatToCBORPayload(otmCtx->selectedDeviceInfo->pstat,
1594 &secPayload->securityData, &secPayload->payloadSize, true))
1596 OCPayloadDestroy((OCPayload *)secPayload);
1597 return OC_STACK_INVALID_JSON;
1599 OIC_LOG(DEBUG, TAG, "Created payload for chage to Provisiong state");
1600 OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1602 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1603 if(!PMGenerateQuery(true,
1604 otmCtx->selectedDeviceInfo->endpoint.addr,
1605 otmCtx->selectedDeviceInfo->securePort,
1606 otmCtx->selectedDeviceInfo->connType,
1607 query, sizeof(query), OIC_RSRC_PSTAT_URI))
1609 OIC_LOG(ERROR, TAG, "PostNormalOperationStatus : Failed to generate query");
1610 return OC_STACK_ERROR;
1612 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1614 OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
1615 cbData.cb = &ReadyForNomalStatusHandler;
1616 cbData.context = (void*)otmCtx;
1618 OCStackResult ret = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload*)secPayload,
1619 otmCtx->selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1620 OIC_LOG_V(INFO, TAG, "OCDoResource returned: %d",ret);
1621 if (ret != OC_STACK_OK)
1623 OIC_LOG(ERROR, TAG, "OCStack resource error");
1626 OIC_LOG(INFO, TAG, "OUT PostNormalOperationStatus");