Merge branch 'master' into windows-port
[platform/upstream/iotivity.git] / resource / csdk / security / src / aclresource.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
21 #ifdef HAVE_STRING_H
22 #include <string.h>
23 #elif HAVE_STRINGS_H
24 #include <strings.h>
25 #endif
26 #include <stdlib.h>
27
28 #include "ocstack.h"
29 #include "ocserverrequest.h"
30 #include "oic_malloc.h"
31 #include "oic_string.h"
32 #include "ocrandom.h"
33 #include "ocpayload.h"
34 #include "utlist.h"
35 #include "payload_logging.h"
36 #include "srmresourcestrings.h"
37 #include "aclresource.h"
38 #include "doxmresource.h"
39 #include "resourcemanager.h"
40 #include "srmutility.h"
41 #include "psinterface.h"
42
43 #include "security_internals.h"
44
45 #define TAG  "SRM-ACL"
46 #define NUMBER_OF_SEC_PROV_RSCS 4
47 #define NUMBER_OF_DEFAULT_SEC_RSCS 2
48 #define STRING_UUID_SIZE (UUID_LENGTH * 2 + 5)
49
50 static const uint8_t ACL_MAP_SIZE = 2;
51 static const uint8_t ACL_ACLIST_MAP_SIZE = 1;
52 static const uint8_t ACL_ACES_MAP_SIZE = 3;
53 static const uint8_t ACL_RESOURCE_MAP_SIZE = 4;
54
55
56 // CborSize is the default cbor payload size being used.
57 static const uint16_t CBOR_SIZE = 2048;
58
59 static OicSecAcl_t *gAcl = NULL;
60 static OCResourceHandle gAclHandle = NULL;
61
62 /**
63  * This function frees OicSecAcl_t object's fields and object itself.
64  */
65 static void FreeACE(OicSecAcl_t *ace)
66 {
67     size_t i;
68     if (NULL == ace)
69     {
70         OIC_LOG(ERROR, TAG, "Invalid Parameter");
71         return;
72     }
73
74     // Clean Resources
75     for (i = 0; i < ace->resourcesLen; i++)
76     {
77         OICFree(ace->resources[i]);
78     }
79     OICFree(ace->resources);
80
81     //Clean Period
82     if (ace->periods)
83     {
84         for (i = 0; i < ace->prdRecrLen; i++)
85         {
86             OICFree(ace->periods[i]);
87         }
88         OICFree(ace->periods);
89     }
90
91     //Clean Recurrence
92     if (ace->recurrences)
93     {
94         for (i = 0; i < ace->prdRecrLen; i++)
95         {
96             OICFree(ace->recurrences[i]);
97         }
98         OICFree(ace->recurrences);
99     }
100
101     // Clean ACL node itself
102     OICFree(ace);
103 }
104
105 void DeleteACLList(OicSecAcl_t* acl)
106 {
107     if (acl)
108     {
109         OicSecAcl_t *aclTmp1 = NULL;
110         OicSecAcl_t *aclTmp2 = NULL;
111         LL_FOREACH_SAFE(acl, aclTmp1, aclTmp2)
112         {
113             LL_DELETE(acl, aclTmp1);
114             FreeACE(aclTmp1);
115         }
116     }
117 }
118
119 static size_t OicSecAclSize(const OicSecAcl_t *secAcl)
120 {
121     if (!secAcl)
122     {
123         return 0;
124     }
125     OicSecAcl_t *acl = (OicSecAcl_t *)secAcl;
126     size_t size = 0;
127     while (acl)
128     {
129        size++;
130        acl = acl->next;
131     }
132     return size;
133 }
134
135 OCStackResult AclToCBORPayload(const OicSecAcl_t *secAcl, uint8_t **payload, size_t *size)
136 {
137      if (NULL == secAcl || NULL == payload || NULL != *payload || NULL == size)
138     {
139         return OC_STACK_INVALID_PARAM;
140     }
141
142     OCStackResult ret = OC_STACK_ERROR;
143     CborError cborEncoderResult = CborNoError;
144     OicSecAcl_t *acl = (OicSecAcl_t *)secAcl;
145     CborEncoder encoder;
146     CborEncoder aclMap;
147     CborEncoder aclListMap;
148     CborEncoder acesArray;
149     uint8_t *outPayload = NULL;
150     size_t cborLen = *size;
151     *size = 0;
152     *payload = NULL;
153
154     if (cborLen == 0)
155     {
156         cborLen = CBOR_SIZE;
157     }
158
159     outPayload = (uint8_t *)OICCalloc(1, cborLen);
160     VERIFY_NON_NULL(TAG, outPayload, ERROR);
161     cbor_encoder_init(&encoder, outPayload, cborLen, 0);
162
163     // Create ACL Map (aclist, rownerid)
164     cborEncoderResult = cbor_encoder_create_map(&encoder, &aclMap, ACL_MAP_SIZE);
165     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Creating ACL Map.");
166
167     cborEncoderResult = cbor_encode_text_string(&aclMap, OIC_JSON_ACLIST_NAME,
168         strlen(OIC_JSON_ACLIST_NAME));
169     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding aclist Name Tag.");
170
171     // Create ACLIST Map (aces)
172     cborEncoderResult = cbor_encoder_create_map(&aclMap, &aclListMap, ACL_ACLIST_MAP_SIZE);
173     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Creating ACLIST Map.");
174
175     cborEncoderResult = cbor_encode_text_string(&aclListMap, OIC_JSON_ACES_NAME,
176         strlen(OIC_JSON_ACES_NAME));
177     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding ACES Name Tag.");
178
179     // Create ACES Array
180     cborEncoderResult = cbor_encoder_create_array(&aclListMap, &acesArray, OicSecAclSize(secAcl));
181     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Creating ACES Array.");
182
183     while (acl)
184     {
185         CborEncoder oicSecAclMap;
186         // ACL Map size - Number of mandatory items
187         uint8_t aclMapSize = ACL_ACES_MAP_SIZE;
188         size_t inLen = 0;
189
190         // Create ACL Map
191         if (acl->periods)
192         {
193             ++aclMapSize;
194         }
195         if (acl->recurrences)
196         {
197             ++aclMapSize;
198         }
199
200         cborEncoderResult = cbor_encoder_create_map(&acesArray, &oicSecAclMap, aclMapSize);
201         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Creating ACES Map");
202
203         // Subject -- Mandatory
204         cborEncoderResult = cbor_encode_text_string(&oicSecAclMap, OIC_JSON_SUBJECTID_NAME,
205             strlen(OIC_JSON_SUBJECTID_NAME));
206         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Subject Name Tag.");
207         inLen = (memcmp(&(acl->subject), &WILDCARD_SUBJECT_ID, sizeof(OicUuid_t)) == 0) ?
208             WILDCARD_SUBJECT_ID_LEN : sizeof(OicUuid_t);
209         if(inLen == WILDCARD_SUBJECT_ID_LEN)
210         {
211             cborEncoderResult = cbor_encode_text_string(&oicSecAclMap, WILDCARD_RESOURCE_URI,
212                 strlen(WILDCARD_RESOURCE_URI));
213             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding Subject Id wildcard Value.");
214         }
215         else
216         {
217             char *subject = NULL;
218             ret = ConvertUuidToStr(&acl->subject, &subject);
219             VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
220             cborEncoderResult = cbor_encode_text_string(&oicSecAclMap, subject, strlen(subject));
221             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding Subject Id Value.");
222             OICFree(subject);
223         }
224
225         // Resources
226         {
227             CborEncoder resources;
228             cborEncoderResult = cbor_encode_text_string(&oicSecAclMap, OIC_JSON_RESOURCES_NAME,
229                 strlen(OIC_JSON_RESOURCES_NAME));
230             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Resource Name Tag.");
231
232             cborEncoderResult = cbor_encoder_create_array(&oicSecAclMap, &resources, acl->resourcesLen);
233             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Resource Name Array.");
234
235             for (size_t i = 0; i < acl->resourcesLen; i++)
236             {
237
238                 CborEncoder rMap;
239                 cborEncoderResult = cbor_encoder_create_map(&resources, &rMap, ACL_RESOURCE_MAP_SIZE);
240                 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding Resource Map.");
241
242                 cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_HREF_NAME,
243                         strlen(OIC_JSON_HREF_NAME));
244                 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding HREF Name Tag.");
245                 cborEncoderResult = cbor_encode_text_string(&rMap, acl->resources[i],
246                         strlen(acl->resources[i]));
247                 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding HREF Value in Map.");
248
249                 cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_REL_NAME,
250                         strlen(OIC_JSON_REL_NAME));
251                 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding REL Name Tag.");
252
253                 // TODO : Need to assign real value of REL
254                 cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_EMPTY_STRING,
255                         strlen(OIC_JSON_EMPTY_STRING));
256                 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding REL Value.");
257
258                 cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_RT_NAME,
259                         strlen(OIC_JSON_RT_NAME));
260                 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Name Tag.");
261
262                 // TODO : Need to assign real value of RT
263                 cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_EMPTY_STRING,
264                         strlen(OIC_JSON_EMPTY_STRING));
265                 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding RT Value.");
266
267                 cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_IF_NAME,
268                         strlen(OIC_JSON_IF_NAME));
269                 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Name Tag.");
270
271                 // TODO : Need to assign real value of IF
272                 cborEncoderResult = cbor_encode_text_string(&rMap, OIC_JSON_EMPTY_STRING,
273                         strlen(OIC_JSON_EMPTY_STRING));
274                 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding IF Value.");
275
276
277                 cborEncoderResult = cbor_encoder_close_container(&resources, &rMap);
278                 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Resource Map.");
279
280             }
281             cborEncoderResult = cbor_encoder_close_container(&oicSecAclMap, &resources);
282             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Resource Name Array.");
283         }
284
285
286         // Permissions -- Mandatory
287         cborEncoderResult = cbor_encode_text_string(&oicSecAclMap, OIC_JSON_PERMISSION_NAME,
288             strlen(OIC_JSON_PERMISSION_NAME));
289         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Permission Name Tag.");
290         cborEncoderResult = cbor_encode_int(&oicSecAclMap, acl->permission);
291         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Permission Name Value.");
292
293         // Period -- Not Mandatory
294         if (acl->periods)
295         {
296
297             CborEncoder period;
298             cborEncoderResult = cbor_encode_text_string(&oicSecAclMap, OIC_JSON_PERIOD_NAME,
299                 strlen(OIC_JSON_PERIOD_NAME));
300             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Period Tag.");
301             cborEncoderResult = cbor_encoder_create_array(&oicSecAclMap, &period, acl->prdRecrLen);
302             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Period Array.");
303             for (size_t i = 0; i < acl->prdRecrLen; i++)
304             {
305                 cborEncoderResult = cbor_encode_text_string(&period, acl->periods[i],
306                     strlen(acl->periods[i]));
307                 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Period Value in Array.");
308             }
309             cborEncoderResult = cbor_encoder_close_container(&oicSecAclMap, &period);
310             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Period Array.");
311         }
312
313         // Recurrence -- Not Mandatory
314         if (acl->recurrences)
315         {
316             CborEncoder recurrences;
317             cborEncoderResult = cbor_encode_text_string(&oicSecAclMap, OIC_JSON_RECURRENCES_NAME,
318                 strlen(OIC_JSON_RECURRENCES_NAME));
319             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Recurrence Tag.");
320             cborEncoderResult = cbor_encoder_create_array(&oicSecAclMap, &recurrences, acl->prdRecrLen);
321             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Recurrence Array.");
322
323             for (size_t i = 0; i < acl->prdRecrLen; i++)
324             {
325                 cborEncoderResult = cbor_encode_text_string(&recurrences, acl->recurrences[i],
326                     strlen(acl->recurrences[i]));
327                 VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding Recurrence Array Value.");
328             }
329             cborEncoderResult = cbor_encoder_close_container(&oicSecAclMap, &recurrences);
330             VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing Recurrence Array");
331
332         }
333
334
335         cborEncoderResult = cbor_encoder_close_container(&acesArray, &oicSecAclMap);
336         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing ACES Map.");
337         acl = acl->next;
338     }
339
340     // Close ACES Array
341     cborEncoderResult = cbor_encoder_close_container(&aclListMap, &acesArray);
342     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing ACES Array.");
343
344     // Close ACLIST Map
345     cborEncoderResult = cbor_encoder_close_container(&aclMap, &aclListMap);
346     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing ACLIST Map.");
347
348     // Rownerid
349     {
350         char *rowner = NULL;
351         cborEncoderResult = cbor_encode_text_string(&aclMap, OIC_JSON_ROWNERID_NAME,
352             strlen(OIC_JSON_ROWNERID_NAME));
353         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Adding rownerid Name.");
354         ret = ConvertUuidToStr(&secAcl->rownerID, &rowner);
355         VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
356         cborEncoderResult = cbor_encode_text_string(&aclMap, rowner, strlen(rowner));
357         VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Addding rownerid Value.");
358         OICFree(rowner);
359     }
360
361     // Close ACL Map
362     cborEncoderResult = cbor_encoder_close_container(&encoder, &aclMap);
363     VERIFY_CBOR_SUCCESS(TAG, cborEncoderResult, "Failed Closing ACL Map.");
364
365     if (CborNoError == cborEncoderResult)
366     {
367         OIC_LOG(DEBUG, TAG, "AclToCBORPayload Successed");
368         *size = encoder.ptr - outPayload;
369         *payload = outPayload;
370         ret = OC_STACK_OK;
371     }
372 exit:
373     if (CborErrorOutOfMemory == cborEncoderResult)
374     {
375         OIC_LOG(DEBUG, TAG, "AclToCBORPayload:CborErrorOutOfMemory : retry with more memory");
376
377         // reallocate and try again!
378         OICFree(outPayload);
379         // Since the allocated initial memory failed, double the memory.
380         cborLen += encoder.ptr - encoder.end;
381         cborEncoderResult = CborNoError;
382         ret = AclToCBORPayload(secAcl, payload, &cborLen);
383         *size = cborLen;
384     }
385     else if (cborEncoderResult != CborNoError)
386     {
387         OIC_LOG(ERROR, TAG, "Failed to AclToCBORPayload");
388         OICFree(outPayload);
389         outPayload = NULL;
390         *size = 0;
391         *payload = NULL;
392         ret = OC_STACK_ERROR;
393     }
394
395     return ret;
396 }
397
398 // This function converts CBOR format to ACL data.
399 // Caller needs to invoke 'free' when done using
400 // note: This function is used in unit test hence not declared static,
401 OicSecAcl_t* CBORPayloadToAcl(const uint8_t *cborPayload, const size_t size)
402 {
403     if (NULL == cborPayload || 0 == size)
404     {
405         return NULL;
406     }
407     OCStackResult ret = OC_STACK_ERROR;
408     CborValue aclCbor = { .parser = NULL };
409     CborParser parser = { .end = NULL };
410     CborError cborFindResult = CborNoError;
411     cbor_parser_init(cborPayload, size, 0, &parser, &aclCbor);
412
413     OicSecAcl_t *headAcl = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
414
415     // Enter ACL Map
416     CborValue aclMap = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
417     cborFindResult = cbor_value_enter_container(&aclCbor, &aclMap);
418     VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering ACL Map.");
419
420     while (cbor_value_is_valid(&aclMap))
421     {
422         char* tagName = NULL;
423         size_t len = 0;
424         CborType type = cbor_value_get_type(&aclMap);
425         if (type == CborTextStringType)
426         {
427             cborFindResult = cbor_value_dup_text_string(&aclMap, &tagName, &len, NULL);
428             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Name in ACL Map.");
429             cborFindResult = cbor_value_advance(&aclMap);
430             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Value in ACL Map.");
431         }
432         if(tagName)
433         {
434             if (strcmp(tagName, OIC_JSON_ACLIST_NAME)  == 0)
435             {
436                 // Enter ACLIST Map
437                 CborValue aclistMap = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
438                 cborFindResult = cbor_value_enter_container(&aclMap, &aclistMap);
439                 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering ACLIST Map.");
440
441
442                 while (cbor_value_is_valid(&aclistMap))
443                 {
444                     char* acName = NULL;
445                     size_t acLen = 0;
446                     CborType acType = cbor_value_get_type(&aclistMap);
447                     if (acType == CborTextStringType)
448                     {
449                         cborFindResult = cbor_value_dup_text_string(&aclistMap, &acName, &acLen, NULL);
450                         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Name in ACLIST Map.");
451                         cborFindResult = cbor_value_advance(&aclistMap);
452                         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Value in ACLIST Map.");
453                     }
454                     if(acName)
455                     {
456                         if (strcmp(acName, OIC_JSON_ACES_NAME)  == 0)
457                         {
458
459                             // Enter ACES Array
460                             CborValue aclArray = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
461                             cborFindResult = cbor_value_enter_container(&aclistMap, &aclArray);
462                             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering ACL Array.");
463
464                             int acesCount = 0;
465                             while (cbor_value_is_valid(&aclArray))
466                             {
467                                 acesCount++;
468
469                                 CborValue aclMap = { .parser = NULL, .ptr = NULL, .remaining = 0, .extra = 0, .type = 0, .flags = 0 };
470                                 cborFindResult = cbor_value_enter_container(&aclArray, &aclMap);
471                                 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering ACL Map.");
472                                 OicSecAcl_t *acl = NULL;
473
474                                 if(acesCount == 1)
475                                 {
476                                     acl = headAcl;
477                                 }
478                                 else
479                                 {
480                                     acl = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
481                                     OicSecAcl_t *temp = headAcl;
482                                     while (temp->next)
483                                     {
484                                         temp = temp->next;
485                                     }
486                                     temp->next = acl;
487                                 }
488                                 VERIFY_NON_NULL(TAG, acl, ERROR);
489
490                                 while (cbor_value_is_valid(&aclMap))
491                                 {
492                                     char* name = NULL;
493                                     size_t len = 0;
494                                     CborType type = cbor_value_get_type(&aclMap);
495                                     if (type == CborTextStringType)
496                                     {
497                                         cborFindResult = cbor_value_dup_text_string(&aclMap, &name, &len, NULL);
498                                         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Name in ACL Map.");
499                                         cborFindResult = cbor_value_advance(&aclMap);
500                                         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Value in ACL Map.");
501                                     }
502                                     if (name)
503                                     {
504                                         // Subject -- Mandatory
505                                         if (strcmp(name, OIC_JSON_SUBJECTID_NAME)  == 0)
506                                         {
507                                             char *subject = NULL;
508                                             cborFindResult = cbor_value_dup_text_string(&aclMap, &subject, &len, NULL);
509                                             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding subject Value.");
510                                             if(strcmp(subject, WILDCARD_RESOURCE_URI) == 0)
511                                             {
512                                                 acl->subject.id[0] = '*';
513                                             }
514                                             else
515                                             {
516                                                 ret = ConvertStrToUuid(subject, &acl->subject);
517                                                 VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
518                                             }
519                                             OICFree(subject);
520                                         }
521
522                                         // Resources -- Mandatory
523                                         if (strcmp(name, OIC_JSON_RESOURCES_NAME) == 0)
524                                         {
525                                             CborValue resources = { .parser = NULL };
526                                             cborFindResult = cbor_value_get_array_length(&aclMap, &acl->resourcesLen);
527                                             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a Resource Array Len Value.");
528                                             cborFindResult = cbor_value_enter_container(&aclMap, &resources);
529                                             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering a Resource Array.");
530
531                                             acl->resources = (char **) OICMalloc(acl->resourcesLen * sizeof(char*));
532                                             VERIFY_NON_NULL(TAG, acl->resources, ERROR);
533                                             int i = 0;
534                                             while (cbor_value_is_valid(&resources))
535                                             {
536                                                 // rMap
537                                                 CborValue rMap = { .parser = NULL  };
538                                                 cborFindResult = cbor_value_enter_container(&resources, &rMap);
539                                                 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Entering Resource Map");
540
541
542                                                 while(cbor_value_is_valid(&rMap))
543                                                 {
544                                                     char *rMapName = NULL;
545                                                     size_t rMapNameLen = 0;
546                                                     cborFindResult = cbor_value_dup_text_string(&rMap, &rMapName, &rMapNameLen, NULL);
547                                                     VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding RMap Data Name Tag.");
548                                                     cborFindResult = cbor_value_advance(&rMap);
549                                                     VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding RMap Data Value.");
550
551                                                     // "href"
552                                                     if (0 == strcmp(OIC_JSON_HREF_NAME, rMapName))
553                                                     {
554                                                         // TODO : Need to check data structure of OicSecAcl_t based on RAML spec.
555                                                         cborFindResult = cbor_value_dup_text_string(&rMap, &acl->resources[i++], &len, NULL);
556                                                         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Href Value.");
557                                                     }
558                                                     // "rel"
559                                                     if (0 == strcmp(OIC_JSON_REL_NAME, rMapName))
560                                                     {
561                                                         // TODO : Need to check data structure of OicSecAcl_t based on RAML spec.
562                                                         char *relData = NULL;
563                                                         cborFindResult = cbor_value_dup_text_string(&rMap, &relData, &len, NULL);
564                                                         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding REL Value.");
565                                                         OICFree(relData);
566                                                     }
567                                                     // "rt"
568                                                     if (0 == strcmp(OIC_JSON_RT_NAME, rMapName))
569                                                     {
570                                                         // TODO : Need to check data structure of OicSecAcl_t and assign based on RAML spec.
571                                                         char *rtData = NULL;
572                                                         cborFindResult = cbor_value_dup_text_string(&rMap, &rtData, &len, NULL);
573                                                         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding RT Value.");
574                                                         OICFree(rtData);
575                                                     }
576
577                                                     // "if"
578                                                     if (0 == strcmp(OIC_JSON_IF_NAME, rMapName))
579                                                     {
580                                                         // TODO : Need to check data structure of OicSecAcl_t and assign based on RAML spec.
581                                                         char *ifData = NULL;
582                                                         cborFindResult = cbor_value_dup_text_string(&rMap, &ifData, &len, NULL);
583                                                         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding IF Value.");
584                                                         OICFree(ifData);
585                                                     }
586
587                                                     if (cbor_value_is_valid(&rMap))
588                                                     {
589                                                         cborFindResult = cbor_value_advance(&rMap);
590                                                         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Rlist Map.");
591                                                     }
592                                                     OICFree(rMapName);
593                                                 }
594
595                                                 if (cbor_value_is_valid(&resources))
596                                                 {
597                                                     cborFindResult = cbor_value_advance(&resources);
598                                                     VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing Resource Array.");
599                                                 }
600                                             }
601                                         }
602
603                                         // Permissions -- Mandatory
604                                         if (strcmp(name, OIC_JSON_PERMISSION_NAME) == 0)
605                                         {
606                                             cborFindResult = cbor_value_get_uint64(&aclMap, (uint64_t *) &acl->permission);
607                                             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a PERM Value.");
608                                         }
609
610                                         // Period -- Not mandatory
611                                         if (strcmp(name, OIC_JSON_PERIOD_NAME) == 0)
612                                         {
613                                             CborValue period = { .parser = NULL };
614                                             cborFindResult = cbor_value_get_array_length(&aclMap, &acl->prdRecrLen);
615                                             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a Period Array Len.");
616                                             cborFindResult = cbor_value_enter_container(&aclMap, &period);
617                                             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a Period Array Map.");
618                                             acl->periods = (char**)OICCalloc(acl->prdRecrLen, sizeof(char*));
619                                             VERIFY_NON_NULL(TAG, acl->periods, ERROR);
620                                             int i = 0;
621                                             while (cbor_value_is_text_string(&period))
622                                             {
623                                                 cborFindResult = cbor_value_dup_text_string(&period, &acl->periods[i++],
624                                                     &len, NULL);
625                                                 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding a Period Array Value.");
626                                                 cborFindResult = cbor_value_advance(&period);
627                                                 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing a Period Array.");
628                                             }
629                                         }
630
631                                         // Recurrence -- Not mandatory
632                                         if (strcmp(name, OIC_JSON_RECURRENCES_NAME) == 0)
633                                         {
634                                             CborValue recurrences = { .parser = NULL };
635                                             cborFindResult = cbor_value_enter_container(&aclMap, &recurrences);
636                                             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Adding Recurrence Array.");
637                                             acl->recurrences = (char**)OICCalloc(acl->prdRecrLen, sizeof(char*));
638                                             VERIFY_NON_NULL(TAG, acl->recurrences, ERROR);
639                                             int i = 0;
640                                             while (cbor_value_is_text_string(&recurrences))
641                                             {
642                                                 cborFindResult = cbor_value_dup_text_string(&recurrences,
643                                                     &acl->recurrences[i++], &len, NULL);
644                                                 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Adding Recurrence Array Value.");
645                                                 cborFindResult = cbor_value_advance(&recurrences);
646                                                 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Closing Recurrence Array.");
647                                             }
648                                         }
649
650                                         OICFree(name);
651                                     }
652
653                                     if (type != CborMapType && cbor_value_is_valid(&aclMap))
654                                     {
655                                         cborFindResult = cbor_value_advance(&aclMap);
656                                         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing the Array.");
657                                     }
658                                 }
659
660                                 acl->next = NULL;
661
662                                 if (cbor_value_is_valid(&aclArray))
663                                 {
664                                     cborFindResult = cbor_value_advance(&aclArray);
665                                     VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing ACL Array.");
666                                 }
667                             }
668                         }
669                         OICFree(acName);
670                     }
671
672                     if (cbor_value_is_valid(&aclistMap))
673                     {
674                         cborFindResult = cbor_value_advance(&aclistMap);
675                         VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing ACLIST Map.");
676                     }
677                 }
678             }
679
680             // TODO : Need to modify headAcl->owners[0].id to headAcl->rowner based on RAML spec.
681             if (strcmp(tagName, OIC_JSON_ROWNERID_NAME)  == 0)
682             {
683                 char *stRowner = NULL;
684                 cborFindResult = cbor_value_dup_text_string(&aclMap, &stRowner, &len, NULL);
685                 VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Finding Rownerid Value.");
686                 ret = ConvertStrToUuid(stRowner, &headAcl->rownerID);
687                 VERIFY_SUCCESS(TAG, ret == OC_STACK_OK, ERROR);
688                 OICFree(stRowner);
689             }
690             OICFree(tagName);
691         }
692         if (cbor_value_is_valid(&aclMap))
693         {
694             cborFindResult = cbor_value_advance(&aclMap);
695             VERIFY_CBOR_SUCCESS(TAG, cborFindResult, "Failed Advancing ACL Map.");
696         }
697     }
698
699 exit:
700     if (cborFindResult != CborNoError)
701     {
702         OIC_LOG(ERROR, TAG, "Failed to CBORPayloadToAcl");
703         DeleteACLList(headAcl);
704         headAcl = NULL;
705     }
706     return headAcl;
707 }
708
709 /**
710  * This method removes ACE for the subject and resource from the ACL
711  *
712  * @param subject of the ACE
713  * @param resource of the ACE
714  *
715  * @return
716  *     ::OC_STACK_RESOURCE_DELETED on success
717  *     ::OC_STACK_NO_RESOURCE on failure to find the appropriate ACE
718  *     ::OC_STACK_INVALID_PARAM on invalid parameter
719  */
720 static OCStackResult RemoveACE(const OicUuid_t * subject, const char * resource)
721 {
722     OIC_LOG(DEBUG, TAG, "IN RemoveACE");
723
724     OicSecAcl_t *acl = NULL;
725     OicSecAcl_t *tempAcl = NULL;
726     bool deleteFlag = false;
727     OCStackResult ret = OC_STACK_NO_RESOURCE;
728
729     if (memcmp(subject->id, &WILDCARD_SUBJECT_ID, sizeof(subject->id)) == 0)
730     {
731         OIC_LOG_V(ERROR, TAG, "%s received invalid parameter", __func__ );
732         return  OC_STACK_INVALID_PARAM;
733     }
734
735     //If resource is NULL then delete all the ACE for the subject.
736     if (NULL == resource || resource[0] == '\0')
737     {
738         LL_FOREACH_SAFE(gAcl, acl, tempAcl)
739         {
740             if (memcmp(acl->subject.id, subject->id, sizeof(subject->id)) == 0)
741             {
742                 LL_DELETE(gAcl, acl);
743                 FreeACE(acl);
744                 deleteFlag = true;
745             }
746         }
747     }
748     else
749     {
750         //Looping through ACL to find the right ACE to delete. If the required resource is the only
751         //resource in the ACE for the subject then delete the whole ACE. If there are more resources
752         //than the required resource in the ACE, for the subject then just delete the resource from
753         //the resource array
754         LL_FOREACH_SAFE(gAcl, acl, tempAcl)
755         {
756             if (memcmp(acl->subject.id, subject->id, sizeof(subject->id)) == 0)
757             {
758                 if (1 == acl->resourcesLen && strcmp(acl->resources[0], resource) == 0)
759                 {
760                     LL_DELETE(gAcl, acl);
761                     FreeACE(acl);
762                     deleteFlag = true;
763                     break;
764                 }
765                 else
766                 {
767                     size_t resPos = -1;
768                     size_t i;
769                     for (i = 0; i < acl->resourcesLen; i++)
770                     {
771                         if (strcmp(acl->resources[i], resource) == 0)
772                         {
773                             resPos = i;
774                             break;
775                         }
776                     }
777                     if (0 <= (int) resPos)
778                     {
779                         OICFree(acl->resources[resPos]);
780                         acl->resources[resPos] = NULL;
781                         acl->resourcesLen -= 1;
782                         for (i = resPos; i < acl->resourcesLen; i++)
783                         {
784                             acl->resources[i] = acl->resources[i + 1];
785                         }
786                         deleteFlag = true;
787                         break;
788                     }
789                 }
790             }
791         }
792     }
793
794     if (deleteFlag)
795     {
796         // In case of unit test do not update persistant storage.
797         if (memcmp(subject->id, &WILDCARD_SUBJECT_B64_ID, sizeof(subject->id)) == 0)
798         {
799             ret = OC_STACK_RESOURCE_DELETED;
800         }
801         else
802         {
803             uint8_t *payload = NULL;
804             size_t size = 0;
805             if (OC_STACK_OK == AclToCBORPayload(gAcl, &payload, &size))
806             {
807                 if (OC_STACK_OK == UpdateSecureResourceInPS(OIC_JSON_ACL_NAME, payload, size))
808                 {
809                     ret = OC_STACK_RESOURCE_DELETED;
810                 }
811                 OICFree(payload);
812             }
813         }
814     }
815     return ret;
816 }
817
818 /**
819  * This method parses the query string received for REST requests and
820  * retrieves the 'subject' field.
821  *
822  * @param query querystring passed in REST request
823  * @param subject subject UUID parsed from query string
824  *
825  * @return true if query parsed successfully and found 'subject', else false.
826  */
827 static bool GetSubjectFromQueryString(const char *query, OicUuid_t *subject)
828 {
829     OicParseQueryIter_t parseIter = { .attrPos = NULL };
830
831     ParseQueryIterInit((unsigned char *) query, &parseIter);
832
833     while (GetNextQuery (&parseIter))
834     {
835         if (strncasecmp((char *) parseIter.attrPos, OIC_JSON_SUBJECTID_NAME, parseIter.attrLen) == 0)
836         {
837             char strUuid[STRING_UUID_SIZE] = {0};
838             VERIFY_SUCCESS(TAG, 0 != parseIter.valLen, ERROR);
839             memcpy(strUuid, parseIter.valPos, parseIter.valLen);
840             OCStackResult res = ConvertStrToUuid(strUuid, subject);
841             VERIFY_SUCCESS(TAG, OC_STACK_OK == res, ERROR);
842             return true;
843         }
844     }
845
846 exit:
847     return false;
848 }
849
850 /**
851  * This method parses the query string received for REST requests and
852  * retrieves the 'resource' field.
853  *
854  * @param query querystring passed in REST request
855  * @param resource resource parsed from query string
856  * @param resourceSize size of the memory pointed to resource
857  *
858  * @return true if query parsed successfully and found 'resource', else false.
859  */
860 static bool GetResourceFromQueryString(const char *query, char *resource, size_t resourceSize)
861 {
862     OicParseQueryIter_t parseIter = { .attrPos = NULL };
863
864     ParseQueryIterInit((unsigned char *) query, &parseIter);
865
866     while (GetNextQuery (&parseIter))
867     {
868         if (strncasecmp((char *) parseIter.attrPos, OIC_JSON_RESOURCES_NAME, parseIter.attrLen)
869                 == 0)
870         {
871             VERIFY_SUCCESS(TAG, 0 != parseIter.valLen, ERROR);
872             OICStrcpy(resource, resourceSize, (char *) parseIter.valPos);
873
874             return true;
875         }
876     }
877
878 exit:
879    return false;
880 }
881
882 static OCEntityHandlerResult HandleACLGetRequest(const OCEntityHandlerRequest *ehRequest)
883 {
884     OIC_LOG(INFO, TAG, "HandleACLGetRequest processing the request");
885     uint8_t* payload = NULL;
886     size_t size = 0;
887     OCEntityHandlerResult ehRet;
888
889     // Process the REST querystring parameters
890     if (ehRequest->query)
891     {
892         OIC_LOG(DEBUG, TAG, "HandleACLGetRequest processing query");
893
894         OicUuid_t subject = {.id= { 0 } };
895         char resource[MAX_URI_LENGTH] = { 0 };
896
897         OicSecAcl_t *savePtr = NULL;
898         const OicSecAcl_t *currentAce = NULL;
899
900         // 'Subject' field is MUST for processing a querystring in REST request.
901         VERIFY_SUCCESS(TAG, true == GetSubjectFromQueryString(ehRequest->query, &subject), ERROR);
902
903         GetResourceFromQueryString(ehRequest->query, resource, sizeof(resource));
904
905         /*
906          * TODO : Currently, this code only provides one ACE for a Subject.
907          * Below code needs to be updated for scenarios when Subject have
908          * multiple ACE's in ACL resource.
909          */
910         while ((currentAce = GetACLResourceData(&subject, &savePtr)))
911         {
912             /*
913              * If REST querystring contains a specific resource, we need
914              * to search for that resource in ACE.
915              */
916             if (resource[0] != '\0')
917             {
918                 for (size_t n = 0; n < currentAce->resourcesLen; n++)
919                 {
920                     if ((currentAce->resources[n])
921                             && (0 == strcmp(resource, currentAce->resources[n])
922                                     || 0 == strcmp(WILDCARD_RESOURCE_URI, currentAce->resources[n])))
923                     {
924                         // Convert ACL data into CBOR format for transmission
925                         if (OC_STACK_OK != AclToCBORPayload(currentAce, &payload, &size))
926                         {
927                             ehRet = OC_EH_ERROR;
928                         }
929                         goto exit;
930                     }
931                 }
932             }
933             else
934             {
935                 // Convert ACL data into CBOR format for transmission
936                 if (OC_STACK_OK != AclToCBORPayload(currentAce, &payload, &size))
937                 {
938                     ehRet = OC_EH_ERROR;
939                 }
940                 goto exit;
941             }
942         }
943     }
944     else
945     {
946         // Convert ACL data into CBOR format for transmission.
947         if (OC_STACK_OK != AclToCBORPayload(gAcl, &payload, &size))
948         {
949             ehRet = OC_EH_ERROR;
950         }
951     }
952 exit:
953     // A device should always have a default acl. Therefore, payload should never be NULL.
954     ehRet = (payload ? OC_EH_OK : OC_EH_ERROR);
955
956     // Send response payload to request originator
957     if (OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, payload, size))
958     {
959         ehRet = OC_EH_ERROR;
960         OIC_LOG(ERROR, TAG, "SendSRMResponse failed for HandleACLGetRequest");
961     }
962     OICFree(payload);
963
964     OIC_LOG_V(DEBUG, TAG, "%s RetVal %d", __func__, ehRet);
965     return ehRet;
966 }
967
968 static OCEntityHandlerResult HandleACLPostRequest(const OCEntityHandlerRequest *ehRequest)
969 {
970     OIC_LOG(INFO, TAG, "HandleACLPostRequest processing the request");
971     OCEntityHandlerResult ehRet = OC_EH_ERROR;
972
973     // Convert CBOR into ACL data and update to SVR buffers. This will also validate the ACL data received.
974     uint8_t *payload = ((OCSecurityPayload *) ehRequest->payload)->securityData;
975     size_t size = ((OCSecurityPayload *) ehRequest->payload)->payloadSize;
976     if (payload)
977     {
978         OicSecAcl_t *newAcl = CBORPayloadToAcl(payload, size);
979         if (newAcl)
980         {
981             // Append the new ACL to existing ACL
982             LL_APPEND(gAcl, newAcl);
983             size_t size = 0;
984             // In case of unit test do not update persistant storage.
985             if (memcmp(newAcl->subject.id, &WILDCARD_SUBJECT_ID, sizeof(newAcl->subject.id)) == 0
986                 || memcmp(newAcl->subject.id, &WILDCARD_SUBJECT_B64_ID, sizeof(newAcl->subject.id)) == 0)
987             {
988                 ehRet = OC_EH_RESOURCE_CREATED;
989             }
990             else
991             {
992                 uint8_t *cborPayload = NULL;
993                 if (OC_STACK_OK == AclToCBORPayload(gAcl, &cborPayload, &size))
994                 {
995                     if (UpdateSecureResourceInPS(OIC_JSON_ACL_NAME, cborPayload, size) == OC_STACK_OK)
996                     {
997                         ehRet = OC_EH_RESOURCE_CREATED;
998                     }
999                     OICFree(cborPayload);
1000                 }
1001             }
1002         }
1003     }
1004
1005     // Send payload to request originator
1006     if (OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, NULL, 0))
1007     {
1008         ehRet = OC_EH_ERROR;
1009         OIC_LOG(ERROR, TAG, "SendSRMResponse failed in HandleACLPostRequest");
1010     }
1011
1012     OIC_LOG_V(DEBUG, TAG, "%s RetVal %d", __func__, ehRet);
1013     return ehRet;
1014 }
1015
1016 static OCEntityHandlerResult HandleACLDeleteRequest(const OCEntityHandlerRequest *ehRequest)
1017 {
1018     OIC_LOG(DEBUG, TAG, "Processing ACLDeleteRequest");
1019     OCEntityHandlerResult ehRet = OC_EH_ERROR;
1020     OicUuid_t subject = { .id= { 0 } };
1021     char resource[MAX_URI_LENGTH] = { 0 };
1022
1023     VERIFY_NON_NULL(TAG, ehRequest->query, ERROR);
1024
1025     // 'Subject' field is MUST for processing a querystring in REST request.
1026     VERIFY_SUCCESS(TAG, true == GetSubjectFromQueryString(ehRequest->query, &subject), ERROR);
1027
1028     GetResourceFromQueryString(ehRequest->query, resource, sizeof(resource));
1029
1030     if (OC_STACK_RESOURCE_DELETED == RemoveACE(&subject, resource))
1031     {
1032         ehRet = OC_EH_RESOURCE_DELETED;
1033     }
1034
1035 exit:
1036     // Send payload to request originator
1037     if (OC_STACK_OK != SendSRMResponse(ehRequest, ehRet, NULL, 0))
1038     {
1039         ehRet = OC_EH_ERROR;
1040         OIC_LOG(ERROR, TAG, "SendSRMResponse failed in HandleACLDeleteRequest");
1041     }
1042
1043     return ehRet;
1044 }
1045
1046 OCEntityHandlerResult ACLEntityHandler(OCEntityHandlerFlag flag, OCEntityHandlerRequest * ehRequest,
1047         void* callbackParameter)
1048 {
1049     OIC_LOG(DEBUG, TAG, "Received request ACLEntityHandler");
1050     (void)callbackParameter;
1051     OCEntityHandlerResult ehRet = OC_EH_ERROR;
1052
1053     if (!ehRequest)
1054     {
1055         return ehRet;
1056     }
1057
1058     if (flag & OC_REQUEST_FLAG)
1059     {
1060         // TODO :  Handle PUT method
1061         OIC_LOG(DEBUG, TAG, "Flag includes OC_REQUEST_FLAG");
1062         switch (ehRequest->method)
1063         {
1064             case OC_REST_GET:
1065                 ehRet = HandleACLGetRequest(ehRequest);
1066                 break;
1067
1068             case OC_REST_POST:
1069                 ehRet = HandleACLPostRequest(ehRequest);
1070                 break;
1071
1072             case OC_REST_DELETE:
1073                 ehRet = HandleACLDeleteRequest(ehRequest);
1074                 break;
1075
1076             default:
1077                 ehRet = OC_EH_ERROR;
1078                 SendSRMResponse(ehRequest, ehRet, NULL, 0);
1079         }
1080     }
1081
1082     return ehRet;
1083 }
1084
1085 /**
1086  * This internal method is used to create '/oic/sec/acl' resource.
1087  */
1088 static OCStackResult CreateACLResource()
1089 {
1090     OCStackResult ret;
1091
1092     ret = OCCreateResource(&gAclHandle,
1093                            OIC_RSRC_TYPE_SEC_ACL,
1094                            OIC_MI_DEF,
1095                            OIC_RSRC_ACL_URI,
1096                            ACLEntityHandler,
1097                            NULL,
1098                            OC_OBSERVABLE | OC_SECURE | OC_EXPLICIT_DISCOVERABLE);
1099
1100     if (OC_STACK_OK != ret)
1101     {
1102         OIC_LOG(FATAL, TAG, "Unable to instantiate ACL resource");
1103         DeInitACLResource();
1104     }
1105     return ret;
1106 }
1107
1108 // This function sets the default ACL and is defined for the unit test only.
1109 OCStackResult SetDefaultACL(OicSecAcl_t *acl)
1110 {
1111     gAcl = acl;
1112     return OC_STACK_OK;
1113 }
1114
1115 OCStackResult GetDefaultACL(OicSecAcl_t** defaultAcl)
1116 {
1117     OCStackResult ret = OC_STACK_ERROR;
1118
1119     OicUuid_t ownerId = { .id = { 0 } };
1120
1121     /*
1122      * TODO In future, when new virtual resources will be added in OIC
1123      * specification, Iotivity stack should be able to add them in
1124      * existing SVR database. To support this, we need to add 'versioning'
1125      * mechanism in SVR database.
1126      */
1127
1128     const char *rsrcs[] = {
1129         OC_RSRVD_WELL_KNOWN_URI,
1130         OC_RSRVD_DEVICE_URI,
1131         OC_RSRVD_PLATFORM_URI,
1132         OC_RSRVD_RESOURCE_TYPES_URI,
1133 #ifdef WITH_PRESENCE
1134         OC_RSRVD_PRESENCE_URI,
1135 #endif //WITH_PRESENCE
1136         OIC_RSRC_ACL_URI,
1137         OIC_RSRC_DOXM_URI,
1138         OIC_RSRC_PSTAT_URI,
1139     };
1140
1141     if (!defaultAcl)
1142     {
1143         return OC_STACK_INVALID_PARAM;
1144     }
1145
1146     OicSecAcl_t *acl = (OicSecAcl_t *) OICCalloc(1, sizeof(OicSecAcl_t));
1147     VERIFY_NON_NULL(TAG, acl, ERROR);
1148
1149     // Subject -- Mandatory
1150     memcpy(&(acl->subject), &WILDCARD_SUBJECT_ID, sizeof(acl->subject));
1151
1152     // Resources -- Mandatory
1153     acl->resourcesLen = sizeof(rsrcs) / sizeof(rsrcs[0]);
1154
1155     acl->resources = (char**) OICCalloc(acl->resourcesLen, sizeof(char*));
1156     VERIFY_NON_NULL(TAG, (acl->resources), ERROR);
1157
1158     for (size_t i = 0; i < acl->resourcesLen; i++)
1159     {
1160         size_t len = strlen(rsrcs[i]) + 1;
1161         acl->resources[i] = (char*) OICMalloc(len * sizeof(char));
1162         VERIFY_NON_NULL(TAG, (acl->resources[i]), ERROR);
1163         OICStrcpy(acl->resources[i], len, rsrcs[i]);
1164     }
1165
1166     acl->permission = PERMISSION_READ;
1167     acl->prdRecrLen = 0;
1168     acl->periods = NULL;
1169     acl->recurrences = NULL;
1170
1171     // Device ID is the owner of this default ACL
1172     if (GetDoxmResourceData() != NULL)
1173     {
1174         ret = GetDoxmDeviceID(&ownerId);
1175         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, FATAL);
1176     }
1177     else
1178     {
1179         OCRandomUuidResult rdm = OCGenerateUuid(ownerId.id);
1180         VERIFY_SUCCESS(TAG, RAND_UUID_OK == rdm, FATAL);
1181     }
1182
1183     memcpy(&acl->rownerID, &ownerId, sizeof(OicUuid_t));
1184
1185     acl->next = NULL;
1186
1187     *defaultAcl = acl;
1188     ret = OC_STACK_OK;
1189
1190 exit:
1191
1192     if (ret != OC_STACK_OK)
1193     {
1194         DeleteACLList(acl);
1195         acl = NULL;
1196     }
1197
1198     return ret;
1199 }
1200
1201 OCStackResult InitACLResource()
1202 {
1203     OCStackResult ret = OC_STACK_ERROR;
1204
1205     uint8_t *data = NULL;
1206     size_t size = 0;
1207     ret = GetSecureVirtualDatabaseFromPS(OIC_JSON_ACL_NAME, &data, &size);
1208     // If database read failed
1209     if (ret != OC_STACK_OK)
1210     {
1211         OIC_LOG(DEBUG, TAG, "ReadSVDataFromPS failed");
1212     }
1213     if (data)
1214     {
1215         // Read ACL resource from PS
1216         gAcl = CBORPayloadToAcl(data, size);
1217     }
1218     /*
1219      * If SVR database in persistent storage got corrupted or
1220      * is not available for some reason, a default ACL is created
1221      * which allows user to initiate ACL provisioning again.
1222      */
1223     if (!gAcl)
1224     {
1225         GetDefaultACL(&gAcl);
1226         // TODO Needs to update persistent storage
1227     }
1228     VERIFY_NON_NULL(TAG, gAcl, FATAL);
1229
1230     // Instantiate 'oic.sec.acl'
1231     ret = CreateACLResource();
1232
1233 exit:
1234     if (OC_STACK_OK != ret)
1235     {
1236         DeInitACLResource();
1237     }
1238     return ret;
1239 }
1240
1241 OCStackResult DeInitACLResource()
1242 {
1243     OCStackResult ret =  OCDeleteResource(gAclHandle);
1244     gAclHandle = NULL;
1245
1246     if (gAcl)
1247     {
1248         DeleteACLList(gAcl);
1249         gAcl = NULL;
1250     }
1251     return ret;
1252 }
1253
1254 const OicSecAcl_t* GetACLResourceData(const OicUuid_t* subjectId, OicSecAcl_t **savePtr)
1255 {
1256     OicSecAcl_t *acl = NULL;
1257     OicSecAcl_t *begin = NULL;
1258
1259     if (NULL == subjectId)
1260     {
1261         return NULL;
1262     }
1263
1264     /*
1265      * savePtr MUST point to NULL if this is the 'first' call to retrieve ACL for
1266      * subjectID.
1267      */
1268     if (NULL == *savePtr)
1269     {
1270         begin = gAcl;
1271     }
1272     else
1273     {
1274         /*
1275          * If this is a 'successive' call, search for location pointed by
1276          * savePtr and assign 'begin' to the next ACL after it in the linked
1277          * list and start searching from there.
1278          */
1279         LL_FOREACH(gAcl, acl)
1280         {
1281             if (acl == *savePtr)
1282             {
1283                 begin = acl->next;
1284             }
1285         }
1286     }
1287
1288     // Find the next ACL corresponding to the 'subjectID' and return it.
1289     LL_FOREACH(begin, acl)
1290     {
1291         if (memcmp(&(acl->subject), subjectId, sizeof(OicUuid_t)) == 0)
1292         {
1293             *savePtr = acl;
1294             return acl;
1295         }
1296     }
1297
1298     // Cleanup in case no ACL is found
1299     *savePtr = NULL;
1300     return NULL;
1301 }
1302
1303 OCStackResult InstallNewACL(const uint8_t *cborPayload, const size_t size)
1304 {
1305     OCStackResult ret = OC_STACK_ERROR;
1306
1307     // Convert CBOR format to ACL data. This will also validate the ACL data received.
1308     OicSecAcl_t* newAcl = CBORPayloadToAcl(cborPayload, size);
1309
1310     if (newAcl)
1311     {
1312         // Append the new ACL to existing ACL
1313         LL_APPEND(gAcl, newAcl);
1314
1315         // Update persistent storage only if it is not WILDCARD_SUBJECT_ID
1316         if (memcmp(newAcl->subject.id, &WILDCARD_SUBJECT_ID, sizeof(newAcl->subject.id)) == 0
1317             || memcmp(newAcl->subject.id, &WILDCARD_SUBJECT_B64_ID, sizeof(newAcl->subject.id)) == 0)
1318         {
1319             ret = OC_STACK_OK;
1320         }
1321         else
1322         {
1323             size_t size = 0;
1324             uint8_t *payload = NULL;
1325             if (OC_STACK_OK == AclToCBORPayload(gAcl, &payload, &size))
1326             {
1327                 if (UpdateSecureResourceInPS(OIC_JSON_ACL_NAME, payload, size) == OC_STACK_OK)
1328                 {
1329                     ret = OC_STACK_OK;
1330                 }
1331                 OICFree(payload);
1332             }
1333         }
1334     }
1335
1336     return ret;
1337 }
1338
1339 /**
1340  * This function generates default ACL for security resource in case of owned status.
1341  *
1342  * @return Default ACL for security resource.
1343  */
1344 static OicSecAcl_t* GetSecDefaultACL()
1345 {
1346     const char *sec_rsrcs[] = {
1347         OIC_RSRC_DOXM_URI,
1348         OIC_RSRC_PSTAT_URI
1349     };
1350     OicUuid_t ownerId = {.id = {0}};
1351     OCStackResult res = OC_STACK_ERROR;
1352     OicSecAcl_t* newDefaultAcl = (OicSecAcl_t*)OICCalloc(1, sizeof(OicSecAcl_t));
1353     VERIFY_NON_NULL(TAG, newDefaultAcl, ERROR);
1354
1355     // Subject -- Mandatory
1356     memcpy(&(newDefaultAcl->subject), &WILDCARD_SUBJECT_ID, WILDCARD_SUBJECT_ID_LEN);
1357
1358     // Resources -- Mandatory
1359     newDefaultAcl->resourcesLen = NUMBER_OF_DEFAULT_SEC_RSCS;
1360     newDefaultAcl->resources = (char**)OICCalloc(NUMBER_OF_DEFAULT_SEC_RSCS, sizeof(char*));
1361     VERIFY_NON_NULL(TAG, (newDefaultAcl->resources), ERROR);
1362
1363     for (size_t i = 0; i <  NUMBER_OF_DEFAULT_SEC_RSCS; i++)
1364     {
1365         size_t len = strlen(sec_rsrcs[i]) + 1;
1366         newDefaultAcl->resources[i] = (char*)OICMalloc(len * sizeof(char));
1367         VERIFY_NON_NULL(TAG, (newDefaultAcl->resources[i]), ERROR);
1368         OICStrcpy(newDefaultAcl->resources[i], len, sec_rsrcs[i]);
1369     }
1370
1371     // Permissions -- Mandatory
1372     newDefaultAcl->permission = PERMISSION_READ;
1373
1374     //Period -- Not Mandatory
1375     newDefaultAcl->prdRecrLen = 0;
1376     newDefaultAcl->periods = NULL;
1377
1378     //Recurrence -- Not Mandatory
1379     newDefaultAcl->recurrences = NULL;
1380
1381     // Device ID is the owner of this default ACL
1382     res = GetDoxmDeviceID(&ownerId);
1383     VERIFY_SUCCESS(TAG, OC_STACK_OK == res, FATAL);
1384
1385     // Owners -- Mandatory
1386     memcpy(&newDefaultAcl->rownerID, &ownerId, sizeof(OicUuid_t));
1387
1388     return newDefaultAcl;
1389 exit:
1390     DeleteACLList(newDefaultAcl);
1391     return NULL;
1392
1393 }
1394
1395 OCStackResult UpdateDefaultSecProvACL()
1396 {
1397     OCStackResult ret = OC_STACK_OK;
1398     OicSecAcl_t *acl = NULL;
1399     OicSecAcl_t *tmp = NULL;
1400
1401     if(gAcl)
1402     {
1403         int matchedRsrc = 0;
1404         bool isRemoved = false;
1405
1406         LL_FOREACH_SAFE(gAcl, acl, tmp)
1407         {
1408             //Find default security resource ACL
1409             if(memcmp(&acl->subject, &WILDCARD_SUBJECT_ID, sizeof(OicUuid_t)) == 0 &&
1410                 ((PERMISSION_READ | PERMISSION_WRITE) == acl->permission))
1411             {
1412                 matchedRsrc = 0;
1413
1414                 for(size_t i = 0; i < acl->resourcesLen; i++)
1415                 {
1416                     if(strncmp(acl->resources[i], OIC_RSRC_DOXM_URI,
1417                                strlen(OIC_RSRC_DOXM_URI) + 1) == 0 ||
1418                        strncmp(acl->resources[i], OIC_RSRC_CRED_URI,
1419                                strlen(OIC_RSRC_CRED_URI) + 1) == 0 ||
1420                        strncmp(acl->resources[i], OIC_RSRC_ACL_URI,
1421                                strlen(OIC_RSRC_ACL_URI) + 1) == 0 ||
1422                        strncmp(acl->resources[i], OIC_RSRC_PSTAT_URI,
1423                                strlen(OIC_RSRC_PSTAT_URI) + 1) == 0)
1424                     {
1425                         matchedRsrc++;
1426                     }
1427                 }
1428
1429                 //If default security resource ACL is detected, delete it.
1430                 if(NUMBER_OF_SEC_PROV_RSCS == matchedRsrc)
1431                 {
1432                     LL_DELETE(gAcl, acl);
1433                     FreeACE(acl);
1434                     isRemoved = true;
1435                 }
1436             }
1437         }
1438
1439         if(isRemoved)
1440         {
1441             /*
1442              * Generate new security resource ACL as follows :
1443              *      subject : "*"
1444              *      resources :  '/oic/sec/doxm', '/oic/sec/pstat'
1445              *      permission : READ
1446              */
1447             OicSecAcl_t *newDefaultAcl = GetSecDefaultACL();
1448             if (newDefaultAcl)
1449             {
1450                 LL_APPEND(gAcl, newDefaultAcl);
1451
1452                 size_t size = 0;
1453                 uint8_t *payload = NULL;
1454                 if (OC_STACK_OK == AclToCBORPayload(gAcl, &payload, &size))
1455                 {
1456                     if (UpdateSecureResourceInPS(OIC_JSON_ACL_NAME, payload, size) == OC_STACK_OK)
1457                     {
1458                         ret = OC_STACK_OK;
1459                     }
1460                     OICFree(payload);
1461                 }
1462             }
1463         }
1464     }
1465
1466     return ret;
1467 }
1468
1469 OCStackResult SetAclRownerId(const OicUuid_t* newROwner)
1470 {
1471     OCStackResult ret = OC_STACK_ERROR;
1472     uint8_t *cborPayload = NULL;
1473     size_t size = 0;
1474     OicUuid_t prevId = {.id={0}};
1475
1476     if(NULL == newROwner)
1477     {
1478         ret = OC_STACK_INVALID_PARAM;
1479     }
1480     if(NULL == gAcl)
1481     {
1482         ret = OC_STACK_NO_RESOURCE;
1483     }
1484
1485     if(newROwner && gAcl)
1486     {
1487         memcpy(prevId.id, gAcl->rownerID.id, sizeof(prevId.id));
1488         memcpy(gAcl->rownerID.id, newROwner->id, sizeof(newROwner->id));
1489
1490         ret = AclToCBORPayload(gAcl, &cborPayload, &size);
1491         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
1492
1493         ret = UpdateSecureResourceInPS(OIC_JSON_ACL_NAME, cborPayload, size);
1494         VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, ERROR);
1495
1496         OICFree(cborPayload);
1497     }
1498
1499     return ret;
1500
1501 exit:
1502     OICFree(cborPayload);
1503     memcpy(gAcl->rownerID.id, prevId.id, sizeof(prevId.id));
1504     return ret;
1505 }
1506
1507 OCStackResult GetAclRownerId(OicUuid_t *rowneruuid)
1508 {
1509     OCStackResult retVal = OC_STACK_ERROR;
1510     if (gAcl)
1511     {
1512         *rowneruuid = gAcl->rownerID;
1513         retVal = OC_STACK_OK;
1514     }
1515     return retVal;
1516 }