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