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