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