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