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"
64 #ifdef _ENABLE_MULTIPLE_OWNER_
65 #include "oxmrandompin.h"
66 #include "oxmpreconfpin.h"
67 #endif //_ENABLE_MULTIPLE_OWNER_
69 #include "pmutility.h"
70 #include "srmutility.h"
71 #include "provisioningdatabasemanager.h"
72 #include "oxmrandompin.h"
73 #include "ocpayload.h"
74 #include "payload_logging.h"
79 * Array to store the callbacks for each owner transfer method.
81 static OTMCallbackData_t g_OTMCbDatas[OIC_OXM_COUNT] = {
83 {.loadSecretCB = LoadSecretJustWorksCallback,
84 .createSecureSessionCB = CreateSecureSessionJustWorksCallback,
85 .createSelectOxmPayloadCB = CreateJustWorksSelectOxmPayload,
86 .createOwnerTransferPayloadCB = CreateJustWorksOwnerTransferPayload},
89 {.loadSecretCB = InputPinCodeCallback,
90 .createSecureSessionCB = CreateSecureSessionRandomPinCallback,
91 .createSelectOxmPayloadCB = CreatePinBasedSelectOxmPayload,
92 .createOwnerTransferPayloadCB = CreatePinBasedOwnerTransferPayload},
95 {.loadSecretCB = NULL,
96 .createSecureSessionCB = NULL,
97 .createSelectOxmPayloadCB = NULL,
98 .createOwnerTransferPayloadCB = NULL},
100 #ifdef _ENABLE_MULTIPLE_OWNER_
102 {.loadSecretCB = LoadPreconfPinCodeCallback,
103 .createSecureSessionCB = CreateSecureSessionPreconfPinCallback,
104 .createSelectOxmPayloadCB = CreatePreconfPinBasedSelectOxmPayload,
105 .createOwnerTransferPayloadCB = CreatePreconfPinBasedOwnerTransferPayload},
106 #endif //_ENABLE_MULTIPLE_OWNER_
110 * Variables for pointing the OTMContext to be used in the DTLS handshake result callback.
112 static OTMContext_t* g_otmCtx = NULL;
115 * Function to select appropriate provisioning method.
117 * @param[in] supportedMethods Array of supported methods
118 * @param[in] numberOfMethods number of supported methods
119 * @param[out] selectedMethod Selected methods
120 * @return OC_STACK_OK on success
122 static OCStackResult SelectProvisioningMethod(const OicSecOxm_t *supportedMethods,
123 size_t numberOfMethods, OicSecOxm_t *selectedMethod)
125 OIC_LOG(DEBUG, TAG, "IN SelectProvisioningMethod");
127 if(numberOfMethods == 0 || !supportedMethods)
129 OIC_LOG(WARNING, TAG, "Could not find a supported OxM.");
130 return OC_STACK_ERROR;
133 *selectedMethod = supportedMethods[0];
134 for(size_t i = 0; i < numberOfMethods; i++)
136 if(*selectedMethod < supportedMethods[i])
138 *selectedMethod = supportedMethods[i];
142 if(NULL == g_OTMCbDatas[(*selectedMethod)].loadSecretCB ||
143 NULL == g_OTMCbDatas[(*selectedMethod)].createSecureSessionCB ||
144 NULL == g_OTMCbDatas[(*selectedMethod)].createSelectOxmPayloadCB ||
145 NULL == g_OTMCbDatas[(*selectedMethod)].createOwnerTransferPayloadCB)
147 OIC_LOG_V(ERROR, TAG, "Please make sure the OxM(%d)'s callback registration", (int)(*selectedMethod));
148 return OC_STACK_INVALID_CALLBACK;
151 OIC_LOG(DEBUG, TAG, "OUT SelectProvisioningMethod");
157 * Function to select operation mode.This function will return most secure common operation mode.
159 * @param[in] selectedDeviceInfo selected device information to performing provisioning.
160 * @param[out] selectedMode selected operation mode
161 * @return OC_STACK_OK on success
163 static void SelectOperationMode(const OCProvisionDev_t *selectedDeviceInfo,
164 OicSecDpom_t *selectedMode)
166 OIC_LOG(DEBUG, TAG, "IN SelectOperationMode");
167 *selectedMode = selectedDeviceInfo->pstat->sm[0];
168 OIC_LOG_V(DEBUG, TAG, "Selected Operation Mode = %d", *selectedMode);
172 * Function to start ownership transfer.
173 * This function will send the first request for provisioning,
174 * The next request message is sent from the response handler for this request.
176 * @param[in] ctx context value passed to callback from calling function.
177 * @param[in] selectedDevice selected device information to performing provisioning.
178 * @return OC_STACK_OK on success
180 static OCStackResult StartOwnershipTransfer(void* ctx, OCProvisionDev_t* selectedDevice);
183 * Function to update owner transfer mode
185 * @param[in] otmCtx Context value of ownership transfer.
186 * @return OC_STACK_OK on success
188 static OCStackResult PostOwnerTransferModeToResource(OTMContext_t* otmCtx);
191 * Function to send request to resource to get its pstat resource information.
193 * @param[in] otmCtx Context value of ownership transfer.
194 * @return OC_STACK_OK on success
196 static OCStackResult GetProvisioningStatusResource(OTMContext_t* otmCtx);
200 * Function to send uuid of owner device to new device.
201 * This function would update 'owner of doxm' as UUID for provisioning tool.
203 * @param[in] otmCtx Context value of ownership transfer.
204 * @return OC_STACK_OK on success
206 static OCStackResult PostOwnerUuid(OTMContext_t* otmCtx);
209 * Function to update the operation mode. As per the spec. Operation mode in client driven
210 * single service provisioning it will be updated to 0x3
212 * @param[in] otmCtx Context value of ownership transfer.
213 * @return OC_STACK_OK on success
215 static OCStackResult PostUpdateOperationMode(OTMContext_t* otmCtx);
218 * Function to update the owner credential to new device
220 * @param[in] otmCtx Context value of ownership transfer.
221 * @param[in] selectedOperationMode selected operation mode
222 * @return OC_STACK_OK on success
224 static OCStackResult PostOwnerCredential(OTMContext_t* otmCtx);
227 * Function to update the owner ACL to new device.
229 * @param[in] otmCtx Context value of ownership transfer.
230 * @return OC_STACK_OK on success
232 static OCStackResult PostOwnerAcl(OTMContext_t* otmCtx);
235 * Function to send ownerShip info.
236 * This function would update 'owned of doxm' as true.
238 * @param[in] otmCtx Context value of ownership transfer.
239 * @return OC_STACK_OK on success
241 static OCStackResult PostOwnershipInformation(OTMContext_t* otmCtx);
244 * Function to update pstat as Ready for provisioning.
245 * This function would update 'cm' from bx0000,0010 to bx0000,0000.
247 * @param[in] ctx context value passed to callback from calling function.
248 * @param[in] selectedDevice selected device information to performing provisioning.
249 * @return OC_STACK_OK on success
251 static OCStackResult PostProvisioningStatus(OTMContext_t* otmCtx);
254 * Function to update pstat as Ready for Normal Operation.
255 * This function would update 'isop' from false to true.
257 * @param[in] ctx context value passed to callback from calling function.
258 * @param[in] selectedDevice selected device information to performing provisioning.
259 * @return OC_STACK_OK on success
261 static OCStackResult PostNormalOperationStatus(OTMContext_t* otmCtx);
263 static bool IsComplete(OTMContext_t* otmCtx)
265 for(size_t i = 0; i < otmCtx->ctxResultArraySize; i++)
267 if(OC_STACK_CONTINUE == otmCtx->ctxResultArray[i].res)
277 * Function to save the result of provisioning.
279 * @param[in,out] otmCtx Context value of ownership transfer.
280 * @param[in] res result of provisioning
282 static void SetResult(OTMContext_t* otmCtx, const OCStackResult res)
284 OIC_LOG_V(DEBUG, TAG, "IN SetResult : %d ", res);
288 OIC_LOG(WARNING, TAG, "OTMContext is NULL");
292 if(otmCtx->selectedDeviceInfo)
294 //Revert psk_info callback and new deivce uuid in case of random PIN OxM
295 if(OIC_RANDOM_DEVICE_PIN == otmCtx->selectedDeviceInfo->doxm->oxmSel)
297 if(CA_STATUS_OK != CAregisterPskCredentialsHandler(GetDtlsPskCredentials))
299 OIC_LOG(WARNING, TAG, "Failed to revert is DTLS credential handler.");
301 OicUuid_t emptyUuid = { .id={0}};
302 SetUuidForPinBasedOxm(&emptyUuid);
305 for(size_t i = 0; i < otmCtx->ctxResultArraySize; i++)
307 if(memcmp(otmCtx->selectedDeviceInfo->doxm->deviceID.id,
308 otmCtx->ctxResultArray[i].deviceId.id, UUID_LENGTH) == 0)
310 otmCtx->ctxResultArray[i].res = res;
311 if(OC_STACK_OK != res)
313 otmCtx->ctxHasError = true;
320 //If all request is completed, invoke the user callback.
321 if(IsComplete(otmCtx))
323 otmCtx->ctxResultCallback(otmCtx->userCtx, otmCtx->ctxResultArraySize,
324 otmCtx->ctxResultArray, otmCtx->ctxHasError);
325 OICFree(otmCtx->ctxResultArray);
330 if(OC_STACK_OK != StartOwnershipTransfer(otmCtx,
331 otmCtx->selectedDeviceInfo->next))
333 OIC_LOG(ERROR, TAG, "Failed to StartOwnershipTransfer");
338 OIC_LOG(DEBUG, TAG, "OUT SetResult");
342 * Function to handle the handshake result in OTM.
343 * This function will be invoked after DTLS handshake
344 * @param endPoint [IN] The remote endpoint.
345 * @param errorInfo [IN] Error information from the endpoint.
348 void DTLSHandshakeCB(const CAEndpoint_t *endpoint, const CAErrorInfo_t *info)
350 if(NULL != g_otmCtx && NULL != g_otmCtx->selectedDeviceInfo &&
351 NULL != endpoint && NULL != info)
353 OIC_LOG_V(INFO, TAG, "Received status from remote device(%s:%d) : %d",
354 endpoint->addr, endpoint->port, info->result);
356 OicSecDoxm_t* newDevDoxm = g_otmCtx->selectedDeviceInfo->doxm;
358 if(NULL != newDevDoxm)
360 OicUuid_t emptyUuid = {.id={0}};
362 //Make sure the address matches.
363 if(strncmp(g_otmCtx->selectedDeviceInfo->endpoint.addr,
365 sizeof(endpoint->addr)) == 0 &&
366 g_otmCtx->selectedDeviceInfo->securePort == endpoint->port)
368 OCStackResult res = OC_STACK_ERROR;
370 //If temporal secure sesstion established successfully
371 if(CA_STATUS_OK == info->result &&
372 false == newDevDoxm->owned &&
373 memcmp(&(newDevDoxm->owner), &emptyUuid, sizeof(OicUuid_t)) == 0)
375 //Send request : POST /oic/sec/doxm [{... , "devowner":"PT's UUID"}]
376 res = PostOwnerUuid(g_otmCtx);
377 if(OC_STACK_OK != res)
379 OIC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to send owner information");
380 SetResult(g_otmCtx, res);
383 //In case of authentication failure
384 else if(CA_DTLS_AUTHENTICATION_FAILURE == info->result)
386 //in case of error from owner credential
387 if(memcmp(&(newDevDoxm->owner), &emptyUuid, sizeof(OicUuid_t)) != 0 &&
388 true == newDevDoxm->owned)
390 OIC_LOG(ERROR, TAG, "The owner credential may incorrect.");
392 if(OC_STACK_OK != RemoveCredential(&(newDevDoxm->deviceID)))
394 OIC_LOG(WARNING, TAG, "Failed to remove the invaild owner credential");
396 SetResult(g_otmCtx, OC_STACK_AUTHENTICATION_FAILURE);
398 //in case of error from wrong PIN, re-start the ownership transfer
399 else if(OIC_RANDOM_DEVICE_PIN == newDevDoxm->oxmSel)
401 OIC_LOG(ERROR, TAG, "The PIN number may incorrect.");
403 memcpy(&(newDevDoxm->owner), &emptyUuid, sizeof(OicUuid_t));
404 newDevDoxm->owned = false;
405 g_otmCtx->attemptCnt++;
407 if(WRONG_PIN_MAX_ATTEMP > g_otmCtx->attemptCnt)
409 res = StartOwnershipTransfer(g_otmCtx, g_otmCtx->selectedDeviceInfo);
410 if(OC_STACK_OK != res)
412 SetResult(g_otmCtx, res);
413 OIC_LOG(ERROR, TAG, "Failed to Re-StartOwnershipTransfer");
418 OIC_LOG(ERROR, TAG, "User has exceeded the number of authentication attempts.");
419 SetResult(g_otmCtx, OC_STACK_AUTHENTICATION_FAILURE);
424 OIC_LOG(ERROR, TAG, "Failed to establish secure session.");
425 SetResult(g_otmCtx, OC_STACK_AUTHENTICATION_FAILURE);
434 * Function to save the Owner/SubOwner PSK.
436 * @param[in] selectedDeviceInfo selected device information to performing provisioning.
437 * @return OC_STACK_OK on success
439 static OCStackResult SaveOwnerPSK(OCProvisionDev_t *selectedDeviceInfo)
441 OIC_LOG(DEBUG, TAG, "IN SaveOwnerPSK");
443 OCStackResult res = OC_STACK_ERROR;
445 CAEndpoint_t endpoint;
446 memset(&endpoint, 0x00, sizeof(CAEndpoint_t));
447 OICStrcpy(endpoint.addr, MAX_ADDR_STR_SIZE_CA, selectedDeviceInfo->endpoint.addr);
448 endpoint.addr[MAX_ADDR_STR_SIZE_CA - 1] = '\0';
449 endpoint.port = selectedDeviceInfo->securePort;
450 endpoint.adapter = selectedDeviceInfo->endpoint.adapter;
452 OicUuid_t ownerDeviceID = {.id={0}};
453 if (OC_STACK_OK != GetDoxmDeviceID(&ownerDeviceID))
455 OIC_LOG(ERROR, TAG, "Error while retrieving Owner's device ID");
459 uint8_t ownerPSK[OWNER_PSK_LENGTH_128] = {0};
460 OicSecKey_t ownerKey = {ownerPSK, OWNER_PSK_LENGTH_128};
462 //Generating OwnerPSK
463 CAResult_t pskRet = CAGenerateOwnerPSK(&endpoint,
464 (uint8_t *)GetOxmString(selectedDeviceInfo->doxm->oxmSel),
465 strlen(GetOxmString(selectedDeviceInfo->doxm->oxmSel)),
466 ownerDeviceID.id, sizeof(ownerDeviceID.id),
467 selectedDeviceInfo->doxm->deviceID.id, sizeof(selectedDeviceInfo->doxm->deviceID.id),
468 ownerPSK, OWNER_PSK_LENGTH_128);
470 if (CA_STATUS_OK == pskRet)
472 OIC_LOG(INFO, TAG,"Owner PSK dump:\n");
473 OIC_LOG_BUFFER(INFO, TAG,ownerPSK, OWNER_PSK_LENGTH_128);
474 //Generating new credential for provisioning tool
475 OicSecCred_t *cred = GenerateCredential(&selectedDeviceInfo->doxm->deviceID,
476 SYMMETRIC_PAIR_WISE_KEY, NULL,
477 &ownerKey, &ownerDeviceID, NULL);
478 VERIFY_NON_NULL(TAG, cred, ERROR);
480 // TODO: Added as workaround. Will be replaced soon.
481 cred->privateData.encoding = OIC_ENCODING_RAW;
484 // NOTE: Test codes to use BASE64 encoded owner PSK.
485 uint32_t outSize = 0;
486 size_t b64BufSize = B64ENCODE_OUT_SAFESIZE((OWNER_PSK_LENGTH_128 + 1));
487 char* b64Buf = (uint8_t *)OICCalloc(1, b64BufSize);
488 VERIFY_NON_NULL(TAG, b64Buf, ERROR);
489 b64Encode(cred->privateData.data, cred->privateData.len, b64Buf, b64BufSize, &outSize);
491 OICFree( cred->privateData.data );
492 cred->privateData.data = (uint8_t *)OICCalloc(1, outSize + 1);
493 VERIFY_NON_NULL(TAG, cred->privateData.data, ERROR);
495 strncpy(cred->privateData.data, b64Buf, outSize);
496 cred->privateData.data[outSize] = '\0';
497 cred->privateData.encoding = OIC_ENCODING_BASE64;
498 cred->privateData.len = outSize;
500 #endif //End of Test codes
502 //Finding previous ownerPSK.
503 const OicSecCred_t* credList = GetCredList();
504 OicSecCred_t* prevCred = NULL;
506 LL_FOREACH(credList, prevCred)
508 //OwnerPSK's type is SYMMETRIC_PAIR_WISE_KEY
509 if (SYMMETRIC_PAIR_WISE_KEY == prevCred->credType &&
510 0 == memcmp(prevCred->subject.id, cred->subject.id, sizeof(cred->subject.id)))
512 credId = prevCred->credId;
517 //If duplicate owner PSK is exists, remove it.
520 OIC_LOG(WARNING, TAG, "Duplicate OwnerPSK was detected.");
521 OIC_LOG(WARNING, TAG, "[Subject] : ");
522 OIC_LOG_BUFFER(WARNING, TAG, prevCred->subject.id, sizeof(prevCred->subject.id));
523 OIC_LOG_V(WARNING, TAG, "[Encoding Type] : %d", prevCred->privateData.encoding);
524 OIC_LOG(WARNING, TAG, "[Private Data] : ");
525 OIC_LOG_BUFFER(WARNING, TAG, prevCred->privateData.data, prevCred->privateData.len);
526 OIC_LOG(WARNING, TAG, "Previous OwnerPSK will be removed.");
528 res = RemoveCredentialByCredId(credId);
529 if(OC_STACK_RESOURCE_DELETED != res)
531 OIC_LOG(ERROR, TAG, "Failed to remove the previous OwnerPSK");
532 DeleteCredList(cred);
537 res = AddCredential(cred);
538 if(res != OC_STACK_OK)
540 DeleteCredList(cred);
546 OIC_LOG(ERROR, TAG, "CAGenerateOwnerPSK failed");
549 OIC_LOG(DEBUG, TAG, "OUT SaveOwnerPSK");
555 * Callback handler for OwnerShipTransferModeHandler API.
557 * @param[in] ctx ctx value passed to callback from calling function.
558 * @param[in] UNUSED handle to an invocation
559 * @param[in] clientResponse Response from queries to remote servers.
560 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
561 * and OC_STACK_KEEP_TRANSACTION to keep it.
563 static OCStackApplicationResult OwnerTransferModeHandler(void *ctx, OCDoHandle UNUSED,
564 OCClientResponse *clientResponse)
566 OIC_LOG(DEBUG, TAG, "IN OwnerTransferModeHandler");
568 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
569 VERIFY_NON_NULL(TAG, ctx, WARNING);
571 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
573 if (OC_STACK_RESOURCE_CHANGED == clientResponse->result)
575 OIC_LOG(INFO, TAG, "OwnerTransferModeHandler : response result = OC_STACK_OK");
576 //Send request : GET /oic/sec/pstat
577 OCStackResult res = GetProvisioningStatusResource(otmCtx);
578 if(OC_STACK_OK != res)
580 OIC_LOG(WARNING, TAG, "Failed to get pstat information");
581 SetResult(otmCtx, res);
586 OIC_LOG_V(WARNING, TAG, "OwnerTransferModeHandler : Client response is incorrect : %d",
587 clientResponse->result);
588 SetResult(otmCtx, clientResponse->result);
591 OIC_LOG(DEBUG, TAG, "OUT OwnerTransferModeHandler");
594 return OC_STACK_DELETE_TRANSACTION;
598 * Callback handler for ProvisioningStatusResouceHandler API.
600 * @param[in] ctx ctx value passed to callback from calling function.
601 * @param[in] UNUSED handle to an invocation
602 * @param[in] clientResponse Response from queries to remote servers.
603 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
604 * and OC_STACK_KEEP_TRANSACTION to keep it.
606 static OCStackApplicationResult ListMethodsHandler(void *ctx, OCDoHandle UNUSED,
607 OCClientResponse *clientResponse)
609 OIC_LOG(DEBUG, TAG, "IN ListMethodsHandler");
611 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
612 VERIFY_NON_NULL(TAG, ctx, WARNING);
614 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
616 if (OC_STACK_OK == clientResponse->result)
618 if (NULL == clientResponse->payload)
620 OIC_LOG(INFO, TAG, "Skiping Null payload");
621 SetResult(otmCtx, OC_STACK_ERROR);
622 return OC_STACK_DELETE_TRANSACTION;
625 if (PAYLOAD_TYPE_SECURITY != clientResponse->payload->type)
627 OIC_LOG(INFO, TAG, "Unknown payload type");
628 SetResult(otmCtx, OC_STACK_ERROR);
629 return OC_STACK_DELETE_TRANSACTION;
631 OicSecPstat_t* pstat = NULL;
632 OCStackResult result = CBORPayloadToPstat(
633 ((OCSecurityPayload*)clientResponse->payload)->securityData,
634 ((OCSecurityPayload*)clientResponse->payload)->payloadSize,
636 if(NULL == pstat || result != OC_STACK_OK)
638 OIC_LOG(ERROR, TAG, "Error while converting cbor to pstat.");
639 SetResult(otmCtx, OC_STACK_ERROR);
640 return OC_STACK_DELETE_TRANSACTION;
642 if(false == (TAKE_OWNER & pstat->cm))
644 OIC_LOG(ERROR, TAG, "Device pairing mode enabling owner transfer operations is disabled");
645 SetResult(otmCtx, OC_STACK_ERROR);
646 return OC_STACK_DELETE_TRANSACTION;
648 otmCtx->selectedDeviceInfo->pstat = pstat;
650 //Select operation mode (Currently supported SINGLE_SERVICE_CLIENT_DRIVEN only)
651 SelectOperationMode(otmCtx->selectedDeviceInfo, &(otmCtx->selectedDeviceInfo->pstat->om));
653 //Send request : POST /oic/sec/pstat [{"om":"bx11", .. }]
654 OCStackResult res = PostUpdateOperationMode(otmCtx);
655 if (OC_STACK_OK != res)
657 OIC_LOG(ERROR, TAG, "Error while updating operation mode.");
658 SetResult(otmCtx, res);
663 OIC_LOG_V(WARNING, TAG, "ListMethodsHandler : Client response is incorrect : %d",
664 clientResponse->result);
665 SetResult(otmCtx, clientResponse->result);
668 OIC_LOG(DEBUG, TAG, "OUT ListMethodsHandler");
670 return OC_STACK_DELETE_TRANSACTION;
674 * Response handler for update owner uuid request.
676 * @param[in] ctx ctx value passed to callback from calling function.
677 * @param[in] UNUSED handle to an invocation
678 * @param[in] clientResponse Response from queries to remote servers.
679 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
680 * and OC_STACK_KEEP_TRANSACTION to keep it.
682 static OCStackApplicationResult OwnerUuidUpdateHandler(void *ctx, OCDoHandle UNUSED,
683 OCClientResponse *clientResponse)
685 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
686 VERIFY_NON_NULL(TAG, ctx, WARNING);
688 OIC_LOG(DEBUG, TAG, "IN OwnerUuidUpdateHandler");
690 OCStackResult res = OC_STACK_OK;
691 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
693 if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
695 if(otmCtx && otmCtx->selectedDeviceInfo)
697 res = SaveOwnerPSK(otmCtx->selectedDeviceInfo);
698 if(OC_STACK_OK != res)
700 OIC_LOG(ERROR, TAG, "OwnerUuidUpdateHandler:Failed to owner PSK generation");
701 SetResult(otmCtx, res);
702 return OC_STACK_DELETE_TRANSACTION;
705 //POST owner credential to new device according to security spec B.
706 res = PostOwnerCredential(otmCtx);
707 if(OC_STACK_OK != res)
710 "OwnerUuidUpdateHandler:Failed to send PosT request for onwer credential");
711 SetResult(otmCtx, res);
712 return OC_STACK_DELETE_TRANSACTION;
718 res = clientResponse->result;
719 OIC_LOG_V(ERROR, TAG, "OwnerUuidHandler : Unexpected result %d", res);
720 SetResult(otmCtx, res);
723 OIC_LOG(DEBUG, TAG, "OUT OwnerUuidUpdateHandler");
726 return OC_STACK_DELETE_TRANSACTION;
730 * Response handler for update operation mode.
732 * @param[in] ctx ctx value passed to callback from calling function.
733 * @param[in] UNUSED handle to an invocation
734 * @param[in] clientResponse Response from queries to remote servers.
735 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
736 * and OC_STACK_KEEP_TRANSACTION to keep it.
738 static OCStackApplicationResult OperationModeUpdateHandler(void *ctx, OCDoHandle UNUSED,
739 OCClientResponse *clientResponse)
741 OIC_LOG(DEBUG, TAG, "IN OperationModeUpdateHandler");
743 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
744 VERIFY_NON_NULL(TAG, ctx, WARNING);
746 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
748 if (OC_STACK_RESOURCE_CHANGED == clientResponse->result)
750 OCStackResult res = OC_STACK_ERROR;
751 OicSecOxm_t selOxm = otmCtx->selectedDeviceInfo->doxm->oxmSel;
754 //Load secret for temporal secure session.
755 if(g_OTMCbDatas[selOxm].loadSecretCB)
757 res = g_OTMCbDatas[selOxm].loadSecretCB(otmCtx);
758 if(OC_STACK_OK != res)
760 OIC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to load secret");
761 SetResult(otmCtx, res);
762 return OC_STACK_DELETE_TRANSACTION;
766 //It will be used in handshake event handler
769 //Try DTLS handshake to generate secure session
770 if(g_OTMCbDatas[selOxm].createSecureSessionCB)
772 res = g_OTMCbDatas[selOxm].createSecureSessionCB(otmCtx);
773 if(OC_STACK_OK != res)
775 OIC_LOG(ERROR, TAG, "OperationModeUpdate : Failed to create DTLS session");
776 SetResult(otmCtx, res);
777 return OC_STACK_DELETE_TRANSACTION;
783 OIC_LOG(ERROR, TAG, "Error while update operation mode");
784 SetResult(otmCtx, clientResponse->result);
787 OIC_LOG(DEBUG, TAG, "OUT OperationModeUpdateHandler");
790 return OC_STACK_DELETE_TRANSACTION;
794 * Response handler for update owner crendetial request.
796 * @param[in] ctx ctx value passed to callback from calling function.
797 * @param[in] UNUSED handle to an invocation
798 * @param[in] clientResponse Response from queries to remote servers.
799 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
800 * and OC_STACK_KEEP_TRANSACTION to keep it.
802 static OCStackApplicationResult OwnerCredentialHandler(void *ctx, OCDoHandle UNUSED,
803 OCClientResponse *clientResponse)
805 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
806 VERIFY_NON_NULL(TAG, ctx, WARNING);
808 OIC_LOG(DEBUG, TAG, "IN OwnerCredentialHandler");
810 OCStackResult res = OC_STACK_OK;
811 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
813 if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
815 if(otmCtx && otmCtx->selectedDeviceInfo)
817 //Close the temporal secure session to verify the owner credential
818 CAEndpoint_t* endpoint = (CAEndpoint_t *)&otmCtx->selectedDeviceInfo->endpoint;
819 endpoint->port = otmCtx->selectedDeviceInfo->securePort;
820 CAResult_t caResult = CA_STATUS_OK;
821 caResult = CAcloseSslConnection(endpoint);
823 if(CA_STATUS_OK != caResult)
825 OIC_LOG(ERROR, TAG, "Failed to close DTLS session");
826 SetResult(otmCtx, caResult);
827 return OC_STACK_DELETE_TRANSACTION;
831 * If we select NULL cipher,
832 * client will select appropriate cipher suite according to server's cipher-suite list.
834 // TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256 = 0xC037, /**< see RFC 5489 */
835 caResult = CASelectCipherSuite(0xC037, endpoint->adapter);
837 if(CA_STATUS_OK != caResult)
839 OIC_LOG(ERROR, TAG, "Failed to select TLS_NULL_WITH_NULL_NULL");
840 SetResult(otmCtx, caResult);
841 return OC_STACK_DELETE_TRANSACTION;
845 * in case of random PIN based OxM,
846 * revert get_psk_info callback of tinyDTLS to use owner credential.
848 if(OIC_RANDOM_DEVICE_PIN == otmCtx->selectedDeviceInfo->doxm->oxmSel)
850 OicUuid_t emptyUuid = { .id={0}};
851 SetUuidForPinBasedOxm(&emptyUuid);
853 caResult = CAregisterPskCredentialsHandler(GetDtlsPskCredentials);
855 if(CA_STATUS_OK != caResult)
857 OIC_LOG(ERROR, TAG, "Failed to revert DTLS credential handler.");
858 SetResult(otmCtx, OC_STACK_INVALID_CALLBACK);
859 return OC_STACK_DELETE_TRANSACTION;
863 otmCtx->selectedDeviceInfo->connType |= CT_FLAG_SECURE;
865 res = PostOwnerAcl(otmCtx);
866 if(OC_STACK_OK != res)
868 OIC_LOG(ERROR, TAG, "Failed to update owner ACL to new device");
869 SetResult(otmCtx, res);
870 return OC_STACK_DELETE_TRANSACTION;
876 res = clientResponse->result;
877 OIC_LOG_V(ERROR, TAG, "OwnerCredentialHandler : Unexpected result %d", res);
878 SetResult(otmCtx, res);
881 OIC_LOG(DEBUG, TAG, "OUT OwnerCredentialHandler");
884 return OC_STACK_DELETE_TRANSACTION;
888 * Response handler for update owner ACL request.
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 OwnerAclHandler(void *ctx, OCDoHandle UNUSED,
897 OCClientResponse *clientResponse)
899 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
900 VERIFY_NON_NULL(TAG, ctx, WARNING);
902 OIC_LOG(DEBUG, TAG, "IN OwnerAclHandler");
904 OCStackResult res = OC_STACK_OK;
905 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
907 if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
909 if(otmCtx && otmCtx->selectedDeviceInfo)
911 //POST /oic/sec/doxm [{ ..., "owned":"TRUE" }]
912 res = PostOwnershipInformation(otmCtx);
913 if(OC_STACK_OK != res)
915 OIC_LOG(ERROR, TAG, "Failed to update ownership information to new device");
916 SetResult(otmCtx, res);
922 res = clientResponse->result;
923 OIC_LOG_V(ERROR, TAG, "OwnerAclHandler : Unexpected result %d", res);
924 SetResult(otmCtx, res);
927 OIC_LOG(DEBUG, TAG, "OUT OwnerAclHandler");
930 return OC_STACK_DELETE_TRANSACTION;
935 * Response handler for update owner information request.
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 OwnershipInformationHandler(void *ctx, OCDoHandle UNUSED,
944 OCClientResponse *clientResponse)
946 VERIFY_NON_NULL(TAG, clientResponse, WARNING);
947 VERIFY_NON_NULL(TAG, ctx, WARNING);
949 OIC_LOG(DEBUG, TAG, "IN OwnershipInformationHandler");
951 OCStackResult res = OC_STACK_OK;
952 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
954 if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
956 if(otmCtx && otmCtx->selectedDeviceInfo)
958 OIC_LOG(INFO, TAG, "Ownership transfer was successfully completed.");
959 OIC_LOG(INFO, TAG, "Set Ready for provisioning state .");
961 res = PostProvisioningStatus(otmCtx);
962 if(OC_STACK_OK != res)
964 OIC_LOG(ERROR, TAG, "Failed to update pstat");
965 SetResult(otmCtx, res);
971 res = clientResponse->result;
972 OIC_LOG_V(ERROR, TAG, "OwnershipInformationHandler : Unexpected result %d", res);
973 SetResult(otmCtx, res);
976 OIC_LOG(DEBUG, TAG, "OUT OwnershipInformationHandler");
979 return OC_STACK_DELETE_TRANSACTION;
983 * Response handler of update provisioning status.
985 * @param[in] ctx ctx value passed to callback from calling function.
986 * @param[in] UNUSED handle to an invocation
987 * @param[in] clientResponse Response from queries to remote servers.
988 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
989 * and OC_STACK_KEEP_TRANSACTION to keep it.
991 static OCStackApplicationResult ProvisioningStatusHandler(void *ctx, OCDoHandle UNUSED,
992 OCClientResponse *clientResponse)
994 OIC_LOG_V(INFO, TAG, "IN ProvisioningStatusHandler.");
996 VERIFY_NON_NULL(TAG, clientResponse, ERROR);
997 VERIFY_NON_NULL(TAG, ctx, ERROR);
999 OTMContext_t* otmCtx = (OTMContext_t*) ctx;
1001 OCStackResult res = OC_STACK_OK;
1003 if(OC_STACK_RESOURCE_CHANGED == clientResponse->result)
1005 if(otmCtx && otmCtx->selectedDeviceInfo)
1007 OIC_LOG(INFO, TAG, "Device state is in Ready for Provisionig.");
1009 res = PostNormalOperationStatus(otmCtx);
1010 if(OC_STACK_OK != res)
1012 OIC_LOG(ERROR, TAG, "Failed to update pstat");
1013 SetResult(otmCtx, res);
1019 OIC_LOG_V(INFO, TAG, "Error occured in provisionDefaultACLCB :: %d\n",
1020 clientResponse->result);
1021 SetResult(otmCtx, clientResponse->result);
1025 OIC_LOG_V(INFO, TAG, "OUT ProvisioningStatusHandler.");
1026 return OC_STACK_DELETE_TRANSACTION;
1030 * Response handler of update provisioning status to Ready for Normal..
1032 * @param[in] ctx ctx value passed to callback from calling function.
1033 * @param[in] UNUSED handle to an invocation
1034 * @param[in] clientResponse Response from queries to remote servers.
1035 * @return OC_STACK_DELETE_TRANSACTION to delete the transaction
1036 * and OC_STACK_KEEP_TRANSACTION to keep it.
1038 static OCStackApplicationResult ReadyForNomalStatusHandler(void *ctx, OCDoHandle UNUSED,
1039 OCClientResponse *clientResponse)
1041 OIC_LOG_V(INFO, TAG, "IN ReadyForNomalStatusHandler.");
1043 VERIFY_NON_NULL(TAG, clientResponse, ERROR);
1044 VERIFY_NON_NULL(TAG, ctx, ERROR);
1046 OTMContext_t* otmCtx = (OTMContext_t*) ctx;
1049 if (OC_STACK_RESOURCE_CHANGED == clientResponse->result)
1051 OIC_LOG(INFO, TAG, "Device state is in Ready for Normal Operation.");
1052 OCStackResult res = PDMAddDevice(&otmCtx->selectedDeviceInfo->doxm->deviceID);
1053 if (OC_STACK_OK == res)
1055 OIC_LOG_V(INFO, TAG, "Add device's UUID in PDM_DB");
1056 SetResult(otmCtx, OC_STACK_OK);
1057 return OC_STACK_DELETE_TRANSACTION;
1061 OIC_LOG(ERROR, TAG, "Ownership transfer is complete but adding information to DB is failed.");
1066 OIC_LOG_V(INFO, TAG, "Error occured in provisionDefaultACLCB :: %d\n",
1067 clientResponse->result);
1068 SetResult(otmCtx, clientResponse->result);
1072 OIC_LOG_V(INFO, TAG, "OUT ReadyForNomalStatusHandler.");
1073 return OC_STACK_DELETE_TRANSACTION;
1076 static OCStackResult PostOwnerCredential(OTMContext_t* otmCtx)
1078 OIC_LOG(DEBUG, TAG, "IN PostOwnerCredential");
1080 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1082 OIC_LOG(ERROR, TAG, "Invalid parameters");
1083 return OC_STACK_INVALID_PARAM;
1086 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1087 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1089 if(!PMGenerateQuery(true,
1090 deviceInfo->endpoint.addr, deviceInfo->securePort,
1091 deviceInfo->connType,
1092 query, sizeof(query), OIC_RSRC_CRED_URI))
1094 OIC_LOG(ERROR, TAG, "PostOwnerCredential : Failed to generate query");
1095 return OC_STACK_ERROR;
1097 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1098 OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1101 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1102 return OC_STACK_NO_MEMORY;
1105 //Generate owner credential for new device
1106 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1107 const OicSecCred_t* ownerCredential = GetCredResourceData(&(deviceInfo->doxm->deviceID));
1108 if(!ownerCredential)
1110 OIC_LOG(ERROR, TAG, "Can not find OwnerPSK.");
1111 return OC_STACK_NO_RESOURCE;
1114 OicUuid_t credSubjectId = {.id={0}};
1115 if(OC_STACK_OK == GetDoxmDeviceID(&credSubjectId))
1117 OicSecCred_t newCredential;
1118 memcpy(&newCredential, ownerCredential, sizeof(OicSecCred_t));
1119 newCredential.next = NULL;
1121 //Set subject ID as PT's ID
1122 memcpy(&(newCredential.subject), &credSubjectId, sizeof(OicUuid_t));
1124 //Fill private data as empty string
1125 newCredential.privateData.data = "";
1126 newCredential.privateData.len = 0;
1127 newCredential.privateData.encoding = ownerCredential->privateData.encoding;
1129 newCredential.publicData.data = NULL;
1130 newCredential.publicData.len = 0;
1133 //Send owner credential to new device : POST /oic/sec/cred [ owner credential ]
1134 if (OC_STACK_OK != CredToCBORPayload(&newCredential, &secPayload->securityData,
1135 &secPayload->payloadSize, secureFlag))
1137 OICFree(secPayload);
1138 OIC_LOG(ERROR, TAG, "Error while converting bin to cbor.");
1139 return OC_STACK_ERROR;
1141 OIC_LOG(DEBUG, TAG, "Cred Payload:");
1142 OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1144 OCCallbackData cbData;
1145 cbData.cb = &OwnerCredentialHandler;
1146 cbData.context = (void *)otmCtx;
1148 OCStackResult res = OCDoResource(NULL, OC_REST_POST, query,
1149 &deviceInfo->endpoint, (OCPayload*)secPayload,
1150 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1151 if (res != OC_STACK_OK)
1153 OIC_LOG(ERROR, TAG, "OCStack resource error");
1158 OIC_LOG(ERROR, TAG, "Failed to read DOXM device ID.");
1159 return OC_STACK_NO_RESOURCE;
1162 OIC_LOG(DEBUG, TAG, "OUT PostOwnerCredential");
1167 static OicSecAcl_t* GenerateOwnerAcl(const OicUuid_t* owner)
1169 OicSecAcl_t* ownerAcl = (OicSecAcl_t*)OICCalloc(1, sizeof(OicSecAcl_t));
1170 OicSecAce_t* ownerAce = (OicSecAce_t*)OICCalloc(1, sizeof(OicSecAce_t));
1171 OicSecRsrc_t* wildcardRsrc = (OicSecRsrc_t*)OICCalloc(1, sizeof(OicSecRsrc_t));
1172 if(NULL == ownerAcl || NULL == ownerAce || NULL == wildcardRsrc)
1174 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1177 LL_APPEND(ownerAcl->aces, ownerAce);
1178 LL_APPEND(ownerAce->resources, wildcardRsrc);
1180 //Set resource owner as PT
1181 memcpy(ownerAcl->rownerID.id, owner->id, sizeof(owner->id));
1183 //PT has full permission.
1184 ownerAce->permission = PERMISSION_FULL_CONTROL;
1186 //Set subject as PT's UUID
1187 memcpy(ownerAce->subjectuuid.id, owner->id, sizeof(owner->id));
1189 wildcardRsrc->href = OICStrdup(WILDCARD_RESOURCE_URI);
1190 if(NULL == wildcardRsrc->href)
1195 wildcardRsrc->interfaceLen = 1;
1196 wildcardRsrc->interfaces = (char**)OICMalloc(wildcardRsrc->interfaceLen * sizeof(char*));
1197 if(NULL == wildcardRsrc->interfaces)
1201 wildcardRsrc->interfaces[0] = OICStrdup(WILDCARD_RESOURCE_URI);
1202 if(NULL == wildcardRsrc->interfaces[0])
1207 wildcardRsrc->typeLen = 1;
1208 wildcardRsrc->types = (char**)OICMalloc(wildcardRsrc->typeLen * sizeof(char*));
1209 if(NULL == wildcardRsrc->types)
1213 wildcardRsrc->types[0] = OICStrdup(WILDCARD_RESOURCE_URI);
1214 if(NULL == wildcardRsrc->types[0])
1222 //in case of memory allocation failed, each resource should be removed individually.
1223 if(NULL == ownerAcl || NULL == ownerAce || NULL == wildcardRsrc)
1227 OICFree(wildcardRsrc);
1231 DeleteACLList(ownerAcl);
1237 * Function to update the owner ACL to new device.
1239 * @param[in] otmCtx Context value of ownership transfer.
1240 * @return OC_STACK_OK on success
1242 static OCStackResult PostOwnerAcl(OTMContext_t* otmCtx)
1244 OCStackResult res = OC_STACK_ERROR;
1246 OIC_LOG(DEBUG, TAG, "IN PostOwnerAcl");
1248 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1250 OIC_LOG(ERROR, TAG, "Invalid parameters");
1251 return OC_STACK_INVALID_PARAM;
1254 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1255 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1256 OicSecAcl_t* ownerAcl = NULL;
1258 if(!PMGenerateQuery(true,
1259 deviceInfo->endpoint.addr, deviceInfo->securePort,
1260 deviceInfo->connType,
1261 query, sizeof(query), OIC_RSRC_ACL_URI))
1263 OIC_LOG(ERROR, TAG, "Failed to generate query");
1264 return OC_STACK_ERROR;
1266 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1269 res = GetDoxmDeviceID(&ownerID);
1270 if(OC_STACK_OK != res)
1272 OIC_LOG(ERROR, TAG, "Failed to generate owner ACL");
1276 //Generate owner ACL for new device
1277 ownerAcl = GenerateOwnerAcl(&ownerID);
1278 if(NULL == ownerAcl)
1280 OIC_LOG(ERROR, TAG, "Failed to generate owner ACL");
1281 return OC_STACK_NO_MEMORY;
1284 //Generate ACL payload
1285 OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1288 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1289 res = OC_STACK_NO_MEMORY;
1293 res = AclToCBORPayload(ownerAcl, &secPayload->securityData, &secPayload->payloadSize);
1294 if (OC_STACK_OK != res)
1296 OICFree(secPayload);
1297 OIC_LOG(ERROR, TAG, "Error while converting bin to cbor.");
1300 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1302 OIC_LOG(DEBUG, TAG, "Owner ACL Payload:");
1303 OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1305 //Send owner ACL to new device : POST /oic/sec/cred [ owner credential ]
1306 OCCallbackData cbData;
1307 cbData.cb = &OwnerAclHandler;
1308 cbData.context = (void *)otmCtx;
1310 res = OCDoResource(NULL, OC_REST_POST, query,
1311 &deviceInfo->endpoint, (OCPayload*)secPayload,
1312 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1313 if (res != OC_STACK_OK)
1315 OIC_LOG(ERROR, TAG, "OCStack resource error");
1319 OIC_LOG(DEBUG, TAG, "OUT PostOwnerAcl");
1322 DeleteACLList(ownerAcl);
1327 static OCStackResult PostOwnerTransferModeToResource(OTMContext_t* otmCtx)
1329 OIC_LOG(DEBUG, TAG, "IN PostOwnerTransferModeToResource");
1331 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1333 OIC_LOG(ERROR, TAG, "Invalid parameters");
1334 return OC_STACK_INVALID_PARAM;
1337 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1338 OicSecOxm_t selectedOxm = deviceInfo->doxm->oxmSel;
1339 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1341 if(!PMGenerateQuery(false,
1342 deviceInfo->endpoint.addr, deviceInfo->endpoint.port,
1343 deviceInfo->connType,
1344 query, sizeof(query), OIC_RSRC_DOXM_URI))
1346 OIC_LOG(ERROR, TAG, "PostOwnerTransferModeToResource : Failed to generate query");
1347 return OC_STACK_ERROR;
1349 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1350 OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1353 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1354 return OC_STACK_NO_MEMORY;
1356 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1357 OCStackResult res = g_OTMCbDatas[selectedOxm].createSelectOxmPayloadCB(otmCtx,
1358 &secPayload->securityData, &secPayload->payloadSize);
1359 if (OC_STACK_OK != res && NULL == secPayload->securityData)
1361 OCPayloadDestroy((OCPayload *)secPayload);
1362 OIC_LOG(ERROR, TAG, "Error while converting bin to cbor");
1363 return OC_STACK_ERROR;
1366 OCCallbackData cbData;
1367 cbData.cb = &OwnerTransferModeHandler;
1368 cbData.context = (void *)otmCtx;
1370 res = OCDoResource(NULL, OC_REST_POST, query,
1371 &deviceInfo->endpoint, (OCPayload *)secPayload,
1372 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1373 if (res != OC_STACK_OK)
1375 OIC_LOG(ERROR, TAG, "OCStack resource error");
1378 OIC_LOG(DEBUG, TAG, "OUT PostOwnerTransferModeToResource");
1383 static OCStackResult GetProvisioningStatusResource(OTMContext_t* otmCtx)
1385 OIC_LOG(DEBUG, TAG, "IN GetProvisioningStatusResource");
1387 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1389 OIC_LOG(ERROR, TAG, "Invailed parameters");
1390 return OC_STACK_INVALID_PARAM;
1393 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1394 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1395 if(!PMGenerateQuery(false,
1396 deviceInfo->endpoint.addr, deviceInfo->endpoint.port,
1397 deviceInfo->connType,
1398 query, sizeof(query), OIC_RSRC_PSTAT_URI))
1400 OIC_LOG(ERROR, TAG, "GetProvisioningStatusResource : Failed to generate query");
1401 return OC_STACK_ERROR;
1403 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1405 OCCallbackData cbData;
1406 cbData.cb = &ListMethodsHandler;
1407 cbData.context = (void *)otmCtx;
1409 OCStackResult res = OCDoResource(NULL, OC_REST_GET, query, NULL, NULL,
1410 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1411 if (res != OC_STACK_OK)
1413 OIC_LOG(ERROR, TAG, "OCStack resource error");
1416 OIC_LOG(DEBUG, TAG, "OUT GetProvisioningStatusResource");
1421 static OCStackResult PostOwnerUuid(OTMContext_t* otmCtx)
1423 OIC_LOG(DEBUG, TAG, "IN PostOwnerUuid");
1425 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1427 OIC_LOG(ERROR, TAG, "Invailed parameters");
1428 return OC_STACK_INVALID_PARAM;
1431 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1432 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1433 if(!PMGenerateQuery(true,
1434 deviceInfo->endpoint.addr, deviceInfo->securePort,
1435 deviceInfo->connType,
1436 query, sizeof(query), OIC_RSRC_DOXM_URI))
1438 OIC_LOG(ERROR, TAG, "PostOwnerUuid : Failed to generate query");
1439 return OC_STACK_ERROR;
1441 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1443 //Post PT's uuid to new device
1444 OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1447 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1448 return OC_STACK_NO_MEMORY;
1450 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1451 OCStackResult res = g_OTMCbDatas[deviceInfo->doxm->oxmSel].createOwnerTransferPayloadCB(
1452 otmCtx, &secPayload->securityData, &secPayload->payloadSize);
1453 if (OC_STACK_OK != res && NULL == secPayload->securityData)
1455 OCPayloadDestroy((OCPayload *)secPayload);
1456 OIC_LOG(ERROR, TAG, "Error while converting doxm bin to cbor.");
1457 return OC_STACK_INVALID_PARAM;
1459 OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1461 OCCallbackData cbData;
1462 cbData.cb = &OwnerUuidUpdateHandler;
1463 cbData.context = (void *)otmCtx;
1466 res = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload *)secPayload,
1467 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1468 if (res != OC_STACK_OK)
1470 OIC_LOG(ERROR, TAG, "OCStack resource error");
1473 OIC_LOG(DEBUG, TAG, "OUT PostOwnerUuid");
1478 static OCStackResult PostOwnershipInformation(OTMContext_t* otmCtx)
1480 OIC_LOG(DEBUG, TAG, "IN PostOwnershipInformation");
1482 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1484 OIC_LOG(ERROR, TAG, "Invailed parameters");
1485 return OC_STACK_INVALID_PARAM;
1488 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1489 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1490 if(!PMGenerateQuery(true,
1491 deviceInfo->endpoint.addr, deviceInfo->securePort,
1492 deviceInfo->connType,
1493 query, sizeof(query), OIC_RSRC_DOXM_URI))
1495 OIC_LOG(ERROR, TAG, "PostOwnershipInformation : Failed to generate query");
1496 return OC_STACK_ERROR;
1498 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1500 //OwnershipInformationHandler
1501 OCSecurityPayload *secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1504 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1505 return OC_STACK_NO_MEMORY;
1508 otmCtx->selectedDeviceInfo->doxm->owned = true;
1510 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1511 OCStackResult res = DoxmToCBORPayload(otmCtx->selectedDeviceInfo->doxm,
1512 &secPayload->securityData, &secPayload->payloadSize, true);
1513 if (OC_STACK_OK != res && NULL == secPayload->securityData)
1515 OCPayloadDestroy((OCPayload *)secPayload);
1516 OIC_LOG(ERROR, TAG, "Error while converting doxm bin to json");
1517 return OC_STACK_INVALID_PARAM;
1520 OCCallbackData cbData;
1521 cbData.cb = &OwnershipInformationHandler;
1522 cbData.context = (void *)otmCtx;
1525 res = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload*)secPayload,
1526 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1527 if (res != OC_STACK_OK)
1529 OIC_LOG(ERROR, TAG, "OCStack resource error");
1532 OIC_LOG(DEBUG, TAG, "OUT PostOwnershipInformation");
1537 static OCStackResult PostUpdateOperationMode(OTMContext_t* otmCtx)
1539 OIC_LOG(DEBUG, TAG, "IN PostUpdateOperationMode");
1541 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1543 return OC_STACK_INVALID_PARAM;
1546 OCProvisionDev_t* deviceInfo = otmCtx->selectedDeviceInfo;
1547 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1548 if(!PMGenerateQuery(false,
1549 deviceInfo->endpoint.addr, deviceInfo->endpoint.port,
1550 deviceInfo->connType,
1551 query, sizeof(query), OIC_RSRC_PSTAT_URI))
1553 OIC_LOG(ERROR, TAG, "PostUpdateOperationMode : Failed to generate query");
1554 return OC_STACK_ERROR;
1556 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1558 OCSecurityPayload* secPayload = (OCSecurityPayload*)OICCalloc(1, sizeof(OCSecurityPayload));
1561 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1562 return OC_STACK_NO_MEMORY;
1564 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1565 OCStackResult res = PstatToCBORPayload(deviceInfo->pstat, &secPayload->securityData,
1566 &secPayload->payloadSize, true);
1567 if (OC_STACK_OK != res)
1569 OCPayloadDestroy((OCPayload *)secPayload);
1570 OIC_LOG(ERROR, TAG, "Error while converting pstat to cbor.");
1571 return OC_STACK_INVALID_PARAM;
1574 OCCallbackData cbData;
1575 cbData.cb = &OperationModeUpdateHandler;
1576 cbData.context = (void *)otmCtx;
1578 res = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload *)secPayload,
1579 deviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1580 if (res != OC_STACK_OK)
1582 OIC_LOG(ERROR, TAG, "OCStack resource error");
1585 OIC_LOG(DEBUG, TAG, "OUT PostUpdateOperationMode");
1590 static OCStackResult StartOwnershipTransfer(void* ctx, OCProvisionDev_t* selectedDevice)
1592 OIC_LOG(INFO, TAG, "IN StartOwnershipTransfer");
1593 OCStackResult res = OC_STACK_INVALID_PARAM;
1595 VERIFY_NON_NULL(TAG, selectedDevice, ERROR);
1596 VERIFY_NON_NULL(TAG, selectedDevice->doxm, ERROR);
1598 OTMContext_t* otmCtx = (OTMContext_t*)ctx;
1599 otmCtx->selectedDeviceInfo = selectedDevice;
1601 //Set to the lowest level OxM, and then find more higher level OxM.
1602 res = SelectProvisioningMethod(selectedDevice->doxm->oxm,
1603 selectedDevice->doxm->oxmLen,
1604 &selectedDevice->doxm->oxmSel);
1605 if(OC_STACK_OK != res)
1607 OIC_LOG(ERROR, TAG, "Failed to select the provisioning method");
1608 SetResult(otmCtx, res);
1611 OIC_LOG_V(DEBUG, TAG, "Selected provisoning method = %d", selectedDevice->doxm->oxmSel);
1613 //Send Req: POST /oic/sec/doxm [{..."OxmSel" :g_OTMCbDatas[Index of Selected OxM].OXMString,...}]
1614 res = PostOwnerTransferModeToResource(otmCtx);
1615 if(OC_STACK_OK != res)
1617 OIC_LOG(WARNING, TAG, "Failed to select the provisioning method");
1618 SetResult(otmCtx, res);
1622 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1623 //Register TLS event handler to catch the tls event while handshake
1624 if(CA_STATUS_OK != CAregisterSslHandshakeCallback(DTLSHandshakeCB))
1626 OIC_LOG(WARNING, TAG, "StartOwnershipTransfer : Failed to register TLS handshake callback.");
1628 #endif // __WITH_DTLS__ or __WITH_TLS__
1629 OIC_LOG(INFO, TAG, "OUT StartOwnershipTransfer");
1635 OCStackResult OTMSetOwnershipTransferCallbackData(OicSecOxm_t oxmType, OTMCallbackData_t* data)
1637 OIC_LOG(DEBUG, TAG, "IN OTMSetOwnerTransferCallbackData");
1641 OIC_LOG(ERROR, TAG, "OTMSetOwnershipTransferCallbackData : Invalid parameters");
1642 return OC_STACK_INVALID_PARAM;
1644 if(oxmType >= OIC_OXM_COUNT)
1646 OIC_LOG(INFO, TAG, "Unknow ownership transfer method");
1647 return OC_STACK_INVALID_PARAM;
1650 g_OTMCbDatas[oxmType].loadSecretCB= data->loadSecretCB;
1651 g_OTMCbDatas[oxmType].createSecureSessionCB = data->createSecureSessionCB;
1652 g_OTMCbDatas[oxmType].createSelectOxmPayloadCB = data->createSelectOxmPayloadCB;
1653 g_OTMCbDatas[oxmType].createOwnerTransferPayloadCB = data->createOwnerTransferPayloadCB;
1655 OIC_LOG(DEBUG, TAG, "OUT OTMSetOwnerTransferCallbackData");
1661 * NOTE : Unowned discovery should be done before performing OTMDoOwnershipTransfer
1663 OCStackResult OTMDoOwnershipTransfer(void* ctx,
1664 OCProvisionDev_t *selectedDevicelist,
1665 OCProvisionResultCB resultCallback)
1667 OIC_LOG(DEBUG, TAG, "IN OTMDoOwnershipTransfer");
1669 if (NULL == selectedDevicelist)
1671 return OC_STACK_INVALID_PARAM;
1673 if (NULL == resultCallback)
1675 return OC_STACK_INVALID_CALLBACK;
1678 OTMContext_t* otmCtx = (OTMContext_t*)OICCalloc(1,sizeof(OTMContext_t));
1681 OIC_LOG(ERROR, TAG, "Failed to create OTM Context");
1682 return OC_STACK_NO_MEMORY;
1684 otmCtx->ctxResultCallback = resultCallback;
1685 otmCtx->ctxHasError = false;
1686 otmCtx->userCtx = ctx;
1687 OCProvisionDev_t* pCurDev = selectedDevicelist;
1689 //Counting number of selected devices.
1690 otmCtx->ctxResultArraySize = 0;
1691 while(NULL != pCurDev)
1693 otmCtx->ctxResultArraySize++;
1694 pCurDev = pCurDev->next;
1697 otmCtx->ctxResultArray =
1698 (OCProvisionResult_t*)OICCalloc(otmCtx->ctxResultArraySize, sizeof(OCProvisionResult_t));
1699 if(NULL == otmCtx->ctxResultArray)
1701 OIC_LOG(ERROR, TAG, "OTMDoOwnershipTransfer : Failed to memory allocation");
1703 return OC_STACK_NO_MEMORY;
1705 pCurDev = selectedDevicelist;
1707 OCStackResult res = OC_STACK_OK;
1708 //Fill the device UUID for result array.
1709 for(size_t devIdx = 0; devIdx < otmCtx->ctxResultArraySize; devIdx++)
1711 //Checking duplication of Device ID.
1712 bool isDuplicate = true;
1713 res = PDMIsDuplicateDevice(&pCurDev->doxm->deviceID, &isDuplicate);
1714 if (OC_STACK_OK != res)
1720 bool isStale = false;
1721 res = PDMIsDeviceStale(&pCurDev->doxm->deviceID, &isStale);
1722 if(OC_STACK_OK != res)
1724 OIC_LOG(ERROR, TAG, "Internal error in PDMIsDeviceStale");
1729 OIC_LOG(INFO, TAG, "Detected duplicated UUID in stale status, "\
1730 "this UUID will be removed from PDM");
1732 res = PDMDeleteDevice(&pCurDev->doxm->deviceID);
1733 if(OC_STACK_OK != res)
1735 OIC_LOG(ERROR, TAG, "Internal error in PDMDeleteDevice");
1741 OIC_LOG(ERROR, TAG, "OTMDoOwnershipTransfer : Device UUID is duplicated");
1742 res = OC_STACK_INVALID_PARAM;
1746 memcpy(otmCtx->ctxResultArray[devIdx].deviceId.id,
1747 pCurDev->doxm->deviceID.id,
1749 otmCtx->ctxResultArray[devIdx].res = OC_STACK_CONTINUE;
1750 pCurDev = pCurDev->next;
1753 StartOwnershipTransfer(otmCtx, selectedDevicelist);
1755 OIC_LOG(DEBUG, TAG, "OUT OTMDoOwnershipTransfer");
1759 OICFree(otmCtx->ctxResultArray);
1764 OCStackResult PostProvisioningStatus(OTMContext_t* otmCtx)
1766 OIC_LOG(INFO, TAG, "IN PostProvisioningStatus");
1768 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1770 OIC_LOG(ERROR, TAG, "OTMContext is NULL");
1771 return OC_STACK_INVALID_PARAM;
1774 //Change the TAKE_OWNER bit of CM to 0.
1775 otmCtx->selectedDeviceInfo->pstat->cm &= (~TAKE_OWNER);
1777 OCSecurityPayload *secPayload = (OCSecurityPayload *)OICCalloc(1, sizeof(OCSecurityPayload));
1780 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1781 return OC_STACK_NO_MEMORY;
1783 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1784 if (OC_STACK_OK != PstatToCBORPayload(otmCtx->selectedDeviceInfo->pstat,
1785 &secPayload->securityData, &secPayload->payloadSize, true))
1787 OCPayloadDestroy((OCPayload *)secPayload);
1788 return OC_STACK_INVALID_JSON;
1790 OIC_LOG(DEBUG, TAG, "Created payload for chage to Provisiong state");
1791 OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1793 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1794 if(!PMGenerateQuery(true,
1795 otmCtx->selectedDeviceInfo->endpoint.addr,
1796 otmCtx->selectedDeviceInfo->securePort,
1797 otmCtx->selectedDeviceInfo->connType,
1798 query, sizeof(query), OIC_RSRC_PSTAT_URI))
1800 OIC_LOG(ERROR, TAG, "PostProvisioningStatus : Failed to generate query");
1801 return OC_STACK_ERROR;
1803 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1805 OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
1806 cbData.cb = &ProvisioningStatusHandler;
1807 cbData.context = (void*)otmCtx;
1809 OCStackResult ret = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload*)secPayload,
1810 otmCtx->selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1811 OIC_LOG_V(INFO, TAG, "OCDoResource returned: %d",ret);
1812 if (ret != OC_STACK_OK)
1814 OIC_LOG(ERROR, TAG, "OCStack resource error");
1817 OIC_LOG(INFO, TAG, "OUT PostProvisioningStatus");
1822 OCStackResult PostNormalOperationStatus(OTMContext_t* otmCtx)
1824 OIC_LOG(INFO, TAG, "IN PostNormalOperationStatus");
1826 if(!otmCtx || !otmCtx->selectedDeviceInfo)
1828 OIC_LOG(ERROR, TAG, "OTMContext is NULL");
1829 return OC_STACK_INVALID_PARAM;
1833 otmCtx->selectedDeviceInfo->pstat->isOp = true;
1835 OCSecurityPayload *secPayload = (OCSecurityPayload *)OICCalloc(1, sizeof(OCSecurityPayload));
1838 OIC_LOG(ERROR, TAG, "Failed to memory allocation");
1839 return OC_STACK_NO_MEMORY;
1841 secPayload->base.type = PAYLOAD_TYPE_SECURITY;
1842 if (OC_STACK_OK != PstatToCBORPayload(otmCtx->selectedDeviceInfo->pstat,
1843 &secPayload->securityData, &secPayload->payloadSize, true))
1845 OCPayloadDestroy((OCPayload *)secPayload);
1846 return OC_STACK_INVALID_JSON;
1848 OIC_LOG(DEBUG, TAG, "Created payload for chage to Provisiong state");
1849 OIC_LOG_BUFFER(DEBUG, TAG, secPayload->securityData, secPayload->payloadSize);
1851 char query[MAX_URI_LENGTH + MAX_QUERY_LENGTH] = {0};
1852 if(!PMGenerateQuery(true,
1853 otmCtx->selectedDeviceInfo->endpoint.addr,
1854 otmCtx->selectedDeviceInfo->securePort,
1855 otmCtx->selectedDeviceInfo->connType,
1856 query, sizeof(query), OIC_RSRC_PSTAT_URI))
1858 OIC_LOG(ERROR, TAG, "PostNormalOperationStatus : Failed to generate query");
1859 return OC_STACK_ERROR;
1861 OIC_LOG_V(DEBUG, TAG, "Query=%s", query);
1863 OCCallbackData cbData = {.context=NULL, .cb=NULL, .cd=NULL};
1864 cbData.cb = &ReadyForNomalStatusHandler;
1865 cbData.context = (void*)otmCtx;
1867 OCStackResult ret = OCDoResource(NULL, OC_REST_POST, query, 0, (OCPayload*)secPayload,
1868 otmCtx->selectedDeviceInfo->connType, OC_HIGH_QOS, &cbData, NULL, 0);
1869 OIC_LOG_V(INFO, TAG, "OCDoResource returned: %d",ret);
1870 if (ret != OC_STACK_OK)
1872 OIC_LOG(ERROR, TAG, "OCStack resource error");
1875 OIC_LOG(INFO, TAG, "OUT PostNormalOperationStatus");