[IOT-1089]Merge remote-tracking branch 'origin/master' into generic-java
[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 #ifdef __WITH_DTLS__
756                         ehRet = (CAEnableAnonECDHCipherSuite(true) == CA_STATUS_OK) ? OC_EH_OK : OC_EH_ERROR;
757 #endif //__WITH_DTLS__
758                         goto exit;
759                     }
760                     else
761                     {
762 #ifdef __WITH_DTLS__
763                         //Save the owner's UUID to derive owner credential
764                         memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
765
766                         // Update new state in persistent storage
767                         if (true == UpdatePersistentStorage(gDoxm))
768                         {
769                             ehRet = OC_EH_OK;
770                         }
771                         else
772                         {
773                             OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
774                             ehRet = OC_EH_ERROR;
775                         }
776
777                         /*
778                          * Disable anonymous ECDH cipher in tinyDTLS since device is now
779                          * in owned state.
780                          */
781                         CAResult_t caRes = CA_STATUS_OK;
782                         caRes = CAEnableAnonECDHCipherSuite(false);
783                         VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
784                         OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
785
786 #ifdef __WITH_X509__
787 #define TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 0xC0AE
788                         CASelectCipherSuite(TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8,
789                                             ehRequest->devAddr.adapter);
790 #endif //__WITH_X509__
791 #endif //__WITH_DTLS__
792                     }
793                 }
794                 else if (OIC_RANDOM_DEVICE_PIN == newDoxm->oxmSel)
795                 {
796                     /*
797                      * If current state of the device is un-owned, enable
798                      * anonymous ECDH cipher in tinyDTLS so that Provisioning
799                      * tool can initiate JUST_WORKS ownership transfer process.
800                      */
801                     if(memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
802                     {
803                         gDoxm->oxmSel = newDoxm->oxmSel;
804                         //Update new state in persistent storage
805                         if ((UpdatePersistentStorage(gDoxm) == true))
806                         {
807                             ehRet = OC_EH_OK;
808                         }
809                         else
810                         {
811                             OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
812                             ehRet = OC_EH_ERROR;
813                         }
814
815 #ifdef __WITH_DTLS__
816                         CAResult_t caRes = CA_STATUS_OK;
817
818                         caRes = CAEnableAnonECDHCipherSuite(false);
819                         VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
820                         OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
821
822                         caRes = CASelectCipherSuite(TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256,
823                                                     ehRequest->devAddr.adapter);
824                         VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
825
826                         char ranPin[OXM_RANDOM_PIN_SIZE + 1] = {0,};
827                          //TODO ehRequest->messageID for copa over TCP always is null. Find reason why.
828                         if(ehRequest->devAddr.adapter == OC_ADAPTER_IP && previousMsgId != ehRequest->messageID)
829                         {
830                             if(OC_STACK_OK == GeneratePin(ranPin, OXM_RANDOM_PIN_SIZE + 1))
831                             {
832                                 //Set the device id to derive temporal PSK
833                                 SetUuidForRandomPinOxm(&gDoxm->deviceID);
834
835                                 /**
836                                  * Since PSK will be used directly by DTLS layer while PIN based ownership transfer,
837                                  * Credential should not be saved into SVR.
838                                  * For this reason, use a temporary get_psk_info callback to random PIN OxM.
839                                  */
840                                 caRes = CARegisterDTLSCredentialsHandler(GetDtlsPskForRandomPinOxm);
841                                 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
842                                 ehRet = OC_EH_OK;
843                             }
844                             else
845                             {
846                                 OIC_LOG(ERROR, TAG, "Failed to generate random PIN");
847                                 ehRet = OC_EH_ERROR;
848                             }
849                         }
850                         else
851                         {
852                             if(OC_STACK_OK == GeneratePin(ranPin, OXM_RANDOM_PIN_SIZE + 1))
853                             {
854                                 //Set the device id to derive temporal PSK
855                                 SetUuidForRandomPinOxm(&gDoxm->deviceID);
856
857                                 /**
858                                  * Since PSK will be used directly by DTLS layer while PIN based ownership transfer,
859                                  * Credential should not be saved into SVR.
860                                  * For this reason, use a temporary get_psk_info callback to random PIN OxM.
861                                  */
862 #ifdef __WITH_TLS__
863                                 caRes = CAregisterTlsCredentialsHandler(GetDtlsPskForRandomPinOxm);
864 #endif
865                                 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
866                                 ehRet = OC_EH_OK;
867                             }
868                             else
869                             {
870                                 OIC_LOG(ERROR, TAG, "Failed to generate random PIN");
871                                 ehRet = OC_EH_ERROR;
872                             }
873
874                         }
875 #endif //__WITH_DTLS__
876                     }
877                     else
878                     {
879 #ifdef __WITH_DTLS__
880                         //Save the owner's UUID to derive owner credential
881                         memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
882
883                         //Update new state in persistent storage
884                         if (UpdatePersistentStorage(gDoxm) == true)
885                         {
886                             ehRet = OC_EH_OK;
887                         }
888                         else
889                         {
890                             OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
891                             ehRet = OC_EH_ERROR;
892                         }
893 #endif
894                     }
895                 }
896             }
897
898             /*
899              * When current state of the device is un-owned and Provisioning
900              * Tool is attempting to change the state to 'Owned' with a
901              * qualified value for the field 'Owner'
902              */
903             if ((false == gDoxm->owned) && (true == newDoxm->owned) &&
904                     (memcmp(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t)) == 0))
905             {
906                 //Change the SVR's resource owner as owner device.
907                 OCStackResult ownerRes = SetAclRownerId(&gDoxm->owner);
908                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
909                 {
910                     ehRet = OC_EH_ERROR;
911                     goto exit;
912                 }
913                 ownerRes = SetAmaclRownerId(&gDoxm->owner);
914                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
915                 {
916                     ehRet = OC_EH_ERROR;
917                     goto exit;
918                 }
919                 ownerRes = SetCredRownerId(&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 = SetPstatRownerId(&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 = SetDpairingRownerId(&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 = SetPconfRownerId(&gDoxm->owner);
938                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
939                 {
940                     ehRet = OC_EH_ERROR;
941                     goto exit;
942                 }
943
944                 gDoxm->owned = true;
945                 memcpy(&gDoxm->rownerID, &gDoxm->owner, sizeof(OicUuid_t));
946
947                 // Update new state in persistent storage
948                 if (UpdatePersistentStorage(gDoxm))
949                 {
950                     //Update default ACE of security resource to prevent anonymous user access.
951                     if(OC_STACK_OK == UpdateDefaultSecProvACE())
952                     {
953                         ehRet = OC_EH_OK;
954                     }
955                     else
956                     {
957                         OIC_LOG(ERROR, TAG, "Failed to remove default ACL for security provisioning");
958                         ehRet = OC_EH_ERROR;
959                     }
960                 }
961                 else
962                 {
963                     OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
964                     ehRet = OC_EH_ERROR;
965                 }
966             }
967         }
968     }
969
970 exit:
971     if(OC_EH_OK != ehRet)
972     {
973
974         /*
975          * If some error is occured while ownership transfer,
976          * ownership transfer related resource should be revert back to initial status.
977         */
978         if(gDoxm)
979         {
980             if(!gDoxm->owned && previousMsgId != ehRequest->messageID)
981             {
982                 OIC_LOG(WARNING, TAG, "The operation failed during handle DOXM request,"\
983                                     "DOXM will be reverted.");
984                 RestoreDoxmToInitState();
985                 RestorePstatToInitState();
986             }
987         }
988         else
989         {
990             OIC_LOG(ERROR, TAG, "Invalid DOXM resource.");
991         }
992     }
993     else
994     {
995         previousMsgId = ehRequest->messageID;
996     }
997
998     //Send payload to request originator
999     ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1000                    OC_EH_OK : OC_EH_ERROR;
1001
1002     DeleteDoxmBinData(newDoxm);
1003
1004     return ehRet;
1005 }
1006
1007 OCEntityHandlerResult DoxmEntityHandler(OCEntityHandlerFlag flag,
1008                                         OCEntityHandlerRequest * ehRequest,
1009                                         void* callbackParam)
1010 {
1011     (void)callbackParam;
1012     OCEntityHandlerResult ehRet = OC_EH_ERROR;
1013
1014     if(NULL == ehRequest)
1015     {
1016         return ehRet;
1017     }
1018
1019     if (flag & OC_REQUEST_FLAG)
1020     {
1021         OIC_LOG(DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
1022
1023         switch (ehRequest->method)
1024         {
1025             case OC_REST_GET:
1026                 ehRet = HandleDoxmGetRequest(ehRequest);
1027                 break;
1028
1029             case OC_REST_POST:
1030                 ehRet = HandleDoxmPostRequest(ehRequest);
1031                 break;
1032
1033             default:
1034                 ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1035                                OC_EH_OK : OC_EH_ERROR;
1036                 break;
1037         }
1038     }
1039
1040     return ehRet;
1041 }
1042
1043 OCStackResult CreateDoxmResource()
1044 {
1045     OCStackResult ret = OCCreateResource(&gDoxmHandle,
1046                                          OIC_RSRC_TYPE_SEC_DOXM,
1047                                          OC_RSRVD_INTERFACE_DEFAULT,
1048                                          OIC_RSRC_DOXM_URI,
1049                                          DoxmEntityHandler,
1050                                          NULL,
1051                                          OC_SECURE |
1052                                          OC_DISCOVERABLE);
1053
1054     if (OC_STACK_OK != ret)
1055     {
1056         OIC_LOG (FATAL, TAG, "Unable to instantiate Doxm resource");
1057         DeInitDoxmResource();
1058     }
1059     return ret;
1060 }
1061
1062 /**
1063  * Checks if DeviceID is generated during provisioning for the new device.
1064  * If DeviceID is NULL then generates the new DeviceID.
1065  * Once DeviceID is assigned to the device it does not change for the lifetime of the device.
1066  */
1067 static OCStackResult CheckDeviceID()
1068 {
1069     OCStackResult ret = OC_STACK_ERROR;
1070     bool validId = false;
1071     for (uint8_t i = 0; i < UUID_LENGTH; i++)
1072     {
1073         if (gDoxm->deviceID.id[i] != 0)
1074         {
1075             validId = true;
1076             break;
1077         }
1078     }
1079
1080     if (!validId)
1081     {
1082         if (OCGenerateUuid(gDoxm->deviceID.id) != RAND_UUID_OK)
1083         {
1084             OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
1085             return ret;
1086         }
1087         ret = OC_STACK_OK;
1088
1089         if (!UpdatePersistentStorage(gDoxm))
1090         {
1091             //TODO: After registering PSI handler in all samples, do ret = OC_STACK_OK here.
1092             OIC_LOG(FATAL, TAG, "UpdatePersistentStorage failed!");
1093         }
1094     }
1095     else
1096     {
1097         ret = OC_STACK_OK;
1098     }
1099     return ret;
1100 }
1101
1102 /**
1103  * Get the default value.
1104  *
1105  * @return the default value of doxm, @ref OicSecDoxm_t.
1106  */
1107 static OicSecDoxm_t* GetDoxmDefault()
1108 {
1109     OIC_LOG(DEBUG, TAG, "GetDoxmToDefault");
1110     return &gDefaultDoxm;
1111 }
1112
1113 const OicSecDoxm_t* GetDoxmResourceData()
1114 {
1115     return gDoxm;
1116 }
1117
1118 OCStackResult InitDoxmResource()
1119 {
1120     OCStackResult ret = OC_STACK_ERROR;
1121
1122     //Read DOXM resource from PS
1123     uint8_t *data = NULL;
1124     size_t size = 0;
1125     ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_DOXM_NAME, &data, &size);
1126     // If database read failed
1127     if (OC_STACK_OK != ret)
1128     {
1129        OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
1130     }
1131     if (data)
1132     {
1133        // Read DOXM resource from PS
1134        ret = CBORPayloadToDoxm(data, size, &gDoxm);
1135     }
1136     /*
1137      * If SVR database in persistent storage got corrupted or
1138      * is not available for some reason, a default doxm is created
1139      * which allows user to initiate doxm provisioning again.
1140      */
1141      if ((OC_STACK_OK != ret) || !data || !gDoxm)
1142     {
1143         gDoxm = GetDoxmDefault();
1144     }
1145
1146     //In case of the server is shut down unintentionally, we should initialize the owner
1147     if(false == gDoxm->owned)
1148     {
1149         OicUuid_t emptyUuid = {.id={0}};
1150         memcpy(&gDoxm->owner, &emptyUuid, sizeof(OicUuid_t));
1151     }
1152
1153     ret = CheckDeviceID();
1154     if (ret == OC_STACK_OK)
1155     {
1156         OIC_LOG_V(DEBUG, TAG, "Initial Doxm Owned = %d", gDoxm->owned);
1157         //Instantiate 'oic.sec.doxm'
1158         ret = CreateDoxmResource();
1159     }
1160     else
1161     {
1162         OIC_LOG (ERROR, TAG, "CheckDeviceID failed");
1163     }
1164     OICFree(data);
1165     return ret;
1166 }
1167
1168 OCStackResult DeInitDoxmResource()
1169 {
1170     OCStackResult ret = OCDeleteResource(gDoxmHandle);
1171     if (gDoxm  != &gDefaultDoxm)
1172     {
1173         DeleteDoxmBinData(gDoxm);
1174     }
1175     gDoxm = NULL;
1176
1177     if (OC_STACK_OK == ret)
1178     {
1179         return OC_STACK_OK;
1180     }
1181     else
1182     {
1183         return OC_STACK_ERROR;
1184     }
1185 }
1186
1187 OCStackResult GetDoxmDeviceID(OicUuid_t *deviceID)
1188 {
1189     if (deviceID && gDoxm)
1190     {
1191        *deviceID = gDoxm->deviceID;
1192         return OC_STACK_OK;
1193     }
1194     return OC_STACK_ERROR;
1195 }
1196
1197 OCStackResult SetDoxmDeviceID(const OicUuid_t *deviceID)
1198 {
1199     bool isPT = false;
1200
1201     if(NULL == deviceID)
1202     {
1203         return OC_STACK_INVALID_PARAM;
1204     }
1205     if(NULL == gDoxm)
1206     {
1207         OIC_LOG(ERROR, TAG, "Doxm resource is not initialized.");
1208         return OC_STACK_NO_RESOURCE;
1209     }
1210
1211     //Check the device's OTM state
1212
1213 #ifdef __WITH_DTLS__}
1214     //for normal device.
1215     if(true == gDoxm->owned)
1216     {
1217         OIC_LOG(ERROR, TAG, "This device owned by owner's device.");
1218         OIC_LOG(ERROR, TAG, "Device UUID cannot be changed to guarantee the reliability of the connection.");
1219         return OC_STACK_ERROR;
1220     }
1221 #endif //__WITH_DTLS
1222
1223     //Save the previous UUID
1224     OicUuid_t tempUuid;
1225     memcpy(tempUuid.id, gDoxm->deviceID.id, sizeof(tempUuid.id));
1226
1227     //Change the UUID
1228     memcpy(gDoxm->deviceID.id, deviceID->id, sizeof(deviceID->id));
1229     if(isPT)
1230     {
1231         memcpy(gDoxm->owner.id, deviceID->id, sizeof(deviceID->id));
1232         memcpy(gDoxm->rownerID.id, deviceID->id, sizeof(deviceID->id));
1233     }
1234
1235     //Update PS
1236     if(!UpdatePersistentStorage(gDoxm))
1237     {
1238         //revert UUID in case of update error
1239         memcpy(gDoxm->deviceID.id, tempUuid.id, sizeof(tempUuid.id));
1240         if(isPT)
1241         {
1242             memcpy(gDoxm->owner.id, tempUuid.id, sizeof(tempUuid.id));
1243             memcpy(gDoxm->rownerID.id, tempUuid.id, sizeof(tempUuid.id));
1244         }
1245
1246         OIC_LOG(ERROR, TAG, "Failed to update persistent storage");
1247         return OC_STACK_ERROR;
1248     }
1249     return OC_STACK_OK;
1250 }
1251
1252 OCStackResult GetDoxmDevOwnerId(OicUuid_t *devownerid)
1253 {
1254     OCStackResult retVal = OC_STACK_ERROR;
1255     if (gDoxm)
1256     {
1257         OIC_LOG_V(DEBUG, TAG, "GetDoxmDevOwnerId(): gDoxm owned =  %d.", \
1258             gDoxm->owned);
1259         if (gDoxm->owned)
1260         {
1261             *devownerid = gDoxm->owner;
1262             retVal = OC_STACK_OK;
1263         }
1264     }
1265     return retVal;
1266 }
1267
1268 OCStackResult GetDoxmRownerId(OicUuid_t *rowneruuid)
1269 {
1270     OCStackResult retVal = OC_STACK_ERROR;
1271     if (gDoxm)
1272     {
1273         if( gDoxm->owned )
1274         {
1275             *rowneruuid = gDoxm->rownerID;
1276                     retVal = OC_STACK_OK;
1277         }
1278     }
1279     return retVal;
1280 }
1281
1282 /**
1283  * Function to restore doxm resurce to initial status.
1284  * This function will use in case of error while ownership transfer
1285  */
1286 void RestoreDoxmToInitState()
1287 {
1288     if(gDoxm)
1289     {
1290         OIC_LOG(INFO, TAG, "DOXM resource will revert back to initial status.");
1291
1292         OicUuid_t emptyUuid = {.id={0}};
1293         memcpy(&(gDoxm->owner), &emptyUuid, sizeof(OicUuid_t));
1294         gDoxm->owned = false;
1295         gDoxm->oxmSel = OIC_JUST_WORKS;
1296
1297         if(!UpdatePersistentStorage(gDoxm))
1298         {
1299             OIC_LOG(ERROR, TAG, "Failed to revert DOXM in persistent storage");
1300         }
1301     }
1302 }