replace : iotivity -> iotivity-sec
[platform/upstream/iotivity.git] / resource / csdk / security / src / doxmresource.c
1 //******************************************************************
2 //
3 // Copyright 2015 Intel Mobile Communications GmbH All Rights Reserved.
4 //
5 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
6 //
7 // Licensed under the Apache License, Version 2.0 (the "License");
8 // you may not use this file except in compliance with the License.
9 // You may obtain a copy of the License at
10 //
11 //      http://www.apache.org/licenses/LICENSE-2.0
12 //
13 // Unless required by applicable law or agreed to in writing, software
14 // distributed under the License is distributed on an "AS IS" BASIS,
15 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 // See the License for the specific language governing permissions and
17 // limitations under the License.
18 //
19 //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
20 #include "iotivity_config.h"
21 #include <stdlib.h>
22 #include <string.h>
23
24 #ifdef HAVE_STRINGS_H
25 #include <strings.h>
26 #endif
27
28 #include "ocstack.h"
29 #include "oic_malloc.h"
30 #include "payload_logging.h"
31 #include "utlist.h"
32 #include "ocrandom.h"
33 #include "ocpayload.h"
34 #include "ocpayloadcbor.h"
35 #include "cainterface.h"
36 #include "ocserverrequest.h"
37 #include "resourcemanager.h"
38 #include "doxmresource.h"
39 #include "pstatresource.h"
40 #include "aclresource.h"
41 #include "amaclresource.h"
42 #include "pconfresource.h"
43 #include "dpairingresource.h"
44 #include "psinterface.h"
45 #include "srmresourcestrings.h"
46 #include "securevirtualresourcetypes.h"
47 #include "credresource.h"
48 #include "srmutility.h"
49 #include "pinoxmcommon.h"
50 #include "oxmverifycommon.h"
51
52 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
53 #include "pkix_interface.h"
54 #include "ca_adapter_net_ssl.h"
55 #endif
56
57 #define TAG  "OIC_SRM_DOXM"
58 #define CHAR_ZERO ('0')
59
60 /** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
61  * The value of payload size is increased until reaching belox max cbor size. */
62 static const uint16_t CBOR_SIZE = 512;
63
64 /** Max cbor size payload. */
65 static const uint16_t CBOR_MAX_SIZE = 4400;
66
67 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
68 /** MAX uuid seed size */
69 #define MAX_UUID_SEED_SIZE (64)
70 /** MIN uuid seed size */
71 #define MIN_UUID_SEED_SIZE (8)
72
73 /** Buffer to save the seed of device UUID */
74 static uint8_t gUuidSeed[MAX_UUID_SEED_SIZE];
75 static size_t gUuidSeedSize = 0;
76 #endif
77
78 #ifdef MULTIPLE_OWNER
79 #define MAX_SUBOWNER_SIZE (64)
80 #define MIN_SUBOWNER_SIZE (1)
81 #define DEFAULT_SUBOWNER_SIZE (32)
82
83 static size_t gMaxSubOwnerSize = DEFAULT_SUBOWNER_SIZE;
84 #endif
85
86 typedef enum ConfirmState{
87     CONFIRM_STATE_READY = 0,
88     CONFIRM_STATE_WAIT = 1,
89     CONFIRM_STATE_ACCEPTED = 2,
90     CONFIRM_STATE_DENIED = 3
91 }ConfirmState_t;
92
93 static OicSecDoxm_t        *gDoxm = NULL;
94 static OCResourceHandle    gDoxmHandle = NULL;
95
96 static OicSecOxm_t gOicSecDoxmJustWorks = OIC_JUST_WORKS;
97 static OicSecDoxm_t gDefaultDoxm =
98 {
99     NULL,                   /* OicUrn_t *oxmType */
100     0,                      /* size_t oxmTypeLen */
101     &gOicSecDoxmJustWorks,  /* uint16_t *oxm */
102     1,                      /* size_t oxmLen */
103     OIC_JUST_WORKS,         /* uint16_t oxmSel */
104     SYMMETRIC_PAIR_WISE_KEY,/* OicSecCredType_t sct */
105     false,                  /* bool owned */
106     {.id = {0}},            /* OicUuid_t deviceID */
107     false,                  /* bool dpc */
108     {.id = {0}},            /* OicUuid_t owner */
109 #ifdef MULTIPLE_OWNER
110     NULL,                   /* OicSecSubOwner_t sub-owner list */
111     NULL,                   /* OicSecMomType_t multiple owner mode */
112 #endif //MULTIPLE_OWNER
113     {.id = {0}},            /* OicUuid_t rownerID */
114 };
115
116 static uint16_t gConfirmMsgId = 0;
117 static ConfirmState_t gConfirmState = CONFIRM_STATE_READY;
118
119
120 /**
121  * This method is internal method.
122  * the param roParsed is optionally used to know whether cborPayload has
123  * at least read only property value or not.
124  */
125 static OCStackResult CBORPayloadToDoxmBin(const uint8_t *cborPayload, size_t size,
126                                 OicSecDoxm_t **doxm, bool *roParsed);
127
128 void DeleteDoxmBinData(OicSecDoxm_t* doxm)
129 {
130     if (doxm)
131     {
132         //Clean oxmType
133         for (size_t i = 0; i < doxm->oxmTypeLen; i++)
134         {
135             OICFree(doxm->oxmType[i]);
136         }
137         OICFree(doxm->oxmType);
138
139         //clean oxm
140         OICFree(doxm->oxm);
141
142 #ifdef MULTIPLE_OWNER
143         //clean mom
144         OICFree(doxm->mom);
145
146         //clean sub-owner list
147         if(NULL != doxm->subOwners)
148         {
149             OicSecSubOwner_t* subowner = NULL;
150             OicSecSubOwner_t* temp = NULL;
151             LL_FOREACH_SAFE(doxm->subOwners, subowner, temp)
152             {
153                 LL_DELETE(doxm->subOwners, subowner);
154                 OICFree(subowner);
155             }
156         }
157 #endif //MULTIPLE_OWNER
158
159         //Clean doxm itself
160         OICFree(doxm);
161     }
162 }
163
164 OCStackResult DoxmToCBORPayload(const OicSecDoxm_t *doxm, uint8_t **payload, size_t *size,
165                                 bool rwOnly)
166 {
167     if (NULL == doxm || NULL == payload || NULL != *payload || NULL == size)
168     {
169         return OC_STACK_INVALID_PARAM;
170     }
171     size_t cborLen = *size;
172     if (0 == cborLen)
173     {
174         cborLen = CBOR_SIZE;
175     }
176     *payload = NULL;
177     *size = 0;
178
179     OCStackResult ret = OC_STACK_ERROR;
180
181     CborEncoder encoder;
182     CborEncoder doxmMap;
183     char* strUuid = NULL;
184
185     int64_t cborEncoderResult = CborNoError;
186
187     uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
188     VERIFY_NON_NULL(TAG, outPayload, ERROR);
189     cbor_encoder_init(&encoder, outPayload, cborLen, 0);
190
191     cborEncoderResult = cbor_encoder_create_map(&encoder, &doxmMap, CborIndefiniteLength);
192     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Doxm Map.");
193
194     //OxmType -- Not Mandatory
195     if (doxm->oxmTypeLen > 0)
196     {
197         CborEncoder oxmType;
198         cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_TYPE_NAME,
199             strlen(OIC_JSON_OXM_TYPE_NAME));
200         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Tag.");
201         cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxmType, doxm->oxmTypeLen);
202         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Array.");
203
204         for (size_t i = 0; i < doxm->oxmTypeLen; i++)
205         {
206             cborEncoderResult = cbor_encode_text_string(&oxmType, doxm->oxmType[i],
207                 strlen(doxm->oxmType[i]));
208             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Value.");
209         }
210         cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxmType);
211         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmType.");
212     }
213
214     //Oxm -- Not Mandatory
215     if (doxm->oxmLen > 0 && false == rwOnly)
216     {
217         CborEncoder oxm;
218         cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXMS_NAME,
219             strlen(OIC_JSON_OXMS_NAME));
220         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Tag.");
221         cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxm, doxm->oxmLen);
222         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Array.");
223
224         for (size_t i = 0; i < doxm->oxmLen; i++)
225         {
226             cborEncoderResult = cbor_encode_int(&oxm, doxm->oxm[i]);
227             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Value");
228         }
229         cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxm);
230         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmName.");
231     }
232
233     //OxmSel -- Mandatory
234     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_SEL_NAME,
235         strlen(OIC_JSON_OXM_SEL_NAME));
236     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Tag.");
237     cborEncoderResult = cbor_encode_int(&doxmMap, doxm->oxmSel);
238     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Value.");
239
240     //sct -- Mandatory
241     if (false == rwOnly)
242     {
243         cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_SUPPORTED_CRED_TYPE_NAME,
244             strlen(OIC_JSON_SUPPORTED_CRED_TYPE_NAME));
245         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Tag");
246         cborEncoderResult = cbor_encode_int(&doxmMap, doxm->sct);
247         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Value.");
248     }
249
250     //Owned -- Mandatory
251     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OWNED_NAME,
252         strlen(OIC_JSON_OWNED_NAME));
253     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Tag.");
254     cborEncoderResult = cbor_encode_boolean(&doxmMap, doxm->owned);
255     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Value.");
256
257     if (false == rwOnly)
258     {
259         //DeviceId -- Mandatory
260         cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVICE_ID_NAME,
261             strlen(OIC_JSON_DEVICE_ID_NAME));
262         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Tag.");
263         ret = ConvertUuidToStr(&doxm->deviceID, &strUuid);
264         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
265         cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
266         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Value.");
267         OICFree(strUuid);
268         strUuid = NULL;
269     }
270
271 #ifdef MULTIPLE_OWNER
272     //Device SubOwnerID -- Not Mandatory
273     if(doxm->subOwners)
274     {
275         size_t subOwnerLen = 0;
276         OicSecSubOwner_t* subOwner = NULL;
277         LL_FOREACH(doxm->subOwners, subOwner)
278         {
279             subOwnerLen++;
280         }
281
282         CborEncoder subOwners;
283         cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_SUBOWNERID_NAME,
284             strlen(OIC_JSON_SUBOWNERID_NAME));
285         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SubOwnerId Tag.");
286         cborEncoderResult = cbor_encoder_create_array(&doxmMap, &subOwners, subOwnerLen);
287         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SubOwner Array.");
288
289         subOwner = NULL;
290         LL_FOREACH(doxm->subOwners, subOwner)
291         {
292             char* strUuid = NULL;
293             ret = ConvertUuidToStr(&subOwner->uuid, &strUuid);
294             VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
295             cborEncoderResult = cbor_encode_text_string(&subOwners, strUuid, strlen(strUuid));
296             OICFree(strUuid);
297             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding SubOwnerId Value");
298         }
299         cborEncoderResult = cbor_encoder_close_container(&doxmMap, &subOwners);
300         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing SubOwnerId.");
301     }
302
303     //Multiple Owner Mode -- Not Mandatory
304     if(doxm->mom)
305     {
306         cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_MOM_NAME,
307             strlen(OIC_JSON_MOM_NAME));
308         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding mom Tag");
309         cborEncoderResult = cbor_encode_int(&doxmMap, (int64_t)doxm->mom->mode);
310         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding mom Value.");
311     }
312 #endif //MULTIPLE_OWNER
313
314     //devownerid -- Mandatory
315     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVOWNERID_NAME,
316         strlen(OIC_JSON_DEVOWNERID_NAME));
317     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Id Tag.");
318     ret = ConvertUuidToStr(&doxm->owner, &strUuid);
319     VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
320     cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
321     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Id Value.");
322     OICFree(strUuid);
323     strUuid = NULL;
324
325     //ROwner -- Mandatory
326     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_ROWNERID_NAME,
327         strlen(OIC_JSON_ROWNERID_NAME));
328     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Tag.");
329     ret = ConvertUuidToStr(&doxm->rownerID, &strUuid);
330     VERIFY_SUCCESS(TAG, OC_STACK_OK == ret , ERROR);
331     cborEncoderResult = cbor_encode_text_string(&doxmMap, strUuid, strlen(strUuid));
332     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ROwner Id Value.");
333     OICFree(strUuid);
334     strUuid = NULL;
335
336     //RT -- Mandatory
337     CborEncoder rtArray;
338     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_RT_NAME,
339             strlen(OIC_JSON_RT_NAME));
340     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Name Tag.");
341     cborEncoderResult = cbor_encoder_create_array(&doxmMap, &rtArray, 1);
342     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Value.");
343     for (size_t i = 0; i < 1; i++)
344     {
345         cborEncoderResult = cbor_encode_text_string(&rtArray, OIC_RSRC_TYPE_SEC_DOXM,
346                 strlen(OIC_RSRC_TYPE_SEC_DOXM));
347         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding RT Value.");
348     }
349     cborEncoderResult = cbor_encoder_close_container(&doxmMap, &rtArray);
350     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing RT.");
351
352     //IF-- Mandatory
353      CborEncoder ifArray;
354      cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_IF_NAME,
355              strlen(OIC_JSON_IF_NAME));
356      VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Name Tag.");
357      cborEncoderResult = cbor_encoder_create_array(&doxmMap, &ifArray, 1);
358      VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Value.");
359     for (size_t i = 0; i < 1; i++)
360     {
361         cborEncoderResult = cbor_encode_text_string(&ifArray, OC_RSRVD_INTERFACE_DEFAULT,
362                 strlen(OC_RSRVD_INTERFACE_DEFAULT));
363         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding IF Value.");
364     }
365     cborEncoderResult = cbor_encoder_close_container(&doxmMap, &ifArray);
366     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing IF.");
367
368     cborEncoderResult = cbor_encoder_close_container(&encoder, &doxmMap);
369     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing DoxmMap.");
370
371     if (CborNoError == cborEncoderResult)
372     {
373         *size = cbor_encoder_get_buffer_size(&encoder, outPayload);
374         *payload = outPayload;
375         ret = OC_STACK_OK;
376     }
377 exit:
378     if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
379     {
380         OIC_LOG(DEBUG, TAG, "Memory getting reallocated.");
381         // reallocate and try again!
382         OICFree(outPayload);
383         outPayload = NULL;
384         // Since the allocated initial memory failed, double the memory.
385         cborLen += cbor_encoder_get_buffer_size(&encoder, encoder.end);
386         OIC_LOG_V(DEBUG, TAG, "Doxm reallocation size : %zd.", cborLen);
387         cborEncoderResult = CborNoError;
388         ret = DoxmToCBORPayload(doxm, payload, &cborLen, rwOnly);
389         *size = cborLen;
390     }
391
392     if ((CborNoError != cborEncoderResult) || (OC_STACK_OK != ret))
393     {
394        OICFree(outPayload);
395        outPayload = NULL;
396        *payload = NULL;
397        *size = 0;
398        ret = OC_STACK_ERROR;
399     }
400
401     return ret;
402 }
403
404 OCStackResult CBORPayloadToDoxm(const uint8_t *cborPayload, size_t size,
405                                 OicSecDoxm_t **secDoxm)
406 {
407     return CBORPayloadToDoxmBin(cborPayload, size, secDoxm, NULL);
408 }
409
410 static OCStackResult CBORPayloadToDoxmBin(const uint8_t *cborPayload, size_t size,
411                                 OicSecDoxm_t **secDoxm, bool *roParsed)
412 {
413     if (NULL == cborPayload || NULL == secDoxm || NULL != *secDoxm || 0 == size)
414     {
415         return OC_STACK_INVALID_PARAM;
416     }
417
418     OCStackResult ret = OC_STACK_ERROR;
419     *secDoxm = NULL;
420
421     CborParser parser;
422     CborError cborFindResult = CborNoError;
423     char* strUuid = NULL;
424     size_t len = 0;
425     CborValue doxmCbor;
426
427     cbor_parser_init(cborPayload, size, 0, &parser, &doxmCbor);
428     CborValue doxmMap;
429     OicSecDoxm_t *doxm = (OicSecDoxm_t *)OICCalloc(1, sizeof(*doxm));
430     VERIFY_NON_NULL(TAG, doxm, ERROR);
431
432     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_TYPE_NAME, &doxmMap);
433     //OxmType -- not Mandatory
434     if (CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
435     {
436         CborValue oxmType;
437
438         cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmTypeLen);
439         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmTypeLen.");
440         VERIFY_SUCCESS(TAG, doxm->oxmTypeLen != 0, ERROR);
441
442         doxm->oxmType = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(*doxm->oxmType));
443         VERIFY_NON_NULL(TAG, doxm->oxmType, ERROR);
444
445         cborFindResult = cbor_value_enter_container(&doxmMap, &oxmType);
446         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmType Array.")
447
448         int i = 0;
449         size_t len = 0;
450         while (cbor_value_is_valid(&oxmType) && cbor_value_is_text_string(&oxmType))
451         {
452             cborFindResult = cbor_value_dup_text_string(&oxmType, &doxm->oxmType[i++],
453                                                         &len, NULL);
454             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding omxType text string.");
455             cborFindResult = cbor_value_advance(&oxmType);
456             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmType.");
457         }
458     }
459
460     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXMS_NAME, &doxmMap);
461     //Oxm -- not Mandatory
462     if (CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
463     {
464         CborValue oxm;
465         cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmLen);
466         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName array Length.");
467         VERIFY_SUCCESS(TAG, doxm->oxmLen != 0, ERROR);
468
469         doxm->oxm = (OicSecOxm_t *)OICCalloc(doxm->oxmLen, sizeof(*doxm->oxm));
470         VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
471
472         cborFindResult = cbor_value_enter_container(&doxmMap, &oxm);
473         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmName Array.")
474
475         int i = 0;
476         while (cbor_value_is_valid(&oxm) && cbor_value_is_integer(&oxm))
477         {
478             int tmp;
479
480             cborFindResult = cbor_value_get_int(&oxm, &tmp);
481             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName Value")
482             doxm->oxm[i++] = (OicSecOxm_t)tmp;
483             cborFindResult = cbor_value_advance(&oxm);
484             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmName.")
485         }
486
487         if (roParsed)
488         {
489             *roParsed = true;
490         }
491     }
492     else
493     {
494         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
495         doxm->oxm = (OicSecOxm_t *) OICCalloc(gDoxm->oxmLen, sizeof(*doxm->oxm));
496         VERIFY_NON_NULL(TAG, doxm->oxm, ERROR);
497         doxm->oxmLen = gDoxm->oxmLen;
498         for (size_t i = 0; i < gDoxm->oxmLen; i++)
499         {
500             doxm->oxm[i] = gDoxm->oxm[i];
501         }
502     }
503
504     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OXM_SEL_NAME, &doxmMap);
505     if (CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
506     {
507         int oxmSel;
508
509         cborFindResult = cbor_value_get_int(&doxmMap, &oxmSel);
510         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sel Name Value.")
511         doxm->oxmSel = (OicSecOxm_t)oxmSel;
512     }
513     else // PUT/POST JSON may not have oxmsel so set it to the gDoxm->oxmSel
514     {
515         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
516         doxm->oxmSel = gDoxm->oxmSel;
517     }
518
519     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_SUPPORTED_CRED_TYPE_NAME, &doxmMap);
520     if (CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
521     {
522         int sct;
523
524         cborFindResult = cbor_value_get_int(&doxmMap, &sct);
525         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sct Name Value.")
526         doxm->sct = (OicSecCredType_t)sct;
527
528         if (roParsed)
529         {
530             *roParsed = true;
531         }
532     }
533     else // PUT/POST JSON may not have sct so set it to the gDoxm->sct
534     {
535         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
536         doxm->sct = gDoxm->sct;
537     }
538
539     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_OWNED_NAME, &doxmMap);
540     if (CborNoError == cborFindResult && cbor_value_is_boolean(&doxmMap))
541     {
542         cborFindResult = cbor_value_get_boolean(&doxmMap, &doxm->owned);
543         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owned Value.")
544     }
545     else // PUT/POST JSON may not have owned so set it to the gDomx->owned
546     {
547         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
548         doxm->owned = gDoxm->owned;
549     }
550
551     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVICE_ID_NAME, &doxmMap);
552     if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
553     {
554         cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
555         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Device Id Value.");
556         ret = ConvertStrToUuid(strUuid , &doxm->deviceID);
557         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
558         OICFree(strUuid);
559         strUuid  = NULL;
560     }
561     else
562     {
563         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
564         memcpy(doxm->deviceID.id, &gDoxm->deviceID.id, sizeof(doxm->deviceID.id));
565     }
566
567     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_DEVOWNERID_NAME, &doxmMap);
568     if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
569     {
570         cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
571         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owner Value.");
572         ret = ConvertStrToUuid(strUuid , &doxm->owner);
573         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
574         OICFree(strUuid);
575         strUuid  = NULL;
576     }
577     else
578     {
579         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
580         memcpy(doxm->owner.id, gDoxm->owner.id, sizeof(doxm->owner.id));
581     }
582
583 #ifdef MULTIPLE_OWNER
584     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_MOM_NAME, &doxmMap);
585     if(CborNoError == cborFindResult && cbor_value_is_integer(&doxmMap))
586     {
587         int mode = 0;
588         cborFindResult = cbor_value_get_int(&doxmMap, &mode);
589         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding mom Name Value.")
590         if(NULL == doxm->mom)
591         {
592             doxm->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
593             VERIFY_NON_NULL(TAG, doxm->mom, ERROR);
594         }
595         doxm->mom->mode = (OicSecMomType_t)mode;
596     }
597     else if(NULL != gDoxm && NULL != gDoxm->mom)
598     {
599         // PUT/POST JSON may not have 'mom' so set it to the gDomx->mom
600         if(NULL == doxm->mom)
601         {
602             doxm->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
603             VERIFY_NON_NULL(TAG, doxm->mom, ERROR);
604         }
605         doxm->mom->mode = gDoxm->mom->mode;
606     }
607
608     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_SUBOWNERID_NAME, &doxmMap);
609     if(CborNoError == cborFindResult && cbor_value_is_array(&doxmMap))
610     {
611         size_t subOwnerLen = 0;
612         CborValue subOwnerCbor;
613         cborFindResult = cbor_value_get_array_length(&doxmMap, &subOwnerLen);
614         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SubOwner array Length.");
615         VERIFY_SUCCESS(TAG, 0 != subOwnerLen, ERROR);
616
617         cborFindResult = cbor_value_enter_container(&doxmMap, &subOwnerCbor);
618         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering SubOwner Array.")
619
620         while (cbor_value_is_valid(&subOwnerCbor) && cbor_value_is_text_string(&subOwnerCbor))
621         {
622             OCStackResult convertRes = OC_STACK_ERROR;
623             OicSecSubOwner_t* subOwner = NULL;
624             char* strUuid = NULL;
625             size_t uuidLen = 0;
626
627             cborFindResult = cbor_value_dup_text_string(&subOwnerCbor, &strUuid, &uuidLen, NULL);
628             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding SubOwnerId Value");
629
630             subOwner = (OicSecSubOwner_t*)OICCalloc(1, sizeof(OicSecSubOwner_t));
631             VERIFY_NON_NULL(TAG, subOwner, ERROR);
632
633             convertRes = ConvertStrToUuid(strUuid, &subOwner->uuid);
634             VERIFY_SUCCESS(TAG, OC_STACK_OK == convertRes, ERROR);
635             subOwner->status = MOT_STATUS_DONE;
636             LL_APPEND(doxm->subOwners, subOwner);
637
638             cborFindResult = cbor_value_advance(&subOwnerCbor);
639             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing SubOwnerId.")
640         }
641     }
642     else if(NULL != gDoxm && NULL != gDoxm->subOwners)
643     {
644         // PUT/POST JSON may not have 'subOwners' so set it to the gDomx->subOwners
645         OicSecSubOwner_t* subOwnerItor = NULL;
646         LL_FOREACH(gDoxm->subOwners, subOwnerItor)
647         {
648             OicSecSubOwner_t* subOwnerId = (OicSecSubOwner_t*)OICCalloc(1, sizeof(OicSecSubOwner_t));
649             VERIFY_NON_NULL(TAG, subOwnerId, ERROR);
650
651             memcpy(&subOwnerId->uuid, &subOwnerItor->uuid, sizeof(OicUuid_t));
652             subOwnerId->status = MOT_STATUS_DONE;
653
654             LL_APPEND(doxm->subOwners, subOwnerId);
655         }
656     }
657 #endif //MULTIPLE_OWNER
658
659     cborFindResult = cbor_value_map_find_value(&doxmCbor, OIC_JSON_ROWNERID_NAME, &doxmMap);
660     if (CborNoError == cborFindResult && cbor_value_is_text_string(&doxmMap))
661     {
662         cborFindResult = cbor_value_dup_text_string(&doxmMap, &strUuid , &len, NULL);
663         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding ROwner Value.");
664         ret = ConvertStrToUuid(strUuid , &doxm->rownerID);
665         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
666         OICFree(strUuid);
667         strUuid  = NULL;
668     }
669     else
670     {
671         VERIFY_NON_NULL(TAG, gDoxm, ERROR);
672         memcpy(doxm->rownerID.id, gDoxm->rownerID.id, sizeof(doxm->rownerID.id));
673     }
674
675     *secDoxm = doxm;
676     ret = OC_STACK_OK;
677
678 exit:
679     if (CborNoError != cborFindResult)
680     {
681         OIC_LOG (ERROR, TAG, "CBORPayloadToDoxm failed!!!");
682         DeleteDoxmBinData(doxm);
683         doxm = NULL;
684         *secDoxm = NULL;
685         ret = OC_STACK_ERROR;
686     }
687     return ret;
688 }
689
690 /**
691  * @todo document this function including why code might need to call this.
692  * The current suspicion is that it's not being called as much as it should.
693  */
694 static bool UpdatePersistentStorage(OicSecDoxm_t * doxm)
695 {
696     bool bRet = false;
697
698     if (NULL != doxm)
699     {
700         // Convert Doxm data into CBOR for update to persistent storage
701         uint8_t *payload = NULL;
702         size_t size = 0;
703         OCStackResult res = DoxmToCBORPayload(doxm, &payload, &size, false);
704         if (payload && (OC_STACK_OK == res)
705             && (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, payload, size)))
706         {
707                 bRet = true;
708         }
709         OICFree(payload);
710     }
711     else
712     {
713         if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, NULL, 0))
714         {
715                 bRet = true;
716         }
717     }
718
719     return bRet;
720 }
721
722 static bool ValidateQuery(const char * query)
723 {
724     // Send doxm resource data if the state of doxm resource
725     // matches with the query parameters.
726     // else send doxm resource data as NULL
727     // TODO Remove this check and rely on Policy Engine
728     // and Provisioning Mode to enforce provisioning-state
729     // access rules. Eventually, the PE and PM code will
730     // not send a request to the /doxm Entity Handler at all
731     // if it should not respond.
732     OIC_LOG (DEBUG, TAG, "In ValidateQuery");
733     if(NULL == gDoxm)
734     {
735         return false;
736     }
737
738     bool bOwnedQry = false;         // does querystring contains 'owned' query ?
739     bool bOwnedMatch = false;       // does 'owned' query value matches with doxm.owned status?
740     bool bDeviceIDQry = false;      // does querystring contains 'deviceid' query ?
741     bool bDeviceIDMatch = false;    // does 'deviceid' query matches with doxm.deviceid ?
742     bool bInterfaceQry = false;      // does querystring contains 'if' query ?
743     bool bInterfaceMatch = false;    // does 'if' query matches with oic.if.baseline ?
744 #ifdef MULTIPLE_OWNER
745     bool bMotMatch = false;       // does 'mom' query value is not '0' && does query value matches with doxm.owned status?
746 #endif //MULTIPLE_OWNER
747
748     OicParseQueryIter_t parseIter = {.attrPos = NULL};
749
750     ParseQueryIterInit((unsigned char*)query, &parseIter);
751
752     while (GetNextQuery(&parseIter))
753     {
754         if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
755         {
756             bOwnedQry = true;
757             if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
758                     (gDoxm->owned))
759             {
760                 bOwnedMatch = true;
761             }
762             else if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_FALSE, parseIter.valLen) == 0)
763                     && (!gDoxm->owned))
764             {
765                 bOwnedMatch = true;
766             }
767         }
768
769 #ifdef MULTIPLE_OWNER
770         if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_MOM_NAME, strlen(OIC_JSON_MOM_NAME)) == 0)
771         {
772             OicSecMomType_t momMode = (OicSecMomType_t)(parseIter.valPos[0] - CHAR_ZERO);
773             if(NULL != gDoxm->mom && momMode != gDoxm->mom->mode)
774             {
775                 if(GetNextQuery(&parseIter))
776                 {
777                     if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
778                     {
779                         if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
780                                 (gDoxm->owned))
781                         {
782                             bMotMatch = true;
783                         }
784                     }
785                 }
786             }
787             return bMotMatch;
788         }
789 #endif //MULTIPLE_OWNER
790
791         if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_DEVICE_ID_NAME, parseIter.attrLen) == 0)
792         {
793             bDeviceIDQry = true;
794             OicUuid_t subject = {.id={0}};
795
796             memcpy(subject.id, parseIter.valPos, parseIter.valLen);
797             if (0 == memcmp(&gDoxm->deviceID.id, &subject.id, sizeof(gDoxm->deviceID.id)))
798             {
799                 bDeviceIDMatch = true;
800             }
801         }
802
803         if (strncasecmp((char *)parseIter.attrPos, OC_RSRVD_INTERFACE, parseIter.attrLen) == 0)
804         {
805             bInterfaceQry = true;
806             if ((strncasecmp((char *)parseIter.valPos, OC_RSRVD_INTERFACE_DEFAULT, parseIter.valLen) == 0))
807             {
808                 bInterfaceMatch = true;
809             }
810             return (bInterfaceQry ? bInterfaceMatch: true);
811         }
812     }
813
814     return ((bOwnedQry ? bOwnedMatch : true) &&
815             (bDeviceIDQry ? bDeviceIDMatch : true));
816 }
817
818 static OCEntityHandlerResult HandleDoxmGetRequest (const OCEntityHandlerRequest * ehRequest)
819 {
820     OCEntityHandlerResult ehRet = OC_EH_OK;
821
822     OIC_LOG(DEBUG, TAG, "Doxm EntityHandle processing GET request");
823
824     //Checking if Get request is a query.
825     if (ehRequest->query)
826     {
827         OIC_LOG_V(DEBUG,TAG,"query:%s",ehRequest->query);
828         OIC_LOG(DEBUG, TAG, "HandleDoxmGetRequest processing query");
829         if (!ValidateQuery(ehRequest->query))
830         {
831             ehRet = OC_EH_ERROR;
832         }
833     }
834
835     /*
836      * For GET or Valid Query request return doxm resource CBOR payload.
837      * For non-valid query return NULL json payload.
838      * A device will 'always' have a default Doxm, so DoxmToCBORPayload will
839      * return valid doxm resource json.
840      */
841     uint8_t *payload = NULL;
842     size_t size = 0;
843
844     if (ehRet == OC_EH_OK)
845     {
846         if (OC_STACK_OK != DoxmToCBORPayload(gDoxm, &payload, &size, false))
847         {
848             OIC_LOG(WARNING, TAG, "DoxmToCBORPayload failed in HandleDoxmGetRequest");
849         }
850     }
851
852     OIC_LOG(DEBUG, TAG, "Send payload for doxm GET request");
853     OIC_LOG_BUFFER(DEBUG, TAG, payload, size);
854
855     // Send response payload to request originator
856     ehRet = ((SendSRMResponse(ehRequest, ehRet, payload, size)) == OC_STACK_OK) ?
857                    OC_EH_OK : OC_EH_ERROR;
858
859     OICFree(payload);
860
861     return ehRet;
862 }
863
864 static void updateWriteableProperty(const OicSecDoxm_t* src, OicSecDoxm_t* dst)
865 {
866     if(src && dst)
867    {
868         // update oxmsel
869         dst->oxmSel = src->oxmSel;
870
871         //update owner
872         memcpy(&(dst->owner), &(src->owner), sizeof(OicUuid_t));
873
874         //update rowner
875         memcpy(&(dst->rownerID), &(src->rownerID), sizeof(OicUuid_t));
876
877         //update deviceuuid
878         memcpy(&(dst->deviceID), &(src->deviceID), sizeof(OicUuid_t));
879
880         //Update owned status
881         if(dst->owned != src->owned)
882         {
883             dst->owned = src->owned;
884         }
885
886 #ifdef MULTIPLE_OWNER
887         if(src->mom)
888         {
889             OIC_LOG(DEBUG, TAG, "dectected 'mom' property");
890             if(NULL == dst->mom)
891             {
892                 dst->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
893                 if(NULL != dst->mom)
894                 {
895                     dst->mom->mode = src->mom->mode;
896                 }
897             }
898         }
899 #endif //MULTIPLE_OWNER
900     }
901 }
902
903 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
904 #ifdef MULTIPLE_OWNER
905 /**
906  * Internal function to get number of sub-owner
907  */
908 static size_t GetSubOwnerSize()
909 {
910     OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
911
912     size_t numberOfSubOwner = 0;
913
914     if (gDoxm && gDoxm->subOwners)
915     {
916         OicSecSubOwner_t* subowner = NULL;
917         LL_FOREACH(gDoxm->subOwners, subowner)
918         {
919             numberOfSubOwner++;
920         }
921     }
922
923     OIC_LOG_V(DEBUG, TAG, "Numer of registered sub-owner=%d", numberOfSubOwner);
924     OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
925
926     return numberOfSubOwner;
927 }
928
929 /**
930  * Callback function to handle MOT DTLS handshake result.
931  * @param[out]   endpoint           remote device information.
932  * @param[out]   errorInfo        CA Error information.
933  */
934 void MultipleOwnerDTLSHandshakeCB(const CAEndpoint_t *endpoint,
935                                 const CAErrorInfo_t *errorInfo)
936 {
937     OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
938     if (!endpoint || !errorInfo)
939     {
940         OIC_LOG(ERROR, TAG, "Invalid param");
941         return;
942     }
943
944     if (!gDoxm)
945     {
946         OIC_LOG_V(ERROR, TAG, "%s: gDoxm is NULL", __func__);
947         return;
948     }
949
950     if ((CA_STATUS_OK == errorInfo->result) && (true == gDoxm->owned)
951         && (OIC_PRECONFIG_PIN == gDoxm->oxmSel) && (NULL != gDoxm->mom)
952         && (OIC_MULTIPLE_OWNER_DISABLE != gDoxm->mom->mode) && (CA_ADAPTER_TCP != endpoint->adapter))
953     {
954         OIC_LOG_V(INFO, TAG, "DTLS session established for sub-owner authentication : (%s:%d)",
955                   endpoint->addr, endpoint->port);
956
957         const CASecureEndpoint_t* authenticatedSubOwnerInfo = CAGetSecureEndpointData(endpoint);
958         if (authenticatedSubOwnerInfo)
959         {
960             if (0 == memcmp(authenticatedSubOwnerInfo->identity.id, gDoxm->owner.id,
961                             authenticatedSubOwnerInfo->identity.id_length))
962             {
963                 OIC_LOG(WARNING, TAG, "Super owner tried MOT, this request will be ignored.");
964                 return;
965             }
966
967             OicSecSubOwner_t* subOwnerInst = NULL;
968             LL_FOREACH(gDoxm->subOwners, subOwnerInst)
969             {
970                 if(0 == memcmp(subOwnerInst->uuid.id,
971                                authenticatedSubOwnerInfo->identity.id,
972                                authenticatedSubOwnerInfo->identity.id_length))
973                 {
974                     break;
975                 }
976             }
977
978             if (NULL == subOwnerInst)
979             {
980                 subOwnerInst = (OicSecSubOwner_t*)OICCalloc(1, sizeof(OicSecSubOwner_t));
981                 if (subOwnerInst)
982                 {
983                     char* strUuid = NULL;
984                     if (OC_STACK_OK != ConvertUuidToStr(&subOwnerInst->uuid, &strUuid))
985                     {
986                         OIC_LOG(WARNING, TAG, "ConvertUuidToStr error");
987                     }
988                     OIC_LOG_V(DEBUG, TAG, "Adding New SubOwner(%s)", strUuid);
989
990                     if (gMaxSubOwnerSize > GetSubOwnerSize())
991                     {
992                         memcpy(subOwnerInst->uuid.id, authenticatedSubOwnerInfo->identity.id,
993                                authenticatedSubOwnerInfo->identity.id_length);
994                         LL_APPEND(gDoxm->subOwners, subOwnerInst);
995                         if (!UpdatePersistentStorage(gDoxm))
996                         {
997                             OIC_LOG(ERROR, TAG, "Failed to register SubOwner UUID into Doxm");
998                         }
999                     }
1000                     else
1001                     {
1002                         OIC_LOG_V(ERROR, TAG, "Number of sub-owner exceeded : (MAX SIZE=%d)", gMaxSubOwnerSize);
1003
1004                         //Close DTLS session
1005                         if (CA_STATUS_OK != CAcloseSslSession(endpoint))
1006                         {
1007                             OIC_LOG_V(ERROR, TAG, "CAcloseSslSession error for [%s:%d]", endpoint->addr, endpoint->port);
1008                         }
1009
1010                         //Remove credential
1011                         if (OC_STACK_RESOURCE_DELETED != RemoveCredential(&subOwnerInst->uuid))
1012                         {
1013                             OIC_LOG_V(ERROR, TAG, "RemoveCredential error for [%s]", strUuid);
1014                         }
1015
1016                         // TODO: How to send error to client side?
1017                     }
1018
1019                     OICFree(strUuid);
1020                 }
1021             }
1022         }
1023     }
1024
1025     if(CA_STATUS_OK != CAregisterPskCredentialsHandler(GetDtlsPskCredentials))
1026     {
1027         OIC_LOG(WARNING, TAG, "Failed to revert the DTLS credential handler");
1028     }
1029
1030     OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
1031 }
1032 #endif //MULTIPLE_OWNER
1033 #endif // defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1034
1035 /**
1036  * Function to validate oxmsel with oxms.
1037  *
1038  * @param[in] supportedMethods   Array of supported methods
1039  * @param[in] numberOfMethods   number of supported methods
1040  * @param[out]  selectedMethod         Selected methods
1041  * @return  TRUE on success
1042  */
1043 static bool ValidateOxmsel(const OicSecOxm_t *supportedMethods,
1044         size_t numberOfMethods, OicSecOxm_t *selectedMethod)
1045 {
1046     bool isValidOxmsel = false;
1047
1048     OIC_LOG(DEBUG, TAG, "IN ValidateOxmsel");
1049     if (numberOfMethods == 0 || !supportedMethods)
1050     {
1051         OIC_LOG(WARNING, TAG, "Could not find a supported OxM.");
1052         return isValidOxmsel;
1053     }
1054
1055     for (size_t i = 0; i < numberOfMethods; i++)
1056     {
1057             if (*selectedMethod  == supportedMethods[i])
1058             {
1059                 isValidOxmsel = true;
1060                 break;
1061             }
1062     }
1063     if (!isValidOxmsel)
1064     {
1065         OIC_LOG(ERROR, TAG, "Not allowed Oxmsel.");
1066         return isValidOxmsel;
1067     }
1068
1069     OIC_LOG(DEBUG, TAG, "OUT ValidateOxmsel");
1070
1071     return isValidOxmsel;
1072 }
1073
1074 static OCEntityHandlerResult HandleDoxmPostRequest(OCEntityHandlerRequest * ehRequest)
1075 {
1076     OIC_LOG (DEBUG, TAG, "Doxm EntityHandle  processing POST request");
1077     OCEntityHandlerResult ehRet = OC_EH_ERROR;
1078     OicUuid_t emptyOwner = {.id = {0} };
1079     static uint16_t previousMsgId = 0;
1080     bool isDuplicatedMsg = false;
1081
1082     /*
1083      * Convert CBOR Doxm data into binary. This will also validate
1084      * the Doxm data received.
1085      */
1086     OicSecDoxm_t *newDoxm = NULL;
1087
1088     if (ehRequest->payload)
1089     {
1090         uint8_t *payload = ((OCSecurityPayload *)ehRequest->payload)->securityData;
1091         size_t size = ((OCSecurityPayload *)ehRequest->payload)->payloadSize;
1092         bool roParsed = false;
1093         OCStackResult res = CBORPayloadToDoxmBin(payload, size, &newDoxm, &roParsed);
1094         if (newDoxm && OC_STACK_OK == res)
1095         {
1096             /*
1097              * message ID is supported for CoAP over UDP only according to RFC 7252
1098              * So we should check message ID to prevent duplicate request handling in case of OC_ADAPTER_IP.
1099              * In case of other transport adapter, duplicate message check is not required.
1100              */
1101             if (OC_ADAPTER_IP == ehRequest->devAddr.adapter &&
1102                  previousMsgId == ehRequest->messageID)
1103             {
1104                 isDuplicatedMsg = true;
1105             }
1106
1107             if (isDuplicatedMsg && ehRequest->messageID == gConfirmMsgId)
1108             {
1109                 if (CONFIRM_STATE_WAIT == gConfirmState)
1110                 {
1111                     OIC_LOG(DEBUG, TAG, "Confirm callback already invoked.");
1112                     OIC_LOG(DEBUG, TAG, "This request will be ignored.");
1113                     DeleteDoxmBinData(newDoxm);
1114                     return OC_EH_OK;
1115                 }
1116                 else
1117                 {
1118                     OIC_LOG_V(DEBUG, TAG, "Confirm request already done, Confirm Result = %s", (CONFIRM_STATE_ACCEPTED == gConfirmState ? "ACCEPTED" : "DENIED"));
1119                     ehRet = (CONFIRM_STATE_ACCEPTED == gConfirmState ? OC_EH_OK : OC_EH_NOT_ACCEPTABLE);
1120                     goto exit;
1121                 }
1122             }
1123
1124             // Check request on RO property
1125             if (true == roParsed)
1126             {
1127                 OIC_LOG(ERROR, TAG, "Not acceptable request because of read-only propertys");
1128                 ehRet = OC_EH_NOT_ACCEPTABLE;
1129                 goto exit;
1130             }
1131
1132             VERIFY_NON_NULL(TAG, gDoxm, ERROR);
1133
1134             // in owned state
1135             if (true == gDoxm->owned)
1136             {
1137                 if (false == ValidateOxmsel(gDoxm->oxm, gDoxm->oxmLen, &newDoxm->oxmSel))
1138                 {
1139                     OIC_LOG(ERROR, TAG, "Not acceptable request because oxmsel does not support on Server");
1140                     ehRet = OC_EH_NOT_ACCEPTABLE;
1141                     goto exit;
1142                 }
1143                 //Update gDoxm based on newDoxm
1144                 updateWriteableProperty(newDoxm, gDoxm);
1145
1146 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1147 #ifdef MULTIPLE_OWNER
1148                 //handle mom
1149                 if(gDoxm->mom)
1150                 {
1151                     if(OIC_MULTIPLE_OWNER_DISABLE != gDoxm->mom->mode)
1152                     {
1153                         CAResult_t caRes = CA_STATUS_FAILED;
1154                         if(OIC_PRECONFIG_PIN == gDoxm->oxmSel || OIC_RANDOM_DEVICE_PIN == gDoxm->oxmSel)
1155                         {
1156                             caRes = CAEnableAnonECDHCipherSuite(false);
1157                             VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1158                             OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1159
1160                             caRes = CASelectCipherSuite((uint16_t)MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, ehRequest->devAddr.adapter);
1161                             VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1162                             OIC_LOG(INFO, TAG, "ECDHE_PSK CipherSuite will be used for MOT");
1163
1164                             //Set the device id to derive temporal PSK
1165                             SetUuidForPinBasedOxm(&gDoxm->deviceID);
1166                         }
1167                         else
1168                         {
1169                             OIC_LOG(WARNING, TAG, "Unsupported OxM for Multiple Ownership Transfer.");
1170                         }
1171
1172                         CAregisterSslHandshakeCallback(MultipleOwnerDTLSHandshakeCB);
1173                     }
1174                     else
1175                     {
1176                         //if MOM is disabled, revert the DTLS handshake callback
1177                         if(CA_STATUS_OK != CAregisterSslHandshakeCallback(NULL))
1178                         {
1179                             OIC_LOG(WARNING, TAG, "Error while revert the DTLS Handshake Callback.");
1180                         }
1181                     }
1182                 }
1183
1184                 if(newDoxm->subOwners)
1185                 {
1186                     OicSecSubOwner_t* subowner = NULL;
1187                     OicSecSubOwner_t* temp = NULL;
1188
1189                     OIC_LOG(DEBUG, TAG, "dectected 'subowners' property");
1190
1191                     if(gDoxm->subOwners)
1192                     {
1193                         LL_FOREACH_SAFE(gDoxm->subOwners, subowner, temp)
1194                         {
1195                             LL_DELETE(gDoxm->subOwners, subowner);
1196                             OICFree(subowner);
1197                         }
1198                     }
1199
1200                     subowner = NULL;
1201                     temp = NULL;
1202                     LL_FOREACH_SAFE(newDoxm->subOwners, subowner, temp)
1203                     {
1204                         LL_DELETE(newDoxm->subOwners, subowner);
1205                         LL_APPEND(gDoxm->subOwners, subowner);
1206                     }
1207                 }
1208 #endif //MULTIPLE_OWNER
1209 #endif // defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1210
1211                 //Update new state in persistent storage
1212                 if (UpdatePersistentStorage(gDoxm) == true)
1213                 {
1214                     ehRet = OC_EH_OK;
1215                 }
1216                 else
1217                 {
1218                     OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1219                     ehRet = OC_EH_ERROR;
1220                 }
1221                 goto exit;
1222             }
1223
1224             // in unowned state
1225             if ((false == gDoxm->owned) && (false == newDoxm->owned))
1226             {
1227                 if (false == ValidateOxmsel(gDoxm->oxm, gDoxm->oxmLen, &newDoxm->oxmSel))
1228                 {
1229                     OIC_LOG(ERROR, TAG, "Not acceptable request because oxmsel does not support on Server");
1230                     ehRet = OC_EH_NOT_ACCEPTABLE;
1231                     goto exit;
1232                 }
1233
1234 #if defined (__WITH_TLS__) || defined(__WITH_DTLS__)
1235                 if (memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
1236                 {
1237                     InvokeOtmEventHandler(ehRequest->devAddr.addr, ehRequest->devAddr.port,
1238                                           NULL, OIC_OTM_STARTED);
1239                 }
1240 #endif
1241
1242                 if (OIC_JUST_WORKS == newDoxm->oxmSel || OIC_MV_JUST_WORKS == newDoxm->oxmSel)
1243                 {
1244                     /*
1245                      * If current state of the device is un-owned, enable
1246                      * anonymous ECDH cipher in tinyDTLS so that Provisioning
1247                      * tool can initiate JUST_WORKS ownership transfer process.
1248                      */
1249                     if (memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
1250                     {
1251                         gDoxm->oxmSel = newDoxm->oxmSel;
1252                         //Update new state in persistent storage
1253                         if ((UpdatePersistentStorage(gDoxm) == true))
1254                         {
1255                             ehRet = OC_EH_OK;
1256                         }
1257                         else
1258                         {
1259                             OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
1260                             ehRet = OC_EH_ERROR;
1261                             goto exit;
1262                         }
1263                         OIC_LOG (INFO, TAG, "Doxm EntityHandle  enabling AnonECDHCipherSuite");
1264 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1265                         ehRet = (CAEnableAnonECDHCipherSuite(true) == CA_STATUS_OK) ? OC_EH_OK : OC_EH_ERROR;
1266 #endif // __WITH_DTLS__ or __WITH_TLS__
1267                         goto exit;
1268                     }
1269                     else
1270                     {
1271 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1272                         //Save the owner's UUID to derive owner credential
1273                         memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
1274
1275                         // Update new state in persistent storage
1276                         if (true == UpdatePersistentStorage(gDoxm))
1277                         {
1278                             ehRet = OC_EH_OK;
1279                         }
1280                         else
1281                         {
1282                             OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1283                             ehRet = OC_EH_ERROR;
1284                             goto exit;
1285                         }
1286
1287                         /*
1288                          * Disable anonymous ECDH cipher in tinyDTLS since device is now
1289                          * in owned state.
1290                          */
1291                         CAResult_t caRes = CA_STATUS_OK;
1292                         caRes = CAEnableAnonECDHCipherSuite(false);
1293                         VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1294                         OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1295
1296                         //In case of Mutual Verified Just-Works, verify mutualVerifNum
1297                         if (OIC_MV_JUST_WORKS == newDoxm->oxmSel && false == newDoxm->owned &&
1298                             false == isDuplicatedMsg)
1299                         {
1300                             uint8_t preMutualVerifNum[OWNER_PSK_LENGTH_128] = {0};
1301                             uint8_t mutualVerifNum[MUTUAL_VERIF_NUM_LEN] = {0};
1302                             OicUuid_t deviceID = {.id = {0}};
1303
1304                             //Generate mutualVerifNum
1305                             OCServerRequest * request = GetServerRequestUsingHandle(ehRequest->requestHandle);
1306
1307                             char label[LABEL_LEN] = {0};
1308                             snprintf(label, LABEL_LEN, "%s%s", MUTUAL_VERIF_NUM, OXM_MV_JUST_WORKS);
1309                             if (OC_STACK_OK != GetDoxmDeviceID(&deviceID))
1310                             {
1311                                 OIC_LOG(ERROR, TAG, "Error while retrieving Owner's device ID");
1312                                 ehRet = OC_EH_ERROR;
1313                                 goto exit;
1314
1315                             }
1316
1317                             CAResult_t pskRet = CAGenerateOwnerPSK((CAEndpoint_t *)&request->devAddr,
1318                                     (uint8_t *)label,
1319                                     strlen(label),
1320                                     gDoxm->owner.id, sizeof(gDoxm->owner.id),
1321                                     gDoxm->deviceID.id, sizeof(gDoxm->deviceID.id),
1322                                     preMutualVerifNum, OWNER_PSK_LENGTH_128);
1323                             if (CA_STATUS_OK != pskRet)
1324                             {
1325                                 OIC_LOG(WARNING, TAG, "Failed to remove the invaild owner credential");
1326                                 ehRet = OC_EH_ERROR;
1327                                 goto exit;
1328
1329                             }
1330
1331                             memcpy(mutualVerifNum, preMutualVerifNum + OWNER_PSK_LENGTH_128 - sizeof(mutualVerifNum),
1332                                     sizeof(mutualVerifNum));
1333
1334                             gConfirmMsgId = ehRequest->messageID;
1335                             gConfirmState = CONFIRM_STATE_WAIT;
1336                             //Wait for user confirmation
1337                             if (OC_STACK_OK != VerifyOwnershipTransfer(mutualVerifNum, DISPLAY_NUM | USER_CONFIRM))
1338                             {
1339                                 ehRet = OC_EH_NOT_ACCEPTABLE;
1340                                 gConfirmState = CONFIRM_STATE_DENIED;
1341                             }
1342                             else
1343                             {
1344                                 ehRet = OC_EH_OK;
1345                                 gConfirmState = CONFIRM_STATE_ACCEPTED;
1346                             }
1347                         }
1348
1349 #endif // __WITH_DTLS__ or __WITH_TLS__
1350                     }
1351                 }
1352                 else if (OIC_RANDOM_DEVICE_PIN == newDoxm->oxmSel)
1353                 {
1354                     /*
1355                      * If current state of the device is un-owned, enable
1356                      * anonymous ECDH cipher in tinyDTLS so that Provisioning
1357                      * tool can initiate JUST_WORKS ownership transfer process.
1358                      */
1359                     if(memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
1360                     {
1361                         gDoxm->oxmSel = newDoxm->oxmSel;
1362                         //Update new state in persistent storage
1363                         if ((UpdatePersistentStorage(gDoxm) == true))
1364                         {
1365                             ehRet = OC_EH_OK;
1366                         }
1367                         else
1368                         {
1369                             OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
1370                             ehRet = OC_EH_ERROR;
1371                         }
1372
1373 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1374                         CAResult_t caRes = CA_STATUS_OK;
1375
1376                         caRes = CAEnableAnonECDHCipherSuite(false);
1377                         VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1378                         OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1379
1380                         caRes = CASelectCipherSuite(MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256,
1381                                                     ehRequest->devAddr.adapter);
1382                         VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1383
1384                         if (!isDuplicatedMsg)
1385                         {
1386                             char ranPin[OXM_RANDOM_PIN_MAX_SIZE + 1] = {0};
1387                             if (OC_STACK_OK == GeneratePin(ranPin, sizeof(ranPin)))
1388                             {
1389                                 //Set the device id to derive temporal PSK
1390                                 SetUuidForPinBasedOxm(&gDoxm->deviceID);
1391
1392                                 /**
1393                                  * Since PSK will be used directly by DTLS layer while PIN based ownership transfer,
1394                                  * Credential should not be saved into SVR.
1395                                  * For this reason, use a temporary get_psk_info callback to random PIN OxM.
1396                                  */
1397                                 caRes = CAregisterPskCredentialsHandler(GetDtlsPskForRandomPinOxm);
1398                                 VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1399                                 ehRet = OC_EH_OK;
1400                             }
1401                             else
1402                             {
1403                                 OIC_LOG(ERROR, TAG, "Failed to generate random PIN");
1404                                 ehRet = OC_EH_ERROR;
1405                             }
1406                         }
1407 #endif // __WITH_DTLS__ or __WITH_TLS__
1408                     }
1409 #if defined(__WITH_DTLS__) || defined(__WITH_TLS__)
1410                     else
1411                     {
1412                         //Save the owner's UUID to derive owner credential
1413                         memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
1414
1415                         // In case of random-pin based OTM, close the PIN display if callback is registered.
1416                         if (!isDuplicatedMsg)
1417                         {
1418                             ClosePinDisplay();
1419                         }
1420
1421                         //Update new state in persistent storage
1422                         if (UpdatePersistentStorage(gDoxm) == true)
1423                         {
1424                             ehRet = OC_EH_OK;
1425                         }
1426                         else
1427                         {
1428                             OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1429                             ehRet = OC_EH_ERROR;
1430                         }
1431                     }
1432 #endif // __WITH_DTLS__ or __WITH_TLS__
1433                 }
1434 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1435                 else if (OIC_MANUFACTURER_CERTIFICATE ==  newDoxm->oxmSel || OIC_CON_MFG_CERT == newDoxm->oxmSel)
1436                 {
1437                     //Get user confirmation
1438                     if (false == newDoxm->owned &&
1439                         false == isDuplicatedMsg &&
1440                         memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) != 0)
1441                     {
1442                         gConfirmMsgId = ehRequest->messageID;
1443                         gConfirmState = CONFIRM_STATE_WAIT;
1444                         if (OC_STACK_OK != VerifyOwnershipTransfer(NULL, USER_CONFIRM))
1445                         {
1446                             ehRet = OC_EH_NOT_ACCEPTABLE;
1447                             gConfirmState = CONFIRM_STATE_DENIED;
1448                             goto exit;
1449                         }
1450                         else
1451                         {
1452                             ehRet = OC_EH_OK;
1453                             gConfirmState = CONFIRM_STATE_ACCEPTED;
1454                         }
1455                     }
1456
1457                     //Save the owner's UUID to derive owner credential
1458                     memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
1459                     gDoxm->oxmSel = newDoxm->oxmSel;
1460                     //Update new state in persistent storage
1461                     if (UpdatePersistentStorage(gDoxm))
1462                     {
1463                         ehRet = OC_EH_OK;
1464                     }
1465                     else
1466                     {
1467                         OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
1468                         ehRet = OC_EH_ERROR;
1469                     }
1470                     CAResult_t caRes = CAEnableAnonECDHCipherSuite(false);
1471                     VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1472                     OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1473
1474                     //Unset pre-selected ciphersuite, if any
1475                     caRes = CASelectCipherSuite(0, ehRequest->devAddr.adapter);
1476                     VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1477                     OIC_LOG(DEBUG, TAG, "No ciphersuite preferred");
1478
1479                     VERIFY_SUCCESS(TAG, CA_STATUS_OK == CAregisterPkixInfoHandler(GetManufacturerPkixInfo), ERROR);
1480                     VERIFY_SUCCESS(TAG, CA_STATUS_OK == CAregisterGetCredentialTypesHandler(InitManufacturerCipherSuiteList), ERROR);
1481                 }
1482 #endif // __WITH_DTLS__ or __WITH_TLS__
1483             }
1484
1485             /*
1486              * When current state of the device is un-owned and Provisioning
1487              * Tool is attempting to change the state to 'Owned' with a
1488              * qualified value for the field 'Owner'
1489              */
1490             if ((false == gDoxm->owned) && (true == newDoxm->owned) &&
1491                     (memcmp(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t)) == 0))
1492             {
1493                 //Change the SVR's resource owner as owner device.
1494                 OCStackResult ownerRes = SetAclRownerId(&gDoxm->owner);
1495                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1496                 {
1497                     ehRet = OC_EH_ERROR;
1498                     goto exit;
1499                 }
1500                 ownerRes = SetAmaclRownerId(&gDoxm->owner);
1501                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1502                 {
1503                     ehRet = OC_EH_ERROR;
1504                     goto exit;
1505                 }
1506                 ownerRes = SetCredRownerId(&gDoxm->owner);
1507                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1508                 {
1509                     ehRet = OC_EH_ERROR;
1510                     goto exit;
1511                 }
1512                 ownerRes = SetPstatRownerId(&gDoxm->owner);
1513                 if(OC_STACK_OK != ownerRes && OC_STACK_NO_RESOURCE != ownerRes)
1514                 {
1515                     ehRet = OC_EH_ERROR;
1516                     goto exit;
1517                 }
1518
1519                 gDoxm->owned = true;
1520                 memcpy(&gDoxm->rownerID, &gDoxm->owner, sizeof(OicUuid_t));
1521
1522                 // Update new state in persistent storage
1523                 if (UpdatePersistentStorage(gDoxm))
1524                 {
1525                     //Update default ACE of security resource to prevent anonymous user access.
1526                     if(OC_STACK_OK == UpdateDefaultSecProvACE())
1527                     {
1528                         ehRet = OC_EH_OK;
1529                     }
1530                     else
1531                     {
1532                         OIC_LOG(ERROR, TAG, "Failed to remove default ACL for security provisioning");
1533                         ehRet = OC_EH_ERROR;
1534                     }
1535                 }
1536                 else
1537                 {
1538                     OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
1539                     ehRet = OC_EH_ERROR;
1540                 }
1541 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1542                 if (OIC_MANUFACTURER_CERTIFICATE == gDoxm->oxmSel ||
1543                                             OIC_CON_MFG_CERT== gDoxm->oxmSel)
1544                 {
1545                     CAregisterPkixInfoHandler(GetPkixInfo);
1546                     CAregisterGetCredentialTypesHandler(InitCipherSuiteList);
1547                 }
1548
1549                 InvokeOtmEventHandler(ehRequest->devAddr.addr, ehRequest->devAddr.port,
1550                                       &gDoxm->owner, OIC_OTM_DONE);
1551 #endif // __WITH_DTLS__ or __WITH_TLS__
1552             }
1553         }
1554     }
1555
1556 exit:
1557     if(OC_EH_OK != ehRet)
1558     {
1559         /*
1560          * If some error is occured while ownership transfer,
1561          * ownership transfer related resource should be revert back to initial status.
1562         */
1563         if(gDoxm)
1564         {
1565             if(!gDoxm->owned)
1566             {
1567                 OIC_LOG(WARNING, TAG, "The operation failed during handle DOXM request");
1568
1569                 if (!isDuplicatedMsg)
1570                 {
1571 #if defined (__WITH_TLS__) || defined(__WITH_DTLS__)
1572                     InvokeOtmEventHandler(ehRequest->devAddr.addr, ehRequest->devAddr.port,
1573                                           NULL, OIC_OTM_ERROR);
1574 #endif
1575                     RestoreDoxmToInitState();
1576                     RestorePstatToInitState();
1577                     OIC_LOG(WARNING, TAG, "DOXM will be reverted.");
1578                 }
1579             }
1580         }
1581         else
1582         {
1583             OIC_LOG(ERROR, TAG, "Invalid DOXM resource.");
1584         }
1585     }
1586
1587     previousMsgId = ehRequest->messageID;
1588
1589 #if defined (__WITH_TLS__) || defined(__WITH_DTLS__)
1590     CAEndpoint_t peer = {0};
1591     OCDevAddr devAddr =  ehRequest->devAddr;
1592
1593     memcpy(&peer.addr, &devAddr.addr, sizeof(peer.addr));
1594     peer.port = devAddr.port;
1595     peer.adapter = (CATransportAdapter_t)devAddr.adapter;
1596
1597     if ((devAddr.flags & OC_FLAG_SECURE) && (false == CAIsExistSslPeer(&peer)))
1598     {
1599         OIC_LOG_V(WARNING, TAG, "Not Exist Peer");
1600         ehRet = OC_EH_OK;
1601     }
1602     else
1603     {
1604         //Send payload to request originator
1605         ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1606             OC_EH_OK : OC_EH_ERROR;
1607     }
1608 #else
1609     //Send payload to request originator
1610     ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1611         OC_EH_OK : OC_EH_ERROR;
1612 #endif
1613
1614     DeleteDoxmBinData(newDoxm);
1615
1616     return ehRet;
1617 }
1618
1619 #ifdef MULTIPLE_OWNER
1620 static OCEntityHandlerResult HandleDoxmDeleteRequest(const OCEntityHandlerRequest *ehRequest)
1621 {
1622     OIC_LOG(DEBUG, TAG, "Processing DoxmDeleteRequest");
1623
1624     OCEntityHandlerResult ehRet = OC_EH_BAD_REQ;
1625
1626     if (NULL == ehRequest->query)
1627     {
1628         return ehRet;
1629     }
1630
1631     OicParseQueryIter_t parseIter = { .attrPos=NULL };
1632     OicUuid_t subject = {.id={0}};
1633
1634     //Parsing REST query to get the subject
1635     ParseQueryIterInit((unsigned char *)ehRequest->query, &parseIter);
1636     while (GetNextQuery(&parseIter))
1637     {
1638         if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_SUBOWNERID_NAME,
1639                 parseIter.attrLen) == 0)
1640         {
1641             if (0 == strncmp((const char*)parseIter.valPos, WILDCARD_RESOURCE_URI,
1642                              strlen(WILDCARD_RESOURCE_URI)))
1643             {
1644                 if(OC_STACK_RESOURCE_DELETED == RemoveSubOwner(&WILDCARD_SUBJECT_ID))
1645                 {
1646                     ehRet = OC_EH_RESOURCE_DELETED;
1647                 }
1648             }
1649             else
1650             {
1651                 OCStackResult ret = ConvertStrToUuid((const char*)parseIter.valPos, &subject);
1652                 VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
1653
1654                 if(OC_STACK_RESOURCE_DELETED == RemoveSubOwner(&subject))
1655                 {
1656                     ehRet = OC_EH_RESOURCE_DELETED;
1657                 }
1658             }
1659         }
1660     }
1661
1662     //Send response to request originator
1663     ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1664                    OC_EH_OK : OC_EH_ERROR;
1665
1666     return ehRet;
1667 exit:
1668     return OC_EH_ERROR;
1669 }
1670 #endif //MULTIPLE_OWNER
1671
1672 OCEntityHandlerResult DoxmEntityHandler(OCEntityHandlerFlag flag,
1673                                         OCEntityHandlerRequest * ehRequest,
1674                                         void* callbackParam)
1675 {
1676     (void)callbackParam;
1677     OCEntityHandlerResult ehRet = OC_EH_ERROR;
1678
1679     if(NULL == ehRequest)
1680     {
1681         return ehRet;
1682     }
1683
1684     if (flag & OC_REQUEST_FLAG)
1685     {
1686         OIC_LOG(DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
1687
1688         switch (ehRequest->method)
1689         {
1690             case OC_REST_GET:
1691                 ehRet = HandleDoxmGetRequest(ehRequest);
1692                 break;
1693
1694             case OC_REST_POST:
1695                 ehRet = HandleDoxmPostRequest(ehRequest);
1696                 break;
1697
1698 #ifdef MULTIPLE_OWNER
1699             case OC_REST_DELETE:
1700                 ehRet = HandleDoxmDeleteRequest(ehRequest);
1701                 break;
1702 #endif //MULTIPLE_OWNER
1703
1704             default:
1705                 ehRet = ((SendSRMResponse(ehRequest, ehRet, NULL, 0)) == OC_STACK_OK) ?
1706                                OC_EH_OK : OC_EH_ERROR;
1707                 break;
1708         }
1709     }
1710
1711     return ehRet;
1712 }
1713
1714 OCStackResult CreateDoxmResource()
1715 {
1716     OCStackResult ret = OCCreateResource(&gDoxmHandle,
1717                                          OIC_RSRC_TYPE_SEC_DOXM,
1718                                          OC_RSRVD_INTERFACE_DEFAULT,
1719                                          OIC_RSRC_DOXM_URI,
1720                                          DoxmEntityHandler,
1721                                          NULL,
1722                                          OC_SECURE |
1723                                          OC_DISCOVERABLE);
1724
1725     if (OC_STACK_OK != ret)
1726     {
1727         OIC_LOG (FATAL, TAG, "Unable to instantiate Doxm resource");
1728         DeInitDoxmResource();
1729     }
1730     return ret;
1731 }
1732
1733 /**
1734  * Checks if DeviceID is generated during provisioning for the new device.
1735  * If DeviceID is NULL then generates the new DeviceID.
1736  * Once DeviceID is assigned to the device it does not change for the lifetime of the device.
1737  */
1738 static OCStackResult CheckDeviceID()
1739 {
1740     OIC_LOG_V(DEBUG, TAG, "IN: %s", __func__);
1741
1742     OCStackResult ret = OC_STACK_ERROR;
1743     bool validId = false;
1744
1745     if (!gDoxm)
1746     {
1747         OIC_LOG_V(ERROR, TAG, "%s: gDoxm is NULL", __func__);
1748         return OC_STACK_INVALID_PARAM;
1749     }
1750
1751     for (uint8_t i = 0; i < UUID_LENGTH; i++)
1752     {
1753         if (gDoxm->deviceID.id[i] != 0)
1754         {
1755             validId = true;
1756             break;
1757         }
1758     }
1759
1760     if (!validId)
1761     {
1762         char* strUuid = NULL;
1763 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
1764         //If seed value is exist, generate UUID using seed with SHA256
1765         if (0 != gUuidSeedSize)
1766         {
1767             uint8_t hashVal[MBEDTLS_MD_MAX_SIZE] = {0};
1768             mbedtls_md_context_t sha_ctx;
1769             int mbedret = 1;
1770
1771             OIC_LOG(DEBUG, TAG, "UUID will be generated using seed w/ SHA256");
1772             OIC_LOG(DEBUG, TAG, "Seed value : ");
1773             OIC_LOG_BUFFER(DEBUG, TAG, gUuidSeed, gUuidSeedSize);
1774
1775             mbedtls_md_init( &sha_ctx );
1776             mbedret = mbedtls_md_setup( &sha_ctx, mbedtls_md_info_from_type( MBEDTLS_MD_SHA256 ), 1 );
1777             if (0 == mbedret)
1778             {
1779                 mbedtls_md_starts( &sha_ctx );
1780                 mbedtls_md_update( &sha_ctx, gUuidSeed, gUuidSeedSize);
1781                 mbedtls_md_finish(&sha_ctx, (unsigned char*)hashVal);
1782                 memcpy(gDoxm->deviceID.id, hashVal, sizeof(gDoxm->deviceID.id));
1783                 ret = OC_STACK_OK;
1784             }
1785             else
1786             {
1787                 OIC_LOG_V(ERROR, TAG,  "mbedtls_md_setup() returned -0x%04x\n", -mbedret);
1788                 ret = OC_STACK_ERROR;
1789             }
1790             mbedtls_md_free( &sha_ctx );
1791         }
1792         else
1793         {
1794             if (RAND_UUID_OK != OCGenerateUuid(gDoxm->deviceID.id))
1795             {
1796                 OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
1797                 return OC_STACK_ERROR;
1798             }
1799             ret = OC_STACK_OK;
1800         }
1801 #else
1802         if (RAND_UUID_OK != OCGenerateUuid(gDoxm->deviceID.id))
1803         {
1804             OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
1805             return ret;
1806         }
1807         ret = OC_STACK_OK;
1808 #endif
1809
1810         if (OC_STACK_OK == ConvertUuidToStr(&gDoxm->deviceID, &strUuid))
1811         {
1812             OIC_LOG_V(DEBUG, TAG, "Generated device UUID is [%s]", strUuid);
1813             OICFree(strUuid);
1814         }
1815         else
1816         {
1817             OIC_LOG(WARNING, TAG, "Failed to convert UUID to string");
1818         }
1819
1820
1821         if (!UpdatePersistentStorage(gDoxm))
1822         {
1823             //TODO: After registering PSI handler in all samples, do ret = OC_STACK_OK here.
1824             OIC_LOG(FATAL, TAG, "UpdatePersistentStorage failed!");
1825         }
1826     }
1827     else
1828     {
1829         ret = OC_STACK_OK;
1830     }
1831
1832     OIC_LOG_V(DEBUG, TAG, "OUT: %s", __func__);
1833
1834     return ret;
1835 }
1836
1837 /**
1838  * Get the default value.
1839  *
1840  * @return the default value of doxm, @ref OicSecDoxm_t.
1841  */
1842 static OicSecDoxm_t* GetDoxmDefault()
1843 {
1844     OIC_LOG(DEBUG, TAG, "GetDoxmToDefault");
1845     return &gDefaultDoxm;
1846 }
1847
1848 const OicSecDoxm_t* GetDoxmResourceData()
1849 {
1850     return gDoxm;
1851 }
1852
1853 #if defined(__WITH_DTLS__) && defined(MULTIPLE_OWNER)
1854 /**
1855  * Internal API to prepare MOT
1856  */
1857 static void PrepareMOT(const OicSecDoxm_t* doxm)
1858 {
1859     OIC_LOG(INFO, TAG, "IN PrepareMOT");
1860     VERIFY_NON_NULL(TAG, doxm, ERROR);
1861
1862     if(true == doxm->owned && NULL != doxm->mom && OIC_MULTIPLE_OWNER_DISABLE != doxm->mom->mode)
1863     {
1864         CAResult_t caRes = CA_STATUS_FAILED;
1865
1866         OIC_LOG(INFO, TAG, "Multiple Ownership Transfer Enabled!");
1867
1868         if(OIC_PRECONFIG_PIN == doxm->oxmSel)
1869         {
1870             caRes = CAEnableAnonECDHCipherSuite(false);
1871             VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1872             OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
1873
1874             caRes = CASelectCipherSuite((uint16_t)MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, CA_ADAPTER_IP);
1875             VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1876 #ifdef __WITH_TLS__
1877             caRes = CASelectCipherSuite((uint16_t)MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256, CA_ADAPTER_TCP);
1878             VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
1879 #endif
1880             OIC_LOG(INFO, TAG, "ECDHE_PSK CipherSuite will be used for MOT");
1881
1882             //Set the device id to derive temporal PSK
1883             SetUuidForPinBasedOxm(&doxm->deviceID);
1884         }
1885         else
1886         {
1887             OIC_LOG(ERROR, TAG, "Unsupported OxM for Multiple Ownership Transfer.");
1888             return;
1889         }
1890
1891         CAregisterSslHandshakeCallback(MultipleOwnerDTLSHandshakeCB);
1892     }
1893
1894     OIC_LOG(INFO, TAG, "OUT PrepareMOT");
1895     return;
1896 exit:
1897     OIC_LOG(WARNING, TAG, "Error in PrepareMOT");
1898 }
1899 #endif //defined(__WITH_DTLS__) && defined(MULTIPLE_OWNER)
1900
1901 OCStackResult InitDoxmResource()
1902 {
1903     OCStackResult ret = OC_STACK_ERROR;
1904
1905     gConfirmState = CONFIRM_STATE_READY;
1906     gConfirmMsgId = 0;
1907
1908     //Read DOXM resource from PS
1909     uint8_t *data = NULL;
1910     size_t size = 0;
1911     ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_DOXM_NAME, &data, &size);
1912     // If database read failed
1913     if (OC_STACK_OK != ret)
1914     {
1915        OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
1916     }
1917     if (data)
1918     {
1919        // Read DOXM resource from PS
1920        ret = CBORPayloadToDoxm(data, size, &gDoxm);
1921     }
1922     /*
1923      * If SVR database in persistent storage got corrupted or
1924      * is not available for some reason, a default doxm is created
1925      * which allows user to initiate doxm provisioning again.
1926      */
1927      if ((OC_STACK_OK != ret) || !data || !gDoxm)
1928     {
1929         gDoxm = GetDoxmDefault();
1930     }
1931
1932     //In case of the server is shut down unintentionally, we should initialize the owner
1933     if(gDoxm && (false == gDoxm->owned))
1934     {
1935         OicUuid_t emptyUuid = {.id={0}};
1936         memcpy(&gDoxm->owner, &emptyUuid, sizeof(OicUuid_t));
1937 #if defined (__WITH_TLS__) || defined(__WITH_DTLS__)
1938         InvokeOtmEventHandler(NULL, 0, NULL, OIC_OTM_READY);
1939 #endif
1940     }
1941
1942     ret = CheckDeviceID();
1943     if (ret == OC_STACK_OK)
1944     {
1945         OIC_LOG_V(DEBUG, TAG, "Initial Doxm Owned = %d", gDoxm->owned);
1946         //Instantiate 'oic.sec.doxm'
1947         ret = CreateDoxmResource();
1948     }
1949     else
1950     {
1951         OIC_LOG (ERROR, TAG, "CheckDeviceID failed");
1952     }
1953     OICFree(data);
1954
1955 #if defined(__WITH_DTLS__) && defined(MULTIPLE_OWNER)
1956     //if MOT is enabled, MOT should be prepared.
1957     if(gDoxm && gDoxm->owned)
1958     {
1959         PrepareMOT(gDoxm);
1960     }
1961 #endif // defined(__WITH_DTLS__) && defined(MULTIPLE_OWNER)
1962
1963     return ret;
1964 }
1965
1966 OCStackResult DeInitDoxmResource()
1967 {
1968     OCStackResult ret = OCDeleteResource(gDoxmHandle);
1969     if (gDoxm  != &gDefaultDoxm)
1970     {
1971         DeleteDoxmBinData(gDoxm);
1972     }
1973     gDoxm = NULL;
1974
1975     if (OC_STACK_OK == ret)
1976     {
1977         return OC_STACK_OK;
1978     }
1979     else
1980     {
1981         return OC_STACK_ERROR;
1982     }
1983 }
1984
1985 OCStackResult GetDoxmDeviceID(OicUuid_t *deviceID)
1986 {
1987     if (deviceID && gDoxm)
1988     {
1989        *deviceID = gDoxm->deviceID;
1990         return OC_STACK_OK;
1991     }
1992     return OC_STACK_ERROR;
1993 }
1994
1995 OCStackResult GetDoxmIsOwned(bool *isOwned)
1996 {
1997     if (isOwned && gDoxm)
1998     {
1999        *isOwned = gDoxm->owned;
2000         return OC_STACK_OK;
2001     }
2002     return OC_STACK_ERROR;
2003 }
2004
2005 #if defined(__WITH_DTLS__) || defined (__WITH_TLS__)
2006 OCStackResult SetDoxmDeviceIDSeed(const uint8_t* seed, size_t seedSize)
2007 {
2008     OIC_LOG_V(INFO, TAG, "In %s", __func__);
2009
2010     if (NULL == seed)
2011     {
2012         return OC_STACK_INVALID_PARAM;
2013     }
2014     if (MAX_UUID_SEED_SIZE < seedSize)
2015     {
2016         OIC_LOG_V(ERROR, TAG, "Seed size is too long (MAX size is %d bytes)", MAX_UUID_SEED_SIZE);
2017         return OC_STACK_INVALID_PARAM;
2018     }
2019     if (MIN_UUID_SEED_SIZE > seedSize)
2020     {
2021         OIC_LOG_V(ERROR, TAG, "Seed size is too small (MIN size is %d bytes)", MIN_UUID_SEED_SIZE);
2022         return OC_STACK_INVALID_PARAM;
2023     }
2024
2025     memset(gUuidSeed, 0x00, sizeof(gUuidSeed));
2026     memcpy(gUuidSeed, seed, seedSize);
2027     gUuidSeedSize = seedSize;
2028
2029     OIC_LOG_V(INFO, TAG, "Out %s", __func__);
2030
2031     return OC_STACK_OK;
2032 }
2033
2034 #endif
2035
2036 OCStackResult SetDoxmDeviceID(const OicUuid_t *deviceID)
2037 {
2038     bool isOwnerUpdated = false;
2039     bool isRownerUpdated = false;
2040     if (NULL == deviceID)
2041     {
2042         return OC_STACK_INVALID_PARAM;
2043     }
2044     if (NULL == gDoxm)
2045     {
2046         OIC_LOG(ERROR, TAG, "Doxm resource is not initialized.");
2047         return OC_STACK_NO_RESOURCE;
2048     }
2049
2050 #ifdef __WITH_DTLS__
2051     //for normal device.
2052     if (true == gDoxm->owned &&
2053         memcmp(gDoxm->deviceID.id, gDoxm->owner.id, sizeof(gDoxm->owner.id)) != 0)
2054     {
2055         OIC_LOG(ERROR, TAG, "This device owned by owner's device.");
2056         OIC_LOG(ERROR, TAG, "Device UUID cannot be changed to guarantee the reliability of the connection.");
2057         return OC_STACK_ERROR;
2058     }
2059 #endif //__WITH_DTLS
2060
2061     //Save the previous UUID
2062     OicUuid_t prevUuid;
2063     memcpy(prevUuid.id, gDoxm->deviceID.id, sizeof(prevUuid.id));
2064
2065     //Change the device UUID
2066     memcpy(gDoxm->deviceID.id, deviceID->id, sizeof(deviceID->id));
2067
2068     //Change the owner ID if necessary
2069     if (memcmp(gDoxm->owner.id, prevUuid.id, sizeof(prevUuid.id)) == 0)
2070     {
2071         memcpy(gDoxm->owner.id, deviceID->id, sizeof(deviceID->id));
2072         isOwnerUpdated = true;
2073     }
2074     //Change the resource owner ID if necessary
2075     if (memcmp(gDoxm->rownerID.id, prevUuid.id, sizeof(prevUuid.id)) == 0)
2076     {
2077         memcpy(gDoxm->rownerID.id, deviceID->id, sizeof(deviceID->id));
2078         isRownerUpdated = true;
2079     }
2080     // TODO: T.B.D Change resource owner for pstat, acl and cred
2081
2082     //Update PS
2083     if (!UpdatePersistentStorage(gDoxm))
2084     {
2085         //revert UUID in case of PSI error
2086         memcpy(gDoxm->deviceID.id, prevUuid.id, sizeof(prevUuid.id));
2087         if (isOwnerUpdated)
2088         {
2089             memcpy(gDoxm->owner.id, prevUuid.id, sizeof(prevUuid.id));
2090         }
2091         if (isRownerUpdated)
2092         {
2093             memcpy(gDoxm->rownerID.id, prevUuid.id, sizeof(prevUuid.id));
2094         }
2095         // TODO: T.B.D Revert resource owner for pstat, acl and cred
2096
2097         OIC_LOG(ERROR, TAG, "Failed to update persistent storage");
2098         return OC_STACK_ERROR;
2099     }
2100     return OC_STACK_OK;
2101 }
2102
2103 OCStackResult GetDoxmDevOwnerId(OicUuid_t *devownerid)
2104 {
2105     OCStackResult retVal = OC_STACK_ERROR;
2106     if (gDoxm)
2107     {
2108         OIC_LOG_V(DEBUG, TAG, "GetDoxmDevOwnerId(): gDoxm owned =  %d.", \
2109             gDoxm->owned);
2110         if (gDoxm->owned)
2111         {
2112             *devownerid = gDoxm->owner;
2113             retVal = OC_STACK_OK;
2114         }
2115     }
2116     return retVal;
2117 }
2118
2119 OCStackResult GetDoxmRownerId(OicUuid_t *rowneruuid)
2120 {
2121     OCStackResult retVal = OC_STACK_ERROR;
2122     if (gDoxm)
2123     {
2124         if( gDoxm->owned )
2125         {
2126             *rowneruuid = gDoxm->rownerID;
2127                     retVal = OC_STACK_OK;
2128         }
2129     }
2130     return retVal;
2131 }
2132
2133 #ifdef MULTIPLE_OWNER
2134 /**
2135  * Compare the UUID to SubOwner.
2136  *
2137  * @param[in] uuid device UUID
2138  *
2139  * @return true if context->subjectId exist subowner list, else false.
2140  */
2141 bool IsSubOwner(const OicUuid_t* uuid)
2142 {
2143     bool retVal = false;
2144
2145     if (NULL == uuid)
2146     {
2147         return retVal;
2148     }
2149
2150     if (gDoxm && gDoxm->subOwners)
2151     {
2152         if (memcmp(gDoxm->owner.id, uuid->id, sizeof(gDoxm->owner.id)) == 0)
2153         {
2154             return false;
2155         }
2156
2157         OicSecSubOwner_t* subOwner = NULL;
2158         LL_FOREACH(gDoxm->subOwners, subOwner)
2159         {
2160             if (memcmp(subOwner->uuid.id, uuid->id, sizeof(uuid->id)) == 0)
2161             {
2162                 return true;
2163             }
2164         }
2165     }
2166     return retVal;
2167 }
2168 #endif //MULTIPLE_OWNER
2169
2170 OCStackResult SetMOTStatus(bool enable)
2171 {
2172     OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
2173 #ifdef MULTIPLE_OWNER
2174     OCStackResult ret = OC_STACK_NO_MEMORY;
2175     uint8_t *cborPayload = NULL;
2176     size_t size = 0;
2177     bool isDeallocateRequired = false;
2178
2179     VERIFY_NON_NULL(TAG, gDoxm, ERROR);
2180     
2181     if (NULL == gDoxm->mom && !enable)
2182     {
2183         OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2184         return OC_STACK_OK;
2185     }
2186
2187     if (NULL == gDoxm->mom)
2188     {
2189         gDoxm->mom = (OicSecMom_t*)OICCalloc(1, sizeof(OicSecMom_t));
2190         VERIFY_NON_NULL(TAG, gDoxm->mom, ERROR);
2191         isDeallocateRequired = true;
2192     }
2193
2194     gDoxm->mom->mode = (enable ? OIC_MULTIPLE_OWNER_ENABLE : OIC_MULTIPLE_OWNER_DISABLE);
2195     gDoxm->oxmSel = OIC_PRECONFIG_PIN;
2196
2197     ret = DoxmToCBORPayload(gDoxm, &cborPayload, &size, false);
2198     VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
2199
2200     ret = UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, cborPayload, size);
2201     VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
2202
2203     isDeallocateRequired = false;
2204
2205 exit:
2206     if (isDeallocateRequired)
2207     {
2208         OICFree(gDoxm->mom);
2209     }
2210     if (cborPayload)
2211     {
2212         OICFree(cborPayload);
2213     }
2214     OIC_LOG_V(DEBUG, TAG, "Out %s : %d", __func__, ret);
2215     return ret;
2216 #else
2217     OC_UNUSED(enable);
2218     OIC_LOG(DEBUG, TAG, "Multiple Owner is not enabled.");
2219     OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2220     return OC_STACK_ERROR;
2221 #endif //MULTIPLE_OWNER
2222 }
2223
2224 OCStackResult RemoveSubOwner(const OicUuid_t* subOwner)
2225 {
2226     OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
2227 #ifdef MULTIPLE_OWNER
2228     OCStackResult ret = OC_STACK_ERROR;
2229     bool isDeleted = false;
2230
2231     if (NULL == subOwner)
2232     {
2233         OIC_LOG(ERROR, TAG, "Invalid sub owner UUID.");
2234         return OC_STACK_INVALID_PARAM;
2235     }
2236     if (NULL == gDoxm)
2237     {
2238         OIC_LOG(ERROR, TAG, "Doxm resource is NULL");
2239         return OC_STACK_NO_RESOURCE;
2240     }
2241     if ( NULL == gDoxm->subOwners)
2242     {
2243         OIC_LOG(WARNING, TAG, "Sub Owner list is empty.");
2244         return OC_STACK_ERROR;
2245     }
2246
2247     OicSecSubOwner_t* curSubOwner = NULL;
2248     OicSecSubOwner_t* tempSubOwner = NULL;
2249     LL_FOREACH_SAFE(gDoxm->subOwners, curSubOwner, tempSubOwner)
2250     {
2251         if (memcmp(curSubOwner->uuid.id, subOwner->id, sizeof(subOwner->id)) == 0 ||
2252             memcmp(WILDCARD_SUBJECT_ID.id, subOwner->id, sizeof(OicUuid_t)) == 0)
2253         {
2254             char* strUuid = NULL;
2255             ret = ConvertUuidToStr(&curSubOwner->uuid, &strUuid);
2256             if (OC_STACK_OK != ret)
2257             {
2258                 OIC_LOG_V(ERROR, TAG, "ConvertUuidToStr error : %d", ret);
2259                 break;
2260             }
2261
2262             OIC_LOG_V(INFO, TAG, "[%s] will be removed from sub owner list.", strUuid);
2263             LL_DELETE(gDoxm->subOwners, curSubOwner);
2264
2265             //Remove the cred for sub owner
2266             ret = RemoveCredential(&curSubOwner->uuid);
2267             if (OC_STACK_RESOURCE_DELETED != ret)
2268             {
2269                 OIC_LOG_V(WARNING, TAG, "RemoveCredential error for [%s] : %d", strUuid, ret);
2270                 break;
2271             }
2272
2273             // TODO: Remove the ACL for sub owner (Currently ACL is not required for sub-owner)
2274
2275             OICFree(strUuid);
2276
2277             isDeleted = true;
2278         }
2279     }
2280
2281     if (isDeleted)
2282     {
2283         //Update persistent storage
2284         if (UpdatePersistentStorage(gDoxm))
2285         {
2286             ret = OC_STACK_RESOURCE_DELETED;
2287         }
2288         else
2289         {
2290             OIC_LOG(ERROR, TAG, "UpdatePersistentStorage error");
2291             ret = OC_STACK_ERROR;
2292         }
2293     }
2294
2295     OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2296     return ret;
2297 #else
2298     OC_UNUSED(subOwner);
2299     OIC_LOG(DEBUG, TAG, "Multiple Owner is not enabled.");
2300     OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2301     return OC_STACK_ERROR;
2302 #endif //MULTIPLE_OWNER
2303
2304 }
2305
2306 OCStackResult SetNumberOfSubOwner(size_t numOfSubOwner)
2307 {
2308     OIC_LOG_V(DEBUG, TAG, "In %s", __func__);
2309 #ifdef MULTIPLE_OWNER
2310     if (MAX_SUBOWNER_SIZE < numOfSubOwner || MIN_SUBOWNER_SIZE > numOfSubOwner)
2311     {
2312         OIC_LOG_V(ERROR, TAG, "Invalid number of sub owner : %d", numOfSubOwner);
2313         return OC_STACK_INVALID_PARAM;
2314     }
2315     gMaxSubOwnerSize = numOfSubOwner;
2316     OIC_LOG_V(DEBUG, TAG, "Number of SubOwner = %d", gMaxSubOwnerSize);
2317     OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2318     return OC_STACK_OK;
2319 #else
2320     OC_UNUSED(numOfSubOwner);
2321     OIC_LOG(DEBUG, TAG, "Multiple Owner is not enabled.");
2322     OIC_LOG_V(DEBUG, TAG, "Out %s", __func__);
2323     return OC_STACK_ERROR;
2324 #endif //MULTIPLE_OWNER
2325 }
2326
2327 /**
2328  * Function to restore doxm resurce to initial status.
2329  * This function will use in case of error while ownership transfer
2330  */
2331 void RestoreDoxmToInitState()
2332 {
2333
2334     gConfirmState = CONFIRM_STATE_READY;
2335     gConfirmMsgId = 0;
2336
2337     if(gDoxm)
2338     {
2339         OIC_LOG(INFO, TAG, "DOXM resource will revert back to initial status.");
2340
2341         OicUuid_t emptyUuid = {.id={0}};
2342         memcpy(&(gDoxm->owner), &emptyUuid, sizeof(OicUuid_t));
2343         gDoxm->owned = false;
2344         gDoxm->oxmSel = OIC_JUST_WORKS;
2345
2346         if(!UpdatePersistentStorage(gDoxm))
2347         {
2348             OIC_LOG(ERROR, TAG, "Failed to revert DOXM in persistent storage");
2349         }
2350     }
2351 }
2352
2353 OCStackResult SetDoxmSelfOwnership(const OicUuid_t* newROwner)
2354 {
2355     OCStackResult ret = OC_STACK_ERROR;
2356     uint8_t *cborPayload = NULL;
2357     size_t size = 0;
2358
2359     if(NULL == gDoxm)
2360     {
2361         ret = OC_STACK_NO_RESOURCE;
2362         return ret;
2363     }
2364
2365     if( newROwner && (false == gDoxm->owned) )
2366     {
2367         gDoxm->owned = true;
2368         memcpy(gDoxm->owner.id, newROwner->id, sizeof(newROwner->id));
2369         memcpy(gDoxm->rownerID.id, newROwner->id, sizeof(newROwner->id));
2370
2371         ret = DoxmToCBORPayload(gDoxm, &cborPayload, &size, false);
2372         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
2373
2374         ret = UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, cborPayload, size);
2375         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
2376
2377         OICFree(cborPayload);
2378     }
2379
2380     return ret;
2381
2382 exit:
2383     OICFree(cborPayload);
2384     return ret;
2385 }
2386