1 //******************************************************************
3 // Copyright 2015 Intel Mobile Communications GmbH All Rights Reserved.
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
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 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
20 #include "iotivity_config.h"
29 #include "oic_malloc.h"
30 #include "payload_logging.h"
33 #include "ocpayload.h"
34 #include "ocpayloadcbor.h"
35 #include "cainterface.h"
36 #include "ocserverrequest.h"
37 #include "resourcemanager.h"
38 #include "doxmresource.h"
39 #include "pstatresource.h"
40 #include "aclresource.h"
41 #include "amaclresource.h"
42 #include "pconfresource.h"
43 #include "dpairingresource.h"
44 #include "psinterface.h"
45 #include "srmresourcestrings.h"
46 #include "securevirtualresourcetypes.h"
47 #include "credresource.h"
48 #include "srmutility.h"
49 #include "pinoxmcommon.h"
50 #include "oxmverifycommon.h"
53 #include "oic_string.h"
55 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
56 #include "pkix_interface.h"
57 #include "ca_adapter_net_ssl.h"
60 #define TAG "OIC_SRM_DOXM"
61 #define CHAR_ZERO ('0')
63 /** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
64 * The value of payload size is increased until reaching belox max cbor size. */
65 static const uint16_t CBOR_SIZE = 512;
67 /** Max cbor size payload. */
68 static const uint16_t CBOR_MAX_SIZE = 4400;
70 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
71 /** MAX uuid seed size */
72 #define MAX_UUID_SEED_SIZE (64)
73 /** MIN uuid seed size */
74 #define MIN_UUID_SEED_SIZE (8)
76 /** Buffer to save the seed of device UUID */
77 static uint8_t gUuidSeed[MAX_UUID_SEED_SIZE];
78 static size_t gUuidSeedSize = 0;
82 #define MAX_SUBOWNER_SIZE (64)
83 #define MIN_SUBOWNER_SIZE (1)
84 #define DEFAULT_SUBOWNER_SIZE (32)
86 static size_t gMaxSubOwnerSize = DEFAULT_SUBOWNER_SIZE;
89 typedef enum ConfirmState{
90 CONFIRM_STATE_READY = 0,
91 CONFIRM_STATE_WAIT = 1,
92 CONFIRM_STATE_ACCEPTED = 2,
93 CONFIRM_STATE_DENIED = 3
96 static OicSecDoxm_t *gDoxm = NULL;
97 static oc_mutex g_mutexDoxm = NULL;
98 static bool g_isDoxmNull = false;
99 static OCResourceHandle gDoxmHandle = NULL;
100 static oc_mutex g_mutexWait;
101 static oc_thread g_waitConfirmThreadId;
103 static InformOxmSelectedCallback_t g_InformOxmSelectedCallback = NULL;
104 static bool g_isConfirmResult;
106 static OicSecOxm_t gOicSecDoxmJustWorks = OIC_JUST_WORKS;
107 static OicSecDoxm_t gDefaultDoxm =
109 NULL, /* OicUrn_t *oxmType */
110 0, /* size_t oxmTypeLen */
111 &gOicSecDoxmJustWorks, /* uint16_t *oxm */
112 1, /* size_t oxmLen */
113 OIC_JUST_WORKS, /* uint16_t oxmSel */
114 SYMMETRIC_PAIR_WISE_KEY,/* OicSecCredType_t sct */
115 false, /* bool owned */
116 {.id = {0}}, /* OicUuid_t deviceID */
117 false, /* bool dpc */
118 {.id = {0}}, /* OicUuid_t owner */
119 #ifdef MULTIPLE_OWNER
120 NULL, /* OicSecSubOwner_t sub-owner list */
121 NULL, /* OicSecMomType_t multiple owner mode */
122 #endif //MULTIPLE_OWNER
123 {.id = {0}}, /* OicUuid_t rownerID */
126 static uint16_t gConfirmMsgId = 0;
127 static ConfirmState_t gConfirmState = CONFIRM_STATE_READY;
129 static uint8_t gEmptyUuid[UUID_LENGTH] = {0};
132 * This method is internal method.
133 * the param roParsed is optionally used to know whether cborPayload has
134 * at least read only property value or not.
136 static OCStackResult CBORPayloadToDoxmBin(const uint8_t *cborPayload, size_t size,
137 OicSecDoxm_t **doxm, bool *roParsed);
139 void DeleteDoxmBinData(OicSecDoxm_t* doxm)
144 for (size_t i = 0; i < doxm->oxmTypeLen; i++)
146 OICFree(doxm->oxmType[i]);
148 OICFree(doxm->oxmType);
153 #ifdef MULTIPLE_OWNER
157 //clean sub-owner list
158 if(NULL != doxm->subOwners)
160 OicSecSubOwner_t* subowner = NULL;
161 OicSecSubOwner_t* temp = NULL;
162 LL_FOREACH_SAFE(doxm->subOwners, subowner, temp)
164 LL_DELETE(doxm->subOwners, subowner);
168 #endif //MULTIPLE_OWNER
176 oc_mutex_free(g_mutexDoxm);
181 OCStackResult DoxmToCBORPayload(const OicSecDoxm_t *doxm, uint8_t **payload, size_t *size,
184 if (NULL == doxm || NULL == payload || NULL != *payload || NULL == size)
186 return OC_STACK_INVALID_PARAM;
188 size_t cborLen = *size;
196 OCStackResult ret = OC_STACK_ERROR;
200 char* strUuid = NULL;
202 int64_t cborEncoderResult = CborNoError;
204 uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
205 VERIFY_NON_NULL(TAG, outPayload, ERROR);
206 cbor_encoder_init(&encoder, outPayload, cborLen, 0);
208 cborEncoderResult = cbor_encoder_create_map(&encoder, &doxmMap, CborIndefiniteLength);
209 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Doxm Map.");
211 //OxmType -- Not Mandatory
212 if (doxm->oxmTypeLen > 0)
215 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_TYPE_NAME,
216 strlen(OIC_JSON_OXM_TYPE_NAME));
217 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Tag.");
218 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxmType, doxm->oxmTypeLen);
219 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Array.");
221 for (size_t i = 0; i < doxm->oxmTypeLen; i++)
223 cborEncoderResult = cbor_encode_text_string(&oxmType, doxm->oxmType[i],
224 strlen(doxm->oxmType[i]));
225 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Value.");
227 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxmType);
228 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmType.");
231 //Oxm -- Not Mandatory
232 if (doxm->oxmLen > 0 && false == rwOnly)
235 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXMS_NAME,
236 strlen(OIC_JSON_OXMS_NAME));
237 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Tag.");
238 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxm, doxm->oxmLen);
239 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Array.");
241 for (size_t i = 0; i < doxm->oxmLen; i++)
243 cborEncoderResult = cbor_encode_int(&oxm, doxm->oxm[i]);
244 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Value");
246 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxm);
247 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmName.");
250 //OxmSel -- Mandatory
251 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_SEL_NAME,
252 strlen(OIC_JSON_OXM_SEL_NAME));
253 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Tag.");
254 cborEncoderResult = cbor_encode_int(&doxmMap, doxm->oxmSel);
255 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Value.");
260 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_SUPPORTED_CRED_TYPE_NAME,
261 strlen(OIC_JSON_SUPPORTED_CRED_TYPE_NAME));
262 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Tag");
263 cborEncoderResult = cbor_encode_int(&doxmMap, doxm->sct);
264 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Value.");
268 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OWNED_NAME,
269 strlen(OIC_JSON_OWNED_NAME));
270 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Tag.");
271 cborEncoderResult = cbor_encode_boolean(&doxmMap, doxm->owned);
272 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Value.");
276 //DeviceId -- Mandatory
277 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVICE_ID_NAME,
278 strlen(OIC_JSON_DEVICE_ID_NAME));
279 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Tag.");
280 ret = ConvertUuidToStr(&doxm->deviceID, &strUuid);
281 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
282 cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
283 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Value.");
288 #ifdef MULTIPLE_OWNER
289 //Device SubOwnerID -- Not Mandatory
292 size_t subOwnerLen = 0;
293 OicSecSubOwner_t* subOwner = NULL;
294 LL_FOREACH(doxm->subOwners, subOwner)
299 CborEncoder subOwners;
300 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_SUBOWNERID_NAME,
301 strlen(OIC_JSON_SUBOWNERID_NAME));
302 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SubOwnerId Tag.");
303 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &subOwners, subOwnerLen);
304 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SubOwner Array.");
307 LL_FOREACH(doxm->subOwners, subOwner)
309 char* strUuid = NULL;
310 ret = ConvertUuidToStr(&subOwner->uuid, &strUuid);
311 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
312 cborEncoderResult = cbor_encode_text_string(&subOwners, strUuid, strlen(strUuid));
314 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SubOwnerId Value");
316 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &subOwners);
317 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing SubOwnerId.");
320 //Multiple Owner Mode -- Not Mandatory
323 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_MOM_NAME,
324 strlen(OIC_JSON_MOM_NAME));
325 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding mom Tag");
326 cborEncoderResult = cbor_encode_int(&doxmMap, (int64_t)doxm->mom->mode);
327 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding mom Value.");
329 #endif //MULTIPLE_OWNER
331 //devownerid -- Mandatory
332 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVOWNERID_NAME,
333 strlen(OIC_JSON_DEVOWNERID_NAME));
334 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Id Tag.");
335 ret = ConvertUuidToStr(&doxm->owner, &strUuid);
336 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
337 cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
338 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Id Value.");
342 //ROwner -- Mandatory
343 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_ROWNERID_NAME,
344 strlen(OIC_JSON_ROWNERID_NAME));
345 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Tag.");
346 ret = ConvertUuidToStr(&doxm->rownerID, &strUuid);
347 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
348 cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
349 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Value.");
355 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_RT_NAME,
356 strlen(OIC_JSON_RT_NAME));
357 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Name Tag.");
358 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &rtArray, 1);
359 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Value.");
360 for (size_t i = 0; i < 1; i++)
362 cborEncoderResult = cbor_encode_text_string(&rtArray, OIC_RSRC_TYPE_SEC_DOXM,
363 strlen(OIC_RSRC_TYPE_SEC_DOXM));
364 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding RT Value.");
366 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &rtArray);
367 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing RT.");
371 cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_IF_NAME,
372 strlen(OIC_JSON_IF_NAME));
373 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Name Tag.");
374 cborEncoderResult = cbor_encoder_create_array(&doxmMap, &ifArray, 1);
375 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Value.");
376 for (size_t i = 0; i < 1; i++)
378 cborEncoderResult = cbor_encode_text_string(&ifArray, OC_RSRVD_INTERFACE_DEFAULT,
379 strlen(OC_RSRVD_INTERFACE_DEFAULT));
380 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding IF Value.");
382 cborEncoderResult = cbor_encoder_close_container(&doxmMap, &ifArray);
383 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing IF.");
385 cborEncoderResult = cbor_encoder_close_container(&encoder, &doxmMap);
386 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing DoxmMap.");
388 if (CborNoError == cborEncoderResult)
390 *size = cbor_encoder_get_buffer_size(&encoder, outPayload);
391 *payload = outPayload;
395 if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
397 OIC_LOG(DEBUG, TAG, "Memory getting reallocated.");
398 // reallocate and try again!
401 // Since the allocated initial memory failed, double the memory.
402 cborLen += cbor_encoder_get_buffer_size(&encoder, encoder.end);
403 OIC_LOG_V(DEBUG, TAG, "Doxm reallocation size : %zd.", cborLen);
404 cborEncoderResult = CborNoError;
405 ret = DoxmToCBORPayload(doxm, payload, &cborLen, rwOnly);
409 if ((CborNoError != cborEncoderResult) || (OC_STACK_OK != ret))
415 ret = OC_STACK_ERROR;
421 OCStackResult CBORPayloadToDoxm(const uint8_t *cborPayload, size_t size,
422 OicSecDoxm_t **secDoxm)
424 return CBORPayloadToDoxmBin(cborPayload, size, secDoxm, NULL);
427 static OCStackResult CBORPayloadToDoxmBin(const uint8_t *cborPayload, size_t size,
428 OicSecDoxm_t **secDoxm, bool *roParsed)
430 if (NULL == cborPayload || NULL == secDoxm || NULL != *secDoxm || 0 == size)
432 return OC_STACK_INVALID_PARAM;
435 OCStackResult ret = OC_STACK_ERROR;
439 CborError cborFindResult = CborNoError;
440 char* strUuid = NULL;
444 cbor_parser_init(cborPayload, size, 0, &parser, &doxmCbor);
446 OicSecDoxm_t *doxm = (OicSecDoxm_t *)OICCalloc(1, sizeof(*doxm));
447 VERIFY_NON_NULL(TAG, doxm, ERROR);
449 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_TYPE_NAME, &doxmMap);
450 //OxmType -- not Mandatory
451 if (CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
455 cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmTypeLen);
456 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmTypeLen.");
457 VERIFY_SUCCESS(TAG, doxm->oxmTypeLen != 0, ERROR);
459 doxm->oxmType = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(*doxm->oxmType));
460 VERIFY_NON_NULL(TAG, doxm->oxmType, ERROR);
462 cborFindResult = cbor_value_enter_container(&doxmMap, &oxmType);
463 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmType Array.")
467 while (cbor_value_is_valid(&oxmType) && cbor_value_is_text_string(&oxmType))
469 cborFindResult = cbor_value_dup_text_string(&oxmType, &doxm->oxmType[i++],
471 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding omxType text string.");
472 cborFindResult = cbor_value_advance(&oxmType);
473 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmType.");
477 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXMS_NAME, &doxmMap);
478 //Oxm -- not Mandatory
479 if (CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
482 cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmLen);
483 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName array Length.");
484 VERIFY_SUCCESS(TAG, doxm->oxmLen != 0, ERROR);
486 doxm->oxm = (OicSecOxm_t *)OICCalloc(doxm->oxmLen, sizeof(*doxm->oxm));
487 VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
489 cborFindResult = cbor_value_enter_container(&doxmMap, &oxm);
490 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmName Array.")
493 while (cbor_value_is_valid(&oxm) && cbor_value_is_integer(&oxm))
497 cborFindResult = cbor_value_get_int(&oxm, &tmp);
498 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName Value")
499 doxm->oxm[i++] = (OicSecOxm_t)tmp;
500 cborFindResult = cbor_value_advance(&oxm);
501 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmName.")
511 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
512 doxm->oxm = (OicSecOxm_t *) OICCalloc(gDoxm->oxmLen, sizeof(*doxm->oxm));
513 VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
514 doxm->oxmLen = gDoxm->oxmLen;
515 for (size_t i = 0; i < gDoxm->oxmLen; i++)
517 doxm->oxm[i] = gDoxm->oxm[i];
521 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_SEL_NAME, &doxmMap);
522 if (CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
526 cborFindResult = cbor_value_get_int(&doxmMap, &oxmSel);
527 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sel Name Value.")
528 doxm->oxmSel = (OicSecOxm_t)oxmSel;
530 else // PUT/POST JSON may not have oxmsel so set it to the gDoxm->oxmSel
532 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
533 doxm->oxmSel = gDoxm->oxmSel;
536 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_SUPPORTED_CRED_TYPE_NAME, &doxmMap);
537 if (CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
541 cborFindResult = cbor_value_get_int(&doxmMap, &sct);
542 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sct Name Value.")
543 doxm->sct = (OicSecCredType_t)sct;
550 else // PUT/POST JSON may not have sct so set it to the gDoxm->sct
552 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
553 doxm->sct = gDoxm->sct;
556 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OWNED_NAME, &doxmMap);
557 if (CborNoError == cborFindResult && cbor_value_is_boolean(&doxmMap))
559 cborFindResult = cbor_value_get_boolean(&doxmMap, &doxm->owned);
560 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owned Value.")
562 else // PUT/POST JSON may not have owned so set it to the gDomx->owned
564 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
565 doxm->owned = gDoxm->owned;
568 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVICE_ID_NAME, &doxmMap);
569 if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
571 cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
572 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Device Id Value.");
573 ret = ConvertStrToUuid(strUuid , &doxm->deviceID);
574 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
580 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
581 memcpy(doxm->deviceID.id, &gDoxm->deviceID.id, sizeof(doxm->deviceID.id));
584 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVOWNERID_NAME, &doxmMap);
585 if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
587 cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
588 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owner Value.");
589 ret = ConvertStrToUuid(strUuid , &doxm->owner);
590 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
596 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
597 memcpy(doxm->owner.id, gDoxm->owner.id, sizeof(doxm->owner.id));
600 #ifdef MULTIPLE_OWNER
601 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_MOM_NAME, &doxmMap);
602 if(CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
605 cborFindResult = cbor_value_get_int(&doxmMap, &mode);
606 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding mom Name Value.")
607 if(NULL == doxm->mom)
609 doxm->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
610 VERIFY_NON_NULL(TAG, doxm->mom, ERROR);
612 doxm->mom->mode = (OicSecMomType_t)mode;
614 else if(NULL != gDoxm && NULL != gDoxm->mom)
616 // PUT/POST JSON may not have 'mom' so set it to the gDomx->mom
617 if(NULL == doxm->mom)
619 doxm->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
620 VERIFY_NON_NULL(TAG, doxm->mom, ERROR);
622 doxm->mom->mode = gDoxm->mom->mode;
625 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_SUBOWNERID_NAME, &doxmMap);
626 if(CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
628 size_t subOwnerLen = 0;
629 CborValue subOwnerCbor;
630 cborFindResult = cbor_value_get_array_length(&doxmMap, &subOwnerLen);
631 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SubOwner array Length.");
632 VERIFY_SUCCESS(TAG, 0 != subOwnerLen, ERROR);
634 cborFindResult = cbor_value_enter_container(&doxmMap, &subOwnerCbor);
635 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering SubOwner Array.")
637 while (cbor_value_is_valid(&subOwnerCbor) && cbor_value_is_text_string(&subOwnerCbor))
639 OCStackResult convertRes = OC_STACK_ERROR;
640 OicSecSubOwner_t* subOwner = NULL;
641 char* strUuid = NULL;
644 cborFindResult = cbor_value_dup_text_string(&subOwnerCbor, &strUuid, &uuidLen, NULL);
645 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SubOwnerId Value");
647 subOwner = (OicSecSubOwner_t*)OICCalloc(1, sizeof(OicSecSubOwner_t));
648 VERIFY_NON_NULL(TAG, subOwner, ERROR);
650 convertRes = ConvertStrToUuid(strUuid, &subOwner->uuid);
651 VERIFY_SUCCESS(TAG, OC_STACK_OK == convertRes, ERROR);
652 subOwner->status = MOT_STATUS_DONE;
653 LL_APPEND(doxm->subOwners, subOwner);
655 cborFindResult = cbor_value_advance(&subOwnerCbor);
656 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing SubOwnerId.")
659 else if(NULL != gDoxm && NULL != gDoxm->subOwners)
661 // PUT/POST JSON may not have 'subOwners' so set it to the gDomx->subOwners
662 OicSecSubOwner_t* subOwnerItor = NULL;
663 LL_FOREACH(gDoxm->subOwners, subOwnerItor)
665 OicSecSubOwner_t* subOwnerId = (OicSecSubOwner_t*)OICCalloc(1, sizeof(OicSecSubOwner_t));
666 VERIFY_NON_NULL(TAG, subOwnerId, ERROR);
668 memcpy(&subOwnerId->uuid, &subOwnerItor->uuid, sizeof(OicUuid_t));
669 subOwnerId->status = MOT_STATUS_DONE;
671 LL_APPEND(doxm->subOwners, subOwnerId);
674 #endif //MULTIPLE_OWNER
676 cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_ROWNERID_NAME, &doxmMap);
677 if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
679 cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
680 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding ROwner Value.");
681 ret = ConvertStrToUuid(strUuid , &doxm->rownerID);
682 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
688 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
689 memcpy(doxm->rownerID.id, gDoxm->rownerID.id, sizeof(doxm->rownerID.id));
696 if (CborNoError != cborFindResult)
698 OIC_LOG (ERROR, TAG, "CBORPayloadToDoxm failed!!!");
699 DeleteDoxmBinData(doxm);
702 ret = OC_STACK_ERROR;
708 * @todo document this function including why code might need to call this.
709 * The current suspicion is that it's not being called as much as it should.
711 static bool UpdatePersistentStorage(OicSecDoxm_t * doxm)
717 // Convert Doxm data into CBOR for update to persistent storage
718 uint8_t *payload = NULL;
720 OCStackResult res = DoxmToCBORPayload(doxm, &payload, &size, false);
721 if (payload && (OC_STACK_OK == res)
722 && (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, payload, size)))
730 if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, NULL, 0))
739 OCStackResult SetDoxmDeviceIDResetPF(const OicUuid_t *deviceID)
741 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
743 OCStackResult res = OC_STACK_ERROR;
745 uint8_t *dbData = NULL;
746 uint8_t *aclCbor = NULL;
747 uint8_t *credCbor = NULL;
748 uint8_t *pstatCbor = NULL;
749 uint8_t *doxmCbor = NULL;
750 uint8_t *resetPfCbor = NULL;
751 int64_t cborEncoderResult = CborNoError;
753 if (NULL == deviceID)
755 OIC_LOG_V(ERROR, TAG, "%s - deviceID is NULL!", __func__);
759 res = GetSecureVirtualDatabaseFromPS(NULL, &dbData, &dbSize);
760 if (OC_STACK_OK != res)
762 OIC_LOG_V(ERROR, TAG, "GetSecureVirtualDatabaseFromPS() is failed(%d)", res);
765 if (dbData && dbSize)
767 size_t aclCborLen = 0;
768 size_t credCborLen = 0;
769 size_t pstatCborLen = 0;
770 size_t doxmCborLen = 0;
771 size_t resetPfCborLen = 0;
772 OicSecDoxm_t *tmpDoxm = NULL;
777 cbor_parser_init(dbData, dbSize, 0, &parser, &cbor);
778 CborValue curVal = {0};
779 CborError cborFindResult = CborNoError;
781 // abort if reset profile doesn't exist
782 cborFindResult = cbor_value_map_find_value(&cbor, OIC_JSON_RESET_PF_NAME, &curVal);
783 if (CborNoError != cborFindResult || !cbor_value_is_byte_string(&curVal))
785 OIC_LOG(DEBUG, TAG, "Reset Profile doesn't exist!");
789 cborFindResult = cbor_value_map_find_value(&cbor, OIC_JSON_ACL_NAME, &curVal);
790 if (CborNoError == cborFindResult && cbor_value_is_byte_string(&curVal))
792 cborFindResult = cbor_value_dup_byte_string(&curVal, &aclCbor, &aclCborLen, NULL);
793 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding ACL Name Value.");
795 cborFindResult = cbor_value_map_find_value(&cbor, OIC_JSON_CRED_NAME, &curVal);
796 if (CborNoError == cborFindResult && cbor_value_is_byte_string(&curVal))
798 cborFindResult = cbor_value_dup_byte_string(&curVal, &credCbor, &credCborLen, NULL);
799 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding CRED Name Value.");
801 cborFindResult = cbor_value_map_find_value(&cbor, OIC_JSON_PSTAT_NAME, &curVal);
802 if (CborNoError == cborFindResult && cbor_value_is_byte_string(&curVal))
804 cborFindResult = cbor_value_dup_byte_string(&curVal, &pstatCbor, &pstatCborLen, NULL);
805 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding PSTAT Name Value.");
807 cborFindResult = cbor_value_map_find_value(&cbor, OIC_JSON_DOXM_NAME, &curVal);
808 if (CborNoError == cborFindResult && cbor_value_is_byte_string(&curVal))
810 cborFindResult = cbor_value_dup_byte_string(&curVal, &doxmCbor, &doxmCborLen, NULL);
811 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding DOXM Name Value.");
813 res = CBORPayloadToDoxm(doxmCbor, doxmCborLen, &tmpDoxm);
814 if (OC_STACK_OK != res)
816 OIC_LOG_V(ERROR, TAG, "%s - CBORPayloadToDoxm error : %d", __func__, res);
819 VERIFY_NON_NULL(TAG, tmpDoxm, ERROR);
820 memcpy(tmpDoxm->deviceID.id, deviceID->id, sizeof(deviceID->id));
824 res = DoxmToCBORPayload(tmpDoxm, &doxmCbor, &doxmCborLen, false);
825 if (OC_STACK_OK != res || 0 == doxmCborLen || NULL == doxmCbor)
827 OIC_LOG_V(ERROR, TAG,"%s - DoxmToCBORPayload error : %d", __func__, res);
834 size_t size = aclCborLen + credCborLen + pstatCborLen + doxmCborLen + 255;
835 resetPfCbor = (uint8_t *) OICCalloc(1, size);
836 VERIFY_NON_NULL(TAG, resetPfCbor, ERROR);
837 CborEncoder encoder; // will be initialized in |cbor_parser_init|
838 cbor_encoder_init(&encoder, resetPfCbor, size, 0);
839 CborEncoder secRsrc; // will be initialized in |cbor_encoder_create_map|
840 cborEncoderResult |= cbor_encoder_create_map(&encoder, &secRsrc, CborIndefiniteLength);
842 cborEncoderResult |= cbor_encode_text_string(&secRsrc, OIC_JSON_ACL_NAME, strlen(OIC_JSON_ACL_NAME));
843 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ACL Name.");
844 cborEncoderResult |= cbor_encode_byte_string(&secRsrc, aclCbor, aclCborLen);
845 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ACL Value.");
849 cborEncoderResult |= cbor_encode_text_string(&secRsrc, OIC_JSON_CRED_NAME, strlen(OIC_JSON_CRED_NAME));
850 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding CRED Name.");
851 cborEncoderResult |= cbor_encode_byte_string(&secRsrc, credCbor, credCborLen);
852 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding CRED Value.");
855 cborEncoderResult |= cbor_encode_text_string(&secRsrc, OIC_JSON_PSTAT_NAME, strlen(OIC_JSON_PSTAT_NAME));
856 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PSTAT Name.");
857 cborEncoderResult |= cbor_encode_byte_string(&secRsrc, pstatCbor, pstatCborLen);
858 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PSTAT Value.");
860 cborEncoderResult |= cbor_encode_text_string(&secRsrc, OIC_JSON_DOXM_NAME, strlen(OIC_JSON_DOXM_NAME));
861 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Doxm Name.");
862 cborEncoderResult |= cbor_encode_byte_string(&secRsrc, doxmCbor, doxmCborLen);
863 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Doxm Value.");
865 cborEncoderResult |= cbor_encoder_close_container(&encoder, &secRsrc);
866 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Array.");
867 resetPfCborLen = cbor_encoder_get_buffer_size(&encoder, resetPfCbor);
870 res = UpdateSecureResourceInPS(OIC_JSON_RESET_PF_NAME, resetPfCbor, resetPfCborLen);
871 if (OC_STACK_OK != res)
873 OIC_LOG_V(ERROR, TAG, "%s - Error in UpdateSecureResourceInPS", __func__);
876 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
884 OICFree(resetPfCbor);
889 static bool ValidateQuery(const char * query)
891 // Send doxm resource data if the state of doxm resource
892 // matches with the query parameters.
893 // else send doxm resource data as NULL
894 // TODO Remove this check and rely on Policy Engine
895 // and Provisioning Mode to enforce provisioning-state
896 // access rules. Eventually, the PE and PM code will
897 // not send a request to the /doxm Entity Handler at all
898 // if it should not respond.
899 OIC_LOG (DEBUG, TAG, "In ValidateQuery");
905 bool bOwnedQry = false; // does querystring contains 'owned' query ?
906 bool bOwnedMatch = false; // does 'owned' query value matches with doxm.owned status?
907 bool bDeviceIDQry = false; // does querystring contains 'deviceid' query ?
908 bool bDeviceIDMatch = false; // does 'deviceid' query matches with doxm.deviceid ?
909 bool bInterfaceQry = false; // does querystring contains 'if' query ?
910 bool bInterfaceMatch = false; // does 'if' query matches with oic.if.baseline ?
911 #ifdef MULTIPLE_OWNER
912 bool bMotMatch = false; // does 'mom' query value is not '0' && does query value matches with doxm.owned status?
913 #endif //MULTIPLE_OWNER
915 OicParseQueryIter_t parseIter = {.attrPos = NULL};
917 ParseQueryIterInit((unsigned char*)query, &parseIter);
919 while (GetNextQuery(&parseIter))
921 if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
924 if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
929 else if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_FALSE, parseIter.valLen) == 0)
936 #ifdef MULTIPLE_OWNER
937 if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_MOM_NAME, strlen(OIC_JSON_MOM_NAME)) == 0)
939 OicSecMomType_t momMode = (OicSecMomType_t)(parseIter.valPos[0] - CHAR_ZERO);
940 if(NULL != gDoxm->mom && momMode != gDoxm->mom->mode)
942 if(GetNextQuery(&parseIter))
944 if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
946 if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
956 #endif //MULTIPLE_OWNER
958 if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_DEVICE_ID_NAME, parseIter.attrLen) == 0)
961 OicUuid_t subject = {.id={0}};
963 memcpy(subject.id, parseIter.valPos, parseIter.valLen);
964 if (0 == memcmp(&gDoxm->deviceID.id, &subject.id, sizeof(gDoxm->deviceID.id)))
966 bDeviceIDMatch = true;
970 if (strncasecmp((char *)parseIter.attrPos, OC_RSRVD_INTERFACE, parseIter.attrLen) == 0)
972 bInterfaceQry = true;
973 if ((strncasecmp((char *)parseIter.valPos, OC_RSRVD_INTERFACE_DEFAULT, parseIter.valLen) == 0))
975 bInterfaceMatch = true;
977 return (bInterfaceQry ? bInterfaceMatch: true);
981 return ((bOwnedQry ? bOwnedMatch : true) &&
982 (bDeviceIDQry ? bDeviceIDMatch : true));
985 static OCEntityHandlerResult HandleDoxmGetRequest (const OCEntityHandlerRequest * ehRequest)
987 OCEntityHandlerResult ehRet = OC_EH_OK;
989 OIC_LOG(DEBUG, TAG, "Doxm EntityHandle processing GET request");
991 //Checking if Get request is a query.
992 if (ehRequest->query)
994 OIC_LOG_V(DEBUG,TAG,"query:%s",ehRequest->query);
995 OIC_LOG(DEBUG, TAG, "HandleDoxmGetRequest processing query");
996 if (!ValidateQuery(ehRequest->query))
1003 * For GET or Valid Query request return doxm resource CBOR payload.
1004 * For non-valid query return NULL json payload.
1005 * A device will 'always' have a default Doxm, so DoxmToCBORPayload will
1006 * return valid doxm resource json.
1008 uint8_t *payload = NULL;
1011 if (ehRet == OC_EH_OK)
1013 if (OC_STACK_OK != DoxmToCBORPayload(gDoxm, &payload, &size, false))
1015 OIC_LOG(WARNING, TAG, "DoxmToCBORPayload failed in HandleDoxmGetRequest");
1019 OIC_LOG(DEBUG, TAG, "Send payload for doxm GET request");
1020 OIC_LOG_BUFFER(DEBUG, TAG, payload, size);
1022 // Send response payload to request originator
1023 ehRet = ((SendSRMResponse(ehRequest, ehRet, payload, size)) == OC_STACK_OK) ?
1024 OC_EH_OK : OC_EH_ERROR;
1031 static void updateWriteableProperty(const OicSecDoxm_t* src, OicSecDoxm_t* dst)
1036 dst->oxmSel = src->oxmSel;
1039 memcpy(&(dst->owner), &(src->owner), sizeof(OicUuid_t));
1042 memcpy(&(dst->rownerID), &(src->rownerID), sizeof(OicUuid_t));
1045 memcpy(&(dst->deviceID), &(src->deviceID), sizeof(OicUuid_t));
1047 //Update owned status
1048 if(dst->owned != src->owned)
1050 dst->owned = src->owned;
1053 #ifdef MULTIPLE_OWNER
1056 OIC_LOG(DEBUG, TAG, "dectected 'mom' property");
1057 if(NULL == dst->mom)
1059 dst->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
1060 if(NULL != dst->mom)
1062 dst->mom->mode = src->mom->mode;
1066 #endif //MULTIPLE_OWNER
1070 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1071 #ifdef MULTIPLE_OWNER
1073 * Internal function to get number of sub-owner
1075 static size_t GetSubOwnerSize()
1077 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
1079 size_t numberOfSubOwner = 0;
1081 if (gDoxm && gDoxm->subOwners)
1083 OicSecSubOwner_t* subowner = NULL;
1084 LL_FOREACH(gDoxm->subOwners, subowner)
1090 OIC_LOG_V(DEBUG, TAG, "Numer of registered sub-owner=%zd", numberOfSubOwner);
1091 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
1093 return numberOfSubOwner;
1097 * Callback function to handle MOT DTLS handshake result.
1098 * @param[out] endpoint remote device information.
1099 * @param[out] errorInfo CA Error information.
1101 void MultipleOwnerDTLSHandshakeCB(const CAEndpoint_t *endpoint,
1102 const CAErrorInfo_t *errorInfo)
1104 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
1105 if (!endpoint || !errorInfo)
1107 OIC_LOG(ERROR, TAG, "Invalid param");
1113 OIC_LOG_V(ERROR, TAG, "%s: gDoxm is NULL", __func__);
1117 if ((CA_STATUS_OK == errorInfo->result) && (true == gDoxm->owned)
1118 && (OIC_PRECONFIG_PIN == gDoxm->oxmSel) && (NULL != gDoxm->mom)
1119 && (OIC_MULTIPLE_OWNER_DISABLE != gDoxm->mom->mode) && (CA_ADAPTER_TCP != endpoint->adapter))
1121 OIC_LOG_V(INFO, TAG, "DTLS session established for sub-owner authentication : (%s:%d)",
1122 endpoint->addr, endpoint->port);
1124 const CASecureEndpoint_t* authenticatedSubOwnerInfo = CAGetSecureEndpointData(endpoint);
1125 if (authenticatedSubOwnerInfo)
1127 if (0 == memcmp(authenticatedSubOwnerInfo->identity.id, gDoxm->owner.id,
1128 authenticatedSubOwnerInfo->identity.id_length))
1130 OIC_LOG(WARNING, TAG, "Super owner tried MOT, this request will be ignored.");
1134 OicSecSubOwner_t* subOwnerInst = NULL;
1135 LL_FOREACH(gDoxm->subOwners, subOwnerInst)
1137 if(0 == memcmp(subOwnerInst->uuid.id,
1138 authenticatedSubOwnerInfo->identity.id,
1139 authenticatedSubOwnerInfo->identity.id_length))
1145 if (NULL == subOwnerInst)
1147 subOwnerInst = (OicSecSubOwner_t*)OICCalloc(1, sizeof(OicSecSubOwner_t));
1150 char* strUuid = NULL;
1151 if (OC_STACK_OK != ConvertUuidToStr(&subOwnerInst->uuid, &strUuid))
1153 OIC_LOG(WARNING, TAG, "ConvertUuidToStr error");
1155 OIC_LOG_V(DEBUG, TAG, "Adding New SubOwner(%s)", strUuid);
1157 if (gMaxSubOwnerSize > GetSubOwnerSize())
1159 memcpy(subOwnerInst->uuid.id, authenticatedSubOwnerInfo->identity.id,
1160 authenticatedSubOwnerInfo->identity.id_length);
1161 LL_APPEND(gDoxm->subOwners, subOwnerInst);
1162 if (!UpdatePersistentStorage(gDoxm))
1164 OIC_LOG(ERROR, TAG, "Failed to register SubOwner UUID into Doxm");
1169 OIC_LOG_V(ERROR, TAG, "Number of sub-owner exceeded : (MAX SIZE=%zd)", gMaxSubOwnerSize);
1171 //Close DTLS session
1172 if (CA_STATUS_OK != CAcloseSslSession(endpoint))
1174 OIC_LOG_V(ERROR, TAG, "CAcloseSslSession error for [%s:%d]", endpoint->addr, endpoint->port);
1178 if (OC_STACK_RESOURCE_DELETED != RemoveCredential(&subOwnerInst->uuid))
1180 OIC_LOG_V(ERROR, TAG, "RemoveCredential error for [%s]", strUuid);
1183 // TODO: How to send error to client side?
1192 if(CA_STATUS_OK != CAregisterPskCredentialsHandler(GetDtlsPskCredentials))
1194 OIC_LOG(WARNING, TAG, "Failed to revert the DTLS credential handler");
1197 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
1199 #endif //MULTIPLE_OWNER
1200 #endif // defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1203 * Function to validate oxmsel with oxms.
1205 * @param[in] supportedMethods Array of supported methods
1206 * @param[in] numberOfMethods number of supported methods
1207 * @param[out] selectedMethod Selected methods
1208 * @return TRUE on success
1210 static bool ValidateOxmsel(const OicSecOxm_t *supportedMethods,
1211 size_t numberOfMethods, OicSecOxm_t *selectedMethod)
1213 bool isValidOxmsel = false;
1215 OIC_LOG(DEBUG, TAG, "IN ValidateOxmsel");
1216 if (numberOfMethods == 0 || !supportedMethods)
1218 OIC_LOG(WARNING, TAG, "Could not find a supported OxM.");
1219 return isValidOxmsel;
1222 for (size_t i = 0; i < numberOfMethods; i++)
1224 if (*selectedMethod == supportedMethods[i])
1226 isValidOxmsel = true;
1232 OIC_LOG(ERROR, TAG, "Not allowed Oxmsel.");
1233 return isValidOxmsel;
1236 OIC_LOG(DEBUG, TAG, "OUT ValidateOxmsel");
1238 return isValidOxmsel;
1241 void SetInformOxmSelCB(InformOxmSelectedCallback_t informOxmSelCB)
1243 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
1244 g_InformOxmSelectedCallback = informOxmSelCB;
1245 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
1248 void UnsetInformOxmSelCB()
1250 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
1251 g_InformOxmSelectedCallback = NULL;
1252 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
1255 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1256 static OCEntityHandlerResult HandleDoxmPostRequest(OCEntityHandlerRequest * ehRequest);
1258 static void DestroyEntityHandlerRequest(OCEntityHandlerRequest * ehRequest)
1260 if (ehRequest == NULL) {
1261 OIC_LOG(WARNING, TAG, "ehRequest is NULL");
1265 OICFree(ehRequest->query);
1267 if (ehRequest->payload) {
1268 OICFree(((OCSecurityPayload *)ehRequest->payload)->securityData);
1269 OICFree(ehRequest->payload);
1275 void * WaitConfirm(OCEntityHandlerRequest * ehRequest)
1277 bool confirmResult = false, confirmState = false;
1279 oc_mutex_lock(g_mutexWait);
1280 oc_cond_wait(g_condWait, g_mutexWait);
1281 oc_cond_free(g_condWait);
1284 oc_mutex_unlock(g_mutexWait);
1285 oc_mutex_free(g_mutexWait);
1288 g_isConfirmResult = true;
1289 GetAsyncVerifyUserResult(&confirmResult, &confirmState);
1290 if (confirmResult == true)
1292 gConfirmState = CONFIRM_STATE_ACCEPTED;
1293 HandleDoxmPostRequest(ehRequest);
1294 g_isConfirmResult = false;
1298 gConfirmState = CONFIRM_STATE_DENIED;
1299 HandleDoxmPostRequest(ehRequest);
1300 g_isConfirmResult = false;
1303 DestroyEntityHandlerRequest(ehRequest);
1308 static OCEntityHandlerRequest *CopyRequest(OCEntityHandlerRequest *entityHandlerRequest)
1310 OIC_LOG(INFO, TAG, "Copying received request for slow response");
1312 if (!entityHandlerRequest)
1314 OIC_LOG_V(ERROR, TAG, "%s: entityHandlerRequest is NULL", __func__);
1318 OCEntityHandlerRequest *copyOfRequest =
1319 (OCEntityHandlerRequest *)OICCalloc(1, sizeof(OCEntityHandlerRequest));
1322 OIC_LOG(ERROR, TAG, "Copy failed due to allocation failure");
1326 memcpy(copyOfRequest, entityHandlerRequest, sizeof(OCEntityHandlerRequest));
1328 if (entityHandlerRequest->query)
1330 copyOfRequest->query = OICStrdup(entityHandlerRequest->query);
1331 if(!copyOfRequest->query)
1333 OIC_LOG(ERROR, TAG, "Copy failed due to allocation failure");
1334 OICFree(copyOfRequest);
1339 if (entityHandlerRequest->payload)
1341 copyOfRequest->payload =
1342 (OCSecurityPayload *)OICCalloc(1, sizeof(OCSecurityPayload));
1343 if(!copyOfRequest->payload)
1345 OIC_LOG(ERROR, TAG, "Copy failed due to allocation failure");
1346 OICFree(copyOfRequest->query);
1347 OICFree(copyOfRequest);
1351 if (((OCSecurityPayload *)entityHandlerRequest->payload)->payloadSize)
1353 ((OCSecurityPayload *)copyOfRequest->payload)->securityData =
1354 (uint8_t *)OICCalloc(1, ((OCSecurityPayload *)entityHandlerRequest->payload)->payloadSize);
1355 if(!((OCSecurityPayload *)copyOfRequest->payload)->securityData)
1357 OIC_LOG(ERROR, TAG, "Copy failed due to allocation failure");
1358 OICFree(copyOfRequest->payload);
1359 OICFree(copyOfRequest->query);
1360 OICFree(copyOfRequest);
1364 memcpy(((OCSecurityPayload *)copyOfRequest->payload)->securityData,
1365 ((OCSecurityPayload *)entityHandlerRequest->payload)->securityData,
1366 ((OCSecurityPayload *)entityHandlerRequest->payload)->payloadSize);
1368 ((OCSecurityPayload *)(copyOfRequest->payload))->payloadSize =
1369 ((OCSecurityPayload *)(entityHandlerRequest->payload))->payloadSize;
1372 copyOfRequest->payload->type = entityHandlerRequest->payload->type;
1373 copyOfRequest->messageID = entityHandlerRequest->messageID;
1376 // Ignore vendor specific header options for example
1377 copyOfRequest->numRcvdVendorSpecificHeaderOptions = 0;
1378 copyOfRequest->rcvdVendorSpecificHeaderOptions = NULL;
1380 OIC_LOG(INFO, TAG, "Copied client request");
1382 return copyOfRequest;
1384 #endif // defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1386 static OCEntityHandlerResult HandleDoxmPostRequest(OCEntityHandlerRequest * ehRequest)
1388 OIC_LOG (DEBUG, TAG, "Doxm EntityHandle processing POST request");
1389 OCEntityHandlerResult ehRet = OC_EH_ERROR;
1390 OicUuid_t emptyOwner = {.id = {0} };
1391 static uint16_t previousMsgId = 0;
1392 bool isDuplicatedMsg = false;
1395 * Convert CBOR Doxm data into binary. This will also validate
1396 * the Doxm data received.
1398 OicSecDoxm_t *newDoxm = NULL;
1400 if (ehRequest->payload)
1402 uint8_t *payload = ((OCSecurityPayload *)ehRequest->payload)->securityData;
1403 size_t size = ((OCSecurityPayload *)ehRequest->payload)->payloadSize;
1404 bool roParsed = false;
1405 OCStackResult res = CBORPayloadToDoxmBin(payload, size, &newDoxm, &roParsed);
1406 if (newDoxm && OC_STACK_OK == res)
1409 * message ID is supported for CoAP over UDP only according to RFC 7252
1410 * So we should check message ID to prevent duplicate request handling in case of OC_ADAPTER_IP.
1411 * In case of other transport adapter, duplicate message check is not required.
1413 if (OC_ADAPTER_IP == ehRequest->devAddr.adapter &&
1414 previousMsgId == ehRequest->messageID && g_isConfirmResult == false)
1416 isDuplicatedMsg = true;
1419 if (isDuplicatedMsg && ehRequest->messageID == gConfirmMsgId)
1421 if (CONFIRM_STATE_WAIT == gConfirmState)
1423 OIC_LOG(DEBUG, TAG, "Confirm callback already invoked.");
1424 OIC_LOG(DEBUG, TAG, "This request will be ignored.");
1425 DeleteDoxmBinData(newDoxm);
1430 OIC_LOG_V(DEBUG, TAG, "Confirm request already done, Confirm Result = %s", (CONFIRM_STATE_ACCEPTED == gConfirmState ? "ACCEPTED" : "DENIED"));
1431 ehRet = (CONFIRM_STATE_ACCEPTED == gConfirmState ? OC_EH_OK : OC_EH_NOT_ACCEPTABLE);
1436 // Check request on RO property
1437 if (true == roParsed)
1439 OIC_LOG(ERROR, TAG, "Not acceptable request because of read-only propertys");
1440 ehRet = OC_EH_NOT_ACCEPTABLE;
1444 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
1447 if (true == gDoxm->owned)
1449 if (false == ValidateOxmsel(gDoxm->oxm, gDoxm->oxmLen, &newDoxm->oxmSel))
1451 OIC_LOG(ERROR, TAG, "Not acceptable request because oxmsel does not support on Server");
1452 ehRet = OC_EH_NOT_ACCEPTABLE;
1456 if(0 != memcmp(&gDoxm->owner.id, &newDoxm->owner.id, sizeof(gDoxm->owner.id)))
1458 OIC_LOG(ERROR, TAG, "Not acceptable request for owned property");
1459 ehRet = OC_EH_NOT_ACCEPTABLE;
1462 //Update gDoxm based on newDoxm
1463 updateWriteableProperty(newDoxm, gDoxm);
1465 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1466 #ifdef MULTIPLE_OWNER
1470 if(OIC_MULTIPLE_OWNER_DISABLE != gDoxm->mom->mode)
1472 CAResult_t caRes = CA_STATUS_FAILED;
1473 if(OIC_PRECONFIG_PIN == gDoxm->oxmSel || OIC_RANDOM_DEVICE_PIN == gDoxm->oxmSel)
1475 caRes = CAEnableAnonECDHCipherSuite(false);
1476 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1477 OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1479 caRes = CASelectCipherSuite((uint16_t)MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, ehRequest->devAddr.adapter);
1480 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1481 OIC_LOG(INFO, TAG, "ECDHE_PSK CipherSuite will be used for MOT");
1483 //Set the device id to derive temporal PSK
1484 SetUuidForPinBasedOxm(&gDoxm->deviceID);
1488 OIC_LOG(WARNING, TAG, "Unsupported OxM for Multiple Ownership Transfer.");
1491 CAregisterSslHandshakeCallback(MultipleOwnerDTLSHandshakeCB);
1495 //if MOM is disabled, revert the DTLS handshake callback
1496 if(CA_STATUS_OK != CAregisterSslHandshakeCallback(NULL))
1498 OIC_LOG(WARNING, TAG, "Error while revert the DTLS Handshake Callback.");
1503 if(newDoxm->subOwners)
1505 OicSecSubOwner_t* subowner = NULL;
1506 OicSecSubOwner_t* temp = NULL;
1508 OIC_LOG(DEBUG, TAG, "dectected 'subowners' property");
1510 if(gDoxm->subOwners)
1512 LL_FOREACH_SAFE(gDoxm->subOwners, subowner, temp)
1514 LL_DELETE(gDoxm->subOwners, subowner);
1521 LL_FOREACH_SAFE(newDoxm->subOwners, subowner, temp)
1523 LL_DELETE(newDoxm->subOwners, subowner);
1524 LL_APPEND(gDoxm->subOwners, subowner);
1527 #endif //MULTIPLE_OWNER
1528 #endif // defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1530 //Update new state in persistent storage
1531 if (UpdatePersistentStorage(gDoxm) == true)
1537 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1538 ehRet = OC_EH_ERROR;
1544 if ((false == gDoxm->owned) && (false == newDoxm->owned))
1546 if (false == ValidateOxmsel(gDoxm->oxm, gDoxm->oxmLen, &newDoxm->oxmSel))
1548 OIC_LOG(ERROR, TAG, "Not acceptable request because oxmsel does not support on Server");
1549 ehRet = OC_EH_NOT_ACCEPTABLE;
1552 if (g_InformOxmSelectedCallback)
1554 g_InformOxmSelectedCallback(newDoxm->oxmSel);
1557 #if defined (__WITH_TLS__) || defined(__WITH_DTLS__)
1558 if (memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
1560 InvokeOtmEventHandler(ehRequest->devAddr.addr, ehRequest->devAddr.port,
1561 NULL, OIC_OTM_STARTED);
1565 OIC_LOG_V(INFO, TAG, "%s: request owner not empty",__func__);
1566 char* strUuid = NULL;
1567 if (OC_STACK_OK == ConvertUuidToStr(&newDoxm->owner, &strUuid))
1569 OIC_LOG_V(INFO, TAG, "%s: request owner: %s",__func__, strUuid);
1575 if (OIC_JUST_WORKS == newDoxm->oxmSel || OIC_MV_JUST_WORKS == newDoxm->oxmSel)
1578 * If current state of the device is un-owned, enable
1579 * anonymous ECDH cipher in tinyDTLS so that Provisioning
1580 * tool can initiate JUST_WORKS ownership transfer process.
1582 if (memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
1584 gDoxm->oxmSel = newDoxm->oxmSel;
1585 //Update new state in persistent storage
1586 if ((UpdatePersistentStorage(gDoxm) == true))
1592 OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
1593 ehRet = OC_EH_ERROR;
1596 OIC_LOG (INFO, TAG, "Doxm EntityHandle enabling AnonECDHCipherSuite");
1597 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1598 ehRet = (CAEnableAnonECDHCipherSuite(true) == CA_STATUS_OK) ? OC_EH_OK : OC_EH_ERROR;
1599 #endif // __WITH_DTLS__ or __WITH_TLS__
1604 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1605 //Save the owner's UUID to derive owner credential
1606 memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
1608 // Update new state in persistent storage
1609 if (true == UpdatePersistentStorage(gDoxm))
1615 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1616 ehRet = OC_EH_ERROR;
1621 * Disable anonymous ECDH cipher in tinyDTLS since device is now
1624 CAResult_t caRes = CA_STATUS_OK;
1625 caRes = CAEnableAnonECDHCipherSuite(false);
1626 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1627 OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1629 //In case of Mutual Verified Just-Works, verify mutualVerifNum
1630 if (OIC_MV_JUST_WORKS == newDoxm->oxmSel && false == newDoxm->owned &&
1631 false == isDuplicatedMsg)
1633 uint8_t preMutualVerifNum[OWNER_PSK_LENGTH_128] = {0};
1634 uint8_t mutualVerifNum[MUTUAL_VERIF_NUM_LEN] = {0};
1635 OicUuid_t deviceID = {.id = {0}};
1637 //Generate mutualVerifNum
1638 OCServerRequest * request = GetServerRequestUsingHandle(ehRequest->requestHandle);
1640 char label[LABEL_LEN] = {0};
1641 snprintf(label, LABEL_LEN, "%s%s", MUTUAL_VERIF_NUM, OXM_MV_JUST_WORKS);
1642 if (OC_STACK_OK != GetDoxmDeviceID(&deviceID))
1644 OIC_LOG(ERROR, TAG, "Error while retrieving Owner's device ID");
1645 ehRet = OC_EH_ERROR;
1650 CAResult_t pskRet = CAGenerateOwnerPSK((CAEndpoint_t *)&request->devAddr,
1653 gDoxm->owner.id, sizeof(gDoxm->owner.id),
1654 gDoxm->deviceID.id, sizeof(gDoxm->deviceID.id),
1655 preMutualVerifNum, OWNER_PSK_LENGTH_128);
1656 if (CA_STATUS_OK != pskRet)
1658 OIC_LOG(WARNING, TAG, "Failed to remove the invaild owner credential");
1659 ehRet = OC_EH_ERROR;
1664 memcpy(mutualVerifNum, preMutualVerifNum + OWNER_PSK_LENGTH_128 - sizeof(mutualVerifNum),
1665 sizeof(mutualVerifNum));
1667 gConfirmMsgId = ehRequest->messageID;
1668 gConfirmState = CONFIRM_STATE_WAIT;
1669 //Wait for user confirmation
1670 if (OC_STACK_OK != VerifyOwnershipTransfer(mutualVerifNum, DISPLAY_NUM | USER_CONFIRM))
1672 ehRet = OC_EH_NOT_ACCEPTABLE;
1673 gConfirmState = CONFIRM_STATE_DENIED;
1678 gConfirmState = CONFIRM_STATE_ACCEPTED;
1682 #endif // __WITH_DTLS__ or __WITH_TLS__
1685 else if (OIC_RANDOM_DEVICE_PIN == newDoxm->oxmSel)
1688 * If current state of the device is un-owned, enable
1689 * anonymous ECDH cipher in tinyDTLS so that Provisioning
1690 * tool can initiate JUST_WORKS ownership transfer process.
1692 if(memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
1694 gDoxm->oxmSel = newDoxm->oxmSel;
1695 //Update new state in persistent storage
1696 if ((UpdatePersistentStorage(gDoxm) == true))
1702 OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
1703 ehRet = OC_EH_ERROR;
1706 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1707 CAResult_t caRes = CA_STATUS_OK;
1709 caRes = CAEnableAnonECDHCipherSuite(false);
1710 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1711 OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1713 caRes = CASelectCipherSuite(MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256,
1714 ehRequest->devAddr.adapter);
1715 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1717 if (!isDuplicatedMsg)
1719 char ranPin[OXM_RANDOM_PIN_MAX_SIZE + 1] = {0};
1720 if (OC_STACK_OK == GeneratePin(ranPin, sizeof(ranPin)))
1722 //Set the device id to derive temporal PSK
1723 SetUuidForPinBasedOxm(&gDoxm->deviceID);
1726 * Since PSK will be used directly by DTLS layer while PIN based ownership transfer,
1727 * Credential should not be saved into SVR.
1728 * For this reason, use a temporary get_psk_info callback to random PIN OxM.
1730 caRes = CAregisterPskCredentialsHandler(GetDtlsPskForRandomPinOxm);
1731 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1736 OIC_LOG(ERROR, TAG, "Failed to generate random PIN");
1737 ehRet = OC_EH_ERROR;
1740 #endif // __WITH_DTLS__ or __WITH_TLS__
1742 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1745 //Save the owner's UUID to derive owner credential
1746 memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
1748 // In case of random-pin based OTM, close the PIN display if callback is registered.
1749 if (!isDuplicatedMsg)
1754 //Update new state in persistent storage
1755 if (UpdatePersistentStorage(gDoxm) == true)
1761 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1762 ehRet = OC_EH_ERROR;
1765 #endif // __WITH_DTLS__ or __WITH_TLS__
1767 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1768 else if (OIC_MANUFACTURER_CERTIFICATE == newDoxm->oxmSel || OIC_CON_MFG_CERT == newDoxm->oxmSel)
1770 if (CONFIRM_STATE_ACCEPTED != gConfirmState && CONFIRM_STATE_DENIED != gConfirmState)
1772 //Get user confirmation
1773 if (false == newDoxm->owned &&
1774 false == isDuplicatedMsg &&
1775 memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) != 0)
1777 gConfirmMsgId = ehRequest->messageID;
1778 gConfirmState = CONFIRM_STATE_WAIT;
1780 if (OC_STACK_OK != VerifyUserConfirm())
1782 if (OC_STACK_OK != VerifyOwnershipTransfer(NULL, USER_CONFIRM))
1784 ehRet = OC_EH_NOT_ACCEPTABLE;
1785 gConfirmState = CONFIRM_STATE_DENIED;
1791 OCEntityHandlerRequest * ehRequestCopy = CopyRequest(ehRequest);
1792 VERIFY_NON_NULL(TAG, ehRequestCopy, ERROR);
1794 g_condWait = oc_cond_new();
1795 g_mutexWait = oc_mutex_new();
1796 if (oc_thread_new (&g_waitConfirmThreadId, WaitConfirm, ehRequestCopy))
1798 oc_thread_detach(g_waitConfirmThreadId);
1801 previousMsgId = ehRequest->messageID;
1807 else if (CONFIRM_STATE_DENIED == gConfirmState)
1809 ehRet = OC_EH_NOT_ACCEPTABLE;
1813 //Save the owner's UUID to derive owner credential
1814 memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
1815 gDoxm->oxmSel = newDoxm->oxmSel;
1816 //Update new state in persistent storage
1817 if (UpdatePersistentStorage(gDoxm))
1823 OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
1824 ehRet = OC_EH_ERROR;
1826 CAResult_t caRes = CAEnableAnonECDHCipherSuite(false);
1827 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1828 OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1830 //Unset pre-selected ciphersuite, if any
1831 caRes = CASelectCipherSuite(0, ehRequest->devAddr.adapter);
1832 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1833 OIC_LOG(DEBUG, TAG, "No ciphersuite preferred");
1835 VERIFY_SUCCESS(TAG, CA_STATUS_OK == CAregisterPkixInfoHandler(GetManufacturerPkixInfo), ERROR);
1836 VERIFY_SUCCESS(TAG, CA_STATUS_OK == CAregisterGetCredentialTypesHandler(InitManufacturerCipherSuiteList), ERROR);
1838 #endif // __WITH_DTLS__ or __WITH_TLS__
1842 * When current state of the device is un-owned and Provisioning
1843 * Tool is attempting to change the state to 'Owned' with a
1844 * qualified value for the field 'Owner'
1846 if ((false == gDoxm->owned) && (true == newDoxm->owned) &&
1847 (memcmp(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t)) == 0))
1849 //Change the SVR's resource owner as owner device.
1850 OCStackResult ownerRes = SetAclRownerId(&gDoxm->owner);
1851 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1853 ehRet = OC_EH_ERROR;
1856 ownerRes = SetAmaclRownerId(&gDoxm->owner);
1857 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1859 ehRet = OC_EH_ERROR;
1862 ownerRes = SetCredRownerId(&gDoxm->owner);
1863 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1865 ehRet = OC_EH_ERROR;
1868 ownerRes = SetPstatRownerId(&gDoxm->owner);
1869 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1871 ehRet = OC_EH_ERROR;
1875 gDoxm->owned = true;
1876 memcpy(&gDoxm->rownerID, &gDoxm->owner, sizeof(OicUuid_t));
1878 // Update new state in persistent storage
1879 if (UpdatePersistentStorage(gDoxm))
1881 //Update default ACE of security resource to prevent anonymous user access.
1882 if(OC_STACK_OK == UpdateDefaultSecProvACE())
1888 OIC_LOG(ERROR, TAG, "Failed to remove default ACL for security provisioning");
1889 ehRet = OC_EH_ERROR;
1894 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1895 ehRet = OC_EH_ERROR;
1897 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1898 if (OIC_MANUFACTURER_CERTIFICATE == gDoxm->oxmSel ||
1899 OIC_CON_MFG_CERT== gDoxm->oxmSel)
1901 CAregisterPkixInfoHandler(GetPkixInfo);
1902 CAregisterGetCredentialTypesHandler(InitCipherSuiteList);
1905 InvokeOtmEventHandler(ehRequest->devAddr.addr, ehRequest->devAddr.port,
1906 &gDoxm->owner, OIC_OTM_DONE);
1907 #endif // __WITH_DTLS__ or __WITH_TLS__
1913 if(OC_EH_OK != ehRet)
1916 * If some error is occured while ownership transfer,
1917 * ownership transfer related resource should be revert back to initial status.
1923 OIC_LOG(WARNING, TAG, "The operation failed during handle DOXM request");
1925 if (!isDuplicatedMsg)
1927 #if defined (__WITH_TLS__) || defined(__WITH_DTLS__)
1928 InvokeOtmEventHandler(ehRequest->devAddr.addr, ehRequest->devAddr.port,
1929 NULL, OIC_OTM_ERROR);
1931 ResetSecureResourceInPS();
1932 OIC_LOG(WARNING, TAG, "DOXM will be reverted.");
1938 OIC_LOG(ERROR, TAG, "Invalid DOXM resource.");
1942 previousMsgId = ehRequest->messageID;
1944 #if defined (__WITH_TLS__) || defined(__WITH_DTLS__)
1945 CAEndpoint_t peer = {0};
1946 OCDevAddr devAddr = ehRequest->devAddr;
1948 memcpy(&peer.addr, &devAddr.addr, sizeof(peer.addr));
1949 peer.port = devAddr.port;
1950 peer.adapter = (CATransportAdapter_t)devAddr.adapter;
1952 if ((devAddr.flags & OC_FLAG_SECURE) && (false == CAIsExistSslPeer(&peer)))
1954 OIC_LOG_V(WARNING, TAG, "Not Exist Peer");
1959 //Send payload to request originator
1960 ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1961 OC_EH_OK : OC_EH_ERROR;
1964 //Send payload to request originator
1965 ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1966 OC_EH_OK : OC_EH_ERROR;
1969 DeleteDoxmBinData(newDoxm);
1974 #ifdef MULTIPLE_OWNER
1975 static OCEntityHandlerResult HandleDoxmDeleteRequest(const OCEntityHandlerRequest *ehRequest)
1977 OIC_LOG(DEBUG, TAG, "Processing DoxmDeleteRequest");
1979 OCEntityHandlerResult ehRet = OC_EH_BAD_REQ;
1981 if (NULL == ehRequest->query)
1986 OicParseQueryIter_t parseIter = { .attrPos=NULL };
1987 OicUuid_t subject = {.id={0}};
1989 //Parsing REST query to get the subject
1990 ParseQueryIterInit((unsigned char *)ehRequest->query, &parseIter);
1991 while (GetNextQuery(&parseIter))
1993 if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_SUBOWNERID_NAME,
1994 parseIter.attrLen) == 0)
1996 if (0 == strncmp((const char*)parseIter.valPos, WILDCARD_RESOURCE_URI,
1997 strlen(WILDCARD_RESOURCE_URI)))
1999 if(OC_STACK_RESOURCE_DELETED == RemoveSubOwner(&WILDCARD_SUBJECT_ID))
2001 ehRet = OC_EH_RESOURCE_DELETED;
2006 OCStackResult ret = ConvertStrToUuid((const char*)parseIter.valPos, &subject);
2007 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
2009 if(OC_STACK_RESOURCE_DELETED == RemoveSubOwner(&subject))
2011 ehRet = OC_EH_RESOURCE_DELETED;
2017 //Send response to request originator
2018 ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
2019 OC_EH_OK : OC_EH_ERROR;
2025 #endif //MULTIPLE_OWNER
2027 OCEntityHandlerResult DoxmEntityHandler(OCEntityHandlerFlag flag,
2028 OCEntityHandlerRequest * ehRequest,
2029 void* callbackParam)
2031 (void)callbackParam;
2032 OCEntityHandlerResult ehRet = OC_EH_ERROR;
2034 if(NULL == ehRequest)
2039 oc_mutex_lock(g_mutexDoxm);
2043 oc_mutex_unlock(g_mutexDoxm);
2044 return OC_EH_SERVICE_UNAVAILABLE;
2047 if (flag & OC_REQUEST_FLAG)
2049 OIC_LOG(DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
2051 switch (ehRequest->method)
2054 ehRet = HandleDoxmGetRequest(ehRequest);
2058 ehRet = HandleDoxmPostRequest(ehRequest);
2061 #ifdef MULTIPLE_OWNER
2062 case OC_REST_DELETE:
2063 ehRet = HandleDoxmDeleteRequest(ehRequest);
2065 #endif //MULTIPLE_OWNER
2068 ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
2069 OC_EH_OK : OC_EH_ERROR;
2073 oc_mutex_unlock(g_mutexDoxm);
2079 OCStackResult CreateDoxmResource()
2081 OCStackResult ret = OCCreateResource(&gDoxmHandle,
2082 OIC_RSRC_TYPE_SEC_DOXM,
2083 OC_RSRVD_INTERFACE_DEFAULT,
2090 if (OC_STACK_OK != ret)
2092 OIC_LOG (FATAL, TAG, "Unable to instantiate Doxm resource");
2093 DeInitDoxmResource();
2099 * Checks if DeviceID is generated during provisioning for the new device.
2100 * If DeviceID is NULL then generates the new DeviceID.
2101 * Once DeviceID is assigned to the device it does not change for the lifetime of the device.
2103 static OCStackResult CheckDeviceID()
2105 OIC_LOG_V(DEBUG, TAG, "IN: %s", __func__);
2107 OCStackResult ret = OC_STACK_ERROR;
2108 bool validId = false;
2112 OIC_LOG_V(ERROR, TAG, "%s: gDoxm is NULL", __func__);
2113 return OC_STACK_INVALID_PARAM;
2116 for (uint8_t i = 0; i < UUID_LENGTH; i++)
2118 if (gDoxm->deviceID.id[i] != 0)
2127 char* strUuid = NULL;
2128 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
2129 //If seed value is exist, generate UUID using seed with SHA256
2130 if (0 != gUuidSeedSize)
2132 uint8_t hashVal[MBEDTLS_MD_MAX_SIZE] = {0};
2133 mbedtls_md_context_t sha_ctx;
2136 OIC_LOG(DEBUG, TAG, "UUID will be generated using seed w/ SHA256");
2137 OIC_LOG(DEBUG, TAG, "Seed value : ");
2138 OIC_LOG_BUFFER(DEBUG, TAG, gUuidSeed, gUuidSeedSize);
2140 mbedtls_md_init( &sha_ctx );
2141 mbedret = mbedtls_md_setup( &sha_ctx, mbedtls_md_info_from_type( MBEDTLS_MD_SHA256 ), 1 );
2144 mbedtls_md_starts( &sha_ctx );
2145 mbedtls_md_update( &sha_ctx, gUuidSeed, gUuidSeedSize);
2146 mbedtls_md_finish(&sha_ctx, (unsigned char*)hashVal);
2147 memcpy(gDoxm->deviceID.id, hashVal, sizeof(gDoxm->deviceID.id));
2152 OIC_LOG_V(ERROR, TAG, "mbedtls_md_setup() returned -0x%04x\n", -mbedret);
2153 ret = OC_STACK_ERROR;
2155 mbedtls_md_free( &sha_ctx );
2159 if (RAND_UUID_OK != OCGenerateUuid(gDoxm->deviceID.id))
2161 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
2162 return OC_STACK_ERROR;
2167 if (RAND_UUID_OK != OCGenerateUuid(gDoxm->deviceID.id))
2169 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
2175 if (OC_STACK_OK == ConvertUuidToStr(&gDoxm->deviceID, &strUuid))
2177 OIC_LOG_V(DEBUG, TAG, "Generated device UUID is [%s]", strUuid);
2182 OIC_LOG(WARNING, TAG, "Failed to convert UUID to string");
2186 if (!UpdatePersistentStorage(gDoxm))
2188 //TODO: After registering PSI handler in all samples, do ret = OC_STACK_OK here.
2189 OIC_LOG(FATAL, TAG, "UpdatePersistentStorage failed!");
2197 OIC_LOG_V(DEBUG, TAG, "OUT: %s", __func__);
2203 * Get the default value.
2205 * @return the default value of doxm, @ref OicSecDoxm_t.
2207 static OicSecDoxm_t* GetDoxmDefault()
2209 OIC_LOG(DEBUG, TAG, "GetDoxmToDefault");
2210 return &gDefaultDoxm;
2213 const OicSecDoxm_t* GetDoxmResourceData()
2218 #if defined(__WITH_DTLS__) && defined(MULTIPLE_OWNER)
2220 * Internal API to prepare MOT
2222 static void PrepareMOT(const OicSecDoxm_t* doxm)
2224 OIC_LOG(INFO, TAG, "IN PrepareMOT");
2225 VERIFY_NON_NULL(TAG, doxm, ERROR);
2227 if(true == doxm->owned && NULL != doxm->mom && OIC_MULTIPLE_OWNER_DISABLE != doxm->mom->mode)
2229 CAResult_t caRes = CA_STATUS_FAILED;
2231 OIC_LOG(INFO, TAG, "Multiple Ownership Transfer Enabled!");
2233 if(OIC_PRECONFIG_PIN == doxm->oxmSel)
2235 caRes = CAEnableAnonECDHCipherSuite(false);
2236 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
2237 OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
2239 caRes = CASelectCipherSuite((uint16_t)MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, CA_ADAPTER_IP);
2240 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
2242 caRes = CASelectCipherSuite((uint16_t)MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, CA_ADAPTER_TCP);
2243 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
2245 OIC_LOG(INFO, TAG, "ECDHE_PSK CipherSuite will be used for MOT");
2247 //Set the device id to derive temporal PSK
2248 SetUuidForPinBasedOxm(&doxm->deviceID);
2252 OIC_LOG(ERROR, TAG, "Unsupported OxM for Multiple Ownership Transfer.");
2256 CAregisterSslHandshakeCallback(MultipleOwnerDTLSHandshakeCB);
2259 OIC_LOG(INFO, TAG, "OUT PrepareMOT");
2262 OIC_LOG(WARNING, TAG, "Error in PrepareMOT");
2264 #endif //defined(__WITH_DTLS__) && defined(MULTIPLE_OWNER)
2266 OCStackResult InitDoxmResource()
2268 OCStackResult ret = OC_STACK_ERROR;
2272 g_mutexDoxm = oc_mutex_new();
2275 return OC_STACK_ERROR;
2279 gConfirmState = CONFIRM_STATE_READY;
2282 //Read DOXM resource from PS
2283 uint8_t *data = NULL;
2285 ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_DOXM_NAME, &data, &size);
2286 // If database read failed
2287 if (OC_STACK_OK != ret)
2289 OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
2293 // Read DOXM resource from PS
2294 ret = CBORPayloadToDoxm(data, size, &gDoxm);
2297 * If SVR database in persistent storage got corrupted or
2298 * is not available for some reason, a default doxm is created
2299 * which allows user to initiate doxm provisioning again.
2301 if ((OC_STACK_OK != ret) || !data || !gDoxm)
2303 gDoxm = GetDoxmDefault();
2306 oc_mutex_lock(g_mutexDoxm);
2307 g_isDoxmNull = false;
2308 oc_mutex_unlock(g_mutexDoxm);
2310 //In case of the server is shut down unintentionally, we should initialize the owner
2311 if(gDoxm && (false == gDoxm->owned))
2313 OicUuid_t emptyUuid = {.id={0}};
2314 memcpy(&gDoxm->owner, &emptyUuid, sizeof(OicUuid_t));
2315 #if defined (__WITH_TLS__) || defined(__WITH_DTLS__)
2316 InvokeOtmEventHandler(NULL, 0, NULL, OIC_OTM_READY);
2320 ret = CheckDeviceID();
2321 if (ret == OC_STACK_OK)
2323 OIC_LOG_V(DEBUG, TAG, "Initial Doxm Owned = %d", gDoxm->owned);
2324 //Instantiate 'oic.sec.doxm'
2325 ret = CreateDoxmResource();
2329 OIC_LOG (ERROR, TAG, "CheckDeviceID failed");
2333 #if defined(__WITH_DTLS__) && defined(MULTIPLE_OWNER)
2334 //if MOT is enabled, MOT should be prepared.
2335 if(gDoxm && gDoxm->owned)
2339 #endif // defined(__WITH_DTLS__) && defined(MULTIPLE_OWNER)
2344 OCStackResult DeInitDoxmResource()
2346 oc_mutex_lock(g_mutexDoxm);
2347 OCStackResult ret = OCDeleteResource(gDoxmHandle);
2348 if (gDoxm != &gDefaultDoxm)
2350 DeleteDoxmBinData(gDoxm);
2353 g_isDoxmNull = true;
2355 if (OC_STACK_OK == ret)
2357 oc_mutex_unlock(g_mutexDoxm);
2362 oc_mutex_unlock(g_mutexDoxm);
2363 return OC_STACK_ERROR;
2367 OCStackResult GetDoxmDeviceID(OicUuid_t *deviceID)
2369 if (deviceID && gDoxm)
2371 *deviceID = gDoxm->deviceID;
2374 return OC_STACK_ERROR;
2377 OCStackResult GetDoxmIsOwned(bool *isOwned)
2379 OIC_LOG_V(INFO, TAG, "In %s", __func__);
2380 if (isOwned && gDoxm)
2382 *isOwned = gDoxm->owned;
2383 OIC_LOG_V(INFO, TAG, "isOwned - %s", *isOwned ? "true" : "false");
2384 OIC_LOG_V(INFO, TAG, "Out %s", __func__);
2387 return OC_STACK_ERROR;
2390 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
2391 OCStackResult SetDoxmDeviceIDSeed(const uint8_t* seed, size_t seedSize)
2393 OIC_LOG_V(INFO, TAG, "In %s", __func__);
2397 return OC_STACK_INVALID_PARAM;
2399 if (MAX_UUID_SEED_SIZE < seedSize)
2401 OIC_LOG_V(ERROR, TAG, "Seed size is too long (MAX size is %d bytes)", MAX_UUID_SEED_SIZE);
2402 return OC_STACK_INVALID_PARAM;
2404 if (MIN_UUID_SEED_SIZE > seedSize)
2406 OIC_LOG_V(ERROR, TAG, "Seed size is too small (MIN size is %d bytes)", MIN_UUID_SEED_SIZE);
2407 return OC_STACK_INVALID_PARAM;
2410 memset(gUuidSeed, 0x00, sizeof(gUuidSeed));
2411 memcpy(gUuidSeed, seed, seedSize);
2412 gUuidSeedSize = seedSize;
2414 OIC_LOG_V(INFO, TAG, "Out %s", __func__);
2421 OCStackResult SetDoxmDeviceID(const OicUuid_t *deviceID)
2423 bool isOwnerUpdated = false;
2424 bool isRownerUpdated = false;
2425 if (NULL == deviceID)
2427 return OC_STACK_INVALID_PARAM;
2431 OIC_LOG(ERROR, TAG, "Doxm resource is not initialized.");
2432 return OC_STACK_NO_RESOURCE;
2435 #ifdef __WITH_DTLS__
2436 //for normal device.
2437 if (true == gDoxm->owned
2438 && memcmp(gEmptyUuid, gDoxm->owner.id, sizeof(gDoxm->owner.id)) != 0
2439 && memcmp(gDoxm->deviceID.id, gDoxm->owner.id, sizeof(gDoxm->owner.id)) != 0)
2441 OIC_LOG(ERROR, TAG, "This device owned by owner's device.");
2442 OIC_LOG(ERROR, TAG, "Device UUID cannot be changed to guarantee the reliability of the connection.");
2443 return OC_STACK_ERROR;
2445 #endif //__WITH_DTLS
2447 //Save the previous UUID
2449 memcpy(prevUuid.id, gDoxm->deviceID.id, sizeof(prevUuid.id));
2451 //Change the device UUID
2452 memcpy(gDoxm->deviceID.id, deviceID->id, sizeof(deviceID->id));
2454 //Change the owner ID if necessary
2455 if (memcmp(gDoxm->owner.id, prevUuid.id, sizeof(prevUuid.id)) == 0)
2457 memcpy(gDoxm->owner.id, deviceID->id, sizeof(deviceID->id));
2458 isOwnerUpdated = true;
2460 //Change the resource owner ID if necessary
2461 if (memcmp(gDoxm->rownerID.id, prevUuid.id, sizeof(prevUuid.id)) == 0)
2463 memcpy(gDoxm->rownerID.id, deviceID->id, sizeof(deviceID->id));
2464 isRownerUpdated = true;
2466 // TODO: T.B.D Change resource owner for pstat, acl and cred
2469 if (!UpdatePersistentStorage(gDoxm))
2471 //revert UUID in case of PSI error
2472 memcpy(gDoxm->deviceID.id, prevUuid.id, sizeof(prevUuid.id));
2475 memcpy(gDoxm->owner.id, prevUuid.id, sizeof(prevUuid.id));
2477 if (isRownerUpdated)
2479 memcpy(gDoxm->rownerID.id, prevUuid.id, sizeof(prevUuid.id));
2481 // TODO: T.B.D Revert resource owner for pstat, acl and cred
2483 OIC_LOG(ERROR, TAG, "Failed to update persistent storage");
2484 return OC_STACK_ERROR;
2489 OCStackResult GetDoxmDevOwnerId(OicUuid_t *devownerid)
2491 OCStackResult retVal = OC_STACK_ERROR;
2494 OIC_LOG_V(DEBUG, TAG, "GetDoxmDevOwnerId(): gDoxm owned = %d.", \
2498 *devownerid = gDoxm->owner;
2499 retVal = OC_STACK_OK;
2505 OCStackResult GetDoxmRownerId(OicUuid_t *rowneruuid)
2507 OCStackResult retVal = OC_STACK_ERROR;
2510 // if( gDoxm->owned )
2512 *rowneruuid = gDoxm->rownerID;
2513 retVal = OC_STACK_OK;
2519 #ifdef MULTIPLE_OWNER
2521 * Compare the UUID to SubOwner.
2523 * @param[in] uuid device UUID
2525 * @return true if context->subjectId exist subowner list, else false.
2527 bool IsSubOwner(const OicUuid_t* uuid)
2529 bool retVal = false;
2536 if (gDoxm && gDoxm->subOwners)
2538 if (memcmp(gDoxm->owner.id, uuid->id, sizeof(gDoxm->owner.id)) == 0)
2543 OicSecSubOwner_t* subOwner = NULL;
2544 LL_FOREACH(gDoxm->subOwners, subOwner)
2546 if (memcmp(subOwner->uuid.id, uuid->id, sizeof(uuid->id)) == 0)
2554 #endif //MULTIPLE_OWNER
2556 OCStackResult SetMOTStatus(bool enable)
2558 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
2559 #ifdef MULTIPLE_OWNER
2560 OCStackResult ret = OC_STACK_NO_MEMORY;
2561 uint8_t *cborPayload = NULL;
2563 bool isDeallocateRequired = false;
2565 VERIFY_NON_NULL(TAG, gDoxm, ERROR);
2567 if (NULL == gDoxm->mom && !enable)
2569 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2573 if (NULL == gDoxm->mom)
2575 gDoxm->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
2576 VERIFY_NON_NULL(TAG, gDoxm->mom, ERROR);
2577 isDeallocateRequired = true;
2580 gDoxm->mom->mode = (enable ? OIC_MULTIPLE_OWNER_ENABLE : OIC_MULTIPLE_OWNER_DISABLE);
2581 gDoxm->oxmSel = OIC_PRECONFIG_PIN;
2583 ret = DoxmToCBORPayload(gDoxm, &cborPayload, &size, false);
2584 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
2586 ret = UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, cborPayload, size);
2587 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
2589 isDeallocateRequired = false;
2592 if (isDeallocateRequired)
2594 OICFree(gDoxm->mom);
2598 OICFree(cborPayload);
2600 OIC_LOG_V(DEBUG, TAG, "Out %s : %d", __func__, ret);
2604 OIC_LOG(DEBUG, TAG, "Multiple Owner is not enabled.");
2605 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2606 return OC_STACK_ERROR;
2607 #endif //MULTIPLE_OWNER
2610 OCStackResult RemoveSubOwner(const OicUuid_t* subOwner)
2612 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
2613 #ifdef MULTIPLE_OWNER
2614 OCStackResult ret = OC_STACK_ERROR;
2615 bool isDeleted = false;
2617 if (NULL == subOwner)
2619 OIC_LOG(ERROR, TAG, "Invalid sub owner UUID.");
2620 return OC_STACK_INVALID_PARAM;
2624 OIC_LOG(ERROR, TAG, "Doxm resource is NULL");
2625 return OC_STACK_NO_RESOURCE;
2627 if ( NULL == gDoxm->subOwners)
2629 OIC_LOG(WARNING, TAG, "Sub Owner list is empty.");
2630 return OC_STACK_ERROR;
2633 OicSecSubOwner_t* curSubOwner = NULL;
2634 OicSecSubOwner_t* tempSubOwner = NULL;
2635 LL_FOREACH_SAFE(gDoxm->subOwners, curSubOwner, tempSubOwner)
2637 if (memcmp(curSubOwner->uuid.id, subOwner->id, sizeof(subOwner->id)) == 0 ||
2638 memcmp(WILDCARD_SUBJECT_ID.id, subOwner->id, sizeof(OicUuid_t)) == 0)
2640 char* strUuid = NULL;
2641 ret = ConvertUuidToStr(&curSubOwner->uuid, &strUuid);
2642 if (OC_STACK_OK != ret)
2644 OIC_LOG_V(ERROR, TAG, "ConvertUuidToStr error : %d", ret);
2648 OIC_LOG_V(INFO, TAG, "[%s] will be removed from sub owner list.", strUuid);
2649 LL_DELETE(gDoxm->subOwners, curSubOwner);
2651 //Remove the cred for sub owner
2652 ret = RemoveCredential(&curSubOwner->uuid);
2653 if (OC_STACK_RESOURCE_DELETED != ret)
2655 OIC_LOG_V(WARNING, TAG, "RemoveCredential error for [%s] : %d", strUuid, ret);
2659 // TODO: Remove the ACL for sub owner (Currently ACL is not required for sub-owner)
2669 //Update persistent storage
2670 if (UpdatePersistentStorage(gDoxm))
2672 ret = OC_STACK_RESOURCE_DELETED;
2676 OIC_LOG(ERROR, TAG, "UpdatePersistentStorage error");
2677 ret = OC_STACK_ERROR;
2681 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2684 OC_UNUSED(subOwner);
2685 OIC_LOG(DEBUG, TAG, "Multiple Owner is not enabled.");
2686 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2687 return OC_STACK_ERROR;
2688 #endif //MULTIPLE_OWNER
2692 OCStackResult SetNumberOfSubOwner(size_t numOfSubOwner)
2694 OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
2695 #ifdef MULTIPLE_OWNER
2696 if (MAX_SUBOWNER_SIZE < numOfSubOwner || MIN_SUBOWNER_SIZE > numOfSubOwner)
2698 OIC_LOG_V(ERROR, TAG, "Invalid number of sub owner : %zd", numOfSubOwner);
2699 return OC_STACK_INVALID_PARAM;
2701 gMaxSubOwnerSize = numOfSubOwner;
2702 OIC_LOG_V(DEBUG, TAG, "Number of SubOwner = %zd", gMaxSubOwnerSize);
2703 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2706 OC_UNUSED(numOfSubOwner);
2707 OIC_LOG(DEBUG, TAG, "Multiple Owner is not enabled.");
2708 OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2709 return OC_STACK_ERROR;
2710 #endif //MULTIPLE_OWNER
2714 * Function to restore doxm resurce to initial status.
2715 * This function will use in case of error while ownership transfer
2717 void RestoreDoxmToInitState()
2720 gConfirmState = CONFIRM_STATE_READY;
2725 OIC_LOG(INFO, TAG, "DOXM resource will revert back to initial status.");
2727 OicUuid_t emptyUuid = {.id={0}};
2728 memcpy(&(gDoxm->owner), &emptyUuid, sizeof(OicUuid_t));
2729 gDoxm->owned = false;
2730 gDoxm->oxmSel = OIC_JUST_WORKS;
2732 if(!UpdatePersistentStorage(gDoxm))
2734 OIC_LOG(ERROR, TAG, "Failed to revert DOXM in persistent storage");
2739 OCStackResult SetDoxmSelfOwnership(const OicUuid_t* newROwner)
2741 OCStackResult ret = OC_STACK_ERROR;
2742 uint8_t *cborPayload = NULL;
2747 ret = OC_STACK_NO_RESOURCE;
2751 if( newROwner && (false == gDoxm->owned) )
2753 gDoxm->owned = true;
2754 memcpy(gDoxm->owner.id, newROwner->id, sizeof(newROwner->id));
2755 memcpy(gDoxm->rownerID.id, newROwner->id, sizeof(newROwner->id));
2757 ret = DoxmToCBORPayload(gDoxm, &cborPayload, &size, false);
2758 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
2760 ret = UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, cborPayload, size);
2761 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
2763 OICFree(cborPayload);
2769 OICFree(cborPayload);