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