1 /* *****************************************************************
3 * Copyright 2015 Samsung Electronics All Rights Reserved.
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
19 * *****************************************************************/
21 // Defining _POSIX_C_SOURCE macro with 199309L (or greater) as value
22 // causes header files to expose definitions
23 // corresponding to the POSIX.1b, Real-time extensions
24 // (IEEE Std 1003.1b-1993) specification
26 // For this specific file, see use of clock_gettime,
27 // Refer to http://pubs.opengroup.org/stage7tc1/functions/clock_gettime.html
28 // and to http://man7.org/linux/man-pages/man2/clock_gettime.2.html
29 #ifndef _POSIX_C_SOURCE
30 #define _POSIX_C_SOURCE 200809L
33 #include "iotivity_config.h"
40 #ifdef HAVE_SYS_TIME_H
47 #include "oic_malloc.h"
48 #include "oic_string.h"
50 #include "cainterface.h"
56 #include "srmresourcestrings.h"
57 #include "doxmresource.h"
58 #include "pstatresource.h"
59 #include "credresource.h"
60 #include "aclresource.h"
61 #include "ownershiptransfermanager.h"
62 #include "securevirtualresourcetypes.h"
63 #include "oxmjustworks.h"
65 #include "pmutility.h"
66 #include "srmutility.h"
67 #include "provisioningdatabasemanager.h"
68 #include "oxmrandompin.h"
69 #include "ocpayload.h"
70 #include "payload_logging.h"
75 * Array to store the callbacks for each owner transfer method.
77 static OTMCallbackData_t g_OTMDatas[OIC_OXM_COUNT];
80 * Variables for pointing the OTMContext to be used in the DTLS handshake result callback.
82 static OTMContext_t* g_otmCtx = NULL;
85 * Function to select appropriate provisioning method.
87 * @param[in] supportedMethods Array of supported methods
88 * @param[in] numberOfMethods number of supported methods
89 * @param[out] selectedMethod Selected methods
90 * @return OC_STACK_OK on success
92 static OCStackResult SelectProvisioningMethod(const OicSecOxm_t *supportedMethods,
93 size_t numberOfMethods, OicSecOxm_t *selectedMethod)
95 OIC_LOG(DEBUG, TAG, "IN SelectProvisioningMethod");
97 if(numberOfMethods == 0 || !supportedMethods)
99 OIC_LOG(WARNING, TAG, "Could not find a supported OxM.");
100 return OC_STACK_ERROR;
103 *selectedMethod = supportedMethods[0];
104 for(size_t i = 0; i < numberOfMethods; i++)
106 if(*selectedMethod < supportedMethods[i])
108 *selectedMethod = supportedMethods[i];
116 * Function to select operation mode.This function will return most secure common operation mode.
118 * @param[in] selectedDeviceInfo selected device information to performing provisioning.
119 * @param[out] selectedMode selected operation mode
120 * @return OC_STACK_OK on success
122 static void SelectOperationMode(const OCProvisionDev_t *selectedDeviceInfo,
123 OicSecDpom_t *selectedMode)
125 OIC_LOG(DEBUG, TAG, "IN SelectOperationMode");
126 *selectedMode = selectedDeviceInfo->pstat->sm[0];
127 OIC_LOG_V(DEBUG, TAG, "Selected Operation Mode = %d", *selectedMode);
131 * Function to start ownership transfer.
132 * This function will send the first request for provisioning,
133 * The next request message is sent from the response handler for this request.
135 * @param[in] ctx context value passed to callback from calling function.
136 * @param[in] selectedDevice selected device information to performing provisioning.
137 * @return OC_STACK_OK on success
139 static OCStackResult StartOwnershipTransfer(void* ctx, OCProvisionDev_t* selectedDevice);
142 * Function to update owner transfer mode
144 * @param[in] otmCtx Context value of ownership transfer.
145 * @return OC_STACK_OK on success
147 static OCStackResult PostOwnerTransferModeToResource(OTMContext_t* otmCtx);
150 * Function to send request to resource to get its pstat resource information.
152 * @param[in] otmCtx Context value of ownership transfer.
153 * @return OC_STACK_OK on success
155 static OCStackResult GetProvisioningStatusResource(OTMContext_t* otmCtx);
159 * Function to send uuid of owner device to new device.
160 * This function would update 'owner of doxm' as UUID for provisioning tool.
162 * @param[in] otmCtx Context value of ownership transfer.
163 * @return OC_STACK_OK on success
165 static OCStackResult PostOwnerUuid(OTMContext_t* otmCtx);
168 * Function to update the operation mode. As per the spec. Operation mode in client driven
169 * single service provisioning it will be updated to 0x3
171 * @param[in] otmCtx Context value of ownership transfer.
172 * @return OC_STACK_OK on success
174 static OCStackResult PostUpdateOperationMode(OTMContext_t* otmCtx);
177 * Function to update the owner credential to new device
179 * @param[in] otmCtx Context value of ownership transfer.
180 * @param[in] selectedOperationMode selected operation mode
181 * @return OC_STACK_OK on success
183 static OCStackResult PostOwnerCredential(OTMContext_t* otmCtx);
186 * Function to send ownerShip info.
187 * This function would update 'owned of doxm' as true.
189 * @param[in] otmCtx Context value of ownership transfer.
190 * @return OC_STACK_OK on success
192 static OCStackResult PostOwnershipInformation(OTMContext_t* otmCtx);
195 * Function to update pstat as Ready for provisioning.
196 * This function would update 'cm' from bx0000,0010 to bx0000,0000.
198 * @param[in] ctx context value passed to callback from calling function.
199 * @param[in] selectedDevice selected device information to performing provisioning.
200 * @return OC_STACK_OK on success
202 static OCStackResult PostProvisioningStatus(OTMContext_t* otmCtx);
205 * Function to update pstat as Ready for Normal Operation.
206 * This function would update 'isop' from false to true.
208 * @param[in] ctx context value passed to callback from calling function.
209 * @param[in] selectedDevice selected device information to performing provisioning.
210 * @return OC_STACK_OK on success
212 static OCStackResult PostNormalOperationStatus(OTMContext_t* otmCtx);
214 static bool IsComplete(OTMContext_t* otmCtx)
216 for(size_t i = 0; i < otmCtx->ctxResultArraySize; i++)
218 if(OC_STACK_CONTINUE == otmCtx->ctxResultArray[i].res)
228 * Function to save the result of provisioning.
230 * @param[in,out] otmCtx Context value of ownership transfer.
231 * @param[in] res result of provisioning
233 static void SetResult(OTMContext_t* otmCtx, const OCStackResult res)
235 OIC_LOG_V(DEBUG, TAG, "IN SetResult : %d ", res);
239 OIC_LOG(WARNING, TAG, "OTMContext is NULL");
243 if(otmCtx->selectedDeviceInfo)
245 //Revert psk_info callback and new deivce uuid in case of random PIN OxM
246 if(OIC_RANDOM_DEVICE_PIN == otmCtx->selectedDeviceInfo->doxm->oxmSel)
248 if(CA_ADAPTER_IP == ((CAEndpoint_t*)(&otmCtx->selectedDeviceInfo->endpoint))->adapter)
250 if(CA_STATUS_OK != CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials))
252 OIC_LOG(WARNING, TAG, "Failed to register DTLS handshake callback.");
258 if(CA_STATUS_OK != CAregisterTlsCredentialsHandler(GetDtlsPskCredentials))
260 OIC_LOG(WARNING, TAG, "Failed to register TLS handshake callback.");
264 OicUuid_t emptyUuid = { .id={0}};
265 SetUuidForRandomPinOxm(&emptyUuid);
268 for(size_t i = 0; i < otmCtx->ctxResultArraySize; i++)
270 if(memcmp(otmCtx->selectedDeviceInfo->doxm->deviceID.id,
271 otmCtx->ctxResultArray[i].deviceId.id, UUID_LENGTH) == 0)
273 otmCtx->ctxResultArray[i].res = res;
274 if(OC_STACK_OK != res)
276 otmCtx->ctxHasError = true;
283 //If all request is completed, invoke the user callback.
284 if(IsComplete(otmCtx))
286 otmCtx->ctxResultCallback(otmCtx->userCtx, otmCtx->ctxResultArraySize,
287 otmCtx->ctxResultArray, otmCtx->ctxHasError);
288 OICFree(otmCtx->ctxResultArray);
293 if(OC_STACK_OK != StartOwnershipTransfer(otmCtx,
294 otmCtx->selectedDeviceInfo->next))
296 OIC_LOG(ERROR, TAG, "Failed to StartOwnershipTransfer");
301 OIC_LOG(DEBUG, TAG, "OUT SetResult");
305 * Function to handle the handshake result in OTM.
306 * This function will be invoked after DTLS handshake
307 * @param endPoint [IN] The remote endpoint.
308 * @param errorInfo [IN] Error information from the endpoint.
311 void DTLSHandshakeCB(const CAEndpoint_t *endpoint, const CAErrorInfo_t *info)
313 if(NULL != g_otmCtx && NULL != g_otmCtx->selectedDeviceInfo &&
314 NULL != endpoint && NULL != info)
316 OIC_LOG_V(INFO, TAG, "Received status from remote device(%s:%d) : %d",
317 endpoint->addr, endpoint->port, info->result);
319 OicSecDoxm_t* newDevDoxm = g_otmCtx->selectedDeviceInfo->doxm;
321 if(NULL != newDevDoxm)
323 OicUuid_t emptyUuid = {.id={0}};
325 //Make sure the address matches.
326 if(strncmp(g_otmCtx->selectedDeviceInfo->endpoint.addr,
328 sizeof(endpoint->addr)) == 0 &&
329 g_otmCtx->selectedDeviceInfo->securePort == endpoint->port)
331 OCStackResult res = OC_STACK_ERROR;
333 //If temporal secure sesstion established successfully
334 if(CA_STATUS_OK == info->result &&
335 false == newDevDoxm->owned &&
336 memcmp(&(newDevDoxm->owner), &emptyUuid, sizeof(OicUuid_t)) == 0)
338 //Send request : POST /oic/sec/doxm [{... , "devowner":"PT's UUID"}]
339 res = PostOwnerUuid(g_otmCtx);
340 if(OC_STACK_OK != res)
342 OIC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to send owner information");
343 SetResult(g_otmCtx, res);
346 //In case of authentication failure
347 else if(CA_DTLS_AUTHENTICATION_FAILURE == info->result)
349 //in case of error from owner credential
350 if(memcmp(&(newDevDoxm->owner), &emptyUuid, sizeof(OicUuid_t)) != 0 &&
351 true == newDevDoxm->owned)
353 OIC_LOG(ERROR, TAG, "The owner credential may incorrect.");
355 if(OC_STACK_OK != RemoveCredential(&(newDevDoxm->deviceID)))
357 OIC_LOG(WARNING, TAG, "Failed to remove the invaild owner credential");
359 SetResult(g_otmCtx, OC_STACK_AUTHENTICATION_FAILURE);
361 //in case of error from wrong PIN, re-start the ownership transfer
362 else if(OIC_RANDOM_DEVICE_PIN == newDevDoxm->oxmSel)
364 OIC_LOG(ERROR, TAG, "The PIN number may incorrect.");
366 memcpy(&(newDevDoxm->owner), &emptyUuid, sizeof(OicUuid_t));
367 newDevDoxm->owned = false;
368 g_otmCtx->attemptCnt++;
370 if(WRONG_PIN_MAX_ATTEMP > g_otmCtx->attemptCnt)
372 res = StartOwnershipTransfer(g_otmCtx, g_otmCtx->selectedDeviceInfo);
373 if(OC_STACK_OK != res)
375 SetResult(g_otmCtx, res);
376 OIC_LOG(ERROR, TAG, "Failed to Re-StartOwnershipTransfer");
381 OIC_LOG(ERROR, TAG, "User has exceeded the number of authentication attempts.");
382 SetResult(g_otmCtx, OC_STACK_AUTHENTICATION_FAILURE);
387 OIC_LOG(ERROR, TAG, "Failed to establish secure session.");
388 SetResult(g_otmCtx, OC_STACK_AUTHENTICATION_FAILURE);
397 * Function to save ownerPSK at provisioning tool end.
399 * @param[in] selectedDeviceInfo selected device information to performing provisioning.
400 * @return OC_STACK_OK on success
402 static OCStackResult SaveOwnerPSK(OCProvisionDev_t *selectedDeviceInfo)
404 OIC_LOG(DEBUG, TAG, "IN SaveOwnerPSK");
406 OCStackResult res = OC_STACK_ERROR;
408 CAEndpoint_t endpoint;
409 memset(&endpoint, 0x00, sizeof(CAEndpoint_t));
410 OICStrcpy(endpoint.addr, MAX_ADDR_STR_SIZE_CA, selectedDeviceInfo->endpoint.addr);
411 endpoint.addr[MAX_ADDR_STR_SIZE_CA - 1] = '\0';
412 endpoint.port = selectedDeviceInfo->securePort;
413 endpoint.adapter = selectedDeviceInfo->endpoint.adapter;
415 OicUuid_t ptDeviceID = {.id={0}};
416 if (OC_STACK_OK != GetDoxmDeviceID(&ptDeviceID))
418 OIC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
422 uint8_t ownerPSK[OWNER_PSK_LENGTH_128] = {0};
423 OicSecKey_t ownerKey = {ownerPSK, OWNER_PSK_LENGTH_128, OIC_ENCODING_UNKNOW};
425 //Generating OwnerPSK
426 CAResult_t pskRet = CAGenerateOwnerPSK(&endpoint,
427 (uint8_t *)GetOxmString(selectedDeviceInfo->doxm->oxmSel),
428 strlen(GetOxmString(selectedDeviceInfo->doxm->oxmSel)),
429 ptDeviceID.id, sizeof(ptDeviceID.id),
430 selectedDeviceInfo->doxm->deviceID.id, sizeof(selectedDeviceInfo->doxm->deviceID.id),
431 ownerPSK, OWNER_PSK_LENGTH_128);
433 if (CA_STATUS_OK == pskRet)
435 OIC_LOG(INFO, TAG,"ownerPSK dump:\n");
436 OIC_LOG_BUFFER(INFO, TAG,ownerPSK, OWNER_PSK_LENGTH_128);
437 //Generating new credential for provisioning tool
438 OicSecCred_t *cred = GenerateCredential(&selectedDeviceInfo->doxm->deviceID,
439 SYMMETRIC_PAIR_WISE_KEY, NULL,
440 &ownerKey, &ptDeviceID);
441 VERIFY_NON_NULL(TAG, cred, ERROR);
443 // TODO: Added as workaround. Will be replaced soon.
444 cred->privateData.encoding = OIC_ENCODING_RAW;
447 // NOTE: Test codes to use BASE64 encoded owner PSK.
448 uint32_t outSize = 0;
449 size_t b64BufSize = B64ENCODE_OUT_SAFESIZE((OWNER_PSK_LENGTH_128 + 1));
450 char* b64Buf = (uint8_t *)OICCalloc(1, b64BufSize);
451 VERIFY_NON_NULL(TAG, b64Buf, ERROR);
452 b64Encode(cred->privateData.data, cred->privateData.len, b64Buf, b64BufSize, &outSize);
454 OICFree( cred->privateData.data );
455 cred->privateData.data = (uint8_t *)OICCalloc(1, outSize + 1);
456 VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
458 strncpy(cred->privateData.data, b64Buf, outSize);
459 cred->privateData.data[outSize] = '\0';
460 cred->privateData.encoding = OIC_ENCODING_BASE64;
461 cred->privateData.len = outSize;
463 #endif //End of Test codes
465 //Finding previous ownerPSK.
466 const OicSecCred_t* credList = GetCredList();
467 OicSecCred_t* prevCred = NULL;
469 LL_FOREACH(credList, prevCred)
471 //OwnerPSK's type is SYMMETRIC_PAIR_WISE_KEY
472 if (SYMMETRIC_PAIR_WISE_KEY == prevCred->credType &&
473 0 == memcmp(prevCred->subject.id, cred->subject.id, sizeof(cred->subject.id)))
475 credId = prevCred->credId;
480 //If duplicate owner PSK is exists, remove it.
483 OIC_LOG(WARNING, TAG, "Duplicate OwnerPSK was detected.");
484 OIC_LOG(WARNING, TAG, "[Subject] : ");
485 OIC_LOG_BUFFER(WARNING, TAG, prevCred->subject.id, sizeof(prevCred->subject.id));
486 OIC_LOG_V(WARNING, TAG, "[Encoding Type] : %d", prevCred->privateData.encoding);
487 OIC_LOG(WARNING, TAG, "[Private Data] : ");
488 OIC_LOG_BUFFER(WARNING, TAG, prevCred->privateData.data, prevCred->privateData.len);
489 OIC_LOG(WARNING, TAG, "Previous OwnerPSK will be removed.");
491 res = RemoveCredentialByCredId(credId);
492 if(OC_STACK_RESOURCE_DELETED != res)
494 OIC_LOG(ERROR, TAG, "Failed to remove the previous OwnerPSK");
495 DeleteCredList(cred);
500 res = AddCredential(cred);
501 if(res != OC_STACK_OK)
503 DeleteCredList(cred);
509 OIC_LOG(ERROR, TAG, "CAGenerateOwnerPSK failed");
512 OIC_LOG(DEBUG, TAG, "OUT SaveOwnerPSK");
518 * Callback handler for OwnerShipTransferModeHandler API.
520 * @param[in] ctx ctx value passed to callback from calling function.
521 * @param[in] UNUSED handle to an invocation
522 * @param[in] clientResponse Response from queries to remote servers.
523 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
524 * and OC_STACK_KEEP_TRANSACTION to keep it.
526 static OCStackApplicationResult OwnerTransferModeHandler(void *ctx, OCDoHandle UNUSED,
527 OCClientResponse *clientResponse)
529 OIC_LOG(DEBUG, TAG, "IN OwnerTransferModeHandler");
531 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
532 VERIFY_NON_NULL(TAG, ctx, WARNING);
534 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
536 if (OC_STACK_RESOURCE_CHANGED == clientResponse->result)
538 OIC_LOG(INFO, TAG, "OwnerTransferModeHandler : response result = OC_STACK_OK");
539 //Send request : GET /oic/sec/pstat
540 OCStackResult res = GetProvisioningStatusResource(otmCtx);
541 if(OC_STACK_OK != res)
543 OIC_LOG(WARNING, TAG, "Failed to get pstat information");
544 SetResult(otmCtx, res);
549 OIC_LOG_V(WARNING, TAG, "OwnerTransferModeHandler : Client response is incorrect : %d",
550 clientResponse->result);
551 SetResult(otmCtx, clientResponse->result);
554 OIC_LOG(DEBUG, TAG, "OUT OwnerTransferModeHandler");
557 return OC_STACK_DELETE_TRANSACTION;
561 * Callback handler for ProvisioningStatusResouceHandler API.
563 * @param[in] ctx ctx value passed to callback from calling function.
564 * @param[in] UNUSED handle to an invocation
565 * @param[in] clientResponse Response from queries to remote servers.
566 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
567 * and OC_STACK_KEEP_TRANSACTION to keep it.
569 static OCStackApplicationResult ListMethodsHandler(void *ctx, OCDoHandle UNUSED,
570 OCClientResponse *clientResponse)
572 OIC_LOG(DEBUG, TAG, "IN ListMethodsHandler");
574 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
575 VERIFY_NON_NULL(TAG, ctx, WARNING);
577 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
579 if (OC_STACK_OK == clientResponse->result)
581 if (NULL == clientResponse->payload)
583 OIC_LOG(INFO, TAG, "Skiping Null payload");
584 SetResult(otmCtx, OC_STACK_ERROR);
585 return OC_STACK_DELETE_TRANSACTION;
588 if (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)
590 OIC_LOG(INFO, TAG, "Unknown payload type");
591 SetResult(otmCtx, OC_STACK_ERROR);
592 return OC_STACK_DELETE_TRANSACTION;
594 OicSecPstat_t* pstat = NULL;
595 OCStackResult result = CBORPayloadToPstat(
596 ((OCSecurityPayload*)clientResponse->payload)->securityData,
597 ((OCSecurityPayload*)clientResponse->payload)->payloadSize,
599 if(NULL == pstat || result != OC_STACK_OK)
601 OIC_LOG(ERROR, TAG, "Error while converting cbor to pstat.");
602 SetResult(otmCtx, OC_STACK_ERROR);
603 return OC_STACK_DELETE_TRANSACTION;
605 if(false == (TAKE_OWNER & pstat->cm))
607 OIC_LOG(ERROR, TAG, "Device pairing mode enabling owner transfer operations is disabled");
608 SetResult(otmCtx, OC_STACK_ERROR);
609 return OC_STACK_DELETE_TRANSACTION;
611 otmCtx->selectedDeviceInfo->pstat = pstat;
613 //Select operation mode (Currently supported SINGLE_SERVICE_CLIENT_DRIVEN only)
614 SelectOperationMode(otmCtx->selectedDeviceInfo, &(otmCtx->selectedDeviceInfo->pstat->om));
616 //Send request : POST /oic/sec/pstat [{"om":"bx11", .. }]
617 OCStackResult res = PostUpdateOperationMode(otmCtx);
618 if (OC_STACK_OK != res)
620 OIC_LOG(ERROR, TAG, "Error while updating operation mode.");
621 SetResult(otmCtx, res);
626 OIC_LOG_V(WARNING, TAG, "ListMethodsHandler : Client response is incorrect : %d",
627 clientResponse->result);
628 SetResult(otmCtx, clientResponse->result);
631 OIC_LOG(DEBUG, TAG, "OUT ListMethodsHandler");
633 return OC_STACK_DELETE_TRANSACTION;
637 * Response handler for update owner uuid request.
639 * @param[in] ctx ctx value passed to callback from calling function.
640 * @param[in] UNUSED handle to an invocation
641 * @param[in] clientResponse Response from queries to remote servers.
642 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
643 * and OC_STACK_KEEP_TRANSACTION to keep it.
645 static OCStackApplicationResult OwnerUuidUpdateHandler(void *ctx, OCDoHandle UNUSED,
646 OCClientResponse *clientResponse)
648 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
649 VERIFY_NON_NULL(TAG, ctx, WARNING);
651 OIC_LOG(DEBUG, TAG, "IN OwnerUuidUpdateHandler");
653 OCStackResult res = OC_STACK_OK;
654 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
656 if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
658 if(otmCtx && otmCtx->selectedDeviceInfo)
660 res = SaveOwnerPSK(otmCtx->selectedDeviceInfo);
661 if(OC_STACK_OK != res)
663 OIC_LOG(ERROR, TAG, "OwnerUuidUpdateHandler:Failed to owner PSK generation");
664 SetResult(otmCtx, res);
665 return OC_STACK_DELETE_TRANSACTION;
668 //POST owner credential to new device according to security spec B.
669 res = PostOwnerCredential(otmCtx);
670 if(OC_STACK_OK != res)
673 "OwnerUuidUpdateHandler:Failed to send PosT request for onwer credential");
674 SetResult(otmCtx, res);
675 return OC_STACK_DELETE_TRANSACTION;
681 res = clientResponse->result;
682 OIC_LOG_V(ERROR, TAG, "OwnerUuidHandler : Unexpected result %d", res);
683 SetResult(otmCtx, res);
686 OIC_LOG(DEBUG, TAG, "OUT OwnerUuidUpdateHandler");
689 return OC_STACK_DELETE_TRANSACTION;
693 * Response handler for update operation mode.
695 * @param[in] ctx ctx value passed to callback from calling function.
696 * @param[in] UNUSED handle to an invocation
697 * @param[in] clientResponse Response from queries to remote servers.
698 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
699 * and OC_STACK_KEEP_TRANSACTION to keep it.
701 static OCStackApplicationResult OperationModeUpdateHandler(void *ctx, OCDoHandle UNUSED,
702 OCClientResponse *clientResponse)
704 OIC_LOG(DEBUG, TAG, "IN OperationModeUpdateHandler");
706 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
707 VERIFY_NON_NULL(TAG, ctx, WARNING);
709 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
711 if (OC_STACK_RESOURCE_CHANGED == clientResponse->result)
713 OCStackResult res = OC_STACK_ERROR;
714 OicSecOxm_t selOxm = otmCtx->selectedDeviceInfo->doxm->oxmSel;
716 //Load secret for temporal secure session.
717 if(g_OTMDatas[selOxm].loadSecretCB)
719 res = g_OTMDatas[selOxm].loadSecretCB(otmCtx);
720 if(OC_STACK_OK != res)
722 OIC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to load secret");
723 SetResult(otmCtx, res);
724 return OC_STACK_DELETE_TRANSACTION;
728 //It will be used in handshake event handler
731 //Try DTLS handshake to generate secure session
732 if(g_OTMDatas[selOxm].createSecureSessionCB)
734 res = g_OTMDatas[selOxm].createSecureSessionCB(otmCtx);
735 if(OC_STACK_OK != res)
737 OIC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to create DTLS session");
738 SetResult(otmCtx, res);
739 return OC_STACK_DELETE_TRANSACTION;
745 OIC_LOG(ERROR, TAG, "Error while update operation mode");
746 SetResult(otmCtx, clientResponse->result);
749 OIC_LOG(DEBUG, TAG, "OUT OperationModeUpdateHandler");
752 return OC_STACK_DELETE_TRANSACTION;
756 * Response handler for update owner crendetial request.
758 * @param[in] ctx ctx value passed to callback from calling function.
759 * @param[in] UNUSED handle to an invocation
760 * @param[in] clientResponse Response from queries to remote servers.
761 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
762 * and OC_STACK_KEEP_TRANSACTION to keep it.
764 static OCStackApplicationResult OwnerCredentialHandler(void *ctx, OCDoHandle UNUSED,
765 OCClientResponse *clientResponse)
767 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
768 VERIFY_NON_NULL(TAG, ctx, WARNING);
770 OIC_LOG(DEBUG, TAG, "IN OwnerCredentialHandler");
772 OCStackResult res = OC_STACK_OK;
773 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
775 if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
777 if(otmCtx && otmCtx->selectedDeviceInfo)
779 //Close the temporal secure session to verify the owner credential
780 CAEndpoint_t* endpoint = (CAEndpoint_t *)&otmCtx->selectedDeviceInfo->endpoint;
781 endpoint->port = otmCtx->selectedDeviceInfo->securePort;
782 CAResult_t caResult = CA_STATUS_OK;
783 if(CA_ADAPTER_IP == endpoint->adapter)
785 caResult = CACloseDtlsSession(endpoint);
790 caResult = CAcloseTlsConnection(endpoint);
793 if(CA_STATUS_OK != caResult)
795 OIC_LOG(ERROR, TAG, "Failed to close DTLS session");
796 SetResult(otmCtx, caResult);
797 return OC_STACK_DELETE_TRANSACTION;
801 * If we select NULL cipher,
802 * client will select appropriate cipher suite according to server's cipher-suite list.
804 if(CA_ADAPTER_IP == endpoint->adapter)
806 caResult = CASelectCipherSuite(TLS_NULL_WITH_NULL_NULL, endpoint->adapter);
810 // TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256 = 0xC037, /**< see RFC 5489 */
811 caResult = CASelectCipherSuite(0xC037, endpoint->adapter);
814 if(CA_STATUS_OK != caResult)
816 OIC_LOG(ERROR, TAG, "Failed to select TLS_NULL_WITH_NULL_NULL");
817 SetResult(otmCtx, caResult);
818 return OC_STACK_DELETE_TRANSACTION;
822 * in case of random PIN based OxM,
823 * revert get_psk_info callback of tinyDTLS to use owner credential.
825 if(OIC_RANDOM_DEVICE_PIN == otmCtx->selectedDeviceInfo->doxm->oxmSel)
827 OicUuid_t emptyUuid = { .id={0}};
828 SetUuidForRandomPinOxm(&emptyUuid);
830 if(CA_ADAPTER_IP == endpoint->adapter)
832 caResult = CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials);
837 caResult = CAregisterTlsCredentialsHandler(GetDtlsPskCredentials);
841 if(CA_STATUS_OK != caResult)
843 OIC_LOG(ERROR, TAG, "Failed to revert DTLS credential handler.");
844 SetResult(otmCtx, OC_STACK_INVALID_CALLBACK);
845 return OC_STACK_DELETE_TRANSACTION;
849 otmCtx->selectedDeviceInfo->connType |= CT_FLAG_SECURE;
851 //POST /oic/sec/doxm [{ ..., "owned":"TRUE" }]
852 res = PostOwnershipInformation(otmCtx);
853 if(OC_STACK_OK != res)
855 OIC_LOG(ERROR, TAG, "Failed to post ownership information to new device");
856 SetResult(otmCtx, res);
857 return OC_STACK_DELETE_TRANSACTION;
863 res = clientResponse->result;
864 OIC_LOG_V(ERROR, TAG, "OwnerCredentialHandler : Unexpected result %d", res);
865 SetResult(otmCtx, res);
868 OIC_LOG(DEBUG, TAG, "OUT OwnerCredentialHandler");
871 return OC_STACK_DELETE_TRANSACTION;
876 * Response handler for update owner information request.
878 * @param[in] ctx ctx value passed to callback from calling function.
879 * @param[in] UNUSED handle to an invocation
880 * @param[in] clientResponse Response from queries to remote servers.
881 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
882 * and OC_STACK_KEEP_TRANSACTION to keep it.
884 static OCStackApplicationResult OwnershipInformationHandler(void *ctx, OCDoHandle UNUSED,
885 OCClientResponse *clientResponse)
887 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
888 VERIFY_NON_NULL(TAG, ctx, WARNING);
890 OIC_LOG(DEBUG, TAG, "IN OwnershipInformationHandler");
892 OCStackResult res = OC_STACK_OK;
893 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
895 if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
897 if(otmCtx && otmCtx->selectedDeviceInfo)
899 OIC_LOG(INFO, TAG, "Ownership transfer was successfully completed.");
900 OIC_LOG(INFO, TAG, "Set Ready for provisioning state .");
902 res = PostProvisioningStatus(otmCtx);
903 if(OC_STACK_OK != res)
905 OIC_LOG(ERROR, TAG, "Failed to update pstat");
906 SetResult(otmCtx, res);
912 res = clientResponse->result;
913 OIC_LOG_V(ERROR, TAG, "OwnershipInformationHandler : Unexpected result %d", res);
914 SetResult(otmCtx, res);
917 OIC_LOG(DEBUG, TAG, "OUT OwnershipInformationHandler");
920 return OC_STACK_DELETE_TRANSACTION;
924 * Response handler of update provisioning status.
926 * @param[in] ctx ctx value passed to callback from calling function.
927 * @param[in] UNUSED handle to an invocation
928 * @param[in] clientResponse Response from queries to remote servers.
929 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
930 * and OC_STACK_KEEP_TRANSACTION to keep it.
932 static OCStackApplicationResult ProvisioningStatusHandler(void *ctx, OCDoHandle UNUSED,
933 OCClientResponse *clientResponse)
935 OIC_LOG_V(INFO, TAG, "IN ProvisioningStatusHandler.");
937 VERIFY_NON_NULL(TAG, clientResponse, ERROR);
938 VERIFY_NON_NULL(TAG, ctx, ERROR);
940 OTMContext_t* otmCtx = (OTMContext_t*) ctx;
942 OCStackResult res = OC_STACK_OK;
944 if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
946 if(otmCtx && otmCtx->selectedDeviceInfo)
948 OIC_LOG(INFO, TAG, "Device state is in Ready for Provisionig.");
950 res = PostNormalOperationStatus(otmCtx);
951 if(OC_STACK_OK != res)
953 OIC_LOG(ERROR, TAG, "Failed to update pstat");
954 SetResult(otmCtx, res);
960 OIC_LOG_V(INFO, TAG, "Error occured in provisionDefaultACLCB :: %d\n",
961 clientResponse->result);
962 SetResult(otmCtx, clientResponse->result);
966 OIC_LOG_V(INFO, TAG, "OUT ProvisioningStatusHandler.");
967 return OC_STACK_DELETE_TRANSACTION;
971 * Response handler of update provisioning status to Ready for Normal..
973 * @param[in] ctx ctx value passed to callback from calling function.
974 * @param[in] UNUSED handle to an invocation
975 * @param[in] clientResponse Response from queries to remote servers.
976 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
977 * and OC_STACK_KEEP_TRANSACTION to keep it.
979 static OCStackApplicationResult ReadyForNomalStatusHandler(void *ctx, OCDoHandle UNUSED,
980 OCClientResponse *clientResponse)
982 OIC_LOG_V(INFO, TAG, "IN ReadyForNomalStatusHandler.");
984 VERIFY_NON_NULL(TAG, clientResponse, ERROR);
985 VERIFY_NON_NULL(TAG, ctx, ERROR);
987 OTMContext_t* otmCtx = (OTMContext_t*) ctx;
990 if (OC_STACK_RESOURCE_CHANGED == clientResponse->result)
992 OIC_LOG(INFO, TAG, "Device state is in Ready for Normal Operation.");
993 OCStackResult res = PDMAddDevice(&otmCtx->selectedDeviceInfo->doxm->deviceID);
994 if (OC_STACK_OK == res)
996 OIC_LOG_V(INFO, TAG, "Add device's UUID in PDM_DB");
997 SetResult(otmCtx, OC_STACK_OK);
998 return OC_STACK_DELETE_TRANSACTION;
1002 OIC_LOG(ERROR, TAG, "Ownership transfer is complete but adding information to DB is failed.");
1007 OIC_LOG_V(INFO, TAG, "Error occured in provisionDefaultACLCB :: %d\n",
1008 clientResponse->result);
1009 SetResult(otmCtx, clientResponse->result);
1013 OIC_LOG_V(INFO, TAG, "OUT ReadyForNomalStatusHandler.");
1014 return OC_STACK_DELETE_TRANSACTION;
1017 static OCStackResult PostOwnerCredential(OTMContext_t* otmCtx)
1019 OIC_LOG(DEBUG, TAG, "IN PostOwnerCredential");
1021 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1023 OIC_LOG(ERROR, TAG, "Invalid parameters");
1024 return OC_STACK_INVALID_PARAM;
1027 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1028 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1030 if(!PMGenerateQuery(true,
1031 deviceInfo->endpoint.addr, deviceInfo->securePort,
1032 deviceInfo->connType,
1033 query, sizeof(query), OIC_RSRC_CRED_URI))
1035 OIC_LOG(ERROR, TAG, "PostOwnerCredential : Failed to generate query");
1036 return OC_STACK_ERROR;
1038 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1039 OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1042 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1043 return OC_STACK_NO_MEMORY;
1046 //Generate owner credential for new device
1047 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1048 const OicSecCred_t* ownerCredential = GetCredResourceData(&(deviceInfo->doxm->deviceID));
1049 if(!ownerCredential)
1051 OIC_LOG(ERROR, TAG, "Can not find OwnerPSK.");
1052 return OC_STACK_NO_RESOURCE;
1055 OicUuid_t credSubjectId = {.id={0}};
1056 if(OC_STACK_OK == GetDoxmDeviceID(&credSubjectId))
1058 OicSecCred_t newCredential;
1059 memcpy(&newCredential, ownerCredential, sizeof(OicSecCred_t));
1060 newCredential.next = NULL;
1062 //Set subject ID as PT's ID
1063 memcpy(&(newCredential.subject), &credSubjectId, sizeof(OicUuid_t));
1065 //Fill private data as empty string
1066 newCredential.privateData.data = "";
1067 newCredential.privateData.len = 0;
1068 newCredential.privateData.encoding = ownerCredential->privateData.encoding;
1069 #ifdef __WITH_X509__
1070 newCredential.publicData.data = NULL;
1071 newCredential.publicData.len = 0;
1074 //Send owner credential to new device : POST /oic/sec/cred [ owner credential ]
1075 if (OC_STACK_OK != CredToCBORPayload(&newCredential, &secPayload->securityData,
1076 &secPayload->payloadSize, secureFlag))
1078 OICFree(secPayload);
1079 OIC_LOG(ERROR, TAG, "Error while converting bin to cbor.");
1080 return OC_STACK_ERROR;
1082 OIC_LOG(DEBUG, TAG, "Cred Payload:");
1083 OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1085 OCCallbackData cbData;
1086 cbData.cb = &OwnerCredentialHandler;
1087 cbData.context = (void *)otmCtx;
1089 OCStackResult res = OCDoResource(NULL, OC_REST_POST, query,
1090 &deviceInfo->endpoint, (OCPayload*)secPayload,
1091 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1092 if (res != OC_STACK_OK)
1094 OIC_LOG(ERROR, TAG, "OCStack resource error");
1099 OIC_LOG(ERROR, TAG, "Failed to read DOXM device ID.");
1100 return OC_STACK_NO_RESOURCE;
1103 OIC_LOG(DEBUG, TAG, "OUT PostOwnerCredential");
1108 static OCStackResult PostOwnerTransferModeToResource(OTMContext_t* otmCtx)
1110 OIC_LOG(DEBUG, TAG, "IN PostOwnerTransferModeToResource");
1112 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1114 OIC_LOG(ERROR, TAG, "Invalid parameters");
1115 return OC_STACK_INVALID_PARAM;
1118 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1119 OicSecOxm_t selectedOxm = deviceInfo->doxm->oxmSel;
1120 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1122 if(!PMGenerateQuery(false,
1123 deviceInfo->endpoint.addr, deviceInfo->endpoint.port,
1124 deviceInfo->connType,
1125 query, sizeof(query), OIC_RSRC_DOXM_URI))
1127 OIC_LOG(ERROR, TAG, "PostOwnerTransferModeToResource : Failed to generate query");
1128 return OC_STACK_ERROR;
1130 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1131 OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1134 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1135 return OC_STACK_NO_MEMORY;
1137 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1138 OCStackResult res = g_OTMDatas[selectedOxm].createSelectOxmPayloadCB(otmCtx,
1139 &secPayload->securityData, &secPayload->payloadSize);
1140 if (OC_STACK_OK != res && NULL == secPayload->securityData)
1142 OCPayloadDestroy((OCPayload *)secPayload);
1143 OIC_LOG(ERROR, TAG, "Error while converting bin to cbor");
1144 return OC_STACK_ERROR;
1147 OCCallbackData cbData;
1148 cbData.cb = &OwnerTransferModeHandler;
1149 cbData.context = (void *)otmCtx;
1151 res = OCDoResource(NULL, OC_REST_POST, query,
1152 &deviceInfo->endpoint, (OCPayload *)secPayload,
1153 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1154 if (res != OC_STACK_OK)
1156 OIC_LOG(ERROR, TAG, "OCStack resource error");
1159 OIC_LOG(DEBUG, TAG, "OUT PostOwnerTransferModeToResource");
1164 static OCStackResult GetProvisioningStatusResource(OTMContext_t* otmCtx)
1166 OIC_LOG(DEBUG, TAG, "IN GetProvisioningStatusResource");
1168 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1170 OIC_LOG(ERROR, TAG, "Invailed parameters");
1171 return OC_STACK_INVALID_PARAM;
1174 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1175 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1176 if(!PMGenerateQuery(false,
1177 deviceInfo->endpoint.addr, deviceInfo->endpoint.port,
1178 deviceInfo->connType,
1179 query, sizeof(query), OIC_RSRC_PSTAT_URI))
1181 OIC_LOG(ERROR, TAG, "GetProvisioningStatusResource : Failed to generate query");
1182 return OC_STACK_ERROR;
1184 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1186 OCCallbackData cbData;
1187 cbData.cb = &ListMethodsHandler;
1188 cbData.context = (void *)otmCtx;
1190 OCStackResult res = OCDoResource(NULL, OC_REST_GET, query, NULL, NULL,
1191 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1192 if (res != OC_STACK_OK)
1194 OIC_LOG(ERROR, TAG, "OCStack resource error");
1197 OIC_LOG(DEBUG, TAG, "OUT GetProvisioningStatusResource");
1202 static OCStackResult PostOwnerUuid(OTMContext_t* otmCtx)
1204 OIC_LOG(DEBUG, TAG, "IN PostOwnerUuid");
1206 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1208 OIC_LOG(ERROR, TAG, "Invailed parameters");
1209 return OC_STACK_INVALID_PARAM;
1212 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1213 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1214 if(!PMGenerateQuery(true,
1215 deviceInfo->endpoint.addr, deviceInfo->securePort,
1216 deviceInfo->connType,
1217 query, sizeof(query), OIC_RSRC_DOXM_URI))
1219 OIC_LOG(ERROR, TAG, "PostOwnerUuid : Failed to generate query");
1220 return OC_STACK_ERROR;
1222 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1224 //Post PT's uuid to new device
1225 OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1228 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1229 return OC_STACK_NO_MEMORY;
1231 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1232 OCStackResult res = g_OTMDatas[deviceInfo->doxm->oxmSel].createOwnerTransferPayloadCB(
1233 otmCtx, &secPayload->securityData, &secPayload->payloadSize);
1234 if (OC_STACK_OK != res && NULL == secPayload->securityData)
1236 OCPayloadDestroy((OCPayload *)secPayload);
1237 OIC_LOG(ERROR, TAG, "Error while converting doxm bin to cbor.");
1238 return OC_STACK_INVALID_PARAM;
1240 OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1242 OCCallbackData cbData;
1243 cbData.cb = &OwnerUuidUpdateHandler;
1244 cbData.context = (void *)otmCtx;
1247 res = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload *)secPayload,
1248 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1249 if (res != OC_STACK_OK)
1251 OIC_LOG(ERROR, TAG, "OCStack resource error");
1254 OIC_LOG(DEBUG, TAG, "OUT PostOwnerUuid");
1259 static OCStackResult PostOwnershipInformation(OTMContext_t* otmCtx)
1261 OIC_LOG(DEBUG, TAG, "IN PostOwnershipInformation");
1263 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1265 OIC_LOG(ERROR, TAG, "Invailed parameters");
1266 return OC_STACK_INVALID_PARAM;
1269 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1270 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1271 if(!PMGenerateQuery(true,
1272 deviceInfo->endpoint.addr, deviceInfo->securePort,
1273 deviceInfo->connType,
1274 query, sizeof(query), OIC_RSRC_DOXM_URI))
1276 OIC_LOG(ERROR, TAG, "PostOwnershipInformation : Failed to generate query");
1277 return OC_STACK_ERROR;
1279 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1281 //OwnershipInformationHandler
1282 OCSecurityPayload *secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1285 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1286 return OC_STACK_NO_MEMORY;
1289 otmCtx->selectedDeviceInfo->doxm->owned = true;
1291 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1292 OCStackResult res = DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm,
1293 &secPayload->securityData, &secPayload->payloadSize, true);
1294 if (OC_STACK_OK != res && NULL == secPayload->securityData)
1296 OCPayloadDestroy((OCPayload *)secPayload);
1297 OIC_LOG(ERROR, TAG, "Error while converting doxm bin to json");
1298 return OC_STACK_INVALID_PARAM;
1301 OCCallbackData cbData;
1302 cbData.cb = &OwnershipInformationHandler;
1303 cbData.context = (void *)otmCtx;
1306 res = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload*)secPayload,
1307 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1308 if (res != OC_STACK_OK)
1310 OIC_LOG(ERROR, TAG, "OCStack resource error");
1313 OIC_LOG(DEBUG, TAG, "OUT PostOwnershipInformation");
1318 static OCStackResult PostUpdateOperationMode(OTMContext_t* otmCtx)
1320 OIC_LOG(DEBUG, TAG, "IN PostUpdateOperationMode");
1322 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1324 return OC_STACK_INVALID_PARAM;
1327 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1328 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1329 if(!PMGenerateQuery(false,
1330 deviceInfo->endpoint.addr, deviceInfo->endpoint.port,
1331 deviceInfo->connType,
1332 query, sizeof(query), OIC_RSRC_PSTAT_URI))
1334 OIC_LOG(ERROR, TAG, "PostUpdateOperationMode : Failed to generate query");
1335 return OC_STACK_ERROR;
1337 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1339 OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1342 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1343 return OC_STACK_NO_MEMORY;
1345 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1346 OCStackResult res = PstatToCBORPayload(deviceInfo->pstat, &secPayload->securityData,
1347 &secPayload->payloadSize, true);
1348 if (OC_STACK_OK != res)
1350 OCPayloadDestroy((OCPayload *)secPayload);
1351 OIC_LOG(ERROR, TAG, "Error while converting pstat to cbor.");
1352 return OC_STACK_INVALID_PARAM;
1355 OCCallbackData cbData;
1356 cbData.cb = &OperationModeUpdateHandler;
1357 cbData.context = (void *)otmCtx;
1359 res = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload *)secPayload,
1360 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1361 if (res != OC_STACK_OK)
1363 OIC_LOG(ERROR, TAG, "OCStack resource error");
1366 OIC_LOG(DEBUG, TAG, "OUT PostUpdateOperationMode");
1371 static OCStackResult StartOwnershipTransfer(void* ctx, OCProvisionDev_t* selectedDevice)
1373 OIC_LOG(INFO, TAG, "IN StartOwnershipTransfer");
1374 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
1375 otmCtx->selectedDeviceInfo = selectedDevice;
1377 //Set to the lowest level OxM, and then find more higher level OxM.
1378 OCStackResult res = SelectProvisioningMethod(selectedDevice->doxm->oxm,
1379 selectedDevice->doxm->oxmLen,
1380 &selectedDevice->doxm->oxmSel);
1381 if(OC_STACK_OK != res)
1383 OIC_LOG(ERROR, TAG, "Failed to select the provisioning method");
1384 SetResult(otmCtx, res);
1387 OIC_LOG_V(DEBUG, TAG, "Selected provisoning method = %d", selectedDevice->doxm->oxmSel);
1389 //Send Req: POST /oic/sec/doxm [{..."OxmSel" :g_OTMDatas[Index of Selected OxM].OXMString,...}]
1390 res = PostOwnerTransferModeToResource(otmCtx);
1391 if(OC_STACK_OK != res)
1393 OIC_LOG(WARNING, TAG, "Failed to select the provisioning method");
1394 SetResult(otmCtx, res);
1398 //Register DTLS event handler to catch the dtls event while handshake
1399 if(CA_ADAPTER_IP == ((CAEndpoint_t*)(&otmCtx->selectedDeviceInfo->endpoint))->adapter)
1401 if(CA_STATUS_OK != CARegisterDTLSCredentialsHandler(GetDtlsPskCredentials))
1403 OIC_LOG(WARNING, TAG, "Failed to register DTLS handshake callback.");
1409 if(CA_STATUS_OK != CAregisterTlsCredentialsHandler(GetDtlsPskCredentials))
1411 OIC_LOG(WARNING, TAG, "Failed to register TLS handshake callback.");
1416 OIC_LOG(INFO, TAG, "OUT StartOwnershipTransfer");
1422 OCStackResult OTMSetOwnershipTransferCallbackData(OicSecOxm_t oxmType, OTMCallbackData_t* data)
1424 OIC_LOG(DEBUG, TAG, "IN OTMSetOwnerTransferCallbackData");
1428 OIC_LOG(ERROR, TAG, "OTMSetOwnershipTransferCallbackData : Invalid parameters");
1429 return OC_STACK_INVALID_PARAM;
1431 if(oxmType >= OIC_OXM_COUNT)
1433 OIC_LOG(INFO, TAG, "Unknow ownership transfer method");
1434 return OC_STACK_INVALID_PARAM;
1437 g_OTMDatas[oxmType].loadSecretCB= data->loadSecretCB;
1438 g_OTMDatas[oxmType].createSecureSessionCB = data->createSecureSessionCB;
1439 g_OTMDatas[oxmType].createSelectOxmPayloadCB = data->createSelectOxmPayloadCB;
1440 g_OTMDatas[oxmType].createOwnerTransferPayloadCB = data->createOwnerTransferPayloadCB;
1442 OIC_LOG(DEBUG, TAG, "OUT OTMSetOwnerTransferCallbackData");
1448 * NOTE : Unowned discovery should be done before performing OTMDoOwnershipTransfer
1450 OCStackResult OTMDoOwnershipTransfer(void* ctx,
1451 OCProvisionDev_t *selectedDevicelist,
1452 OCProvisionResultCB resultCallback)
1454 OIC_LOG(DEBUG, TAG, "IN OTMDoOwnershipTransfer");
1456 if (NULL == selectedDevicelist)
1458 return OC_STACK_INVALID_PARAM;
1460 if (NULL == resultCallback)
1462 return OC_STACK_INVALID_CALLBACK;
1465 OTMContext_t* otmCtx = (OTMContext_t*)OICCalloc(1,sizeof(OTMContext_t));
1468 OIC_LOG(ERROR, TAG, "Failed to create OTM Context");
1469 return OC_STACK_NO_MEMORY;
1471 otmCtx->ctxResultCallback = resultCallback;
1472 otmCtx->ctxHasError = false;
1473 otmCtx->userCtx = ctx;
1474 OCProvisionDev_t* pCurDev = selectedDevicelist;
1476 //Counting number of selected devices.
1477 otmCtx->ctxResultArraySize = 0;
1478 while(NULL != pCurDev)
1480 otmCtx->ctxResultArraySize++;
1481 pCurDev = pCurDev->next;
1484 otmCtx->ctxResultArray =
1485 (OCProvisionResult_t*)OICCalloc(otmCtx->ctxResultArraySize, sizeof(OCProvisionResult_t));
1486 if(NULL == otmCtx->ctxResultArray)
1488 OIC_LOG(ERROR, TAG, "OTMDoOwnershipTransfer : Failed to memory allocation");
1490 return OC_STACK_NO_MEMORY;
1492 pCurDev = selectedDevicelist;
1494 OCStackResult res = OC_STACK_OK;
1495 //Fill the device UUID for result array.
1496 for(size_t devIdx = 0; devIdx < otmCtx->ctxResultArraySize; devIdx++)
1498 //Checking duplication of Device ID.
1499 bool isDuplicate = true;
1500 res = PDMIsDuplicateDevice(&pCurDev->doxm->deviceID, &isDuplicate);
1501 if (OC_STACK_OK != res)
1507 bool isStale = false;
1508 res = PDMIsDeviceStale(&pCurDev->doxm->deviceID, &isStale);
1509 if(OC_STACK_OK != res)
1511 OIC_LOG(ERROR, TAG, "Internal error in PDMIsDeviceStale");
1516 OIC_LOG(INFO, TAG, "Detected duplicated UUID in stale status, "\
1517 "this UUID will be removed from PDM");
1519 res = PDMDeleteDevice(&pCurDev->doxm->deviceID);
1520 if(OC_STACK_OK != res)
1522 OIC_LOG(ERROR, TAG, "Internal error in PDMDeleteDevice");
1528 OIC_LOG(ERROR, TAG, "OTMDoOwnershipTransfer : Device UUID is duplicated");
1529 res = OC_STACK_INVALID_PARAM;
1533 memcpy(otmCtx->ctxResultArray[devIdx].deviceId.id,
1534 pCurDev->doxm->deviceID.id,
1536 otmCtx->ctxResultArray[devIdx].res = OC_STACK_CONTINUE;
1537 pCurDev = pCurDev->next;
1540 StartOwnershipTransfer(otmCtx, selectedDevicelist);
1542 OIC_LOG(DEBUG, TAG, "OUT OTMDoOwnershipTransfer");
1546 OICFree(otmCtx->ctxResultArray);
1551 OCStackResult PostProvisioningStatus(OTMContext_t* otmCtx)
1553 OIC_LOG(INFO, TAG, "IN PostProvisioningStatus");
1555 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1557 OIC_LOG(ERROR, TAG, "OTMContext is NULL");
1558 return OC_STACK_INVALID_PARAM;
1561 //Change the TAKE_OWNER bit of CM to 0.
1562 otmCtx->selectedDeviceInfo->pstat->cm &= (~TAKE_OWNER);
1564 OCSecurityPayload *secPayload = (OCSecurityPayload *)OICCalloc(1, sizeof(OCSecurityPayload));
1567 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1568 return OC_STACK_NO_MEMORY;
1570 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1571 if (OC_STACK_OK != PstatToCBORPayload(otmCtx->selectedDeviceInfo->pstat,
1572 &secPayload->securityData, &secPayload->payloadSize, true))
1574 OCPayloadDestroy((OCPayload *)secPayload);
1575 return OC_STACK_INVALID_JSON;
1577 OIC_LOG(DEBUG, TAG, "Created payload for chage to Provisiong state");
1578 OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1580 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1581 if(!PMGenerateQuery(true,
1582 otmCtx->selectedDeviceInfo->endpoint.addr,
1583 otmCtx->selectedDeviceInfo->securePort,
1584 otmCtx->selectedDeviceInfo->connType,
1585 query, sizeof(query), OIC_RSRC_PSTAT_URI))
1587 OIC_LOG(ERROR, TAG, "PostProvisioningStatus : Failed to generate query");
1588 return OC_STACK_ERROR;
1590 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1592 OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
1593 cbData.cb = &ProvisioningStatusHandler;
1594 cbData.context = (void*)otmCtx;
1596 OCStackResult ret = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload*)secPayload,
1597 otmCtx->selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1598 OIC_LOG_V(INFO, TAG, "OCDoResource returned: %d",ret);
1599 if (ret != OC_STACK_OK)
1601 OIC_LOG(ERROR, TAG, "OCStack resource error");
1604 OIC_LOG(INFO, TAG, "OUT PostProvisioningStatus");
1609 OCStackResult PostNormalOperationStatus(OTMContext_t* otmCtx)
1611 OIC_LOG(INFO, TAG, "IN PostNormalOperationStatus");
1613 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1615 OIC_LOG(ERROR, TAG, "OTMContext is NULL");
1616 return OC_STACK_INVALID_PARAM;
1620 otmCtx->selectedDeviceInfo->pstat->isOp = true;
1622 OCSecurityPayload *secPayload = (OCSecurityPayload *)OICCalloc(1, sizeof(OCSecurityPayload));
1625 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1626 return OC_STACK_NO_MEMORY;
1628 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1629 if (OC_STACK_OK != PstatToCBORPayload(otmCtx->selectedDeviceInfo->pstat,
1630 &secPayload->securityData, &secPayload->payloadSize, true))
1632 OCPayloadDestroy((OCPayload *)secPayload);
1633 return OC_STACK_INVALID_JSON;
1635 OIC_LOG(DEBUG, TAG, "Created payload for chage to Provisiong state");
1636 OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1638 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1639 if(!PMGenerateQuery(true,
1640 otmCtx->selectedDeviceInfo->endpoint.addr,
1641 otmCtx->selectedDeviceInfo->securePort,
1642 otmCtx->selectedDeviceInfo->connType,
1643 query, sizeof(query), OIC_RSRC_PSTAT_URI))
1645 OIC_LOG(ERROR, TAG, "PostNormalOperationStatus : Failed to generate query");
1646 return OC_STACK_ERROR;
1648 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1650 OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
1651 cbData.cb = &ReadyForNomalStatusHandler;
1652 cbData.context = (void*)otmCtx;
1654 OCStackResult ret = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload*)secPayload,
1655 otmCtx->selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1656 OIC_LOG_V(INFO, TAG, "OCDoResource returned: %d",ret);
1657 if (ret != OC_STACK_OK)
1659 OIC_LOG(ERROR, TAG, "OCStack resource error");
1662 OIC_LOG(INFO, TAG, "OUT PostNormalOperationStatus");