Fix the messageID handling issue in SVR's request handler.
[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 "ocpayloadcbor.h"
39 #include "cainterface.h"
40 #include "ocserverrequest.h"
41 #include "resourcemanager.h"
42 #include "doxmresource.h"
43 #include "pstatresource.h"
44 #include "aclresource.h"
45 #include "amaclresource.h"
46 #include "pconfresource.h"
47 #include "dpairingresource.h"
48 #include "psinterface.h"
49 #include "srmresourcestrings.h"
50 #include "securevirtualresourcetypes.h"
51 #include "credresource.h"
52 #include "srmutility.h"
53 #include "pinoxmcommon.h"
54 #include "oxmverifycommon.h"
55
56 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
57 #include "pkix_interface.h"
58 #endif
59
60 #define TAG  "OIC_SRM_DOXM"
61 #define CHAR_ZERO ('0')
62
63 /** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
64  * The value of payload size is increased until reaching belox max cbor size. */
65 static const uint16_t CBOR_SIZE = 512;
66
67 /** Max cbor size payload. */
68 static const uint16_t CBOR_MAX_SIZE = 4400;
69
70 static OicSecDoxm_t        *gDoxm = NULL;
71 static OCResourceHandle    gDoxmHandle = NULL;
72
73 static OicSecOxm_t gOicSecDoxmJustWorks = OIC_JUST_WORKS;
74 static OicSecDoxm_t gDefaultDoxm =
75 {
76     NULL,                   /* OicUrn_t *oxmType */
77     0,                      /* size_t oxmTypeLen */
78     &gOicSecDoxmJustWorks,  /* uint16_t *oxm */
79     1,                      /* size_t oxmLen */
80     OIC_JUST_WORKS,         /* uint16_t oxmSel */
81     SYMMETRIC_PAIR_WISE_KEY,/* OicSecCredType_t sct */
82     false,                  /* bool owned */
83     {.id = {0}},            /* OicUuid_t deviceID */
84     false,                  /* bool dpc */
85     {.id = {0}},            /* OicUuid_t owner */
86 #ifdef MULTIPLE_OWNER
87     NULL,                   /* OicSecSubOwner_t sub-owner list */
88     NULL,                   /* OicSecMomType_t multiple owner mode */
89 #endif //MULTIPLE_OWNER
90     {.id = {0}},            /* OicUuid_t rownerID */
91 };
92
93 /**
94  * This method is internal method.
95  * the param roParsed is optionally used to know whether cborPayload has
96  * at least read only property value or not.
97  */
98 static OCStackResult CBORPayloadToDoxmBin(const uint8_t *cborPayload, size_t size,
99                                 OicSecDoxm_t **doxm, bool *roParsed);
100
101 void DeleteDoxmBinData(OicSecDoxm_t* doxm)
102 {
103     if (doxm)
104     {
105         //Clean oxmType
106         for (size_t i = 0; i < doxm->oxmTypeLen; i++)
107         {
108             OICFree(doxm->oxmType[i]);
109         }
110         OICFree(doxm->oxmType);
111
112         //clean oxm
113         OICFree(doxm->oxm);
114
115 #ifdef MULTIPLE_OWNER
116         //clean mom
117         OICFree(doxm->mom);
118
119         //clean sub-owner list
120         if(NULL != doxm->subOwners)
121         {
122             OicSecSubOwner_t* subowner = NULL;
123             OicSecSubOwner_t* temp = NULL;
124             LL_FOREACH_SAFE(doxm->subOwners, subowner, temp)
125             {
126                 LL_DELETE(doxm->subOwners, subowner);
127                 OICFree(subowner);
128             }
129         }
130 #endif //MULTIPLE_OWNER
131
132         //Clean doxm itself
133         OICFree(doxm);
134     }
135 }
136
137 OCStackResult DoxmToCBORPayload(const OicSecDoxm_t *doxm, uint8_t **payload, size_t *size,
138                                 bool rwOnly)
139 {
140     if (NULL == doxm || NULL == payload || NULL != *payload || NULL == size)
141     {
142         return OC_STACK_INVALID_PARAM;
143     }
144     size_t cborLen = *size;
145     if (0 == cborLen)
146     {
147         cborLen = CBOR_SIZE;
148     }
149     *payload = NULL;
150     *size = 0;
151
152     OCStackResult ret = OC_STACK_ERROR;
153
154     CborEncoder encoder;
155     CborEncoder doxmMap;
156     char* strUuid = NULL;
157
158     int64_t cborEncoderResult = CborNoError;
159
160     uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
161     VERIFY_NON_NULL(TAG, outPayload, ERROR);
162     cbor_encoder_init(&encoder, outPayload, cborLen, 0);
163
164     cborEncoderResult = cbor_encoder_create_map(&encoder, &doxmMap, CborIndefiniteLength);
165     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Doxm Map.");
166
167     //OxmType -- Not Mandatory
168     if (doxm->oxmTypeLen > 0)
169     {
170         CborEncoder oxmType;
171         cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_TYPE_NAME,
172             strlen(OIC_JSON_OXM_TYPE_NAME));
173         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Tag.");
174         cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxmType, doxm->oxmTypeLen);
175         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Array.");
176
177         for (size_t i = 0; i < doxm->oxmTypeLen; i++)
178         {
179             cborEncoderResult = cbor_encode_text_string(&oxmType, doxm->oxmType[i],
180                 strlen(doxm->oxmType[i]));
181             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Value.");
182         }
183         cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxmType);
184         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmType.");
185     }
186
187     //Oxm -- Not Mandatory
188     if (doxm->oxmLen > 0 && false == rwOnly)
189     {
190         CborEncoder oxm;
191         cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXMS_NAME,
192             strlen(OIC_JSON_OXMS_NAME));
193         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Tag.");
194         cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxm, doxm->oxmLen);
195         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Array.");
196
197         for (size_t i = 0; i < doxm->oxmLen; i++)
198         {
199             cborEncoderResult = cbor_encode_int(&oxm, doxm->oxm[i]);
200             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Value");
201         }
202         cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxm);
203         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmName.");
204     }
205
206     //OxmSel -- Mandatory
207     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_SEL_NAME,
208         strlen(OIC_JSON_OXM_SEL_NAME));
209     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Tag.");
210     cborEncoderResult = cbor_encode_int(&doxmMap, doxm->oxmSel);
211     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Value.");
212
213     //sct -- Mandatory
214     if (false == rwOnly)
215     {
216         cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_SUPPORTED_CRED_TYPE_NAME,
217             strlen(OIC_JSON_SUPPORTED_CRED_TYPE_NAME));
218         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Tag");
219         cborEncoderResult = cbor_encode_int(&doxmMap, doxm->sct);
220         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Value.");
221     }
222
223     //Owned -- Mandatory
224     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OWNED_NAME,
225         strlen(OIC_JSON_OWNED_NAME));
226     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Tag.");
227     cborEncoderResult = cbor_encode_boolean(&doxmMap, doxm->owned);
228     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Value.");
229
230     if (false == rwOnly)
231     {
232         //DeviceId -- Mandatory
233         cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVICE_ID_NAME,
234             strlen(OIC_JSON_DEVICE_ID_NAME));
235         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Tag.");
236         ret = ConvertUuidToStr(&doxm->deviceID, &strUuid);
237         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
238         cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
239         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Value.");
240         OICFree(strUuid);
241         strUuid = NULL;
242     }
243
244 #ifdef MULTIPLE_OWNER
245     //Device SubOwnerID -- Not Mandatory
246     if(doxm->subOwners)
247     {
248         size_t subOwnerLen = 0;
249         OicSecSubOwner_t* subOwner = NULL;
250         LL_FOREACH(doxm->subOwners, subOwner)
251         {
252             subOwnerLen++;
253         }
254
255         CborEncoder subOwners;
256         cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_SUBOWNERID_NAME,
257             strlen(OIC_JSON_SUBOWNERID_NAME));
258         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SubOwnerId Tag.");
259         cborEncoderResult = cbor_encoder_create_array(&doxmMap, &subOwners, subOwnerLen);
260         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SubOwner Array.");
261
262         subOwner = NULL;
263         LL_FOREACH(doxm->subOwners, subOwner)
264         {
265             char* strUuid = NULL;
266             ret = ConvertUuidToStr(&subOwner->uuid, &strUuid);
267             VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
268             cborEncoderResult = cbor_encode_text_string(&subOwners, strUuid, strlen(strUuid));
269             OICFree(strUuid);
270             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SubOwnerId Value");
271         }
272         cborEncoderResult = cbor_encoder_close_container(&doxmMap, &subOwners);
273         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing SubOwnerId.");
274     }
275
276     //Multiple Owner Mode -- Not Mandatory
277     if(doxm->mom)
278     {
279         cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_MOM_NAME,
280             strlen(OIC_JSON_MOM_NAME));
281         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding mom Tag");
282         cborEncoderResult = cbor_encode_int(&doxmMap, (int64_t)doxm->mom->mode);
283         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding mom Value.");
284     }
285 #endif //MULTIPLE_OWNER
286
287     //devownerid -- Mandatory
288     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVOWNERID_NAME,
289         strlen(OIC_JSON_DEVOWNERID_NAME));
290     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Id Tag.");
291     ret = ConvertUuidToStr(&doxm->owner, &strUuid);
292     VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
293     cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
294     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Id Value.");
295     OICFree(strUuid);
296     strUuid = NULL;
297
298     //ROwner -- Mandatory
299     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_ROWNERID_NAME,
300         strlen(OIC_JSON_ROWNERID_NAME));
301     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Tag.");
302     ret = ConvertUuidToStr(&doxm->rownerID, &strUuid);
303     VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
304     cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
305     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Value.");
306     OICFree(strUuid);
307     strUuid = NULL;
308
309     //RT -- Mandatory
310     CborEncoder rtArray;
311     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_RT_NAME,
312             strlen(OIC_JSON_RT_NAME));
313     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Name Tag.");
314     cborEncoderResult = cbor_encoder_create_array(&doxmMap, &rtArray, 1);
315     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Value.");
316     for (size_t i = 0; i < 1; i++)
317     {
318         cborEncoderResult = cbor_encode_text_string(&rtArray, OIC_RSRC_TYPE_SEC_DOXM,
319                 strlen(OIC_RSRC_TYPE_SEC_DOXM));
320         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding RT Value.");
321     }
322     cborEncoderResult = cbor_encoder_close_container(&doxmMap, &rtArray);
323     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing RT.");
324
325     //IF-- Mandatory
326      CborEncoder ifArray;
327      cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_IF_NAME,
328              strlen(OIC_JSON_IF_NAME));
329      VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Name Tag.");
330      cborEncoderResult = cbor_encoder_create_array(&doxmMap, &ifArray, 1);
331      VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Value.");
332     for (size_t i = 0; i < 1; i++)
333     {
334         cborEncoderResult = cbor_encode_text_string(&ifArray, OC_RSRVD_INTERFACE_DEFAULT,
335                 strlen(OC_RSRVD_INTERFACE_DEFAULT));
336         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding IF Value.");
337     }
338     cborEncoderResult = cbor_encoder_close_container(&doxmMap, &ifArray);
339     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing IF.");
340
341     cborEncoderResult = cbor_encoder_close_container(&encoder, &doxmMap);
342     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing DoxmMap.");
343
344     if (CborNoError == cborEncoderResult)
345     {
346         *size = cbor_encoder_get_buffer_size(&encoder, outPayload);
347         *payload = outPayload;
348         ret = OC_STACK_OK;
349     }
350 exit:
351     if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
352     {
353         OIC_LOG(DEBUG, TAG, "Memory getting reallocated.");
354         // reallocate and try again!
355         OICFree(outPayload);
356         // Since the allocated initial memory failed, double the memory.
357         cborLen += cbor_encoder_get_buffer_size(&encoder, encoder.end);
358         OIC_LOG_V(DEBUG, TAG, "Doxm reallocation size : %zd.", cborLen);
359         cborEncoderResult = CborNoError;
360         ret = DoxmToCBORPayload(doxm, payload, &cborLen, rwOnly);
361         *size = cborLen;
362     }
363
364     if ((CborNoError != cborEncoderResult) || (OC_STACK_OK != ret))
365     {
366        OICFree(outPayload);
367        outPayload = NULL;
368        *payload = NULL;
369        *size = 0;
370        ret = OC_STACK_ERROR;
371     }
372
373     return ret;
374 }
375
376 OCStackResult CBORPayloadToDoxm(const uint8_t *cborPayload, size_t size,
377                                 OicSecDoxm_t **secDoxm)
378 {
379     return CBORPayloadToDoxmBin(cborPayload, size, secDoxm, NULL);
380 }
381
382 static OCStackResult CBORPayloadToDoxmBin(const uint8_t *cborPayload, size_t size,
383                                 OicSecDoxm_t **secDoxm, bool *roParsed)
384 {
385     if (NULL == cborPayload || NULL == secDoxm || NULL != *secDoxm || 0 == size)
386     {
387         return OC_STACK_INVALID_PARAM;
388     }
389
390     OCStackResult ret = OC_STACK_ERROR;
391     *secDoxm = NULL;
392
393     CborParser parser;
394     CborError cborFindResult = CborNoError;
395     char* strUuid = NULL;
396     size_t len = 0;
397     CborValue doxmCbor;
398
399     cbor_parser_init(cborPayload, size, 0, &parser, &doxmCbor);
400     CborValue doxmMap;
401     OicSecDoxm_t *doxm = (OicSecDoxm_t *)OICCalloc(1, sizeof(*doxm));
402     VERIFY_NON_NULL(TAG, doxm, ERROR);
403
404     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_TYPE_NAME, &doxmMap);
405     //OxmType -- not Mandatory
406     if (CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
407     {
408         CborValue oxmType;
409
410         cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmTypeLen);
411         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmTypeLen.");
412         VERIFY_SUCCESS(TAG, doxm->oxmTypeLen != 0, ERROR);
413
414         doxm->oxmType = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(*doxm->oxmType));
415         VERIFY_NON_NULL(TAG, doxm->oxmType, ERROR);
416
417         cborFindResult = cbor_value_enter_container(&doxmMap, &oxmType);
418         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmType Array.")
419
420         int i = 0;
421         size_t len = 0;
422         while (cbor_value_is_valid(&oxmType) && cbor_value_is_text_string(&oxmType))
423         {
424             cborFindResult = cbor_value_dup_text_string(&oxmType, &doxm->oxmType[i++],
425                                                         &len, NULL);
426             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding omxType text string.");
427             cborFindResult = cbor_value_advance(&oxmType);
428             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmType.");
429         }
430     }
431
432     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXMS_NAME, &doxmMap);
433     //Oxm -- not Mandatory
434     if (CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
435     {
436         CborValue oxm;
437         cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmLen);
438         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName array Length.");
439         VERIFY_SUCCESS(TAG, doxm->oxmLen != 0, ERROR);
440
441         doxm->oxm = (OicSecOxm_t *)OICCalloc(doxm->oxmLen, sizeof(*doxm->oxm));
442         VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
443
444         cborFindResult = cbor_value_enter_container(&doxmMap, &oxm);
445         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmName Array.")
446
447         int i = 0;
448         while (cbor_value_is_valid(&oxm) && cbor_value_is_integer(&oxm))
449         {
450             int tmp;
451
452             cborFindResult = cbor_value_get_int(&oxm, &tmp);
453             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName Value")
454             doxm->oxm[i++] = (OicSecOxm_t)tmp;
455             cborFindResult = cbor_value_advance(&oxm);
456             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmName.")
457         }
458
459         if (roParsed)
460         {
461             *roParsed = true;
462         }
463     }
464     else
465     {
466         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
467         doxm->oxm = (OicSecOxm_t *) OICCalloc(gDoxm->oxmLen, sizeof(*doxm->oxm));
468         VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
469         doxm->oxmLen = gDoxm->oxmLen;
470         for (size_t i = 0; i < gDoxm->oxmLen; i++)
471         {
472             doxm->oxm[i] = gDoxm->oxm[i];
473         }
474     }
475
476     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_SEL_NAME, &doxmMap);
477     if (CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
478     {
479         int oxmSel;
480
481         cborFindResult = cbor_value_get_int(&doxmMap, &oxmSel);
482         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sel Name Value.")
483         doxm->oxmSel = (OicSecOxm_t)oxmSel;
484     }
485     else // PUT/POST JSON may not have oxmsel so set it to the gDoxm->oxmSel
486     {
487         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
488         doxm->oxmSel = gDoxm->oxmSel;
489     }
490
491     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_SUPPORTED_CRED_TYPE_NAME, &doxmMap);
492     if (CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
493     {
494         int sct;
495
496         cborFindResult = cbor_value_get_int(&doxmMap, &sct);
497         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sct Name Value.")
498         doxm->sct = (OicSecCredType_t)sct;
499
500         if (roParsed)
501         {
502             *roParsed = true;
503         }
504     }
505     else // PUT/POST JSON may not have sct so set it to the gDoxm->sct
506     {
507         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
508         doxm->sct = gDoxm->sct;
509     }
510
511     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OWNED_NAME, &doxmMap);
512     if (CborNoError == cborFindResult && cbor_value_is_boolean(&doxmMap))
513     {
514         cborFindResult = cbor_value_get_boolean(&doxmMap, &doxm->owned);
515         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owned Value.")
516     }
517     else // PUT/POST JSON may not have owned so set it to the gDomx->owned
518     {
519         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
520         doxm->owned = gDoxm->owned;
521     }
522
523     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVICE_ID_NAME, &doxmMap);
524     if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
525     {
526         cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
527         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Device Id Value.");
528         ret = ConvertStrToUuid(strUuid , &doxm->deviceID);
529         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
530         OICFree(strUuid);
531         strUuid  = NULL;
532     }
533     else
534     {
535         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
536         memcpy(doxm->deviceID.id, &gDoxm->deviceID.id, sizeof(doxm->deviceID.id));
537     }
538
539     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVOWNERID_NAME, &doxmMap);
540     if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
541     {
542         cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
543         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owner Value.");
544         ret = ConvertStrToUuid(strUuid , &doxm->owner);
545         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
546         OICFree(strUuid);
547         strUuid  = NULL;
548     }
549     else
550     {
551         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
552         memcpy(doxm->owner.id, gDoxm->owner.id, sizeof(doxm->owner.id));
553     }
554
555 #ifdef MULTIPLE_OWNER
556     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_MOM_NAME, &doxmMap);
557     if(CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
558     {
559         int mode = 0;
560         cborFindResult = cbor_value_get_int(&doxmMap, &mode);
561         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding mom Name Value.")
562         if(NULL == doxm->mom)
563         {
564             doxm->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
565             VERIFY_NON_NULL(TAG, doxm->mom, ERROR);
566         }
567         doxm->mom->mode = (OicSecMomType_t)mode;
568     }
569     else if(NULL != gDoxm && NULL != gDoxm->mom)
570     {
571         // PUT/POST JSON may not have 'mom' so set it to the gDomx->mom
572         if(NULL == doxm->mom)
573         {
574             doxm->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
575             VERIFY_NON_NULL(TAG, doxm->mom, ERROR);
576         }
577         doxm->mom->mode = gDoxm->mom->mode;
578     }
579
580     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_SUBOWNERID_NAME, &doxmMap);
581     if(CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
582     {
583         size_t subOwnerLen = 0;
584         CborValue subOwnerCbor;
585         cborFindResult = cbor_value_get_array_length(&doxmMap, &subOwnerLen);
586         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SubOwner array Length.");
587         VERIFY_SUCCESS(TAG, 0 != subOwnerLen, ERROR);
588
589         cborFindResult = cbor_value_enter_container(&doxmMap, &subOwnerCbor);
590         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering SubOwner Array.")
591
592         while (cbor_value_is_valid(&subOwnerCbor) && cbor_value_is_text_string(&subOwnerCbor))
593         {
594             OCStackResult convertRes = OC_STACK_ERROR;
595             OicSecSubOwner_t* subOwner = NULL;
596             char* strUuid = NULL;
597             size_t uuidLen = 0;
598
599             cborFindResult = cbor_value_dup_text_string(&subOwnerCbor, &strUuid, &uuidLen, NULL);
600             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SubOwnerId Value");
601
602             subOwner = (OicSecSubOwner_t*)OICCalloc(1, sizeof(OicSecSubOwner_t));
603             VERIFY_NON_NULL(TAG, subOwner, ERROR);
604
605             convertRes = ConvertStrToUuid(strUuid, &subOwner->uuid);
606             VERIFY_SUCCESS(TAG, OC_STACK_OK == convertRes, ERROR);
607             subOwner->status = MOT_STATUS_DONE;
608             LL_APPEND(doxm->subOwners, subOwner);
609
610             cborFindResult = cbor_value_advance(&subOwnerCbor);
611             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing SubOwnerId.")
612         }
613     }
614     else if(NULL != gDoxm && NULL != gDoxm->subOwners)
615     {
616         // PUT/POST JSON may not have 'subOwners' so set it to the gDomx->subOwners
617         OicSecSubOwner_t* subOwnerItor = NULL;
618         LL_FOREACH(gDoxm->subOwners, subOwnerItor)
619         {
620             OicSecSubOwner_t* subOwnerId = (OicSecSubOwner_t*)OICCalloc(1, sizeof(OicSecSubOwner_t));
621             VERIFY_NON_NULL(TAG, subOwnerId, ERROR);
622
623             memcpy(&subOwnerId->uuid, &subOwnerItor->uuid, sizeof(OicUuid_t));
624             subOwnerId->status = MOT_STATUS_DONE;
625
626             LL_APPEND(doxm->subOwners, subOwnerId);
627         }
628     }
629 #endif //MULTIPLE_OWNER
630
631     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_ROWNERID_NAME, &doxmMap);
632     if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
633     {
634         cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
635         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding ROwner Value.");
636         ret = ConvertStrToUuid(strUuid , &doxm->rownerID);
637         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
638         OICFree(strUuid);
639         strUuid  = NULL;
640     }
641     else
642     {
643         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
644         memcpy(doxm->rownerID.id, gDoxm->rownerID.id, sizeof(doxm->rownerID.id));
645     }
646
647     *secDoxm = doxm;
648     ret = OC_STACK_OK;
649
650 exit:
651     if (CborNoError != cborFindResult)
652     {
653         OIC_LOG (ERROR, TAG, "CBORPayloadToDoxm failed!!!");
654         DeleteDoxmBinData(doxm);
655         doxm = NULL;
656         *secDoxm = NULL;
657         ret = OC_STACK_ERROR;
658     }
659     return ret;
660 }
661
662 /**
663  * @todo document this function including why code might need to call this.
664  * The current suspicion is that it's not being called as much as it should.
665  */
666 static bool UpdatePersistentStorage(OicSecDoxm_t * doxm)
667 {
668     bool bRet = false;
669
670     if (NULL != doxm)
671     {
672         // Convert Doxm data into CBOR for update to persistent storage
673         uint8_t *payload = NULL;
674         size_t size = 0;
675         OCStackResult res = DoxmToCBORPayload(doxm, &payload, &size, false);
676         if (payload && (OC_STACK_OK == res)
677             && (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, payload, size)))
678         {
679                 bRet = true;
680         }
681         OICFree(payload);
682     }
683     else
684     {
685         if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, NULL, 0))
686         {
687                 bRet = true;
688         }
689     }
690
691     return bRet;
692 }
693
694 static bool ValidateQuery(const char * query)
695 {
696     // Send doxm resource data if the state of doxm resource
697     // matches with the query parameters.
698     // else send doxm resource data as NULL
699     // TODO Remove this check and rely on Policy Engine
700     // and Provisioning Mode to enforce provisioning-state
701     // access rules. Eventually, the PE and PM code will
702     // not send a request to the /doxm Entity Handler at all
703     // if it should not respond.
704     OIC_LOG (DEBUG, TAG, "In ValidateQuery");
705     if(NULL == gDoxm)
706     {
707         return false;
708     }
709
710     bool bOwnedQry = false;         // does querystring contains 'owned' query ?
711     bool bOwnedMatch = false;       // does 'owned' query value matches with doxm.owned status?
712     bool bDeviceIDQry = false;      // does querystring contains 'deviceid' query ?
713     bool bDeviceIDMatch = false;    // does 'deviceid' query matches with doxm.deviceid ?
714     bool bInterfaceQry = false;      // does querystring contains 'if' query ?
715     bool bInterfaceMatch = false;    // does 'if' query matches with oic.if.baseline ?
716 #ifdef MULTIPLE_OWNER
717     bool bMotQry = false;         // does querystring contains 'mom' and 'owned' query ?
718     bool bMotMatch = false;       // does 'mom' query value is not '0' && does query value matches with doxm.owned status?
719 #endif //MULTIPLE_OWNER
720
721     OicParseQueryIter_t parseIter = {.attrPos = NULL};
722
723     ParseQueryIterInit((unsigned char*)query, &parseIter);
724
725     while (GetNextQuery(&parseIter))
726     {
727         if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
728         {
729             bOwnedQry = true;
730             if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
731                     (gDoxm->owned))
732             {
733                 bOwnedMatch = true;
734             }
735             else if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_FALSE, parseIter.valLen) == 0)
736                     && (!gDoxm->owned))
737             {
738                 bOwnedMatch = true;
739             }
740         }
741
742 #ifdef MULTIPLE_OWNER
743         if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_MOM_NAME, strlen(OIC_JSON_MOM_NAME)) == 0)
744         {
745             bMotQry = true;
746             OicSecMomType_t momMode = (OicSecMomType_t)(parseIter.valPos[0] - CHAR_ZERO);
747             if(NULL != gDoxm->mom && momMode != gDoxm->mom->mode)
748             {
749                 if(GetNextQuery(&parseIter))
750                 {
751                     if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
752                     {
753                         if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
754                                 (gDoxm->owned))
755                         {
756                             bMotMatch = true;
757                         }
758                     }
759                 }
760             }
761             return bMotMatch;
762         }
763 #endif //MULTIPLE_OWNER
764
765         if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_DEVICE_ID_NAME, parseIter.attrLen) == 0)
766         {
767             bDeviceIDQry = true;
768             OicUuid_t subject = {.id={0}};
769
770             memcpy(subject.id, parseIter.valPos, parseIter.valLen);
771             if (0 == memcmp(&gDoxm->deviceID.id, &subject.id, sizeof(gDoxm->deviceID.id)))
772             {
773                 bDeviceIDMatch = true;
774             }
775         }
776
777         if (strncasecmp((char *)parseIter.attrPos, OC_RSRVD_INTERFACE, parseIter.attrLen) == 0)
778         {
779             bInterfaceQry = true;
780             if ((strncasecmp((char *)parseIter.valPos, OC_RSRVD_INTERFACE_DEFAULT, parseIter.valLen) == 0))
781             {
782                 bInterfaceMatch = true;
783             }
784             return (bInterfaceQry ? bInterfaceMatch: true);
785         }
786     }
787
788 #ifdef MULTIPLE_OWNER
789     return ((bOwnedQry ? bOwnedMatch : true) &&
790             (bDeviceIDQry ? bDeviceIDMatch : true) &&
791             (bMotQry ? bMotMatch : true));
792 #else
793     return ((bOwnedQry ? bOwnedMatch : true) &&
794             (bDeviceIDQry ? bDeviceIDMatch : true));
795 #endif //MULTIPLE_OWNER
796 }
797
798 static OCEntityHandlerResult HandleDoxmGetRequest (const OCEntityHandlerRequest * ehRequest)
799 {
800     OCEntityHandlerResult ehRet = OC_EH_OK;
801
802     OIC_LOG(DEBUG, TAG, "Doxm EntityHandle processing GET request");
803
804     //Checking if Get request is a query.
805     if (ehRequest->query)
806     {
807         OIC_LOG_V(DEBUG,TAG,"query:%s",ehRequest->query);
808         OIC_LOG(DEBUG, TAG, "HandleDoxmGetRequest processing query");
809         if (!ValidateQuery(ehRequest->query))
810         {
811             ehRet = OC_EH_ERROR;
812         }
813     }
814
815     /*
816      * For GET or Valid Query request return doxm resource CBOR payload.
817      * For non-valid query return NULL json payload.
818      * A device will 'always' have a default Doxm, so DoxmToCBORPayload will
819      * return valid doxm resource json.
820      */
821     uint8_t *payload = NULL;
822     size_t size = 0;
823
824     if (ehRet == OC_EH_OK)
825     {
826         if (OC_STACK_OK != DoxmToCBORPayload(gDoxm, &payload, &size, false))
827         {
828             OIC_LOG(WARNING, TAG, "DoxmToCBORPayload failed in HandleDoxmGetRequest");
829         }
830     }
831
832     OIC_LOG(DEBUG, TAG, "Send payload for doxm GET request");
833     OIC_LOG_BUFFER(DEBUG, TAG, payload, size);
834
835     // Send response payload to request originator
836     ehRet = ((SendSRMResponse(ehRequest, ehRet, payload, size)) == OC_STACK_OK) ?
837                    OC_EH_OK : OC_EH_ERROR;
838
839     OICFree(payload);
840
841     return ehRet;
842 }
843
844 static void updateWriteableProperty(const OicSecDoxm_t* src, OicSecDoxm_t* dst)
845 {
846     if(src && dst)
847    {
848         // update oxmsel
849         dst->oxmSel = src->oxmSel;
850
851         //update owner
852         memcpy(&(dst->owner), &(src->owner), sizeof(OicUuid_t));
853
854         //update rowner
855         memcpy(&(dst->rownerID), &(src->rownerID), sizeof(OicUuid_t));
856
857         //update deviceuuid
858         memcpy(&(dst->deviceID), &(src->deviceID), sizeof(OicUuid_t));
859
860         //Update owned status
861         if(dst->owned != src->owned)
862         {
863             dst->owned = src->owned;
864         }
865
866 #ifdef MULTIPLE_OWNER
867         if(src->mom)
868         {
869             OIC_LOG(DEBUG, TAG, "dectected 'mom' property");
870             if(NULL == dst->mom)
871             {
872                 dst->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
873                 if(NULL != dst->mom)
874                 {
875                     dst->mom->mode = src->mom->mode;
876                 }
877             }
878         }
879 #endif //MULTIPLE_OWNER
880     }
881 }
882
883 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
884 #ifdef MULTIPLE_OWNER
885 /**
886  * Callback function to handle MOT DTLS handshake result.
887  * @param[out]   object           remote device information.
888  * @param[out]   errorInfo        CA Error information.
889  */
890 void MultipleOwnerDTLSHandshakeCB(const CAEndpoint_t *object,
891                                 const CAErrorInfo_t *errorInfo)
892 {
893     OIC_LOG(DEBUG, TAG, "IN MultipleOwnerDTLSHandshakeCB");
894
895     if(CA_STATUS_OK == errorInfo->result)
896     {
897         const CASecureEndpoint_t* authenticatedSubOwnerInfo = CAGetSecureEndpointData(object);
898         if(authenticatedSubOwnerInfo)
899         {
900             if (0 == memcmp(authenticatedSubOwnerInfo->identity.id, gDoxm->owner.id,
901                             authenticatedSubOwnerInfo->identity.id_length))
902             {
903                 OIC_LOG(WARNING, TAG, "Super owner tried MOT, this request will be ignored.");
904                 return;
905             }
906
907             OicSecSubOwner_t* subOwnerInst = NULL;
908             LL_FOREACH(gDoxm->subOwners, subOwnerInst)
909             {
910                 if(0 == memcmp(subOwnerInst->uuid.id,
911                                authenticatedSubOwnerInfo->identity.id,
912                                authenticatedSubOwnerInfo->identity.id_length))
913                 {
914                     break;
915                 }
916             }
917
918             if(NULL == subOwnerInst)
919             {
920                 subOwnerInst = (OicSecSubOwner_t*)OICCalloc(1, sizeof(OicSecSubOwner_t));
921                 if(subOwnerInst)
922                 {
923                     char* strUuid = NULL;
924                     memcpy(subOwnerInst->uuid.id, authenticatedSubOwnerInfo->identity.id,
925                            authenticatedSubOwnerInfo->identity.id_length);
926                     if(OC_STACK_OK != ConvertUuidToStr(&subOwnerInst->uuid, &strUuid))
927                     {
928                         OIC_LOG(ERROR, TAG, "Failed to allocate memory.");
929                         return;
930                     }
931                     OIC_LOG_V(DEBUG, TAG, "Adding New SubOwner(%s)", strUuid);
932                     OICFree(strUuid);
933                     LL_APPEND(gDoxm->subOwners, subOwnerInst);
934                     if(!UpdatePersistentStorage(gDoxm))
935                     {
936                         OIC_LOG(ERROR, TAG, "Failed to register SubOwner UUID into Doxm");
937                     }
938                 }
939             }
940         }
941     }
942
943     if(CA_STATUS_OK != CAregisterPskCredentialsHandler(GetDtlsPskCredentials))
944     {
945         OIC_LOG(WARNING, TAG, "Failed to revert the DTLS credential handler");
946     }
947
948     OIC_LOG(DEBUG, TAG, "OUT MultipleOwnerDTLSHandshakeCB");
949 }
950 #endif //MULTIPLE_OWNER
951 #endif // defined(__WITH_DTLS__) || defined (__WITH_TLS__)
952
953 /**
954  * Function to validate oxmsel with oxms.
955  *
956  * @param[in] supportedMethods   Array of supported methods
957  * @param[in] numberOfMethods   number of supported methods
958  * @param[out]  selectedMethod         Selected methods
959  * @return  TRUE on success
960  */
961 static bool ValidateOxmsel(const OicSecOxm_t *supportedMethods,
962         size_t numberOfMethods, OicSecOxm_t *selectedMethod)
963 {
964     bool isValidOxmsel = false;
965
966     OIC_LOG(DEBUG, TAG, "IN ValidateOxmsel");
967     if (numberOfMethods == 0 || !supportedMethods)
968     {
969         OIC_LOG(WARNING, TAG, "Could not find a supported OxM.");
970         return isValidOxmsel;
971     }
972
973     for (size_t i = 0; i < numberOfMethods; i++)
974     {
975             if (*selectedMethod  == supportedMethods[i])
976             {
977                 isValidOxmsel = true;
978                 break;
979             }
980     }
981     if (!isValidOxmsel)
982     {
983         OIC_LOG(ERROR, TAG, "Not allowed Oxmsel.");
984         return isValidOxmsel;
985     }
986
987     OIC_LOG(DEBUG, TAG, "OUT ValidateOxmsel");
988
989     return isValidOxmsel;
990 }
991
992 static OCEntityHandlerResult HandleDoxmPostRequest(OCEntityHandlerRequest * ehRequest)
993 {
994     OIC_LOG (DEBUG, TAG, "Doxm EntityHandle  processing POST request");
995     OCEntityHandlerResult ehRet = OC_EH_ERROR;
996     OicUuid_t emptyOwner = {.id = {0} };
997     static uint16_t previousMsgId = 0;
998     bool isDuplicatedMsg = false;
999
1000     /*
1001      * Convert CBOR Doxm data into binary. This will also validate
1002      * the Doxm data received.
1003      */
1004     OicSecDoxm_t *newDoxm = NULL;
1005
1006     if (ehRequest->payload)
1007     {
1008         uint8_t *payload = ((OCSecurityPayload *)ehRequest->payload)->securityData;
1009         size_t size = ((OCSecurityPayload *)ehRequest->payload)->payloadSize;
1010         bool roParsed = false;
1011         OCStackResult res = CBORPayloadToDoxmBin(payload, size, &newDoxm, &roParsed);
1012         if (newDoxm && OC_STACK_OK == res)
1013         {
1014             /*
1015              * message ID is supported for CoAP over UDP only according to RFC 7252
1016              * So we should check message ID to prevent duplicate request handling in case of OC_ADAPTER_IP.
1017              * In case of other transport adapter, duplicate message check is not required.
1018              */
1019             if (OC_ADAPTER_IP == ehRequest->devAddr.adapter &&
1020                  previousMsgId == ehRequest->messageID)
1021             {
1022                 isDuplicatedMsg = true;
1023             }
1024
1025             // Check request on RO property
1026             if (true == roParsed)
1027             {
1028                 OIC_LOG(ERROR, TAG, "Not acceptable request because of read-only propertys");
1029                 ehRet = OC_EH_NOT_ACCEPTABLE;
1030                 goto exit;
1031             }
1032
1033             // in owned state
1034             if (true == gDoxm->owned)
1035             {
1036                 //Update gDoxm based on newDoxm
1037                 updateWriteableProperty(newDoxm, gDoxm);
1038
1039 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1040 #ifdef MULTIPLE_OWNER
1041                 //handle mom
1042                 if(gDoxm->mom)
1043                 {
1044                     if(OIC_MULTIPLE_OWNER_DISABLE != gDoxm->mom->mode)
1045                     {
1046                         CAResult_t caRes = CA_STATUS_FAILED;
1047                         if(OIC_PRECONFIG_PIN == gDoxm->oxmSel || OIC_RANDOM_DEVICE_PIN == gDoxm->oxmSel)
1048                         {
1049                             caRes = CAEnableAnonECDHCipherSuite(false);
1050                             VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1051                             OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1052
1053                             caRes = CASelectCipherSuite((uint16_t)TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256, ehRequest->devAddr.adapter);
1054                             VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1055                             OIC_LOG(INFO, TAG, "ECDHE_PSK CipherSuite will be used for MOT");
1056
1057                             //Set the device id to derive temporal PSK
1058                             SetUuidForPinBasedOxm(&gDoxm->deviceID);
1059                         }
1060                         else
1061                         {
1062                             OIC_LOG(WARNING, TAG, "Unsupported OxM for Multiple Ownership Transfer.");
1063                         }
1064
1065                         CAregisterSslHandshakeCallback(MultipleOwnerDTLSHandshakeCB);
1066                     }
1067                     else
1068                     {
1069                         //if MOM is disabled, revert the DTLS handshake callback
1070                         if(CA_STATUS_OK != CAregisterSslHandshakeCallback(NULL))
1071                         {
1072                             OIC_LOG(WARNING, TAG, "Error while revert the DTLS Handshake Callback.");
1073                         }
1074                     }
1075                 }
1076
1077                 if(newDoxm->subOwners)
1078                 {
1079                     OicSecSubOwner_t* subowner = NULL;
1080                     OicSecSubOwner_t* temp = NULL;
1081
1082                     OIC_LOG(DEBUG, TAG, "dectected 'subowners' property");
1083
1084                     if(gDoxm->subOwners)
1085                     {
1086                         LL_FOREACH_SAFE(gDoxm->subOwners, subowner, temp)
1087                         {
1088                             LL_DELETE(gDoxm->subOwners, subowner);
1089                             OICFree(subowner);
1090                         }
1091                     }
1092
1093                     subowner = NULL;
1094                     temp = NULL;
1095                     LL_FOREACH_SAFE(newDoxm->subOwners, subowner, temp)
1096                     {
1097                         LL_DELETE(newDoxm->subOwners, subowner);
1098                         LL_APPEND(gDoxm->subOwners, subowner);
1099                     }
1100                 }
1101 #endif //MULTIPLE_OWNER
1102 #endif // defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1103
1104                 //Update new state in persistent storage
1105                 if (UpdatePersistentStorage(gDoxm) == true)
1106                 {
1107                     ehRet = OC_EH_OK;
1108                 }
1109                 else
1110                 {
1111                     OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1112                     ehRet = OC_EH_ERROR;
1113                 }
1114                 goto exit;
1115             }
1116
1117             // in unowned state
1118             if ((false == gDoxm->owned) && (false == newDoxm->owned))
1119             {
1120                 if (false == ValidateOxmsel(gDoxm->oxm, gDoxm->oxmLen, &newDoxm->oxmSel))
1121                 {
1122                     OIC_LOG(ERROR, TAG, "Not acceptable request because oxmsel does not support on Server");
1123                     ehRet = OC_EH_NOT_ACCEPTABLE;
1124                     goto exit;
1125                 }
1126
1127                 if (OIC_JUST_WORKS == newDoxm->oxmSel || OIC_MV_JUST_WORKS == newDoxm->oxmSel)
1128                 {
1129                     /*
1130                      * If current state of the device is un-owned, enable
1131                      * anonymous ECDH cipher in tinyDTLS so that Provisioning
1132                      * tool can initiate JUST_WORKS ownership transfer process.
1133                      */
1134                     if (memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
1135                     {
1136                         gDoxm->oxmSel = newDoxm->oxmSel;
1137                         //Update new state in persistent storage
1138                         if ((UpdatePersistentStorage(gDoxm) == true))
1139                         {
1140                             ehRet = OC_EH_OK;
1141                         }
1142                         else
1143                         {
1144                             OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
1145                             ehRet = OC_EH_ERROR;
1146                             goto exit;
1147                         }
1148                         OIC_LOG (INFO, TAG, "Doxm EntityHandle  enabling AnonECDHCipherSuite");
1149 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1150                         ehRet = (CAEnableAnonECDHCipherSuite(true) == CA_STATUS_OK) ? OC_EH_OK : OC_EH_ERROR;
1151 #endif // __WITH_DTLS__ or __WITH_TLS__
1152                         goto exit;
1153                     }
1154                     else
1155                     {
1156 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1157                         //Save the owner's UUID to derive owner credential
1158                         memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
1159
1160                         // Update new state in persistent storage
1161                         if (true == UpdatePersistentStorage(gDoxm))
1162                         {
1163                             ehRet = OC_EH_OK;
1164                         }
1165                         else
1166                         {
1167                             OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1168                             ehRet = OC_EH_ERROR;
1169                             goto exit;
1170                         }
1171
1172                         /*
1173                          * Disable anonymous ECDH cipher in tinyDTLS since device is now
1174                          * in owned state.
1175                          */
1176                         CAResult_t caRes = CA_STATUS_OK;
1177                         caRes = CAEnableAnonECDHCipherSuite(false);
1178                         VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1179                         OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1180
1181                         //In case of Mutual Verified Just-Works, verify mutualVerifNum
1182                         if (OIC_MV_JUST_WORKS == newDoxm->oxmSel && false == newDoxm->owned &&
1183                             false == isDuplicatedMsg)
1184                         {
1185                             uint8_t preMutualVerifNum[OWNER_PSK_LENGTH_128] = {0};
1186                             uint8_t mutualVerifNum[MUTUAL_VERIF_NUM_LEN] = {0};
1187                             OicUuid_t deviceID = {.id = {0}};
1188
1189                             //Generate mutualVerifNum
1190                             OCServerRequest * request = GetServerRequestUsingHandle(ehRequest->requestHandle);
1191
1192                             char label[LABEL_LEN] = {0};
1193                             snprintf(label, LABEL_LEN, "%s%s", MUTUAL_VERIF_NUM, OXM_MV_JUST_WORKS);
1194                             if (OC_STACK_OK != GetDoxmDeviceID(&deviceID))
1195                             {
1196                                 OIC_LOG(ERROR, TAG, "Error while retrieving Owner's device ID");
1197                                 ehRet = OC_EH_ERROR;
1198                                 goto exit;
1199
1200                             }
1201
1202                             CAResult_t pskRet = CAGenerateOwnerPSK((CAEndpoint_t *)&request->devAddr,
1203                                     (uint8_t *)label,
1204                                     strlen(label),
1205                                     gDoxm->owner.id, sizeof(gDoxm->owner.id),
1206                                     gDoxm->deviceID.id, sizeof(gDoxm->deviceID.id),
1207                                     preMutualVerifNum, OWNER_PSK_LENGTH_128);
1208                             if (CA_STATUS_OK != pskRet)
1209                             {
1210                                 OIC_LOG(WARNING, TAG, "Failed to remove the invaild owner credential");
1211                                 ehRet = OC_EH_ERROR;
1212                                 goto exit;
1213
1214                             }
1215
1216                             memcpy(mutualVerifNum, preMutualVerifNum + OWNER_PSK_LENGTH_128 - sizeof(mutualVerifNum),
1217                                     sizeof(mutualVerifNum));
1218
1219                             //Wait for user confirmation
1220                             if (OC_STACK_OK != VerifyOwnershipTransfer(mutualVerifNum, DISPLAY_NUM | USER_CONFIRM))
1221                             {
1222                                 ehRet = OC_EH_NOT_ACCEPTABLE;
1223                             }
1224                             else
1225                             {
1226                                 ehRet = OC_EH_OK;
1227                             }
1228                         }
1229
1230 #endif // __WITH_DTLS__ or __WITH_TLS__
1231                     }
1232                 }
1233                 else if (OIC_RANDOM_DEVICE_PIN == newDoxm->oxmSel)
1234                 {
1235                     /*
1236                      * If current state of the device is un-owned, enable
1237                      * anonymous ECDH cipher in tinyDTLS so that Provisioning
1238                      * tool can initiate JUST_WORKS ownership transfer process.
1239                      */
1240                     if(memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
1241                     {
1242                         gDoxm->oxmSel = newDoxm->oxmSel;
1243                         //Update new state in persistent storage
1244                         if ((UpdatePersistentStorage(gDoxm) == true))
1245                         {
1246                             ehRet = OC_EH_OK;
1247                         }
1248                         else
1249                         {
1250                             OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
1251                             ehRet = OC_EH_ERROR;
1252                         }
1253
1254 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1255                         CAResult_t caRes = CA_STATUS_OK;
1256
1257                         caRes = CAEnableAnonECDHCipherSuite(false);
1258                         VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1259                         OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1260
1261                         caRes = CASelectCipherSuite(TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256,
1262                                                     ehRequest->devAddr.adapter);
1263                         VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1264
1265                         if (!isDuplicatedMsg)
1266                         {
1267                             char ranPin[OXM_RANDOM_PIN_MAX_SIZE + 1] = {0};
1268                             if (OC_STACK_OK == GeneratePin(ranPin, sizeof(ranPin)))
1269                             {
1270                                 //Set the device id to derive temporal PSK
1271                                 SetUuidForPinBasedOxm(&gDoxm->deviceID);
1272
1273                                 /**
1274                                  * Since PSK will be used directly by DTLS layer while PIN based ownership transfer,
1275                                  * Credential should not be saved into SVR.
1276                                  * For this reason, use a temporary get_psk_info callback to random PIN OxM.
1277                                  */
1278                                 caRes = CAregisterPskCredentialsHandler(GetDtlsPskForRandomPinOxm);
1279                                 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1280                                 ehRet = OC_EH_OK;
1281                             }
1282                             else
1283                             {
1284                                 OIC_LOG(ERROR, TAG, "Failed to generate random PIN");
1285                                 ehRet = OC_EH_ERROR;
1286                             }
1287                         }
1288 #endif // __WITH_DTLS__ or __WITH_TLS__
1289                     }
1290 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1291                     else
1292                     {
1293                         //Save the owner's UUID to derive owner credential
1294                         memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
1295
1296                         //Update new state in persistent storage
1297                         if (UpdatePersistentStorage(gDoxm) == true)
1298                         {
1299                             ehRet = OC_EH_OK;
1300                         }
1301                         else
1302                         {
1303                             OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1304                             ehRet = OC_EH_ERROR;
1305                         }
1306                     }
1307 #endif // __WITH_DTLS__ or __WITH_TLS__
1308                 }
1309 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1310                 else if (OIC_MANUFACTURER_CERTIFICATE ==  newDoxm->oxmSel || OIC_CON_MFG_CERT == newDoxm->oxmSel)
1311                 {
1312                     //Save the owner's UUID to derive owner credential
1313                     memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
1314                     gDoxm->oxmSel = newDoxm->oxmSel;
1315                     //Update new state in persistent storage
1316                     if (UpdatePersistentStorage(gDoxm))
1317                     {
1318                         ehRet = OC_EH_OK;
1319                     }
1320                     else
1321                     {
1322                         OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
1323                         ehRet = OC_EH_ERROR;
1324                     }
1325                     CAResult_t caRes = CAEnableAnonECDHCipherSuite(false);
1326                     VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1327                     OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1328
1329                     VERIFY_SUCCESS(TAG, CA_STATUS_OK == CAregisterPkixInfoHandler(GetManufacturerPkixInfo), ERROR);
1330                     VERIFY_SUCCESS(TAG, CA_STATUS_OK == CAregisterGetCredentialTypesHandler(InitManufacturerCipherSuiteList), ERROR);
1331
1332                     //In case of Confirm Manufacturer Cert, get user confirmation
1333                     if (OIC_CON_MFG_CERT == newDoxm->oxmSel && false == newDoxm->owned &&
1334                         false == isDuplicatedMsg &&
1335                         memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) != 0)
1336                     {
1337                         if (OC_STACK_OK != VerifyOwnershipTransfer(NULL, USER_CONFIRM))
1338                         {
1339                             ehRet = OC_EH_NOT_ACCEPTABLE;
1340                         }
1341                         else
1342                         {
1343                             ehRet = OC_EH_OK;
1344                         }
1345                     }
1346
1347
1348                 }
1349 #endif // __WITH_DTLS__ or __WITH_TLS__
1350             }
1351
1352             /*
1353              * When current state of the device is un-owned and Provisioning
1354              * Tool is attempting to change the state to 'Owned' with a
1355              * qualified value for the field 'Owner'
1356              */
1357             if ((false == gDoxm->owned) && (true == newDoxm->owned) &&
1358                     (memcmp(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t)) == 0))
1359             {
1360                 //Change the SVR's resource owner as owner device.
1361                 OCStackResult ownerRes = SetAclRownerId(&gDoxm->owner);
1362                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1363                 {
1364                     ehRet = OC_EH_ERROR;
1365                     goto exit;
1366                 }
1367                 ownerRes = SetAmaclRownerId(&gDoxm->owner);
1368                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1369                 {
1370                     ehRet = OC_EH_ERROR;
1371                     goto exit;
1372                 }
1373                 ownerRes = SetCredRownerId(&gDoxm->owner);
1374                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1375                 {
1376                     ehRet = OC_EH_ERROR;
1377                     goto exit;
1378                 }
1379                 ownerRes = SetPstatRownerId(&gDoxm->owner);
1380                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1381                 {
1382                     ehRet = OC_EH_ERROR;
1383                     goto exit;
1384                 }
1385                 ownerRes = SetDpairingRownerId(&gDoxm->owner);
1386                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1387                 {
1388                     ehRet = OC_EH_ERROR;
1389                     goto exit;
1390                 }
1391                 ownerRes = SetPconfRownerId(&gDoxm->owner);
1392                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1393                 {
1394                     ehRet = OC_EH_ERROR;
1395                     goto exit;
1396                 }
1397
1398                 gDoxm->owned = true;
1399                 memcpy(&gDoxm->rownerID, &gDoxm->owner, sizeof(OicUuid_t));
1400
1401                 // Update new state in persistent storage
1402                 if (UpdatePersistentStorage(gDoxm))
1403                 {
1404                     //Update default ACE of security resource to prevent anonymous user access.
1405                     if(OC_STACK_OK == UpdateDefaultSecProvACE())
1406                     {
1407                         ehRet = OC_EH_OK;
1408                     }
1409                     else
1410                     {
1411                         OIC_LOG(ERROR, TAG, "Failed to remove default ACL for security provisioning");
1412                         ehRet = OC_EH_ERROR;
1413                     }
1414                 }
1415                 else
1416                 {
1417                     OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1418                     ehRet = OC_EH_ERROR;
1419                 }
1420 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1421                 if (OIC_MANUFACTURER_CERTIFICATE == gDoxm->oxmSel ||
1422                                             OIC_CON_MFG_CERT== gDoxm->oxmSel)
1423                 {
1424                     CAregisterPkixInfoHandler(GetPkixInfo);
1425                     CAregisterGetCredentialTypesHandler(InitCipherSuiteList);
1426                 }
1427 #endif // __WITH_DTLS__ or __WITH_TLS__
1428             }
1429         }
1430     }
1431
1432 exit:
1433     if(OC_EH_OK != ehRet)
1434     {
1435
1436         /*
1437          * If some error is occured while ownership transfer,
1438          * ownership transfer related resource should be revert back to initial status.
1439         */
1440         if(gDoxm)
1441         {
1442             if(!gDoxm->owned)
1443             {
1444                 OIC_LOG(WARNING, TAG, "The operation failed during handle DOXM request");
1445
1446                 if (!isDuplicatedMsg)
1447                 {
1448                     RestoreDoxmToInitState();
1449                     RestorePstatToInitState();
1450                     OIC_LOG(WARNING, TAG, "DOXM will be reverted.");
1451                 }
1452             }
1453         }
1454         else
1455         {
1456             OIC_LOG(ERROR, TAG, "Invalid DOXM resource.");
1457         }
1458     }
1459     else
1460     {
1461         previousMsgId = ehRequest->messageID;
1462     }
1463
1464     //Send payload to request originator
1465     ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1466                    OC_EH_OK : OC_EH_ERROR;
1467
1468     DeleteDoxmBinData(newDoxm);
1469
1470     return ehRet;
1471 }
1472
1473 OCEntityHandlerResult DoxmEntityHandler(OCEntityHandlerFlag flag,
1474                                         OCEntityHandlerRequest * ehRequest,
1475                                         void* callbackParam)
1476 {
1477     (void)callbackParam;
1478     OCEntityHandlerResult ehRet = OC_EH_ERROR;
1479
1480     if(NULL == ehRequest)
1481     {
1482         return ehRet;
1483     }
1484
1485     if (flag & OC_REQUEST_FLAG)
1486     {
1487         OIC_LOG(DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
1488
1489         switch (ehRequest->method)
1490         {
1491             case OC_REST_GET:
1492                 ehRet = HandleDoxmGetRequest(ehRequest);
1493                 break;
1494
1495             case OC_REST_POST:
1496                 ehRet = HandleDoxmPostRequest(ehRequest);
1497                 break;
1498
1499             default:
1500                 ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1501                                OC_EH_OK : OC_EH_ERROR;
1502                 break;
1503         }
1504     }
1505
1506     return ehRet;
1507 }
1508
1509 OCStackResult CreateDoxmResource()
1510 {
1511     OCStackResult ret = OCCreateResource(&gDoxmHandle,
1512                                          OIC_RSRC_TYPE_SEC_DOXM,
1513                                          OC_RSRVD_INTERFACE_DEFAULT,
1514                                          OIC_RSRC_DOXM_URI,
1515                                          DoxmEntityHandler,
1516                                          NULL,
1517                                          OC_SECURE |
1518                                          OC_DISCOVERABLE);
1519
1520     if (OC_STACK_OK != ret)
1521     {
1522         OIC_LOG (FATAL, TAG, "Unable to instantiate Doxm resource");
1523         DeInitDoxmResource();
1524     }
1525     return ret;
1526 }
1527
1528 /**
1529  * Checks if DeviceID is generated during provisioning for the new device.
1530  * If DeviceID is NULL then generates the new DeviceID.
1531  * Once DeviceID is assigned to the device it does not change for the lifetime of the device.
1532  */
1533 static OCStackResult CheckDeviceID()
1534 {
1535     OCStackResult ret = OC_STACK_ERROR;
1536     bool validId = false;
1537     for (uint8_t i = 0; i < UUID_LENGTH; i++)
1538     {
1539         if (gDoxm->deviceID.id[i] != 0)
1540         {
1541             validId = true;
1542             break;
1543         }
1544     }
1545
1546     if (!validId)
1547     {
1548         if (!OCGenerateUuid(gDoxm->deviceID.id))
1549         {
1550             OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
1551             return OC_STACK_ERROR;
1552         }
1553         ret = OC_STACK_OK;
1554
1555         if (!UpdatePersistentStorage(gDoxm))
1556         {
1557             //TODO: After registering PSI handler in all samples, do ret = OC_STACK_OK here.
1558             OIC_LOG(FATAL, TAG, "UpdatePersistentStorage failed!");
1559         }
1560     }
1561     else
1562     {
1563         ret = OC_STACK_OK;
1564     }
1565     return ret;
1566 }
1567
1568 /**
1569  * Get the default value.
1570  *
1571  * @return the default value of doxm, @ref OicSecDoxm_t.
1572  */
1573 static OicSecDoxm_t* GetDoxmDefault()
1574 {
1575     OIC_LOG(DEBUG, TAG, "GetDoxmToDefault");
1576     return &gDefaultDoxm;
1577 }
1578
1579 const OicSecDoxm_t* GetDoxmResourceData()
1580 {
1581     return gDoxm;
1582 }
1583
1584 #if defined(__WITH_DTLS__) && defined(MULTIPLE_OWNER)
1585 /**
1586  * Internal API to prepare MOT
1587  */
1588 static void PrepareMOT(const OicSecDoxm_t* doxm)
1589 {
1590     OIC_LOG(INFO, TAG, "IN PrepareMOT");
1591     VERIFY_NON_NULL(TAG, doxm, ERROR);
1592
1593     if(true == doxm->owned && NULL != doxm->mom && OIC_MULTIPLE_OWNER_DISABLE != doxm->mom->mode)
1594     {
1595         CAResult_t caRes = CA_STATUS_FAILED;
1596
1597         OIC_LOG(INFO, TAG, "Multiple Ownership Transfer Enabled!");
1598
1599         if(OIC_PRECONFIG_PIN == doxm->oxmSel)
1600         {
1601             caRes = CAEnableAnonECDHCipherSuite(false);
1602             VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1603             OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1604
1605             caRes = CASelectCipherSuite((uint16_t)TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256, CA_ADAPTER_IP);
1606             VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1607 #ifdef __WITH_TLS__
1608             caRes = CASelectCipherSuite((uint16_t)TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256, CA_ADAPTER_TCP);
1609             VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1610 #endif
1611             OIC_LOG(INFO, TAG, "ECDHE_PSK CipherSuite will be used for MOT");
1612
1613             //Set the device id to derive temporal PSK
1614             SetUuidForPinBasedOxm(&doxm->deviceID);
1615         }
1616         else
1617         {
1618             OIC_LOG(ERROR, TAG, "Unsupported OxM for Multiple Ownership Transfer.");
1619             return;
1620         }
1621
1622         CAregisterSslHandshakeCallback(MultipleOwnerDTLSHandshakeCB);
1623     }
1624
1625     OIC_LOG(INFO, TAG, "OUT PrepareMOT");
1626     return;
1627 exit:
1628     OIC_LOG(WARNING, TAG, "Error in PrepareMOT");
1629 }
1630 #endif //defined(__WITH_DTLS__) && defined(MULTIPLE_OWNER)
1631
1632 OCStackResult InitDoxmResource()
1633 {
1634     OCStackResult ret = OC_STACK_ERROR;
1635
1636     //Read DOXM resource from PS
1637     uint8_t *data = NULL;
1638     size_t size = 0;
1639     ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_DOXM_NAME, &data, &size);
1640     // If database read failed
1641     if (OC_STACK_OK != ret)
1642     {
1643        OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
1644     }
1645     if (data)
1646     {
1647        // Read DOXM resource from PS
1648        ret = CBORPayloadToDoxm(data, size, &gDoxm);
1649     }
1650     /*
1651      * If SVR database in persistent storage got corrupted or
1652      * is not available for some reason, a default doxm is created
1653      * which allows user to initiate doxm provisioning again.
1654      */
1655      if ((OC_STACK_OK != ret) || !data || !gDoxm)
1656     {
1657         gDoxm = GetDoxmDefault();
1658     }
1659
1660     //In case of the server is shut down unintentionally, we should initialize the owner
1661     if(false == gDoxm->owned)
1662     {
1663         OicUuid_t emptyUuid = {.id={0}};
1664         memcpy(&gDoxm->owner, &emptyUuid, sizeof(OicUuid_t));
1665     }
1666
1667     ret = CheckDeviceID();
1668     if (ret == OC_STACK_OK)
1669     {
1670         OIC_LOG_V(DEBUG, TAG, "Initial Doxm Owned = %d", gDoxm->owned);
1671         //Instantiate 'oic.sec.doxm'
1672         ret = CreateDoxmResource();
1673     }
1674     else
1675     {
1676         OIC_LOG (ERROR, TAG, "CheckDeviceID failed");
1677     }
1678     OICFree(data);
1679
1680 #if defined(__WITH_DTLS__) && defined(MULTIPLE_OWNER)
1681     //if MOT is enabled, MOT should be prepared.
1682     if(gDoxm && gDoxm->owned)
1683     {
1684         PrepareMOT(gDoxm);
1685     }
1686 #endif // defined(__WITH_DTLS__) && defined(MULTIPLE_OWNER)
1687
1688     return ret;
1689 }
1690
1691 OCStackResult DeInitDoxmResource()
1692 {
1693     OCStackResult ret = OCDeleteResource(gDoxmHandle);
1694     if (gDoxm  != &gDefaultDoxm)
1695     {
1696         DeleteDoxmBinData(gDoxm);
1697     }
1698     gDoxm = NULL;
1699
1700     if (OC_STACK_OK == ret)
1701     {
1702         return OC_STACK_OK;
1703     }
1704     else
1705     {
1706         return OC_STACK_ERROR;
1707     }
1708 }
1709
1710 OCStackResult GetDoxmDeviceID(OicUuid_t *deviceID)
1711 {
1712     if (deviceID && gDoxm)
1713     {
1714        *deviceID = gDoxm->deviceID;
1715         return OC_STACK_OK;
1716     }
1717     return OC_STACK_ERROR;
1718 }
1719
1720 OCStackResult GetDoxmIsOwned(bool *isOwned)
1721 {
1722     if (isOwned && gDoxm)
1723     {
1724        *isOwned = gDoxm->owned;
1725         return OC_STACK_OK;
1726     }
1727     return OC_STACK_ERROR;
1728 }
1729
1730 OCStackResult SetDoxmDeviceID(const OicUuid_t *deviceID)
1731 {
1732     bool isPT = false;
1733
1734     if(NULL == deviceID)
1735     {
1736         return OC_STACK_INVALID_PARAM;
1737     }
1738     if(NULL == gDoxm)
1739     {
1740         OIC_LOG(ERROR, TAG, "Doxm resource is not initialized.");
1741         return OC_STACK_NO_RESOURCE;
1742     }
1743
1744     //Check the device's OTM state
1745
1746 #ifdef __WITH_DTLS__
1747     //for normal device.
1748     if(true == gDoxm->owned &&
1749        memcmp(gDoxm->deviceID.id, gDoxm->owner.id, sizeof(gDoxm->owner.id)) != 0)
1750     {
1751         OIC_LOG(ERROR, TAG, "This device owned by owner's device.");
1752         OIC_LOG(ERROR, TAG, "Device UUID cannot be changed to guarantee the reliability of the connection.");
1753         return OC_STACK_ERROR;
1754     }
1755 #endif //__WITH_DTLS
1756
1757     //Save the previous UUID
1758     OicUuid_t tempUuid;
1759     memcpy(tempUuid.id, gDoxm->deviceID.id, sizeof(tempUuid.id));
1760
1761     //Change the UUID
1762     memcpy(gDoxm->deviceID.id, deviceID->id, sizeof(deviceID->id));
1763     if(isPT)
1764     {
1765         memcpy(gDoxm->owner.id, deviceID->id, sizeof(deviceID->id));
1766         memcpy(gDoxm->rownerID.id, deviceID->id, sizeof(deviceID->id));
1767     }
1768
1769     //Update PS
1770     if(!UpdatePersistentStorage(gDoxm))
1771     {
1772         //revert UUID in case of update error
1773         memcpy(gDoxm->deviceID.id, tempUuid.id, sizeof(tempUuid.id));
1774         if(isPT)
1775         {
1776             memcpy(gDoxm->owner.id, tempUuid.id, sizeof(tempUuid.id));
1777             memcpy(gDoxm->rownerID.id, tempUuid.id, sizeof(tempUuid.id));
1778         }
1779
1780         OIC_LOG(ERROR, TAG, "Failed to update persistent storage");
1781         return OC_STACK_ERROR;
1782     }
1783     return OC_STACK_OK;
1784 }
1785
1786 OCStackResult GetDoxmDevOwnerId(OicUuid_t *devownerid)
1787 {
1788     OCStackResult retVal = OC_STACK_ERROR;
1789     if (gDoxm)
1790     {
1791         OIC_LOG_V(DEBUG, TAG, "GetDoxmDevOwnerId(): gDoxm owned =  %d.", \
1792             gDoxm->owned);
1793         if (gDoxm->owned)
1794         {
1795             *devownerid = gDoxm->owner;
1796             retVal = OC_STACK_OK;
1797         }
1798     }
1799     return retVal;
1800 }
1801
1802 OCStackResult GetDoxmRownerId(OicUuid_t *rowneruuid)
1803 {
1804     OCStackResult retVal = OC_STACK_ERROR;
1805     if (gDoxm)
1806     {
1807         if( gDoxm->owned )
1808         {
1809             *rowneruuid = gDoxm->rownerID;
1810                     retVal = OC_STACK_OK;
1811         }
1812     }
1813     return retVal;
1814 }
1815
1816 #ifdef MULTIPLE_OWNER
1817 /**
1818  * Compare the UUID to SubOwner.
1819  *
1820  * @param[in] uuid device UUID
1821  *
1822  * @return true if context->subjectId exist subowner list, else false.
1823  */
1824 bool IsSubOwner(const OicUuid_t* uuid)
1825 {
1826     bool retVal = false;
1827
1828     if (NULL == uuid)
1829     {
1830         return retVal;
1831     }
1832
1833     if (gDoxm && gDoxm->subOwners)
1834     {
1835         if (memcmp(gDoxm->owner.id, uuid->id, sizeof(gDoxm->owner.id)) == 0)
1836         {
1837             return false;
1838         }
1839
1840         OicSecSubOwner_t* subOwner = NULL;
1841         LL_FOREACH(gDoxm->subOwners, subOwner)
1842         {
1843             if (memcmp(subOwner->uuid.id, uuid->id, sizeof(uuid->id)) == 0)
1844             {
1845                 return true;
1846             }
1847         }
1848     }
1849     return retVal;
1850 }
1851 #endif //MULTIPLE_OWNER
1852
1853 /**
1854  * Function to restore doxm resurce to initial status.
1855  * This function will use in case of error while ownership transfer
1856  */
1857 void RestoreDoxmToInitState()
1858 {
1859     if(gDoxm)
1860     {
1861         OIC_LOG(INFO, TAG, "DOXM resource will revert back to initial status.");
1862
1863         OicUuid_t emptyUuid = {.id={0}};
1864         memcpy(&(gDoxm->owner), &emptyUuid, sizeof(OicUuid_t));
1865         gDoxm->owned = false;
1866         gDoxm->oxmSel = OIC_JUST_WORKS;
1867
1868         if(!UpdatePersistentStorage(gDoxm))
1869         {
1870             OIC_LOG(ERROR, TAG, "Failed to revert DOXM in persistent storage");
1871         }
1872     }
1873 }
1874
1875 OCStackResult SetDoxmSelfOwnership(const OicUuid_t* newROwner)
1876 {
1877     OCStackResult ret = OC_STACK_ERROR;
1878     uint8_t *cborPayload = NULL;
1879     size_t size = 0;
1880
1881     if(NULL == gDoxm)
1882     {
1883         ret = OC_STACK_NO_RESOURCE;
1884         return ret;
1885     }
1886
1887     if( newROwner && (false == gDoxm->owned) )
1888     {
1889         gDoxm->owned = true;
1890         memcpy(gDoxm->owner.id, newROwner->id, sizeof(newROwner->id));
1891         memcpy(gDoxm->rownerID.id, newROwner->id, sizeof(newROwner->id));
1892
1893         ret = DoxmToCBORPayload(gDoxm, &cborPayload, &size, false);
1894         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
1895
1896         ret = UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, cborPayload, size);
1897         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
1898
1899         OICFree(cborPayload);
1900     }
1901
1902     return ret;
1903
1904 exit:
1905     OICFree(cborPayload);
1906     return ret;
1907 }
1908