Update the random PIN generator module to provide high entropy.
[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 #define TAG  "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 = encoder.ptr - 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 += encoder.ptr - 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         if (roParsed)
548         {
549             *roParsed = true;
550         }
551     }
552     else
553     {
554         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
555         memcpy(doxm->deviceID.id, &gDoxm->deviceID.id, sizeof(doxm->deviceID.id));
556     }
557
558     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVOWNERID_NAME, &doxmMap);
559     if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
560     {
561         cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
562         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owner Value.");
563         ret = ConvertStrToUuid(strUuid , &doxm->owner);
564         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
565         OICFree(strUuid);
566         strUuid  = NULL;
567     }
568     else
569     {
570         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
571         memcpy(doxm->owner.id, gDoxm->owner.id, sizeof(doxm->owner.id));
572     }
573
574 #ifdef _ENABLE_MULTIPLE_OWNER_
575     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_MOM_NAME, &doxmMap);
576     if(CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
577     {
578         int mode = 0;
579         cborFindResult = cbor_value_get_int(&doxmMap, &mode);
580         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding mom Name Value.")
581         if(NULL == doxm->mom)
582         {
583             doxm->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
584             VERIFY_NON_NULL(TAG, doxm->mom, ERROR);
585         }
586         doxm->mom->mode = (OicSecMomType_t)mode;
587     }
588     else if(NULL != gDoxm && NULL != gDoxm->mom)
589     {
590         // PUT/POST JSON may not have 'mom' so set it to the gDomx->mom
591         if(NULL == doxm->mom)
592         {
593             doxm->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
594             VERIFY_NON_NULL(TAG, doxm->mom, ERROR);
595         }
596         doxm->mom->mode = gDoxm->mom->mode;
597     }
598
599     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_SUBOWNERID_NAME, &doxmMap);
600     if(CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
601     {
602         size_t subOwnerLen = 0;
603         CborValue subOwnerCbor;
604         cborFindResult = cbor_value_get_array_length(&doxmMap, &subOwnerLen);
605         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SubOwner array Length.");
606         VERIFY_SUCCESS(TAG, 0 != subOwnerLen, ERROR);
607
608         cborFindResult = cbor_value_enter_container(&doxmMap, &subOwnerCbor);
609         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering SubOwner Array.")
610
611         while (cbor_value_is_valid(&subOwnerCbor) && cbor_value_is_text_string(&subOwnerCbor))
612         {
613             OCStackResult convertRes = OC_STACK_ERROR;
614             OicSecSubOwner_t* subOwner = NULL;
615             char* strUuid = NULL;
616             size_t uuidLen = 0;
617
618             cborFindResult = cbor_value_dup_text_string(&subOwnerCbor, &strUuid, &uuidLen, NULL);
619             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SubOwnerId Value");
620
621             subOwner = (OicSecSubOwner_t*)OICCalloc(1, sizeof(OicSecSubOwner_t));
622             VERIFY_NON_NULL(TAG, subOwner, ERROR);
623
624             convertRes = ConvertStrToUuid(strUuid, &subOwner->uuid);
625             VERIFY_SUCCESS(TAG, OC_STACK_OK == convertRes, ERROR);
626             subOwner->status = MOT_STATUS_DONE;
627             LL_APPEND(doxm->subOwners, subOwner);
628
629             cborFindResult = cbor_value_advance(&subOwnerCbor);
630             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing SubOwnerId.")
631         }
632     }
633     else if(NULL != gDoxm && NULL != gDoxm->subOwners)
634     {
635         // PUT/POST JSON may not have 'subOwners' so set it to the gDomx->subOwners
636         OicSecSubOwner_t* subOwnerItor = NULL;
637         LL_FOREACH(gDoxm->subOwners, subOwnerItor)
638         {
639             OicSecSubOwner_t* subOwnerId = (OicSecSubOwner_t*)OICCalloc(1, sizeof(OicSecSubOwner_t));
640             VERIFY_NON_NULL(TAG, subOwnerId, ERROR);
641
642             memcpy(&subOwnerId->uuid, &subOwnerItor->uuid, sizeof(OicUuid_t));
643             subOwnerId->status = MOT_STATUS_DONE;
644
645             LL_APPEND(doxm->subOwners, subOwnerId);
646         }
647     }
648 #endif //_ENABLE_MULTIPLE_OWNER_
649
650     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_ROWNERID_NAME, &doxmMap);
651     if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
652     {
653         cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
654         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding ROwner Value.");
655         ret = ConvertStrToUuid(strUuid , &doxm->rownerID);
656         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
657         OICFree(strUuid);
658         strUuid  = NULL;
659     }
660     else
661     {
662         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
663         memcpy(doxm->rownerID.id, gDoxm->rownerID.id, sizeof(doxm->rownerID.id));
664     }
665
666     *secDoxm = doxm;
667     ret = OC_STACK_OK;
668
669 exit:
670     if (CborNoError != cborFindResult)
671     {
672         OIC_LOG (ERROR, TAG, "CBORPayloadToDoxm failed!!!");
673         DeleteDoxmBinData(doxm);
674         doxm = NULL;
675         *secDoxm = NULL;
676         ret = OC_STACK_ERROR;
677     }
678     return ret;
679 }
680
681 /**
682  * @todo document this function including why code might need to call this.
683  * The current suspicion is that it's not being called as much as it should.
684  */
685 static bool UpdatePersistentStorage(OicSecDoxm_t * doxm)
686 {
687     bool bRet = false;
688
689     if (NULL != doxm)
690     {
691         // Convert Doxm data into CBOR for update to persistent storage
692         uint8_t *payload = NULL;
693         size_t size = 0;
694         OCStackResult res = DoxmToCBORPayload(doxm, &payload, &size, false);
695         if (payload && (OC_STACK_OK == res)
696             && (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, payload, size)))
697         {
698                 bRet = true;
699         }
700         OICFree(payload);
701     }
702     else
703     {
704         if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, NULL, 0))
705         {
706                 bRet = true;
707         }
708     }
709
710     return bRet;
711 }
712
713 static bool ValidateQuery(const char * query)
714 {
715     // Send doxm resource data if the state of doxm resource
716     // matches with the query parameters.
717     // else send doxm resource data as NULL
718     // TODO Remove this check and rely on Policy Engine
719     // and Provisioning Mode to enforce provisioning-state
720     // access rules. Eventually, the PE and PM code will
721     // not send a request to the /doxm Entity Handler at all
722     // if it should not respond.
723     OIC_LOG (DEBUG, TAG, "In ValidateQuery");
724     if(NULL == gDoxm)
725     {
726         return false;
727     }
728
729     bool bOwnedQry = false;         // does querystring contains 'owned' query ?
730     bool bOwnedMatch = false;       // does 'owned' query value matches with doxm.owned status?
731     bool bDeviceIDQry = false;      // does querystring contains 'deviceid' query ?
732     bool bDeviceIDMatch = false;    // does 'deviceid' query matches with doxm.deviceid ?
733     bool bInterfaceQry = false;      // does querystring contains 'if' query ?
734     bool bInterfaceMatch = false;    // does 'if' query matches with oic.if.baseline ?
735 #ifdef _ENABLE_MULTIPLE_OWNER_
736     bool bMotQry = false;         // does querystring contains 'mom' and 'owned' query ?
737     bool bMotMatch = false;       // does 'mom' query value is not '0' && does query value matches with doxm.owned status?
738 #endif //_ENABLE_MULTIPLE_OWNER_
739
740     OicParseQueryIter_t parseIter = {.attrPos = NULL};
741
742     ParseQueryIterInit((unsigned char*)query, &parseIter);
743
744     while (GetNextQuery(&parseIter))
745     {
746         if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
747         {
748             bOwnedQry = true;
749             if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
750                     (gDoxm->owned))
751             {
752                 bOwnedMatch = true;
753             }
754             else if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_FALSE, parseIter.valLen) == 0)
755                     && (!gDoxm->owned))
756             {
757                 bOwnedMatch = true;
758             }
759         }
760
761 #ifdef _ENABLE_MULTIPLE_OWNER_
762         if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_MOM_NAME, strlen(OIC_JSON_MOM_NAME)) == 0)
763         {
764             bMotQry = true;
765             OicSecMomType_t momMode = (OicSecMomType_t)(parseIter.valPos[0] - CHAR_ZERO);
766             if(NULL != gDoxm->mom && momMode != gDoxm->mom->mode)
767             {
768                 if(GetNextQuery(&parseIter))
769                 {
770                     if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
771                     {
772                         if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
773                                 (gDoxm->owned))
774                         {
775                             bMotMatch = true;
776                         }
777                     }
778                 }
779             }
780             return bMotMatch;
781         }
782 #endif //_ENABLE_MULTIPLE_OWNER_
783
784         if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_DEVICE_ID_NAME, parseIter.attrLen) == 0)
785         {
786             bDeviceIDQry = true;
787             OicUuid_t subject = {.id={0}};
788
789             memcpy(subject.id, parseIter.valPos, parseIter.valLen);
790             if (0 == memcmp(&gDoxm->deviceID.id, &subject.id, sizeof(gDoxm->deviceID.id)))
791             {
792                 bDeviceIDMatch = true;
793             }
794         }
795
796         if (strncasecmp((char *)parseIter.attrPos, OC_RSRVD_INTERFACE, parseIter.attrLen) == 0)
797         {
798             bInterfaceQry = true;
799             if ((strncasecmp((char *)parseIter.valPos, OC_RSRVD_INTERFACE_DEFAULT, parseIter.valLen) == 0))
800             {
801                 bInterfaceMatch = true;
802             }
803             return (bInterfaceQry ? bInterfaceMatch: true);
804         }
805     }
806
807 #ifdef _ENABLE_MULTIPLE_OWNER_
808     return ((bOwnedQry ? bOwnedMatch : true) &&
809             (bDeviceIDQry ? bDeviceIDMatch : true) &&
810             (bMotQry ? bMotMatch : true));
811 #else
812     return ((bOwnedQry ? bOwnedMatch : true) &&
813             (bDeviceIDQry ? bDeviceIDMatch : true));
814 #endif //_ENABLE_MULTIPLE_OWNER_
815 }
816
817 static OCEntityHandlerResult HandleDoxmGetRequest (const OCEntityHandlerRequest * ehRequest)
818 {
819     OCEntityHandlerResult ehRet = OC_EH_OK;
820
821     OIC_LOG(DEBUG, TAG, "Doxm EntityHandle processing GET request");
822
823     //Checking if Get request is a query.
824     if (ehRequest->query)
825     {
826         OIC_LOG_V(DEBUG,TAG,"query:%s",ehRequest->query);
827         OIC_LOG(DEBUG, TAG, "HandleDoxmGetRequest processing query");
828         if (!ValidateQuery(ehRequest->query))
829         {
830             ehRet = OC_EH_ERROR;
831         }
832     }
833
834     /*
835      * For GET or Valid Query request return doxm resource CBOR payload.
836      * For non-valid query return NULL json payload.
837      * A device will 'always' have a default Doxm, so DoxmToCBORPayload will
838      * return valid doxm resource json.
839      */
840     uint8_t *payload = NULL;
841     size_t size = 0;
842
843     if (ehRet == OC_EH_OK)
844     {
845         if (OC_STACK_OK != DoxmToCBORPayload(gDoxm, &payload, &size, false))
846         {
847             OIC_LOG(WARNING, TAG, "DoxmToCBORPayload failed in HandleDoxmGetRequest");
848         }
849     }
850
851     OIC_LOG(DEBUG, TAG, "Send payload for doxm GET request");
852     OIC_LOG_BUFFER(DEBUG, TAG, payload, size);
853
854     // Send response payload to request originator
855     ehRet = ((SendSRMResponse(ehRequest, ehRet, payload, size)) == OC_STACK_OK) ?
856                    OC_EH_OK : OC_EH_ERROR;
857
858     OICFree(payload);
859
860     return ehRet;
861 }
862
863 static void updateWriteableProperty(const OicSecDoxm_t* src, OicSecDoxm_t* dst)
864 {
865     if(src && dst)
866    {
867         // update oxmsel
868         dst->oxmSel = src->oxmSel;
869
870         //update owner
871         memcpy(&(dst->owner), &(src->owner), sizeof(OicUuid_t));
872
873         //update rowner
874         memcpy(&(dst->rownerID), &(src->rownerID), sizeof(OicUuid_t));
875
876         //Update owned status
877         if(dst->owned != src->owned)
878         {
879             dst->owned = src->owned;
880         }
881
882         //update oxms
883         if(0 < src->oxmLen)
884         {
885             OicSecOxm_t* tempOxm = (OicSecOxm_t*)OICMalloc(sizeof(OicSecOxm_t) * src->oxmLen);
886             if(NULL != tempOxm)
887             {
888                 for(size_t i = 0; i < src->oxmLen; i++)
889                 {
890                     tempOxm[i] = src->oxm[i];
891                 }
892                 OICFree(dst->oxm);
893
894                 dst->oxm = tempOxm;
895                 dst->oxmLen = src->oxmLen;
896             }
897         }
898
899 #ifdef _ENABLE_MULTIPLE_OWNER_
900         if(src->mom)
901         {
902             OIC_LOG(DEBUG, TAG, "dectected 'mom' property");
903             if(NULL == dst->mom)
904             {
905                 dst->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
906                 if(NULL != dst->mom)
907                 {
908                     dst->mom->mode = src->mom->mode;
909                 }
910             }
911         }
912 #endif //_ENABLE_MULTIPLE_OWNER_
913     }
914 }
915
916 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
917 #ifdef _ENABLE_MULTIPLE_OWNER_
918 /**
919  * Callback function to handle MOT DTLS handshake result.
920  * @param[out]   object           remote device information.
921  * @param[out]   errorInfo        CA Error information.
922  */
923 void MultipleOwnerDTLSHandshakeCB(const CAEndpoint_t *object,
924                                 const CAErrorInfo_t *errorInfo)
925 {
926     OIC_LOG(DEBUG, TAG, "IN MultipleOwnerDTLSHandshakeCB");
927
928     if(CA_STATUS_OK == errorInfo->result)
929     {
930         const CASecureEndpoint_t* authenticatedSubOwnerInfo = CAGetSecureEndpointData(object);
931         if(authenticatedSubOwnerInfo)
932         {
933             OicSecSubOwner_t* subOwnerInst = (OicSecSubOwner_t*)OICMalloc(sizeof(OicSecSubOwner_t));
934             if(subOwnerInst)
935             {
936                 OIC_LOG(DEBUG, TAG, "Adding New SubOwner");
937                 memcpy(subOwnerInst->uuid.id, authenticatedSubOwnerInfo->identity.id, authenticatedSubOwnerInfo->identity.id_length);
938                 LL_APPEND(gDoxm->subOwners, subOwnerInst);
939                 if(!UpdatePersistentStorage(gDoxm))
940                 {
941                     OIC_LOG(ERROR, TAG, "Failed to register SubOwner UUID into Doxm");
942                 }
943             }
944         }
945     }
946
947     if(CA_STATUS_OK != CAregisterPskCredentialsHandler(GetDtlsPskCredentials))
948     {
949         OIC_LOG(WARNING, TAG, "Failed to revert the DTLS credential handler");
950     }
951
952     OIC_LOG(DEBUG, TAG, "OUT MultipleOwnerDTLSHandshakeCB");
953 }
954 #endif //_ENABLE_MULTIPLE_OWNER_
955 #endif // defined(__WITH_DTLS__) || defined (__WITH_TLS__)
956
957 static OCEntityHandlerResult HandleDoxmPostRequest(const OCEntityHandlerRequest * ehRequest)
958 {
959     OIC_LOG (DEBUG, TAG, "Doxm EntityHandle  processing POST request");
960     OCEntityHandlerResult ehRet = OC_EH_ERROR;
961     OicUuid_t emptyOwner = {.id = {0} };
962     static uint16_t previousMsgId = 0;
963
964     /*
965      * Convert CBOR Doxm data into binary. This will also validate
966      * the Doxm data received.
967      */
968     OicSecDoxm_t *newDoxm = NULL;
969
970     if (ehRequest->payload)
971     {
972         uint8_t *payload = ((OCSecurityPayload *)ehRequest->payload)->securityData;
973         size_t size = ((OCSecurityPayload *)ehRequest->payload)->payloadSize;
974         bool roParsed = false;
975         OCStackResult res = CBORPayloadToDoxmBin(payload, size, &newDoxm, &roParsed);
976         if (newDoxm && OC_STACK_OK == res)
977         {
978             // Check request on RO property
979             if (true == roParsed)
980             {
981                 OIC_LOG(ERROR, TAG, "Not acceptable request because of read-only propertys");
982                 ehRet = OC_EH_NOT_ACCEPTABLE;
983                 goto exit;
984             }
985
986             // in owned state
987             if (true == gDoxm->owned)
988             {
989                 //Update gDoxm based on newDoxm
990                 updateWriteableProperty(newDoxm, gDoxm);
991
992 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
993 #ifdef _ENABLE_MULTIPLE_OWNER_
994                 //handle mom
995                 if(gDoxm->mom)
996                 {
997                     if(OIC_MULTIPLE_OWNER_DISABLE != gDoxm->mom->mode)
998                     {
999                         CAResult_t caRes = CA_STATUS_FAILED;
1000                         if(OIC_PRECONFIG_PIN == gDoxm->oxmSel || OIC_RANDOM_DEVICE_PIN == gDoxm->oxmSel)
1001                         {
1002                             caRes = CAEnableAnonECDHCipherSuite(false);
1003                             VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1004                             OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1005
1006                             caRes = CASelectCipherSuite((uint16_t)TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256, ehRequest->devAddr.adapter);
1007                             VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1008                             OIC_LOG(INFO, TAG, "ECDHE_PSK CipherSuite will be used for MOT");
1009
1010                             //Set the device id to derive temporal PSK
1011                             SetUuidForPinBasedOxm(&gDoxm->deviceID);
1012                         }
1013                         else
1014                         {
1015                             OIC_LOG(WARNING, TAG, "Unsupported OxM for Multiple Ownership Transfer.");
1016                         }
1017
1018                         CAregisterSslHandshakeCallback(MultipleOwnerDTLSHandshakeCB);
1019                     }
1020                     else
1021                     {
1022                         //if MOM is disabled, revert the DTLS handshake callback
1023                         if(CA_STATUS_OK != CAregisterSslHandshakeCallback(NULL))
1024                         {
1025                             OIC_LOG(WARNING, TAG, "Error while revert the DTLS Handshake Callback.");
1026                         }
1027                     }
1028                 }
1029
1030                 if(newDoxm->subOwners)
1031                 {
1032                     OicSecSubOwner_t* subowner = NULL;
1033                     OicSecSubOwner_t* temp = NULL;
1034
1035                     OIC_LOG(DEBUG, TAG, "dectected 'subowners' property");
1036
1037                     if(gDoxm->subOwners)
1038                     {
1039                         LL_FOREACH_SAFE(gDoxm->subOwners, subowner, temp)
1040                         {
1041                             LL_DELETE(gDoxm->subOwners, subowner);
1042                             OICFree(subowner);
1043                         }
1044                     }
1045
1046                     subowner = NULL;
1047                     temp = NULL;
1048                     LL_FOREACH_SAFE(newDoxm->subOwners, subowner, temp)
1049                     {
1050                         LL_DELETE(newDoxm->subOwners, subowner);
1051                         LL_APPEND(gDoxm->subOwners, subowner);
1052                     }
1053                 }
1054 #endif //_ENABLE_MULTIPLE_OWNER_
1055 #endif // defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1056
1057                 //Update new state in persistent storage
1058                 if (UpdatePersistentStorage(gDoxm) == true)
1059                 {
1060                     ehRet = OC_EH_OK;
1061                 }
1062                 else
1063                 {
1064                     OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1065                     ehRet = OC_EH_ERROR;
1066                 }
1067                 goto exit;
1068             }
1069
1070             // in unowned state
1071             if ((false == gDoxm->owned) && (false == newDoxm->owned))
1072             {
1073                 if (OIC_JUST_WORKS == newDoxm->oxmSel)
1074                 {
1075                     /*
1076                      * If current state of the device is un-owned, enable
1077                      * anonymous ECDH cipher in tinyDTLS so that Provisioning
1078                      * tool can initiate JUST_WORKS ownership transfer process.
1079                      */
1080                     if (memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
1081                     {
1082                         OIC_LOG (INFO, TAG, "Doxm EntityHandle  enabling AnonECDHCipherSuite");
1083 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1084                         ehRet = (CAEnableAnonECDHCipherSuite(true) == CA_STATUS_OK) ? OC_EH_OK : OC_EH_ERROR;
1085 #endif // __WITH_DTLS__ or __WITH_TLS__
1086                         goto exit;
1087                     }
1088                     else
1089                     {
1090 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1091                         //Save the owner's UUID to derive owner credential
1092                         memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
1093
1094                         // Update new state in persistent storage
1095                         if (true == UpdatePersistentStorage(gDoxm))
1096                         {
1097                             ehRet = OC_EH_OK;
1098                         }
1099                         else
1100                         {
1101                             OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1102                             ehRet = OC_EH_ERROR;
1103                         }
1104
1105                         /*
1106                          * Disable anonymous ECDH cipher in tinyDTLS since device is now
1107                          * in owned state.
1108                          */
1109                         CAResult_t caRes = CA_STATUS_OK;
1110                         caRes = CAEnableAnonECDHCipherSuite(false);
1111                         VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1112                         OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1113
1114 #endif // __WITH_DTLS__ or __WITH_TLS__
1115                     }
1116                 }
1117                 else if (OIC_RANDOM_DEVICE_PIN == newDoxm->oxmSel)
1118                 {
1119                     /*
1120                      * If current state of the device is un-owned, enable
1121                      * anonymous ECDH cipher in tinyDTLS so that Provisioning
1122                      * tool can initiate JUST_WORKS ownership transfer process.
1123                      */
1124                     if(memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
1125                     {
1126                         gDoxm->oxmSel = newDoxm->oxmSel;
1127                         //Update new state in persistent storage
1128                         if ((UpdatePersistentStorage(gDoxm) == true))
1129                         {
1130                             ehRet = OC_EH_OK;
1131                         }
1132                         else
1133                         {
1134                             OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
1135                             ehRet = OC_EH_ERROR;
1136                         }
1137
1138 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1139                         CAResult_t caRes = CA_STATUS_OK;
1140
1141                         caRes = CAEnableAnonECDHCipherSuite(false);
1142                         VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1143                         OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1144
1145                         caRes = CASelectCipherSuite(TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256,
1146                                                     ehRequest->devAddr.adapter);
1147                         VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1148
1149                         char ranPin[OXM_RANDOM_PIN_MAX_SIZE + 1] = {0};
1150                          //TODO ehRequest->messageID for copa over TCP always is null. Find reason why.
1151                         if(ehRequest->devAddr.adapter == OC_ADAPTER_IP && previousMsgId != ehRequest->messageID)
1152                         {
1153                             if(OC_STACK_OK == GeneratePin(ranPin, sizeof(ranPin)))
1154                             {
1155                                 //Set the device id to derive temporal PSK
1156                                 SetUuidForPinBasedOxm(&gDoxm->deviceID);
1157
1158                                 /**
1159                                  * Since PSK will be used directly by DTLS layer while PIN based ownership transfer,
1160                                  * Credential should not be saved into SVR.
1161                                  * For this reason, use a temporary get_psk_info callback to random PIN OxM.
1162                                  */
1163                                 caRes = CAregisterPskCredentialsHandler(GetDtlsPskForRandomPinOxm);
1164                                 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1165                                 ehRet = OC_EH_OK;
1166                             }
1167                             else
1168                             {
1169                                 OIC_LOG(ERROR, TAG, "Failed to generate random PIN");
1170                                 ehRet = OC_EH_ERROR;
1171                             }
1172                         }
1173                         else if(previousMsgId != ehRequest->messageID)
1174                         {
1175                             if(OC_STACK_OK == GeneratePin(ranPin, sizeof(ranPin)))
1176                             {
1177                                 //Set the device id to derive temporal PSK
1178                                 SetUuidForPinBasedOxm(&gDoxm->deviceID);
1179
1180                                 /**
1181                                  * Since PSK will be used directly by DTLS layer while PIN based ownership transfer,
1182                                  * Credential should not be saved into SVR.
1183                                  * For this reason, use a temporary get_psk_info callback to random PIN OxM.
1184                                  */
1185                                 caRes = CAregisterPskCredentialsHandler(GetDtlsPskForRandomPinOxm);
1186                                 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1187                                 ehRet = OC_EH_OK;
1188                             }
1189                             else
1190                             {
1191                                 OIC_LOG(ERROR, TAG, "Failed to generate random PIN");
1192                                 ehRet = OC_EH_ERROR;
1193                             }
1194
1195                         }
1196 #endif // __WITH_DTLS__ or __WITH_TLS__
1197                     }
1198 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1199                     else
1200                     {
1201                         //Save the owner's UUID to derive owner credential
1202                         memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
1203
1204                         //Update new state in persistent storage
1205                         if (UpdatePersistentStorage(gDoxm) == true)
1206                         {
1207                             ehRet = OC_EH_OK;
1208                         }
1209                         else
1210                         {
1211                             OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1212                             ehRet = OC_EH_ERROR;
1213                         }
1214                     }
1215 #endif // __WITH_DTLS__ or __WITH_TLS__
1216                 }
1217             }
1218
1219             /*
1220              * When current state of the device is un-owned and Provisioning
1221              * Tool is attempting to change the state to 'Owned' with a
1222              * qualified value for the field 'Owner'
1223              */
1224             if ((false == gDoxm->owned) && (true == newDoxm->owned) &&
1225                     (memcmp(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t)) == 0))
1226             {
1227                 //Change the SVR's resource owner as owner device.
1228                 OCStackResult ownerRes = SetAclRownerId(&gDoxm->owner);
1229                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1230                 {
1231                     ehRet = OC_EH_ERROR;
1232                     goto exit;
1233                 }
1234                 ownerRes = SetAmaclRownerId(&gDoxm->owner);
1235                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1236                 {
1237                     ehRet = OC_EH_ERROR;
1238                     goto exit;
1239                 }
1240                 ownerRes = SetCredRownerId(&gDoxm->owner);
1241                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1242                 {
1243                     ehRet = OC_EH_ERROR;
1244                     goto exit;
1245                 }
1246                 ownerRes = SetPstatRownerId(&gDoxm->owner);
1247                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1248                 {
1249                     ehRet = OC_EH_ERROR;
1250                     goto exit;
1251                 }
1252                 ownerRes = SetDpairingRownerId(&gDoxm->owner);
1253                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1254                 {
1255                     ehRet = OC_EH_ERROR;
1256                     goto exit;
1257                 }
1258                 ownerRes = SetPconfRownerId(&gDoxm->owner);
1259                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1260                 {
1261                     ehRet = OC_EH_ERROR;
1262                     goto exit;
1263                 }
1264
1265                 gDoxm->owned = true;
1266                 memcpy(&gDoxm->rownerID, &gDoxm->owner, sizeof(OicUuid_t));
1267
1268                 // Update new state in persistent storage
1269                 if (UpdatePersistentStorage(gDoxm))
1270                 {
1271                     //Update default ACE of security resource to prevent anonymous user access.
1272                     if(OC_STACK_OK == UpdateDefaultSecProvACE())
1273                     {
1274                         ehRet = OC_EH_OK;
1275                     }
1276                     else
1277                     {
1278                         OIC_LOG(ERROR, TAG, "Failed to remove default ACL for security provisioning");
1279                         ehRet = OC_EH_ERROR;
1280                     }
1281                 }
1282                 else
1283                 {
1284                     OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1285                     ehRet = OC_EH_ERROR;
1286                 }
1287             }
1288         }
1289     }
1290
1291 exit:
1292     if(OC_EH_OK != ehRet)
1293     {
1294
1295         /*
1296          * If some error is occured while ownership transfer,
1297          * ownership transfer related resource should be revert back to initial status.
1298         */
1299         if(gDoxm)
1300         {
1301             if(!gDoxm->owned && previousMsgId != ehRequest->messageID)
1302             {
1303                 OIC_LOG(WARNING, TAG, "The operation failed during handle DOXM request,"\
1304                                     "DOXM will be reverted.");
1305                 RestoreDoxmToInitState();
1306                 RestorePstatToInitState();
1307             }
1308         }
1309         else
1310         {
1311             OIC_LOG(ERROR, TAG, "Invalid DOXM resource.");
1312         }
1313     }
1314     else
1315     {
1316         previousMsgId = ehRequest->messageID;
1317     }
1318
1319     //Send payload to request originator
1320     ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1321                    OC_EH_OK : OC_EH_ERROR;
1322
1323     DeleteDoxmBinData(newDoxm);
1324
1325     return ehRet;
1326 }
1327
1328 OCEntityHandlerResult DoxmEntityHandler(OCEntityHandlerFlag flag,
1329                                         OCEntityHandlerRequest * ehRequest,
1330                                         void* callbackParam)
1331 {
1332     (void)callbackParam;
1333     OCEntityHandlerResult ehRet = OC_EH_ERROR;
1334
1335     if(NULL == ehRequest)
1336     {
1337         return ehRet;
1338     }
1339
1340     if (flag & OC_REQUEST_FLAG)
1341     {
1342         OIC_LOG(DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
1343
1344         switch (ehRequest->method)
1345         {
1346             case OC_REST_GET:
1347                 ehRet = HandleDoxmGetRequest(ehRequest);
1348                 break;
1349
1350             case OC_REST_POST:
1351                 ehRet = HandleDoxmPostRequest(ehRequest);
1352                 break;
1353
1354             default:
1355                 ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1356                                OC_EH_OK : OC_EH_ERROR;
1357                 break;
1358         }
1359     }
1360
1361     return ehRet;
1362 }
1363
1364 OCStackResult CreateDoxmResource()
1365 {
1366     OCStackResult ret = OCCreateResource(&gDoxmHandle,
1367                                          OIC_RSRC_TYPE_SEC_DOXM,
1368                                          OC_RSRVD_INTERFACE_DEFAULT,
1369                                          OIC_RSRC_DOXM_URI,
1370                                          DoxmEntityHandler,
1371                                          NULL,
1372                                          OC_SECURE |
1373                                          OC_DISCOVERABLE);
1374
1375     if (OC_STACK_OK != ret)
1376     {
1377         OIC_LOG (FATAL, TAG, "Unable to instantiate Doxm resource");
1378         DeInitDoxmResource();
1379     }
1380     return ret;
1381 }
1382
1383 /**
1384  * Checks if DeviceID is generated during provisioning for the new device.
1385  * If DeviceID is NULL then generates the new DeviceID.
1386  * Once DeviceID is assigned to the device it does not change for the lifetime of the device.
1387  */
1388 static OCStackResult CheckDeviceID()
1389 {
1390     OCStackResult ret = OC_STACK_ERROR;
1391     bool validId = false;
1392     for (uint8_t i = 0; i < UUID_LENGTH; i++)
1393     {
1394         if (gDoxm->deviceID.id[i] != 0)
1395         {
1396             validId = true;
1397             break;
1398         }
1399     }
1400
1401     if (!validId)
1402     {
1403         if (OCGenerateUuid(gDoxm->deviceID.id) != RAND_UUID_OK)
1404         {
1405             OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
1406             return ret;
1407         }
1408         ret = OC_STACK_OK;
1409
1410         if (!UpdatePersistentStorage(gDoxm))
1411         {
1412             //TODO: After registering PSI handler in all samples, do ret = OC_STACK_OK here.
1413             OIC_LOG(FATAL, TAG, "UpdatePersistentStorage failed!");
1414         }
1415     }
1416     else
1417     {
1418         ret = OC_STACK_OK;
1419     }
1420     return ret;
1421 }
1422
1423 /**
1424  * Get the default value.
1425  *
1426  * @return the default value of doxm, @ref OicSecDoxm_t.
1427  */
1428 static OicSecDoxm_t* GetDoxmDefault()
1429 {
1430     OIC_LOG(DEBUG, TAG, "GetDoxmToDefault");
1431     return &gDefaultDoxm;
1432 }
1433
1434 const OicSecDoxm_t* GetDoxmResourceData()
1435 {
1436     return gDoxm;
1437 }
1438
1439 #if defined(__WITH_DTLS__) && defined(_ENABLE_MULTIPLE_OWNER_)
1440 /**
1441  * Internal API to prepare MOT
1442  */
1443 static void PrepareMOT(const OicSecDoxm_t* doxm)
1444 {
1445     OIC_LOG(INFO, TAG, "IN PrepareMOT");
1446     VERIFY_NON_NULL(TAG, doxm, ERROR);
1447
1448     if(true == doxm->owned && NULL != doxm->mom && OIC_MULTIPLE_OWNER_DISABLE != doxm->mom->mode)
1449     {
1450         CAResult_t caRes = CA_STATUS_FAILED;
1451
1452         OIC_LOG(INFO, TAG, "Multiple Ownership Transfer Enabled!");
1453
1454         if(OIC_PRECONFIG_PIN == doxm->oxmSel)
1455         {
1456             caRes = CAEnableAnonECDHCipherSuite(false);
1457             VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1458             OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1459
1460             caRes = CASelectCipherSuite((uint16_t)TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256, CA_ADAPTER_IP);
1461             VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1462 #ifdef __WITH_TLS__
1463             caRes = CASelectCipherSuite((uint16_t)TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256, CA_ADAPTER_TCP);
1464             VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1465 #endif
1466             OIC_LOG(INFO, TAG, "ECDHE_PSK CipherSuite will be used for MOT");
1467
1468             //Set the device id to derive temporal PSK
1469             SetUuidForPinBasedOxm(&doxm->deviceID);
1470         }
1471         else
1472         {
1473             OIC_LOG(ERROR, TAG, "Unsupported OxM for Multiple Ownership Transfer.");
1474             return;
1475         }
1476
1477         CAregisterSslHandshakeCallback(MultipleOwnerDTLSHandshakeCB);
1478     }
1479
1480     OIC_LOG(INFO, TAG, "OUT PrepareMOT");
1481     return;
1482 exit:
1483     OIC_LOG(WARNING, TAG, "Error in PrepareMOT");
1484 }
1485 #endif //defined(__WITH_DTLS__) && defined(_ENABLE_MULTIPLE_OWNER_)
1486
1487 OCStackResult InitDoxmResource()
1488 {
1489     OCStackResult ret = OC_STACK_ERROR;
1490
1491     //Read DOXM resource from PS
1492     uint8_t *data = NULL;
1493     size_t size = 0;
1494     ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_DOXM_NAME, &data, &size);
1495     // If database read failed
1496     if (OC_STACK_OK != ret)
1497     {
1498        OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
1499     }
1500     if (data)
1501     {
1502        // Read DOXM resource from PS
1503        ret = CBORPayloadToDoxm(data, size, &gDoxm);
1504     }
1505     /*
1506      * If SVR database in persistent storage got corrupted or
1507      * is not available for some reason, a default doxm is created
1508      * which allows user to initiate doxm provisioning again.
1509      */
1510      if ((OC_STACK_OK != ret) || !data || !gDoxm)
1511     {
1512         gDoxm = GetDoxmDefault();
1513     }
1514
1515     //In case of the server is shut down unintentionally, we should initialize the owner
1516     if(false == gDoxm->owned)
1517     {
1518         OicUuid_t emptyUuid = {.id={0}};
1519         memcpy(&gDoxm->owner, &emptyUuid, sizeof(OicUuid_t));
1520     }
1521
1522     ret = CheckDeviceID();
1523     if (ret == OC_STACK_OK)
1524     {
1525         OIC_LOG_V(DEBUG, TAG, "Initial Doxm Owned = %d", gDoxm->owned);
1526         //Instantiate 'oic.sec.doxm'
1527         ret = CreateDoxmResource();
1528     }
1529     else
1530     {
1531         OIC_LOG (ERROR, TAG, "CheckDeviceID failed");
1532     }
1533     OICFree(data);
1534
1535 #if defined(__WITH_DTLS__) && defined(_ENABLE_MULTIPLE_OWNER_)
1536     //if MOT is enabled, MOT should be prepared.
1537     if(gDoxm && gDoxm->owned)
1538     {
1539         PrepareMOT(gDoxm);
1540     }
1541 #endif // defined(__WITH_DTLS__) && defined(_ENABLE_MULTIPLE_OWNER_)
1542
1543     return ret;
1544 }
1545
1546 OCStackResult DeInitDoxmResource()
1547 {
1548     OCStackResult ret = OCDeleteResource(gDoxmHandle);
1549     if (gDoxm  != &gDefaultDoxm)
1550     {
1551         DeleteDoxmBinData(gDoxm);
1552     }
1553     gDoxm = NULL;
1554
1555     if (OC_STACK_OK == ret)
1556     {
1557         return OC_STACK_OK;
1558     }
1559     else
1560     {
1561         return OC_STACK_ERROR;
1562     }
1563 }
1564
1565 OCStackResult GetDoxmDeviceID(OicUuid_t *deviceID)
1566 {
1567     if (deviceID && gDoxm)
1568     {
1569        *deviceID = gDoxm->deviceID;
1570         return OC_STACK_OK;
1571     }
1572     return OC_STACK_ERROR;
1573 }
1574
1575 OCStackResult GetDoxmIsOwned(bool *isOwned)
1576 {
1577     if (isOwned && gDoxm)
1578     {
1579        *isOwned = gDoxm->owned;
1580         return OC_STACK_OK;
1581     }
1582     return OC_STACK_ERROR;
1583 }
1584
1585 OCStackResult SetDoxmDeviceID(const OicUuid_t *deviceID)
1586 {
1587     bool isPT = false;
1588
1589     if(NULL == deviceID)
1590     {
1591         return OC_STACK_INVALID_PARAM;
1592     }
1593     if(NULL == gDoxm)
1594     {
1595         OIC_LOG(ERROR, TAG, "Doxm resource is not initialized.");
1596         return OC_STACK_NO_RESOURCE;
1597     }
1598
1599     //Check the device's OTM state
1600
1601 #ifdef __WITH_DTLS__
1602     //for normal device.
1603     if(true == gDoxm->owned &&
1604        memcmp(gDoxm->deviceID.id, gDoxm->owner.id, sizeof(gDoxm->owner.id)) != 0)
1605     {
1606         OIC_LOG(ERROR, TAG, "This device owned by owner's device.");
1607         OIC_LOG(ERROR, TAG, "Device UUID cannot be changed to guarantee the reliability of the connection.");
1608         return OC_STACK_ERROR;
1609     }
1610 #endif //__WITH_DTLS
1611
1612     //Save the previous UUID
1613     OicUuid_t tempUuid;
1614     memcpy(tempUuid.id, gDoxm->deviceID.id, sizeof(tempUuid.id));
1615
1616     //Change the UUID
1617     memcpy(gDoxm->deviceID.id, deviceID->id, sizeof(deviceID->id));
1618     if(isPT)
1619     {
1620         memcpy(gDoxm->owner.id, deviceID->id, sizeof(deviceID->id));
1621         memcpy(gDoxm->rownerID.id, deviceID->id, sizeof(deviceID->id));
1622     }
1623
1624     //Update PS
1625     if(!UpdatePersistentStorage(gDoxm))
1626     {
1627         //revert UUID in case of update error
1628         memcpy(gDoxm->deviceID.id, tempUuid.id, sizeof(tempUuid.id));
1629         if(isPT)
1630         {
1631             memcpy(gDoxm->owner.id, tempUuid.id, sizeof(tempUuid.id));
1632             memcpy(gDoxm->rownerID.id, tempUuid.id, sizeof(tempUuid.id));
1633         }
1634
1635         OIC_LOG(ERROR, TAG, "Failed to update persistent storage");
1636         return OC_STACK_ERROR;
1637     }
1638     return OC_STACK_OK;
1639 }
1640
1641 OCStackResult GetDoxmDevOwnerId(OicUuid_t *devownerid)
1642 {
1643     OCStackResult retVal = OC_STACK_ERROR;
1644     if (gDoxm)
1645     {
1646         OIC_LOG_V(DEBUG, TAG, "GetDoxmDevOwnerId(): gDoxm owned =  %d.", \
1647             gDoxm->owned);
1648         if (gDoxm->owned)
1649         {
1650             *devownerid = gDoxm->owner;
1651             retVal = OC_STACK_OK;
1652         }
1653     }
1654     return retVal;
1655 }
1656
1657 OCStackResult GetDoxmRownerId(OicUuid_t *rowneruuid)
1658 {
1659     OCStackResult retVal = OC_STACK_ERROR;
1660     if (gDoxm)
1661     {
1662         if( gDoxm->owned )
1663         {
1664             *rowneruuid = gDoxm->rownerID;
1665                     retVal = OC_STACK_OK;
1666         }
1667     }
1668     return retVal;
1669 }
1670
1671 #ifdef _ENABLE_MULTIPLE_OWNER_
1672 /**
1673  * Compare the UUID to SubOwner.
1674  *
1675  * @param[in] uuid device UUID
1676  *
1677  * @return true if context->subjectId exist subowner list, else false.
1678  */
1679 bool IsSubOwner(const OicUuid_t* uuid)
1680 {
1681     bool retVal = false;
1682
1683     if(NULL == uuid)
1684     {
1685         return retVal;
1686     }
1687
1688     if (gDoxm && gDoxm->subOwners)
1689     {
1690         OicSecSubOwner_t* subOwner = NULL;
1691         LL_FOREACH(gDoxm->subOwners, subOwner)
1692         {
1693             if(memcmp(subOwner->uuid.id, uuid->id, sizeof(uuid->id)) == 0)
1694             {
1695                 return true;
1696             }
1697         }
1698     }
1699     return retVal;
1700 }
1701 #endif //_ENABLE_MULTIPLE_OWNER_
1702
1703 /**
1704  * Function to restore doxm resurce to initial status.
1705  * This function will use in case of error while ownership transfer
1706  */
1707 void RestoreDoxmToInitState()
1708 {
1709     if(gDoxm)
1710     {
1711         OIC_LOG(INFO, TAG, "DOXM resource will revert back to initial status.");
1712
1713         OicUuid_t emptyUuid = {.id={0}};
1714         memcpy(&(gDoxm->owner), &emptyUuid, sizeof(OicUuid_t));
1715         gDoxm->owned = false;
1716         gDoxm->oxmSel = OIC_JUST_WORKS;
1717
1718         if(!UpdatePersistentStorage(gDoxm))
1719         {
1720             OIC_LOG(ERROR, TAG, "Failed to revert DOXM in persistent storage");
1721         }
1722     }
1723 }