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)
248 if(CA_STATUS_OK != CAregisterTlsCredentialsHandler(GetDtlsPskCredentials))
250 OIC_LOG(WARNING, TAG, "Failed to revert is TLS credential handler.");
253 if(CA_STATUS_OK != CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials))
255 OIC_LOG(WARNING, TAG, "Failed to revert is DTLS credential handler.");
257 OicUuid_t emptyUuid = { .id={0}};
258 SetUuidForRandomPinOxm(&emptyUuid);
261 for(size_t i = 0; i < otmCtx->ctxResultArraySize; i++)
263 if(memcmp(otmCtx->selectedDeviceInfo->doxm->deviceID.id,
264 otmCtx->ctxResultArray[i].deviceId.id, UUID_LENGTH) == 0)
266 otmCtx->ctxResultArray[i].res = res;
267 if(OC_STACK_OK != res)
269 otmCtx->ctxHasError = true;
276 //If all request is completed, invoke the user callback.
277 if(IsComplete(otmCtx))
279 otmCtx->ctxResultCallback(otmCtx->userCtx, otmCtx->ctxResultArraySize,
280 otmCtx->ctxResultArray, otmCtx->ctxHasError);
281 OICFree(otmCtx->ctxResultArray);
286 if(OC_STACK_OK != StartOwnershipTransfer(otmCtx,
287 otmCtx->selectedDeviceInfo->next))
289 OIC_LOG(ERROR, TAG, "Failed to StartOwnershipTransfer");
294 OIC_LOG(DEBUG, TAG, "OUT SetResult");
298 * Function to handle the handshake result in OTM.
299 * This function will be invoked after DTLS handshake
300 * @param endPoint [IN] The remote endpoint.
301 * @param errorInfo [IN] Error information from the endpoint.
304 void DTLSHandshakeCB(const CAEndpoint_t *endpoint, const CAErrorInfo_t *info)
306 if(NULL != g_otmCtx && NULL != g_otmCtx->selectedDeviceInfo &&
307 NULL != endpoint && NULL != info)
309 OIC_LOG_V(INFO, TAG, "Received status from remote device(%s:%d) : %d",
310 endpoint->addr, endpoint->port, info->result);
312 OicSecDoxm_t* newDevDoxm = g_otmCtx->selectedDeviceInfo->doxm;
314 if(NULL != newDevDoxm)
316 OicUuid_t emptyUuid = {.id={0}};
318 //Make sure the address matches.
319 if(strncmp(g_otmCtx->selectedDeviceInfo->endpoint.addr,
321 sizeof(endpoint->addr)) == 0 &&
322 g_otmCtx->selectedDeviceInfo->securePort == endpoint->port)
324 OCStackResult res = OC_STACK_ERROR;
326 //If temporal secure sesstion established successfully
327 if(CA_STATUS_OK == info->result &&
328 false == newDevDoxm->owned &&
329 memcmp(&(newDevDoxm->owner), &emptyUuid, sizeof(OicUuid_t)) == 0)
331 //Send request : POST /oic/sec/doxm [{... , "devowner":"PT's UUID"}]
332 res = PostOwnerUuid(g_otmCtx);
333 if(OC_STACK_OK != res)
335 OIC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to send owner information");
336 SetResult(g_otmCtx, res);
339 //In case of authentication failure
340 else if(CA_DTLS_AUTHENTICATION_FAILURE == info->result)
342 //in case of error from owner credential
343 if(memcmp(&(newDevDoxm->owner), &emptyUuid, sizeof(OicUuid_t)) != 0 &&
344 true == newDevDoxm->owned)
346 OIC_LOG(ERROR, TAG, "The owner credential may incorrect.");
348 if(OC_STACK_OK != RemoveCredential(&(newDevDoxm->deviceID)))
350 OIC_LOG(WARNING, TAG, "Failed to remove the invaild owner credential");
352 SetResult(g_otmCtx, OC_STACK_AUTHENTICATION_FAILURE);
354 //in case of error from wrong PIN, re-start the ownership transfer
355 else if(OIC_RANDOM_DEVICE_PIN == newDevDoxm->oxmSel)
357 OIC_LOG(ERROR, TAG, "The PIN number may incorrect.");
359 memcpy(&(newDevDoxm->owner), &emptyUuid, sizeof(OicUuid_t));
360 newDevDoxm->owned = false;
361 g_otmCtx->attemptCnt++;
363 if(WRONG_PIN_MAX_ATTEMP > g_otmCtx->attemptCnt)
365 res = StartOwnershipTransfer(g_otmCtx, g_otmCtx->selectedDeviceInfo);
366 if(OC_STACK_OK != res)
368 SetResult(g_otmCtx, res);
369 OIC_LOG(ERROR, TAG, "Failed to Re-StartOwnershipTransfer");
374 OIC_LOG(ERROR, TAG, "User has exceeded the number of authentication attempts.");
375 SetResult(g_otmCtx, OC_STACK_AUTHENTICATION_FAILURE);
380 OIC_LOG(ERROR, TAG, "Failed to establish secure session.");
381 SetResult(g_otmCtx, OC_STACK_AUTHENTICATION_FAILURE);
390 * Function to save ownerPSK at provisioning tool end.
392 * @param[in] selectedDeviceInfo selected device information to performing provisioning.
393 * @return OC_STACK_OK on success
395 static OCStackResult SaveOwnerPSK(OCProvisionDev_t *selectedDeviceInfo)
397 OIC_LOG(DEBUG, TAG, "IN SaveOwnerPSK");
399 OCStackResult res = OC_STACK_ERROR;
401 CAEndpoint_t endpoint;
402 memset(&endpoint, 0x00, sizeof(CAEndpoint_t));
403 OICStrcpy(endpoint.addr, MAX_ADDR_STR_SIZE_CA, selectedDeviceInfo->endpoint.addr);
404 endpoint.addr[MAX_ADDR_STR_SIZE_CA - 1] = '\0';
405 endpoint.port = selectedDeviceInfo->securePort;
406 endpoint.adapter = selectedDeviceInfo->endpoint.adapter;
408 OicUuid_t ptDeviceID = {.id={0}};
409 if (OC_STACK_OK != GetDoxmDeviceID(&ptDeviceID))
411 OIC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
415 uint8_t ownerPSK[OWNER_PSK_LENGTH_128] = {0};
416 OicSecKey_t ownerKey = {ownerPSK, OWNER_PSK_LENGTH_128};
418 //Generating OwnerPSK
419 CAResult_t pskRet = CAGenerateOwnerPSK(&endpoint,
420 (uint8_t *)GetOxmString(selectedDeviceInfo->doxm->oxmSel),
421 strlen(GetOxmString(selectedDeviceInfo->doxm->oxmSel)),
422 ptDeviceID.id, sizeof(ptDeviceID.id),
423 selectedDeviceInfo->doxm->deviceID.id, sizeof(selectedDeviceInfo->doxm->deviceID.id),
424 ownerPSK, OWNER_PSK_LENGTH_128);
426 if (CA_STATUS_OK == pskRet)
428 OIC_LOG(INFO, TAG,"ownerPSK dump:\n");
429 OIC_LOG_BUFFER(INFO, TAG,ownerPSK, OWNER_PSK_LENGTH_128);
430 //Generating new credential for provisioning tool
431 OicSecCred_t *cred = GenerateCredential(&selectedDeviceInfo->doxm->deviceID,
432 SYMMETRIC_PAIR_WISE_KEY, NULL,
433 &ownerKey, &ptDeviceID);
434 VERIFY_NON_NULL(TAG, cred, ERROR);
436 // TODO: Added as workaround. Will be replaced soon.
437 cred->privateData.encoding = OIC_ENCODING_RAW;
440 // NOTE: Test codes to use BASE64 encoded owner PSK.
441 uint32_t outSize = 0;
442 size_t b64BufSize = B64ENCODE_OUT_SAFESIZE((OWNER_PSK_LENGTH_128 + 1));
443 char* b64Buf = (uint8_t *)OICCalloc(1, b64BufSize);
444 VERIFY_NON_NULL(TAG, b64Buf, ERROR);
445 b64Encode(cred->privateData.data, cred->privateData.len, b64Buf, b64BufSize, &outSize);
447 OICFree( cred->privateData.data );
448 cred->privateData.data = (uint8_t *)OICCalloc(1, outSize + 1);
449 VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
451 strncpy(cred->privateData.data, b64Buf, outSize);
452 cred->privateData.data[outSize] = '\0';
453 cred->privateData.encoding = OIC_ENCODING_BASE64;
454 cred->privateData.len = outSize;
456 #endif //End of Test codes
458 res = AddCredential(cred);
459 if(res != OC_STACK_OK)
461 DeleteCredList(cred);
467 OIC_LOG(ERROR, TAG, "CAGenerateOwnerPSK failed");
470 OIC_LOG(DEBUG, TAG, "OUT SaveOwnerPSK");
476 * Callback handler for OwnerShipTransferModeHandler API.
478 * @param[in] ctx ctx value passed to callback from calling function.
479 * @param[in] UNUSED handle to an invocation
480 * @param[in] clientResponse Response from queries to remote servers.
481 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
482 * and OC_STACK_KEEP_TRANSACTION to keep it.
484 static OCStackApplicationResult OwnerTransferModeHandler(void *ctx, OCDoHandle UNUSED,
485 OCClientResponse *clientResponse)
487 OIC_LOG(DEBUG, TAG, "IN OwnerTransferModeHandler");
489 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
490 VERIFY_NON_NULL(TAG, ctx, WARNING);
492 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
494 if (OC_STACK_RESOURCE_CHANGED == clientResponse->result)
496 OIC_LOG(INFO, TAG, "OwnerTransferModeHandler : response result = OC_STACK_OK");
497 //Send request : GET /oic/sec/pstat
498 OCStackResult res = GetProvisioningStatusResource(otmCtx);
499 if(OC_STACK_OK != res)
501 OIC_LOG(WARNING, TAG, "Failed to get pstat information");
502 SetResult(otmCtx, res);
507 OIC_LOG_V(WARNING, TAG, "OwnerTransferModeHandler : Client response is incorrect : %d",
508 clientResponse->result);
509 SetResult(otmCtx, clientResponse->result);
512 OIC_LOG(DEBUG, TAG, "OUT OwnerTransferModeHandler");
515 return OC_STACK_DELETE_TRANSACTION;
519 * Callback handler for ProvisioningStatusResouceHandler API.
521 * @param[in] ctx ctx value passed to callback from calling function.
522 * @param[in] UNUSED handle to an invocation
523 * @param[in] clientResponse Response from queries to remote servers.
524 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
525 * and OC_STACK_KEEP_TRANSACTION to keep it.
527 static OCStackApplicationResult ListMethodsHandler(void *ctx, OCDoHandle UNUSED,
528 OCClientResponse *clientResponse)
530 OIC_LOG(DEBUG, TAG, "IN ListMethodsHandler");
532 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
533 VERIFY_NON_NULL(TAG, ctx, WARNING);
535 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
537 if (OC_STACK_OK == clientResponse->result)
539 if (NULL == clientResponse->payload)
541 OIC_LOG(INFO, TAG, "Skiping Null payload");
542 SetResult(otmCtx, OC_STACK_ERROR);
543 return OC_STACK_DELETE_TRANSACTION;
546 if (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)
548 OIC_LOG(INFO, TAG, "Unknown payload type");
549 SetResult(otmCtx, OC_STACK_ERROR);
550 return OC_STACK_DELETE_TRANSACTION;
552 OicSecPstat_t* pstat = NULL;
553 OCStackResult result = CBORPayloadToPstat(
554 ((OCSecurityPayload*)clientResponse->payload)->securityData,
555 ((OCSecurityPayload*)clientResponse->payload)->payloadSize,
557 if(NULL == pstat || result != OC_STACK_OK)
559 OIC_LOG(ERROR, TAG, "Error while converting cbor to pstat.");
560 SetResult(otmCtx, OC_STACK_ERROR);
561 return OC_STACK_DELETE_TRANSACTION;
563 if(false == (TAKE_OWNER & pstat->cm))
565 OIC_LOG(ERROR, TAG, "Device pairing mode enabling owner transfer operations is disabled");
566 SetResult(otmCtx, OC_STACK_ERROR);
567 return OC_STACK_DELETE_TRANSACTION;
569 otmCtx->selectedDeviceInfo->pstat = pstat;
571 //Select operation mode (Currently supported SINGLE_SERVICE_CLIENT_DRIVEN only)
572 SelectOperationMode(otmCtx->selectedDeviceInfo, &(otmCtx->selectedDeviceInfo->pstat->om));
574 //Send request : POST /oic/sec/pstat [{"om":"bx11", .. }]
575 OCStackResult res = PostUpdateOperationMode(otmCtx);
576 if (OC_STACK_OK != res)
578 OIC_LOG(ERROR, TAG, "Error while updating operation mode.");
579 SetResult(otmCtx, res);
584 OIC_LOG_V(WARNING, TAG, "ListMethodsHandler : Client response is incorrect : %d",
585 clientResponse->result);
586 SetResult(otmCtx, clientResponse->result);
589 OIC_LOG(DEBUG, TAG, "OUT ListMethodsHandler");
591 return OC_STACK_DELETE_TRANSACTION;
595 * Response handler for update owner uuid request.
597 * @param[in] ctx ctx value passed to callback from calling function.
598 * @param[in] UNUSED handle to an invocation
599 * @param[in] clientResponse Response from queries to remote servers.
600 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
601 * and OC_STACK_KEEP_TRANSACTION to keep it.
603 static OCStackApplicationResult OwnerUuidUpdateHandler(void *ctx, OCDoHandle UNUSED,
604 OCClientResponse *clientResponse)
606 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
607 VERIFY_NON_NULL(TAG, ctx, WARNING);
609 OIC_LOG(DEBUG, TAG, "IN OwnerUuidUpdateHandler");
611 OCStackResult res = OC_STACK_OK;
612 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
614 if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
616 if(otmCtx && otmCtx->selectedDeviceInfo)
618 res = SaveOwnerPSK(otmCtx->selectedDeviceInfo);
619 if(OC_STACK_OK != res)
621 OIC_LOG(ERROR, TAG, "OwnerUuidUpdateHandler:Failed to owner PSK generation");
622 SetResult(otmCtx, res);
623 return OC_STACK_DELETE_TRANSACTION;
626 //POST owner credential to new device according to security spec B.
627 res = PostOwnerCredential(otmCtx);
628 if(OC_STACK_OK != res)
631 "OwnerUuidUpdateHandler:Failed to send PosT request for onwer credential");
632 SetResult(otmCtx, res);
633 return OC_STACK_DELETE_TRANSACTION;
639 res = clientResponse->result;
640 OIC_LOG_V(ERROR, TAG, "OwnerUuidHandler : Unexpected result %d", res);
641 SetResult(otmCtx, res);
644 OIC_LOG(DEBUG, TAG, "OUT OwnerUuidUpdateHandler");
647 return OC_STACK_DELETE_TRANSACTION;
651 * Response handler for update operation mode.
653 * @param[in] ctx ctx value passed to callback from calling function.
654 * @param[in] UNUSED handle to an invocation
655 * @param[in] clientResponse Response from queries to remote servers.
656 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
657 * and OC_STACK_KEEP_TRANSACTION to keep it.
659 static OCStackApplicationResult OperationModeUpdateHandler(void *ctx, OCDoHandle UNUSED,
660 OCClientResponse *clientResponse)
662 OIC_LOG(DEBUG, TAG, "IN OperationModeUpdateHandler");
664 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
665 VERIFY_NON_NULL(TAG, ctx, WARNING);
667 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
669 if (OC_STACK_RESOURCE_CHANGED == clientResponse->result)
671 OCStackResult res = OC_STACK_ERROR;
672 OicSecOxm_t selOxm = otmCtx->selectedDeviceInfo->doxm->oxmSel;
674 //Load secret for temporal secure session.
675 if(g_OTMDatas[selOxm].loadSecretCB)
677 res = g_OTMDatas[selOxm].loadSecretCB(otmCtx);
678 if(OC_STACK_OK != res)
680 OIC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to load secret");
681 SetResult(otmCtx, res);
682 return OC_STACK_DELETE_TRANSACTION;
686 //It will be used in handshake event handler
689 //Try DTLS handshake to generate secure session
690 if(g_OTMDatas[selOxm].createSecureSessionCB)
692 res = g_OTMDatas[selOxm].createSecureSessionCB(otmCtx);
693 if(OC_STACK_OK != res)
695 OIC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to create DTLS session");
696 SetResult(otmCtx, res);
697 return OC_STACK_DELETE_TRANSACTION;
703 OIC_LOG(ERROR, TAG, "Error while update operation mode");
704 SetResult(otmCtx, clientResponse->result);
707 OIC_LOG(DEBUG, TAG, "OUT OperationModeUpdateHandler");
710 return OC_STACK_DELETE_TRANSACTION;
714 * Response handler for update owner crendetial request.
716 * @param[in] ctx ctx value passed to callback from calling function.
717 * @param[in] UNUSED handle to an invocation
718 * @param[in] clientResponse Response from queries to remote servers.
719 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
720 * and OC_STACK_KEEP_TRANSACTION to keep it.
722 static OCStackApplicationResult OwnerCredentialHandler(void *ctx, OCDoHandle UNUSED,
723 OCClientResponse *clientResponse)
725 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
726 VERIFY_NON_NULL(TAG, ctx, WARNING);
728 OIC_LOG(DEBUG, TAG, "IN OwnerCredentialHandler");
730 OCStackResult res = OC_STACK_OK;
731 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
733 if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
735 if(otmCtx && otmCtx->selectedDeviceInfo)
737 //Close the temporal secure session to verify the owner credential
738 CAEndpoint_t* endpoint = (CAEndpoint_t *)&otmCtx->selectedDeviceInfo->endpoint;
739 endpoint->port = otmCtx->selectedDeviceInfo->securePort;
740 CAResult_t caResult = CA_STATUS_OK;
741 if(CA_ADAPTER_IP == endpoint->adapter)
743 caResult = CACloseDtlsSession(endpoint);
748 caResult = CAcloseTlsConnection(endpoint);
751 if(CA_STATUS_OK != caResult)
753 OIC_LOG(ERROR, TAG, "Failed to close DTLS session");
754 SetResult(otmCtx, caResult);
755 return OC_STACK_DELETE_TRANSACTION;
759 * If we select NULL cipher,
760 * client will select appropriate cipher suite according to server's cipher-suite list.
762 if(CA_ADAPTER_IP == endpoint->adapter)
764 caResult = CASelectCipherSuite(TLS_NULL_WITH_NULL_NULL, endpoint->adapter);
768 // TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256 = 0xC037, /**< see RFC 5489 */
769 caResult = CASelectCipherSuite(0xC037, endpoint->adapter);
772 if(CA_STATUS_OK != caResult)
774 OIC_LOG(ERROR, TAG, "Failed to select TLS_NULL_WITH_NULL_NULL");
775 SetResult(otmCtx, caResult);
776 return OC_STACK_DELETE_TRANSACTION;
780 * in case of random PIN based OxM,
781 * revert get_psk_info callback of tinyDTLS to use owner credential.
783 if(OIC_RANDOM_DEVICE_PIN == otmCtx->selectedDeviceInfo->doxm->oxmSel)
785 OicUuid_t emptyUuid = { .id={0}};
786 SetUuidForRandomPinOxm(&emptyUuid);
788 if(CA_ADAPTER_IP == endpoint->adapter)
790 caResult = CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials);
795 caResult = CAregisterTlsCredentialsHandler(GetDtlsPskCredentials);
799 if(CA_STATUS_OK != caResult)
801 OIC_LOG(ERROR, TAG, "Failed to revert DTLS credential handler.");
802 SetResult(otmCtx, OC_STACK_INVALID_CALLBACK);
803 return OC_STACK_DELETE_TRANSACTION;
807 otmCtx->selectedDeviceInfo->connType |= CT_FLAG_SECURE;
809 //POST /oic/sec/doxm [{ ..., "owned":"TRUE" }]
810 res = PostOwnershipInformation(otmCtx);
811 if(OC_STACK_OK != res)
813 OIC_LOG(ERROR, TAG, "Failed to post ownership information to new device");
814 SetResult(otmCtx, res);
815 return OC_STACK_DELETE_TRANSACTION;
821 res = clientResponse->result;
822 OIC_LOG_V(ERROR, TAG, "OwnerCredentialHandler : Unexpected result %d", res);
823 SetResult(otmCtx, res);
826 OIC_LOG(DEBUG, TAG, "OUT OwnerCredentialHandler");
829 return OC_STACK_DELETE_TRANSACTION;
834 * Response handler for update owner information request.
836 * @param[in] ctx ctx value passed to callback from calling function.
837 * @param[in] UNUSED handle to an invocation
838 * @param[in] clientResponse Response from queries to remote servers.
839 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
840 * and OC_STACK_KEEP_TRANSACTION to keep it.
842 static OCStackApplicationResult OwnershipInformationHandler(void *ctx, OCDoHandle UNUSED,
843 OCClientResponse *clientResponse)
845 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
846 VERIFY_NON_NULL(TAG, ctx, WARNING);
848 OIC_LOG(DEBUG, TAG, "IN OwnershipInformationHandler");
850 OCStackResult res = OC_STACK_OK;
851 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
853 if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
855 if(otmCtx && otmCtx->selectedDeviceInfo)
857 OIC_LOG(INFO, TAG, "Ownership transfer was successfully completed.");
858 OIC_LOG(INFO, TAG, "Set Ready for provisioning state .");
860 res = PostProvisioningStatus(otmCtx);
861 if(OC_STACK_OK != res)
863 OIC_LOG(ERROR, TAG, "Failed to update pstat");
864 SetResult(otmCtx, res);
870 res = clientResponse->result;
871 OIC_LOG_V(ERROR, TAG, "OwnershipInformationHandler : Unexpected result %d", res);
872 SetResult(otmCtx, res);
875 OIC_LOG(DEBUG, TAG, "OUT OwnershipInformationHandler");
878 return OC_STACK_DELETE_TRANSACTION;
882 * Response handler of update provisioning status.
884 * @param[in] ctx ctx value passed to callback from calling function.
885 * @param[in] UNUSED handle to an invocation
886 * @param[in] clientResponse Response from queries to remote servers.
887 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
888 * and OC_STACK_KEEP_TRANSACTION to keep it.
890 static OCStackApplicationResult ProvisioningStatusHandler(void *ctx, OCDoHandle UNUSED,
891 OCClientResponse *clientResponse)
893 OIC_LOG_V(INFO, TAG, "IN ProvisioningStatusHandler.");
895 VERIFY_NON_NULL(TAG, clientResponse, ERROR);
896 VERIFY_NON_NULL(TAG, ctx, ERROR);
898 OTMContext_t* otmCtx = (OTMContext_t*) ctx;
900 OCStackResult res = OC_STACK_OK;
902 if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
904 if(otmCtx && otmCtx->selectedDeviceInfo)
906 OIC_LOG(INFO, TAG, "Device state is in Ready for Provisionig.");
908 res = PostNormalOperationStatus(otmCtx);
909 if(OC_STACK_OK != res)
911 OIC_LOG(ERROR, TAG, "Failed to update pstat");
912 SetResult(otmCtx, res);
918 OIC_LOG_V(INFO, TAG, "Error occured in provisionDefaultACLCB :: %d\n",
919 clientResponse->result);
920 SetResult(otmCtx, clientResponse->result);
924 OIC_LOG_V(INFO, TAG, "OUT ProvisioningStatusHandler.");
925 return OC_STACK_DELETE_TRANSACTION;
929 * Response handler of update provisioning status to Ready for Normal..
931 * @param[in] ctx ctx value passed to callback from calling function.
932 * @param[in] UNUSED handle to an invocation
933 * @param[in] clientResponse Response from queries to remote servers.
934 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
935 * and OC_STACK_KEEP_TRANSACTION to keep it.
937 static OCStackApplicationResult ReadyForNomalStatusHandler(void *ctx, OCDoHandle UNUSED,
938 OCClientResponse *clientResponse)
940 OIC_LOG_V(INFO, TAG, "IN ReadyForNomalStatusHandler.");
942 VERIFY_NON_NULL(TAG, clientResponse, ERROR);
943 VERIFY_NON_NULL(TAG, ctx, ERROR);
945 OTMContext_t* otmCtx = (OTMContext_t*) ctx;
948 if (OC_STACK_RESOURCE_CHANGED == clientResponse->result)
950 OIC_LOG(INFO, TAG, "Device state is in Ready for Normal Operation.");
951 OCStackResult res = PDMAddDevice(&otmCtx->selectedDeviceInfo->doxm->deviceID);
952 if (OC_STACK_OK == res)
954 OIC_LOG_V(INFO, TAG, "Add device's UUID in PDM_DB");
955 SetResult(otmCtx, OC_STACK_OK);
956 return OC_STACK_DELETE_TRANSACTION;
960 OIC_LOG(ERROR, TAG, "Ownership transfer is complete but adding information to DB is failed.");
965 OIC_LOG_V(INFO, TAG, "Error occured in provisionDefaultACLCB :: %d\n",
966 clientResponse->result);
967 SetResult(otmCtx, clientResponse->result);
971 OIC_LOG_V(INFO, TAG, "OUT ReadyForNomalStatusHandler.");
972 return OC_STACK_DELETE_TRANSACTION;
975 static OCStackResult PostOwnerCredential(OTMContext_t* otmCtx)
977 OIC_LOG(DEBUG, TAG, "IN PostOwnerCredential");
979 if(!otmCtx || !otmCtx->selectedDeviceInfo)
981 OIC_LOG(ERROR, TAG, "Invalid parameters");
982 return OC_STACK_INVALID_PARAM;
985 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
986 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
988 if(!PMGenerateQuery(true,
989 deviceInfo->endpoint.addr, deviceInfo->securePort,
990 deviceInfo->connType,
991 query, sizeof(query), OIC_RSRC_CRED_URI))
993 OIC_LOG(ERROR, TAG, "PostOwnerCredential : Failed to generate query");
994 return OC_STACK_ERROR;
996 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
997 OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1000 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1001 return OC_STACK_NO_MEMORY;
1004 //Generate owner credential for new device
1005 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1006 const OicSecCred_t* ownerCredential = GetCredResourceData(&(deviceInfo->doxm->deviceID));
1007 if(!ownerCredential)
1009 OIC_LOG(ERROR, TAG, "Can not find OwnerPSK.");
1010 return OC_STACK_NO_RESOURCE;
1013 OicUuid_t credSubjectId = {.id={0}};
1014 if(OC_STACK_OK == GetDoxmDeviceID(&credSubjectId))
1016 OicSecCred_t newCredential;
1017 memcpy(&newCredential, ownerCredential, sizeof(OicSecCred_t));
1018 newCredential.next = NULL;
1020 //Set subject ID as PT's ID
1021 memcpy(&(newCredential.subject), &credSubjectId, sizeof(OicUuid_t));
1023 //Fill private data as empty string
1024 newCredential.privateData.data = "";
1025 newCredential.privateData.len = 0;
1026 newCredential.privateData.encoding = ownerCredential->privateData.encoding;
1027 #ifdef __WITH_X509__
1028 newCredential.publicData.data = NULL;
1029 newCredential.publicData.len = 0;
1032 //Send owner credential to new device : POST /oic/sec/cred [ owner credential ]
1033 if (OC_STACK_OK != CredToCBORPayload(&newCredential, &secPayload->securityData,
1034 &secPayload->payloadSize, secureFlag))
1036 OICFree(secPayload);
1037 OIC_LOG(ERROR, TAG, "Error while converting bin to cbor.");
1038 return OC_STACK_ERROR;
1040 OIC_LOG(DEBUG, TAG, "Cred Payload:");
1041 OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1043 OCCallbackData cbData;
1044 cbData.cb = &OwnerCredentialHandler;
1045 cbData.context = (void *)otmCtx;
1047 OCStackResult res = OCDoResource(NULL, OC_REST_POST, query,
1048 &deviceInfo->endpoint, (OCPayload*)secPayload,
1049 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1050 if (res != OC_STACK_OK)
1052 OIC_LOG(ERROR, TAG, "OCStack resource error");
1057 OIC_LOG(ERROR, TAG, "Failed to read DOXM device ID.");
1058 return OC_STACK_NO_RESOURCE;
1061 OIC_LOG(DEBUG, TAG, "OUT PostOwnerCredential");
1066 static OCStackResult PostOwnerTransferModeToResource(OTMContext_t* otmCtx)
1068 OIC_LOG(DEBUG, TAG, "IN PostOwnerTransferModeToResource");
1070 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1072 OIC_LOG(ERROR, TAG, "Invalid parameters");
1073 return OC_STACK_INVALID_PARAM;
1076 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1077 OicSecOxm_t selectedOxm = deviceInfo->doxm->oxmSel;
1078 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1080 if(!PMGenerateQuery(false,
1081 deviceInfo->endpoint.addr, deviceInfo->endpoint.port,
1082 deviceInfo->connType,
1083 query, sizeof(query), OIC_RSRC_DOXM_URI))
1085 OIC_LOG(ERROR, TAG, "PostOwnerTransferModeToResource : Failed to generate query");
1086 return OC_STACK_ERROR;
1088 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1089 OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1092 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1093 return OC_STACK_NO_MEMORY;
1095 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1096 OCStackResult res = g_OTMDatas[selectedOxm].createSelectOxmPayloadCB(otmCtx,
1097 &secPayload->securityData, &secPayload->payloadSize);
1098 if (OC_STACK_OK != res && NULL == secPayload->securityData)
1100 OCPayloadDestroy((OCPayload *)secPayload);
1101 OIC_LOG(ERROR, TAG, "Error while converting bin to cbor");
1102 return OC_STACK_ERROR;
1105 OCCallbackData cbData;
1106 cbData.cb = &OwnerTransferModeHandler;
1107 cbData.context = (void *)otmCtx;
1109 res = OCDoResource(NULL, OC_REST_POST, query,
1110 &deviceInfo->endpoint, (OCPayload *)secPayload,
1111 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1112 if (res != OC_STACK_OK)
1114 OIC_LOG(ERROR, TAG, "OCStack resource error");
1117 OIC_LOG(DEBUG, TAG, "OUT PostOwnerTransferModeToResource");
1122 static OCStackResult GetProvisioningStatusResource(OTMContext_t* otmCtx)
1124 OIC_LOG(DEBUG, TAG, "IN GetProvisioningStatusResource");
1126 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1128 OIC_LOG(ERROR, TAG, "Invailed parameters");
1129 return OC_STACK_INVALID_PARAM;
1132 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1133 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1134 if(!PMGenerateQuery(false,
1135 deviceInfo->endpoint.addr, deviceInfo->endpoint.port,
1136 deviceInfo->connType,
1137 query, sizeof(query), OIC_RSRC_PSTAT_URI))
1139 OIC_LOG(ERROR, TAG, "GetProvisioningStatusResource : Failed to generate query");
1140 return OC_STACK_ERROR;
1142 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1144 OCCallbackData cbData;
1145 cbData.cb = &ListMethodsHandler;
1146 cbData.context = (void *)otmCtx;
1148 OCStackResult res = OCDoResource(NULL, OC_REST_GET, query, NULL, NULL,
1149 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1150 if (res != OC_STACK_OK)
1152 OIC_LOG(ERROR, TAG, "OCStack resource error");
1155 OIC_LOG(DEBUG, TAG, "OUT GetProvisioningStatusResource");
1160 static OCStackResult PostOwnerUuid(OTMContext_t* otmCtx)
1162 OIC_LOG(DEBUG, TAG, "IN PostOwnerUuid");
1164 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1166 OIC_LOG(ERROR, TAG, "Invailed parameters");
1167 return OC_STACK_INVALID_PARAM;
1170 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1171 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1172 if(!PMGenerateQuery(true,
1173 deviceInfo->endpoint.addr, deviceInfo->securePort,
1174 deviceInfo->connType,
1175 query, sizeof(query), OIC_RSRC_DOXM_URI))
1177 OIC_LOG(ERROR, TAG, "PostOwnerUuid : Failed to generate query");
1178 return OC_STACK_ERROR;
1180 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1182 //Post PT's uuid to new device
1183 OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1186 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1187 return OC_STACK_NO_MEMORY;
1189 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1190 OCStackResult res = g_OTMDatas[deviceInfo->doxm->oxmSel].createOwnerTransferPayloadCB(
1191 otmCtx, &secPayload->securityData, &secPayload->payloadSize);
1192 if (OC_STACK_OK != res && NULL == secPayload->securityData)
1194 OCPayloadDestroy((OCPayload *)secPayload);
1195 OIC_LOG(ERROR, TAG, "Error while converting doxm bin to cbor.");
1196 return OC_STACK_INVALID_PARAM;
1198 OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1200 OCCallbackData cbData;
1201 cbData.cb = &OwnerUuidUpdateHandler;
1202 cbData.context = (void *)otmCtx;
1205 res = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload *)secPayload,
1206 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1207 if (res != OC_STACK_OK)
1209 OIC_LOG(ERROR, TAG, "OCStack resource error");
1212 OIC_LOG(DEBUG, TAG, "OUT PostOwnerUuid");
1217 static OCStackResult PostOwnershipInformation(OTMContext_t* otmCtx)
1219 OIC_LOG(DEBUG, TAG, "IN PostOwnershipInformation");
1221 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1223 OIC_LOG(ERROR, TAG, "Invailed parameters");
1224 return OC_STACK_INVALID_PARAM;
1227 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1228 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1229 if(!PMGenerateQuery(true,
1230 deviceInfo->endpoint.addr, deviceInfo->securePort,
1231 deviceInfo->connType,
1232 query, sizeof(query), OIC_RSRC_DOXM_URI))
1234 OIC_LOG(ERROR, TAG, "PostOwnershipInformation : Failed to generate query");
1235 return OC_STACK_ERROR;
1237 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1239 //OwnershipInformationHandler
1240 OCSecurityPayload *secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1243 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1244 return OC_STACK_NO_MEMORY;
1247 otmCtx->selectedDeviceInfo->doxm->owned = true;
1249 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1250 OCStackResult res = DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm,
1251 &secPayload->securityData, &secPayload->payloadSize, true);
1252 if (OC_STACK_OK != res && NULL == secPayload->securityData)
1254 OCPayloadDestroy((OCPayload *)secPayload);
1255 OIC_LOG(ERROR, TAG, "Error while converting doxm bin to json");
1256 return OC_STACK_INVALID_PARAM;
1259 OCCallbackData cbData;
1260 cbData.cb = &OwnershipInformationHandler;
1261 cbData.context = (void *)otmCtx;
1264 res = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload*)secPayload,
1265 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1266 if (res != OC_STACK_OK)
1268 OIC_LOG(ERROR, TAG, "OCStack resource error");
1271 OIC_LOG(DEBUG, TAG, "OUT PostOwnershipInformation");
1276 static OCStackResult PostUpdateOperationMode(OTMContext_t* otmCtx)
1278 OIC_LOG(DEBUG, TAG, "IN PostUpdateOperationMode");
1280 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1282 return OC_STACK_INVALID_PARAM;
1285 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1286 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1287 if(!PMGenerateQuery(false,
1288 deviceInfo->endpoint.addr, deviceInfo->endpoint.port,
1289 deviceInfo->connType,
1290 query, sizeof(query), OIC_RSRC_PSTAT_URI))
1292 OIC_LOG(ERROR, TAG, "PostUpdateOperationMode : Failed to generate query");
1293 return OC_STACK_ERROR;
1295 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1297 OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1300 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1301 return OC_STACK_NO_MEMORY;
1303 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1304 OCStackResult res = PstatToCBORPayload(deviceInfo->pstat, &secPayload->securityData,
1305 &secPayload->payloadSize, true);
1306 if (OC_STACK_OK != res)
1308 OCPayloadDestroy((OCPayload *)secPayload);
1309 OIC_LOG(ERROR, TAG, "Error while converting pstat to cbor.");
1310 return OC_STACK_INVALID_PARAM;
1313 OCCallbackData cbData;
1314 cbData.cb = &OperationModeUpdateHandler;
1315 cbData.context = (void *)otmCtx;
1317 res = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload *)secPayload,
1318 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1319 if (res != OC_STACK_OK)
1321 OIC_LOG(ERROR, TAG, "OCStack resource error");
1324 OIC_LOG(DEBUG, TAG, "OUT PostUpdateOperationMode");
1329 static OCStackResult StartOwnershipTransfer(void* ctx, OCProvisionDev_t* selectedDevice)
1331 OIC_LOG(INFO, TAG, "IN StartOwnershipTransfer");
1332 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
1333 otmCtx->selectedDeviceInfo = selectedDevice;
1335 //Set to the lowest level OxM, and then find more higher level OxM.
1336 OCStackResult res = SelectProvisioningMethod(selectedDevice->doxm->oxm,
1337 selectedDevice->doxm->oxmLen,
1338 &selectedDevice->doxm->oxmSel);
1339 if(OC_STACK_OK != res)
1341 OIC_LOG(ERROR, TAG, "Failed to select the provisioning method");
1342 SetResult(otmCtx, res);
1345 OIC_LOG_V(DEBUG, TAG, "Selected provisoning method = %d", selectedDevice->doxm->oxmSel);
1347 //Send Req: POST /oic/sec/doxm [{..."OxmSel" :g_OTMDatas[Index of Selected OxM].OXMString,...}]
1348 res = PostOwnerTransferModeToResource(otmCtx);
1349 if(OC_STACK_OK != res)
1351 OIC_LOG(WARNING, TAG, "Failed to select the provisioning method");
1352 SetResult(otmCtx, res);
1356 //Register DTLS event handler to catch the dtls event while handshake
1357 if(CA_STATUS_OK != CARegisterDTLSHandshakeCallback(DTLSHandshakeCB))
1359 OIC_LOG(WARNING, TAG, "StartOwnershipTransfer : Failed to register DTLS handshake callback.");
1362 //Register TLS event handler to catch the tls event while handshake
1363 if(CA_STATUS_OK != CAregisterTlsHandshakeCallback(DTLSHandshakeCB))
1365 OIC_LOG(WARNING, TAG, "StartOwnershipTransfer : Failed to register TLS handshake callback.");
1368 OIC_LOG(INFO, TAG, "OUT StartOwnershipTransfer");
1374 OCStackResult OTMSetOwnershipTransferCallbackData(OicSecOxm_t oxmType, OTMCallbackData_t* data)
1376 OIC_LOG(DEBUG, TAG, "IN OTMSetOwnerTransferCallbackData");
1380 OIC_LOG(ERROR, TAG, "OTMSetOwnershipTransferCallbackData : Invalid parameters");
1381 return OC_STACK_INVALID_PARAM;
1383 if(oxmType >= OIC_OXM_COUNT)
1385 OIC_LOG(INFO, TAG, "Unknow ownership transfer method");
1386 return OC_STACK_INVALID_PARAM;
1389 g_OTMDatas[oxmType].loadSecretCB= data->loadSecretCB;
1390 g_OTMDatas[oxmType].createSecureSessionCB = data->createSecureSessionCB;
1391 g_OTMDatas[oxmType].createSelectOxmPayloadCB = data->createSelectOxmPayloadCB;
1392 g_OTMDatas[oxmType].createOwnerTransferPayloadCB = data->createOwnerTransferPayloadCB;
1394 OIC_LOG(DEBUG, TAG, "OUT OTMSetOwnerTransferCallbackData");
1400 * NOTE : Unowned discovery should be done before performing OTMDoOwnershipTransfer
1402 OCStackResult OTMDoOwnershipTransfer(void* ctx,
1403 OCProvisionDev_t *selectedDevicelist,
1404 OCProvisionResultCB resultCallback)
1406 OIC_LOG(DEBUG, TAG, "IN OTMDoOwnershipTransfer");
1408 if (NULL == selectedDevicelist)
1410 return OC_STACK_INVALID_PARAM;
1412 if (NULL == resultCallback)
1414 return OC_STACK_INVALID_CALLBACK;
1417 OTMContext_t* otmCtx = (OTMContext_t*)OICCalloc(1,sizeof(OTMContext_t));
1420 OIC_LOG(ERROR, TAG, "Failed to create OTM Context");
1421 return OC_STACK_NO_MEMORY;
1423 otmCtx->ctxResultCallback = resultCallback;
1424 otmCtx->ctxHasError = false;
1425 otmCtx->userCtx = ctx;
1426 OCProvisionDev_t* pCurDev = selectedDevicelist;
1428 //Counting number of selected devices.
1429 otmCtx->ctxResultArraySize = 0;
1430 while(NULL != pCurDev)
1432 otmCtx->ctxResultArraySize++;
1433 pCurDev = pCurDev->next;
1436 otmCtx->ctxResultArray =
1437 (OCProvisionResult_t*)OICCalloc(otmCtx->ctxResultArraySize, sizeof(OCProvisionResult_t));
1438 if(NULL == otmCtx->ctxResultArray)
1440 OIC_LOG(ERROR, TAG, "OTMDoOwnershipTransfer : Failed to memory allocation");
1442 return OC_STACK_NO_MEMORY;
1444 pCurDev = selectedDevicelist;
1446 OCStackResult res = OC_STACK_OK;
1447 //Fill the device UUID for result array.
1448 for(size_t devIdx = 0; devIdx < otmCtx->ctxResultArraySize; devIdx++)
1450 //Checking duplication of Device ID.
1451 bool isDuplicate = true;
1452 res = PDMIsDuplicateDevice(&pCurDev->doxm->deviceID, &isDuplicate);
1453 if (OC_STACK_OK != res)
1459 bool isStale = false;
1460 res = PDMIsDeviceStale(&pCurDev->doxm->deviceID, &isStale);
1461 if(OC_STACK_OK != res)
1463 OIC_LOG(ERROR, TAG, "Internal error in PDMIsDeviceStale");
1468 OIC_LOG(INFO, TAG, "Detected duplicated UUID in stale status, "\
1469 "this UUID will be removed from PDM");
1471 res = PDMDeleteDevice(&pCurDev->doxm->deviceID);
1472 if(OC_STACK_OK != res)
1474 OIC_LOG(ERROR, TAG, "Internal error in PDMDeleteDevice");
1480 OIC_LOG(ERROR, TAG, "OTMDoOwnershipTransfer : Device UUID is duplicated");
1481 res = OC_STACK_INVALID_PARAM;
1485 memcpy(otmCtx->ctxResultArray[devIdx].deviceId.id,
1486 pCurDev->doxm->deviceID.id,
1488 otmCtx->ctxResultArray[devIdx].res = OC_STACK_CONTINUE;
1489 pCurDev = pCurDev->next;
1492 StartOwnershipTransfer(otmCtx, selectedDevicelist);
1494 OIC_LOG(DEBUG, TAG, "OUT OTMDoOwnershipTransfer");
1498 OICFree(otmCtx->ctxResultArray);
1503 OCStackResult PostProvisioningStatus(OTMContext_t* otmCtx)
1505 OIC_LOG(INFO, TAG, "IN PostProvisioningStatus");
1507 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1509 OIC_LOG(ERROR, TAG, "OTMContext is NULL");
1510 return OC_STACK_INVALID_PARAM;
1513 //Change the TAKE_OWNER bit of CM to 0.
1514 otmCtx->selectedDeviceInfo->pstat->cm &= (~TAKE_OWNER);
1516 OCSecurityPayload *secPayload = (OCSecurityPayload *)OICCalloc(1, sizeof(OCSecurityPayload));
1519 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1520 return OC_STACK_NO_MEMORY;
1522 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1523 if (OC_STACK_OK != PstatToCBORPayload(otmCtx->selectedDeviceInfo->pstat,
1524 &secPayload->securityData, &secPayload->payloadSize, true))
1526 OCPayloadDestroy((OCPayload *)secPayload);
1527 return OC_STACK_INVALID_JSON;
1529 OIC_LOG(DEBUG, TAG, "Created payload for chage to Provisiong state");
1530 OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1532 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1533 if(!PMGenerateQuery(true,
1534 otmCtx->selectedDeviceInfo->endpoint.addr,
1535 otmCtx->selectedDeviceInfo->securePort,
1536 otmCtx->selectedDeviceInfo->connType,
1537 query, sizeof(query), OIC_RSRC_PSTAT_URI))
1539 OIC_LOG(ERROR, TAG, "PostProvisioningStatus : Failed to generate query");
1540 return OC_STACK_ERROR;
1542 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1544 OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
1545 cbData.cb = &ProvisioningStatusHandler;
1546 cbData.context = (void*)otmCtx;
1548 OCStackResult ret = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload*)secPayload,
1549 otmCtx->selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1550 OIC_LOG_V(INFO, TAG, "OCDoResource returned: %d",ret);
1551 if (ret != OC_STACK_OK)
1553 OIC_LOG(ERROR, TAG, "OCStack resource error");
1556 OIC_LOG(INFO, TAG, "OUT PostProvisioningStatus");
1561 OCStackResult PostNormalOperationStatus(OTMContext_t* otmCtx)
1563 OIC_LOG(INFO, TAG, "IN PostNormalOperationStatus");
1565 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1567 OIC_LOG(ERROR, TAG, "OTMContext is NULL");
1568 return OC_STACK_INVALID_PARAM;
1572 otmCtx->selectedDeviceInfo->pstat->isOp = true;
1574 OCSecurityPayload *secPayload = (OCSecurityPayload *)OICCalloc(1, sizeof(OCSecurityPayload));
1577 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1578 return OC_STACK_NO_MEMORY;
1580 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1581 if (OC_STACK_OK != PstatToCBORPayload(otmCtx->selectedDeviceInfo->pstat,
1582 &secPayload->securityData, &secPayload->payloadSize, true))
1584 OCPayloadDestroy((OCPayload *)secPayload);
1585 return OC_STACK_INVALID_JSON;
1587 OIC_LOG(DEBUG, TAG, "Created payload for chage to Provisiong state");
1588 OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1590 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1591 if(!PMGenerateQuery(true,
1592 otmCtx->selectedDeviceInfo->endpoint.addr,
1593 otmCtx->selectedDeviceInfo->securePort,
1594 otmCtx->selectedDeviceInfo->connType,
1595 query, sizeof(query), OIC_RSRC_PSTAT_URI))
1597 OIC_LOG(ERROR, TAG, "PostNormalOperationStatus : Failed to generate query");
1598 return OC_STACK_ERROR;
1600 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1602 OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
1603 cbData.cb = &ReadyForNomalStatusHandler;
1604 cbData.context = (void*)otmCtx;
1606 OCStackResult ret = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload*)secPayload,
1607 otmCtx->selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1608 OIC_LOG_V(INFO, TAG, "OCDoResource returned: %d",ret);
1609 if (ret != OC_STACK_OK)
1611 OIC_LOG(ERROR, TAG, "OCStack resource error");
1614 OIC_LOG(INFO, TAG, "OUT PostNormalOperationStatus");