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