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_STATUS_OK != CAregisterPskCredentialsHandler(GetDtlsPskCredentials))
250 OIC_LOG(WARNING, TAG, "Failed to revert is DTLS credential handler.");
252 OicUuid_t emptyUuid = { .id={0}};
253 SetUuidForRandomPinOxm(&emptyUuid);
256 for(size_t i = 0; i < otmCtx->ctxResultArraySize; i++)
258 if(memcmp(otmCtx->selectedDeviceInfo->doxm->deviceID.id,
259 otmCtx->ctxResultArray[i].deviceId.id, UUID_LENGTH) == 0)
261 otmCtx->ctxResultArray[i].res = res;
262 if(OC_STACK_OK != res)
264 otmCtx->ctxHasError = true;
271 //If all request is completed, invoke the user callback.
272 if(IsComplete(otmCtx))
274 otmCtx->ctxResultCallback(otmCtx->userCtx, otmCtx->ctxResultArraySize,
275 otmCtx->ctxResultArray, otmCtx->ctxHasError);
276 OICFree(otmCtx->ctxResultArray);
281 if(OC_STACK_OK != StartOwnershipTransfer(otmCtx,
282 otmCtx->selectedDeviceInfo->next))
284 OIC_LOG(ERROR, TAG, "Failed to StartOwnershipTransfer");
289 OIC_LOG(DEBUG, TAG, "OUT SetResult");
293 * Function to handle the handshake result in OTM.
294 * This function will be invoked after DTLS handshake
295 * @param endPoint [IN] The remote endpoint.
296 * @param errorInfo [IN] Error information from the endpoint.
299 void DTLSHandshakeCB(const CAEndpoint_t *endpoint, const CAErrorInfo_t *info)
301 if(NULL != g_otmCtx && NULL != g_otmCtx->selectedDeviceInfo &&
302 NULL != endpoint && NULL != info)
304 OIC_LOG_V(INFO, TAG, "Received status from remote device(%s:%d) : %d",
305 endpoint->addr, endpoint->port, info->result);
307 OicSecDoxm_t* newDevDoxm = g_otmCtx->selectedDeviceInfo->doxm;
309 if(NULL != newDevDoxm)
311 OicUuid_t emptyUuid = {.id={0}};
313 //Make sure the address matches.
314 if(strncmp(g_otmCtx->selectedDeviceInfo->endpoint.addr,
316 sizeof(endpoint->addr)) == 0 &&
317 g_otmCtx->selectedDeviceInfo->securePort == endpoint->port)
319 OCStackResult res = OC_STACK_ERROR;
321 //If temporal secure sesstion established successfully
322 if(CA_STATUS_OK == info->result &&
323 false == newDevDoxm->owned &&
324 memcmp(&(newDevDoxm->owner), &emptyUuid, sizeof(OicUuid_t)) == 0)
326 //Send request : POST /oic/sec/doxm [{... , "devowner":"PT's UUID"}]
327 res = PostOwnerUuid(g_otmCtx);
328 if(OC_STACK_OK != res)
330 OIC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to send owner information");
331 SetResult(g_otmCtx, res);
334 //In case of authentication failure
335 else if(CA_DTLS_AUTHENTICATION_FAILURE == info->result)
337 //in case of error from owner credential
338 if(memcmp(&(newDevDoxm->owner), &emptyUuid, sizeof(OicUuid_t)) != 0 &&
339 true == newDevDoxm->owned)
341 OIC_LOG(ERROR, TAG, "The owner credential may incorrect.");
343 if(OC_STACK_OK != RemoveCredential(&(newDevDoxm->deviceID)))
345 OIC_LOG(WARNING, TAG, "Failed to remove the invaild owner credential");
347 SetResult(g_otmCtx, OC_STACK_AUTHENTICATION_FAILURE);
349 //in case of error from wrong PIN, re-start the ownership transfer
350 else if(OIC_RANDOM_DEVICE_PIN == newDevDoxm->oxmSel)
352 OIC_LOG(ERROR, TAG, "The PIN number may incorrect.");
354 memcpy(&(newDevDoxm->owner), &emptyUuid, sizeof(OicUuid_t));
355 newDevDoxm->owned = false;
356 g_otmCtx->attemptCnt++;
358 if(WRONG_PIN_MAX_ATTEMP > g_otmCtx->attemptCnt)
360 res = StartOwnershipTransfer(g_otmCtx, g_otmCtx->selectedDeviceInfo);
361 if(OC_STACK_OK != res)
363 SetResult(g_otmCtx, res);
364 OIC_LOG(ERROR, TAG, "Failed to Re-StartOwnershipTransfer");
369 OIC_LOG(ERROR, TAG, "User has exceeded the number of authentication attempts.");
370 SetResult(g_otmCtx, OC_STACK_AUTHENTICATION_FAILURE);
375 OIC_LOG(ERROR, TAG, "Failed to establish secure session.");
376 SetResult(g_otmCtx, OC_STACK_AUTHENTICATION_FAILURE);
385 * Function to save ownerPSK at provisioning tool end.
387 * @param[in] selectedDeviceInfo selected device information to performing provisioning.
388 * @return OC_STACK_OK on success
390 static OCStackResult SaveOwnerPSK(OCProvisionDev_t *selectedDeviceInfo)
392 OIC_LOG(DEBUG, TAG, "IN SaveOwnerPSK");
394 OCStackResult res = OC_STACK_ERROR;
396 CAEndpoint_t endpoint;
397 memset(&endpoint, 0x00, sizeof(CAEndpoint_t));
398 OICStrcpy(endpoint.addr, MAX_ADDR_STR_SIZE_CA, selectedDeviceInfo->endpoint.addr);
399 endpoint.addr[MAX_ADDR_STR_SIZE_CA - 1] = '\0';
400 endpoint.port = selectedDeviceInfo->securePort;
401 endpoint.adapter = selectedDeviceInfo->endpoint.adapter;
403 OicUuid_t ptDeviceID = {.id={0}};
404 if (OC_STACK_OK != GetDoxmDeviceID(&ptDeviceID))
406 OIC_LOG(ERROR, TAG, "Error while retrieving provisioning tool's device ID");
410 uint8_t ownerPSK[OWNER_PSK_LENGTH_128] = {0};
411 OicSecKey_t ownerKey = {ownerPSK, OWNER_PSK_LENGTH_128};
413 //Generating OwnerPSK
414 CAResult_t pskRet = CAGenerateOwnerPSK(&endpoint,
415 (uint8_t *)GetOxmString(selectedDeviceInfo->doxm->oxmSel),
416 strlen(GetOxmString(selectedDeviceInfo->doxm->oxmSel)),
417 ptDeviceID.id, sizeof(ptDeviceID.id),
418 selectedDeviceInfo->doxm->deviceID.id, sizeof(selectedDeviceInfo->doxm->deviceID.id),
419 ownerPSK, OWNER_PSK_LENGTH_128);
421 if (CA_STATUS_OK == pskRet)
423 OIC_LOG(INFO, TAG,"ownerPSK dump:\n");
424 OIC_LOG_BUFFER(INFO, TAG,ownerPSK, OWNER_PSK_LENGTH_128);
425 //Generating new credential for provisioning tool
426 OicSecCred_t *cred = GenerateCredential(&selectedDeviceInfo->doxm->deviceID,
427 SYMMETRIC_PAIR_WISE_KEY, NULL,
428 &ownerKey, &ptDeviceID);
429 VERIFY_NON_NULL(TAG, cred, ERROR);
431 // TODO: Added as workaround. Will be replaced soon.
432 cred->privateData.encoding = OIC_ENCODING_RAW;
435 // NOTE: Test codes to use BASE64 encoded owner PSK.
436 uint32_t outSize = 0;
437 size_t b64BufSize = B64ENCODE_OUT_SAFESIZE((OWNER_PSK_LENGTH_128 + 1));
438 char* b64Buf = (uint8_t *)OICCalloc(1, b64BufSize);
439 VERIFY_NON_NULL(TAG, b64Buf, ERROR);
440 b64Encode(cred->privateData.data, cred->privateData.len, b64Buf, b64BufSize, &outSize);
442 OICFree( cred->privateData.data );
443 cred->privateData.data = (uint8_t *)OICCalloc(1, outSize + 1);
444 VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
446 strncpy(cred->privateData.data, b64Buf, outSize);
447 cred->privateData.data[outSize] = '\0';
448 cred->privateData.encoding = OIC_ENCODING_BASE64;
449 cred->privateData.len = outSize;
451 #endif //End of Test codes
453 //Finding previous ownerPSK.
454 const OicSecCred_t* credList = GetCredList();
455 OicSecCred_t* prevCred = NULL;
457 LL_FOREACH(credList, prevCred)
459 //OwnerPSK's type is SYMMETRIC_PAIR_WISE_KEY
460 if (SYMMETRIC_PAIR_WISE_KEY == prevCred->credType &&
461 0 == memcmp(prevCred->subject.id, cred->subject.id, sizeof(cred->subject.id)))
463 credId = prevCred->credId;
468 //If duplicate owner PSK is exists, remove it.
471 OIC_LOG(WARNING, TAG, "Duplicate OwnerPSK was detected.");
472 OIC_LOG(WARNING, TAG, "[Subject] : ");
473 OIC_LOG_BUFFER(WARNING, TAG, prevCred->subject.id, sizeof(prevCred->subject.id));
474 OIC_LOG_V(WARNING, TAG, "[Encoding Type] : %d", prevCred->privateData.encoding);
475 OIC_LOG(WARNING, TAG, "[Private Data] : ");
476 OIC_LOG_BUFFER(WARNING, TAG, prevCred->privateData.data, prevCred->privateData.len);
477 OIC_LOG(WARNING, TAG, "Previous OwnerPSK will be removed.");
479 res = RemoveCredentialByCredId(credId);
480 if(OC_STACK_RESOURCE_DELETED != res)
482 OIC_LOG(ERROR, TAG, "Failed to remove the previous OwnerPSK");
483 DeleteCredList(cred);
488 res = AddCredential(cred);
489 if(res != OC_STACK_OK)
491 DeleteCredList(cred);
497 OIC_LOG(ERROR, TAG, "CAGenerateOwnerPSK failed");
500 OIC_LOG(DEBUG, TAG, "OUT SaveOwnerPSK");
506 * Callback handler for OwnerShipTransferModeHandler API.
508 * @param[in] ctx ctx value passed to callback from calling function.
509 * @param[in] UNUSED handle to an invocation
510 * @param[in] clientResponse Response from queries to remote servers.
511 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
512 * and OC_STACK_KEEP_TRANSACTION to keep it.
514 static OCStackApplicationResult OwnerTransferModeHandler(void *ctx, OCDoHandle UNUSED,
515 OCClientResponse *clientResponse)
517 OIC_LOG(DEBUG, TAG, "IN OwnerTransferModeHandler");
519 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
520 VERIFY_NON_NULL(TAG, ctx, WARNING);
522 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
524 if (OC_STACK_RESOURCE_CHANGED == clientResponse->result)
526 OIC_LOG(INFO, TAG, "OwnerTransferModeHandler : response result = OC_STACK_OK");
527 //Send request : GET /oic/sec/pstat
528 OCStackResult res = GetProvisioningStatusResource(otmCtx);
529 if(OC_STACK_OK != res)
531 OIC_LOG(WARNING, TAG, "Failed to get pstat information");
532 SetResult(otmCtx, res);
537 OIC_LOG_V(WARNING, TAG, "OwnerTransferModeHandler : Client response is incorrect : %d",
538 clientResponse->result);
539 SetResult(otmCtx, clientResponse->result);
542 OIC_LOG(DEBUG, TAG, "OUT OwnerTransferModeHandler");
545 return OC_STACK_DELETE_TRANSACTION;
549 * Callback handler for ProvisioningStatusResouceHandler API.
551 * @param[in] ctx ctx value passed to callback from calling function.
552 * @param[in] UNUSED handle to an invocation
553 * @param[in] clientResponse Response from queries to remote servers.
554 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
555 * and OC_STACK_KEEP_TRANSACTION to keep it.
557 static OCStackApplicationResult ListMethodsHandler(void *ctx, OCDoHandle UNUSED,
558 OCClientResponse *clientResponse)
560 OIC_LOG(DEBUG, TAG, "IN ListMethodsHandler");
562 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
563 VERIFY_NON_NULL(TAG, ctx, WARNING);
565 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
567 if (OC_STACK_OK == clientResponse->result)
569 if (NULL == clientResponse->payload)
571 OIC_LOG(INFO, TAG, "Skiping Null payload");
572 SetResult(otmCtx, OC_STACK_ERROR);
573 return OC_STACK_DELETE_TRANSACTION;
576 if (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)
578 OIC_LOG(INFO, TAG, "Unknown payload type");
579 SetResult(otmCtx, OC_STACK_ERROR);
580 return OC_STACK_DELETE_TRANSACTION;
582 OicSecPstat_t* pstat = NULL;
583 OCStackResult result = CBORPayloadToPstat(
584 ((OCSecurityPayload*)clientResponse->payload)->securityData,
585 ((OCSecurityPayload*)clientResponse->payload)->payloadSize,
587 if(NULL == pstat || result != OC_STACK_OK)
589 OIC_LOG(ERROR, TAG, "Error while converting cbor to pstat.");
590 SetResult(otmCtx, OC_STACK_ERROR);
591 return OC_STACK_DELETE_TRANSACTION;
593 if(false == (TAKE_OWNER & pstat->cm))
595 OIC_LOG(ERROR, TAG, "Device pairing mode enabling owner transfer operations is disabled");
596 SetResult(otmCtx, OC_STACK_ERROR);
597 return OC_STACK_DELETE_TRANSACTION;
599 otmCtx->selectedDeviceInfo->pstat = pstat;
601 //Select operation mode (Currently supported SINGLE_SERVICE_CLIENT_DRIVEN only)
602 SelectOperationMode(otmCtx->selectedDeviceInfo, &(otmCtx->selectedDeviceInfo->pstat->om));
604 //Send request : POST /oic/sec/pstat [{"om":"bx11", .. }]
605 OCStackResult res = PostUpdateOperationMode(otmCtx);
606 if (OC_STACK_OK != res)
608 OIC_LOG(ERROR, TAG, "Error while updating operation mode.");
609 SetResult(otmCtx, res);
614 OIC_LOG_V(WARNING, TAG, "ListMethodsHandler : Client response is incorrect : %d",
615 clientResponse->result);
616 SetResult(otmCtx, clientResponse->result);
619 OIC_LOG(DEBUG, TAG, "OUT ListMethodsHandler");
621 return OC_STACK_DELETE_TRANSACTION;
625 * Response handler for update owner uuid request.
627 * @param[in] ctx ctx value passed to callback from calling function.
628 * @param[in] UNUSED handle to an invocation
629 * @param[in] clientResponse Response from queries to remote servers.
630 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
631 * and OC_STACK_KEEP_TRANSACTION to keep it.
633 static OCStackApplicationResult OwnerUuidUpdateHandler(void *ctx, OCDoHandle UNUSED,
634 OCClientResponse *clientResponse)
636 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
637 VERIFY_NON_NULL(TAG, ctx, WARNING);
639 OIC_LOG(DEBUG, TAG, "IN OwnerUuidUpdateHandler");
641 OCStackResult res = OC_STACK_OK;
642 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
644 if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
646 if(otmCtx && otmCtx->selectedDeviceInfo)
648 res = SaveOwnerPSK(otmCtx->selectedDeviceInfo);
649 if(OC_STACK_OK != res)
651 OIC_LOG(ERROR, TAG, "OwnerUuidUpdateHandler:Failed to owner PSK generation");
652 SetResult(otmCtx, res);
653 return OC_STACK_DELETE_TRANSACTION;
656 //POST owner credential to new device according to security spec B.
657 res = PostOwnerCredential(otmCtx);
658 if(OC_STACK_OK != res)
661 "OwnerUuidUpdateHandler:Failed to send PosT request for onwer credential");
662 SetResult(otmCtx, res);
663 return OC_STACK_DELETE_TRANSACTION;
669 res = clientResponse->result;
670 OIC_LOG_V(ERROR, TAG, "OwnerUuidHandler : Unexpected result %d", res);
671 SetResult(otmCtx, res);
674 OIC_LOG(DEBUG, TAG, "OUT OwnerUuidUpdateHandler");
677 return OC_STACK_DELETE_TRANSACTION;
681 * Response handler for update operation mode.
683 * @param[in] ctx ctx value passed to callback from calling function.
684 * @param[in] UNUSED handle to an invocation
685 * @param[in] clientResponse Response from queries to remote servers.
686 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
687 * and OC_STACK_KEEP_TRANSACTION to keep it.
689 static OCStackApplicationResult OperationModeUpdateHandler(void *ctx, OCDoHandle UNUSED,
690 OCClientResponse *clientResponse)
692 OIC_LOG(DEBUG, TAG, "IN OperationModeUpdateHandler");
694 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
695 VERIFY_NON_NULL(TAG, ctx, WARNING);
697 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
699 if (OC_STACK_RESOURCE_CHANGED == clientResponse->result)
701 OCStackResult res = OC_STACK_ERROR;
702 OicSecOxm_t selOxm = otmCtx->selectedDeviceInfo->doxm->oxmSel;
704 //Load secret for temporal secure session.
705 if(g_OTMDatas[selOxm].loadSecretCB)
707 res = g_OTMDatas[selOxm].loadSecretCB(otmCtx);
708 if(OC_STACK_OK != res)
710 OIC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to load secret");
711 SetResult(otmCtx, res);
712 return OC_STACK_DELETE_TRANSACTION;
716 //It will be used in handshake event handler
719 //Try DTLS handshake to generate secure session
720 if(g_OTMDatas[selOxm].createSecureSessionCB)
722 res = g_OTMDatas[selOxm].createSecureSessionCB(otmCtx);
723 if(OC_STACK_OK != res)
725 OIC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to create DTLS session");
726 SetResult(otmCtx, res);
727 return OC_STACK_DELETE_TRANSACTION;
733 OIC_LOG(ERROR, TAG, "Error while update operation mode");
734 SetResult(otmCtx, clientResponse->result);
737 OIC_LOG(DEBUG, TAG, "OUT OperationModeUpdateHandler");
740 return OC_STACK_DELETE_TRANSACTION;
744 * Response handler for update owner crendetial request.
746 * @param[in] ctx ctx value passed to callback from calling function.
747 * @param[in] UNUSED handle to an invocation
748 * @param[in] clientResponse Response from queries to remote servers.
749 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
750 * and OC_STACK_KEEP_TRANSACTION to keep it.
752 static OCStackApplicationResult OwnerCredentialHandler(void *ctx, OCDoHandle UNUSED,
753 OCClientResponse *clientResponse)
755 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
756 VERIFY_NON_NULL(TAG, ctx, WARNING);
758 OIC_LOG(DEBUG, TAG, "IN OwnerCredentialHandler");
760 OCStackResult res = OC_STACK_OK;
761 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
763 if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
765 if(otmCtx && otmCtx->selectedDeviceInfo)
767 //Close the temporal secure session to verify the owner credential
768 CAEndpoint_t* endpoint = (CAEndpoint_t *)&otmCtx->selectedDeviceInfo->endpoint;
769 endpoint->port = otmCtx->selectedDeviceInfo->securePort;
770 CAResult_t caResult = CA_STATUS_OK;
771 caResult = CAcloseSslConnection(endpoint);
773 if(CA_STATUS_OK != caResult)
775 OIC_LOG(ERROR, TAG, "Failed to close DTLS session");
776 SetResult(otmCtx, caResult);
777 return OC_STACK_DELETE_TRANSACTION;
781 * If we select NULL cipher,
782 * client will select appropriate cipher suite according to server's cipher-suite list.
784 // TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256 = 0xC037, /**< see RFC 5489 */
785 caResult = CASelectCipherSuite(0xC037, endpoint->adapter);
787 if(CA_STATUS_OK != caResult)
789 OIC_LOG(ERROR, TAG, "Failed to select TLS_NULL_WITH_NULL_NULL");
790 SetResult(otmCtx, caResult);
791 return OC_STACK_DELETE_TRANSACTION;
795 * in case of random PIN based OxM,
796 * revert get_psk_info callback of tinyDTLS to use owner credential.
798 if(OIC_RANDOM_DEVICE_PIN == otmCtx->selectedDeviceInfo->doxm->oxmSel)
800 OicUuid_t emptyUuid = { .id={0}};
801 SetUuidForRandomPinOxm(&emptyUuid);
803 caResult = CAregisterPskCredentialsHandler(GetDtlsPskCredentials);
805 if(CA_STATUS_OK != caResult)
807 OIC_LOG(ERROR, TAG, "Failed to revert DTLS credential handler.");
808 SetResult(otmCtx, OC_STACK_INVALID_CALLBACK);
809 return OC_STACK_DELETE_TRANSACTION;
813 otmCtx->selectedDeviceInfo->connType |= CT_FLAG_SECURE;
815 //POST /oic/sec/doxm [{ ..., "owned":"TRUE" }]
816 res = PostOwnershipInformation(otmCtx);
817 if(OC_STACK_OK != res)
819 OIC_LOG(ERROR, TAG, "Failed to post ownership information to new device");
820 SetResult(otmCtx, res);
821 return OC_STACK_DELETE_TRANSACTION;
827 res = clientResponse->result;
828 OIC_LOG_V(ERROR, TAG, "OwnerCredentialHandler : Unexpected result %d", res);
829 SetResult(otmCtx, res);
832 OIC_LOG(DEBUG, TAG, "OUT OwnerCredentialHandler");
835 return OC_STACK_DELETE_TRANSACTION;
840 * Response handler for update owner information request.
842 * @param[in] ctx ctx value passed to callback from calling function.
843 * @param[in] UNUSED handle to an invocation
844 * @param[in] clientResponse Response from queries to remote servers.
845 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
846 * and OC_STACK_KEEP_TRANSACTION to keep it.
848 static OCStackApplicationResult OwnershipInformationHandler(void *ctx, OCDoHandle UNUSED,
849 OCClientResponse *clientResponse)
851 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
852 VERIFY_NON_NULL(TAG, ctx, WARNING);
854 OIC_LOG(DEBUG, TAG, "IN OwnershipInformationHandler");
856 OCStackResult res = OC_STACK_OK;
857 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
859 if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
861 if(otmCtx && otmCtx->selectedDeviceInfo)
863 OIC_LOG(INFO, TAG, "Ownership transfer was successfully completed.");
864 OIC_LOG(INFO, TAG, "Set Ready for provisioning state .");
866 res = PostProvisioningStatus(otmCtx);
867 if(OC_STACK_OK != res)
869 OIC_LOG(ERROR, TAG, "Failed to update pstat");
870 SetResult(otmCtx, res);
876 res = clientResponse->result;
877 OIC_LOG_V(ERROR, TAG, "OwnershipInformationHandler : Unexpected result %d", res);
878 SetResult(otmCtx, res);
881 OIC_LOG(DEBUG, TAG, "OUT OwnershipInformationHandler");
884 return OC_STACK_DELETE_TRANSACTION;
888 * Response handler of update provisioning status.
890 * @param[in] ctx ctx value passed to callback from calling function.
891 * @param[in] UNUSED handle to an invocation
892 * @param[in] clientResponse Response from queries to remote servers.
893 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
894 * and OC_STACK_KEEP_TRANSACTION to keep it.
896 static OCStackApplicationResult ProvisioningStatusHandler(void *ctx, OCDoHandle UNUSED,
897 OCClientResponse *clientResponse)
899 OIC_LOG_V(INFO, TAG, "IN ProvisioningStatusHandler.");
901 VERIFY_NON_NULL(TAG, clientResponse, ERROR);
902 VERIFY_NON_NULL(TAG, ctx, ERROR);
904 OTMContext_t* otmCtx = (OTMContext_t*) ctx;
906 OCStackResult res = OC_STACK_OK;
908 if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
910 if(otmCtx && otmCtx->selectedDeviceInfo)
912 OIC_LOG(INFO, TAG, "Device state is in Ready for Provisionig.");
914 res = PostNormalOperationStatus(otmCtx);
915 if(OC_STACK_OK != res)
917 OIC_LOG(ERROR, TAG, "Failed to update pstat");
918 SetResult(otmCtx, res);
924 OIC_LOG_V(INFO, TAG, "Error occured in provisionDefaultACLCB :: %d\n",
925 clientResponse->result);
926 SetResult(otmCtx, clientResponse->result);
930 OIC_LOG_V(INFO, TAG, "OUT ProvisioningStatusHandler.");
931 return OC_STACK_DELETE_TRANSACTION;
935 * Response handler of update provisioning status to Ready for Normal..
937 * @param[in] ctx ctx value passed to callback from calling function.
938 * @param[in] UNUSED handle to an invocation
939 * @param[in] clientResponse Response from queries to remote servers.
940 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
941 * and OC_STACK_KEEP_TRANSACTION to keep it.
943 static OCStackApplicationResult ReadyForNomalStatusHandler(void *ctx, OCDoHandle UNUSED,
944 OCClientResponse *clientResponse)
946 OIC_LOG_V(INFO, TAG, "IN ReadyForNomalStatusHandler.");
948 VERIFY_NON_NULL(TAG, clientResponse, ERROR);
949 VERIFY_NON_NULL(TAG, ctx, ERROR);
951 OTMContext_t* otmCtx = (OTMContext_t*) ctx;
954 if (OC_STACK_RESOURCE_CHANGED == clientResponse->result)
956 OIC_LOG(INFO, TAG, "Device state is in Ready for Normal Operation.");
957 OCStackResult res = PDMAddDevice(&otmCtx->selectedDeviceInfo->doxm->deviceID);
958 if (OC_STACK_OK == res)
960 OIC_LOG_V(INFO, TAG, "Add device's UUID in PDM_DB");
961 SetResult(otmCtx, OC_STACK_OK);
962 return OC_STACK_DELETE_TRANSACTION;
966 OIC_LOG(ERROR, TAG, "Ownership transfer is complete but adding information to DB is failed.");
971 OIC_LOG_V(INFO, TAG, "Error occured in provisionDefaultACLCB :: %d\n",
972 clientResponse->result);
973 SetResult(otmCtx, clientResponse->result);
977 OIC_LOG_V(INFO, TAG, "OUT ReadyForNomalStatusHandler.");
978 return OC_STACK_DELETE_TRANSACTION;
981 static OCStackResult PostOwnerCredential(OTMContext_t* otmCtx)
983 OIC_LOG(DEBUG, TAG, "IN PostOwnerCredential");
985 if(!otmCtx || !otmCtx->selectedDeviceInfo)
987 OIC_LOG(ERROR, TAG, "Invalid parameters");
988 return OC_STACK_INVALID_PARAM;
991 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
992 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
994 if(!PMGenerateQuery(true,
995 deviceInfo->endpoint.addr, deviceInfo->securePort,
996 deviceInfo->connType,
997 query, sizeof(query), OIC_RSRC_CRED_URI))
999 OIC_LOG(ERROR, TAG, "PostOwnerCredential : Failed to generate query");
1000 return OC_STACK_ERROR;
1002 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1003 OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1006 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1007 return OC_STACK_NO_MEMORY;
1010 //Generate owner credential for new device
1011 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1012 const OicSecCred_t* ownerCredential = GetCredResourceData(&(deviceInfo->doxm->deviceID));
1013 if(!ownerCredential)
1015 OIC_LOG(ERROR, TAG, "Can not find OwnerPSK.");
1016 return OC_STACK_NO_RESOURCE;
1019 OicUuid_t credSubjectId = {.id={0}};
1020 if(OC_STACK_OK == GetDoxmDeviceID(&credSubjectId))
1022 OicSecCred_t newCredential;
1023 memcpy(&newCredential, ownerCredential, sizeof(OicSecCred_t));
1024 newCredential.next = NULL;
1026 //Set subject ID as PT's ID
1027 memcpy(&(newCredential.subject), &credSubjectId, sizeof(OicUuid_t));
1029 //Fill private data as empty string
1030 newCredential.privateData.data = "";
1031 newCredential.privateData.len = 0;
1032 newCredential.privateData.encoding = ownerCredential->privateData.encoding;
1034 newCredential.publicData.data = NULL;
1035 newCredential.publicData.len = 0;
1038 //Send owner credential to new device : POST /oic/sec/cred [ owner credential ]
1039 if (OC_STACK_OK != CredToCBORPayload(&newCredential, &secPayload->securityData,
1040 &secPayload->payloadSize, secureFlag))
1042 OICFree(secPayload);
1043 OIC_LOG(ERROR, TAG, "Error while converting bin to cbor.");
1044 return OC_STACK_ERROR;
1046 OIC_LOG(DEBUG, TAG, "Cred Payload:");
1047 OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1049 OCCallbackData cbData;
1050 cbData.cb = &OwnerCredentialHandler;
1051 cbData.context = (void *)otmCtx;
1053 OCStackResult res = OCDoResource(NULL, OC_REST_POST, query,
1054 &deviceInfo->endpoint, (OCPayload*)secPayload,
1055 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1056 if (res != OC_STACK_OK)
1058 OIC_LOG(ERROR, TAG, "OCStack resource error");
1063 OIC_LOG(ERROR, TAG, "Failed to read DOXM device ID.");
1064 return OC_STACK_NO_RESOURCE;
1067 OIC_LOG(DEBUG, TAG, "OUT PostOwnerCredential");
1072 static OCStackResult PostOwnerTransferModeToResource(OTMContext_t* otmCtx)
1074 OIC_LOG(DEBUG, TAG, "IN PostOwnerTransferModeToResource");
1076 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1078 OIC_LOG(ERROR, TAG, "Invalid parameters");
1079 return OC_STACK_INVALID_PARAM;
1082 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1083 OicSecOxm_t selectedOxm = deviceInfo->doxm->oxmSel;
1084 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1086 if(!PMGenerateQuery(false,
1087 deviceInfo->endpoint.addr, deviceInfo->endpoint.port,
1088 deviceInfo->connType,
1089 query, sizeof(query), OIC_RSRC_DOXM_URI))
1091 OIC_LOG(ERROR, TAG, "PostOwnerTransferModeToResource : Failed to generate query");
1092 return OC_STACK_ERROR;
1094 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1095 OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1098 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1099 return OC_STACK_NO_MEMORY;
1101 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1102 OCStackResult res = g_OTMDatas[selectedOxm].createSelectOxmPayloadCB(otmCtx,
1103 &secPayload->securityData, &secPayload->payloadSize);
1104 if (OC_STACK_OK != res && NULL == secPayload->securityData)
1106 OCPayloadDestroy((OCPayload *)secPayload);
1107 OIC_LOG(ERROR, TAG, "Error while converting bin to cbor");
1108 return OC_STACK_ERROR;
1111 OCCallbackData cbData;
1112 cbData.cb = &OwnerTransferModeHandler;
1113 cbData.context = (void *)otmCtx;
1115 res = OCDoResource(NULL, OC_REST_POST, query,
1116 &deviceInfo->endpoint, (OCPayload *)secPayload,
1117 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1118 if (res != OC_STACK_OK)
1120 OIC_LOG(ERROR, TAG, "OCStack resource error");
1123 OIC_LOG(DEBUG, TAG, "OUT PostOwnerTransferModeToResource");
1128 static OCStackResult GetProvisioningStatusResource(OTMContext_t* otmCtx)
1130 OIC_LOG(DEBUG, TAG, "IN GetProvisioningStatusResource");
1132 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1134 OIC_LOG(ERROR, TAG, "Invailed parameters");
1135 return OC_STACK_INVALID_PARAM;
1138 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1139 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1140 if(!PMGenerateQuery(false,
1141 deviceInfo->endpoint.addr, deviceInfo->endpoint.port,
1142 deviceInfo->connType,
1143 query, sizeof(query), OIC_RSRC_PSTAT_URI))
1145 OIC_LOG(ERROR, TAG, "GetProvisioningStatusResource : Failed to generate query");
1146 return OC_STACK_ERROR;
1148 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1150 OCCallbackData cbData;
1151 cbData.cb = &ListMethodsHandler;
1152 cbData.context = (void *)otmCtx;
1154 OCStackResult res = OCDoResource(NULL, OC_REST_GET, query, NULL, NULL,
1155 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1156 if (res != OC_STACK_OK)
1158 OIC_LOG(ERROR, TAG, "OCStack resource error");
1161 OIC_LOG(DEBUG, TAG, "OUT GetProvisioningStatusResource");
1166 static OCStackResult PostOwnerUuid(OTMContext_t* otmCtx)
1168 OIC_LOG(DEBUG, TAG, "IN PostOwnerUuid");
1170 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1172 OIC_LOG(ERROR, TAG, "Invailed parameters");
1173 return OC_STACK_INVALID_PARAM;
1176 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1177 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1178 if(!PMGenerateQuery(true,
1179 deviceInfo->endpoint.addr, deviceInfo->securePort,
1180 deviceInfo->connType,
1181 query, sizeof(query), OIC_RSRC_DOXM_URI))
1183 OIC_LOG(ERROR, TAG, "PostOwnerUuid : Failed to generate query");
1184 return OC_STACK_ERROR;
1186 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1188 //Post PT's uuid to new device
1189 OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1192 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1193 return OC_STACK_NO_MEMORY;
1195 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1196 OCStackResult res = g_OTMDatas[deviceInfo->doxm->oxmSel].createOwnerTransferPayloadCB(
1197 otmCtx, &secPayload->securityData, &secPayload->payloadSize);
1198 if (OC_STACK_OK != res && NULL == secPayload->securityData)
1200 OCPayloadDestroy((OCPayload *)secPayload);
1201 OIC_LOG(ERROR, TAG, "Error while converting doxm bin to cbor.");
1202 return OC_STACK_INVALID_PARAM;
1204 OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1206 OCCallbackData cbData;
1207 cbData.cb = &OwnerUuidUpdateHandler;
1208 cbData.context = (void *)otmCtx;
1211 res = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload *)secPayload,
1212 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1213 if (res != OC_STACK_OK)
1215 OIC_LOG(ERROR, TAG, "OCStack resource error");
1218 OIC_LOG(DEBUG, TAG, "OUT PostOwnerUuid");
1223 static OCStackResult PostOwnershipInformation(OTMContext_t* otmCtx)
1225 OIC_LOG(DEBUG, TAG, "IN PostOwnershipInformation");
1227 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1229 OIC_LOG(ERROR, TAG, "Invailed parameters");
1230 return OC_STACK_INVALID_PARAM;
1233 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1234 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1235 if(!PMGenerateQuery(true,
1236 deviceInfo->endpoint.addr, deviceInfo->securePort,
1237 deviceInfo->connType,
1238 query, sizeof(query), OIC_RSRC_DOXM_URI))
1240 OIC_LOG(ERROR, TAG, "PostOwnershipInformation : Failed to generate query");
1241 return OC_STACK_ERROR;
1243 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1245 //OwnershipInformationHandler
1246 OCSecurityPayload *secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1249 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1250 return OC_STACK_NO_MEMORY;
1253 otmCtx->selectedDeviceInfo->doxm->owned = true;
1255 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1256 OCStackResult res = DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm,
1257 &secPayload->securityData, &secPayload->payloadSize, true);
1258 if (OC_STACK_OK != res && NULL == secPayload->securityData)
1260 OCPayloadDestroy((OCPayload *)secPayload);
1261 OIC_LOG(ERROR, TAG, "Error while converting doxm bin to json");
1262 return OC_STACK_INVALID_PARAM;
1265 OCCallbackData cbData;
1266 cbData.cb = &OwnershipInformationHandler;
1267 cbData.context = (void *)otmCtx;
1270 res = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload*)secPayload,
1271 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1272 if (res != OC_STACK_OK)
1274 OIC_LOG(ERROR, TAG, "OCStack resource error");
1277 OIC_LOG(DEBUG, TAG, "OUT PostOwnershipInformation");
1282 static OCStackResult PostUpdateOperationMode(OTMContext_t* otmCtx)
1284 OIC_LOG(DEBUG, TAG, "IN PostUpdateOperationMode");
1286 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1288 return OC_STACK_INVALID_PARAM;
1291 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1292 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1293 if(!PMGenerateQuery(false,
1294 deviceInfo->endpoint.addr, deviceInfo->endpoint.port,
1295 deviceInfo->connType,
1296 query, sizeof(query), OIC_RSRC_PSTAT_URI))
1298 OIC_LOG(ERROR, TAG, "PostUpdateOperationMode : Failed to generate query");
1299 return OC_STACK_ERROR;
1301 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1303 OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1306 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1307 return OC_STACK_NO_MEMORY;
1309 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1310 OCStackResult res = PstatToCBORPayload(deviceInfo->pstat, &secPayload->securityData,
1311 &secPayload->payloadSize, true);
1312 if (OC_STACK_OK != res)
1314 OCPayloadDestroy((OCPayload *)secPayload);
1315 OIC_LOG(ERROR, TAG, "Error while converting pstat to cbor.");
1316 return OC_STACK_INVALID_PARAM;
1319 OCCallbackData cbData;
1320 cbData.cb = &OperationModeUpdateHandler;
1321 cbData.context = (void *)otmCtx;
1323 res = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload *)secPayload,
1324 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1325 if (res != OC_STACK_OK)
1327 OIC_LOG(ERROR, TAG, "OCStack resource error");
1330 OIC_LOG(DEBUG, TAG, "OUT PostUpdateOperationMode");
1335 static OCStackResult StartOwnershipTransfer(void* ctx, OCProvisionDev_t* selectedDevice)
1337 OIC_LOG(INFO, TAG, "IN StartOwnershipTransfer");
1338 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
1339 otmCtx->selectedDeviceInfo = selectedDevice;
1341 //Set to the lowest level OxM, and then find more higher level OxM.
1342 OCStackResult res = SelectProvisioningMethod(selectedDevice->doxm->oxm,
1343 selectedDevice->doxm->oxmLen,
1344 &selectedDevice->doxm->oxmSel);
1345 if(OC_STACK_OK != res)
1347 OIC_LOG(ERROR, TAG, "Failed to select the provisioning method");
1348 SetResult(otmCtx, res);
1351 OIC_LOG_V(DEBUG, TAG, "Selected provisoning method = %d", selectedDevice->doxm->oxmSel);
1353 //Send Req: POST /oic/sec/doxm [{..."OxmSel" :g_OTMDatas[Index of Selected OxM].OXMString,...}]
1354 res = PostOwnerTransferModeToResource(otmCtx);
1355 if(OC_STACK_OK != res)
1357 OIC_LOG(WARNING, TAG, "Failed to select the provisioning method");
1358 SetResult(otmCtx, res);
1362 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1363 //Register TLS event handler to catch the tls event while handshake
1364 if(CA_STATUS_OK != CAregisterSslHandshakeCallback(DTLSHandshakeCB))
1366 OIC_LOG(WARNING, TAG, "StartOwnershipTransfer : Failed to register TLS handshake callback.");
1368 #endif // __WITH_DTLS__ or __WITH_TLS__
1369 OIC_LOG(INFO, TAG, "OUT StartOwnershipTransfer");
1375 OCStackResult OTMSetOwnershipTransferCallbackData(OicSecOxm_t oxmType, OTMCallbackData_t* data)
1377 OIC_LOG(DEBUG, TAG, "IN OTMSetOwnerTransferCallbackData");
1381 OIC_LOG(ERROR, TAG, "OTMSetOwnershipTransferCallbackData : Invalid parameters");
1382 return OC_STACK_INVALID_PARAM;
1384 if(oxmType >= OIC_OXM_COUNT)
1386 OIC_LOG(INFO, TAG, "Unknow ownership transfer method");
1387 return OC_STACK_INVALID_PARAM;
1390 g_OTMDatas[oxmType].loadSecretCB= data->loadSecretCB;
1391 g_OTMDatas[oxmType].createSecureSessionCB = data->createSecureSessionCB;
1392 g_OTMDatas[oxmType].createSelectOxmPayloadCB = data->createSelectOxmPayloadCB;
1393 g_OTMDatas[oxmType].createOwnerTransferPayloadCB = data->createOwnerTransferPayloadCB;
1395 OIC_LOG(DEBUG, TAG, "OUT OTMSetOwnerTransferCallbackData");
1401 * NOTE : Unowned discovery should be done before performing OTMDoOwnershipTransfer
1403 OCStackResult OTMDoOwnershipTransfer(void* ctx,
1404 OCProvisionDev_t *selectedDevicelist,
1405 OCProvisionResultCB resultCallback)
1407 OIC_LOG(DEBUG, TAG, "IN OTMDoOwnershipTransfer");
1409 if (NULL == selectedDevicelist)
1411 return OC_STACK_INVALID_PARAM;
1413 if (NULL == resultCallback)
1415 return OC_STACK_INVALID_CALLBACK;
1418 OTMContext_t* otmCtx = (OTMContext_t*)OICCalloc(1,sizeof(OTMContext_t));
1421 OIC_LOG(ERROR, TAG, "Failed to create OTM Context");
1422 return OC_STACK_NO_MEMORY;
1424 otmCtx->ctxResultCallback = resultCallback;
1425 otmCtx->ctxHasError = false;
1426 otmCtx->userCtx = ctx;
1427 OCProvisionDev_t* pCurDev = selectedDevicelist;
1429 //Counting number of selected devices.
1430 otmCtx->ctxResultArraySize = 0;
1431 while(NULL != pCurDev)
1433 otmCtx->ctxResultArraySize++;
1434 pCurDev = pCurDev->next;
1437 otmCtx->ctxResultArray =
1438 (OCProvisionResult_t*)OICCalloc(otmCtx->ctxResultArraySize, sizeof(OCProvisionResult_t));
1439 if(NULL == otmCtx->ctxResultArray)
1441 OIC_LOG(ERROR, TAG, "OTMDoOwnershipTransfer : Failed to memory allocation");
1443 return OC_STACK_NO_MEMORY;
1445 pCurDev = selectedDevicelist;
1447 OCStackResult res = OC_STACK_OK;
1448 //Fill the device UUID for result array.
1449 for(size_t devIdx = 0; devIdx < otmCtx->ctxResultArraySize; devIdx++)
1451 //Checking duplication of Device ID.
1452 bool isDuplicate = true;
1453 res = PDMIsDuplicateDevice(&pCurDev->doxm->deviceID, &isDuplicate);
1454 if (OC_STACK_OK != res)
1460 bool isStale = false;
1461 res = PDMIsDeviceStale(&pCurDev->doxm->deviceID, &isStale);
1462 if(OC_STACK_OK != res)
1464 OIC_LOG(ERROR, TAG, "Internal error in PDMIsDeviceStale");
1469 OIC_LOG(INFO, TAG, "Detected duplicated UUID in stale status, "\
1470 "this UUID will be removed from PDM");
1472 res = PDMDeleteDevice(&pCurDev->doxm->deviceID);
1473 if(OC_STACK_OK != res)
1475 OIC_LOG(ERROR, TAG, "Internal error in PDMDeleteDevice");
1481 OIC_LOG(ERROR, TAG, "OTMDoOwnershipTransfer : Device UUID is duplicated");
1482 res = OC_STACK_INVALID_PARAM;
1486 memcpy(otmCtx->ctxResultArray[devIdx].deviceId.id,
1487 pCurDev->doxm->deviceID.id,
1489 otmCtx->ctxResultArray[devIdx].res = OC_STACK_CONTINUE;
1490 pCurDev = pCurDev->next;
1493 StartOwnershipTransfer(otmCtx, selectedDevicelist);
1495 OIC_LOG(DEBUG, TAG, "OUT OTMDoOwnershipTransfer");
1499 OICFree(otmCtx->ctxResultArray);
1504 OCStackResult PostProvisioningStatus(OTMContext_t* otmCtx)
1506 OIC_LOG(INFO, TAG, "IN PostProvisioningStatus");
1508 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1510 OIC_LOG(ERROR, TAG, "OTMContext is NULL");
1511 return OC_STACK_INVALID_PARAM;
1514 //Change the TAKE_OWNER bit of CM to 0.
1515 otmCtx->selectedDeviceInfo->pstat->cm &= (~TAKE_OWNER);
1517 OCSecurityPayload *secPayload = (OCSecurityPayload *)OICCalloc(1, sizeof(OCSecurityPayload));
1520 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1521 return OC_STACK_NO_MEMORY;
1523 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1524 if (OC_STACK_OK != PstatToCBORPayload(otmCtx->selectedDeviceInfo->pstat,
1525 &secPayload->securityData, &secPayload->payloadSize, true))
1527 OCPayloadDestroy((OCPayload *)secPayload);
1528 return OC_STACK_INVALID_JSON;
1530 OIC_LOG(DEBUG, TAG, "Created payload for chage to Provisiong state");
1531 OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1533 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1534 if(!PMGenerateQuery(true,
1535 otmCtx->selectedDeviceInfo->endpoint.addr,
1536 otmCtx->selectedDeviceInfo->securePort,
1537 otmCtx->selectedDeviceInfo->connType,
1538 query, sizeof(query), OIC_RSRC_PSTAT_URI))
1540 OIC_LOG(ERROR, TAG, "PostProvisioningStatus : Failed to generate query");
1541 return OC_STACK_ERROR;
1543 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1545 OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
1546 cbData.cb = &ProvisioningStatusHandler;
1547 cbData.context = (void*)otmCtx;
1549 OCStackResult ret = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload*)secPayload,
1550 otmCtx->selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1551 OIC_LOG_V(INFO, TAG, "OCDoResource returned: %d",ret);
1552 if (ret != OC_STACK_OK)
1554 OIC_LOG(ERROR, TAG, "OCStack resource error");
1557 OIC_LOG(INFO, TAG, "OUT PostProvisioningStatus");
1562 OCStackResult PostNormalOperationStatus(OTMContext_t* otmCtx)
1564 OIC_LOG(INFO, TAG, "IN PostNormalOperationStatus");
1566 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1568 OIC_LOG(ERROR, TAG, "OTMContext is NULL");
1569 return OC_STACK_INVALID_PARAM;
1573 otmCtx->selectedDeviceInfo->pstat->isOp = true;
1575 OCSecurityPayload *secPayload = (OCSecurityPayload *)OICCalloc(1, sizeof(OCSecurityPayload));
1578 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1579 return OC_STACK_NO_MEMORY;
1581 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1582 if (OC_STACK_OK != PstatToCBORPayload(otmCtx->selectedDeviceInfo->pstat,
1583 &secPayload->securityData, &secPayload->payloadSize, true))
1585 OCPayloadDestroy((OCPayload *)secPayload);
1586 return OC_STACK_INVALID_JSON;
1588 OIC_LOG(DEBUG, TAG, "Created payload for chage to Provisiong state");
1589 OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1591 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1592 if(!PMGenerateQuery(true,
1593 otmCtx->selectedDeviceInfo->endpoint.addr,
1594 otmCtx->selectedDeviceInfo->securePort,
1595 otmCtx->selectedDeviceInfo->connType,
1596 query, sizeof(query), OIC_RSRC_PSTAT_URI))
1598 OIC_LOG(ERROR, TAG, "PostNormalOperationStatus : Failed to generate query");
1599 return OC_STACK_ERROR;
1601 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1603 OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
1604 cbData.cb = &ReadyForNomalStatusHandler;
1605 cbData.context = (void*)otmCtx;
1607 OCStackResult ret = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload*)secPayload,
1608 otmCtx->selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1609 OIC_LOG_V(INFO, TAG, "OCDoResource returned: %d",ret);
1610 if (ret != OC_STACK_OK)
1612 OIC_LOG(ERROR, TAG, "OCStack resource error");
1615 OIC_LOG(INFO, TAG, "OUT PostNormalOperationStatus");