Imported Upstream version 1.1.1
[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 <stdlib.h>
21 #include <string.h>
22
23 #if HAVE_STRINGS_H
24 #include <strings.h>
25 #endif
26
27 #ifdef __WITH_DTLS__
28 #include "global.h"
29 #endif
30
31 #include "ocstack.h"
32 #include "oic_malloc.h"
33 #include "payload_logging.h"
34 #include "utlist.h"
35 #include "ocrandom.h"
36 #include "ocpayload.h"
37 #include "cainterface.h"
38 #include "ocserverrequest.h"
39 #include "resourcemanager.h"
40 #include "doxmresource.h"
41 #include "pstatresource.h"
42 #include "aclresource.h"
43 #include "amaclresource.h"
44 #include "pconfresource.h"
45 #include "dpairingresource.h"
46 #include "psinterface.h"
47 #include "srmresourcestrings.h"
48 #include "securevirtualresourcetypes.h"
49 #include "credresource.h"
50 #include "srmutility.h"
51 #include "pinoxmcommon.h"
52
53 #define TAG  "SRM-DOXM"
54
55 /** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
56  * The value of payload size is increased until reaching belox max cbor size. */
57 static const uint16_t CBOR_SIZE = 512;
58
59 /** Max cbor size payload. */
60 static const uint16_t CBOR_MAX_SIZE = 4400;
61
62 /** DOXM Map size - Number of mandatory items. */
63 static const uint8_t DOXM_MAP_SIZE = 9;
64
65 static OicSecDoxm_t        *gDoxm = NULL;
66 static OCResourceHandle    gDoxmHandle = NULL;
67
68 static OicSecOxm_t gOicSecDoxmJustWorks = OIC_JUST_WORKS;
69 static OicSecDoxm_t gDefaultDoxm =
70 {
71     NULL,                   /* OicUrn_t *oxmType */
72     0,                      /* size_t oxmTypeLen */
73     &gOicSecDoxmJustWorks,  /* uint16_t *oxm */
74     1,                      /* size_t oxmLen */
75     OIC_JUST_WORKS,         /* uint16_t oxmSel */
76     SYMMETRIC_PAIR_WISE_KEY,/* OicSecCredType_t sct */
77     false,                  /* bool owned */
78     {.id = {0}},            /* OicUuid_t deviceID */
79     false,                  /* bool dpc */
80     {.id = {0}},            /* OicUuid_t owner */
81     {.id = {0}},            /* OicUuid_t rownerID */
82 };
83
84 /**
85  * This method is internal method.
86  * the param roParsed is optionally used to know whether cborPayload has
87  * at least read only property value or not.
88  */
89 static OCStackResult CBORPayloadToDoxmBin(const uint8_t *cborPayload, size_t size,
90                                 OicSecDoxm_t **doxm, bool *roParsed);
91
92 void DeleteDoxmBinData(OicSecDoxm_t* doxm)
93 {
94     if (doxm)
95     {
96         //Clean oxmType
97         for (size_t i = 0; i < doxm->oxmTypeLen; i++)
98         {
99             OICFree(doxm->oxmType[i]);
100         }
101         OICFree(doxm->oxmType);
102
103         //clean oxm
104         OICFree(doxm->oxm);
105
106         //Clean doxm itself
107         OICFree(doxm);
108     }
109 }
110
111 OCStackResult DoxmToCBORPayload(const OicSecDoxm_t *doxm, uint8_t **payload, size_t *size,
112                                 bool rwOnly)
113 {
114     if (NULL == doxm || NULL == payload || NULL != *payload || NULL == size)
115     {
116         return OC_STACK_INVALID_PARAM;
117     }
118     size_t cborLen = *size;
119     if (0 == cborLen)
120     {
121         cborLen = CBOR_SIZE;
122     }
123     *payload = NULL;
124     *size = 0;
125
126     OCStackResult ret = OC_STACK_ERROR;
127
128     CborEncoder encoder;
129     CborEncoder doxmMap;
130     char* strUuid = NULL;
131
132     int64_t cborEncoderResult = CborNoError;
133     uint8_t mapSize = DOXM_MAP_SIZE;
134     if (doxm->oxmTypeLen > 0)
135     {
136         mapSize++;
137     }
138     if (doxm->oxmLen > 0)
139     {
140         mapSize++;
141     }
142
143     uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
144     VERIFY_NON_NULL(TAG, outPayload, ERROR);
145     cbor_encoder_init(&encoder, outPayload, cborLen, 0);
146
147     cborEncoderResult = cbor_encoder_create_map(&encoder, &doxmMap, mapSize);
148     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Doxm Map.");
149
150     //OxmType -- Not Mandatory
151     if (doxm->oxmTypeLen > 0)
152     {
153         CborEncoder oxmType;
154         cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_TYPE_NAME,
155             strlen(OIC_JSON_OXM_TYPE_NAME));
156         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Tag.");
157         cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxmType, doxm->oxmTypeLen);
158         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Array.");
159
160         for (size_t i = 0; i < doxm->oxmTypeLen; i++)
161         {
162             cborEncoderResult = cbor_encode_text_string(&oxmType, doxm->oxmType[i],
163                 strlen(doxm->oxmType[i]));
164             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Value.");
165         }
166         cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxmType);
167         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmType.");
168     }
169
170     //Oxm -- Not Mandatory
171     if (doxm->oxmLen > 0 && false == rwOnly)
172     {
173         CborEncoder oxm;
174         cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXMS_NAME,
175             strlen(OIC_JSON_OXMS_NAME));
176         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Tag.");
177         cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxm, doxm->oxmLen);
178         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Array.");
179
180         for (size_t i = 0; i < doxm->oxmLen; i++)
181         {
182             cborEncoderResult = cbor_encode_int(&oxm, doxm->oxm[i]);
183             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Value");
184         }
185         cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxm);
186         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmName.");
187     }
188
189     //OxmSel -- Mandatory
190     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_SEL_NAME,
191         strlen(OIC_JSON_OXM_SEL_NAME));
192     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Tag.");
193     cborEncoderResult = cbor_encode_int(&doxmMap, doxm->oxmSel);
194     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Value.");
195
196     //sct -- Mandatory
197     if (false == rwOnly)
198     {
199         cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_SUPPORTED_CRED_TYPE_NAME,
200             strlen(OIC_JSON_SUPPORTED_CRED_TYPE_NAME));
201         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Tag");
202         cborEncoderResult = cbor_encode_int(&doxmMap, doxm->sct);
203         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Value.");
204     }
205
206     //Owned -- Mandatory
207     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OWNED_NAME,
208         strlen(OIC_JSON_OWNED_NAME));
209     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Tag.");
210     cborEncoderResult = cbor_encode_boolean(&doxmMap, doxm->owned);
211     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Value.");
212
213     if (false == rwOnly)
214     {
215         //DeviceId -- Mandatory
216         cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVICE_ID_NAME,
217             strlen(OIC_JSON_DEVICE_ID_NAME));
218         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Tag.");
219         ret = ConvertUuidToStr(&doxm->deviceID, &strUuid);
220         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
221         cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
222         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Value.");
223         OICFree(strUuid);
224         strUuid = NULL;
225     }
226
227     //devownerid -- Mandatory
228     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVOWNERID_NAME,
229         strlen(OIC_JSON_DEVOWNERID_NAME));
230     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Id Tag.");
231     ret = ConvertUuidToStr(&doxm->owner, &strUuid);
232     VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
233     cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
234     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Id Value.");
235     OICFree(strUuid);
236     strUuid = NULL;
237
238     //ROwner -- Mandatory
239     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_ROWNERID_NAME,
240         strlen(OIC_JSON_ROWNERID_NAME));
241     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Tag.");
242     ret = ConvertUuidToStr(&doxm->rownerID, &strUuid);
243     VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
244     cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
245     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Value.");
246     OICFree(strUuid);
247     strUuid = NULL;
248
249     //x.org.iotivity.dpc -- not Mandatory(vendor-specific), but this type is boolean, so instance always has a value.
250     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DPC_NAME,
251         strlen(OIC_JSON_DPC_NAME));
252     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DPC Tag.");
253     cborEncoderResult = cbor_encode_boolean(&doxmMap, doxm->dpc);
254     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DPC Value.");
255
256     //RT -- Mandatory
257     CborEncoder rtArray;
258     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_RT_NAME,
259             strlen(OIC_JSON_RT_NAME));
260     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Name Tag.");
261     cborEncoderResult = cbor_encoder_create_array(&doxmMap, &rtArray, 1);
262     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Value.");
263     for (size_t i = 0; i < 1; i++)
264     {
265         cborEncoderResult = cbor_encode_text_string(&rtArray, OIC_RSRC_TYPE_SEC_DOXM,
266                 strlen(OIC_RSRC_TYPE_SEC_DOXM));
267         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding RT Value.");
268     }
269     cborEncoderResult = cbor_encoder_close_container(&doxmMap, &rtArray);
270     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing RT.");
271
272     //IF-- Mandatory
273      CborEncoder ifArray;
274      cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_IF_NAME,
275              strlen(OIC_JSON_IF_NAME));
276      VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Name Tag.");
277      cborEncoderResult = cbor_encoder_create_array(&doxmMap, &ifArray, 1);
278      VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Value.");
279     for (size_t i = 0; i < 1; i++)
280     {
281         cborEncoderResult = cbor_encode_text_string(&ifArray, OC_RSRVD_INTERFACE_DEFAULT,
282                 strlen(OC_RSRVD_INTERFACE_DEFAULT));
283         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding IF Value.");
284     }
285     cborEncoderResult = cbor_encoder_close_container(&doxmMap, &ifArray);
286     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing IF.");
287
288     cborEncoderResult = cbor_encoder_close_container(&encoder, &doxmMap);
289     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing DoxmMap.");
290
291     if (CborNoError == cborEncoderResult)
292     {
293         *size = encoder.ptr - outPayload;
294         *payload = outPayload;
295         ret = OC_STACK_OK;
296     }
297 exit:
298     if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
299     {
300         OIC_LOG(DEBUG, TAG, "Memory getting reallocated.");
301         // reallocate and try again!
302         OICFree(outPayload);
303         // Since the allocated initial memory failed, double the memory.
304         cborLen += encoder.ptr - encoder.end;
305         OIC_LOG_V(DEBUG, TAG, "Doxm reallocation size : %zd.", cborLen);
306         cborEncoderResult = CborNoError;
307         ret = DoxmToCBORPayload(doxm, payload, &cborLen, rwOnly);
308         *size = cborLen;
309     }
310
311     if ((CborNoError != cborEncoderResult) || (OC_STACK_OK != ret))
312     {
313        OICFree(outPayload);
314        outPayload = NULL;
315        *payload = NULL;
316        *size = 0;
317        ret = OC_STACK_ERROR;
318     }
319
320     return ret;
321 }
322
323 OCStackResult CBORPayloadToDoxm(const uint8_t *cborPayload, size_t size,
324                                 OicSecDoxm_t **secDoxm)
325 {
326     return CBORPayloadToDoxmBin(cborPayload, size, secDoxm, NULL);
327 }
328
329 static OCStackResult CBORPayloadToDoxmBin(const uint8_t *cborPayload, size_t size,
330                                 OicSecDoxm_t **secDoxm, bool *roParsed)
331 {
332     if (NULL == cborPayload || NULL == secDoxm || NULL != *secDoxm || 0 == size)
333     {
334         return OC_STACK_INVALID_PARAM;
335     }
336
337     OCStackResult ret = OC_STACK_ERROR;
338     *secDoxm = NULL;
339
340     CborParser parser;
341     CborError cborFindResult = CborNoError;
342     char* strUuid = NULL;
343     size_t len = 0;
344     CborValue doxmCbor;
345
346     cbor_parser_init(cborPayload, size, 0, &parser, &doxmCbor);
347     CborValue doxmMap;
348     OicSecDoxm_t *doxm = (OicSecDoxm_t *)OICCalloc(1, sizeof(*doxm));
349     VERIFY_NON_NULL(TAG, doxm, ERROR);
350
351     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_TYPE_NAME, &doxmMap);
352     //OxmType -- not Mandatory
353     if (CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
354     {
355         CborValue oxmType;
356
357         cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmTypeLen);
358         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmTypeLen.")
359         VERIFY_SUCCESS(TAG, doxm->oxmTypeLen != 0, ERROR);
360
361         doxm->oxmType = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(*doxm->oxmType));
362         VERIFY_NON_NULL(TAG, doxm->oxmType, ERROR);
363
364         cborFindResult = cbor_value_enter_container(&doxmMap, &oxmType);
365         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmType Array.")
366
367         int i = 0;
368         size_t len = 0;
369         while (cbor_value_is_valid(&oxmType) && cbor_value_is_text_string(&oxmType))
370         {
371             cborFindResult = cbor_value_dup_text_string(&oxmType, &doxm->oxmType[i++],
372                                                         &len, NULL);
373             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding omxType text string.")
374             cborFindResult = cbor_value_advance(&oxmType);
375             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmType.")
376         }
377     }
378
379     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXMS_NAME, &doxmMap);
380     //Oxm -- not Mandatory
381     if (CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
382     {
383         CborValue oxm;
384         cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmLen);
385         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName array Length.")
386         VERIFY_SUCCESS(TAG, doxm->oxmLen != 0, ERROR);
387
388         doxm->oxm = (OicSecOxm_t *)OICCalloc(doxm->oxmLen, sizeof(*doxm->oxm));
389         VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
390
391         cborFindResult = cbor_value_enter_container(&doxmMap, &oxm);
392         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmName Array.")
393
394         int i = 0;
395         while (cbor_value_is_valid(&oxm) && cbor_value_is_integer(&oxm))
396         {
397             cborFindResult = cbor_value_get_int(&oxm, (int *) &doxm->oxm[i++]);
398             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName Value")
399             cborFindResult = cbor_value_advance(&oxm);
400             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmName.")
401         }
402
403         if (roParsed)
404         {
405             *roParsed = true;
406         }
407     }
408     else
409     {
410         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
411         doxm->oxm = (OicSecOxm_t *) OICCalloc(gDoxm->oxmLen, sizeof(*doxm->oxm));
412         VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
413         doxm->oxmLen = gDoxm->oxmLen;
414         int i;
415         for (i = 0; i < gDoxm->oxmLen; i++)
416         {
417             doxm->oxm[i] = gDoxm->oxm[i];
418         }
419     }
420
421     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_SEL_NAME, &doxmMap);
422     if (CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
423     {
424         cborFindResult = cbor_value_get_int(&doxmMap, (int *) &doxm->oxmSel);
425         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sel Name Value.")
426     }
427     else // PUT/POST JSON may not have oxmsel so set it to the gDoxm->oxmSel
428     {
429         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
430         doxm->oxmSel = gDoxm->oxmSel;
431     }
432
433     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_SUPPORTED_CRED_TYPE_NAME, &doxmMap);
434     if (CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
435     {
436         cborFindResult = cbor_value_get_int(&doxmMap, (int *) &doxm->sct);
437         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sct Name Value.")
438
439         if (roParsed)
440         {
441             *roParsed = true;
442         }
443     }
444     else // PUT/POST JSON may not have sct so set it to the gDoxm->sct
445     {
446         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
447         doxm->sct = gDoxm->sct;
448     }
449
450     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OWNED_NAME, &doxmMap);
451     if (CborNoError == cborFindResult && cbor_value_is_boolean(&doxmMap))
452     {
453         cborFindResult = cbor_value_get_boolean(&doxmMap, &doxm->owned);
454         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owned Value.")
455     }
456     else // PUT/POST JSON may not have owned so set it to the gDomx->owned
457     {
458         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
459         doxm->owned = gDoxm->owned;
460     }
461
462     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DPC_NAME, &doxmMap);
463     if (CborNoError == cborFindResult && cbor_value_is_boolean(&doxmMap))
464     {
465         cborFindResult = cbor_value_get_boolean(&doxmMap, &doxm->dpc);
466         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding DPC Value.")
467     }
468     else // PUT/POST JSON may not have dpc so set it to the gDomx->dpc
469     {
470         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
471         doxm->dpc = gDoxm->dpc;
472     }
473
474     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVICE_ID_NAME, &doxmMap);
475     if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
476     {
477         cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
478         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Device Id Value.");
479         ret = ConvertStrToUuid(strUuid , &doxm->deviceID);
480         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
481         OICFree(strUuid);
482         strUuid  = NULL;
483
484         if (roParsed)
485         {
486             *roParsed = true;
487         }
488     }
489     else
490     {
491         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
492         memcpy(doxm->deviceID.id, &gDoxm->deviceID.id, sizeof(doxm->deviceID.id));
493     }
494
495     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVOWNERID_NAME, &doxmMap);
496     if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
497     {
498         cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
499         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owner Value.");
500         ret = ConvertStrToUuid(strUuid , &doxm->owner);
501         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
502         OICFree(strUuid);
503         strUuid  = NULL;
504     }
505     else
506     {
507         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
508         memcpy(doxm->owner.id, gDoxm->owner.id, sizeof(doxm->owner.id));
509     }
510
511     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_ROWNERID_NAME, &doxmMap);
512     if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
513     {
514         cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
515         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding ROwner Value.");
516         ret = ConvertStrToUuid(strUuid , &doxm->rownerID);
517         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
518         OICFree(strUuid);
519         strUuid  = NULL;
520     }
521     else
522     {
523         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
524         memcpy(doxm->rownerID.id, gDoxm->rownerID.id, sizeof(doxm->rownerID.id));
525     }
526
527     *secDoxm = doxm;
528     ret = OC_STACK_OK;
529
530 exit:
531     if (CborNoError != cborFindResult)
532     {
533         OIC_LOG (ERROR, TAG, "CBORPayloadToDoxm failed!!!");
534         DeleteDoxmBinData(doxm);
535         doxm = NULL;
536         *secDoxm = NULL;
537         ret = OC_STACK_ERROR;
538     }
539     return ret;
540 }
541
542 /**
543  * @todo document this function including why code might need to call this.
544  * The current suspicion is that it's not being called as much as it should.
545  */
546 static bool UpdatePersistentStorage(OicSecDoxm_t * doxm)
547 {
548     bool bRet = false;
549
550     if (NULL != doxm)
551     {
552         // Convert Doxm data into CBOR for update to persistent storage
553         uint8_t *payload = NULL;
554         size_t size = 0;
555         OCStackResult res = DoxmToCBORPayload(doxm, &payload, &size, false);
556         if (payload && (OC_STACK_OK == res)
557             && (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, payload, size)))
558         {
559                 bRet = true;
560         }
561         OICFree(payload);
562     }
563     else
564     {
565         if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, NULL, 0))
566         {
567                 bRet = true;
568         }
569     }
570
571     return bRet;
572 }
573
574 static bool ValidateQuery(const char * query)
575 {
576     // Send doxm resource data if the state of doxm resource
577     // matches with the query parameters.
578     // else send doxm resource data as NULL
579     // TODO Remove this check and rely on Policy Engine
580     // and Provisioning Mode to enforce provisioning-state
581     // access rules. Eventually, the PE and PM code will
582     // not send a request to the /doxm Entity Handler at all
583     // if it should not respond.
584     OIC_LOG (DEBUG, TAG, "In ValidateQuery");
585     if(NULL == gDoxm)
586     {
587         return false;
588     }
589
590     bool bOwnedQry = false;         // does querystring contains 'owned' query ?
591     bool bOwnedMatch = false;       // does 'owned' query value matches with doxm.owned status?
592     bool bDeviceIDQry = false;      // does querystring contains 'deviceid' query ?
593     bool bDeviceIDMatch = false;    // does 'deviceid' query matches with doxm.deviceid ?
594     bool bInterfaceQry = false;      // does querystring contains 'if' query ?
595     bool bInterfaceMatch = false;    // does 'if' query matches with oic.if.baseline ?
596
597     OicParseQueryIter_t parseIter = {.attrPos = NULL};
598
599     ParseQueryIterInit((unsigned char*)query, &parseIter);
600
601     while (GetNextQuery(&parseIter))
602     {
603         if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
604         {
605             bOwnedQry = true;
606             if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
607                     (gDoxm->owned))
608             {
609                 bOwnedMatch = true;
610             }
611             else if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_FALSE, parseIter.valLen) == 0)
612                     && (!gDoxm->owned))
613             {
614                 bOwnedMatch = true;
615             }
616         }
617
618         if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_DEVICE_ID_NAME, parseIter.attrLen) == 0)
619         {
620             bDeviceIDQry = true;
621             OicUuid_t subject = {.id={0}};
622
623             memcpy(subject.id, parseIter.valPos, parseIter.valLen);
624             if (0 == memcmp(&gDoxm->deviceID.id, &subject.id, sizeof(gDoxm->deviceID.id)))
625             {
626                 bDeviceIDMatch = true;
627             }
628         }
629
630         if (strncasecmp((char *)parseIter.attrPos, OC_RSRVD_INTERFACE, parseIter.attrLen) == 0)
631         {
632             bInterfaceQry = true;
633             if ((strncasecmp((char *)parseIter.valPos, OC_RSRVD_INTERFACE_DEFAULT, parseIter.valLen) == 0))
634             {
635                 bInterfaceMatch = true;
636             }
637             return (bInterfaceQry ? bInterfaceMatch: true);
638         }
639     }
640
641     return ((bOwnedQry ? bOwnedMatch : true) && (bDeviceIDQry ? bDeviceIDMatch : true));
642 }
643
644 static OCEntityHandlerResult HandleDoxmGetRequest (const OCEntityHandlerRequest * ehRequest)
645 {
646     OCEntityHandlerResult ehRet = OC_EH_OK;
647
648     OIC_LOG(DEBUG, TAG, "Doxm EntityHandle processing GET request");
649
650     //Checking if Get request is a query.
651     if (ehRequest->query)
652     {
653         OIC_LOG_V(DEBUG,TAG,"query:%s",ehRequest->query);
654         OIC_LOG(DEBUG, TAG, "HandleDoxmGetRequest processing query");
655         if (!ValidateQuery(ehRequest->query))
656         {
657             ehRet = OC_EH_ERROR;
658         }
659     }
660
661     /*
662      * For GET or Valid Query request return doxm resource CBOR payload.
663      * For non-valid query return NULL json payload.
664      * A device will 'always' have a default Doxm, so DoxmToCBORPayload will
665      * return valid doxm resource json.
666      */
667     uint8_t *payload = NULL;
668     size_t size = 0;
669
670     if (ehRet == OC_EH_OK)
671     {
672         if (OC_STACK_OK != DoxmToCBORPayload(gDoxm, &payload, &size, false))
673         {
674             OIC_LOG(WARNING, TAG, "DoxmToCBORPayload failed in HandleDoxmGetRequest");
675         }
676     }
677
678     // Send response payload to request originator
679     ehRet = ((SendSRMResponse(ehRequest, ehRet, payload, size)) == OC_STACK_OK) ?
680                    OC_EH_OK : OC_EH_ERROR;
681
682     OICFree(payload);
683
684     return ehRet;
685 }
686
687 static OCEntityHandlerResult HandleDoxmPostRequest(const OCEntityHandlerRequest * ehRequest)
688 {
689     OIC_LOG (DEBUG, TAG, "Doxm EntityHandle  processing POST request");
690     OCEntityHandlerResult ehRet = OC_EH_ERROR;
691     OicUuid_t emptyOwner = {.id = {0} };
692     static uint16_t previousMsgId = 0;
693
694     /*
695      * Convert CBOR Doxm data into binary. This will also validate
696      * the Doxm data received.
697      */
698     OicSecDoxm_t *newDoxm = NULL;
699
700     if (ehRequest->payload)
701     {
702         uint8_t *payload = ((OCSecurityPayload *)ehRequest->payload)->securityData;
703         size_t size = ((OCSecurityPayload *)ehRequest->payload)->payloadSize;
704         bool roParsed = false;
705         OCStackResult res = CBORPayloadToDoxmBin(payload, size, &newDoxm, &roParsed);
706         if (newDoxm && OC_STACK_OK == res)
707         {
708             // Check request on RO property
709             if (true == roParsed)
710             {
711                 OIC_LOG(ERROR, TAG, "Not acceptable request because of read-only propertys");
712                 ehRet = OC_EH_NOT_ACCEPTABLE;
713                 goto exit;
714             }
715
716             // in owned state
717             if (true == gDoxm->owned)
718             {
719                 // update writable properties
720                 gDoxm->oxmSel = newDoxm->oxmSel;
721                 memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
722                 memcpy(&(gDoxm->rownerID), &(newDoxm->rownerID), sizeof(OicUuid_t));
723
724                 if(gDoxm->owned != newDoxm->owned)
725                 {
726                     gDoxm->owned = newDoxm->owned;
727                 }
728
729                 //Update new state in persistent storage
730                 if (UpdatePersistentStorage(gDoxm) == true)
731                 {
732                     ehRet = OC_EH_OK;
733                 }
734                 else
735                 {
736                     OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
737                     ehRet = OC_EH_ERROR;
738                 }
739                 goto exit;
740             }
741
742             // in unowned state
743             if ((false == gDoxm->owned) && (false == newDoxm->owned))
744             {
745                 if (OIC_JUST_WORKS == newDoxm->oxmSel)
746                 {
747                     /*
748                      * If current state of the device is un-owned, enable
749                      * anonymous ECDH cipher in tinyDTLS so that Provisioning
750                      * tool can initiate JUST_WORKS ownership transfer process.
751                      */
752                     if (memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
753                     {
754                         OIC_LOG (INFO, TAG, "Doxm EntityHandle  enabling AnonECDHCipherSuite");
755 #ifdef __WITH_DTLS__
756                         ehRet = (CAEnableAnonECDHCipherSuite(true) == CA_STATUS_OK) ? OC_EH_OK : OC_EH_ERROR;
757 #endif //__WITH_DTLS__
758                         goto exit;
759                     }
760                     else
761                     {
762 #ifdef __WITH_DTLS__
763                         //Save the owner's UUID to derive owner credential
764                         memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
765
766                         // Update new state in persistent storage
767                         if (true == UpdatePersistentStorage(gDoxm))
768                         {
769                             ehRet = OC_EH_OK;
770                         }
771                         else
772                         {
773                             OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
774                             ehRet = OC_EH_ERROR;
775                         }
776
777                         /*
778                          * Disable anonymous ECDH cipher in tinyDTLS since device is now
779                          * in owned state.
780                          */
781                         CAResult_t caRes = CA_STATUS_OK;
782                         caRes = CAEnableAnonECDHCipherSuite(false);
783                         VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
784                         OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
785
786 #ifdef __WITH_X509__
787 #define TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 0xC0AE
788                         CASelectCipherSuite(TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8);
789 #endif //__WITH_X509__
790 #endif //__WITH_DTLS__
791                     }
792                 }
793                 else if (OIC_RANDOM_DEVICE_PIN == newDoxm->oxmSel)
794                 {
795                     /*
796                      * If current state of the device is un-owned, enable
797                      * anonymous ECDH cipher in tinyDTLS so that Provisioning
798                      * tool can initiate JUST_WORKS ownership transfer process.
799                      */
800                     if(memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
801                     {
802                         gDoxm->oxmSel = newDoxm->oxmSel;
803                         //Update new state in persistent storage
804                         if ((UpdatePersistentStorage(gDoxm) == true))
805                         {
806                             ehRet = OC_EH_OK;
807                         }
808                         else
809                         {
810                             OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
811                             ehRet = OC_EH_ERROR;
812                         }
813
814 #ifdef __WITH_DTLS__
815                         CAResult_t caRes = CA_STATUS_OK;
816
817                         caRes = CAEnableAnonECDHCipherSuite(false);
818                         VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
819                         OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
820
821                         caRes = CASelectCipherSuite(TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256);
822                         VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
823
824                         if(previousMsgId != ehRequest->messageID)
825                         {
826                             char ranPin[OXM_RANDOM_PIN_SIZE + 1] = {0,};
827                             if(OC_STACK_OK == GeneratePin(ranPin, OXM_RANDOM_PIN_SIZE + 1))
828                             {
829                                 //Set the device id to derive temporal PSK
830                                 SetUuidForRandomPinOxm(&gDoxm->deviceID);
831
832                                 /**
833                                  * Since PSK will be used directly by DTLS layer while PIN based ownership transfer,
834                                  * Credential should not be saved into SVR.
835                                  * For this reason, use a temporary get_psk_info callback to random PIN OxM.
836                                  */
837                                 caRes = CARegisterDTLSCredentialsHandler(GetDtlsPskForRandomPinOxm);
838                                 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
839                                 ehRet = OC_EH_OK;
840                             }
841                             else
842                             {
843                                 OIC_LOG(ERROR, TAG, "Failed to generate random PIN");
844                                 ehRet = OC_EH_ERROR;
845                             }
846                         }
847 #endif //__WITH_DTLS__
848                     }
849                     else
850                     {
851 #ifdef __WITH_DTLS__
852                         //Save the owner's UUID to derive owner credential
853                         memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
854
855                         //Update new state in persistent storage
856                         if (UpdatePersistentStorage(gDoxm) == true)
857                         {
858                             ehRet = OC_EH_OK;
859                         }
860                         else
861                         {
862                             OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
863                             ehRet = OC_EH_ERROR;
864                         }
865 #endif
866                     }
867                 }
868             }
869
870             /*
871              * When current state of the device is un-owned and Provisioning
872              * Tool is attempting to change the state to 'Owned' with a
873              * qualified value for the field 'Owner'
874              */
875             if ((false == gDoxm->owned) && (true == newDoxm->owned) &&
876                     (memcmp(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t)) == 0))
877             {
878                 //Change the SVR's resource owner as owner device.
879                 OCStackResult ownerRes = SetAclRownerId(&gDoxm->owner);
880                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
881                 {
882                     ehRet = OC_EH_ERROR;
883                     goto exit;
884                 }
885                 ownerRes = SetAmaclRownerId(&gDoxm->owner);
886                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
887                 {
888                     ehRet = OC_EH_ERROR;
889                     goto exit;
890                 }
891                 ownerRes = SetCredRownerId(&gDoxm->owner);
892                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
893                 {
894                     ehRet = OC_EH_ERROR;
895                     goto exit;
896                 }
897                 ownerRes = SetPstatRownerId(&gDoxm->owner);
898                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
899                 {
900                     ehRet = OC_EH_ERROR;
901                     goto exit;
902                 }
903                 ownerRes = SetDpairingRownerId(&gDoxm->owner);
904                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
905                 {
906                     ehRet = OC_EH_ERROR;
907                     goto exit;
908                 }
909                 ownerRes = SetPconfRownerId(&gDoxm->owner);
910                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
911                 {
912                     ehRet = OC_EH_ERROR;
913                     goto exit;
914                 }
915
916                 gDoxm->owned = true;
917                 memcpy(&gDoxm->rownerID, &gDoxm->owner, sizeof(OicUuid_t));
918
919                 // Update new state in persistent storage
920                 if (UpdatePersistentStorage(gDoxm))
921                 {
922                     //Update default ACE of security resource to prevent anonymous user access.
923                     if(OC_STACK_OK == UpdateDefaultSecProvACE())
924                     {
925                         ehRet = OC_EH_OK;
926                     }
927                     else
928                     {
929                         OIC_LOG(ERROR, TAG, "Failed to remove default ACL for security provisioning");
930                         ehRet = OC_EH_ERROR;
931                     }
932                 }
933                 else
934                 {
935                     OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
936                     ehRet = OC_EH_ERROR;
937                 }
938             }
939         }
940     }
941
942 exit:
943     if(OC_EH_OK != ehRet)
944     {
945
946         /*
947          * If some error is occured while ownership transfer,
948          * ownership transfer related resource should be revert back to initial status.
949         */
950         if(gDoxm)
951         {
952             if(!gDoxm->owned && previousMsgId != ehRequest->messageID)
953             {
954                 OIC_LOG(WARNING, TAG, "The operation failed during handle DOXM request,"\
955                                     "DOXM will be reverted.");
956                 RestoreDoxmToInitState();
957                 RestorePstatToInitState();
958             }
959         }
960         else
961         {
962             OIC_LOG(ERROR, TAG, "Invalid DOXM resource.");
963         }
964     }
965     else
966     {
967         previousMsgId = ehRequest->messageID;
968     }
969
970     //Send payload to request originator
971     ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
972                    OC_EH_OK : OC_EH_ERROR;
973
974     DeleteDoxmBinData(newDoxm);
975
976     return ehRet;
977 }
978
979 OCEntityHandlerResult DoxmEntityHandler(OCEntityHandlerFlag flag,
980                                         OCEntityHandlerRequest * ehRequest,
981                                         void* callbackParam)
982 {
983     (void)callbackParam;
984     OCEntityHandlerResult ehRet = OC_EH_ERROR;
985
986     if(NULL == ehRequest)
987     {
988         return ehRet;
989     }
990
991     if (flag & OC_REQUEST_FLAG)
992     {
993         OIC_LOG(DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
994
995         switch (ehRequest->method)
996         {
997             case OC_REST_GET:
998                 ehRet = HandleDoxmGetRequest(ehRequest);
999                 break;
1000
1001             case OC_REST_POST:
1002                 ehRet = HandleDoxmPostRequest(ehRequest);
1003                 break;
1004
1005             default:
1006                 ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1007                                OC_EH_OK : OC_EH_ERROR;
1008                 break;
1009         }
1010     }
1011
1012     return ehRet;
1013 }
1014
1015 OCStackResult CreateDoxmResource()
1016 {
1017     OCStackResult ret = OCCreateResource(&gDoxmHandle,
1018                                          OIC_RSRC_TYPE_SEC_DOXM,
1019                                          OC_RSRVD_INTERFACE_DEFAULT,
1020                                          OIC_RSRC_DOXM_URI,
1021                                          DoxmEntityHandler,
1022                                          NULL,
1023                                          OC_SECURE |
1024                                          OC_DISCOVERABLE);
1025
1026     if (OC_STACK_OK != ret)
1027     {
1028         OIC_LOG (FATAL, TAG, "Unable to instantiate Doxm resource");
1029         DeInitDoxmResource();
1030     }
1031     return ret;
1032 }
1033
1034 /**
1035  * Checks if DeviceID is generated during provisioning for the new device.
1036  * If DeviceID is NULL then generates the new DeviceID.
1037  * Once DeviceID is assigned to the device it does not change for the lifetime of the device.
1038  */
1039 static OCStackResult CheckDeviceID()
1040 {
1041     OCStackResult ret = OC_STACK_ERROR;
1042     bool validId = false;
1043     for (uint8_t i = 0; i < UUID_LENGTH; i++)
1044     {
1045         if (gDoxm->deviceID.id[i] != 0)
1046         {
1047             validId = true;
1048             break;
1049         }
1050     }
1051
1052     if (!validId)
1053     {
1054         if (OCGenerateUuid(gDoxm->deviceID.id) != RAND_UUID_OK)
1055         {
1056             OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
1057             return ret;
1058         }
1059         ret = OC_STACK_OK;
1060
1061         if (!UpdatePersistentStorage(gDoxm))
1062         {
1063             //TODO: After registering PSI handler in all samples, do ret = OC_STACK_OK here.
1064             OIC_LOG(FATAL, TAG, "UpdatePersistentStorage failed!");
1065         }
1066     }
1067     else
1068     {
1069         ret = OC_STACK_OK;
1070     }
1071     return ret;
1072 }
1073
1074 /**
1075  * Get the default value.
1076  *
1077  * @return the default value of doxm, @ref OicSecDoxm_t.
1078  */
1079 static OicSecDoxm_t* GetDoxmDefault()
1080 {
1081     OIC_LOG(DEBUG, TAG, "GetDoxmToDefault");
1082     return &gDefaultDoxm;
1083 }
1084
1085 const OicSecDoxm_t* GetDoxmResourceData()
1086 {
1087     return gDoxm;
1088 }
1089
1090 OCStackResult InitDoxmResource()
1091 {
1092     OCStackResult ret = OC_STACK_ERROR;
1093
1094     //Read DOXM resource from PS
1095     uint8_t *data = NULL;
1096     size_t size = 0;
1097     ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_DOXM_NAME, &data, &size);
1098     // If database read failed
1099     if (OC_STACK_OK != ret)
1100     {
1101        OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
1102     }
1103     if (data)
1104     {
1105        // Read DOXM resource from PS
1106        ret = CBORPayloadToDoxm(data, size, &gDoxm);
1107     }
1108     /*
1109      * If SVR database in persistent storage got corrupted or
1110      * is not available for some reason, a default doxm is created
1111      * which allows user to initiate doxm provisioning again.
1112      */
1113      if ((OC_STACK_OK != ret) || !data || !gDoxm)
1114     {
1115         gDoxm = GetDoxmDefault();
1116     }
1117
1118     //In case of the server is shut down unintentionally, we should initialize the owner
1119     if(false == gDoxm->owned)
1120     {
1121         OicUuid_t emptyUuid = {.id={0}};
1122         memcpy(&gDoxm->owner, &emptyUuid, sizeof(OicUuid_t));
1123     }
1124
1125     ret = CheckDeviceID();
1126     if (ret == OC_STACK_OK)
1127     {
1128         OIC_LOG_V(DEBUG, TAG, "Initial Doxm Owned = %d", gDoxm->owned);
1129         //Instantiate 'oic.sec.doxm'
1130         ret = CreateDoxmResource();
1131     }
1132     else
1133     {
1134         OIC_LOG (ERROR, TAG, "CheckDeviceID failed");
1135     }
1136     OICFree(data);
1137     return ret;
1138 }
1139
1140 OCStackResult DeInitDoxmResource()
1141 {
1142     OCStackResult ret = OCDeleteResource(gDoxmHandle);
1143     if (gDoxm  != &gDefaultDoxm)
1144     {
1145         DeleteDoxmBinData(gDoxm);
1146     }
1147     gDoxm = NULL;
1148
1149     if (OC_STACK_OK == ret)
1150     {
1151         return OC_STACK_OK;
1152     }
1153     else
1154     {
1155         return OC_STACK_ERROR;
1156     }
1157 }
1158
1159 OCStackResult GetDoxmDeviceID(OicUuid_t *deviceID)
1160 {
1161     if (deviceID && gDoxm)
1162     {
1163        *deviceID = gDoxm->deviceID;
1164         return OC_STACK_OK;
1165     }
1166     return OC_STACK_ERROR;
1167 }
1168
1169 OCStackResult GetDoxmDevOwnerId(OicUuid_t *devownerid)
1170 {
1171     OCStackResult retVal = OC_STACK_ERROR;
1172     if (gDoxm)
1173     {
1174         OIC_LOG_V(DEBUG, TAG, "GetDoxmDevOwnerId(): gDoxm owned =  %d.", \
1175             gDoxm->owned);
1176         if (gDoxm->owned)
1177         {
1178             *devownerid = gDoxm->owner;
1179             retVal = OC_STACK_OK;
1180         }
1181     }
1182     return retVal;
1183 }
1184
1185 OCStackResult GetDoxmRownerId(OicUuid_t *rowneruuid)
1186 {
1187     OCStackResult retVal = OC_STACK_ERROR;
1188     if (gDoxm)
1189     {
1190         if( gDoxm->owned )
1191         {
1192             *rowneruuid = gDoxm->rownerID;
1193                     retVal = OC_STACK_OK;
1194         }
1195     }
1196     return retVal;
1197 }
1198
1199 /**
1200  * Function to restore doxm resurce to initial status.
1201  * This function will use in case of error while ownership transfer
1202  */
1203 void RestoreDoxmToInitState()
1204 {
1205     if(gDoxm)
1206     {
1207         OIC_LOG(INFO, TAG, "DOXM resource will revert back to initial status.");
1208
1209         OicUuid_t emptyUuid = {.id={0}};
1210         memcpy(&(gDoxm->owner), &emptyUuid, sizeof(OicUuid_t));
1211         gDoxm->owned = false;
1212         gDoxm->oxmSel = OIC_JUST_WORKS;
1213
1214         if(!UpdatePersistentStorage(gDoxm))
1215         {
1216             OIC_LOG(ERROR, TAG, "Failed to revert DOXM in persistent storage");
1217         }
1218     }
1219 }