Merge branch 'tizen' into tizen_5.5
[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 #include "ocstack.h"
29 #include "oic_malloc.h"
30 #include "payload_logging.h"
31 #include "utlist.h"
32 #include "ocrandom.h"
33 #include "ocpayload.h"
34 #include "ocpayloadcbor.h"
35 #include "cainterface.h"
36 #include "ocserverrequest.h"
37 #include "resourcemanager.h"
38 #include "doxmresource.h"
39 #include "pstatresource.h"
40 #include "aclresource.h"
41 #include "amaclresource.h"
42 #include "pconfresource.h"
43 #include "dpairingresource.h"
44 #include "psinterface.h"
45 #include "srmresourcestrings.h"
46 #include "securevirtualresourcetypes.h"
47 #include "credresource.h"
48 #include "srmutility.h"
49 #include "pinoxmcommon.h"
50 #include "oxmverifycommon.h"
51 #include "octhread.h"
52 #include "oic_time.h"
53 #include "oic_string.h"
54
55 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
56 #include "pkix_interface.h"
57 #include "ca_adapter_net_ssl.h"
58 #endif
59
60 #define TAG  "OIC_SRM_DOXM"
61 #define CHAR_ZERO ('0')
62
63 /** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
64  * The value of payload size is increased until reaching belox max cbor size. */
65 static const uint16_t CBOR_SIZE = 512;
66
67 /** Max cbor size payload. */
68 static const uint16_t CBOR_MAX_SIZE = 4400;
69
70 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
71 /** MAX uuid seed size */
72 #define MAX_UUID_SEED_SIZE (64)
73 /** MIN uuid seed size */
74 #define MIN_UUID_SEED_SIZE (8)
75
76 /** Buffer to save the seed of device UUID */
77 static uint8_t gUuidSeed[MAX_UUID_SEED_SIZE];
78 static size_t gUuidSeedSize = 0;
79 #endif
80
81 #ifdef MULTIPLE_OWNER
82 #define MAX_SUBOWNER_SIZE (64)
83 #define MIN_SUBOWNER_SIZE (1)
84 #define DEFAULT_SUBOWNER_SIZE (32)
85
86 static size_t gMaxSubOwnerSize = DEFAULT_SUBOWNER_SIZE;
87 #endif
88
89 typedef enum ConfirmState{
90     CONFIRM_STATE_READY = 0,
91     CONFIRM_STATE_WAIT = 1,
92     CONFIRM_STATE_ACCEPTED = 2,
93     CONFIRM_STATE_DENIED = 3
94 }ConfirmState_t;
95
96 static OicSecDoxm_t        *gDoxm = NULL;
97 static oc_mutex            g_mutexDoxm = NULL;
98 static bool                g_isDoxmNull = false;
99 static OCResourceHandle    gDoxmHandle = NULL;
100 static oc_mutex            g_mutexWait;
101 static oc_thread           g_waitConfirmThreadId;
102 oc_cond                    g_condWait;
103 static InformOxmSelectedCallback_t g_InformOxmSelectedCallback = NULL;
104 static bool                g_isConfirmResult;
105
106 static OicSecOxm_t gOicSecDoxmJustWorks = OIC_JUST_WORKS;
107 static OicSecDoxm_t gDefaultDoxm =
108 {
109     NULL,                   /* OicUrn_t *oxmType */
110     0,                      /* size_t oxmTypeLen */
111     &gOicSecDoxmJustWorks,  /* uint16_t *oxm */
112     1,                      /* size_t oxmLen */
113     OIC_JUST_WORKS,         /* uint16_t oxmSel */
114     SYMMETRIC_PAIR_WISE_KEY,/* OicSecCredType_t sct */
115     false,                  /* bool owned */
116     {.id = {0}},            /* OicUuid_t deviceID */
117     false,                  /* bool dpc */
118     {.id = {0}},            /* OicUuid_t owner */
119 #ifdef MULTIPLE_OWNER
120     NULL,                   /* OicSecSubOwner_t sub-owner list */
121     NULL,                   /* OicSecMomType_t multiple owner mode */
122 #endif //MULTIPLE_OWNER
123     {.id = {0}},            /* OicUuid_t rownerID */
124 };
125
126 static uint16_t gConfirmMsgId = 0;
127 static ConfirmState_t gConfirmState = CONFIRM_STATE_READY;
128
129 static uint8_t gEmptyUuid[UUID_LENGTH] = {0};
130
131 /**
132  * This method is internal method.
133  * the param roParsed is optionally used to know whether cborPayload has
134  * at least read only property value or not.
135  */
136 static OCStackResult CBORPayloadToDoxmBin(const uint8_t *cborPayload, size_t size,
137                                 OicSecDoxm_t **doxm, bool *roParsed);
138
139 void DeleteDoxmBinData(OicSecDoxm_t* doxm)
140 {
141     if (doxm)
142     {
143         //Clean oxmType
144         for (size_t i = 0; i < doxm->oxmTypeLen; i++)
145         {
146             OICFree(doxm->oxmType[i]);
147         }
148         OICFree(doxm->oxmType);
149
150         //clean oxm
151         OICFree(doxm->oxm);
152
153 #ifdef MULTIPLE_OWNER
154         //clean mom
155         OICFree(doxm->mom);
156
157         //clean sub-owner list
158         if(NULL != doxm->subOwners)
159         {
160             OicSecSubOwner_t* subowner = NULL;
161             OicSecSubOwner_t* temp = NULL;
162             LL_FOREACH_SAFE(doxm->subOwners, subowner, temp)
163             {
164                 LL_DELETE(doxm->subOwners, subowner);
165                 OICFree(subowner);
166             }
167         }
168 #endif //MULTIPLE_OWNER
169
170         //Clean doxm itself
171         OICFree(doxm);
172     }
173
174     if(g_mutexDoxm)
175     {
176         oc_mutex_free(g_mutexDoxm);
177         g_mutexDoxm = NULL;
178     }
179 }
180
181 OCStackResult DoxmToCBORPayload(const OicSecDoxm_t *doxm, uint8_t **payload, size_t *size,
182                                 bool rwOnly)
183 {
184     if (NULL == doxm || NULL == payload || NULL != *payload || NULL == size)
185     {
186         return OC_STACK_INVALID_PARAM;
187     }
188     size_t cborLen = *size;
189     if (0 == cborLen)
190     {
191         cborLen = CBOR_SIZE;
192     }
193     *payload = NULL;
194     *size = 0;
195
196     OCStackResult ret = OC_STACK_ERROR;
197
198     CborEncoder encoder;
199     CborEncoder doxmMap;
200     char* strUuid = NULL;
201
202     int64_t cborEncoderResult = CborNoError;
203
204     uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
205     VERIFY_NON_NULL(TAG, outPayload, ERROR);
206     cbor_encoder_init(&encoder, outPayload, cborLen, 0);
207
208     cborEncoderResult = cbor_encoder_create_map(&encoder, &doxmMap, CborIndefiniteLength);
209     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Doxm Map.");
210
211     //OxmType -- Not Mandatory
212     if (doxm->oxmTypeLen > 0)
213     {
214         CborEncoder oxmType;
215         cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_TYPE_NAME,
216             strlen(OIC_JSON_OXM_TYPE_NAME));
217         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Tag.");
218         cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxmType, doxm->oxmTypeLen);
219         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Array.");
220
221         for (size_t i = 0; i < doxm->oxmTypeLen; i++)
222         {
223             cborEncoderResult = cbor_encode_text_string(&oxmType, doxm->oxmType[i],
224                 strlen(doxm->oxmType[i]));
225             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Value.");
226         }
227         cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxmType);
228         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmType.");
229     }
230
231     //Oxm -- Not Mandatory
232     if (doxm->oxmLen > 0 && false == rwOnly)
233     {
234         CborEncoder oxm;
235         cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXMS_NAME,
236             strlen(OIC_JSON_OXMS_NAME));
237         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Tag.");
238         cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxm, doxm->oxmLen);
239         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Array.");
240
241         for (size_t i = 0; i < doxm->oxmLen; i++)
242         {
243             cborEncoderResult = cbor_encode_int(&oxm, doxm->oxm[i]);
244             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Value");
245         }
246         cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxm);
247         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmName.");
248     }
249
250     //OxmSel -- Mandatory
251     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_SEL_NAME,
252         strlen(OIC_JSON_OXM_SEL_NAME));
253     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Tag.");
254     cborEncoderResult = cbor_encode_int(&doxmMap, doxm->oxmSel);
255     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Value.");
256
257     //sct -- Mandatory
258     if (false == rwOnly)
259     {
260         cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_SUPPORTED_CRED_TYPE_NAME,
261             strlen(OIC_JSON_SUPPORTED_CRED_TYPE_NAME));
262         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Tag");
263         cborEncoderResult = cbor_encode_int(&doxmMap, doxm->sct);
264         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Value.");
265     }
266
267     //Owned -- Mandatory
268     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OWNED_NAME,
269         strlen(OIC_JSON_OWNED_NAME));
270     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Tag.");
271     cborEncoderResult = cbor_encode_boolean(&doxmMap, doxm->owned);
272     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Value.");
273
274     if (false == rwOnly)
275     {
276         //DeviceId -- Mandatory
277         cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVICE_ID_NAME,
278             strlen(OIC_JSON_DEVICE_ID_NAME));
279         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Tag.");
280         ret = ConvertUuidToStr(&doxm->deviceID, &strUuid);
281         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
282         cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
283         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Value.");
284         OICFree(strUuid);
285         strUuid = NULL;
286     }
287
288 #ifdef MULTIPLE_OWNER
289     //Device SubOwnerID -- Not Mandatory
290     if(doxm->subOwners)
291     {
292         size_t subOwnerLen = 0;
293         OicSecSubOwner_t* subOwner = NULL;
294         LL_FOREACH(doxm->subOwners, subOwner)
295         {
296             subOwnerLen++;
297         }
298
299         CborEncoder subOwners;
300         cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_SUBOWNERID_NAME,
301             strlen(OIC_JSON_SUBOWNERID_NAME));
302         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SubOwnerId Tag.");
303         cborEncoderResult = cbor_encoder_create_array(&doxmMap, &subOwners, subOwnerLen);
304         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SubOwner Array.");
305
306         subOwner = NULL;
307         LL_FOREACH(doxm->subOwners, subOwner)
308         {
309             char* strUuid = NULL;
310             ret = ConvertUuidToStr(&subOwner->uuid, &strUuid);
311             VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
312             cborEncoderResult = cbor_encode_text_string(&subOwners, strUuid, strlen(strUuid));
313             OICFree(strUuid);
314             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SubOwnerId Value");
315         }
316         cborEncoderResult = cbor_encoder_close_container(&doxmMap, &subOwners);
317         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing SubOwnerId.");
318     }
319
320     //Multiple Owner Mode -- Not Mandatory
321     if(doxm->mom)
322     {
323         cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_MOM_NAME,
324             strlen(OIC_JSON_MOM_NAME));
325         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding mom Tag");
326         cborEncoderResult = cbor_encode_int(&doxmMap, (int64_t)doxm->mom->mode);
327         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding mom Value.");
328     }
329 #endif //MULTIPLE_OWNER
330
331     //devownerid -- Mandatory
332     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVOWNERID_NAME,
333         strlen(OIC_JSON_DEVOWNERID_NAME));
334     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Id Tag.");
335     ret = ConvertUuidToStr(&doxm->owner, &strUuid);
336     VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
337     cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
338     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Id Value.");
339     OICFree(strUuid);
340     strUuid = NULL;
341
342     //ROwner -- Mandatory
343     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_ROWNERID_NAME,
344         strlen(OIC_JSON_ROWNERID_NAME));
345     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Tag.");
346     ret = ConvertUuidToStr(&doxm->rownerID, &strUuid);
347     VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
348     cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
349     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Value.");
350     OICFree(strUuid);
351     strUuid = NULL;
352
353     //RT -- Mandatory
354     CborEncoder rtArray;
355     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_RT_NAME,
356             strlen(OIC_JSON_RT_NAME));
357     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Name Tag.");
358     cborEncoderResult = cbor_encoder_create_array(&doxmMap, &rtArray, 1);
359     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Value.");
360     for (size_t i = 0; i < 1; i++)
361     {
362         cborEncoderResult = cbor_encode_text_string(&rtArray, OIC_RSRC_TYPE_SEC_DOXM,
363                 strlen(OIC_RSRC_TYPE_SEC_DOXM));
364         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding RT Value.");
365     }
366     cborEncoderResult = cbor_encoder_close_container(&doxmMap, &rtArray);
367     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing RT.");
368
369     //IF-- Mandatory
370      CborEncoder ifArray;
371      cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_IF_NAME,
372              strlen(OIC_JSON_IF_NAME));
373      VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Name Tag.");
374      cborEncoderResult = cbor_encoder_create_array(&doxmMap, &ifArray, 1);
375      VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Value.");
376     for (size_t i = 0; i < 1; i++)
377     {
378         cborEncoderResult = cbor_encode_text_string(&ifArray, OC_RSRVD_INTERFACE_DEFAULT,
379                 strlen(OC_RSRVD_INTERFACE_DEFAULT));
380         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding IF Value.");
381     }
382     cborEncoderResult = cbor_encoder_close_container(&doxmMap, &ifArray);
383     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing IF.");
384
385     cborEncoderResult = cbor_encoder_close_container(&encoder, &doxmMap);
386     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing DoxmMap.");
387
388     if (CborNoError == cborEncoderResult)
389     {
390         *size = cbor_encoder_get_buffer_size(&encoder, outPayload);
391         *payload = outPayload;
392         ret = OC_STACK_OK;
393     }
394 exit:
395     if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
396     {
397         OIC_LOG(DEBUG, TAG, "Memory getting reallocated.");
398         // reallocate and try again!
399         OICFree(outPayload);
400         outPayload = NULL;
401         // Since the allocated initial memory failed, double the memory.
402         cborLen += cbor_encoder_get_buffer_size(&encoder, encoder.end);
403         OIC_LOG_V(DEBUG, TAG, "Doxm reallocation size : %zd.", cborLen);
404         cborEncoderResult = CborNoError;
405         ret = DoxmToCBORPayload(doxm, payload, &cborLen, rwOnly);
406         *size = cborLen;
407     }
408
409     if ((CborNoError != cborEncoderResult) || (OC_STACK_OK != ret))
410     {
411        OICFree(outPayload);
412        outPayload = NULL;
413        *payload = NULL;
414        *size = 0;
415        ret = OC_STACK_ERROR;
416     }
417
418     return ret;
419 }
420
421 OCStackResult CBORPayloadToDoxm(const uint8_t *cborPayload, size_t size,
422                                 OicSecDoxm_t **secDoxm)
423 {
424     return CBORPayloadToDoxmBin(cborPayload, size, secDoxm, NULL);
425 }
426
427 static OCStackResult CBORPayloadToDoxmBin(const uint8_t *cborPayload, size_t size,
428                                 OicSecDoxm_t **secDoxm, bool *roParsed)
429 {
430     if (NULL == cborPayload || NULL == secDoxm || NULL != *secDoxm || 0 == size)
431     {
432         return OC_STACK_INVALID_PARAM;
433     }
434
435     OCStackResult ret = OC_STACK_ERROR;
436     *secDoxm = NULL;
437
438     CborParser parser;
439     CborError cborFindResult = CborNoError;
440     char* strUuid = NULL;
441     size_t len = 0;
442     CborValue doxmCbor;
443
444     cbor_parser_init(cborPayload, size, 0, &parser, &doxmCbor);
445     CborValue doxmMap;
446     OicSecDoxm_t *doxm = (OicSecDoxm_t *)OICCalloc(1, sizeof(*doxm));
447     VERIFY_NON_NULL(TAG, doxm, ERROR);
448
449     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_TYPE_NAME, &doxmMap);
450     //OxmType -- not Mandatory
451     if (CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
452     {
453         CborValue oxmType;
454
455         cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmTypeLen);
456         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmTypeLen.");
457         VERIFY_SUCCESS(TAG, doxm->oxmTypeLen != 0, ERROR);
458
459         doxm->oxmType = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(*doxm->oxmType));
460         VERIFY_NON_NULL(TAG, doxm->oxmType, ERROR);
461
462         cborFindResult = cbor_value_enter_container(&doxmMap, &oxmType);
463         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmType Array.")
464
465         int i = 0;
466         size_t len = 0;
467         while (cbor_value_is_valid(&oxmType) && cbor_value_is_text_string(&oxmType))
468         {
469             cborFindResult = cbor_value_dup_text_string(&oxmType, &doxm->oxmType[i++],
470                                                         &len, NULL);
471             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding omxType text string.");
472             cborFindResult = cbor_value_advance(&oxmType);
473             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmType.");
474         }
475     }
476
477     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXMS_NAME, &doxmMap);
478     //Oxm -- not Mandatory
479     if (CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
480     {
481         CborValue oxm;
482         cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmLen);
483         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName array Length.");
484         VERIFY_SUCCESS(TAG, doxm->oxmLen != 0, ERROR);
485
486         doxm->oxm = (OicSecOxm_t *)OICCalloc(doxm->oxmLen, sizeof(*doxm->oxm));
487         VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
488
489         cborFindResult = cbor_value_enter_container(&doxmMap, &oxm);
490         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmName Array.")
491
492         int i = 0;
493         while (cbor_value_is_valid(&oxm) && cbor_value_is_integer(&oxm))
494         {
495             int tmp;
496
497             cborFindResult = cbor_value_get_int(&oxm, &tmp);
498             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName Value")
499             doxm->oxm[i++] = (OicSecOxm_t)tmp;
500             cborFindResult = cbor_value_advance(&oxm);
501             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmName.")
502         }
503
504         if (roParsed)
505         {
506             *roParsed = true;
507         }
508     }
509     else
510     {
511         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
512         doxm->oxm = (OicSecOxm_t *) OICCalloc(gDoxm->oxmLen, sizeof(*doxm->oxm));
513         VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
514         doxm->oxmLen = gDoxm->oxmLen;
515         for (size_t i = 0; i < gDoxm->oxmLen; i++)
516         {
517             doxm->oxm[i] = gDoxm->oxm[i];
518         }
519     }
520
521     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_SEL_NAME, &doxmMap);
522     if (CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
523     {
524         int oxmSel;
525
526         cborFindResult = cbor_value_get_int(&doxmMap, &oxmSel);
527         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sel Name Value.")
528         doxm->oxmSel = (OicSecOxm_t)oxmSel;
529     }
530     else // PUT/POST JSON may not have oxmsel so set it to the gDoxm->oxmSel
531     {
532         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
533         doxm->oxmSel = gDoxm->oxmSel;
534     }
535
536     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_SUPPORTED_CRED_TYPE_NAME, &doxmMap);
537     if (CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
538     {
539         int sct;
540
541         cborFindResult = cbor_value_get_int(&doxmMap, &sct);
542         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sct Name Value.")
543         doxm->sct = (OicSecCredType_t)sct;
544
545         if (roParsed)
546         {
547             *roParsed = true;
548         }
549     }
550     else // PUT/POST JSON may not have sct so set it to the gDoxm->sct
551     {
552         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
553         doxm->sct = gDoxm->sct;
554     }
555
556     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OWNED_NAME, &doxmMap);
557     if (CborNoError == cborFindResult && cbor_value_is_boolean(&doxmMap))
558     {
559         cborFindResult = cbor_value_get_boolean(&doxmMap, &doxm->owned);
560         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owned Value.")
561     }
562     else // PUT/POST JSON may not have owned so set it to the gDomx->owned
563     {
564         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
565         doxm->owned = gDoxm->owned;
566     }
567
568     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVICE_ID_NAME, &doxmMap);
569     if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
570     {
571         cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
572         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Device Id Value.");
573         ret = ConvertStrToUuid(strUuid , &doxm->deviceID);
574         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
575         OICFree(strUuid);
576         strUuid  = NULL;
577     }
578     else
579     {
580         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
581         memcpy(doxm->deviceID.id, &gDoxm->deviceID.id, sizeof(doxm->deviceID.id));
582     }
583
584     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVOWNERID_NAME, &doxmMap);
585     if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
586     {
587         cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
588         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owner Value.");
589         ret = ConvertStrToUuid(strUuid , &doxm->owner);
590         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
591         OICFree(strUuid);
592         strUuid  = NULL;
593     }
594     else
595     {
596         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
597         memcpy(doxm->owner.id, gDoxm->owner.id, sizeof(doxm->owner.id));
598     }
599
600 #ifdef MULTIPLE_OWNER
601     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_MOM_NAME, &doxmMap);
602     if(CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
603     {
604         int mode = 0;
605         cborFindResult = cbor_value_get_int(&doxmMap, &mode);
606         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding mom Name Value.")
607         if(NULL == doxm->mom)
608         {
609             doxm->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
610             VERIFY_NON_NULL(TAG, doxm->mom, ERROR);
611         }
612         doxm->mom->mode = (OicSecMomType_t)mode;
613     }
614     else if(NULL != gDoxm && NULL != gDoxm->mom)
615     {
616         // PUT/POST JSON may not have 'mom' so set it to the gDomx->mom
617         if(NULL == doxm->mom)
618         {
619             doxm->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
620             VERIFY_NON_NULL(TAG, doxm->mom, ERROR);
621         }
622         doxm->mom->mode = gDoxm->mom->mode;
623     }
624
625     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_SUBOWNERID_NAME, &doxmMap);
626     if(CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
627     {
628         size_t subOwnerLen = 0;
629         CborValue subOwnerCbor;
630         cborFindResult = cbor_value_get_array_length(&doxmMap, &subOwnerLen);
631         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SubOwner array Length.");
632         VERIFY_SUCCESS(TAG, 0 != subOwnerLen, ERROR);
633
634         cborFindResult = cbor_value_enter_container(&doxmMap, &subOwnerCbor);
635         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering SubOwner Array.")
636
637         while (cbor_value_is_valid(&subOwnerCbor) && cbor_value_is_text_string(&subOwnerCbor))
638         {
639             OCStackResult convertRes = OC_STACK_ERROR;
640             OicSecSubOwner_t* subOwner = NULL;
641             char* strUuid = NULL;
642             size_t uuidLen = 0;
643
644             cborFindResult = cbor_value_dup_text_string(&subOwnerCbor, &strUuid, &uuidLen, NULL);
645             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SubOwnerId Value");
646
647             subOwner = (OicSecSubOwner_t*)OICCalloc(1, sizeof(OicSecSubOwner_t));
648             VERIFY_NON_NULL(TAG, subOwner, ERROR);
649
650             convertRes = ConvertStrToUuid(strUuid, &subOwner->uuid);
651             VERIFY_SUCCESS(TAG, OC_STACK_OK == convertRes, ERROR);
652             subOwner->status = MOT_STATUS_DONE;
653             LL_APPEND(doxm->subOwners, subOwner);
654
655             cborFindResult = cbor_value_advance(&subOwnerCbor);
656             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing SubOwnerId.")
657         }
658     }
659     else if(NULL != gDoxm && NULL != gDoxm->subOwners)
660     {
661         // PUT/POST JSON may not have 'subOwners' so set it to the gDomx->subOwners
662         OicSecSubOwner_t* subOwnerItor = NULL;
663         LL_FOREACH(gDoxm->subOwners, subOwnerItor)
664         {
665             OicSecSubOwner_t* subOwnerId = (OicSecSubOwner_t*)OICCalloc(1, sizeof(OicSecSubOwner_t));
666             VERIFY_NON_NULL(TAG, subOwnerId, ERROR);
667
668             memcpy(&subOwnerId->uuid, &subOwnerItor->uuid, sizeof(OicUuid_t));
669             subOwnerId->status = MOT_STATUS_DONE;
670
671             LL_APPEND(doxm->subOwners, subOwnerId);
672         }
673     }
674 #endif //MULTIPLE_OWNER
675
676     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_ROWNERID_NAME, &doxmMap);
677     if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
678     {
679         cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
680         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding ROwner Value.");
681         ret = ConvertStrToUuid(strUuid , &doxm->rownerID);
682         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
683         OICFree(strUuid);
684         strUuid  = NULL;
685     }
686     else
687     {
688         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
689         memcpy(doxm->rownerID.id, gDoxm->rownerID.id, sizeof(doxm->rownerID.id));
690     }
691
692     *secDoxm = doxm;
693     ret = OC_STACK_OK;
694
695 exit:
696     if (CborNoError != cborFindResult)
697     {
698         OIC_LOG (ERROR, TAG, "CBORPayloadToDoxm failed!!!");
699         DeleteDoxmBinData(doxm);
700         doxm = NULL;
701         *secDoxm = NULL;
702         ret = OC_STACK_ERROR;
703     }
704     return ret;
705 }
706
707 /**
708  * @todo document this function including why code might need to call this.
709  * The current suspicion is that it's not being called as much as it should.
710  */
711 static bool UpdatePersistentStorage(OicSecDoxm_t * doxm)
712 {
713     bool bRet = false;
714
715     if (NULL != doxm)
716     {
717         // Convert Doxm data into CBOR for update to persistent storage
718         uint8_t *payload = NULL;
719         size_t size = 0;
720         OCStackResult res = DoxmToCBORPayload(doxm, &payload, &size, false);
721         if (payload && (OC_STACK_OK == res)
722             && (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, payload, size)))
723         {
724                 bRet = true;
725         }
726         OICFree(payload);
727     }
728     else
729     {
730         if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, NULL, 0))
731         {
732                 bRet = true;
733         }
734     }
735
736     return bRet;
737 }
738
739 OCStackResult SetDoxmDeviceIDResetPF(const OicUuid_t *deviceID)
740 {
741     OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
742
743     OCStackResult res = OC_STACK_ERROR;
744     size_t dbSize = 0;
745     uint8_t *dbData = NULL;
746     uint8_t *aclCbor = NULL;
747     uint8_t *credCbor = NULL;
748     uint8_t *pstatCbor = NULL;
749     uint8_t *doxmCbor = NULL;
750     uint8_t *resetPfCbor = NULL;
751     int64_t cborEncoderResult = CborNoError;
752
753     if (NULL == deviceID)
754     {
755         OIC_LOG_V(ERROR, TAG, "%s - deviceID is NULL!", __func__);
756         return res;
757     }
758
759     res = GetSecureVirtualDatabaseFromPS(NULL, &dbData, &dbSize);
760     if (OC_STACK_OK != res)
761     {
762         OIC_LOG_V(ERROR, TAG, "GetSecureVirtualDatabaseFromPS() is failed(%d)", res);
763         return res;
764     }
765     if (dbData && dbSize)
766     {
767         size_t aclCborLen = 0;
768         size_t credCborLen = 0;
769         size_t pstatCborLen = 0;
770         size_t doxmCborLen = 0;
771         size_t resetPfCborLen = 0;
772         OicSecDoxm_t *tmpDoxm = NULL;
773
774         {
775             CborParser parser;
776             CborValue cbor;
777             cbor_parser_init(dbData, dbSize, 0, &parser, &cbor);
778             CborValue curVal = {0};
779             CborError cborFindResult = CborNoError;
780
781             // abort if reset profile doesn't exist
782             cborFindResult = cbor_value_map_find_value(&cbor, OIC_JSON_RESET_PF_NAME, &curVal);
783             if (CborNoError != cborFindResult || !cbor_value_is_byte_string(&curVal))
784             {
785                 OIC_LOG(DEBUG, TAG, "Reset Profile doesn't exist!");
786                 res=OC_STACK_ERROR;
787                 goto exit;
788             }
789             cborFindResult = cbor_value_map_find_value(&cbor, OIC_JSON_ACL_NAME, &curVal);
790             if (CborNoError == cborFindResult && cbor_value_is_byte_string(&curVal))
791             {
792                 cborFindResult = cbor_value_dup_byte_string(&curVal, &aclCbor, &aclCborLen, NULL);
793                 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding ACL Name Value.");
794             }
795             cborFindResult = cbor_value_map_find_value(&cbor, OIC_JSON_CRED_NAME, &curVal);
796             if (CborNoError == cborFindResult && cbor_value_is_byte_string(&curVal))
797             {
798                 cborFindResult = cbor_value_dup_byte_string(&curVal, &credCbor, &credCborLen, NULL);
799                 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding CRED Name Value.");
800             }
801             cborFindResult = cbor_value_map_find_value(&cbor, OIC_JSON_PSTAT_NAME, &curVal);
802             if (CborNoError == cborFindResult && cbor_value_is_byte_string(&curVal))
803             {
804                 cborFindResult = cbor_value_dup_byte_string(&curVal, &pstatCbor, &pstatCborLen, NULL);
805                 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding PSTAT Name Value.");
806             }
807             cborFindResult = cbor_value_map_find_value(&cbor, OIC_JSON_DOXM_NAME, &curVal);
808             if (CborNoError == cborFindResult && cbor_value_is_byte_string(&curVal))
809             {
810                 cborFindResult = cbor_value_dup_byte_string(&curVal, &doxmCbor, &doxmCborLen, NULL);
811                 VERIFY_CBOR_SUCCESS(TAG, cborFindResult,  "Failed Finding DOXM Name Value.");
812
813                 res = CBORPayloadToDoxm(doxmCbor, doxmCborLen, &tmpDoxm);
814                 if (OC_STACK_OK != res)
815                 {
816                     OIC_LOG_V(ERROR, TAG, "%s - CBORPayloadToDoxm error : %d", __func__, res);
817                     goto exit;
818                 }
819                 VERIFY_NON_NULL(TAG, tmpDoxm, ERROR);
820                 memcpy(tmpDoxm->deviceID.id, deviceID->id, sizeof(deviceID->id));
821                 OICFree(doxmCbor);
822                 doxmCbor = NULL;
823                 doxmCborLen = 0;
824                 res = DoxmToCBORPayload(tmpDoxm, &doxmCbor, &doxmCborLen, false);
825                 if (OC_STACK_OK != res || 0 == doxmCborLen || NULL == doxmCbor)
826                 {
827                     OIC_LOG_V(ERROR, TAG,"%s - DoxmToCBORPayload error : %d", __func__, res);
828                     goto exit;
829                 }
830             }
831         }
832
833         {
834             size_t size = aclCborLen + credCborLen + pstatCborLen + doxmCborLen + 255;
835             resetPfCbor = (uint8_t *) OICCalloc(1, size);
836             VERIFY_NON_NULL(TAG, resetPfCbor, ERROR);
837             CborEncoder encoder;  // will be initialized in |cbor_parser_init|
838             cbor_encoder_init(&encoder, resetPfCbor, size, 0);
839             CborEncoder secRsrc;  // will be initialized in |cbor_encoder_create_map|
840             cborEncoderResult |= cbor_encoder_create_map(&encoder, &secRsrc, CborIndefiniteLength);
841
842             cborEncoderResult |= cbor_encode_text_string(&secRsrc, OIC_JSON_ACL_NAME, strlen(OIC_JSON_ACL_NAME));
843             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ACL Name.");
844             cborEncoderResult |= cbor_encode_byte_string(&secRsrc, aclCbor, aclCborLen);
845             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ACL Value.");
846
847             if (credCborLen)
848             {
849                 cborEncoderResult |= cbor_encode_text_string(&secRsrc, OIC_JSON_CRED_NAME, strlen(OIC_JSON_CRED_NAME));
850                 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding CRED Name.");
851                 cborEncoderResult |= cbor_encode_byte_string(&secRsrc, credCbor, credCborLen);
852                 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding CRED Value.");
853             }
854
855             cborEncoderResult |= cbor_encode_text_string(&secRsrc, OIC_JSON_PSTAT_NAME, strlen(OIC_JSON_PSTAT_NAME));
856             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PSTAT Name.");
857             cborEncoderResult |= cbor_encode_byte_string(&secRsrc, pstatCbor, pstatCborLen);
858             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding PSTAT Value.");
859
860             cborEncoderResult |= cbor_encode_text_string(&secRsrc, OIC_JSON_DOXM_NAME, strlen(OIC_JSON_DOXM_NAME));
861             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Doxm Name.");
862             cborEncoderResult |= cbor_encode_byte_string(&secRsrc, doxmCbor, doxmCborLen);
863             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Doxm Value.");
864
865             cborEncoderResult |= cbor_encoder_close_container(&encoder, &secRsrc);
866             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Array.");
867             resetPfCborLen = cbor_encoder_get_buffer_size(&encoder, resetPfCbor);
868         }
869
870         res = UpdateSecureResourceInPS(OIC_JSON_RESET_PF_NAME, resetPfCbor, resetPfCborLen);
871         if (OC_STACK_OK != res)
872         {
873             OIC_LOG_V(ERROR, TAG, "%s - Error in UpdateSecureResourceInPS", __func__);
874         }
875     }
876     OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
877
878 exit:
879     OICFree(dbData);
880     OICFree(aclCbor);
881     OICFree(credCbor);
882     OICFree(pstatCbor);
883     OICFree(doxmCbor);
884     OICFree(resetPfCbor);
885
886     return res;
887 }
888
889 static bool ValidateQuery(const char * query)
890 {
891     // Send doxm resource data if the state of doxm resource
892     // matches with the query parameters.
893     // else send doxm resource data as NULL
894     // TODO Remove this check and rely on Policy Engine
895     // and Provisioning Mode to enforce provisioning-state
896     // access rules. Eventually, the PE and PM code will
897     // not send a request to the /doxm Entity Handler at all
898     // if it should not respond.
899     OIC_LOG (DEBUG, TAG, "In ValidateQuery");
900     if(NULL == gDoxm)
901     {
902         return false;
903     }
904
905     bool bOwnedQry = false;         // does querystring contains 'owned' query ?
906     bool bOwnedMatch = false;       // does 'owned' query value matches with doxm.owned status?
907     bool bDeviceIDQry = false;      // does querystring contains 'deviceid' query ?
908     bool bDeviceIDMatch = false;    // does 'deviceid' query matches with doxm.deviceid ?
909     bool bInterfaceQry = false;      // does querystring contains 'if' query ?
910     bool bInterfaceMatch = false;    // does 'if' query matches with oic.if.baseline ?
911 #ifdef MULTIPLE_OWNER
912     bool bMotMatch = false;       // does 'mom' query value is not '0' && does query value matches with doxm.owned status?
913 #endif //MULTIPLE_OWNER
914
915     OicParseQueryIter_t parseIter = {.attrPos = NULL};
916
917     ParseQueryIterInit((unsigned char*)query, &parseIter);
918
919     while (GetNextQuery(&parseIter))
920     {
921         if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
922         {
923             bOwnedQry = true;
924             if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
925                     (gDoxm->owned))
926             {
927                 bOwnedMatch = true;
928             }
929             else if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_FALSE, parseIter.valLen) == 0)
930                     && (!gDoxm->owned))
931             {
932                 bOwnedMatch = true;
933             }
934         }
935
936 #ifdef MULTIPLE_OWNER
937         if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_MOM_NAME, strlen(OIC_JSON_MOM_NAME)) == 0)
938         {
939             OicSecMomType_t momMode = (OicSecMomType_t)(parseIter.valPos[0] - CHAR_ZERO);
940             if(NULL != gDoxm->mom && momMode != gDoxm->mom->mode)
941             {
942                 if(GetNextQuery(&parseIter))
943                 {
944                     if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
945                     {
946                         if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
947                                 (gDoxm->owned))
948                         {
949                             bMotMatch = true;
950                         }
951                     }
952                 }
953             }
954             return bMotMatch;
955         }
956 #endif //MULTIPLE_OWNER
957
958         if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_DEVICE_ID_NAME, parseIter.attrLen) == 0)
959         {
960             bDeviceIDQry = true;
961             OicUuid_t subject = {.id={0}};
962
963             memcpy(subject.id, parseIter.valPos, parseIter.valLen);
964             if (0 == memcmp(&gDoxm->deviceID.id, &subject.id, sizeof(gDoxm->deviceID.id)))
965             {
966                 bDeviceIDMatch = true;
967             }
968         }
969
970         if (strncasecmp((char *)parseIter.attrPos, OC_RSRVD_INTERFACE, parseIter.attrLen) == 0)
971         {
972             bInterfaceQry = true;
973             if ((strncasecmp((char *)parseIter.valPos, OC_RSRVD_INTERFACE_DEFAULT, parseIter.valLen) == 0))
974             {
975                 bInterfaceMatch = true;
976             }
977             return (bInterfaceQry ? bInterfaceMatch: true);
978         }
979     }
980
981     return ((bOwnedQry ? bOwnedMatch : true) &&
982             (bDeviceIDQry ? bDeviceIDMatch : true));
983 }
984
985 static OCEntityHandlerResult HandleDoxmGetRequest (const OCEntityHandlerRequest * ehRequest)
986 {
987     OCEntityHandlerResult ehRet = OC_EH_OK;
988
989     OIC_LOG(DEBUG, TAG, "Doxm EntityHandle processing GET request");
990
991     //Checking if Get request is a query.
992     if (ehRequest->query)
993     {
994         OIC_LOG_V(DEBUG,TAG,"query:%s",ehRequest->query);
995         OIC_LOG(DEBUG, TAG, "HandleDoxmGetRequest processing query");
996         if (!ValidateQuery(ehRequest->query))
997         {
998             ehRet = OC_EH_ERROR;
999         }
1000     }
1001
1002     /*
1003      * For GET or Valid Query request return doxm resource CBOR payload.
1004      * For non-valid query return NULL json payload.
1005      * A device will 'always' have a default Doxm, so DoxmToCBORPayload will
1006      * return valid doxm resource json.
1007      */
1008     uint8_t *payload = NULL;
1009     size_t size = 0;
1010
1011     if (ehRet == OC_EH_OK)
1012     {
1013         if (OC_STACK_OK != DoxmToCBORPayload(gDoxm, &payload, &size, false))
1014         {
1015             OIC_LOG(WARNING, TAG, "DoxmToCBORPayload failed in HandleDoxmGetRequest");
1016         }
1017     }
1018
1019     OIC_LOG(DEBUG, TAG, "Send payload for doxm GET request");
1020     OIC_LOG_BUFFER(DEBUG, TAG, payload, size);
1021
1022     // Send response payload to request originator
1023     ehRet = ((SendSRMResponse(ehRequest, ehRet, payload, size)) == OC_STACK_OK) ?
1024                    OC_EH_OK : OC_EH_ERROR;
1025
1026     OICFree(payload);
1027
1028     return ehRet;
1029 }
1030
1031 static void updateWriteableProperty(const OicSecDoxm_t* src, OicSecDoxm_t* dst)
1032 {
1033     if(src && dst)
1034    {
1035         // update oxmsel
1036         dst->oxmSel = src->oxmSel;
1037
1038         //update owner
1039         memcpy(&(dst->owner), &(src->owner), sizeof(OicUuid_t));
1040
1041         //update rowner
1042         memcpy(&(dst->rownerID), &(src->rownerID), sizeof(OicUuid_t));
1043
1044         //update deviceuuid
1045         memcpy(&(dst->deviceID), &(src->deviceID), sizeof(OicUuid_t));
1046
1047         //Update owned status
1048         if(dst->owned != src->owned)
1049         {
1050             dst->owned = src->owned;
1051         }
1052
1053 #ifdef MULTIPLE_OWNER
1054         if(src->mom)
1055         {
1056             OIC_LOG(DEBUG, TAG, "dectected 'mom' property");
1057             if(NULL == dst->mom)
1058             {
1059                 dst->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
1060                 if(NULL != dst->mom)
1061                 {
1062                     dst->mom->mode = src->mom->mode;
1063                 }
1064             }
1065         }
1066 #endif //MULTIPLE_OWNER
1067     }
1068 }
1069
1070 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1071 #ifdef MULTIPLE_OWNER
1072 /**
1073  * Internal function to get number of sub-owner
1074  */
1075 static size_t GetSubOwnerSize()
1076 {
1077     OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
1078
1079     size_t numberOfSubOwner = 0;
1080
1081     if (gDoxm && gDoxm->subOwners)
1082     {
1083         OicSecSubOwner_t* subowner = NULL;
1084         LL_FOREACH(gDoxm->subOwners, subowner)
1085         {
1086             numberOfSubOwner++;
1087         }
1088     }
1089
1090     OIC_LOG_V(DEBUG, TAG, "Numer of registered sub-owner=%zd", numberOfSubOwner);
1091     OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
1092
1093     return numberOfSubOwner;
1094 }
1095
1096 /**
1097  * Callback function to handle MOT DTLS handshake result.
1098  * @param[out]   endpoint           remote device information.
1099  * @param[out]   errorInfo        CA Error information.
1100  */
1101 void MultipleOwnerDTLSHandshakeCB(const CAEndpoint_t *endpoint,
1102                                 const CAErrorInfo_t *errorInfo)
1103 {
1104     OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
1105     if (!endpoint || !errorInfo)
1106     {
1107         OIC_LOG(ERROR, TAG, "Invalid param");
1108         return;
1109     }
1110
1111     if (!gDoxm)
1112     {
1113         OIC_LOG_V(ERROR, TAG, "%s: gDoxm is NULL", __func__);
1114         return;
1115     }
1116
1117     if ((CA_STATUS_OK == errorInfo->result) && (true == gDoxm->owned)
1118         && (OIC_PRECONFIG_PIN == gDoxm->oxmSel) && (NULL != gDoxm->mom)
1119         && (OIC_MULTIPLE_OWNER_DISABLE != gDoxm->mom->mode) && (CA_ADAPTER_TCP != endpoint->adapter))
1120     {
1121         OIC_LOG_V(INFO, TAG, "DTLS session established for sub-owner authentication : (%s:%d)",
1122                   endpoint->addr, endpoint->port);
1123
1124         const CASecureEndpoint_t* authenticatedSubOwnerInfo = CAGetSecureEndpointData(endpoint);
1125         if (authenticatedSubOwnerInfo)
1126         {
1127             if (0 == memcmp(authenticatedSubOwnerInfo->identity.id, gDoxm->owner.id,
1128                             authenticatedSubOwnerInfo->identity.id_length))
1129             {
1130                 OIC_LOG(WARNING, TAG, "Super owner tried MOT, this request will be ignored.");
1131                 return;
1132             }
1133
1134             OicSecSubOwner_t* subOwnerInst = NULL;
1135             LL_FOREACH(gDoxm->subOwners, subOwnerInst)
1136             {
1137                 if(0 == memcmp(subOwnerInst->uuid.id,
1138                                authenticatedSubOwnerInfo->identity.id,
1139                                authenticatedSubOwnerInfo->identity.id_length))
1140                 {
1141                     break;
1142                 }
1143             }
1144
1145             if (NULL == subOwnerInst)
1146             {
1147                 subOwnerInst = (OicSecSubOwner_t*)OICCalloc(1, sizeof(OicSecSubOwner_t));
1148                 if (subOwnerInst)
1149                 {
1150                     char* strUuid = NULL;
1151                     if (OC_STACK_OK != ConvertUuidToStr(&subOwnerInst->uuid, &strUuid))
1152                     {
1153                         OIC_LOG(WARNING, TAG, "ConvertUuidToStr error");
1154                     }
1155                     OIC_LOG_V(DEBUG, TAG, "Adding New SubOwner(%s)", strUuid);
1156
1157                     if (gMaxSubOwnerSize > GetSubOwnerSize())
1158                     {
1159                         memcpy(subOwnerInst->uuid.id, authenticatedSubOwnerInfo->identity.id,
1160                                authenticatedSubOwnerInfo->identity.id_length);
1161                         LL_APPEND(gDoxm->subOwners, subOwnerInst);
1162                         if (!UpdatePersistentStorage(gDoxm))
1163                         {
1164                             OIC_LOG(ERROR, TAG, "Failed to register SubOwner UUID into Doxm");
1165                         }
1166                     }
1167                     else
1168                     {
1169                         OIC_LOG_V(ERROR, TAG, "Number of sub-owner exceeded : (MAX SIZE=%zd)", gMaxSubOwnerSize);
1170
1171                         //Close DTLS session
1172                         if (CA_STATUS_OK != CAcloseSslSession(endpoint))
1173                         {
1174                             OIC_LOG_V(ERROR, TAG, "CAcloseSslSession error for [%s:%d]", endpoint->addr, endpoint->port);
1175                         }
1176
1177                         //Remove credential
1178                         if (OC_STACK_RESOURCE_DELETED != RemoveCredential(&subOwnerInst->uuid))
1179                         {
1180                             OIC_LOG_V(ERROR, TAG, "RemoveCredential error for [%s]", strUuid);
1181                         }
1182
1183                         // TODO: How to send error to client side?
1184                     }
1185
1186                     OICFree(strUuid);
1187                 }
1188             }
1189         }
1190     }
1191
1192     if(CA_STATUS_OK != CAregisterPskCredentialsHandler(GetDtlsPskCredentials))
1193     {
1194         OIC_LOG(WARNING, TAG, "Failed to revert the DTLS credential handler");
1195     }
1196
1197     OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
1198 }
1199 #endif //MULTIPLE_OWNER
1200 #endif // defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1201
1202 /**
1203  * Function to validate oxmsel with oxms.
1204  *
1205  * @param[in] supportedMethods   Array of supported methods
1206  * @param[in] numberOfMethods   number of supported methods
1207  * @param[out]  selectedMethod         Selected methods
1208  * @return  TRUE on success
1209  */
1210 static bool ValidateOxmsel(const OicSecOxm_t *supportedMethods,
1211         size_t numberOfMethods, OicSecOxm_t *selectedMethod)
1212 {
1213     bool isValidOxmsel = false;
1214
1215     OIC_LOG(DEBUG, TAG, "IN ValidateOxmsel");
1216     if (numberOfMethods == 0 || !supportedMethods)
1217     {
1218         OIC_LOG(WARNING, TAG, "Could not find a supported OxM.");
1219         return isValidOxmsel;
1220     }
1221
1222     for (size_t i = 0; i < numberOfMethods; i++)
1223     {
1224             if (*selectedMethod  == supportedMethods[i])
1225             {
1226                 isValidOxmsel = true;
1227                 break;
1228             }
1229     }
1230     if (!isValidOxmsel)
1231     {
1232         OIC_LOG(ERROR, TAG, "Not allowed Oxmsel.");
1233         return isValidOxmsel;
1234     }
1235
1236     OIC_LOG(DEBUG, TAG, "OUT ValidateOxmsel");
1237
1238     return isValidOxmsel;
1239 }
1240
1241 void SetInformOxmSelCB(InformOxmSelectedCallback_t informOxmSelCB)
1242 {
1243     OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
1244     g_InformOxmSelectedCallback = informOxmSelCB;
1245     OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
1246 }
1247
1248 void UnsetInformOxmSelCB()
1249 {
1250     OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
1251     g_InformOxmSelectedCallback = NULL;
1252     OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
1253 }
1254
1255 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1256 static OCEntityHandlerResult HandleDoxmPostRequest(OCEntityHandlerRequest * ehRequest);
1257
1258 static void DestroyEntityHandlerRequest(OCEntityHandlerRequest * ehRequest)
1259 {
1260     if (ehRequest == NULL) {
1261         OIC_LOG(WARNING, TAG, "ehRequest is NULL");
1262         return;
1263     }
1264
1265     OICFree(ehRequest->query);
1266
1267     if (ehRequest->payload) {
1268         OICFree(((OCSecurityPayload *)ehRequest->payload)->securityData);
1269         OICFree(ehRequest->payload);
1270     }
1271
1272     OICFree(ehRequest);
1273 }
1274
1275 void * WaitConfirm(OCEntityHandlerRequest * ehRequest)
1276 {
1277     bool confirmResult = false, confirmState = false;
1278
1279     oc_mutex_lock(g_mutexWait);
1280     oc_cond_wait(g_condWait, g_mutexWait);
1281     oc_cond_free(g_condWait);
1282     g_condWait = NULL;
1283
1284     oc_mutex_unlock(g_mutexWait);
1285     oc_mutex_free(g_mutexWait);
1286     g_mutexWait = NULL;
1287
1288     g_isConfirmResult = true;
1289     GetAsyncVerifyUserResult(&confirmResult, &confirmState);
1290     if (confirmResult == true)
1291     {
1292         gConfirmState = CONFIRM_STATE_ACCEPTED;
1293         HandleDoxmPostRequest(ehRequest);
1294         g_isConfirmResult = false;
1295     }
1296     else
1297     {
1298         gConfirmState = CONFIRM_STATE_DENIED;
1299         HandleDoxmPostRequest(ehRequest);
1300         g_isConfirmResult = false;
1301     }
1302
1303     DestroyEntityHandlerRequest(ehRequest);
1304
1305     return NULL;
1306 }
1307
1308 static OCEntityHandlerRequest *CopyRequest(OCEntityHandlerRequest *entityHandlerRequest)
1309 {
1310     OIC_LOG(INFO, TAG, "Copying received request for slow response");
1311
1312     if (!entityHandlerRequest)
1313     {
1314         OIC_LOG_V(ERROR, TAG, "%s: entityHandlerRequest is NULL", __func__);
1315         return NULL;
1316     }
1317
1318     OCEntityHandlerRequest *copyOfRequest =
1319             (OCEntityHandlerRequest *)OICCalloc(1, sizeof(OCEntityHandlerRequest));
1320     if(!copyOfRequest)
1321     {
1322         OIC_LOG(ERROR, TAG, "Copy failed due to allocation failure");
1323         return NULL;
1324     }
1325
1326     memcpy(copyOfRequest, entityHandlerRequest, sizeof(OCEntityHandlerRequest));
1327
1328     if (entityHandlerRequest->query)
1329     {
1330         copyOfRequest->query = OICStrdup(entityHandlerRequest->query);
1331         if(!copyOfRequest->query)
1332         {
1333             OIC_LOG(ERROR, TAG, "Copy failed due to allocation failure");
1334             OICFree(copyOfRequest);
1335             return NULL;
1336         }
1337     }
1338
1339     if (entityHandlerRequest->payload)
1340     {
1341         copyOfRequest->payload =
1342                 (OCSecurityPayload *)OICCalloc(1, sizeof(OCSecurityPayload));
1343         if(!copyOfRequest->payload)
1344         {
1345             OIC_LOG(ERROR, TAG, "Copy failed due to allocation failure");
1346             OICFree(copyOfRequest->query);
1347             OICFree(copyOfRequest);
1348             return NULL;
1349         }
1350
1351         if (((OCSecurityPayload *)entityHandlerRequest->payload)->payloadSize)
1352         {
1353             ((OCSecurityPayload *)copyOfRequest->payload)->securityData =
1354                     (uint8_t *)OICCalloc(1, ((OCSecurityPayload *)entityHandlerRequest->payload)->payloadSize);
1355             if(!((OCSecurityPayload *)copyOfRequest->payload)->securityData)
1356             {
1357                 OIC_LOG(ERROR, TAG, "Copy failed due to allocation failure");
1358                 OICFree(copyOfRequest->payload);
1359                 OICFree(copyOfRequest->query);
1360                 OICFree(copyOfRequest);
1361                 return NULL;
1362             }
1363
1364             memcpy(((OCSecurityPayload *)copyOfRequest->payload)->securityData,
1365                   ((OCSecurityPayload *)entityHandlerRequest->payload)->securityData,
1366                   ((OCSecurityPayload *)entityHandlerRequest->payload)->payloadSize);
1367
1368             ((OCSecurityPayload *)(copyOfRequest->payload))->payloadSize =
1369                     ((OCSecurityPayload *)(entityHandlerRequest->payload))->payloadSize;
1370         }
1371
1372         copyOfRequest->payload->type = entityHandlerRequest->payload->type;
1373         copyOfRequest->messageID = entityHandlerRequest->messageID;
1374     }
1375
1376     // Ignore vendor specific header options for example
1377     copyOfRequest->numRcvdVendorSpecificHeaderOptions = 0;
1378     copyOfRequest->rcvdVendorSpecificHeaderOptions = NULL;
1379
1380     OIC_LOG(INFO, TAG, "Copied client request");
1381
1382     return copyOfRequest;
1383 }
1384 #endif // defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1385
1386 static OCEntityHandlerResult HandleDoxmPostRequest(OCEntityHandlerRequest * ehRequest)
1387 {
1388     OIC_LOG (DEBUG, TAG, "Doxm EntityHandle  processing POST request");
1389     OCEntityHandlerResult ehRet = OC_EH_ERROR;
1390     OicUuid_t emptyOwner = {.id = {0} };
1391     static uint16_t previousMsgId = 0;
1392     bool isDuplicatedMsg = false;
1393
1394     /*
1395      * Convert CBOR Doxm data into binary. This will also validate
1396      * the Doxm data received.
1397      */
1398     OicSecDoxm_t *newDoxm = NULL;
1399
1400     if (ehRequest->payload)
1401     {
1402         uint8_t *payload = ((OCSecurityPayload *)ehRequest->payload)->securityData;
1403         size_t size = ((OCSecurityPayload *)ehRequest->payload)->payloadSize;
1404         bool roParsed = false;
1405         OCStackResult res = CBORPayloadToDoxmBin(payload, size, &newDoxm, &roParsed);
1406         if (newDoxm && OC_STACK_OK == res)
1407         {
1408             /*
1409              * message ID is supported for CoAP over UDP only according to RFC 7252
1410              * So we should check message ID to prevent duplicate request handling in case of OC_ADAPTER_IP.
1411              * In case of other transport adapter, duplicate message check is not required.
1412              */
1413             if (OC_ADAPTER_IP == ehRequest->devAddr.adapter &&
1414                  previousMsgId == ehRequest->messageID && g_isConfirmResult == false)
1415             {
1416                 isDuplicatedMsg = true;
1417             }
1418
1419             if (isDuplicatedMsg && ehRequest->messageID == gConfirmMsgId)
1420             {
1421                 if (CONFIRM_STATE_WAIT == gConfirmState)
1422                 {
1423                     OIC_LOG(DEBUG, TAG, "Confirm callback already invoked.");
1424                     OIC_LOG(DEBUG, TAG, "This request will be ignored.");
1425                     DeleteDoxmBinData(newDoxm);
1426                     return OC_EH_OK;
1427                 }
1428                 else
1429                 {
1430                     OIC_LOG_V(DEBUG, TAG, "Confirm request already done, Confirm Result = %s", (CONFIRM_STATE_ACCEPTED == gConfirmState ? "ACCEPTED" : "DENIED"));
1431                     ehRet = (CONFIRM_STATE_ACCEPTED == gConfirmState ? OC_EH_OK : OC_EH_NOT_ACCEPTABLE);
1432                     goto exit;
1433                 }
1434             }
1435
1436             // Check request on RO property
1437             if (true == roParsed)
1438             {
1439                 OIC_LOG(ERROR, TAG, "Not acceptable request because of read-only propertys");
1440                 ehRet = OC_EH_NOT_ACCEPTABLE;
1441                 goto exit;
1442             }
1443
1444             VERIFY_NON_NULL(TAG, gDoxm, ERROR);
1445
1446             // in owned state
1447             if (true == gDoxm->owned)
1448             {
1449                 if (false == ValidateOxmsel(gDoxm->oxm, gDoxm->oxmLen, &newDoxm->oxmSel))
1450                 {
1451                     OIC_LOG(ERROR, TAG, "Not acceptable request because oxmsel does not support on Server");
1452                     ehRet = OC_EH_NOT_ACCEPTABLE;
1453                     goto exit;
1454                 }
1455
1456                 if(0 != memcmp(&gDoxm->owner.id, &newDoxm->owner.id, sizeof(gDoxm->owner.id)))
1457                 {
1458                     OIC_LOG(ERROR, TAG, "Not acceptable request for owned property");
1459                     ehRet = OC_EH_NOT_ACCEPTABLE;
1460                 }
1461
1462                 //Update gDoxm based on newDoxm
1463                 updateWriteableProperty(newDoxm, gDoxm);
1464
1465 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1466 #ifdef MULTIPLE_OWNER
1467                 //handle mom
1468                 if(gDoxm->mom)
1469                 {
1470                     if(OIC_MULTIPLE_OWNER_DISABLE != gDoxm->mom->mode)
1471                     {
1472                         CAResult_t caRes = CA_STATUS_FAILED;
1473                         if(OIC_PRECONFIG_PIN == gDoxm->oxmSel || OIC_RANDOM_DEVICE_PIN == gDoxm->oxmSel)
1474                         {
1475                             caRes = CAEnableAnonECDHCipherSuite(false);
1476                             VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1477                             OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1478
1479                             caRes = CASelectCipherSuite((uint16_t)MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, ehRequest->devAddr.adapter);
1480                             VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1481                             OIC_LOG(INFO, TAG, "ECDHE_PSK CipherSuite will be used for MOT");
1482
1483                             //Set the device id to derive temporal PSK
1484                             SetUuidForPinBasedOxm(&gDoxm->deviceID);
1485                         }
1486                         else
1487                         {
1488                             OIC_LOG(WARNING, TAG, "Unsupported OxM for Multiple Ownership Transfer.");
1489                         }
1490
1491                         CAregisterSslHandshakeCallback(MultipleOwnerDTLSHandshakeCB);
1492                     }
1493                     else
1494                     {
1495                         //if MOM is disabled, revert the DTLS handshake callback
1496                         if(CA_STATUS_OK != CAregisterSslHandshakeCallback(NULL))
1497                         {
1498                             OIC_LOG(WARNING, TAG, "Error while revert the DTLS Handshake Callback.");
1499                         }
1500                     }
1501                 }
1502
1503                 if(newDoxm->subOwners)
1504                 {
1505                     OicSecSubOwner_t* subowner = NULL;
1506                     OicSecSubOwner_t* temp = NULL;
1507
1508                     OIC_LOG(DEBUG, TAG, "dectected 'subowners' property");
1509
1510                     if(gDoxm->subOwners)
1511                     {
1512                         LL_FOREACH_SAFE(gDoxm->subOwners, subowner, temp)
1513                         {
1514                             LL_DELETE(gDoxm->subOwners, subowner);
1515                             OICFree(subowner);
1516                         }
1517                     }
1518
1519                     subowner = NULL;
1520                     temp = NULL;
1521                     LL_FOREACH_SAFE(newDoxm->subOwners, subowner, temp)
1522                     {
1523                         LL_DELETE(newDoxm->subOwners, subowner);
1524                         LL_APPEND(gDoxm->subOwners, subowner);
1525                     }
1526                 }
1527 #endif //MULTIPLE_OWNER
1528 #endif // defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1529
1530                 //Update new state in persistent storage
1531                 if (UpdatePersistentStorage(gDoxm) == true)
1532                 {
1533                     ehRet = OC_EH_OK;
1534                 }
1535                 else
1536                 {
1537                     OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1538                     ehRet = OC_EH_ERROR;
1539                 }
1540                 goto exit;
1541             }
1542
1543             // in unowned state
1544             if ((false == gDoxm->owned) && (false == newDoxm->owned))
1545             {
1546                 if (false == ValidateOxmsel(gDoxm->oxm, gDoxm->oxmLen, &newDoxm->oxmSel))
1547                 {
1548                     OIC_LOG(ERROR, TAG, "Not acceptable request because oxmsel does not support on Server");
1549                     ehRet = OC_EH_NOT_ACCEPTABLE;
1550                     goto exit;
1551                 }
1552                 if (g_InformOxmSelectedCallback)
1553                 {
1554                     g_InformOxmSelectedCallback(newDoxm->oxmSel);
1555                 }
1556
1557 #if defined (__WITH_TLS__) || defined(__WITH_DTLS__)
1558                 if (memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
1559                 {
1560                     InvokeOtmEventHandler(ehRequest->devAddr.addr, ehRequest->devAddr.port,
1561                                           NULL, OIC_OTM_STARTED);
1562                 }
1563                 else
1564                 {
1565                     OIC_LOG_V(INFO, TAG, "%s: request owner not empty",__func__);
1566                     char* strUuid = NULL;
1567                     if (OC_STACK_OK == ConvertUuidToStr(&newDoxm->owner, &strUuid))
1568                     {
1569                         OIC_LOG_V(INFO, TAG, "%s: request owner: %s",__func__, strUuid);
1570                         OICFree(strUuid);
1571                     }
1572                 }
1573 #endif
1574
1575                 if (OIC_JUST_WORKS == newDoxm->oxmSel || OIC_MV_JUST_WORKS == newDoxm->oxmSel)
1576                 {
1577                     /*
1578                      * If current state of the device is un-owned, enable
1579                      * anonymous ECDH cipher in tinyDTLS so that Provisioning
1580                      * tool can initiate JUST_WORKS ownership transfer process.
1581                      */
1582                     if (memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
1583                     {
1584                         gDoxm->oxmSel = newDoxm->oxmSel;
1585                         //Update new state in persistent storage
1586                         if ((UpdatePersistentStorage(gDoxm) == true))
1587                         {
1588                             ehRet = OC_EH_OK;
1589                         }
1590                         else
1591                         {
1592                             OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
1593                             ehRet = OC_EH_ERROR;
1594                             goto exit;
1595                         }
1596                         OIC_LOG (INFO, TAG, "Doxm EntityHandle  enabling AnonECDHCipherSuite");
1597 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1598                         ehRet = (CAEnableAnonECDHCipherSuite(true) == CA_STATUS_OK) ? OC_EH_OK : OC_EH_ERROR;
1599 #endif // __WITH_DTLS__ or __WITH_TLS__
1600                         goto exit;
1601                     }
1602                     else
1603                     {
1604 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1605                         //Save the owner's UUID to derive owner credential
1606                         memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
1607
1608                         // Update new state in persistent storage
1609                         if (true == UpdatePersistentStorage(gDoxm))
1610                         {
1611                             ehRet = OC_EH_OK;
1612                         }
1613                         else
1614                         {
1615                             OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1616                             ehRet = OC_EH_ERROR;
1617                             goto exit;
1618                         }
1619
1620                         /*
1621                          * Disable anonymous ECDH cipher in tinyDTLS since device is now
1622                          * in owned state.
1623                          */
1624                         CAResult_t caRes = CA_STATUS_OK;
1625                         caRes = CAEnableAnonECDHCipherSuite(false);
1626                         VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1627                         OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1628
1629                         //In case of Mutual Verified Just-Works, verify mutualVerifNum
1630                         if (OIC_MV_JUST_WORKS == newDoxm->oxmSel && false == newDoxm->owned &&
1631                             false == isDuplicatedMsg)
1632                         {
1633                             uint8_t preMutualVerifNum[OWNER_PSK_LENGTH_128] = {0};
1634                             uint8_t mutualVerifNum[MUTUAL_VERIF_NUM_LEN] = {0};
1635                             OicUuid_t deviceID = {.id = {0}};
1636
1637                             //Generate mutualVerifNum
1638                             OCServerRequest * request = GetServerRequestUsingHandle(ehRequest->requestHandle);
1639
1640                             char label[LABEL_LEN] = {0};
1641                             snprintf(label, LABEL_LEN, "%s%s", MUTUAL_VERIF_NUM, OXM_MV_JUST_WORKS);
1642                             if (OC_STACK_OK != GetDoxmDeviceID(&deviceID))
1643                             {
1644                                 OIC_LOG(ERROR, TAG, "Error while retrieving Owner's device ID");
1645                                 ehRet = OC_EH_ERROR;
1646                                 goto exit;
1647
1648                             }
1649
1650                             CAResult_t pskRet = CAGenerateOwnerPSK((CAEndpoint_t *)&request->devAddr,
1651                                     (uint8_t *)label,
1652                                     strlen(label),
1653                                     gDoxm->owner.id, sizeof(gDoxm->owner.id),
1654                                     gDoxm->deviceID.id, sizeof(gDoxm->deviceID.id),
1655                                     preMutualVerifNum, OWNER_PSK_LENGTH_128);
1656                             if (CA_STATUS_OK != pskRet)
1657                             {
1658                                 OIC_LOG(WARNING, TAG, "Failed to remove the invaild owner credential");
1659                                 ehRet = OC_EH_ERROR;
1660                                 goto exit;
1661
1662                             }
1663
1664                             memcpy(mutualVerifNum, preMutualVerifNum + OWNER_PSK_LENGTH_128 - sizeof(mutualVerifNum),
1665                                     sizeof(mutualVerifNum));
1666
1667                             gConfirmMsgId = ehRequest->messageID;
1668                             gConfirmState = CONFIRM_STATE_WAIT;
1669                             //Wait for user confirmation
1670                             if (OC_STACK_OK != VerifyOwnershipTransfer(mutualVerifNum, DISPLAY_NUM | USER_CONFIRM))
1671                             {
1672                                 ehRet = OC_EH_NOT_ACCEPTABLE;
1673                                 gConfirmState = CONFIRM_STATE_DENIED;
1674                             }
1675                             else
1676                             {
1677                                 ehRet = OC_EH_OK;
1678                                 gConfirmState = CONFIRM_STATE_ACCEPTED;
1679                             }
1680                         }
1681
1682 #endif // __WITH_DTLS__ or __WITH_TLS__
1683                     }
1684                 }
1685                 else if (OIC_RANDOM_DEVICE_PIN == newDoxm->oxmSel)
1686                 {
1687                     /*
1688                      * If current state of the device is un-owned, enable
1689                      * anonymous ECDH cipher in tinyDTLS so that Provisioning
1690                      * tool can initiate JUST_WORKS ownership transfer process.
1691                      */
1692                     if(memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
1693                     {
1694                         gDoxm->oxmSel = newDoxm->oxmSel;
1695                         //Update new state in persistent storage
1696                         if ((UpdatePersistentStorage(gDoxm) == true))
1697                         {
1698                             ehRet = OC_EH_OK;
1699                         }
1700                         else
1701                         {
1702                             OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
1703                             ehRet = OC_EH_ERROR;
1704                         }
1705
1706 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1707                         CAResult_t caRes = CA_STATUS_OK;
1708
1709                         caRes = CAEnableAnonECDHCipherSuite(false);
1710                         VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1711                         OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1712
1713                         caRes = CASelectCipherSuite(MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256,
1714                                                     ehRequest->devAddr.adapter);
1715                         VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1716
1717                         if (!isDuplicatedMsg)
1718                         {
1719                             char ranPin[OXM_RANDOM_PIN_MAX_SIZE + 1] = {0};
1720                             if (OC_STACK_OK == GeneratePin(ranPin, sizeof(ranPin)))
1721                             {
1722                                 //Set the device id to derive temporal PSK
1723                                 SetUuidForPinBasedOxm(&gDoxm->deviceID);
1724
1725                                 /**
1726                                  * Since PSK will be used directly by DTLS layer while PIN based ownership transfer,
1727                                  * Credential should not be saved into SVR.
1728                                  * For this reason, use a temporary get_psk_info callback to random PIN OxM.
1729                                  */
1730                                 caRes = CAregisterPskCredentialsHandler(GetDtlsPskForRandomPinOxm);
1731                                 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1732                                 ehRet = OC_EH_OK;
1733                             }
1734                             else
1735                             {
1736                                 OIC_LOG(ERROR, TAG, "Failed to generate random PIN");
1737                                 ehRet = OC_EH_ERROR;
1738                             }
1739                         }
1740 #endif // __WITH_DTLS__ or __WITH_TLS__
1741                     }
1742 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1743                     else
1744                     {
1745                         //Save the owner's UUID to derive owner credential
1746                         memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
1747
1748                         // In case of random-pin based OTM, close the PIN display if callback is registered.
1749                         if (!isDuplicatedMsg)
1750                         {
1751                             ClosePinDisplay();
1752                         }
1753
1754                         //Update new state in persistent storage
1755                         if (UpdatePersistentStorage(gDoxm) == true)
1756                         {
1757                             ehRet = OC_EH_OK;
1758                         }
1759                         else
1760                         {
1761                             OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1762                             ehRet = OC_EH_ERROR;
1763                         }
1764                     }
1765 #endif // __WITH_DTLS__ or __WITH_TLS__
1766                 }
1767 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1768                 else if (OIC_MANUFACTURER_CERTIFICATE ==  newDoxm->oxmSel || OIC_CON_MFG_CERT == newDoxm->oxmSel)
1769                 {
1770                     if (CONFIRM_STATE_ACCEPTED != gConfirmState && CONFIRM_STATE_DENIED != gConfirmState)
1771                     {
1772                         //Get user confirmation
1773                         if (false == newDoxm->owned &&
1774                             false == isDuplicatedMsg &&
1775                             memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) != 0)
1776                         {
1777                             gConfirmMsgId = ehRequest->messageID;
1778                             gConfirmState = CONFIRM_STATE_WAIT;
1779
1780                             if (OC_STACK_OK != VerifyUserConfirm())
1781                             {
1782                                 if (OC_STACK_OK != VerifyOwnershipTransfer(NULL, USER_CONFIRM))
1783                                 {
1784                                     ehRet = OC_EH_NOT_ACCEPTABLE;
1785                                     gConfirmState = CONFIRM_STATE_DENIED;
1786                                     goto exit;
1787                                 }
1788                             }
1789                             else
1790                             {
1791                                 OCEntityHandlerRequest * ehRequestCopy = CopyRequest(ehRequest);
1792                                 VERIFY_NON_NULL(TAG, ehRequestCopy, ERROR);
1793
1794                                 g_condWait = oc_cond_new();
1795                                 g_mutexWait = oc_mutex_new();
1796                                 if (oc_thread_new (&g_waitConfirmThreadId, WaitConfirm, ehRequestCopy))
1797                                 {
1798                                     oc_thread_detach(g_waitConfirmThreadId);
1799                                 }
1800
1801                                 previousMsgId = ehRequest->messageID;
1802
1803                                 return OC_EH_SLOW;
1804                             }
1805                         }
1806                     }
1807                     else if (CONFIRM_STATE_DENIED == gConfirmState)
1808                     {
1809                         ehRet = OC_EH_NOT_ACCEPTABLE;
1810                         goto exit;
1811                     }
1812
1813                     //Save the owner's UUID to derive owner credential
1814                     memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
1815                     gDoxm->oxmSel = newDoxm->oxmSel;
1816                     //Update new state in persistent storage
1817                     if (UpdatePersistentStorage(gDoxm))
1818                     {
1819                         ehRet = OC_EH_OK;
1820                     }
1821                     else
1822                     {
1823                         OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
1824                         ehRet = OC_EH_ERROR;
1825                     }
1826                     CAResult_t caRes = CAEnableAnonECDHCipherSuite(false);
1827                     VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1828                     OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1829
1830                     //Unset pre-selected ciphersuite, if any
1831                     caRes = CASelectCipherSuite(0, ehRequest->devAddr.adapter);
1832                     VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1833                     OIC_LOG(DEBUG, TAG, "No ciphersuite preferred");
1834
1835                     VERIFY_SUCCESS(TAG, CA_STATUS_OK == CAregisterPkixInfoHandler(GetManufacturerPkixInfo), ERROR);
1836                     VERIFY_SUCCESS(TAG, CA_STATUS_OK == CAregisterGetCredentialTypesHandler(InitManufacturerCipherSuiteList), ERROR);
1837                 }
1838 #endif // __WITH_DTLS__ or __WITH_TLS__
1839             }
1840
1841             /*
1842              * When current state of the device is un-owned and Provisioning
1843              * Tool is attempting to change the state to 'Owned' with a
1844              * qualified value for the field 'Owner'
1845              */
1846             if ((false == gDoxm->owned) && (true == newDoxm->owned) &&
1847                     (memcmp(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t)) == 0))
1848             {
1849                 //Change the SVR's resource owner as owner device.
1850                 OCStackResult ownerRes = SetAclRownerId(&gDoxm->owner);
1851                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1852                 {
1853                     ehRet = OC_EH_ERROR;
1854                     goto exit;
1855                 }
1856                 ownerRes = SetAmaclRownerId(&gDoxm->owner);
1857                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1858                 {
1859                     ehRet = OC_EH_ERROR;
1860                     goto exit;
1861                 }
1862                 ownerRes = SetCredRownerId(&gDoxm->owner);
1863                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1864                 {
1865                     ehRet = OC_EH_ERROR;
1866                     goto exit;
1867                 }
1868                 ownerRes = SetPstatRownerId(&gDoxm->owner);
1869                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1870                 {
1871                     ehRet = OC_EH_ERROR;
1872                     goto exit;
1873                 }
1874
1875                 gDoxm->owned = true;
1876                 memcpy(&gDoxm->rownerID, &gDoxm->owner, sizeof(OicUuid_t));
1877
1878                 // Update new state in persistent storage
1879                 if (UpdatePersistentStorage(gDoxm))
1880                 {
1881                     //Update default ACE of security resource to prevent anonymous user access.
1882                     if(OC_STACK_OK == UpdateDefaultSecProvACE())
1883                     {
1884                         ehRet = OC_EH_OK;
1885                     }
1886                     else
1887                     {
1888                         OIC_LOG(ERROR, TAG, "Failed to remove default ACL for security provisioning");
1889                         ehRet = OC_EH_ERROR;
1890                     }
1891                 }
1892                 else
1893                 {
1894                     OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1895                     ehRet = OC_EH_ERROR;
1896                 }
1897 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1898                 if (OIC_MANUFACTURER_CERTIFICATE == gDoxm->oxmSel ||
1899                                             OIC_CON_MFG_CERT== gDoxm->oxmSel)
1900                 {
1901                     CAregisterPkixInfoHandler(GetPkixInfo);
1902                     CAregisterGetCredentialTypesHandler(InitCipherSuiteList);
1903                 }
1904
1905                 InvokeOtmEventHandler(ehRequest->devAddr.addr, ehRequest->devAddr.port,
1906                                       &gDoxm->owner, OIC_OTM_DONE);
1907 #endif // __WITH_DTLS__ or __WITH_TLS__
1908             }
1909         }
1910     }
1911
1912 exit:
1913     if(OC_EH_OK != ehRet)
1914     {
1915         /*
1916          * If some error is occured while ownership transfer,
1917          * ownership transfer related resource should be revert back to initial status.
1918         */
1919         if(gDoxm)
1920         {
1921             if(!gDoxm->owned)
1922             {
1923                 OIC_LOG(WARNING, TAG, "The operation failed during handle DOXM request");
1924
1925                 if (!isDuplicatedMsg)
1926                 {
1927 #if defined (__WITH_TLS__) || defined(__WITH_DTLS__)
1928                     InvokeOtmEventHandler(ehRequest->devAddr.addr, ehRequest->devAddr.port,
1929                                           NULL, OIC_OTM_ERROR);
1930 #endif
1931                     ResetSecureResourceInPS();
1932                     OIC_LOG(WARNING, TAG, "DOXM will be reverted.");
1933                 }
1934             }
1935         }
1936         else
1937         {
1938             OIC_LOG(ERROR, TAG, "Invalid DOXM resource.");
1939         }
1940     }
1941
1942     previousMsgId = ehRequest->messageID;
1943
1944 #if defined (__WITH_TLS__) || defined(__WITH_DTLS__)
1945     CAEndpoint_t peer = {0};
1946     OCDevAddr devAddr =  ehRequest->devAddr;
1947
1948     memcpy(&peer.addr, &devAddr.addr, sizeof(peer.addr));
1949     peer.port = devAddr.port;
1950     peer.adapter = (CATransportAdapter_t)devAddr.adapter;
1951
1952     if ((devAddr.flags & OC_FLAG_SECURE) && (false == CAIsExistSslPeer(&peer)))
1953     {
1954         OIC_LOG_V(WARNING, TAG, "Not Exist Peer");
1955         ehRet = OC_EH_OK;
1956     }
1957     else
1958     {
1959         //Send payload to request originator
1960         ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1961             OC_EH_OK : OC_EH_ERROR;
1962     }
1963 #else
1964     //Send payload to request originator
1965     ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1966         OC_EH_OK : OC_EH_ERROR;
1967 #endif
1968
1969     DeleteDoxmBinData(newDoxm);
1970
1971     return ehRet;
1972 }
1973
1974 #ifdef MULTIPLE_OWNER
1975 static OCEntityHandlerResult HandleDoxmDeleteRequest(const OCEntityHandlerRequest *ehRequest)
1976 {
1977     OIC_LOG(DEBUG, TAG, "Processing DoxmDeleteRequest");
1978
1979     OCEntityHandlerResult ehRet = OC_EH_BAD_REQ;
1980
1981     if (NULL == ehRequest->query)
1982     {
1983         return ehRet;
1984     }
1985
1986     OicParseQueryIter_t parseIter = { .attrPos=NULL };
1987     OicUuid_t subject = {.id={0}};
1988
1989     //Parsing REST query to get the subject
1990     ParseQueryIterInit((unsigned char *)ehRequest->query, &parseIter);
1991     while (GetNextQuery(&parseIter))
1992     {
1993         if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_SUBOWNERID_NAME,
1994                 parseIter.attrLen) == 0)
1995         {
1996             if (0 == strncmp((const char*)parseIter.valPos, WILDCARD_RESOURCE_URI,
1997                              strlen(WILDCARD_RESOURCE_URI)))
1998             {
1999                 if(OC_STACK_RESOURCE_DELETED == RemoveSubOwner(&WILDCARD_SUBJECT_ID))
2000                 {
2001                     ehRet = OC_EH_RESOURCE_DELETED;
2002                 }
2003             }
2004             else
2005             {
2006                 OCStackResult ret = ConvertStrToUuid((const char*)parseIter.valPos, &subject);
2007                 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
2008
2009                 if(OC_STACK_RESOURCE_DELETED == RemoveSubOwner(&subject))
2010                 {
2011                     ehRet = OC_EH_RESOURCE_DELETED;
2012                 }
2013             }
2014         }
2015     }
2016
2017     //Send response to request originator
2018     ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
2019                    OC_EH_OK : OC_EH_ERROR;
2020
2021     return ehRet;
2022 exit:
2023     return OC_EH_ERROR;
2024 }
2025 #endif //MULTIPLE_OWNER
2026
2027 OCEntityHandlerResult DoxmEntityHandler(OCEntityHandlerFlag flag,
2028                                         OCEntityHandlerRequest * ehRequest,
2029                                         void* callbackParam)
2030 {
2031     (void)callbackParam;
2032     OCEntityHandlerResult ehRet = OC_EH_ERROR;
2033
2034     if(NULL == ehRequest)
2035     {
2036         return ehRet;
2037     }
2038
2039     oc_mutex_lock(g_mutexDoxm);
2040
2041     if(g_isDoxmNull)
2042     {
2043         oc_mutex_unlock(g_mutexDoxm);
2044         return OC_EH_SERVICE_UNAVAILABLE;
2045     }
2046
2047     if (flag & OC_REQUEST_FLAG)
2048     {
2049         OIC_LOG(DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
2050
2051         switch (ehRequest->method)
2052         {
2053             case OC_REST_GET:
2054                 ehRet = HandleDoxmGetRequest(ehRequest);
2055                 break;
2056
2057             case OC_REST_POST:
2058                 ehRet = HandleDoxmPostRequest(ehRequest);
2059                 break;
2060
2061 #ifdef MULTIPLE_OWNER
2062             case OC_REST_DELETE:
2063                 ehRet = HandleDoxmDeleteRequest(ehRequest);
2064                 break;
2065 #endif //MULTIPLE_OWNER
2066
2067             default:
2068                 ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
2069                                OC_EH_OK : OC_EH_ERROR;
2070                 break;
2071         }
2072
2073         oc_mutex_unlock(g_mutexDoxm);
2074     }
2075
2076     return ehRet;
2077 }
2078
2079 OCStackResult CreateDoxmResource()
2080 {
2081     OCStackResult ret = OCCreateResource(&gDoxmHandle,
2082                                          OIC_RSRC_TYPE_SEC_DOXM,
2083                                          OC_RSRVD_INTERFACE_DEFAULT,
2084                                          OIC_RSRC_DOXM_URI,
2085                                          DoxmEntityHandler,
2086                                          NULL,
2087                                          OC_SECURE |
2088                                          OC_DISCOVERABLE);
2089
2090     if (OC_STACK_OK != ret)
2091     {
2092         OIC_LOG (FATAL, TAG, "Unable to instantiate Doxm resource");
2093         DeInitDoxmResource();
2094     }
2095     return ret;
2096 }
2097
2098 /**
2099  * Checks if DeviceID is generated during provisioning for the new device.
2100  * If DeviceID is NULL then generates the new DeviceID.
2101  * Once DeviceID is assigned to the device it does not change for the lifetime of the device.
2102  */
2103 static OCStackResult CheckDeviceID()
2104 {
2105     OIC_LOG_V(DEBUG, TAG, "IN: %s", __func__);
2106
2107     OCStackResult ret = OC_STACK_ERROR;
2108     bool validId = false;
2109
2110     if (!gDoxm)
2111     {
2112         OIC_LOG_V(ERROR, TAG, "%s: gDoxm is NULL", __func__);
2113         return OC_STACK_INVALID_PARAM;
2114     }
2115
2116     for (uint8_t i = 0; i < UUID_LENGTH; i++)
2117     {
2118         if (gDoxm->deviceID.id[i] != 0)
2119         {
2120             validId = true;
2121             break;
2122         }
2123     }
2124
2125     if (!validId)
2126     {
2127         char* strUuid = NULL;
2128 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
2129         //If seed value is exist, generate UUID using seed with SHA256
2130         if (0 != gUuidSeedSize)
2131         {
2132             uint8_t hashVal[MBEDTLS_MD_MAX_SIZE] = {0};
2133             mbedtls_md_context_t sha_ctx;
2134             int mbedret = 1;
2135
2136             OIC_LOG(DEBUG, TAG, "UUID will be generated using seed w/ SHA256");
2137             OIC_LOG(DEBUG, TAG, "Seed value : ");
2138             OIC_LOG_BUFFER(DEBUG, TAG, gUuidSeed, gUuidSeedSize);
2139
2140             mbedtls_md_init( &sha_ctx );
2141             mbedret = mbedtls_md_setup( &sha_ctx, mbedtls_md_info_from_type( MBEDTLS_MD_SHA256 ), 1 );
2142             if (0 == mbedret)
2143             {
2144                 mbedtls_md_starts( &sha_ctx );
2145                 mbedtls_md_update( &sha_ctx, gUuidSeed, gUuidSeedSize);
2146                 mbedtls_md_finish(&sha_ctx, (unsigned char*)hashVal);
2147                 memcpy(gDoxm->deviceID.id, hashVal, sizeof(gDoxm->deviceID.id));
2148                 ret = OC_STACK_OK;
2149             }
2150             else
2151             {
2152                 OIC_LOG_V(ERROR, TAG,  "mbedtls_md_setup() returned -0x%04x\n", -mbedret);
2153                 ret = OC_STACK_ERROR;
2154             }
2155             mbedtls_md_free( &sha_ctx );
2156         }
2157         else
2158         {
2159             if (RAND_UUID_OK != OCGenerateUuid(gDoxm->deviceID.id))
2160             {
2161                 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
2162                 return OC_STACK_ERROR;
2163             }
2164             ret = OC_STACK_OK;
2165         }
2166 #else
2167         if (RAND_UUID_OK != OCGenerateUuid(gDoxm->deviceID.id))
2168         {
2169             OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
2170             return ret;
2171         }
2172         ret = OC_STACK_OK;
2173 #endif
2174
2175         if (OC_STACK_OK == ConvertUuidToStr(&gDoxm->deviceID, &strUuid))
2176         {
2177             OIC_LOG_V(DEBUG, TAG, "Generated device UUID is [%s]", strUuid);
2178             OICFree(strUuid);
2179         }
2180         else
2181         {
2182             OIC_LOG(WARNING, TAG, "Failed to convert UUID to string");
2183         }
2184
2185
2186         if (!UpdatePersistentStorage(gDoxm))
2187         {
2188             //TODO: After registering PSI handler in all samples, do ret = OC_STACK_OK here.
2189             OIC_LOG(FATAL, TAG, "UpdatePersistentStorage failed!");
2190         }
2191     }
2192     else
2193     {
2194         ret = OC_STACK_OK;
2195     }
2196
2197     OIC_LOG_V(DEBUG, TAG, "OUT: %s", __func__);
2198
2199     return ret;
2200 }
2201
2202 /**
2203  * Get the default value.
2204  *
2205  * @return the default value of doxm, @ref OicSecDoxm_t.
2206  */
2207 static OicSecDoxm_t* GetDoxmDefault()
2208 {
2209     OIC_LOG(DEBUG, TAG, "GetDoxmToDefault");
2210     return &gDefaultDoxm;
2211 }
2212
2213 const OicSecDoxm_t* GetDoxmResourceData()
2214 {
2215     return gDoxm;
2216 }
2217
2218 #if defined(__WITH_DTLS__) && defined(MULTIPLE_OWNER)
2219 /**
2220  * Internal API to prepare MOT
2221  */
2222 static void PrepareMOT(const OicSecDoxm_t* doxm)
2223 {
2224     OIC_LOG(INFO, TAG, "IN PrepareMOT");
2225     VERIFY_NON_NULL(TAG, doxm, ERROR);
2226
2227     if(true == doxm->owned && NULL != doxm->mom && OIC_MULTIPLE_OWNER_DISABLE != doxm->mom->mode)
2228     {
2229         CAResult_t caRes = CA_STATUS_FAILED;
2230
2231         OIC_LOG(INFO, TAG, "Multiple Ownership Transfer Enabled!");
2232
2233         if(OIC_PRECONFIG_PIN == doxm->oxmSel)
2234         {
2235             caRes = CAEnableAnonECDHCipherSuite(false);
2236             VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
2237             OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
2238
2239             caRes = CASelectCipherSuite((uint16_t)MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, CA_ADAPTER_IP);
2240             VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
2241 #ifdef __WITH_TLS__
2242             caRes = CASelectCipherSuite((uint16_t)MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, CA_ADAPTER_TCP);
2243             VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
2244 #endif
2245             OIC_LOG(INFO, TAG, "ECDHE_PSK CipherSuite will be used for MOT");
2246
2247             //Set the device id to derive temporal PSK
2248             SetUuidForPinBasedOxm(&doxm->deviceID);
2249         }
2250         else
2251         {
2252             OIC_LOG(ERROR, TAG, "Unsupported OxM for Multiple Ownership Transfer.");
2253             return;
2254         }
2255
2256         CAregisterSslHandshakeCallback(MultipleOwnerDTLSHandshakeCB);
2257     }
2258
2259     OIC_LOG(INFO, TAG, "OUT PrepareMOT");
2260     return;
2261 exit:
2262     OIC_LOG(WARNING, TAG, "Error in PrepareMOT");
2263 }
2264 #endif //defined(__WITH_DTLS__) && defined(MULTIPLE_OWNER)
2265
2266 OCStackResult InitDoxmResource()
2267 {
2268     OCStackResult ret = OC_STACK_ERROR;
2269
2270     if (!g_mutexDoxm)
2271     {
2272         g_mutexDoxm = oc_mutex_new();
2273             if(!g_mutexDoxm)
2274             {
2275                 return OC_STACK_ERROR;
2276             }
2277     }
2278
2279     gConfirmState = CONFIRM_STATE_READY;
2280     gConfirmMsgId = 0;
2281
2282     //Read DOXM resource from PS
2283     uint8_t *data = NULL;
2284     size_t size = 0;
2285     ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_DOXM_NAME, &data, &size);
2286     // If database read failed
2287     if (OC_STACK_OK != ret)
2288     {
2289        OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
2290     }
2291     if (data)
2292     {
2293        // Read DOXM resource from PS
2294        ret = CBORPayloadToDoxm(data, size, &gDoxm);
2295     }
2296     /*
2297      * If SVR database in persistent storage got corrupted or
2298      * is not available for some reason, a default doxm is created
2299      * which allows user to initiate doxm provisioning again.
2300      */
2301      if ((OC_STACK_OK != ret) || !data || !gDoxm)
2302     {
2303         gDoxm = GetDoxmDefault();
2304     }
2305
2306      oc_mutex_lock(g_mutexDoxm);
2307      g_isDoxmNull = false;
2308      oc_mutex_unlock(g_mutexDoxm);
2309
2310     //In case of the server is shut down unintentionally, we should initialize the owner
2311     if(gDoxm && (false == gDoxm->owned))
2312     {
2313         OicUuid_t emptyUuid = {.id={0}};
2314         memcpy(&gDoxm->owner, &emptyUuid, sizeof(OicUuid_t));
2315 #if defined (__WITH_TLS__) || defined(__WITH_DTLS__)
2316         InvokeOtmEventHandler(NULL, 0, NULL, OIC_OTM_READY);
2317 #endif
2318     }
2319
2320     ret = CheckDeviceID();
2321     if (ret == OC_STACK_OK)
2322     {
2323         OIC_LOG_V(DEBUG, TAG, "Initial Doxm Owned = %d", gDoxm->owned);
2324         //Instantiate 'oic.sec.doxm'
2325         ret = CreateDoxmResource();
2326     }
2327     else
2328     {
2329         OIC_LOG (ERROR, TAG, "CheckDeviceID failed");
2330     }
2331     OICFree(data);
2332
2333 #if defined(__WITH_DTLS__) && defined(MULTIPLE_OWNER)
2334     //if MOT is enabled, MOT should be prepared.
2335     if(gDoxm && gDoxm->owned)
2336     {
2337         PrepareMOT(gDoxm);
2338     }
2339 #endif // defined(__WITH_DTLS__) && defined(MULTIPLE_OWNER)
2340
2341     return ret;
2342 }
2343
2344 OCStackResult DeInitDoxmResource()
2345 {
2346     oc_mutex_lock(g_mutexDoxm);
2347     OCStackResult ret = OCDeleteResource(gDoxmHandle);
2348     if (gDoxm  != &gDefaultDoxm)
2349     {
2350         DeleteDoxmBinData(gDoxm);
2351     }
2352     gDoxm = NULL;
2353     g_isDoxmNull = true;
2354
2355     if (OC_STACK_OK == ret)
2356     {
2357         oc_mutex_unlock(g_mutexDoxm);
2358         return OC_STACK_OK;
2359     }
2360     else
2361     {
2362         oc_mutex_unlock(g_mutexDoxm);
2363         return OC_STACK_ERROR;
2364     }
2365 }
2366
2367 OCStackResult GetDoxmDeviceID(OicUuid_t *deviceID)
2368 {
2369     if (deviceID && gDoxm)
2370     {
2371        *deviceID = gDoxm->deviceID;
2372         return OC_STACK_OK;
2373     }
2374     return OC_STACK_ERROR;
2375 }
2376
2377 OCStackResult GetDoxmIsOwned(bool *isOwned)
2378 {
2379     OIC_LOG_V(INFO, TAG, "In %s", __func__);
2380     if (isOwned && gDoxm)
2381     {
2382         *isOwned = gDoxm->owned;
2383         OIC_LOG_V(INFO, TAG, "isOwned - %s", *isOwned ? "true" : "false");
2384         OIC_LOG_V(INFO, TAG, "Out %s", __func__);
2385         return OC_STACK_OK;
2386     }
2387     return OC_STACK_ERROR;
2388 }
2389
2390 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
2391 OCStackResult SetDoxmDeviceIDSeed(const uint8_t* seed, size_t seedSize)
2392 {
2393     OIC_LOG_V(INFO, TAG, "In %s", __func__);
2394
2395     if (NULL == seed)
2396     {
2397         return OC_STACK_INVALID_PARAM;
2398     }
2399     if (MAX_UUID_SEED_SIZE < seedSize)
2400     {
2401         OIC_LOG_V(ERROR, TAG, "Seed size is too long (MAX size is %d bytes)", MAX_UUID_SEED_SIZE);
2402         return OC_STACK_INVALID_PARAM;
2403     }
2404     if (MIN_UUID_SEED_SIZE > seedSize)
2405     {
2406         OIC_LOG_V(ERROR, TAG, "Seed size is too small (MIN size is %d bytes)", MIN_UUID_SEED_SIZE);
2407         return OC_STACK_INVALID_PARAM;
2408     }
2409
2410     memset(gUuidSeed, 0x00, sizeof(gUuidSeed));
2411     memcpy(gUuidSeed, seed, seedSize);
2412     gUuidSeedSize = seedSize;
2413
2414     OIC_LOG_V(INFO, TAG, "Out %s", __func__);
2415
2416     return OC_STACK_OK;
2417 }
2418
2419 #endif
2420
2421 OCStackResult SetDoxmDeviceID(const OicUuid_t *deviceID)
2422 {
2423     bool isOwnerUpdated = false;
2424     bool isRownerUpdated = false;
2425     if (NULL == deviceID)
2426     {
2427         return OC_STACK_INVALID_PARAM;
2428     }
2429     if (NULL == gDoxm)
2430     {
2431         OIC_LOG(ERROR, TAG, "Doxm resource is not initialized.");
2432         return OC_STACK_NO_RESOURCE;
2433     }
2434
2435 #ifdef __WITH_DTLS__
2436     //for normal device.
2437     if (true == gDoxm->owned
2438             && memcmp(gEmptyUuid, gDoxm->owner.id, sizeof(gDoxm->owner.id)) != 0
2439             && memcmp(gDoxm->deviceID.id, gDoxm->owner.id, sizeof(gDoxm->owner.id)) != 0)
2440     {
2441         OIC_LOG(ERROR, TAG, "This device owned by owner's device.");
2442         OIC_LOG(ERROR, TAG, "Device UUID cannot be changed to guarantee the reliability of the connection.");
2443         return OC_STACK_ERROR;
2444     }
2445 #endif //__WITH_DTLS
2446
2447     //Save the previous UUID
2448     OicUuid_t prevUuid;
2449     memcpy(prevUuid.id, gDoxm->deviceID.id, sizeof(prevUuid.id));
2450
2451     //Change the device UUID
2452     memcpy(gDoxm->deviceID.id, deviceID->id, sizeof(deviceID->id));
2453
2454     //Change the owner ID if necessary
2455     if (memcmp(gDoxm->owner.id, prevUuid.id, sizeof(prevUuid.id)) == 0)
2456     {
2457         memcpy(gDoxm->owner.id, deviceID->id, sizeof(deviceID->id));
2458         isOwnerUpdated = true;
2459     }
2460     //Change the resource owner ID if necessary
2461     if (memcmp(gDoxm->rownerID.id, prevUuid.id, sizeof(prevUuid.id)) == 0)
2462     {
2463         memcpy(gDoxm->rownerID.id, deviceID->id, sizeof(deviceID->id));
2464         isRownerUpdated = true;
2465     }
2466     // TODO: T.B.D Change resource owner for pstat, acl and cred
2467
2468     //Update PS
2469     if (!UpdatePersistentStorage(gDoxm))
2470     {
2471         //revert UUID in case of PSI error
2472         memcpy(gDoxm->deviceID.id, prevUuid.id, sizeof(prevUuid.id));
2473         if (isOwnerUpdated)
2474         {
2475             memcpy(gDoxm->owner.id, prevUuid.id, sizeof(prevUuid.id));
2476         }
2477         if (isRownerUpdated)
2478         {
2479             memcpy(gDoxm->rownerID.id, prevUuid.id, sizeof(prevUuid.id));
2480         }
2481         // TODO: T.B.D Revert resource owner for pstat, acl and cred
2482
2483         OIC_LOG(ERROR, TAG, "Failed to update persistent storage");
2484         return OC_STACK_ERROR;
2485     }
2486     return OC_STACK_OK;
2487 }
2488
2489 OCStackResult GetDoxmDevOwnerId(OicUuid_t *devownerid)
2490 {
2491     OCStackResult retVal = OC_STACK_ERROR;
2492     if (gDoxm)
2493     {
2494         OIC_LOG_V(DEBUG, TAG, "GetDoxmDevOwnerId(): gDoxm owned =  %d.", \
2495             gDoxm->owned);
2496         //if (gDoxm->owned)
2497         {
2498             *devownerid = gDoxm->owner;
2499             retVal = OC_STACK_OK;
2500         }
2501     }
2502     return retVal;
2503 }
2504
2505 OCStackResult GetDoxmRownerId(OicUuid_t *rowneruuid)
2506 {
2507     OCStackResult retVal = OC_STACK_ERROR;
2508     if (gDoxm)
2509     {
2510        // if( gDoxm->owned )
2511         {
2512             *rowneruuid = gDoxm->rownerID;
2513                     retVal = OC_STACK_OK;
2514         }
2515     }
2516     return retVal;
2517 }
2518
2519 #ifdef MULTIPLE_OWNER
2520 /**
2521  * Compare the UUID to SubOwner.
2522  *
2523  * @param[in] uuid device UUID
2524  *
2525  * @return true if context->subjectId exist subowner list, else false.
2526  */
2527 bool IsSubOwner(const OicUuid_t* uuid)
2528 {
2529     bool retVal = false;
2530
2531     if (NULL == uuid)
2532     {
2533         return retVal;
2534     }
2535
2536     if (gDoxm && gDoxm->subOwners)
2537     {
2538         if (memcmp(gDoxm->owner.id, uuid->id, sizeof(gDoxm->owner.id)) == 0)
2539         {
2540             return false;
2541         }
2542
2543         OicSecSubOwner_t* subOwner = NULL;
2544         LL_FOREACH(gDoxm->subOwners, subOwner)
2545         {
2546             if (memcmp(subOwner->uuid.id, uuid->id, sizeof(uuid->id)) == 0)
2547             {
2548                 return true;
2549             }
2550         }
2551     }
2552     return retVal;
2553 }
2554 #endif //MULTIPLE_OWNER
2555
2556 OCStackResult SetMOTStatus(bool enable)
2557 {
2558     OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
2559 #ifdef MULTIPLE_OWNER
2560     OCStackResult ret = OC_STACK_NO_MEMORY;
2561     uint8_t *cborPayload = NULL;
2562     size_t size = 0;
2563     bool isDeallocateRequired = false;
2564
2565     VERIFY_NON_NULL(TAG, gDoxm, ERROR);
2566
2567     if (NULL == gDoxm->mom && !enable)
2568     {
2569         OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2570         return OC_STACK_OK;
2571     }
2572
2573     if (NULL == gDoxm->mom)
2574     {
2575         gDoxm->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
2576         VERIFY_NON_NULL(TAG, gDoxm->mom, ERROR);
2577         isDeallocateRequired = true;
2578     }
2579
2580     gDoxm->mom->mode = (enable ? OIC_MULTIPLE_OWNER_ENABLE : OIC_MULTIPLE_OWNER_DISABLE);
2581     gDoxm->oxmSel = OIC_PRECONFIG_PIN;
2582
2583     ret = DoxmToCBORPayload(gDoxm, &cborPayload, &size, false);
2584     VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
2585
2586     ret = UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, cborPayload, size);
2587     VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
2588
2589     isDeallocateRequired = false;
2590
2591 exit:
2592     if (isDeallocateRequired)
2593     {
2594         OICFree(gDoxm->mom);
2595     }
2596     if (cborPayload)
2597     {
2598         OICFree(cborPayload);
2599     }
2600     OIC_LOG_V(DEBUG, TAG, "Out %s : %d", __func__, ret);
2601     return ret;
2602 #else
2603     OC_UNUSED(enable);
2604     OIC_LOG(DEBUG, TAG, "Multiple Owner is not enabled.");
2605     OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2606     return OC_STACK_ERROR;
2607 #endif //MULTIPLE_OWNER
2608 }
2609
2610 OCStackResult RemoveSubOwner(const OicUuid_t* subOwner)
2611 {
2612     OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
2613 #ifdef MULTIPLE_OWNER
2614     OCStackResult ret = OC_STACK_ERROR;
2615     bool isDeleted = false;
2616
2617     if (NULL == subOwner)
2618     {
2619         OIC_LOG(ERROR, TAG, "Invalid sub owner UUID.");
2620         return OC_STACK_INVALID_PARAM;
2621     }
2622     if (NULL == gDoxm)
2623     {
2624         OIC_LOG(ERROR, TAG, "Doxm resource is NULL");
2625         return OC_STACK_NO_RESOURCE;
2626     }
2627     if ( NULL == gDoxm->subOwners)
2628     {
2629         OIC_LOG(WARNING, TAG, "Sub Owner list is empty.");
2630         return OC_STACK_ERROR;
2631     }
2632
2633     OicSecSubOwner_t* curSubOwner = NULL;
2634     OicSecSubOwner_t* tempSubOwner = NULL;
2635     LL_FOREACH_SAFE(gDoxm->subOwners, curSubOwner, tempSubOwner)
2636     {
2637         if (memcmp(curSubOwner->uuid.id, subOwner->id, sizeof(subOwner->id)) == 0 ||
2638             memcmp(WILDCARD_SUBJECT_ID.id, subOwner->id, sizeof(OicUuid_t)) == 0)
2639         {
2640             char* strUuid = NULL;
2641             ret = ConvertUuidToStr(&curSubOwner->uuid, &strUuid);
2642             if (OC_STACK_OK != ret)
2643             {
2644                 OIC_LOG_V(ERROR, TAG, "ConvertUuidToStr error : %d", ret);
2645                 break;
2646             }
2647
2648             OIC_LOG_V(INFO, TAG, "[%s] will be removed from sub owner list.", strUuid);
2649             LL_DELETE(gDoxm->subOwners, curSubOwner);
2650
2651             //Remove the cred for sub owner
2652             ret = RemoveCredential(&curSubOwner->uuid);
2653             if (OC_STACK_RESOURCE_DELETED != ret)
2654             {
2655                 OIC_LOG_V(WARNING, TAG, "RemoveCredential error for [%s] : %d", strUuid, ret);
2656                 break;
2657             }
2658
2659             // TODO: Remove the ACL for sub owner (Currently ACL is not required for sub-owner)
2660
2661             OICFree(strUuid);
2662
2663             isDeleted = true;
2664         }
2665     }
2666
2667     if (isDeleted)
2668     {
2669         //Update persistent storage
2670         if (UpdatePersistentStorage(gDoxm))
2671         {
2672             ret = OC_STACK_RESOURCE_DELETED;
2673         }
2674         else
2675         {
2676             OIC_LOG(ERROR, TAG, "UpdatePersistentStorage error");
2677             ret = OC_STACK_ERROR;
2678         }
2679     }
2680
2681     OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2682     return ret;
2683 #else
2684     OC_UNUSED(subOwner);
2685     OIC_LOG(DEBUG, TAG, "Multiple Owner is not enabled.");
2686     OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2687     return OC_STACK_ERROR;
2688 #endif //MULTIPLE_OWNER
2689
2690 }
2691
2692 OCStackResult SetNumberOfSubOwner(size_t numOfSubOwner)
2693 {
2694     OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
2695 #ifdef MULTIPLE_OWNER
2696     if (MAX_SUBOWNER_SIZE < numOfSubOwner || MIN_SUBOWNER_SIZE > numOfSubOwner)
2697     {
2698         OIC_LOG_V(ERROR, TAG, "Invalid number of sub owner : %zd", numOfSubOwner);
2699         return OC_STACK_INVALID_PARAM;
2700     }
2701     gMaxSubOwnerSize = numOfSubOwner;
2702     OIC_LOG_V(DEBUG, TAG, "Number of SubOwner = %zd", gMaxSubOwnerSize);
2703     OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2704     return OC_STACK_OK;
2705 #else
2706     OC_UNUSED(numOfSubOwner);
2707     OIC_LOG(DEBUG, TAG, "Multiple Owner is not enabled.");
2708     OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2709     return OC_STACK_ERROR;
2710 #endif //MULTIPLE_OWNER
2711 }
2712
2713 /**
2714  * Function to restore doxm resurce to initial status.
2715  * This function will use in case of error while ownership transfer
2716  */
2717 void RestoreDoxmToInitState()
2718 {
2719
2720     gConfirmState = CONFIRM_STATE_READY;
2721     gConfirmMsgId = 0;
2722
2723     if(gDoxm)
2724     {
2725         OIC_LOG(INFO, TAG, "DOXM resource will revert back to initial status.");
2726
2727         OicUuid_t emptyUuid = {.id={0}};
2728         memcpy(&(gDoxm->owner), &emptyUuid, sizeof(OicUuid_t));
2729         gDoxm->owned = false;
2730         gDoxm->oxmSel = OIC_JUST_WORKS;
2731
2732         if(!UpdatePersistentStorage(gDoxm))
2733         {
2734             OIC_LOG(ERROR, TAG, "Failed to revert DOXM in persistent storage");
2735         }
2736     }
2737 }
2738
2739 OCStackResult SetDoxmSelfOwnership(const OicUuid_t* newROwner)
2740 {
2741     OCStackResult ret = OC_STACK_ERROR;
2742     uint8_t *cborPayload = NULL;
2743     size_t size = 0;
2744
2745     if(NULL == gDoxm)
2746     {
2747         ret = OC_STACK_NO_RESOURCE;
2748         return ret;
2749     }
2750
2751     if( newROwner && (false == gDoxm->owned) )
2752     {
2753         gDoxm->owned = true;
2754         memcpy(gDoxm->owner.id, newROwner->id, sizeof(newROwner->id));
2755         memcpy(gDoxm->rownerID.id, newROwner->id, sizeof(newROwner->id));
2756
2757         ret = DoxmToCBORPayload(gDoxm, &cborPayload, &size, false);
2758         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
2759
2760         ret = UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, cborPayload, size);
2761         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
2762
2763         OICFree(cborPayload);
2764     }
2765
2766     return ret;
2767
2768 exit:
2769     OICFree(cborPayload);
2770     return ret;
2771 }
2772