[IOT-1601]Adding logic to validate oxmsel updationg in owned=true
[platform/upstream/iotivity.git] / resource / csdk / security / src / doxmresource.c
1 //******************************************************************
2 //
3 // Copyright 2015 Intel Mobile Communications GmbH All Rights Reserved.
4 //
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
6 //
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
10 //
11 //      http://www.apache.org/licenses/LICENSE-2.0
12 //
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.
18 //
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
20 #include "iotivity_config.h"
21 #include <stdlib.h>
22 #include <string.h>
23
24 #ifdef HAVE_STRINGS_H
25 #include <strings.h>
26 #endif
27
28 #ifdef __WITH_DTLS__
29 #include "global.h"
30 #endif
31
32 #include "ocstack.h"
33 #include "oic_malloc.h"
34 #include "payload_logging.h"
35 #include "utlist.h"
36 #include "ocrandom.h"
37 #include "ocpayload.h"
38 #include "ocpayloadcbor.h"
39 #include "cainterface.h"
40 #include "ocserverrequest.h"
41 #include "resourcemanager.h"
42 #include "doxmresource.h"
43 #include "pstatresource.h"
44 #include "aclresource.h"
45 #include "amaclresource.h"
46 #include "pconfresource.h"
47 #include "dpairingresource.h"
48 #include "psinterface.h"
49 #include "srmresourcestrings.h"
50 #include "securevirtualresourcetypes.h"
51 #include "credresource.h"
52 #include "srmutility.h"
53 #include "pinoxmcommon.h"
54
55 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
56 #include "pkix_interface.h"
57 #endif
58
59 #define TAG  "OIC_SRM_DOXM"
60 #define CHAR_ZERO ('0')
61
62 /** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
63  * The value of payload size is increased until reaching belox max cbor size. */
64 static const uint16_t CBOR_SIZE = 512;
65
66 /** Max cbor size payload. */
67 static const uint16_t CBOR_MAX_SIZE = 4400;
68
69 static OicSecDoxm_t        *gDoxm = NULL;
70 static OCResourceHandle    gDoxmHandle = NULL;
71
72 static OicSecOxm_t gOicSecDoxmJustWorks = OIC_JUST_WORKS;
73 static OicSecDoxm_t gDefaultDoxm =
74 {
75     NULL,                   /* OicUrn_t *oxmType */
76     0,                      /* size_t oxmTypeLen */
77     &gOicSecDoxmJustWorks,  /* uint16_t *oxm */
78     1,                      /* size_t oxmLen */
79     OIC_JUST_WORKS,         /* uint16_t oxmSel */
80     SYMMETRIC_PAIR_WISE_KEY,/* OicSecCredType_t sct */
81     false,                  /* bool owned */
82     {.id = {0}},            /* OicUuid_t deviceID */
83     false,                  /* bool dpc */
84     {.id = {0}},            /* OicUuid_t owner */
85 #ifdef _ENABLE_MULTIPLE_OWNER_
86     NULL,                   /* OicSecSubOwner_t sub-owner list */
87     NULL,                   /* OicSecMomType_t multiple owner mode */
88 #endif //_ENABLE_MULTIPLE_OWNER_
89     {.id = {0}},            /* OicUuid_t rownerID */
90 };
91
92 /**
93  * This method is internal method.
94  * the param roParsed is optionally used to know whether cborPayload has
95  * at least read only property value or not.
96  */
97 static OCStackResult CBORPayloadToDoxmBin(const uint8_t *cborPayload, size_t size,
98                                 OicSecDoxm_t **doxm, bool *roParsed);
99
100 void DeleteDoxmBinData(OicSecDoxm_t* doxm)
101 {
102     if (doxm)
103     {
104         //Clean oxmType
105         for (size_t i = 0; i < doxm->oxmTypeLen; i++)
106         {
107             OICFree(doxm->oxmType[i]);
108         }
109         OICFree(doxm->oxmType);
110
111         //clean oxm
112         OICFree(doxm->oxm);
113
114 #ifdef _ENABLE_MULTIPLE_OWNER_
115         //clean mom
116         OICFree(doxm->mom);
117
118         //clean sub-owner list
119         if(NULL != doxm->subOwners)
120         {
121             OicSecSubOwner_t* subowner = NULL;
122             OicSecSubOwner_t* temp = NULL;
123             LL_FOREACH_SAFE(doxm->subOwners, subowner, temp)
124             {
125                 LL_DELETE(doxm->subOwners, subowner);
126                 OICFree(subowner);
127             }
128         }
129 #endif //_ENABLE_MULTIPLE_OWNER_
130
131         //Clean doxm itself
132         OICFree(doxm);
133     }
134 }
135
136 OCStackResult DoxmToCBORPayload(const OicSecDoxm_t *doxm, uint8_t **payload, size_t *size,
137                                 bool rwOnly)
138 {
139     if (NULL == doxm || NULL == payload || NULL != *payload || NULL == size)
140     {
141         return OC_STACK_INVALID_PARAM;
142     }
143     size_t cborLen = *size;
144     if (0 == cborLen)
145     {
146         cborLen = CBOR_SIZE;
147     }
148     *payload = NULL;
149     *size = 0;
150
151     OCStackResult ret = OC_STACK_ERROR;
152
153     CborEncoder encoder;
154     CborEncoder doxmMap;
155     char* strUuid = NULL;
156
157     int64_t cborEncoderResult = CborNoError;
158
159     uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
160     VERIFY_NON_NULL(TAG, outPayload, ERROR);
161     cbor_encoder_init(&encoder, outPayload, cborLen, 0);
162
163     cborEncoderResult = cbor_encoder_create_map(&encoder, &doxmMap, CborIndefiniteLength);
164     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Doxm Map.");
165
166     //OxmType -- Not Mandatory
167     if (doxm->oxmTypeLen > 0)
168     {
169         CborEncoder oxmType;
170         cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_TYPE_NAME,
171             strlen(OIC_JSON_OXM_TYPE_NAME));
172         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Tag.");
173         cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxmType, doxm->oxmTypeLen);
174         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Array.");
175
176         for (size_t i = 0; i < doxm->oxmTypeLen; i++)
177         {
178             cborEncoderResult = cbor_encode_text_string(&oxmType, doxm->oxmType[i],
179                 strlen(doxm->oxmType[i]));
180             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Value.");
181         }
182         cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxmType);
183         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmType.");
184     }
185
186     //Oxm -- Not Mandatory
187     if (doxm->oxmLen > 0 && false == rwOnly)
188     {
189         CborEncoder oxm;
190         cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXMS_NAME,
191             strlen(OIC_JSON_OXMS_NAME));
192         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Tag.");
193         cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxm, doxm->oxmLen);
194         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Array.");
195
196         for (size_t i = 0; i < doxm->oxmLen; i++)
197         {
198             cborEncoderResult = cbor_encode_int(&oxm, doxm->oxm[i]);
199             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Value");
200         }
201         cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxm);
202         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmName.");
203     }
204
205     //OxmSel -- Mandatory
206     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_SEL_NAME,
207         strlen(OIC_JSON_OXM_SEL_NAME));
208     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Tag.");
209     cborEncoderResult = cbor_encode_int(&doxmMap, doxm->oxmSel);
210     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Value.");
211
212     //sct -- Mandatory
213     if (false == rwOnly)
214     {
215         cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_SUPPORTED_CRED_TYPE_NAME,
216             strlen(OIC_JSON_SUPPORTED_CRED_TYPE_NAME));
217         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Tag");
218         cborEncoderResult = cbor_encode_int(&doxmMap, doxm->sct);
219         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Value.");
220     }
221
222     //Owned -- Mandatory
223     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OWNED_NAME,
224         strlen(OIC_JSON_OWNED_NAME));
225     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Tag.");
226     cborEncoderResult = cbor_encode_boolean(&doxmMap, doxm->owned);
227     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Value.");
228
229     if (false == rwOnly)
230     {
231         //DeviceId -- Mandatory
232         cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVICE_ID_NAME,
233             strlen(OIC_JSON_DEVICE_ID_NAME));
234         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Tag.");
235         ret = ConvertUuidToStr(&doxm->deviceID, &strUuid);
236         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
237         cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
238         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Value.");
239         OICFree(strUuid);
240         strUuid = NULL;
241     }
242
243 #ifdef _ENABLE_MULTIPLE_OWNER_
244     //Device SubOwnerID -- Not Mandatory
245     if(doxm->subOwners)
246     {
247         size_t subOwnerLen = 0;
248         OicSecSubOwner_t* subOwner = NULL;
249         LL_FOREACH(doxm->subOwners, subOwner)
250         {
251             subOwnerLen++;
252         }
253
254         CborEncoder subOwners;
255         cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_SUBOWNERID_NAME,
256             strlen(OIC_JSON_SUBOWNERID_NAME));
257         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SubOwnerId Tag.");
258         cborEncoderResult = cbor_encoder_create_array(&doxmMap, &subOwners, subOwnerLen);
259         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SubOwner Array.");
260
261         subOwner = NULL;
262         LL_FOREACH(doxm->subOwners, subOwner)
263         {
264             char* strUuid = NULL;
265             ret = ConvertUuidToStr(&subOwner->uuid, &strUuid);
266             VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
267             cborEncoderResult = cbor_encode_text_string(&subOwners, strUuid, strlen(strUuid));
268             OICFree(strUuid);
269             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SubOwnerId Value");
270         }
271         cborEncoderResult = cbor_encoder_close_container(&doxmMap, &subOwners);
272         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing SubOwnerId.");
273     }
274
275     //Multiple Owner Mode -- Not Mandatory
276     if(doxm->mom)
277     {
278         cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_MOM_NAME,
279             strlen(OIC_JSON_MOM_NAME));
280         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding mom Tag");
281         cborEncoderResult = cbor_encode_int(&doxmMap, (int64_t)doxm->mom->mode);
282         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding mom Value.");
283     }
284 #endif //_ENABLE_MULTIPLE_OWNER_
285
286     //devownerid -- Mandatory
287     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVOWNERID_NAME,
288         strlen(OIC_JSON_DEVOWNERID_NAME));
289     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Id Tag.");
290     ret = ConvertUuidToStr(&doxm->owner, &strUuid);
291     VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
292     cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
293     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Id Value.");
294     OICFree(strUuid);
295     strUuid = NULL;
296
297     //ROwner -- Mandatory
298     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_ROWNERID_NAME,
299         strlen(OIC_JSON_ROWNERID_NAME));
300     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Tag.");
301     ret = ConvertUuidToStr(&doxm->rownerID, &strUuid);
302     VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
303     cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
304     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Value.");
305     OICFree(strUuid);
306     strUuid = NULL;
307
308     //RT -- Mandatory
309     CborEncoder rtArray;
310     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_RT_NAME,
311             strlen(OIC_JSON_RT_NAME));
312     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Name Tag.");
313     cborEncoderResult = cbor_encoder_create_array(&doxmMap, &rtArray, 1);
314     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Value.");
315     for (size_t i = 0; i < 1; i++)
316     {
317         cborEncoderResult = cbor_encode_text_string(&rtArray, OIC_RSRC_TYPE_SEC_DOXM,
318                 strlen(OIC_RSRC_TYPE_SEC_DOXM));
319         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding RT Value.");
320     }
321     cborEncoderResult = cbor_encoder_close_container(&doxmMap, &rtArray);
322     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing RT.");
323
324     //IF-- Mandatory
325      CborEncoder ifArray;
326      cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_IF_NAME,
327              strlen(OIC_JSON_IF_NAME));
328      VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Name Tag.");
329      cborEncoderResult = cbor_encoder_create_array(&doxmMap, &ifArray, 1);
330      VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Value.");
331     for (size_t i = 0; i < 1; i++)
332     {
333         cborEncoderResult = cbor_encode_text_string(&ifArray, OC_RSRVD_INTERFACE_DEFAULT,
334                 strlen(OC_RSRVD_INTERFACE_DEFAULT));
335         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding IF Value.");
336     }
337     cborEncoderResult = cbor_encoder_close_container(&doxmMap, &ifArray);
338     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing IF.");
339
340     cborEncoderResult = cbor_encoder_close_container(&encoder, &doxmMap);
341     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing DoxmMap.");
342
343     if (CborNoError == cborEncoderResult)
344     {
345         *size = cbor_encoder_get_buffer_size(&encoder, outPayload);
346         *payload = outPayload;
347         ret = OC_STACK_OK;
348     }
349 exit:
350     if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
351     {
352         OIC_LOG(DEBUG, TAG, "Memory getting reallocated.");
353         // reallocate and try again!
354         OICFree(outPayload);
355         // Since the allocated initial memory failed, double the memory.
356         cborLen += cbor_encoder_get_buffer_size(&encoder, encoder.end);
357         OIC_LOG_V(DEBUG, TAG, "Doxm reallocation size : %zd.", cborLen);
358         cborEncoderResult = CborNoError;
359         ret = DoxmToCBORPayload(doxm, payload, &cborLen, rwOnly);
360         *size = cborLen;
361     }
362
363     if ((CborNoError != cborEncoderResult) || (OC_STACK_OK != ret))
364     {
365        OICFree(outPayload);
366        outPayload = NULL;
367        *payload = NULL;
368        *size = 0;
369        ret = OC_STACK_ERROR;
370     }
371
372     return ret;
373 }
374
375 OCStackResult CBORPayloadToDoxm(const uint8_t *cborPayload, size_t size,
376                                 OicSecDoxm_t **secDoxm)
377 {
378     return CBORPayloadToDoxmBin(cborPayload, size, secDoxm, NULL);
379 }
380
381 static OCStackResult CBORPayloadToDoxmBin(const uint8_t *cborPayload, size_t size,
382                                 OicSecDoxm_t **secDoxm, bool *roParsed)
383 {
384     if (NULL == cborPayload || NULL == secDoxm || NULL != *secDoxm || 0 == size)
385     {
386         return OC_STACK_INVALID_PARAM;
387     }
388
389     OCStackResult ret = OC_STACK_ERROR;
390     *secDoxm = NULL;
391
392     CborParser parser;
393     CborError cborFindResult = CborNoError;
394     char* strUuid = NULL;
395     size_t len = 0;
396     CborValue doxmCbor;
397
398     cbor_parser_init(cborPayload, size, 0, &parser, &doxmCbor);
399     CborValue doxmMap;
400     OicSecDoxm_t *doxm = (OicSecDoxm_t *)OICCalloc(1, sizeof(*doxm));
401     VERIFY_NON_NULL(TAG, doxm, ERROR);
402
403     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_TYPE_NAME, &doxmMap);
404     //OxmType -- not Mandatory
405     if (CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
406     {
407         CborValue oxmType;
408
409         cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmTypeLen);
410         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmTypeLen.");
411         VERIFY_SUCCESS(TAG, doxm->oxmTypeLen != 0, ERROR);
412
413         doxm->oxmType = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(*doxm->oxmType));
414         VERIFY_NON_NULL(TAG, doxm->oxmType, ERROR);
415
416         cborFindResult = cbor_value_enter_container(&doxmMap, &oxmType);
417         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmType Array.")
418
419         int i = 0;
420         size_t len = 0;
421         while (cbor_value_is_valid(&oxmType) && cbor_value_is_text_string(&oxmType))
422         {
423             cborFindResult = cbor_value_dup_text_string(&oxmType, &doxm->oxmType[i++],
424                                                         &len, NULL);
425             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding omxType text string.");
426             cborFindResult = cbor_value_advance(&oxmType);
427             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmType.");
428         }
429     }
430
431     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXMS_NAME, &doxmMap);
432     //Oxm -- not Mandatory
433     if (CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
434     {
435         CborValue oxm;
436         cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmLen);
437         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName array Length.");
438         VERIFY_SUCCESS(TAG, doxm->oxmLen != 0, ERROR);
439
440         doxm->oxm = (OicSecOxm_t *)OICCalloc(doxm->oxmLen, sizeof(*doxm->oxm));
441         VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
442
443         cborFindResult = cbor_value_enter_container(&doxmMap, &oxm);
444         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmName Array.")
445
446         int i = 0;
447         while (cbor_value_is_valid(&oxm) && cbor_value_is_integer(&oxm))
448         {
449             int tmp;
450
451             cborFindResult = cbor_value_get_int(&oxm, &tmp);
452             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName Value")
453             doxm->oxm[i++] = (OicSecOxm_t)tmp;
454             cborFindResult = cbor_value_advance(&oxm);
455             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmName.")
456         }
457
458         if (roParsed)
459         {
460             *roParsed = true;
461         }
462     }
463     else
464     {
465         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
466         doxm->oxm = (OicSecOxm_t *) OICCalloc(gDoxm->oxmLen, sizeof(*doxm->oxm));
467         VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
468         doxm->oxmLen = gDoxm->oxmLen;
469         for (size_t i = 0; i < gDoxm->oxmLen; i++)
470         {
471             doxm->oxm[i] = gDoxm->oxm[i];
472         }
473     }
474
475     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_SEL_NAME, &doxmMap);
476     if (CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
477     {
478         int oxmSel;
479
480         cborFindResult = cbor_value_get_int(&doxmMap, &oxmSel);
481         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sel Name Value.")
482         doxm->oxmSel = (OicSecOxm_t)oxmSel;
483     }
484     else // PUT/POST JSON may not have oxmsel so set it to the gDoxm->oxmSel
485     {
486         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
487         doxm->oxmSel = gDoxm->oxmSel;
488     }
489
490     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_SUPPORTED_CRED_TYPE_NAME, &doxmMap);
491     if (CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
492     {
493         int sct;
494
495         cborFindResult = cbor_value_get_int(&doxmMap, &sct);
496         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sct Name Value.")
497         doxm->sct = (OicSecCredType_t)sct;
498
499         if (roParsed)
500         {
501             *roParsed = true;
502         }
503     }
504     else // PUT/POST JSON may not have sct so set it to the gDoxm->sct
505     {
506         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
507         doxm->sct = gDoxm->sct;
508     }
509
510     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OWNED_NAME, &doxmMap);
511     if (CborNoError == cborFindResult && cbor_value_is_boolean(&doxmMap))
512     {
513         cborFindResult = cbor_value_get_boolean(&doxmMap, &doxm->owned);
514         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owned Value.")
515     }
516     else // PUT/POST JSON may not have owned so set it to the gDomx->owned
517     {
518         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
519         doxm->owned = gDoxm->owned;
520     }
521
522     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVICE_ID_NAME, &doxmMap);
523     if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
524     {
525         cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
526         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Device Id Value.");
527         ret = ConvertStrToUuid(strUuid , &doxm->deviceID);
528         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
529         OICFree(strUuid);
530         strUuid  = NULL;
531     }
532     else
533     {
534         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
535         memcpy(doxm->deviceID.id, &gDoxm->deviceID.id, sizeof(doxm->deviceID.id));
536     }
537
538     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVOWNERID_NAME, &doxmMap);
539     if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
540     {
541         cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
542         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owner Value.");
543         ret = ConvertStrToUuid(strUuid , &doxm->owner);
544         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
545         OICFree(strUuid);
546         strUuid  = NULL;
547     }
548     else
549     {
550         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
551         memcpy(doxm->owner.id, gDoxm->owner.id, sizeof(doxm->owner.id));
552     }
553
554 #ifdef _ENABLE_MULTIPLE_OWNER_
555     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_MOM_NAME, &doxmMap);
556     if(CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
557     {
558         int mode = 0;
559         cborFindResult = cbor_value_get_int(&doxmMap, &mode);
560         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding mom Name Value.")
561         if(NULL == doxm->mom)
562         {
563             doxm->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
564             VERIFY_NON_NULL(TAG, doxm->mom, ERROR);
565         }
566         doxm->mom->mode = (OicSecMomType_t)mode;
567     }
568     else if(NULL != gDoxm && NULL != gDoxm->mom)
569     {
570         // PUT/POST JSON may not have 'mom' so set it to the gDomx->mom
571         if(NULL == doxm->mom)
572         {
573             doxm->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
574             VERIFY_NON_NULL(TAG, doxm->mom, ERROR);
575         }
576         doxm->mom->mode = gDoxm->mom->mode;
577     }
578
579     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_SUBOWNERID_NAME, &doxmMap);
580     if(CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
581     {
582         size_t subOwnerLen = 0;
583         CborValue subOwnerCbor;
584         cborFindResult = cbor_value_get_array_length(&doxmMap, &subOwnerLen);
585         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SubOwner array Length.");
586         VERIFY_SUCCESS(TAG, 0 != subOwnerLen, ERROR);
587
588         cborFindResult = cbor_value_enter_container(&doxmMap, &subOwnerCbor);
589         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering SubOwner Array.")
590
591         while (cbor_value_is_valid(&subOwnerCbor) && cbor_value_is_text_string(&subOwnerCbor))
592         {
593             OCStackResult convertRes = OC_STACK_ERROR;
594             OicSecSubOwner_t* subOwner = NULL;
595             char* strUuid = NULL;
596             size_t uuidLen = 0;
597
598             cborFindResult = cbor_value_dup_text_string(&subOwnerCbor, &strUuid, &uuidLen, NULL);
599             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SubOwnerId Value");
600
601             subOwner = (OicSecSubOwner_t*)OICCalloc(1, sizeof(OicSecSubOwner_t));
602             VERIFY_NON_NULL(TAG, subOwner, ERROR);
603
604             convertRes = ConvertStrToUuid(strUuid, &subOwner->uuid);
605             VERIFY_SUCCESS(TAG, OC_STACK_OK == convertRes, ERROR);
606             subOwner->status = MOT_STATUS_DONE;
607             LL_APPEND(doxm->subOwners, subOwner);
608
609             cborFindResult = cbor_value_advance(&subOwnerCbor);
610             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing SubOwnerId.")
611         }
612     }
613     else if(NULL != gDoxm && NULL != gDoxm->subOwners)
614     {
615         // PUT/POST JSON may not have 'subOwners' so set it to the gDomx->subOwners
616         OicSecSubOwner_t* subOwnerItor = NULL;
617         LL_FOREACH(gDoxm->subOwners, subOwnerItor)
618         {
619             OicSecSubOwner_t* subOwnerId = (OicSecSubOwner_t*)OICCalloc(1, sizeof(OicSecSubOwner_t));
620             VERIFY_NON_NULL(TAG, subOwnerId, ERROR);
621
622             memcpy(&subOwnerId->uuid, &subOwnerItor->uuid, sizeof(OicUuid_t));
623             subOwnerId->status = MOT_STATUS_DONE;
624
625             LL_APPEND(doxm->subOwners, subOwnerId);
626         }
627     }
628 #endif //_ENABLE_MULTIPLE_OWNER_
629
630     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_ROWNERID_NAME, &doxmMap);
631     if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
632     {
633         cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
634         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding ROwner Value.");
635         ret = ConvertStrToUuid(strUuid , &doxm->rownerID);
636         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
637         OICFree(strUuid);
638         strUuid  = NULL;
639     }
640     else
641     {
642         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
643         memcpy(doxm->rownerID.id, gDoxm->rownerID.id, sizeof(doxm->rownerID.id));
644     }
645
646     *secDoxm = doxm;
647     ret = OC_STACK_OK;
648
649 exit:
650     if (CborNoError != cborFindResult)
651     {
652         OIC_LOG (ERROR, TAG, "CBORPayloadToDoxm failed!!!");
653         DeleteDoxmBinData(doxm);
654         doxm = NULL;
655         *secDoxm = NULL;
656         ret = OC_STACK_ERROR;
657     }
658     return ret;
659 }
660
661 /**
662  * @todo document this function including why code might need to call this.
663  * The current suspicion is that it's not being called as much as it should.
664  */
665 static bool UpdatePersistentStorage(OicSecDoxm_t * doxm)
666 {
667     bool bRet = false;
668
669     if (NULL != doxm)
670     {
671         // Convert Doxm data into CBOR for update to persistent storage
672         uint8_t *payload = NULL;
673         size_t size = 0;
674         OCStackResult res = DoxmToCBORPayload(doxm, &payload, &size, false);
675         if (payload && (OC_STACK_OK == res)
676             && (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, payload, size)))
677         {
678                 bRet = true;
679         }
680         OICFree(payload);
681     }
682     else
683     {
684         if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, NULL, 0))
685         {
686                 bRet = true;
687         }
688     }
689
690     return bRet;
691 }
692
693 static bool ValidateQuery(const char * query)
694 {
695     // Send doxm resource data if the state of doxm resource
696     // matches with the query parameters.
697     // else send doxm resource data as NULL
698     // TODO Remove this check and rely on Policy Engine
699     // and Provisioning Mode to enforce provisioning-state
700     // access rules. Eventually, the PE and PM code will
701     // not send a request to the /doxm Entity Handler at all
702     // if it should not respond.
703     OIC_LOG (DEBUG, TAG, "In ValidateQuery");
704     if(NULL == gDoxm)
705     {
706         return false;
707     }
708
709     bool bOwnedQry = false;         // does querystring contains 'owned' query ?
710     bool bOwnedMatch = false;       // does 'owned' query value matches with doxm.owned status?
711     bool bDeviceIDQry = false;      // does querystring contains 'deviceid' query ?
712     bool bDeviceIDMatch = false;    // does 'deviceid' query matches with doxm.deviceid ?
713     bool bInterfaceQry = false;      // does querystring contains 'if' query ?
714     bool bInterfaceMatch = false;    // does 'if' query matches with oic.if.baseline ?
715 #ifdef _ENABLE_MULTIPLE_OWNER_
716     bool bMotQry = false;         // does querystring contains 'mom' and 'owned' query ?
717     bool bMotMatch = false;       // does 'mom' query value is not '0' && does query value matches with doxm.owned status?
718 #endif //_ENABLE_MULTIPLE_OWNER_
719
720     OicParseQueryIter_t parseIter = {.attrPos = NULL};
721
722     ParseQueryIterInit((unsigned char*)query, &parseIter);
723
724     while (GetNextQuery(&parseIter))
725     {
726         if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
727         {
728             bOwnedQry = true;
729             if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
730                     (gDoxm->owned))
731             {
732                 bOwnedMatch = true;
733             }
734             else if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_FALSE, parseIter.valLen) == 0)
735                     && (!gDoxm->owned))
736             {
737                 bOwnedMatch = true;
738             }
739         }
740
741 #ifdef _ENABLE_MULTIPLE_OWNER_
742         if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_MOM_NAME, strlen(OIC_JSON_MOM_NAME)) == 0)
743         {
744             bMotQry = true;
745             OicSecMomType_t momMode = (OicSecMomType_t)(parseIter.valPos[0] - CHAR_ZERO);
746             if(NULL != gDoxm->mom && momMode != gDoxm->mom->mode)
747             {
748                 if(GetNextQuery(&parseIter))
749                 {
750                     if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
751                     {
752                         if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
753                                 (gDoxm->owned))
754                         {
755                             bMotMatch = true;
756                         }
757                     }
758                 }
759             }
760             return bMotMatch;
761         }
762 #endif //_ENABLE_MULTIPLE_OWNER_
763
764         if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_DEVICE_ID_NAME, parseIter.attrLen) == 0)
765         {
766             bDeviceIDQry = true;
767             OicUuid_t subject = {.id={0}};
768
769             memcpy(subject.id, parseIter.valPos, parseIter.valLen);
770             if (0 == memcmp(&gDoxm->deviceID.id, &subject.id, sizeof(gDoxm->deviceID.id)))
771             {
772                 bDeviceIDMatch = true;
773             }
774         }
775
776         if (strncasecmp((char *)parseIter.attrPos, OC_RSRVD_INTERFACE, parseIter.attrLen) == 0)
777         {
778             bInterfaceQry = true;
779             if ((strncasecmp((char *)parseIter.valPos, OC_RSRVD_INTERFACE_DEFAULT, parseIter.valLen) == 0))
780             {
781                 bInterfaceMatch = true;
782             }
783             return (bInterfaceQry ? bInterfaceMatch: true);
784         }
785     }
786
787 #ifdef _ENABLE_MULTIPLE_OWNER_
788     return ((bOwnedQry ? bOwnedMatch : true) &&
789             (bDeviceIDQry ? bDeviceIDMatch : true) &&
790             (bMotQry ? bMotMatch : true));
791 #else
792     return ((bOwnedQry ? bOwnedMatch : true) &&
793             (bDeviceIDQry ? bDeviceIDMatch : true));
794 #endif //_ENABLE_MULTIPLE_OWNER_
795 }
796
797 static OCEntityHandlerResult HandleDoxmGetRequest (const OCEntityHandlerRequest * ehRequest)
798 {
799     OCEntityHandlerResult ehRet = OC_EH_OK;
800
801     OIC_LOG(DEBUG, TAG, "Doxm EntityHandle processing GET request");
802
803     //Checking if Get request is a query.
804     if (ehRequest->query)
805     {
806         OIC_LOG_V(DEBUG,TAG,"query:%s",ehRequest->query);
807         OIC_LOG(DEBUG, TAG, "HandleDoxmGetRequest processing query");
808         if (!ValidateQuery(ehRequest->query))
809         {
810             ehRet = OC_EH_ERROR;
811         }
812     }
813
814     /*
815      * For GET or Valid Query request return doxm resource CBOR payload.
816      * For non-valid query return NULL json payload.
817      * A device will 'always' have a default Doxm, so DoxmToCBORPayload will
818      * return valid doxm resource json.
819      */
820     uint8_t *payload = NULL;
821     size_t size = 0;
822
823     if (ehRet == OC_EH_OK)
824     {
825         if (OC_STACK_OK != DoxmToCBORPayload(gDoxm, &payload, &size, false))
826         {
827             OIC_LOG(WARNING, TAG, "DoxmToCBORPayload failed in HandleDoxmGetRequest");
828         }
829     }
830
831     OIC_LOG(DEBUG, TAG, "Send payload for doxm GET request");
832     OIC_LOG_BUFFER(DEBUG, TAG, payload, size);
833
834     // Send response payload to request originator
835     ehRet = ((SendSRMResponse(ehRequest, ehRet, payload, size)) == OC_STACK_OK) ?
836                    OC_EH_OK : OC_EH_ERROR;
837
838     OICFree(payload);
839
840     return ehRet;
841 }
842
843 static void updateWriteableProperty(const OicSecDoxm_t* src, OicSecDoxm_t* dst)
844 {
845     if(src && dst)
846    {
847         // update oxmsel
848         dst->oxmSel = src->oxmSel;
849
850         //update owner
851         memcpy(&(dst->owner), &(src->owner), sizeof(OicUuid_t));
852
853         //update rowner
854         memcpy(&(dst->rownerID), &(src->rownerID), sizeof(OicUuid_t));
855
856         //update deviceuuid
857         memcpy(&(dst->deviceID), &(src->deviceID), sizeof(OicUuid_t));
858
859         //Update owned status
860         if(dst->owned != src->owned)
861         {
862             dst->owned = src->owned;
863         }
864
865 #ifdef _ENABLE_MULTIPLE_OWNER_
866         if(src->mom)
867         {
868             OIC_LOG(DEBUG, TAG, "dectected 'mom' property");
869             if(NULL == dst->mom)
870             {
871                 dst->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
872                 if(NULL != dst->mom)
873                 {
874                     dst->mom->mode = src->mom->mode;
875                 }
876             }
877         }
878 #endif //_ENABLE_MULTIPLE_OWNER_
879     }
880 }
881
882 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
883 #ifdef _ENABLE_MULTIPLE_OWNER_
884 /**
885  * Callback function to handle MOT DTLS handshake result.
886  * @param[out]   object           remote device information.
887  * @param[out]   errorInfo        CA Error information.
888  */
889 void MultipleOwnerDTLSHandshakeCB(const CAEndpoint_t *object,
890                                 const CAErrorInfo_t *errorInfo)
891 {
892     OIC_LOG(DEBUG, TAG, "IN MultipleOwnerDTLSHandshakeCB");
893
894     if(CA_STATUS_OK == errorInfo->result)
895     {
896         const CASecureEndpoint_t* authenticatedSubOwnerInfo = CAGetSecureEndpointData(object);
897         if(authenticatedSubOwnerInfo)
898         {
899             OicSecSubOwner_t* subOwnerInst = NULL;
900             LL_FOREACH(gDoxm->subOwners, subOwnerInst)
901             {
902                 if(0 == memcmp(subOwnerInst->uuid.id,
903                                authenticatedSubOwnerInfo->identity.id,
904                                authenticatedSubOwnerInfo->identity.id_length))
905                 {
906                     break;
907                 }
908             }
909
910             if(NULL == subOwnerInst)
911             {
912                 subOwnerInst = (OicSecSubOwner_t*)OICCalloc(1, sizeof(OicSecSubOwner_t));
913                 if(subOwnerInst)
914                 {
915                     OIC_LOG(DEBUG, TAG, "Adding New SubOwner");
916                     memcpy(subOwnerInst->uuid.id, authenticatedSubOwnerInfo->identity.id,
917                            authenticatedSubOwnerInfo->identity.id_length);
918                     LL_APPEND(gDoxm->subOwners, subOwnerInst);
919                     if(!UpdatePersistentStorage(gDoxm))
920                     {
921                         OIC_LOG(ERROR, TAG, "Failed to register SubOwner UUID into Doxm");
922                     }
923                 }
924             }
925         }
926     }
927
928     if(CA_STATUS_OK != CAregisterPskCredentialsHandler(GetDtlsPskCredentials))
929     {
930         OIC_LOG(WARNING, TAG, "Failed to revert the DTLS credential handler");
931     }
932
933     OIC_LOG(DEBUG, TAG, "OUT MultipleOwnerDTLSHandshakeCB");
934 }
935 #endif //_ENABLE_MULTIPLE_OWNER_
936 #endif // defined(__WITH_DTLS__) || defined (__WITH_TLS__)
937
938 /**
939  * Function to validate oxmsel with oxms.
940  *
941  * @param[in] supportedMethods   Array of supported methods
942  * @param[in] numberOfMethods   number of supported methods
943  * @param[out]  selectedMethod         Selected methods
944  * @return  TRUE on success
945  */
946 static bool ValidateOxmsel(const OicSecOxm_t *supportedMethods,
947         size_t numberOfMethods, OicSecOxm_t *selectedMethod)
948 {
949     bool isValidOxmsel = false;
950
951     OIC_LOG(DEBUG, TAG, "IN ValidateOxmsel");
952     if (numberOfMethods == 0 || !supportedMethods)
953     {
954         OIC_LOG(WARNING, TAG, "Could not find a supported OxM.");
955         return isValidOxmsel;
956     }
957
958     for (size_t i = 0; i < numberOfMethods; i++)
959     {
960             if (*selectedMethod  == supportedMethods[i])
961             {
962                 isValidOxmsel = true;
963                 break;
964             }
965     }
966     if (!isValidOxmsel)
967     {
968         OIC_LOG(ERROR, TAG, "Not allowed Oxmsel.");
969         return isValidOxmsel;
970     }
971
972     OIC_LOG(DEBUG, TAG, "OUT ValidateOxmsel");
973
974     return isValidOxmsel;
975 }
976
977 static OCEntityHandlerResult HandleDoxmPostRequest(OCEntityHandlerRequest * ehRequest)
978 {
979     OIC_LOG (DEBUG, TAG, "Doxm EntityHandle  processing POST request");
980     OCEntityHandlerResult ehRet = OC_EH_ERROR;
981     OicUuid_t emptyOwner = {.id = {0} };
982     static uint16_t previousMsgId = 0;
983
984     /*
985      * Convert CBOR Doxm data into binary. This will also validate
986      * the Doxm data received.
987      */
988     OicSecDoxm_t *newDoxm = NULL;
989
990     if (ehRequest->payload)
991     {
992         uint8_t *payload = ((OCSecurityPayload *)ehRequest->payload)->securityData;
993         size_t size = ((OCSecurityPayload *)ehRequest->payload)->payloadSize;
994         bool roParsed = false;
995         OCStackResult res = CBORPayloadToDoxmBin(payload, size, &newDoxm, &roParsed);
996         if (newDoxm && OC_STACK_OK == res)
997         {
998             // Check request on RO property
999             if (true == roParsed)
1000             {
1001                 OIC_LOG(ERROR, TAG, "Not acceptable request because of read-only propertys");
1002                 ehRet = OC_EH_NOT_ACCEPTABLE;
1003                 goto exit;
1004             }
1005
1006             // in owned state
1007             if (true == gDoxm->owned)
1008             {
1009                 if (false == ValidateOxmsel(gDoxm->oxm, gDoxm->oxmLen, &newDoxm->oxmSel))
1010                 {
1011                     OIC_LOG(ERROR, TAG, "Not acceptable request because oxmsel does not support on Server");
1012                     ehRet = OC_EH_NOT_ACCEPTABLE;
1013                     goto exit;
1014                 }
1015                 //Update gDoxm based on newDoxm
1016                 updateWriteableProperty(newDoxm, gDoxm);
1017
1018 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1019 #ifdef _ENABLE_MULTIPLE_OWNER_
1020                 //handle mom
1021                 if(gDoxm->mom)
1022                 {
1023                     if(OIC_MULTIPLE_OWNER_DISABLE != gDoxm->mom->mode)
1024                     {
1025                         CAResult_t caRes = CA_STATUS_FAILED;
1026                         if(OIC_PRECONFIG_PIN == gDoxm->oxmSel || OIC_RANDOM_DEVICE_PIN == gDoxm->oxmSel)
1027                         {
1028                             caRes = CAEnableAnonECDHCipherSuite(false);
1029                             VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1030                             OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1031
1032                             caRes = CASelectCipherSuite((uint16_t)TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256, ehRequest->devAddr.adapter);
1033                             VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1034                             OIC_LOG(INFO, TAG, "ECDHE_PSK CipherSuite will be used for MOT");
1035
1036                             //Set the device id to derive temporal PSK
1037                             SetUuidForPinBasedOxm(&gDoxm->deviceID);
1038                         }
1039                         else
1040                         {
1041                             OIC_LOG(WARNING, TAG, "Unsupported OxM for Multiple Ownership Transfer.");
1042                         }
1043
1044                         CAregisterSslHandshakeCallback(MultipleOwnerDTLSHandshakeCB);
1045                     }
1046                     else
1047                     {
1048                         //if MOM is disabled, revert the DTLS handshake callback
1049                         if(CA_STATUS_OK != CAregisterSslHandshakeCallback(NULL))
1050                         {
1051                             OIC_LOG(WARNING, TAG, "Error while revert the DTLS Handshake Callback.");
1052                         }
1053                     }
1054                 }
1055
1056                 if(newDoxm->subOwners)
1057                 {
1058                     OicSecSubOwner_t* subowner = NULL;
1059                     OicSecSubOwner_t* temp = NULL;
1060
1061                     OIC_LOG(DEBUG, TAG, "dectected 'subowners' property");
1062
1063                     if(gDoxm->subOwners)
1064                     {
1065                         LL_FOREACH_SAFE(gDoxm->subOwners, subowner, temp)
1066                         {
1067                             LL_DELETE(gDoxm->subOwners, subowner);
1068                             OICFree(subowner);
1069                         }
1070                     }
1071
1072                     subowner = NULL;
1073                     temp = NULL;
1074                     LL_FOREACH_SAFE(newDoxm->subOwners, subowner, temp)
1075                     {
1076                         LL_DELETE(newDoxm->subOwners, subowner);
1077                         LL_APPEND(gDoxm->subOwners, subowner);
1078                     }
1079                 }
1080 #endif //_ENABLE_MULTIPLE_OWNER_
1081 #endif // defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1082
1083                 //Update new state in persistent storage
1084                 if (UpdatePersistentStorage(gDoxm) == true)
1085                 {
1086                     ehRet = OC_EH_OK;
1087                 }
1088                 else
1089                 {
1090                     OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1091                     ehRet = OC_EH_ERROR;
1092                 }
1093                 goto exit;
1094             }
1095
1096             // in unowned state
1097             if ((false == gDoxm->owned) && (false == newDoxm->owned))
1098             {
1099                 if (false == ValidateOxmsel(gDoxm->oxm, gDoxm->oxmLen, &newDoxm->oxmSel))
1100                 {
1101                     OIC_LOG(ERROR, TAG, "Not acceptable request because oxmsel does not support on Server");
1102                     ehRet = OC_EH_NOT_ACCEPTABLE;
1103                     goto exit;
1104                 }
1105
1106                 if (OIC_JUST_WORKS == newDoxm->oxmSel)
1107                 {
1108                     /*
1109                      * If current state of the device is un-owned, enable
1110                      * anonymous ECDH cipher in tinyDTLS so that Provisioning
1111                      * tool can initiate JUST_WORKS ownership transfer process.
1112                      */
1113                     if (memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
1114                     {
1115                         OIC_LOG (INFO, TAG, "Doxm EntityHandle  enabling AnonECDHCipherSuite");
1116 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1117                         ehRet = (CAEnableAnonECDHCipherSuite(true) == CA_STATUS_OK) ? OC_EH_OK : OC_EH_ERROR;
1118 #endif // __WITH_DTLS__ or __WITH_TLS__
1119                         goto exit;
1120                     }
1121                     else
1122                     {
1123 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1124                         //Save the owner's UUID to derive owner credential
1125                         memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
1126
1127                         // Update new state in persistent storage
1128                         if (true == UpdatePersistentStorage(gDoxm))
1129                         {
1130                             ehRet = OC_EH_OK;
1131                         }
1132                         else
1133                         {
1134                             OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1135                             ehRet = OC_EH_ERROR;
1136                         }
1137
1138                         /*
1139                          * Disable anonymous ECDH cipher in tinyDTLS since device is now
1140                          * in owned state.
1141                          */
1142                         CAResult_t caRes = CA_STATUS_OK;
1143                         caRes = CAEnableAnonECDHCipherSuite(false);
1144                         VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1145                         OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1146
1147 #endif // __WITH_DTLS__ or __WITH_TLS__
1148                     }
1149                 }
1150                 else if (OIC_RANDOM_DEVICE_PIN == newDoxm->oxmSel)
1151                 {
1152                     /*
1153                      * If current state of the device is un-owned, enable
1154                      * anonymous ECDH cipher in tinyDTLS so that Provisioning
1155                      * tool can initiate JUST_WORKS ownership transfer process.
1156                      */
1157                     if(memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
1158                     {
1159                         gDoxm->oxmSel = newDoxm->oxmSel;
1160                         //Update new state in persistent storage
1161                         if ((UpdatePersistentStorage(gDoxm) == true))
1162                         {
1163                             ehRet = OC_EH_OK;
1164                         }
1165                         else
1166                         {
1167                             OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
1168                             ehRet = OC_EH_ERROR;
1169                         }
1170
1171 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1172                         CAResult_t caRes = CA_STATUS_OK;
1173
1174                         caRes = CAEnableAnonECDHCipherSuite(false);
1175                         VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1176                         OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1177
1178                         caRes = CASelectCipherSuite(TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256,
1179                                                     ehRequest->devAddr.adapter);
1180                         VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1181
1182                         char ranPin[OXM_RANDOM_PIN_MAX_SIZE + 1] = {0};
1183                          //TODO ehRequest->messageID for copa over TCP always is null. Find reason why.
1184                         if(ehRequest->devAddr.adapter == OC_ADAPTER_IP && previousMsgId != ehRequest->messageID)
1185                         {
1186                             if(OC_STACK_OK == GeneratePin(ranPin, sizeof(ranPin)))
1187                             {
1188                                 //Set the device id to derive temporal PSK
1189                                 SetUuidForPinBasedOxm(&gDoxm->deviceID);
1190
1191                                 /**
1192                                  * Since PSK will be used directly by DTLS layer while PIN based ownership transfer,
1193                                  * Credential should not be saved into SVR.
1194                                  * For this reason, use a temporary get_psk_info callback to random PIN OxM.
1195                                  */
1196                                 caRes = CAregisterPskCredentialsHandler(GetDtlsPskForRandomPinOxm);
1197                                 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1198                                 ehRet = OC_EH_OK;
1199                             }
1200                             else
1201                             {
1202                                 OIC_LOG(ERROR, TAG, "Failed to generate random PIN");
1203                                 ehRet = OC_EH_ERROR;
1204                             }
1205                         }
1206                         else if(OC_ADAPTER_TCP == ehRequest->devAddr.adapter)
1207                         {
1208                             if(OC_STACK_OK == GeneratePin(ranPin, sizeof(ranPin)))
1209                             {
1210                                 //Set the device id to derive temporal PSK
1211                                 SetUuidForPinBasedOxm(&gDoxm->deviceID);
1212
1213                                 /**
1214                                  * Since PSK will be used directly by DTLS layer while PIN based ownership transfer,
1215                                  * Credential should not be saved into SVR.
1216                                  * For this reason, use a temporary get_psk_info callback to random PIN OxM.
1217                                  */
1218                                 caRes = CAregisterPskCredentialsHandler(GetDtlsPskForRandomPinOxm);
1219                                 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1220                                 ehRet = OC_EH_OK;
1221                             }
1222                             else
1223                             {
1224                                 OIC_LOG(ERROR, TAG, "Failed to generate random PIN");
1225                                 ehRet = OC_EH_ERROR;
1226                             }
1227
1228                         }
1229 #endif // __WITH_DTLS__ or __WITH_TLS__
1230                     }
1231 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1232                     else
1233                     {
1234                         //Save the owner's UUID to derive owner credential
1235                         memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
1236
1237                         //Update new state in persistent storage
1238                         if (UpdatePersistentStorage(gDoxm) == true)
1239                         {
1240                             ehRet = OC_EH_OK;
1241                         }
1242                         else
1243                         {
1244                             OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1245                             ehRet = OC_EH_ERROR;
1246                         }
1247                     }
1248 #endif // __WITH_DTLS__ or __WITH_TLS__
1249                 }
1250 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1251                 else if (OIC_MANUFACTURER_CERTIFICATE ==  newDoxm->oxmSel)
1252                 {
1253                     //Save the owner's UUID to derive owner credential
1254                     memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
1255                     gDoxm->oxmSel = newDoxm->oxmSel;
1256                     //Update new state in persistent storage
1257                     if (UpdatePersistentStorage(gDoxm))
1258                     {
1259                         ehRet = OC_EH_OK;
1260                     }
1261                     else
1262                     {
1263                         OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
1264                         ehRet = OC_EH_ERROR;
1265                     }
1266                     CAResult_t caRes = CAEnableAnonECDHCipherSuite(false);
1267                     VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1268                     OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1269
1270                     VERIFY_SUCCESS(TAG, CA_STATUS_OK == CAregisterPkixInfoHandler(GetManufacturerPkixInfo), ERROR);
1271                     VERIFY_SUCCESS(TAG, CA_STATUS_OK == CAregisterGetCredentialTypesHandler(InitManufacturerCipherSuiteList), ERROR);
1272                 }
1273 #endif // __WITH_DTLS__ or __WITH_TLS__
1274             }
1275
1276             /*
1277              * When current state of the device is un-owned and Provisioning
1278              * Tool is attempting to change the state to 'Owned' with a
1279              * qualified value for the field 'Owner'
1280              */
1281             if ((false == gDoxm->owned) && (true == newDoxm->owned) &&
1282                     (memcmp(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t)) == 0))
1283             {
1284                 //Change the SVR's resource owner as owner device.
1285                 OCStackResult ownerRes = SetAclRownerId(&gDoxm->owner);
1286                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1287                 {
1288                     ehRet = OC_EH_ERROR;
1289                     goto exit;
1290                 }
1291                 ownerRes = SetAmaclRownerId(&gDoxm->owner);
1292                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1293                 {
1294                     ehRet = OC_EH_ERROR;
1295                     goto exit;
1296                 }
1297                 ownerRes = SetCredRownerId(&gDoxm->owner);
1298                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1299                 {
1300                     ehRet = OC_EH_ERROR;
1301                     goto exit;
1302                 }
1303                 ownerRes = SetPstatRownerId(&gDoxm->owner);
1304                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1305                 {
1306                     ehRet = OC_EH_ERROR;
1307                     goto exit;
1308                 }
1309                 ownerRes = SetDpairingRownerId(&gDoxm->owner);
1310                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1311                 {
1312                     ehRet = OC_EH_ERROR;
1313                     goto exit;
1314                 }
1315                 ownerRes = SetPconfRownerId(&gDoxm->owner);
1316                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1317                 {
1318                     ehRet = OC_EH_ERROR;
1319                     goto exit;
1320                 }
1321
1322                 gDoxm->owned = true;
1323                 memcpy(&gDoxm->rownerID, &gDoxm->owner, sizeof(OicUuid_t));
1324
1325                 // Update new state in persistent storage
1326                 if (UpdatePersistentStorage(gDoxm))
1327                 {
1328                     //Update default ACE of security resource to prevent anonymous user access.
1329                     if(OC_STACK_OK == UpdateDefaultSecProvACE())
1330                     {
1331                         ehRet = OC_EH_OK;
1332                     }
1333                     else
1334                     {
1335                         OIC_LOG(ERROR, TAG, "Failed to remove default ACL for security provisioning");
1336                         ehRet = OC_EH_ERROR;
1337                     }
1338                 }
1339                 else
1340                 {
1341                     OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1342                     ehRet = OC_EH_ERROR;
1343                 }
1344 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1345                 if (OIC_MANUFACTURER_CERTIFICATE == gDoxm->oxmSel)
1346                 {
1347                     CAregisterPkixInfoHandler(GetPkixInfo);
1348                     CAregisterGetCredentialTypesHandler(InitCipherSuiteList);
1349                 }
1350 #endif // __WITH_DTLS__ or __WITH_TLS__
1351             }
1352         }
1353     }
1354
1355 exit:
1356     if(OC_EH_OK != ehRet)
1357     {
1358
1359         /*
1360          * If some error is occured while ownership transfer,
1361          * ownership transfer related resource should be revert back to initial status.
1362         */
1363         if(gDoxm)
1364         {
1365             if(!gDoxm->owned)
1366             {
1367                 OIC_LOG(WARNING, TAG, "The operation failed during handle DOXM request");
1368
1369                 if((OC_ADAPTER_IP == ehRequest->devAddr.adapter && previousMsgId != ehRequest->messageID)
1370                    || OC_ADAPTER_TCP == ehRequest->devAddr.adapter)
1371                 {
1372                     RestoreDoxmToInitState();
1373                     RestorePstatToInitState();
1374                     OIC_LOG(WARNING, TAG, "DOXM will be reverted.");
1375                 }
1376             }
1377         }
1378         else
1379         {
1380             OIC_LOG(ERROR, TAG, "Invalid DOXM resource.");
1381         }
1382     }
1383     else
1384     {
1385         previousMsgId = ehRequest->messageID++;
1386     }
1387
1388     //Send payload to request originator
1389     ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1390                    OC_EH_OK : OC_EH_ERROR;
1391
1392     DeleteDoxmBinData(newDoxm);
1393
1394     return ehRet;
1395 }
1396
1397 OCEntityHandlerResult DoxmEntityHandler(OCEntityHandlerFlag flag,
1398                                         OCEntityHandlerRequest * ehRequest,
1399                                         void* callbackParam)
1400 {
1401     (void)callbackParam;
1402     OCEntityHandlerResult ehRet = OC_EH_ERROR;
1403
1404     if(NULL == ehRequest)
1405     {
1406         return ehRet;
1407     }
1408
1409     if (flag & OC_REQUEST_FLAG)
1410     {
1411         OIC_LOG(DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
1412
1413         switch (ehRequest->method)
1414         {
1415             case OC_REST_GET:
1416                 ehRet = HandleDoxmGetRequest(ehRequest);
1417                 break;
1418
1419             case OC_REST_POST:
1420                 ehRet = HandleDoxmPostRequest(ehRequest);
1421                 break;
1422
1423             default:
1424                 ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1425                                OC_EH_OK : OC_EH_ERROR;
1426                 break;
1427         }
1428     }
1429
1430     return ehRet;
1431 }
1432
1433 OCStackResult CreateDoxmResource()
1434 {
1435     OCStackResult ret = OCCreateResource(&gDoxmHandle,
1436                                          OIC_RSRC_TYPE_SEC_DOXM,
1437                                          OC_RSRVD_INTERFACE_DEFAULT,
1438                                          OIC_RSRC_DOXM_URI,
1439                                          DoxmEntityHandler,
1440                                          NULL,
1441                                          OC_SECURE |
1442                                          OC_DISCOVERABLE);
1443
1444     if (OC_STACK_OK != ret)
1445     {
1446         OIC_LOG (FATAL, TAG, "Unable to instantiate Doxm resource");
1447         DeInitDoxmResource();
1448     }
1449     return ret;
1450 }
1451
1452 /**
1453  * Checks if DeviceID is generated during provisioning for the new device.
1454  * If DeviceID is NULL then generates the new DeviceID.
1455  * Once DeviceID is assigned to the device it does not change for the lifetime of the device.
1456  */
1457 static OCStackResult CheckDeviceID()
1458 {
1459     OCStackResult ret = OC_STACK_ERROR;
1460     bool validId = false;
1461     for (uint8_t i = 0; i < UUID_LENGTH; i++)
1462     {
1463         if (gDoxm->deviceID.id[i] != 0)
1464         {
1465             validId = true;
1466             break;
1467         }
1468     }
1469
1470     if (!validId)
1471     {
1472         if (OCGenerateUuid(gDoxm->deviceID.id) != RAND_UUID_OK)
1473         {
1474             OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
1475             return ret;
1476         }
1477         ret = OC_STACK_OK;
1478
1479         if (!UpdatePersistentStorage(gDoxm))
1480         {
1481             //TODO: After registering PSI handler in all samples, do ret = OC_STACK_OK here.
1482             OIC_LOG(FATAL, TAG, "UpdatePersistentStorage failed!");
1483         }
1484     }
1485     else
1486     {
1487         ret = OC_STACK_OK;
1488     }
1489     return ret;
1490 }
1491
1492 /**
1493  * Get the default value.
1494  *
1495  * @return the default value of doxm, @ref OicSecDoxm_t.
1496  */
1497 static OicSecDoxm_t* GetDoxmDefault()
1498 {
1499     OIC_LOG(DEBUG, TAG, "GetDoxmToDefault");
1500     return &gDefaultDoxm;
1501 }
1502
1503 const OicSecDoxm_t* GetDoxmResourceData()
1504 {
1505     return gDoxm;
1506 }
1507
1508 #if defined(__WITH_DTLS__) && defined(_ENABLE_MULTIPLE_OWNER_)
1509 /**
1510  * Internal API to prepare MOT
1511  */
1512 static void PrepareMOT(const OicSecDoxm_t* doxm)
1513 {
1514     OIC_LOG(INFO, TAG, "IN PrepareMOT");
1515     VERIFY_NON_NULL(TAG, doxm, ERROR);
1516
1517     if(true == doxm->owned && NULL != doxm->mom && OIC_MULTIPLE_OWNER_DISABLE != doxm->mom->mode)
1518     {
1519         CAResult_t caRes = CA_STATUS_FAILED;
1520
1521         OIC_LOG(INFO, TAG, "Multiple Ownership Transfer Enabled!");
1522
1523         if(OIC_PRECONFIG_PIN == doxm->oxmSel)
1524         {
1525             caRes = CAEnableAnonECDHCipherSuite(false);
1526             VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1527             OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1528
1529             caRes = CASelectCipherSuite((uint16_t)TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256, CA_ADAPTER_IP);
1530             VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1531 #ifdef __WITH_TLS__
1532             caRes = CASelectCipherSuite((uint16_t)TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256, CA_ADAPTER_TCP);
1533             VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1534 #endif
1535             OIC_LOG(INFO, TAG, "ECDHE_PSK CipherSuite will be used for MOT");
1536
1537             //Set the device id to derive temporal PSK
1538             SetUuidForPinBasedOxm(&doxm->deviceID);
1539         }
1540         else
1541         {
1542             OIC_LOG(ERROR, TAG, "Unsupported OxM for Multiple Ownership Transfer.");
1543             return;
1544         }
1545
1546         CAregisterSslHandshakeCallback(MultipleOwnerDTLSHandshakeCB);
1547     }
1548
1549     OIC_LOG(INFO, TAG, "OUT PrepareMOT");
1550     return;
1551 exit:
1552     OIC_LOG(WARNING, TAG, "Error in PrepareMOT");
1553 }
1554 #endif //defined(__WITH_DTLS__) && defined(_ENABLE_MULTIPLE_OWNER_)
1555
1556 OCStackResult InitDoxmResource()
1557 {
1558     OCStackResult ret = OC_STACK_ERROR;
1559
1560     //Read DOXM resource from PS
1561     uint8_t *data = NULL;
1562     size_t size = 0;
1563     ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_DOXM_NAME, &data, &size);
1564     // If database read failed
1565     if (OC_STACK_OK != ret)
1566     {
1567        OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
1568     }
1569     if (data)
1570     {
1571        // Read DOXM resource from PS
1572        ret = CBORPayloadToDoxm(data, size, &gDoxm);
1573     }
1574     /*
1575      * If SVR database in persistent storage got corrupted or
1576      * is not available for some reason, a default doxm is created
1577      * which allows user to initiate doxm provisioning again.
1578      */
1579      if ((OC_STACK_OK != ret) || !data || !gDoxm)
1580     {
1581         gDoxm = GetDoxmDefault();
1582     }
1583
1584     //In case of the server is shut down unintentionally, we should initialize the owner
1585     if(false == gDoxm->owned)
1586     {
1587         OicUuid_t emptyUuid = {.id={0}};
1588         memcpy(&gDoxm->owner, &emptyUuid, sizeof(OicUuid_t));
1589     }
1590
1591     ret = CheckDeviceID();
1592     if (ret == OC_STACK_OK)
1593     {
1594         OIC_LOG_V(DEBUG, TAG, "Initial Doxm Owned = %d", gDoxm->owned);
1595         //Instantiate 'oic.sec.doxm'
1596         ret = CreateDoxmResource();
1597     }
1598     else
1599     {
1600         OIC_LOG (ERROR, TAG, "CheckDeviceID failed");
1601     }
1602     OICFree(data);
1603
1604 #if defined(__WITH_DTLS__) && defined(_ENABLE_MULTIPLE_OWNER_)
1605     //if MOT is enabled, MOT should be prepared.
1606     if(gDoxm && gDoxm->owned)
1607     {
1608         PrepareMOT(gDoxm);
1609     }
1610 #endif // defined(__WITH_DTLS__) && defined(_ENABLE_MULTIPLE_OWNER_)
1611
1612     return ret;
1613 }
1614
1615 OCStackResult DeInitDoxmResource()
1616 {
1617     OCStackResult ret = OCDeleteResource(gDoxmHandle);
1618     if (gDoxm  != &gDefaultDoxm)
1619     {
1620         DeleteDoxmBinData(gDoxm);
1621     }
1622     gDoxm = NULL;
1623
1624     if (OC_STACK_OK == ret)
1625     {
1626         return OC_STACK_OK;
1627     }
1628     else
1629     {
1630         return OC_STACK_ERROR;
1631     }
1632 }
1633
1634 OCStackResult GetDoxmDeviceID(OicUuid_t *deviceID)
1635 {
1636     if (deviceID && gDoxm)
1637     {
1638        *deviceID = gDoxm->deviceID;
1639         return OC_STACK_OK;
1640     }
1641     return OC_STACK_ERROR;
1642 }
1643
1644 OCStackResult GetDoxmIsOwned(bool *isOwned)
1645 {
1646     if (isOwned && gDoxm)
1647     {
1648        *isOwned = gDoxm->owned;
1649         return OC_STACK_OK;
1650     }
1651     return OC_STACK_ERROR;
1652 }
1653
1654 OCStackResult SetDoxmDeviceID(const OicUuid_t *deviceID)
1655 {
1656     bool isPT = false;
1657
1658     if(NULL == deviceID)
1659     {
1660         return OC_STACK_INVALID_PARAM;
1661     }
1662     if(NULL == gDoxm)
1663     {
1664         OIC_LOG(ERROR, TAG, "Doxm resource is not initialized.");
1665         return OC_STACK_NO_RESOURCE;
1666     }
1667
1668     //Check the device's OTM state
1669
1670 #ifdef __WITH_DTLS__
1671     //for normal device.
1672     if(true == gDoxm->owned &&
1673        memcmp(gDoxm->deviceID.id, gDoxm->owner.id, sizeof(gDoxm->owner.id)) != 0)
1674     {
1675         OIC_LOG(ERROR, TAG, "This device owned by owner's device.");
1676         OIC_LOG(ERROR, TAG, "Device UUID cannot be changed to guarantee the reliability of the connection.");
1677         return OC_STACK_ERROR;
1678     }
1679 #endif //__WITH_DTLS
1680
1681     //Save the previous UUID
1682     OicUuid_t tempUuid;
1683     memcpy(tempUuid.id, gDoxm->deviceID.id, sizeof(tempUuid.id));
1684
1685     //Change the UUID
1686     memcpy(gDoxm->deviceID.id, deviceID->id, sizeof(deviceID->id));
1687     if(isPT)
1688     {
1689         memcpy(gDoxm->owner.id, deviceID->id, sizeof(deviceID->id));
1690         memcpy(gDoxm->rownerID.id, deviceID->id, sizeof(deviceID->id));
1691     }
1692
1693     //Update PS
1694     if(!UpdatePersistentStorage(gDoxm))
1695     {
1696         //revert UUID in case of update error
1697         memcpy(gDoxm->deviceID.id, tempUuid.id, sizeof(tempUuid.id));
1698         if(isPT)
1699         {
1700             memcpy(gDoxm->owner.id, tempUuid.id, sizeof(tempUuid.id));
1701             memcpy(gDoxm->rownerID.id, tempUuid.id, sizeof(tempUuid.id));
1702         }
1703
1704         OIC_LOG(ERROR, TAG, "Failed to update persistent storage");
1705         return OC_STACK_ERROR;
1706     }
1707     return OC_STACK_OK;
1708 }
1709
1710 OCStackResult GetDoxmDevOwnerId(OicUuid_t *devownerid)
1711 {
1712     OCStackResult retVal = OC_STACK_ERROR;
1713     if (gDoxm)
1714     {
1715         OIC_LOG_V(DEBUG, TAG, "GetDoxmDevOwnerId(): gDoxm owned =  %d.", \
1716             gDoxm->owned);
1717         if (gDoxm->owned)
1718         {
1719             *devownerid = gDoxm->owner;
1720             retVal = OC_STACK_OK;
1721         }
1722     }
1723     return retVal;
1724 }
1725
1726 OCStackResult GetDoxmRownerId(OicUuid_t *rowneruuid)
1727 {
1728     OCStackResult retVal = OC_STACK_ERROR;
1729     if (gDoxm)
1730     {
1731         if( gDoxm->owned )
1732         {
1733             *rowneruuid = gDoxm->rownerID;
1734                     retVal = OC_STACK_OK;
1735         }
1736     }
1737     return retVal;
1738 }
1739
1740 #ifdef _ENABLE_MULTIPLE_OWNER_
1741 /**
1742  * Compare the UUID to SubOwner.
1743  *
1744  * @param[in] uuid device UUID
1745  *
1746  * @return true if context->subjectId exist subowner list, else false.
1747  */
1748 bool IsSubOwner(const OicUuid_t* uuid)
1749 {
1750     bool retVal = false;
1751
1752     if(NULL == uuid)
1753     {
1754         return retVal;
1755     }
1756
1757     if (gDoxm && gDoxm->subOwners)
1758     {
1759         OicSecSubOwner_t* subOwner = NULL;
1760         LL_FOREACH(gDoxm->subOwners, subOwner)
1761         {
1762             if(memcmp(subOwner->uuid.id, uuid->id, sizeof(uuid->id)) == 0)
1763             {
1764                 return true;
1765             }
1766         }
1767     }
1768     return retVal;
1769 }
1770 #endif //_ENABLE_MULTIPLE_OWNER_
1771
1772 /**
1773  * Function to restore doxm resurce to initial status.
1774  * This function will use in case of error while ownership transfer
1775  */
1776 void RestoreDoxmToInitState()
1777 {
1778     if(gDoxm)
1779     {
1780         OIC_LOG(INFO, TAG, "DOXM resource will revert back to initial status.");
1781
1782         OicUuid_t emptyUuid = {.id={0}};
1783         memcpy(&(gDoxm->owner), &emptyUuid, sizeof(OicUuid_t));
1784         gDoxm->owned = false;
1785         gDoxm->oxmSel = OIC_JUST_WORKS;
1786
1787         if(!UpdatePersistentStorage(gDoxm))
1788         {
1789             OIC_LOG(ERROR, TAG, "Failed to revert DOXM in persistent storage");
1790         }
1791     }
1792 }