Fixed compiler warnings
[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 #include <stdlib.h>
22 #include <string.h>
23 #include "ocstack.h"
24 #include "logger.h"
25 #include "oic_malloc.h"
26 #include "oic_string.h"
27 #include "cJSON.h"
28 #include "base64.h"
29 #include "resourcemanager.h"
30 #include "aclresource.h"
31 #include "psinterface.h"
32 #include "utlist.h"
33 #include "srmresourcestrings.h"
34 #include "doxmresource.h"
35 #include "srmutility.h"
36 #include "ocserverrequest.h"
37 #include <stdlib.h>
38 #ifdef WITH_ARDUINO
39 #include <string.h>
40 #else
41 #include <strings.h>
42 #endif
43
44 #define TAG  PCF("SRM-ACL")
45
46 OicSecAcl_t               *gAcl = NULL;
47 static OCResourceHandle    gAclHandle = NULL;
48
49 /**
50  * This function frees OicSecAcl_t object's fields and object itself.
51  */
52 static void FreeACE(OicSecAcl_t *ace)
53 {
54     size_t i;
55     if(NULL == ace)
56     {
57         OC_LOG (INFO, TAG, PCF("Invalid Parameter"));
58         return;
59     }
60
61     // Clean Resources
62     for (i = 0; i < ace->resourcesLen; i++)
63     {
64         OICFree(ace->resources[i]);
65     }
66     OICFree(ace->resources);
67
68     //Clean Period & Recurrence
69     for(i = 0; i < ace->prdRecrLen; i++)
70     {
71         OICFree(ace->periods[i]);
72         OICFree(ace->recurrences[i]);
73     }
74     OICFree(ace->periods);
75     OICFree(ace->recurrences);
76
77     // Clean Owners
78     OICFree(ace->owners);
79
80     // Clean ACL node itself
81     OICFree(ace);
82 }
83
84 void DeleteACLList(OicSecAcl_t* acl)
85 {
86     if (acl)
87     {
88         OicSecAcl_t *aclTmp1 = NULL;
89         OicSecAcl_t *aclTmp2 = NULL;
90         LL_FOREACH_SAFE(acl, aclTmp1, aclTmp2)
91         {
92             LL_DELETE(acl, aclTmp1);
93             FreeACE(aclTmp1);
94         }
95     }
96 }
97
98 /*
99  * This internal method converts ACL data into JSON format.
100  *
101  * Note: Caller needs to invoke 'free' when finished done using
102  * return string.
103  */
104 char * BinToAclJSON(const OicSecAcl_t * acl)
105 {
106     cJSON *jsonRoot = NULL;
107     char *jsonStr = NULL;
108
109     if (acl)
110     {
111         jsonRoot = cJSON_CreateObject();
112         VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
113
114         cJSON *jsonAclArray = NULL;
115         cJSON_AddItemToObject (jsonRoot, OIC_JSON_ACL_NAME, jsonAclArray = cJSON_CreateArray());
116         VERIFY_NON_NULL(TAG, jsonAclArray, ERROR);
117
118         while(acl)
119         {
120             char base64Buff[B64ENCODE_OUT_SAFESIZE(sizeof(((OicUuid_t*)0)->id)) + 1] = {};
121             uint32_t outLen = 0;
122             size_t inLen = 0;
123             B64Result b64Ret = B64_OK;
124
125             cJSON *jsonAcl = cJSON_CreateObject();
126
127             // Subject -- Mandatory
128             outLen = 0;
129             if (memcmp(&(acl->subject), &WILDCARD_SUBJECT_ID, sizeof(OicUuid_t)) == 0)
130             {
131                 inLen = WILDCARD_SUBJECT_ID_LEN;
132             }
133             else
134             {
135                 inLen =  sizeof(OicUuid_t);
136             }
137             b64Ret = b64Encode(acl->subject.id, inLen, base64Buff,
138                 sizeof(base64Buff), &outLen);
139             VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
140             cJSON_AddStringToObject(jsonAcl, OIC_JSON_SUBJECT_NAME, base64Buff );
141
142             // Resources -- Mandatory
143             cJSON *jsonRsrcArray = NULL;
144             cJSON_AddItemToObject (jsonAcl, OIC_JSON_RESOURCES_NAME, jsonRsrcArray = cJSON_CreateArray());
145             VERIFY_NON_NULL(TAG, jsonRsrcArray, ERROR);
146             for (size_t i = 0; i < acl->resourcesLen; i++)
147             {
148                 cJSON_AddItemToArray (jsonRsrcArray, cJSON_CreateString(acl->resources[i]));
149             }
150
151             // Permissions -- Mandatory
152             cJSON_AddNumberToObject (jsonAcl, OIC_JSON_PERMISSION_NAME, acl->permission);
153
154             //Period & Recurrence -- Not Mandatory
155             if(0 != acl->prdRecrLen)
156             {
157                 cJSON *jsonPeriodArray = NULL;
158                 cJSON_AddItemToObject (jsonAcl, OIC_JSON_PERIODS_NAME,
159                         jsonPeriodArray = cJSON_CreateArray());
160                 VERIFY_NON_NULL(TAG, jsonPeriodArray, ERROR);
161                 for (size_t i = 0; i < acl->prdRecrLen; i++)
162                 {
163                     cJSON_AddItemToArray (jsonPeriodArray,
164                             cJSON_CreateString(acl->periods[i]));
165                 }
166             }
167
168             //Recurrence -- Not Mandatory
169             if(0 != acl->prdRecrLen && acl->recurrences)
170             {
171                 cJSON *jsonRecurArray  = NULL;
172                 cJSON_AddItemToObject (jsonAcl, OIC_JSON_RECURRENCES_NAME,
173                         jsonRecurArray = cJSON_CreateArray());
174                 VERIFY_NON_NULL(TAG, jsonRecurArray, ERROR);
175                 for (size_t i = 0; i < acl->prdRecrLen; i++)
176                 {
177                     cJSON_AddItemToArray (jsonRecurArray,
178                             cJSON_CreateString(acl->recurrences[i]));
179                 }
180             }
181
182             // Owners -- Mandatory
183             cJSON *jsonOwnrArray = NULL;
184             cJSON_AddItemToObject (jsonAcl, OIC_JSON_OWNERS_NAME, jsonOwnrArray = cJSON_CreateArray());
185             VERIFY_NON_NULL(TAG, jsonOwnrArray, ERROR);
186             for (size_t i = 0; i < acl->ownersLen; i++)
187             {
188                 outLen = 0;
189
190                 b64Ret = b64Encode(acl->owners[i].id, sizeof(((OicUuid_t*)0)->id), base64Buff,
191                     sizeof(base64Buff), &outLen);
192                 VERIFY_SUCCESS(TAG, b64Ret == B64_OK, ERROR);
193
194                 cJSON_AddItemToArray (jsonOwnrArray, cJSON_CreateString(base64Buff));
195             }
196
197             // Attach current acl node to Acl Array
198             cJSON_AddItemToArray(jsonAclArray, jsonAcl);
199             acl = acl->next;
200         }
201
202         jsonStr = cJSON_PrintUnformatted(jsonRoot);
203     }
204
205 exit:
206     if (jsonRoot)
207     {
208         cJSON_Delete(jsonRoot);
209     }
210     return jsonStr;
211 }
212
213 /*
214  * This internal method converts JSON ACL into binary ACL.
215  */
216 OicSecAcl_t * JSONToAclBin(const char * jsonStr)
217 {
218     OCStackResult ret = OC_STACK_ERROR;
219     OicSecAcl_t * headAcl = NULL;
220     OicSecAcl_t * prevAcl = NULL;
221     cJSON *jsonRoot = NULL;
222     cJSON *jsonAclArray = NULL;
223
224     VERIFY_NON_NULL(TAG, jsonStr, ERROR);
225
226     jsonRoot = cJSON_Parse(jsonStr);
227     VERIFY_NON_NULL(TAG, jsonRoot, ERROR);
228
229     jsonAclArray = cJSON_GetObjectItem(jsonRoot, OIC_JSON_ACL_NAME);
230     VERIFY_NON_NULL(TAG, jsonAclArray, ERROR);
231
232     if (cJSON_Array == jsonAclArray->type)
233     {
234         int numAcl = cJSON_GetArraySize(jsonAclArray);
235         int idx = 0;
236
237         VERIFY_SUCCESS(TAG, numAcl > 0, INFO);
238         do
239         {
240             cJSON *jsonAcl = cJSON_GetArrayItem(jsonAclArray, idx);
241             VERIFY_NON_NULL(TAG, jsonAcl, ERROR);
242
243             OicSecAcl_t *acl = (OicSecAcl_t*)OICCalloc(1, sizeof(OicSecAcl_t));
244             VERIFY_NON_NULL(TAG, acl, ERROR);
245
246             headAcl = (headAcl) ? headAcl : acl;
247             if (prevAcl)
248             {
249                 prevAcl->next = acl;
250             }
251
252             size_t jsonObjLen = 0;
253             cJSON *jsonObj = NULL;
254
255             unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
256             uint32_t outLen = 0;
257             B64Result b64Ret = B64_OK;
258
259             // Subject -- Mandatory
260             jsonObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_SUBJECT_NAME);
261             VERIFY_NON_NULL(TAG, jsonObj, ERROR);
262             VERIFY_SUCCESS(TAG, cJSON_String == jsonObj->type, ERROR);
263             outLen = 0;
264             b64Ret = b64Decode(jsonObj->valuestring, strlen(jsonObj->valuestring), base64Buff,
265                         sizeof(base64Buff), &outLen);
266             VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(acl->subject.id)), ERROR);
267             memcpy(acl->subject.id, base64Buff, outLen);
268
269             // Resources -- Mandatory
270             jsonObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_RESOURCES_NAME);
271             VERIFY_NON_NULL(TAG, jsonObj, ERROR);
272             VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
273
274             acl->resourcesLen = cJSON_GetArraySize(jsonObj);
275             VERIFY_SUCCESS(TAG, acl->resourcesLen > 0, ERROR);
276             acl->resources = (char**)OICCalloc(acl->resourcesLen, sizeof(char*));
277             VERIFY_NON_NULL(TAG, (acl->resources), ERROR);
278
279             size_t idxx = 0;
280             do
281             {
282                 cJSON *jsonRsrc = cJSON_GetArrayItem(jsonObj, idxx);
283                 VERIFY_NON_NULL(TAG, jsonRsrc, ERROR);
284
285                 jsonObjLen = strlen(jsonRsrc->valuestring) + 1;
286                 acl->resources[idxx] = (char*)OICMalloc(jsonObjLen);
287                 VERIFY_NON_NULL(TAG, (acl->resources[idxx]), ERROR);
288                 OICStrcpy(acl->resources[idxx], jsonObjLen, jsonRsrc->valuestring);
289             } while ( ++idxx < acl->resourcesLen);
290
291             // Permissions -- Mandatory
292             jsonObj = cJSON_GetObjectItem(jsonAcl,
293                                 OIC_JSON_PERMISSION_NAME);
294             VERIFY_NON_NULL(TAG, jsonObj, ERROR);
295             VERIFY_SUCCESS(TAG, cJSON_Number == jsonObj->type, ERROR);
296             acl->permission = jsonObj->valueint;
297
298             //Period -- Not Mandatory
299             cJSON *jsonPeriodObj = cJSON_GetObjectItem(jsonAcl,
300                     OIC_JSON_PERIODS_NAME);
301             if(jsonPeriodObj)
302             {
303                 VERIFY_SUCCESS(TAG, cJSON_Array == jsonPeriodObj->type,
304                                ERROR);
305                 acl->prdRecrLen = cJSON_GetArraySize(jsonPeriodObj);
306                 if(acl->prdRecrLen > 0)
307                 {
308                     acl->periods = (char**)OICCalloc(acl->prdRecrLen,
309                                     sizeof(char*));
310                     VERIFY_NON_NULL(TAG, acl->periods, ERROR);
311
312                     cJSON *jsonPeriod = NULL;
313                     for(size_t i = 0; i < acl->prdRecrLen; i++)
314                     {
315                         jsonPeriod = cJSON_GetArrayItem(jsonPeriodObj, i);
316                         VERIFY_NON_NULL(TAG, jsonPeriod, ERROR);
317
318                         jsonObjLen = strlen(jsonPeriod->valuestring) + 1;
319                         acl->periods[i] = (char*)OICMalloc(jsonObjLen);
320                         VERIFY_NON_NULL(TAG, acl->periods[i], ERROR);
321                         OICStrcpy(acl->periods[i], jsonObjLen,
322                                   jsonPeriod->valuestring);
323                     }
324                 }
325             }
326
327             //Recurrence -- Not mandatory
328             cJSON *jsonRecurObj = cJSON_GetObjectItem(jsonAcl,
329                                         OIC_JSON_RECURRENCES_NAME);
330             if(jsonRecurObj)
331             {
332                 VERIFY_SUCCESS(TAG, cJSON_Array == jsonRecurObj->type,
333                                ERROR);
334                 if(acl->prdRecrLen > 0)
335                 {
336                     acl->recurrences = (char**)OICCalloc(acl->prdRecrLen,
337                                              sizeof(char*));
338                     VERIFY_NON_NULL(TAG, acl->recurrences, ERROR);
339
340                     cJSON *jsonRecur = NULL;
341                     for(size_t i = 0; i < acl->prdRecrLen; i++)
342                     {
343                         jsonRecur = cJSON_GetArrayItem(jsonRecurObj, i);
344                         jsonObjLen = strlen(jsonRecur->valuestring) + 1;
345                         acl->recurrences[i] = (char*)OICMalloc(jsonObjLen);
346                         VERIFY_NON_NULL(TAG, acl->recurrences[i], ERROR);
347                         OICStrcpy(acl->recurrences[i], jsonObjLen,
348                                   jsonRecur->valuestring);
349                     }
350                 }
351             }
352
353             // Owners -- Mandatory
354             jsonObj = cJSON_GetObjectItem(jsonAcl, OIC_JSON_OWNERS_NAME);
355             VERIFY_NON_NULL(TAG, jsonObj, ERROR);
356             VERIFY_SUCCESS(TAG, cJSON_Array == jsonObj->type, ERROR);
357
358             acl->ownersLen = cJSON_GetArraySize(jsonObj);
359             VERIFY_SUCCESS(TAG, acl->ownersLen > 0, ERROR);
360             acl->owners = (OicUuid_t*)OICCalloc(acl->ownersLen, sizeof(OicUuid_t));
361             VERIFY_NON_NULL(TAG, (acl->owners), ERROR);
362
363             idxx = 0;
364             do
365             {
366                 cJSON *jsonOwnr = cJSON_GetArrayItem(jsonObj, idxx);
367                 VERIFY_NON_NULL(TAG, jsonOwnr, ERROR);
368                 VERIFY_SUCCESS(TAG, cJSON_String == jsonOwnr->type, ERROR);
369
370                 outLen = 0;
371                 b64Ret = b64Decode(jsonOwnr->valuestring, strlen(jsonOwnr->valuestring), base64Buff,
372                             sizeof(base64Buff), &outLen);
373
374                 VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(acl->owners[idxx].id)),
375                                     ERROR);
376                 memcpy(acl->owners[idxx].id, base64Buff, outLen);
377             } while ( ++idxx < acl->ownersLen);
378
379             prevAcl = acl;
380         } while( ++idx < numAcl);
381     }
382
383     ret = OC_STACK_OK;
384
385 exit:
386     cJSON_Delete(jsonRoot);
387     if (OC_STACK_OK != ret)
388     {
389         DeleteACLList(headAcl);
390         headAcl = NULL;
391     }
392     return headAcl;
393 }
394
395 static bool UpdatePersistentStorage(const OicSecAcl_t *acl)
396 {
397     // Convert ACL data into JSON for update to persistent storage
398     char *jsonStr = BinToAclJSON(acl);
399     if (jsonStr)
400     {
401         cJSON *jsonAcl = cJSON_Parse(jsonStr);
402         OICFree(jsonStr);
403
404         if ((jsonAcl) && (OC_STACK_OK == UpdateSVRDatabase(OIC_JSON_ACL_NAME, jsonAcl)))
405         {
406             return true;
407         }
408         cJSON_Delete(jsonAcl);
409     }
410     return false;
411 }
412 /*
413  * This method removes ACE for the subject and resource from the ACL
414  *
415  * @param subject  - subject of the ACE
416  * @param resource - resource of the ACE
417  *
418  * @return
419  *     OC_STACK_RESOURCE_DELETED on success
420  *     OC_STACK_NO_RESOURC on failure to find the appropriate ACE
421  *     OC_STACK_INVALID_PARAM on invalid parameter
422  */
423 static OCStackResult RemoveACE(const OicUuid_t * subject,
424                                const char * resource)
425 {
426     OC_LOG(INFO, TAG, PCF("IN RemoveACE"));
427
428     OicSecAcl_t *acl = NULL;
429     OicSecAcl_t *tempAcl = NULL;
430     bool deleteFlag = false;
431     OCStackResult ret = OC_STACK_NO_RESOURCE;
432
433     if(memcmp(subject->id, &WILDCARD_SUBJECT_ID, sizeof(subject->id)) == 0)
434     {
435         OC_LOG_V (INFO, TAG, PCF("%s received invalid parameter"), __func__ );
436         return  OC_STACK_INVALID_PARAM;
437     }
438
439     //If resource is NULL then delete all the ACE for the subject.
440     if(NULL == resource)
441     {
442         LL_FOREACH_SAFE(gAcl, acl, tempAcl)
443         {
444             if(memcmp(acl->subject.id, subject->id, sizeof(subject->id)) == 0)
445             {
446                 LL_DELETE(gAcl, acl);
447                 FreeACE(acl);
448                 deleteFlag = true;
449             }
450         }
451     }
452     else
453     {
454         //Looping through ACL to find the right ACE to delete. If the required resource is the only
455         //resource in the ACE for the subject then delete the whole ACE. If there are more resources
456         //than the required resource in the ACE, for the subject then just delete the resource from
457         //the resource array
458         LL_FOREACH_SAFE(gAcl, acl, tempAcl)
459         {
460             if(memcmp(acl->subject.id, subject->id, sizeof(subject->id)) == 0)
461             {
462                 if(1 == acl->resourcesLen && strcmp(acl->resources[0],  resource) == 0)
463                 {
464                     LL_DELETE(gAcl, acl);
465                     FreeACE(acl);
466                     deleteFlag = true;
467                     break;
468                 }
469                 else
470                 {
471                     int resPos = -1;
472                     size_t i;
473                     for(i = 0; i < acl->resourcesLen; i++)
474                     {
475                         if(strcmp(acl->resources[i],  resource) == 0)
476                         {
477                             resPos = i;
478                             break;
479                         }
480                     }
481                     if((0 <= resPos))
482                     {
483                         OICFree(acl->resources[resPos]);
484                         acl->resources[resPos] = NULL;
485                         acl->resourcesLen -= 1;
486                         for(i = resPos; i < acl->resourcesLen; i++)
487                         {
488                             acl->resources[i] = acl->resources[i+1];
489                         }
490                         deleteFlag = true;
491                         break;
492                     }
493                 }
494             }
495         }
496     }
497
498     if(deleteFlag)
499     {
500         if(UpdatePersistentStorage(gAcl))
501         {
502             ret = OC_STACK_RESOURCE_DELETED;
503         }
504     }
505     return ret;
506 }
507
508 static OCEntityHandlerResult HandleACLGetRequest (const OCEntityHandlerRequest * ehRequest)
509 {
510     // Convert ACL data into JSON for transmission
511     char* jsonStr = BinToAclJSON(gAcl);
512
513     /*
514      * A device should 'always' have a default ACL. Therefore,
515      * jsonStr should never be NULL.
516      */
517     OCEntityHandlerResult ehRet = (jsonStr ? OC_EH_OK : OC_EH_ERROR);
518
519     // Send response payload to request originator
520     SendSRMResponse(ehRequest, ehRet, jsonStr);
521
522     OICFree(jsonStr);
523
524     OC_LOG_V (INFO, TAG, PCF("%s RetVal %d"), __func__ , ehRet);
525     return ehRet;
526 }
527
528 static OCEntityHandlerResult HandleACLPostRequest (const OCEntityHandlerRequest * ehRequest)
529 {
530     OCEntityHandlerResult ehRet = OC_EH_ERROR;
531
532     // Convert JSON ACL data into binary. This will also validate the ACL data received.
533     OicSecAcl_t* newAcl = JSONToAclBin(((OCSecurityPayload*)ehRequest->payload)->securityData);
534
535     if (newAcl)
536     {
537         // Append the new ACL to existing ACL
538         LL_APPEND(gAcl, newAcl);
539
540         if(UpdatePersistentStorage(gAcl))
541         {
542             ehRet = OC_EH_RESOURCE_CREATED;
543         }
544     }
545
546     // Send payload to request originator
547     SendSRMResponse(ehRequest, ehRet, NULL);
548
549     OC_LOG_V (INFO, TAG, PCF("%s RetVal %d"), __func__ , ehRet);
550     return ehRet;
551 }
552
553 static OCEntityHandlerResult HandleACLDeleteRequest(const OCEntityHandlerRequest *ehRequest)
554 {
555     OC_LOG (INFO, TAG, PCF("Processing ACLDeleteRequest"));
556     OCEntityHandlerResult ehRet = OC_EH_ERROR;
557
558     if(NULL == ehRequest->query)
559     {
560         return ehRet;
561     }
562     OicParseQueryIter_t parseIter = {.attrPos=NULL};
563     OicUuid_t subject = {.id={0}};
564     char * resource = NULL;
565
566     //Parsing REST query to get subject & resource
567     ParseQueryIterInit((unsigned char *)ehRequest->query, &parseIter);
568
569     while(GetNextQuery(&parseIter))
570     {
571         if(strncasecmp((char *)parseIter.attrPos, OIC_JSON_SUBJECT_NAME, parseIter.attrLen) == 0)
572         {
573             unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
574             uint32_t outLen = 0;
575             B64Result b64Ret = B64_OK;
576
577            b64Ret = b64Decode((char *)parseIter.valPos, parseIter.valLen, base64Buff,
578                                sizeof(base64Buff), &outLen);
579
580            VERIFY_SUCCESS(TAG, (b64Ret == B64_OK && outLen <= sizeof(subject.id)), ERROR);
581            memcpy(subject.id, base64Buff, outLen);
582         }
583         if(strncasecmp((char *)parseIter.attrPos, OIC_JSON_RESOURCES_NAME, parseIter.attrLen) == 0)
584         {
585             resource = (char *)OICMalloc(parseIter.valLen);
586             VERIFY_NON_NULL(TAG, resource, ERROR);
587             OICStrcpy(resource, sizeof(resource), (char *)parseIter.valPos);
588         }
589     }
590
591     if(OC_STACK_RESOURCE_DELETED == RemoveACE(&subject, resource))
592     {
593         ehRet = OC_EH_RESOURCE_DELETED;
594     }
595     OICFree(resource);
596
597     // Send payload to request originator
598     SendSRMResponse(ehRequest, ehRet, NULL);
599
600 exit:
601     return ehRet;
602 }
603
604 /*
605  * This internal method is the entity handler for ACL resources and
606  * will handle REST request (GET/PUT/POST/DEL) for them.
607  */
608 OCEntityHandlerResult ACLEntityHandler (OCEntityHandlerFlag flag,
609                                         OCEntityHandlerRequest * ehRequest,
610                                         void* callbackParameter)
611 {
612     OC_LOG(INFO, TAG, PCF("Received request ACLEntityHandler"));
613     (void)callbackParameter;
614     OCEntityHandlerResult ehRet = OC_EH_ERROR;
615
616     if (!ehRequest)
617     {
618         return ehRet;
619     }
620
621     if (flag & OC_REQUEST_FLAG)
622     {
623         // TODO :  Handle PUT and DEL methods
624         OC_LOG (INFO, TAG, PCF("Flag includes OC_REQUEST_FLAG"));
625         switch (ehRequest->method)
626         {
627             case OC_REST_GET:
628                 ehRet = HandleACLGetRequest(ehRequest);
629                 break;
630
631             case OC_REST_POST:
632                 ehRet = HandleACLPostRequest(ehRequest);
633                 break;
634
635             case OC_REST_DELETE:
636                 ehRet = HandleACLDeleteRequest(ehRequest);
637                 break;
638
639             default:
640                 ehRet = OC_EH_ERROR;
641                 SendSRMResponse(ehRequest, ehRet, NULL);
642         }
643     }
644
645     return ehRet;
646 }
647
648 /*
649  * This internal method is used to create '/oic/sec/acl' resource.
650  */
651 OCStackResult CreateACLResource()
652 {
653     OCStackResult ret;
654
655     ret = OCCreateResource(&gAclHandle,
656                            OIC_RSRC_TYPE_SEC_ACL,
657                            OIC_MI_DEF,
658                            OIC_RSRC_ACL_URI,
659                            ACLEntityHandler,
660                            NULL,
661                            OC_OBSERVABLE | OC_SECURE | OC_EXPLICIT_DISCOVERABLE);
662
663     if (OC_STACK_OK != ret)
664     {
665         OC_LOG (FATAL, TAG, PCF("Unable to instantiate ACL resource"));
666         DeInitACLResource();
667     }
668     return ret;
669 }
670
671 /*
672  * This internal method is to retrieve the default ACL.
673  * If SVR database in persistent storage got corrupted or
674  * is not available for some reason, a default ACL is created
675  * which allows user to initiate ACL provisioning again.
676  */
677 OCStackResult  GetDefaultACL(OicSecAcl_t** defaultAcl)
678 {
679     OCStackResult ret = OC_STACK_ERROR;
680
681     OicUuid_t ownerId = {.id = {0}};
682
683     /*
684      * TODO In future, when new virtual resources will be added in OIC
685      * specification, Iotivity stack should be able to add them in
686      * existing SVR database. To support this, we need to add 'versioning'
687      * mechanism in SVR database.
688      */
689
690     const char *rsrcs[] = {
691         OC_RSRVD_WELL_KNOWN_URI,
692         OC_RSRVD_DEVICE_URI,
693         OC_RSRVD_PLATFORM_URI,
694         OC_RSRVD_RESOURCE_TYPES_URI,
695 #ifdef WITH_PRESENCE
696         OC_RSRVD_PRESENCE_URI,
697 #endif //WITH_PRESENCE
698         OIC_RSRC_ACL_URI,
699         OIC_RSRC_DOXM_URI,
700         OIC_RSRC_PSTAT_URI,
701     };
702
703     if (!defaultAcl)
704     {
705         return OC_STACK_INVALID_PARAM;
706     }
707
708     OicSecAcl_t *acl = (OicSecAcl_t *)OICCalloc(1, sizeof(OicSecAcl_t));
709     VERIFY_NON_NULL(TAG, acl, ERROR);
710
711     // Subject -- Mandatory
712     memcpy(&(acl->subject), &WILDCARD_SUBJECT_ID, sizeof(acl->subject));
713
714     // Resources -- Mandatory
715     acl->resourcesLen = sizeof(rsrcs)/sizeof(rsrcs[0]);
716
717     acl->resources = (char**)OICCalloc(acl->resourcesLen, sizeof(char*));
718     VERIFY_NON_NULL(TAG, (acl->resources), ERROR);
719
720     for (size_t i = 0; i <  acl->resourcesLen; i++)
721     {
722         size_t len = strlen(rsrcs[i]) + 1;
723         acl->resources[i] = (char*)OICMalloc(len * sizeof(char));
724         VERIFY_NON_NULL(TAG, (acl->resources[i]), ERROR);
725         OICStrcpy(acl->resources[i], len, rsrcs[i]);
726     }
727
728     acl->permission = PERMISSION_READ;
729     acl->prdRecrLen = 0;
730     acl->periods = NULL;
731     acl->recurrences = NULL;
732
733     // Device ID is the owner of this default ACL
734     ret = GetDoxmDeviceID( &ownerId);
735     VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, FATAL);
736
737     acl->ownersLen = 1;
738     acl->owners = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t));
739     VERIFY_NON_NULL(TAG, (acl->owners), ERROR);
740     memcpy(acl->owners, &ownerId, sizeof(OicUuid_t));
741
742     acl->next = NULL;
743
744     *defaultAcl = acl;
745     ret = OC_STACK_OK;
746
747 exit:
748
749     if (ret != OC_STACK_OK)
750     {
751         DeleteACLList(acl);
752         acl = NULL;
753     }
754
755     return ret;
756 }
757
758 /**
759  * Initialize ACL resource by loading data from persistent storage.
760  *
761  * @retval  OC_STACK_OK for Success, otherwise some error value
762  */
763 OCStackResult InitACLResource()
764 {
765     OCStackResult ret = OC_STACK_ERROR;
766
767     // Read ACL resource from PS
768     char* jsonSVRDatabase = GetSVRDatabase();
769
770     if (jsonSVRDatabase)
771     {
772         // Convert JSON ACL into binary format
773         gAcl = JSONToAclBin(jsonSVRDatabase);
774         OICFree(jsonSVRDatabase);
775     }
776     /*
777      * If SVR database in persistent storage got corrupted or
778      * is not available for some reason, a default ACL is created
779      * which allows user to initiate ACL provisioning again.
780      */
781     if (!jsonSVRDatabase || !gAcl)
782     {
783         GetDefaultACL(&gAcl);
784         // TODO Needs to update persistent storage
785     }
786     VERIFY_NON_NULL(TAG, gAcl, FATAL);
787
788     // Instantiate 'oic.sec.acl'
789     ret = CreateACLResource();
790
791 exit:
792     if (OC_STACK_OK != ret)
793     {
794         DeInitACLResource();
795     }
796     return ret;
797 }
798
799 /**
800  * Perform cleanup for ACL resources.
801  *
802  * @retval  none
803  */
804 void DeInitACLResource()
805 {
806     OCDeleteResource(gAclHandle);
807     gAclHandle = NULL;
808
809     DeleteACLList(gAcl);
810     gAcl = NULL;
811 }
812
813 /**
814  * This method is used by PolicyEngine to retrieve ACL for a Subject.
815  *
816  * @param subjectId ID of the subject for which ACL is required.
817  * @param savePtr is used internally by @ref GetACLResourceData to maintain index between
818  *                successive calls for same subjectId.
819  *
820  * @retval  reference to @ref OicSecAcl_t if ACL is found, else NULL
821  *
822  * @note On the first call to @ref GetACLResourceData, savePtr should point to NULL
823  */
824 const OicSecAcl_t* GetACLResourceData(const OicUuid_t* subjectId, OicSecAcl_t **savePtr)
825 {
826     OicSecAcl_t *acl = NULL;
827     OicSecAcl_t *begin = NULL;
828
829     if ( NULL == subjectId)
830     {
831         return NULL;
832     }
833
834     /*
835      * savePtr MUST point to NULL if this is the 'first' call to retrieve ACL for
836      * subjectID.
837      */
838     if (NULL == *savePtr)
839     {
840         begin = gAcl;
841     }
842     else
843     {
844         /*
845          * If this is a 'successive' call, search for location pointed by
846          * savePtr and assign 'begin' to the next ACL after it in the linked
847          * list and start searching from there.
848          */
849         LL_FOREACH(gAcl, acl)
850         {
851             if (acl == *savePtr)
852             {
853                 begin = acl->next;
854             }
855         }
856     }
857
858     // Find the next ACL corresponding to the 'subjectID' and return it.
859     LL_FOREACH(begin, acl)
860     {
861         if (memcmp(&(acl->subject), subjectId, sizeof(OicUuid_t)) == 0)
862         {
863             *savePtr = acl;
864             return acl;
865         }
866     }
867
868     // Cleanup in case no ACL is found
869     *savePtr = NULL;
870     return NULL;
871 }