Doxm payload conversion from JSON to CBOR
[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 <stdlib.h>
21 #include <string.h>
22
23 #if HAVE_STRINGS_H
24 #include <strings.h>
25 #endif
26
27 #ifdef __WITH_DTLS__
28 #include "global.h"
29 #endif
30
31 #include "ocstack.h"
32 #include "oic_malloc.h"
33 #include "payload_logging.h"
34 #include "utlist.h"
35 #include "ocrandom.h"
36 #include "ocpayload.h"
37 #include "cainterface.h"
38 #include "ocserverrequest.h"
39 #include "resourcemanager.h"
40 #include "doxmresource.h"
41 #include "pstatresource.h"
42 #include "aclresource.h"
43 #include "psinterface.h"
44 #include "srmresourcestrings.h"
45 #include "securevirtualresourcetypes.h"
46 #include "credresource.h"
47 #include "srmutility.h"
48 #include "pinoxmcommon.h"
49
50 #define TAG  "SRM-DOXM"
51
52 /** Default cbor payload size. This value is increased in case of CborErrorOutOfMemory.
53  * The value of payload size is increased until reaching belox max cbor size. */
54 static const uint8_t CBOR_SIZE = 255;
55
56 /** Max cbor size payload. */
57 static const uint16_t CBOR_MAX_SIZE = 4400;
58
59 /** DOXM Map size - Number of mandatory items. */
60 static const uint8_t DOXM_MAP_SIZE = 5;
61
62 static OicSecDoxm_t        *gDoxm = NULL;
63 static OCResourceHandle    gDoxmHandle = NULL;
64
65 static OicSecOxm_t gOicSecDoxmJustWorks = OIC_JUST_WORKS;
66 static OicSecDoxm_t gDefaultDoxm =
67 {
68     NULL,                   /* OicUrn_t *oxmType */
69     0,                      /* size_t oxmTypeLen */
70     &gOicSecDoxmJustWorks,  /* uint16_t *oxm */
71     1,                      /* size_t oxmLen */
72     OIC_JUST_WORKS,         /* uint16_t oxmSel */
73     SYMMETRIC_PAIR_WISE_KEY,/* OicSecCredType_t sct */
74     false,                  /* bool owned */
75     {.id = {0}},            /* OicUuid_t deviceID */
76     false,                  /* bool dpc */
77     {.id = {0}},            /* OicUuid_t owner */
78 };
79
80 void DeleteDoxmBinData(OicSecDoxm_t* doxm)
81 {
82     if (doxm)
83     {
84         //Clean oxmType
85         for (size_t i = 0; i < doxm->oxmTypeLen; i++)
86         {
87             OICFree(doxm->oxmType[i]);
88         }
89         OICFree(doxm->oxmType);
90
91         //clean oxm
92         OICFree(doxm->oxm);
93
94         //Clean doxm itself
95         OICFree(doxm);
96     }
97 }
98
99 OCStackResult DoxmToCBORPayload(const OicSecDoxm_t *doxm, uint8_t **payload, size_t *size)
100 {
101     if (NULL == doxm || NULL == payload || NULL != *payload || NULL == size)
102     {
103         return OC_STACK_INVALID_PARAM;
104     }
105
106     size_t cborLen = *size;
107     if (0 == cborLen)
108     {
109         cborLen = CBOR_SIZE;
110     }
111
112     *payload = NULL;
113     *size = 0;
114
115     OCStackResult ret = OC_STACK_ERROR;
116
117     CborEncoder encoder = { {.ptr = NULL }, .end = 0 };
118     CborEncoder doxmMap = { {.ptr = NULL }, .end = 0 };
119
120     CborError cborEncoderResult = CborNoError;
121
122     uint8_t mapSize = DOXM_MAP_SIZE;
123
124     if (doxm->oxmTypeLen > 0)
125     {
126         mapSize++;
127     }
128     if (doxm->oxmLen > 0)
129     {
130         mapSize++;
131     }
132
133     uint8_t *outPayload = (uint8_t *)OICCalloc(1, cborLen);
134     VERIFY_NON_NULL(TAG, outPayload, ERROR);
135     cbor_encoder_init(&encoder, outPayload, cborLen, 0);
136
137     cborEncoderResult = cbor_encoder_create_map(&encoder, &doxmMap, mapSize);
138     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Doxm Map.");
139
140     //OxmType -- Not Mandatory
141     if (doxm->oxmTypeLen > 0)
142     {
143         cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_TYPE_NAME,
144             strlen(OIC_JSON_OXM_TYPE_NAME));
145         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Tag.");
146         CborEncoder oxmType = { {.ptr = NULL }, .end = 0 };
147         cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxmType, doxm->oxmTypeLen);
148         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Array.");
149
150         for (size_t i = 0; i < doxm->oxmTypeLen; i++)
151         {
152             cborEncoderResult = cbor_encode_text_string(&oxmType, doxm->oxmType[i],
153                 strlen(doxm->oxmType[i]));
154             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmType Value.");
155         }
156         cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxmType);
157         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmType.");
158     }
159
160     //Oxm -- Not Mandatory
161     if (doxm->oxmLen > 0)
162     {
163         cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_NAME,
164             strlen(OIC_JSON_OXM_NAME));
165         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Tag.");
166         CborEncoder oxm = { {.ptr = NULL }, .end = 0 };
167         cborEncoderResult = cbor_encoder_create_array(&doxmMap, &oxm, doxm->oxmLen);
168         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Array.");
169
170         for (size_t i = 0; i < doxm->oxmLen; i++)
171         {
172             cborEncoderResult = cbor_encode_int(&oxm, doxm->oxm[i]);
173             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding oxmName Value");
174         }
175         cborEncoderResult = cbor_encoder_close_container(&doxmMap, &oxm);
176         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing oxmName.");
177     }
178
179     //OxmSel -- Mandatory
180     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OXM_SEL_NAME,
181         strlen(OIC_JSON_OXM_SEL_NAME));
182     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Tag.");
183     cborEncoderResult = cbor_encode_int(&doxmMap, doxm->oxmSel);
184     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Sel Value.");
185
186     //sct -- Mandatory
187     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_SUPPORTED_CRED_TYPE_NAME,
188         strlen(OIC_JSON_SUPPORTED_CRED_TYPE_NAME));
189     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Tag");
190     cborEncoderResult = cbor_encode_int(&doxmMap, doxm->sct);
191     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Cred Type Value.");
192
193     //Owned -- Mandatory
194     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OWNED_NAME,
195         strlen(OIC_JSON_OWNED_NAME));
196     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Tag.");
197     cborEncoderResult = cbor_encode_boolean(&doxmMap, doxm->owned);
198     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owned Value.");
199
200     //TODO: Need more clarification on deviceIDFormat field type.
201 #if 0
202     //DeviceIdFormat -- Mandatory
203     cJSON_AddNumberToObject(jsonDoxm, OIC_JSON_DEVICE_ID_FORMAT_NAME, doxm->deviceIDFormat);
204 #endif
205
206     //DeviceId -- Mandatory
207     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DEVICE_ID_NAME,
208         strlen(OIC_JSON_DEVICE_ID_NAME));
209     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Tag.");
210     cborEncoderResult = cbor_encode_byte_string(&doxmMap, doxm->deviceID.id,
211                                                 sizeof(doxm->deviceID.id));
212     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Device Id Value.");
213
214     //DPC -- Mandatory
215     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_DPC_NAME,
216         strlen(OIC_JSON_DPC_NAME));
217     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DPC Tag.");
218     cborEncoderResult = cbor_encode_boolean(&doxmMap, doxm->dpc);
219     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding DPC Value.");
220
221     //Owner -- Mandatory
222     cborEncoderResult = cbor_encode_text_string(&doxmMap, OIC_JSON_OWNER_NAME,
223         strlen(OIC_JSON_OWNER_NAME));
224     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner tag.");
225     cborEncoderResult = cbor_encode_byte_string(&doxmMap, doxm->owner.id,
226                                                 sizeof(doxm->owner.id));
227     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Owner Value");
228
229     cborEncoderResult = cbor_encoder_close_container(&encoder, &doxmMap);
230     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing DoxmMap.");
231
232     *size = encoder.ptr - outPayload;
233     *payload = outPayload;
234     ret = OC_STACK_OK;
235
236 exit:
237     if ((CborErrorOutOfMemory == cborEncoderResult) && (cborLen < CBOR_MAX_SIZE))
238     {
239        // reallocate and try again!
240        OICFree(outPayload);
241        // Since the allocated initial memory failed, double the memory.
242        cborLen += encoder.ptr - encoder.end;
243        cborEncoderResult = CborNoError;
244        ret = DoxmToCBORPayload(doxm, payload, &cborLen);
245     }
246
247     if ((CborNoError != cborEncoderResult) || (OC_STACK_OK != ret))
248     {
249        OICFree(outPayload);
250        outPayload = NULL;
251        *payload = NULL;
252        *size = 0;
253        ret = OC_STACK_ERROR;
254     }
255
256     return ret;
257 }
258
259 OCStackResult CBORPayloadToDoxm(const uint8_t *cborPayload, size_t size,
260                                 OicSecDoxm_t **secDoxm)
261 {
262     if (NULL == cborPayload || NULL == secDoxm || NULL != *secDoxm)
263     {
264         return OC_STACK_INVALID_PARAM;
265     }
266
267     OCStackResult ret = OC_STACK_ERROR;
268     *secDoxm = NULL;
269
270     CborValue doxmCbor = { .parser = NULL };
271     CborParser parser = { .end = NULL };
272     CborError cborFindResult = CborNoError;
273     int cborLen = size;
274     if (0 == size)
275     {
276         cborLen = CBOR_SIZE;
277     }
278     cbor_parser_init(cborPayload, cborLen, 0, &parser, &doxmCbor);
279     CborValue doxmMap = { .parser = NULL } ;
280     OicSecDoxm_t *doxm = NULL;
281     cborFindResult = cbor_value_enter_container(&doxmCbor, &doxmMap);
282     VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering Doxm Map.")
283
284     doxm = (OicSecDoxm_t *)OICCalloc(1, sizeof(*doxm));
285     VERIFY_NON_NULL(TAG, doxm, ERROR);
286
287     while (cbor_value_is_valid(&doxmMap))
288     {
289         char *name = NULL;
290         size_t len = 0;
291         cborFindResult = cbor_value_dup_text_string(&doxmMap, &name, &len, NULL);
292         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Doxm Map Name.")
293         cborFindResult = cbor_value_advance(&doxmMap);
294         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Doxm Map.")
295
296         CborType type = cbor_value_get_type(&doxmMap);
297
298         //OxmType -- not Mandatory
299         if (0 == strcmp(OIC_JSON_OXM_TYPE_NAME, name))
300         {
301             CborValue oxmType = { .parser = NULL };
302
303             cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmTypeLen);
304             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmTypeLen.")
305             VERIFY_SUCCESS(TAG, doxm->oxmTypeLen != 0, ERROR);
306
307             doxm->oxmType = (OicUrn_t *)OICCalloc(doxm->oxmTypeLen, sizeof(*doxm->oxmType));
308             VERIFY_NON_NULL(TAG, doxm->oxmType, ERROR);
309
310             cborFindResult = cbor_value_enter_container(&doxmMap, &oxmType);
311             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmType Array.")
312
313             int i = 0;
314             size_t len = 0;
315             while (cbor_value_is_valid(&oxmType))
316             {
317                 cborFindResult = cbor_value_dup_text_string(&oxmType, &doxm->oxmType[i++],
318                                                             &len, NULL);
319                 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding omxType text string.")
320                 cborFindResult = cbor_value_advance(&oxmType);
321                 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmType.")
322             }
323         }
324
325         //Oxm -- not Mandatory
326         if (0 == strcmp(OIC_JSON_OXM_NAME, name))
327         {
328             CborValue oxm = { .parser = NULL };
329
330             cborFindResult = cbor_value_get_array_length(&doxmMap, &doxm->oxmLen);
331             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName array Length.")
332             VERIFY_SUCCESS(TAG, doxm->oxmLen != 0, ERROR);
333
334             doxm->oxm = (OicSecOxm_t *)OICCalloc(doxm->oxmLen, sizeof(*doxm->oxm));
335             VERIFY_NON_NULL(TAG, doxm->oxmType, ERROR);
336
337             cborFindResult = cbor_value_enter_container(&doxmMap, &oxm);
338             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering oxmName Array.")
339
340             int i = 0;
341             while (cbor_value_is_valid(&oxm))
342             {
343                 cborFindResult = cbor_value_get_int(&oxm, (int *) &doxm->oxm[i++]);
344                 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding oxmName Value")
345                 cborFindResult = cbor_value_advance(&oxm);
346                 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing oxmName.")
347             }
348         }
349
350         if (0 == strcmp(OIC_JSON_OXM_SEL_NAME, name))
351         {
352             cborFindResult = cbor_value_get_int(&doxmMap, (int *) &doxm->oxmSel);
353             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sel Name Value.")
354         }
355
356         if (0 == strcmp(OIC_JSON_SUPPORTED_CRED_TYPE_NAME, name))
357         {
358             cborFindResult = cbor_value_get_int(&doxmMap, (int *) &doxm->sct);
359             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Sct Name Value.")
360         }
361
362         if (0 == strcmp(OIC_JSON_OWNED_NAME, name))
363         {
364             cborFindResult = cbor_value_get_boolean(&doxmMap, &doxm->owned);
365             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owned Value.")
366         }
367
368         if (0 == strcmp(OIC_JSON_DPC_NAME, name))
369         {
370             cborFindResult = cbor_value_get_boolean(&doxmMap, &doxm->dpc);
371             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding DPC Value.")
372         }
373
374         if (0 == strcmp(OIC_JSON_DEVICE_ID_NAME, name))
375         {
376             uint8_t *id = NULL;
377             cborFindResult = cbor_value_dup_byte_string(&doxmMap, &id, &len, NULL);
378             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding DeviceId Value.")
379             memcpy(doxm->deviceID.id, id, len);
380             OICFree(id);
381         }
382         if (0 == strcmp(OIC_JSON_OWNER_NAME, name))
383         {
384             uint8_t *id = NULL;
385             cborFindResult = cbor_value_dup_byte_string(&doxmMap, &id , &len, NULL);
386             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Owner Name Value.")
387             memcpy(doxm->owner.id, id, len);
388             OICFree(id);
389         }
390         if (CborMapType != type && cbor_value_is_valid(&doxmMap))
391         {
392             cborFindResult = cbor_value_advance(&doxmMap);
393             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing DoxmMap.")
394         }
395         OICFree(name);
396     }
397
398     *secDoxm = doxm;
399     ret = OC_STACK_OK;
400
401 exit:
402     if (CborNoError != cborFindResult)
403     {
404         OIC_LOG (ERROR, TAG, "CBORPayloadToDoxm failed!!!");
405         DeleteDoxmBinData(doxm);
406         doxm = NULL;
407         ret = OC_STACK_ERROR;
408     }
409     return ret;
410 }
411
412 /**
413  * @todo document this function including why code might need to call this.
414  * The current suspicion is that it's not being called as much as it should.
415  */
416 static bool UpdatePersistentStorage(OicSecDoxm_t * doxm)
417 {
418     bool bRet = false;
419
420     if (NULL != doxm)
421     {
422         // Convert Doxm data into CBOR for update to persistent storage
423         uint8_t *payload = NULL;
424         size_t size = 0;
425         OCStackResult res = DoxmToCBORPayload(doxm, &payload, &size);
426         if (payload && (OC_STACK_OK == res)
427             && (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_DOXM_NAME, payload, size)))
428         {
429                 bRet = true;
430         }
431         OICFree(payload);
432     }
433
434     return bRet;
435 }
436
437 static bool ValidateQuery(const char * query)
438 {
439     // Send doxm resource data if the state of doxm resource
440     // matches with the query parameters.
441     // else send doxm resource data as NULL
442     // TODO Remove this check and rely on Policy Engine
443     // and Provisioning Mode to enforce provisioning-state
444     // access rules. Eventually, the PE and PM code will
445     // not send a request to the /doxm Entity Handler at all
446     // if it should not respond.
447     OIC_LOG (DEBUG, TAG, "In ValidateQuery");
448     if(NULL == gDoxm)
449     {
450         return false;
451     }
452
453     bool bOwnedQry = false;         // does querystring contains 'owned' query ?
454     bool bOwnedMatch = false;       // does 'owned' query value matches with doxm.owned status?
455     bool bDeviceIDQry = false;      // does querystring contains 'deviceid' query ?
456     bool bDeviceIDMatch = false;    // does 'deviceid' query matches with doxm.deviceid ?
457
458     OicParseQueryIter_t parseIter = {.attrPos = NULL};
459
460     ParseQueryIterInit((unsigned char*)query, &parseIter);
461
462     while (GetNextQuery(&parseIter))
463     {
464         if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_OWNED_NAME, parseIter.attrLen) == 0)
465         {
466             bOwnedQry = true;
467             if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_TRUE, parseIter.valLen) == 0) &&
468                     (gDoxm->owned))
469             {
470                 bOwnedMatch = true;
471             }
472             else if ((strncasecmp((char *)parseIter.valPos, OIC_SEC_FALSE, parseIter.valLen) == 0)
473                     && (!gDoxm->owned))
474             {
475                 bOwnedMatch = true;
476             }
477         }
478
479         if (strncasecmp((char *)parseIter.attrPos, OIC_JSON_DEVICE_ID_NAME, parseIter.attrLen) == 0)
480         {
481             bDeviceIDQry = true;
482             OicUuid_t subject = {.id={0}};
483
484             memcpy(subject.id, parseIter.valPos, parseIter.valLen);
485             if (0 == memcmp(&gDoxm->deviceID.id, &subject.id, sizeof(gDoxm->deviceID.id)))
486             {
487                 bDeviceIDMatch = true;
488             }
489         }
490     }
491
492     return ((bOwnedQry ? bOwnedMatch : true) && (bDeviceIDQry ? bDeviceIDMatch : true));
493 }
494
495 static OCEntityHandlerResult HandleDoxmGetRequest (const OCEntityHandlerRequest * ehRequest)
496 {
497     OCEntityHandlerResult ehRet = OC_EH_OK;
498
499     OIC_LOG(DEBUG, TAG, "Doxm EntityHandle processing GET request");
500
501     //Checking if Get request is a query.
502     if (ehRequest->query)
503     {
504         OIC_LOG(DEBUG, TAG, "HandleDoxmGetRequest processing query");
505         if (!ValidateQuery(ehRequest->query))
506         {
507             ehRet = OC_EH_ERROR;
508         }
509     }
510
511     /*
512      * For GET or Valid Query request return doxm resource CBOR payload.
513      * For non-valid query return NULL json payload.
514      * A device will 'always' have a default Doxm, so DoxmToCBORPayload will
515      * return valid doxm resource json.
516      */
517     uint8_t *payload = NULL;
518
519     if (ehRet == OC_EH_OK)
520     {
521         size_t size = 0;
522         if (OC_STACK_OK != DoxmToCBORPayload(gDoxm, &payload, &size))
523         {
524             payload = NULL;
525         }
526     }
527
528     // Send response payload to request originator
529     if (OC_STACK_OK != SendSRMCBORResponse(ehRequest, ehRet, payload))
530     {
531         OIC_LOG(ERROR, TAG, "SendSRMCBORResponse failed in HandleDoxmGetRequest");
532     }
533
534     OICFree(payload);
535
536     return ehRet;
537 }
538
539 static OCEntityHandlerResult HandleDoxmPutRequest(const OCEntityHandlerRequest * ehRequest)
540 {
541     OIC_LOG (DEBUG, TAG, "Doxm EntityHandle  processing PUT request");
542     OCEntityHandlerResult ehRet = OC_EH_ERROR;
543     OicUuid_t emptyOwner = {.id = {0} };
544
545     /*
546      * Convert CBOR Doxm data into binary. This will also validate
547      * the Doxm data received.
548      */
549     uint8_t *payload = ((OCSecurityPayload *)ehRequest->payload)->securityData1;
550     OicSecDoxm_t *newDoxm = NULL;
551
552     if (payload)
553     {
554         OCStackResult res = CBORPayloadToDoxm(payload, CBOR_SIZE, &newDoxm);
555
556         if (newDoxm && OC_STACK_OK == res)
557         {
558             // Iotivity SRM ONLY supports OIC_JUST_WORKS now
559             if (OIC_JUST_WORKS == newDoxm->oxmSel)
560             {
561                 /*
562                  * If current state of the device is un-owned, enable
563                  * anonymous ECDH cipher in tinyDTLS so that Provisioning
564                  * tool can initiate JUST_WORKS ownership transfer process.
565                  */
566                 if ((false == gDoxm->owned) && (false == newDoxm->owned))
567                 {
568                     OIC_LOG (INFO, TAG, "Doxm EntityHandle  enabling AnonECDHCipherSuite");
569 #ifdef __WITH_DTLS__
570                     ehRet = (CAEnableAnonECDHCipherSuite(true) == CA_STATUS_OK) ? OC_EH_OK : OC_EH_ERROR;
571 #endif //__WITH_DTLS__
572                     goto exit;
573                 }
574                 else
575                 {
576 #ifdef __WITH_DTLS__
577                     //Save the owner's UUID to derive owner credential
578                     memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
579
580                     // OCServerRequest *request = (OCServerRequest *)ehRequest->requestHandle;
581                     // Generating OwnerPSK
582                     // OIC_LOG (INFO, TAG, "Doxm EntityHandle  generating OwnerPSK");
583                     // Generate new credential for provisioning tool
584                     // ehRet = AddOwnerPSK((CAEndpoint_t *)&request->devAddr, newDoxm,
585                     //       (uint8_t*) OXM_JUST_WORKS, strlen(OXM_JUST_WORKS));
586                     // VERIFY_SUCCESS(TAG, OC_EH_OK == ehRet, ERROR);
587
588                     // Update new state in persistent storage
589                     if (true == UpdatePersistentStorage(gDoxm))
590                     {
591                         ehRet = OC_EH_OK;
592                     }
593                     else
594                     {
595                         OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
596                         ehRet = OC_EH_ERROR;
597                     }
598
599                    /*
600                     * Disable anonymous ECDH cipher in tinyDTLS since device is now
601                     * in owned state.
602                     */
603                     CAResult_t caRes = CA_STATUS_OK;
604                     caRes = CAEnableAnonECDHCipherSuite(false);
605                     VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
606                     OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
607
608 #ifdef __WITH_X509__
609 #define TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 0xC0AE
610                     CASelectCipherSuite(TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8);
611 #endif //__WITH_X509__
612 #endif //__WITH_DTLS__
613                 }
614             }
615         }
616         else if (OIC_RANDOM_DEVICE_PIN == newDoxm->oxmSel)
617         {
618             if ((false == gDoxm->owned) && (false == newDoxm->owned))
619             {
620                 /*
621                  * If current state of the device is un-owned, enable
622                  * anonymous ECDH cipher in tinyDTLS so that Provisioning
623                  * tool can initiate JUST_WORKS ownership transfer process.
624                  */
625                 if(memcmp(&(newDoxm->owner), &emptyOwner, sizeof(OicUuid_t)) == 0)
626                 {
627                     gDoxm->oxmSel = newDoxm->oxmSel;
628                     //Update new state in persistent storage
629                     if ((UpdatePersistentStorage(gDoxm) == true))
630                     {
631                         ehRet = OC_EH_OK;
632                     }
633                     else
634                     {
635                         OIC_LOG(WARNING, TAG, "Failed to update DOXM in persistent storage");
636                         ehRet = OC_EH_ERROR;
637                     }
638
639 #ifdef __WITH_DTLS__
640                     CAResult_t caRes = CA_STATUS_OK;
641
642                     caRes = CAEnableAnonECDHCipherSuite(false);
643                     VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
644                     OIC_LOG(INFO, TAG, "ECDH_ANON CipherSuite is DISABLED");
645
646                     caRes = CASelectCipherSuite(TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA_256);
647                     VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
648
649                     char ranPin[OXM_RANDOM_PIN_SIZE + 1] = {0,};
650                     if(OC_STACK_OK == GeneratePin(ranPin, OXM_RANDOM_PIN_SIZE + 1))
651                     {
652                         //Set the device id to derive temporal PSK
653                         SetUuidForRandomPinOxm(&gDoxm->deviceID);
654
655                         /**
656                          * Since PSK will be used directly by DTLS layer while PIN based ownership transfer,
657                          * Credential should not be saved into SVR.
658                          * For this reason, use a temporary get_psk_info callback to random PIN OxM.
659                          */
660                         caRes = CARegisterDTLSCredentialsHandler(GetDtlsPskForRandomPinOxm);
661                         VERIFY_SUCCESS(TAG, caRes == CA_STATUS_OK, ERROR);
662                         ehRet = OC_EH_OK;
663                     }
664                     else
665                     {
666                         OIC_LOG(ERROR, TAG, "Failed to generate random PIN");
667                         ehRet = OC_EH_ERROR;
668                     }
669 #endif //__WITH_DTLS__
670                 }
671                 else
672                 {
673 #ifdef __WITH_DTLS__
674                     //Save the owner's UUID to derive owner credential
675                     memcpy(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t));
676
677                     //Update new state in persistent storage
678                     if (UpdatePersistentStorage(gDoxm) == true)
679                     {
680                         ehRet = OC_EH_OK;
681                     }
682                     else
683                     {
684                         OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
685                         ehRet = OC_EH_ERROR;
686                     }
687 #endif
688                 }
689             }
690         }
691
692         /*
693          * When current state of the device is un-owned and Provisioning
694          * Tool is attempting to change the state to 'Owned' with a
695          * qualified value for the field 'Owner'
696          */
697         if ((false == gDoxm->owned) && (true == newDoxm->owned) &&
698             (memcmp(&(gDoxm->owner), &(newDoxm->owner), sizeof(OicUuid_t)) == 0))
699         {
700             gDoxm->owned = true;
701             // Update new state in persistent storage
702             if (UpdatePersistentStorage(gDoxm))
703             {
704                 //Update default ACL of security resource to prevent anonymous user access.
705                 if(OC_STACK_OK == UpdateDefaultSecProvACL())
706                 {
707                     ehRet = OC_EH_OK;
708                 }
709                 else
710                 {
711                     OIC_LOG(ERROR, TAG, "Failed to remove default ACL for security provisioning");
712                     ehRet = OC_EH_ERROR;
713                 }
714             }
715             else
716             {
717                 OIC_LOG(ERROR, TAG, "Failed to update DOXM in persistent storage");
718                 ehRet = OC_EH_ERROR;
719             }
720         }
721     }
722
723 exit:
724     if(OC_EH_OK != ehRet)
725     {
726         OIC_LOG(WARNING, TAG, "The operation failed during handle DOXM request,"\
727                             "DOXM will be reverted.");
728
729         /*
730          * If some error is occured while ownership transfer,
731          * ownership transfer related resource should be revert back to initial status.
732          */
733         RestoreDoxmToInitState();
734         RestorePstatToInitState();
735     }
736
737     //Send payload to request originator
738     if (OC_STACK_OK != SendSRMCBORResponse(ehRequest, ehRet, NULL))
739     {
740         OIC_LOG(ERROR, TAG, "SendSRMCBORResponse failed in HandleDoxmPostRequest");
741     }
742     DeleteDoxmBinData(newDoxm);
743
744     return ehRet;
745 }
746
747 OCEntityHandlerResult DoxmEntityHandler(OCEntityHandlerFlag flag,
748                                         OCEntityHandlerRequest * ehRequest,
749                                         void* callbackParam)
750 {
751     (void)callbackParam;
752     OCEntityHandlerResult ehRet = OC_EH_ERROR;
753
754     if(NULL == ehRequest)
755     {
756         return ehRet;
757     }
758
759     if (flag & OC_REQUEST_FLAG)
760     {
761         OIC_LOG(DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
762
763         switch (ehRequest->method)
764         {
765             case OC_REST_GET:
766                 ehRet = HandleDoxmGetRequest(ehRequest);
767                 break;
768
769             case OC_REST_PUT:
770                 ehRet = HandleDoxmPutRequest(ehRequest);
771                 break;
772
773             default:
774                 ehRet = OC_EH_ERROR;
775                 SendSRMCBORResponse(ehRequest, ehRet, NULL);
776                 break;
777         }
778     }
779
780     return ehRet;
781 }
782
783 OCStackResult CreateDoxmResource()
784 {
785     OCStackResult ret = OCCreateResource(&gDoxmHandle,
786                                          OIC_RSRC_TYPE_SEC_DOXM,
787                                          OIC_MI_DEF,
788                                          OIC_RSRC_DOXM_URI,
789                                          DoxmEntityHandler,
790                                          NULL,
791                                          OC_OBSERVABLE | OC_SECURE |
792                                          OC_EXPLICIT_DISCOVERABLE);
793
794     if (OC_STACK_OK != ret)
795     {
796         OIC_LOG (FATAL, TAG, "Unable to instantiate Doxm resource");
797         DeInitDoxmResource();
798     }
799     return ret;
800 }
801
802 /**
803  * Checks if DeviceID is generated during provisioning for the new device.
804  * If DeviceID is NULL then generates the new DeviceID.
805  * Once DeviceID is assigned to the device it does not change for the lifetime of the device.
806  */
807 static OCStackResult CheckDeviceID()
808 {
809     OCStackResult ret = OC_STACK_ERROR;
810     bool validId = false;
811     for (uint8_t i = 0; i < UUID_LENGTH; i++)
812     {
813         if (gDoxm->deviceID.id[i] != 0)
814         {
815             validId = true;
816             break;
817         }
818     }
819
820     if (!validId)
821     {
822         if (OCGenerateUuid(gDoxm->deviceID.id) != RAND_UUID_OK)
823         {
824             OIC_LOG(FATAL, TAG, "Generate UUID for Server Instance failed!");
825             return ret;
826         }
827         ret = OC_STACK_OK;
828
829         if (UpdatePersistentStorage(gDoxm))
830         {
831             //TODO: After registering PSI handler in all samples, do ret = OC_STACK_OK here.
832             OIC_LOG(FATAL, TAG, "UpdatePersistentStorage failed!");
833         }
834     }
835     else
836     {
837         ret = OC_STACK_OK;
838     }
839     return ret;
840 }
841
842 /**
843  * Get the default value.
844  *
845  * @return the default value of doxm, @ref OicSecDoxm_t.
846  */
847 static OicSecDoxm_t* GetDoxmDefault()
848 {
849     OIC_LOG(DEBUG, TAG, "GetDoxmToDefault");
850     return &gDefaultDoxm;
851 }
852
853 const OicSecDoxm_t* GetDoxmResourceData()
854 {
855     return gDoxm;
856 }
857
858 OCStackResult InitDoxmResource()
859 {
860     OCStackResult ret = OC_STACK_ERROR;
861
862     //Read DOXM resource from PS
863     uint8_t *data = NULL;
864     size_t size = 0;
865     ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_DOXM_NAME, &data, &size);
866     // If database read failed
867     if (OC_STACK_OK != ret)
868     {
869        OIC_LOG (DEBUG, TAG, "ReadSVDataFromPS failed");
870     }
871     if (data)
872     {
873        // Read DOXM resource from PS
874        ret = CBORPayloadToDoxm(data, size, &gDoxm);
875     }
876     /*
877      * If SVR database in persistent storage got corrupted or
878      * is not available for some reason, a default doxm is created
879      * which allows user to initiate doxm provisioning again.
880      */
881      if ((OC_STACK_OK != ret) || !data || !gDoxm)
882     {
883         gDoxm = GetDoxmDefault();
884     }
885
886     //In case of the server is shut down unintentionally, we should initialize the owner
887     if(false == gDoxm->owned)
888     {
889         OicUuid_t emptyUuid = {.id={0}};
890         memcpy(&gDoxm->owner, &emptyUuid, sizeof(OicUuid_t));
891     }
892
893     ret = CheckDeviceID();
894     if (ret == OC_STACK_OK)
895     {
896         //Instantiate 'oic.sec.doxm'
897         ret = CreateDoxmResource();
898     }
899     else
900     {
901         OIC_LOG (ERROR, TAG, "CheckDeviceID failed");
902     }
903     OICFree(data);
904     return ret;
905 }
906
907 OCStackResult DeInitDoxmResource()
908 {
909     OCStackResult ret = OCDeleteResource(gDoxmHandle);
910     if (gDoxm  != &gDefaultDoxm)
911     {
912         DeleteDoxmBinData(gDoxm);
913     }
914     gDoxm = NULL;
915
916     if (OC_STACK_OK == ret)
917     {
918         return OC_STACK_OK;
919     }
920     else
921     {
922         return OC_STACK_ERROR;
923     }
924 }
925
926 OCStackResult GetDoxmDeviceID(OicUuid_t *deviceID)
927 {
928     if (deviceID && gDoxm)
929     {
930        *deviceID = gDoxm->deviceID;
931         return OC_STACK_OK;
932     }
933     return OC_STACK_ERROR;
934 }
935
936 OCStackResult GetDoxmDevOwnerId(OicUuid_t *devOwner)
937 {
938     OCStackResult retVal = OC_STACK_ERROR;
939     if (gDoxm)
940     {
941         if (gDoxm->owned)
942         {
943             *devOwner = gDoxm->owner; // TODO change to devOwner when available
944             retVal = OC_STACK_OK;
945         }
946     }
947     return retVal;
948 }
949
950 /**
951  * Function to restore doxm resurce to initial status.
952  * This function will use in case of error while ownership transfer
953  */
954 void RestoreDoxmToInitState()
955 {
956     if(gDoxm)
957     {
958         OIC_LOG(INFO, TAG, "DOXM resource will revert back to initial status.");
959
960         OicUuid_t emptyUuid = {.id={0}};
961         memcpy(&(gDoxm->owner), &emptyUuid, sizeof(OicUuid_t));
962         gDoxm->owned = false;
963         gDoxm->oxmSel = OIC_JUST_WORKS;
964
965         if(!UpdatePersistentStorage(gDoxm))
966         {
967             OIC_LOG(ERROR, TAG, "Failed to revert DOXM in persistent storage");
968         }
969     }
970 }