Merge branch 'cloud-interface'
[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             int tmp;
398
399             cborFindResult = cbor_value_get_int(&oxm, &tmp);
400             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName Value")
401             doxm->oxm[i++] = (OicSecOxm_t)tmp;
402             cborFindResult = cbor_value_advance(&oxm);
403             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmName.")
404         }
405
406         if (roParsed)
407         {
408             *roParsed = true;
409         }
410     }
411     else
412     {
413         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
414         doxm->oxm = (OicSecOxm_t *) OICCalloc(gDoxm->oxmLen, sizeof(*doxm->oxm));
415         VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
416         doxm->oxmLen = gDoxm->oxmLen;
417         int i;
418         for (i = 0; i < gDoxm->oxmLen; i++)
419         {
420             doxm->oxm[i] = gDoxm->oxm[i];
421         }
422     }
423
424     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_SEL_NAME, &doxmMap);
425     if (CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
426     {
427         int oxmSel;
428
429         cborFindResult = cbor_value_get_int(&doxmMap, &oxmSel);
430         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sel Name Value.")
431         doxm->oxmSel = (OicSecOxm_t)oxmSel;
432     }
433     else // PUT/POST JSON may not have oxmsel so set it to the gDoxm->oxmSel
434     {
435         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
436         doxm->oxmSel = gDoxm->oxmSel;
437     }
438
439     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_SUPPORTED_CRED_TYPE_NAME, &doxmMap);
440     if (CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
441     {
442         int sct;
443
444         cborFindResult = cbor_value_get_int(&doxmMap, &sct);
445         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sct Name Value.")
446         doxm->sct = (OicSecCredType_t)sct;
447
448         if (roParsed)
449         {
450             *roParsed = true;
451         }
452     }
453     else // PUT/POST JSON may not have sct so set it to the gDoxm->sct
454     {
455         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
456         doxm->sct = gDoxm->sct;
457     }
458
459     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OWNED_NAME, &doxmMap);
460     if (CborNoError == cborFindResult && cbor_value_is_boolean(&doxmMap))
461     {
462         cborFindResult = cbor_value_get_boolean(&doxmMap, &doxm->owned);
463         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owned Value.")
464     }
465     else // PUT/POST JSON may not have owned so set it to the gDomx->owned
466     {
467         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
468         doxm->owned = gDoxm->owned;
469     }
470
471     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DPC_NAME, &doxmMap);
472     if (CborNoError == cborFindResult && cbor_value_is_boolean(&doxmMap))
473     {
474         cborFindResult = cbor_value_get_boolean(&doxmMap, &doxm->dpc);
475         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding DPC Value.")
476     }
477     else // PUT/POST JSON may not have dpc so set it to the gDomx->dpc
478     {
479         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
480         doxm->dpc = gDoxm->dpc;
481     }
482
483     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVICE_ID_NAME, &doxmMap);
484     if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
485     {
486         cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
487         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Device Id Value.");
488         ret = ConvertStrToUuid(strUuid , &doxm->deviceID);
489         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
490         OICFree(strUuid);
491         strUuid  = NULL;
492
493         if (roParsed)
494         {
495             *roParsed = true;
496         }
497     }
498     else
499     {
500         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
501         memcpy(doxm->deviceID.id, &gDoxm->deviceID.id, sizeof(doxm->deviceID.id));
502     }
503
504     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVOWNERID_NAME, &doxmMap);
505     if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
506     {
507         cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
508         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owner Value.");
509         ret = ConvertStrToUuid(strUuid , &doxm->owner);
510         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
511         OICFree(strUuid);
512         strUuid  = NULL;
513     }
514     else
515     {
516         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
517         memcpy(doxm->owner.id, gDoxm->owner.id, sizeof(doxm->owner.id));
518     }
519
520     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_ROWNERID_NAME, &doxmMap);
521     if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
522     {
523         cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
524         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding ROwner Value.");
525         ret = ConvertStrToUuid(strUuid , &doxm->rownerID);
526         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
527         OICFree(strUuid);
528         strUuid  = NULL;
529     }
530     else
531     {
532         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
533         memcpy(doxm->rownerID.id, gDoxm->rownerID.id, sizeof(doxm->rownerID.id));
534     }
535
536     *secDoxm = doxm;
537     ret = OC_STACK_OK;
538
539 exit:
540     if (CborNoError != cborFindResult)
541     {
542         OIC_LOG (ERROR, TAG, "CBORPayloadToDoxm failed!!!");
543         DeleteDoxmBinData(doxm);
544         doxm = NULL;
545         *secDoxm = NULL;
546         ret = OC_STACK_ERROR;
547     }
548     return ret;
549 }
550
551 /**
552  * @todo document this function including why code might need to call this.
553  * The current suspicion is that it's not being called as much as it should.
554  */
555 static bool UpdatePersistentStorage(OicSecDoxm_t * doxm)
556 {
557     bool bRet = false;
558
559     if (NULL != doxm)
560     {
561         // Convert Doxm data into CBOR for update to persistent storage
562         uint8_t *payload = NULL;
563         size_t size = 0;
564         OCStackResult res = DoxmToCBORPayload(doxm, &payload, &size, false);
565         if (payload && (OC_STACK_OK == res)
566             && (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, payload, size)))
567         {
568                 bRet = true;
569         }
570         OICFree(payload);
571     }
572     else
573     {
574         if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, NULL, 0))
575         {
576                 bRet = true;
577         }
578     }
579
580     return bRet;
581 }
582
583 static bool ValidateQuery(const char * query)
584 {
585     // Send doxm resource data if the state of doxm resource
586     // matches with the query parameters.
587     // else send doxm resource data as NULL
588     // TODO Remove this check and rely on Policy Engine
589     // and Provisioning Mode to enforce provisioning-state
590     // access rules. Eventually, the PE and PM code will
591     // not send a request to the /doxm Entity Handler at all
592     // if it should not respond.
593     OIC_LOG (DEBUG, TAG, "In ValidateQuery");
594     if(NULL == gDoxm)
595     {
596         return false;
597     }
598
599     bool bOwnedQry = false;         // does querystring contains 'owned' query ?
600     bool bOwnedMatch = false;       // does 'owned' query value matches with doxm.owned status?
601     bool bDeviceIDQry = false;      // does querystring contains 'deviceid' query ?
602     bool bDeviceIDMatch = false;    // does 'deviceid' query matches with doxm.deviceid ?
603     bool bInterfaceQry = false;      // does querystring contains 'if' query ?
604     bool bInterfaceMatch = false;    // does 'if' query matches with oic.if.baseline ?
605
606     OicParseQueryIter_t parseIter = {.attrPos = NULL};
607
608     ParseQueryIterInit((unsigned char*)query, &parseIter);
609
610     while (GetNextQuery(&parseIter))
611     {
612         if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
613         {
614             bOwnedQry = true;
615             if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
616                     (gDoxm->owned))
617             {
618                 bOwnedMatch = true;
619             }
620             else if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_FALSE, parseIter.valLen) == 0)
621                     && (!gDoxm->owned))
622             {
623                 bOwnedMatch = true;
624             }
625         }
626
627         if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_DEVICE_ID_NAME, parseIter.attrLen) == 0)
628         {
629             bDeviceIDQry = true;
630             OicUuid_t subject = {.id={0}};
631
632             memcpy(subject.id, parseIter.valPos, parseIter.valLen);
633             if (0 == memcmp(&gDoxm->deviceID.id, &subject.id, sizeof(gDoxm->deviceID.id)))
634             {
635                 bDeviceIDMatch = true;
636             }
637         }
638
639         if (strncasecmp((char *)parseIter.attrPos, OC_RSRVD_INTERFACE, parseIter.attrLen) == 0)
640         {
641             bInterfaceQry = true;
642             if ((strncasecmp((char *)parseIter.valPos, OC_RSRVD_INTERFACE_DEFAULT, parseIter.valLen) == 0))
643             {
644                 bInterfaceMatch = true;
645             }
646             return (bInterfaceQry ? bInterfaceMatch: true);
647         }
648     }
649
650     return ((bOwnedQry ? bOwnedMatch : true) && (bDeviceIDQry ? bDeviceIDMatch : true));
651 }
652
653 static OCEntityHandlerResult HandleDoxmGetRequest (const OCEntityHandlerRequest * ehRequest)
654 {
655     OCEntityHandlerResult ehRet = OC_EH_OK;
656
657     OIC_LOG(DEBUG, TAG, "Doxm EntityHandle processing GET request");
658
659     //Checking if Get request is a query.
660     if (ehRequest->query)
661     {
662         OIC_LOG_V(DEBUG,TAG,"query:%s",ehRequest->query);
663         OIC_LOG(DEBUG, TAG, "HandleDoxmGetRequest processing query");
664         if (!ValidateQuery(ehRequest->query))
665         {
666             ehRet = OC_EH_ERROR;
667         }
668     }
669
670     /*
671      * For GET or Valid Query request return doxm resource CBOR payload.
672      * For non-valid query return NULL json payload.
673      * A device will 'always' have a default Doxm, so DoxmToCBORPayload will
674      * return valid doxm resource json.
675      */
676     uint8_t *payload = NULL;
677     size_t size = 0;
678
679     if (ehRet == OC_EH_OK)
680     {
681         if (OC_STACK_OK != DoxmToCBORPayload(gDoxm, &payload, &size, false))
682         {
683             OIC_LOG(WARNING, TAG, "DoxmToCBORPayload failed in HandleDoxmGetRequest");
684         }
685     }
686
687     OIC_LOG(DEBUG, TAG, "Send payload for doxm GET request");
688     OIC_LOG_BUFFER(DEBUG, TAG, payload, size);
689
690     // Send response payload to request originator
691     ehRet = ((SendSRMResponse(ehRequest, ehRet, payload, size)) == OC_STACK_OK) ?
692                    OC_EH_OK : OC_EH_ERROR;
693
694     OICFree(payload);
695
696     return ehRet;
697 }
698
699 static OCEntityHandlerResult HandleDoxmPostRequest(const OCEntityHandlerRequest * ehRequest)
700 {
701     OIC_LOG (DEBUG, TAG, "Doxm EntityHandle  processing POST request");
702     OCEntityHandlerResult ehRet = OC_EH_ERROR;
703     OicUuid_t emptyOwner = {.id = {0} };
704     static uint16_t previousMsgId = 0;
705
706     /*
707      * Convert CBOR Doxm data into binary. This will also validate
708      * the Doxm data received.
709      */
710     OicSecDoxm_t *newDoxm = NULL;
711
712     if (ehRequest->payload)
713     {
714         uint8_t *payload = ((OCSecurityPayload *)ehRequest->payload)->securityData;
715         size_t size = ((OCSecurityPayload *)ehRequest->payload)->payloadSize;
716         bool roParsed = false;
717         OCStackResult res = CBORPayloadToDoxmBin(payload, size, &newDoxm, &roParsed);
718         if (newDoxm && OC_STACK_OK == res)
719         {
720             // Check request on RO property
721             if (true == roParsed)
722             {
723                 OIC_LOG(ERROR, TAG, "Not acceptable request because of read-only propertys");
724                 ehRet = OC_EH_NOT_ACCEPTABLE;
725                 goto exit;
726             }
727
728             // in owned state
729             if (true == gDoxm->owned)
730             {
731                 // update writable properties
732                 gDoxm->oxmSel = newDoxm->oxmSel;
733                 memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
734                 memcpy(&(gDoxm->rownerID), &(newDoxm->rownerID), sizeof(OicUuid_t));
735
736                 if(gDoxm->owned != newDoxm->owned)
737                 {
738                     gDoxm->owned = newDoxm->owned;
739                 }
740
741                 //Update new state in persistent storage
742                 if (UpdatePersistentStorage(gDoxm) == true)
743                 {
744                     ehRet = OC_EH_OK;
745                 }
746                 else
747                 {
748                     OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
749                     ehRet = OC_EH_ERROR;
750                 }
751                 goto exit;
752             }
753
754             // in unowned state
755             if ((false == gDoxm->owned) && (false == newDoxm->owned))
756             {
757                 if (OIC_JUST_WORKS == newDoxm->oxmSel)
758                 {
759                     /*
760                      * If current state of the device is un-owned, enable
761                      * anonymous ECDH cipher in tinyDTLS so that Provisioning
762                      * tool can initiate JUST_WORKS ownership transfer process.
763                      */
764                     if (memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
765                     {
766                         OIC_LOG (INFO, TAG, "Doxm EntityHandle  enabling AnonECDHCipherSuite");
767 #ifdef __WITH_DTLS__
768                         ehRet = (CAEnableAnonECDHCipherSuite(true) == CA_STATUS_OK) ? OC_EH_OK : OC_EH_ERROR;
769 #endif //__WITH_DTLS__
770                         goto exit;
771                     }
772                     else
773                     {
774 #ifdef __WITH_DTLS__
775                         //Save the owner's UUID to derive owner credential
776                         memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
777
778                         // Update new state in persistent storage
779                         if (true == UpdatePersistentStorage(gDoxm))
780                         {
781                             ehRet = OC_EH_OK;
782                         }
783                         else
784                         {
785                             OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
786                             ehRet = OC_EH_ERROR;
787                         }
788
789                         /*
790                          * Disable anonymous ECDH cipher in tinyDTLS since device is now
791                          * in owned state.
792                          */
793                         CAResult_t caRes = CA_STATUS_OK;
794                         caRes = CAEnableAnonECDHCipherSuite(false);
795                         VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
796                         OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
797
798 #ifdef __WITH_X509__
799 #define TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 0xC0AE
800                         CASelectCipherSuite(TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8,
801                                             ehRequest->devAddr.adapter);
802 #endif //__WITH_X509__
803 #endif //__WITH_DTLS__
804                     }
805                 }
806                 else if (OIC_RANDOM_DEVICE_PIN == newDoxm->oxmSel)
807                 {
808                     /*
809                      * If current state of the device is un-owned, enable
810                      * anonymous ECDH cipher in tinyDTLS so that Provisioning
811                      * tool can initiate JUST_WORKS ownership transfer process.
812                      */
813                     if(memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
814                     {
815                         gDoxm->oxmSel = newDoxm->oxmSel;
816                         //Update new state in persistent storage
817                         if ((UpdatePersistentStorage(gDoxm) == true))
818                         {
819                             ehRet = OC_EH_OK;
820                         }
821                         else
822                         {
823                             OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
824                             ehRet = OC_EH_ERROR;
825                         }
826
827 #ifdef __WITH_DTLS__
828                         CAResult_t caRes = CA_STATUS_OK;
829
830                         caRes = CAEnableAnonECDHCipherSuite(false);
831                         VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
832                         OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
833
834                         caRes = CASelectCipherSuite(TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256,
835                                                     ehRequest->devAddr.adapter);
836                         VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
837
838                         char ranPin[OXM_RANDOM_PIN_SIZE + 1] = {0,};
839                          //TODO ehRequest->messageID for copa over TCP always is null. Find reason why.
840                         if(ehRequest->devAddr.adapter == OC_ADAPTER_IP && previousMsgId != ehRequest->messageID)
841                         {
842                             if(OC_STACK_OK == GeneratePin(ranPin, OXM_RANDOM_PIN_SIZE + 1))
843                             {
844                                 //Set the device id to derive temporal PSK
845                                 SetUuidForRandomPinOxm(&gDoxm->deviceID);
846
847                                 /**
848                                  * Since PSK will be used directly by DTLS layer while PIN based ownership transfer,
849                                  * Credential should not be saved into SVR.
850                                  * For this reason, use a temporary get_psk_info callback to random PIN OxM.
851                                  */
852                                 caRes = CARegisterDTLSCredentialsHandler(GetDtlsPskForRandomPinOxm);
853                                 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
854                                 ehRet = OC_EH_OK;
855                             }
856                             else
857                             {
858                                 OIC_LOG(ERROR, TAG, "Failed to generate random PIN");
859                                 ehRet = OC_EH_ERROR;
860                             }
861                         }
862                         else
863                         {
864                             if(OC_STACK_OK == GeneratePin(ranPin, OXM_RANDOM_PIN_SIZE + 1))
865                             {
866                                 //Set the device id to derive temporal PSK
867                                 SetUuidForRandomPinOxm(&gDoxm->deviceID);
868
869                                 /**
870                                  * Since PSK will be used directly by DTLS layer while PIN based ownership transfer,
871                                  * Credential should not be saved into SVR.
872                                  * For this reason, use a temporary get_psk_info callback to random PIN OxM.
873                                  */
874 #ifdef __WITH_TLS__
875                                 caRes = CAregisterTlsCredentialsHandler(GetDtlsPskForRandomPinOxm);
876 #endif
877                                 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
878                                 ehRet = OC_EH_OK;
879                             }
880                             else
881                             {
882                                 OIC_LOG(ERROR, TAG, "Failed to generate random PIN");
883                                 ehRet = OC_EH_ERROR;
884                             }
885
886                         }
887 #endif //__WITH_DTLS__
888                     }
889                     else
890                     {
891 #ifdef __WITH_DTLS__
892                         //Save the owner's UUID to derive owner credential
893                         memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
894
895                         //Update new state in persistent storage
896                         if (UpdatePersistentStorage(gDoxm) == true)
897                         {
898                             ehRet = OC_EH_OK;
899                         }
900                         else
901                         {
902                             OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
903                             ehRet = OC_EH_ERROR;
904                         }
905 #endif
906                     }
907                 }
908             }
909
910             /*
911              * When current state of the device is un-owned and Provisioning
912              * Tool is attempting to change the state to 'Owned' with a
913              * qualified value for the field 'Owner'
914              */
915             if ((false == gDoxm->owned) && (true == newDoxm->owned) &&
916                     (memcmp(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t)) == 0))
917             {
918                 //Change the SVR's resource owner as owner device.
919                 OCStackResult ownerRes = SetAclRownerId(&gDoxm->owner);
920                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
921                 {
922                     ehRet = OC_EH_ERROR;
923                     goto exit;
924                 }
925                 ownerRes = SetAmaclRownerId(&gDoxm->owner);
926                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
927                 {
928                     ehRet = OC_EH_ERROR;
929                     goto exit;
930                 }
931                 ownerRes = SetCredRownerId(&gDoxm->owner);
932                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
933                 {
934                     ehRet = OC_EH_ERROR;
935                     goto exit;
936                 }
937                 ownerRes = SetPstatRownerId(&gDoxm->owner);
938                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
939                 {
940                     ehRet = OC_EH_ERROR;
941                     goto exit;
942                 }
943                 ownerRes = SetDpairingRownerId(&gDoxm->owner);
944                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
945                 {
946                     ehRet = OC_EH_ERROR;
947                     goto exit;
948                 }
949                 ownerRes = SetPconfRownerId(&gDoxm->owner);
950                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
951                 {
952                     ehRet = OC_EH_ERROR;
953                     goto exit;
954                 }
955
956                 gDoxm->owned = true;
957                 memcpy(&gDoxm->rownerID, &gDoxm->owner, sizeof(OicUuid_t));
958
959                 // Update new state in persistent storage
960                 if (UpdatePersistentStorage(gDoxm))
961                 {
962                     //Update default ACE of security resource to prevent anonymous user access.
963                     if(OC_STACK_OK == UpdateDefaultSecProvACE())
964                     {
965                         ehRet = OC_EH_OK;
966                     }
967                     else
968                     {
969                         OIC_LOG(ERROR, TAG, "Failed to remove default ACL for security provisioning");
970                         ehRet = OC_EH_ERROR;
971                     }
972                 }
973                 else
974                 {
975                     OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
976                     ehRet = OC_EH_ERROR;
977                 }
978             }
979         }
980     }
981
982 exit:
983     if(OC_EH_OK != ehRet)
984     {
985
986         /*
987          * If some error is occured while ownership transfer,
988          * ownership transfer related resource should be revert back to initial status.
989         */
990         if(gDoxm)
991         {
992             if(!gDoxm->owned && previousMsgId != ehRequest->messageID)
993             {
994                 OIC_LOG(WARNING, TAG, "The operation failed during handle DOXM request,"\
995                                     "DOXM will be reverted.");
996                 RestoreDoxmToInitState();
997                 RestorePstatToInitState();
998             }
999         }
1000         else
1001         {
1002             OIC_LOG(ERROR, TAG, "Invalid DOXM resource.");
1003         }
1004     }
1005     else
1006     {
1007         previousMsgId = ehRequest->messageID;
1008     }
1009
1010     //Send payload to request originator
1011     ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1012                    OC_EH_OK : OC_EH_ERROR;
1013
1014     DeleteDoxmBinData(newDoxm);
1015
1016     return ehRet;
1017 }
1018
1019 OCEntityHandlerResult DoxmEntityHandler(OCEntityHandlerFlag flag,
1020                                         OCEntityHandlerRequest * ehRequest,
1021                                         void* callbackParam)
1022 {
1023     (void)callbackParam;
1024     OCEntityHandlerResult ehRet = OC_EH_ERROR;
1025
1026     if(NULL == ehRequest)
1027     {
1028         return ehRet;
1029     }
1030
1031     if (flag & OC_REQUEST_FLAG)
1032     {
1033         OIC_LOG(DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
1034
1035         switch (ehRequest->method)
1036         {
1037             case OC_REST_GET:
1038                 ehRet = HandleDoxmGetRequest(ehRequest);
1039                 break;
1040
1041             case OC_REST_POST:
1042                 ehRet = HandleDoxmPostRequest(ehRequest);
1043                 break;
1044
1045             default:
1046                 ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1047                                OC_EH_OK : OC_EH_ERROR;
1048                 break;
1049         }
1050     }
1051
1052     return ehRet;
1053 }
1054
1055 OCStackResult CreateDoxmResource()
1056 {
1057     OCStackResult ret = OCCreateResource(&gDoxmHandle,
1058                                          OIC_RSRC_TYPE_SEC_DOXM,
1059                                          OC_RSRVD_INTERFACE_DEFAULT,
1060                                          OIC_RSRC_DOXM_URI,
1061                                          DoxmEntityHandler,
1062                                          NULL,
1063                                          OC_SECURE |
1064                                          OC_DISCOVERABLE);
1065
1066     if (OC_STACK_OK != ret)
1067     {
1068         OIC_LOG (FATAL, TAG, "Unable to instantiate Doxm resource");
1069         DeInitDoxmResource();
1070     }
1071     return ret;
1072 }
1073
1074 /**
1075  * Checks if DeviceID is generated during provisioning for the new device.
1076  * If DeviceID is NULL then generates the new DeviceID.
1077  * Once DeviceID is assigned to the device it does not change for the lifetime of the device.
1078  */
1079 static OCStackResult CheckDeviceID()
1080 {
1081     OCStackResult ret = OC_STACK_ERROR;
1082     bool validId = false;
1083     for (uint8_t i = 0; i < UUID_LENGTH; i++)
1084     {
1085         if (gDoxm->deviceID.id[i] != 0)
1086         {
1087             validId = true;
1088             break;
1089         }
1090     }
1091
1092     if (!validId)
1093     {
1094         if (OCGenerateUuid(gDoxm->deviceID.id) != RAND_UUID_OK)
1095         {
1096             OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
1097             return ret;
1098         }
1099         ret = OC_STACK_OK;
1100
1101         if (!UpdatePersistentStorage(gDoxm))
1102         {
1103             //TODO: After registering PSI handler in all samples, do ret = OC_STACK_OK here.
1104             OIC_LOG(FATAL, TAG, "UpdatePersistentStorage failed!");
1105         }
1106     }
1107     else
1108     {
1109         ret = OC_STACK_OK;
1110     }
1111     return ret;
1112 }
1113
1114 /**
1115  * Get the default value.
1116  *
1117  * @return the default value of doxm, @ref OicSecDoxm_t.
1118  */
1119 static OicSecDoxm_t* GetDoxmDefault()
1120 {
1121     OIC_LOG(DEBUG, TAG, "GetDoxmToDefault");
1122     return &gDefaultDoxm;
1123 }
1124
1125 const OicSecDoxm_t* GetDoxmResourceData()
1126 {
1127     return gDoxm;
1128 }
1129
1130 OCStackResult InitDoxmResource()
1131 {
1132     OCStackResult ret = OC_STACK_ERROR;
1133
1134     //Read DOXM resource from PS
1135     uint8_t *data = NULL;
1136     size_t size = 0;
1137     ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_DOXM_NAME, &data, &size);
1138     // If database read failed
1139     if (OC_STACK_OK != ret)
1140     {
1141        OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
1142     }
1143     if (data)
1144     {
1145        // Read DOXM resource from PS
1146        ret = CBORPayloadToDoxm(data, size, &gDoxm);
1147     }
1148     /*
1149      * If SVR database in persistent storage got corrupted or
1150      * is not available for some reason, a default doxm is created
1151      * which allows user to initiate doxm provisioning again.
1152      */
1153      if ((OC_STACK_OK != ret) || !data || !gDoxm)
1154     {
1155         gDoxm = GetDoxmDefault();
1156     }
1157
1158     //In case of the server is shut down unintentionally, we should initialize the owner
1159     if(false == gDoxm->owned)
1160     {
1161         OicUuid_t emptyUuid = {.id={0}};
1162         memcpy(&gDoxm->owner, &emptyUuid, sizeof(OicUuid_t));
1163     }
1164
1165     ret = CheckDeviceID();
1166     if (ret == OC_STACK_OK)
1167     {
1168         OIC_LOG_V(DEBUG, TAG, "Initial Doxm Owned = %d", gDoxm->owned);
1169         //Instantiate 'oic.sec.doxm'
1170         ret = CreateDoxmResource();
1171     }
1172     else
1173     {
1174         OIC_LOG (ERROR, TAG, "CheckDeviceID failed");
1175     }
1176     OICFree(data);
1177     return ret;
1178 }
1179
1180 OCStackResult DeInitDoxmResource()
1181 {
1182     OCStackResult ret = OCDeleteResource(gDoxmHandle);
1183     if (gDoxm  != &gDefaultDoxm)
1184     {
1185         DeleteDoxmBinData(gDoxm);
1186     }
1187     gDoxm = NULL;
1188
1189     if (OC_STACK_OK == ret)
1190     {
1191         return OC_STACK_OK;
1192     }
1193     else
1194     {
1195         return OC_STACK_ERROR;
1196     }
1197 }
1198
1199 OCStackResult GetDoxmDeviceID(OicUuid_t *deviceID)
1200 {
1201     if (deviceID && gDoxm)
1202     {
1203        *deviceID = gDoxm->deviceID;
1204         return OC_STACK_OK;
1205     }
1206     return OC_STACK_ERROR;
1207 }
1208
1209 OCStackResult GetDoxmDevOwnerId(OicUuid_t *devownerid)
1210 {
1211     OCStackResult retVal = OC_STACK_ERROR;
1212     if (gDoxm)
1213     {
1214         OIC_LOG_V(DEBUG, TAG, "GetDoxmDevOwnerId(): gDoxm owned =  %d.", \
1215             gDoxm->owned);
1216         if (gDoxm->owned)
1217         {
1218             *devownerid = gDoxm->owner;
1219             retVal = OC_STACK_OK;
1220         }
1221     }
1222     return retVal;
1223 }
1224
1225 OCStackResult GetDoxmRownerId(OicUuid_t *rowneruuid)
1226 {
1227     OCStackResult retVal = OC_STACK_ERROR;
1228     if (gDoxm)
1229     {
1230         if( gDoxm->owned )
1231         {
1232             *rowneruuid = gDoxm->rownerID;
1233                     retVal = OC_STACK_OK;
1234         }
1235     }
1236     return retVal;
1237 }
1238
1239 /**
1240  * Function to restore doxm resurce to initial status.
1241  * This function will use in case of error while ownership transfer
1242  */
1243 void RestoreDoxmToInitState()
1244 {
1245     if(gDoxm)
1246     {
1247         OIC_LOG(INFO, TAG, "DOXM resource will revert back to initial status.");
1248
1249         OicUuid_t emptyUuid = {.id={0}};
1250         memcpy(&(gDoxm->owner), &emptyUuid, sizeof(OicUuid_t));
1251         gDoxm->owned = false;
1252         gDoxm->oxmSel = OIC_JUST_WORKS;
1253
1254         if(!UpdatePersistentStorage(gDoxm))
1255         {
1256             OIC_LOG(ERROR, TAG, "Failed to revert DOXM in persistent storage");
1257         }
1258     }
1259 }