Merge branch 'security-CKM' into 'master'
[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  "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, "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, "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, "%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 || resource[0] == '\0')
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 /*
509  * This method parses the query string received for REST requests and
510  * retrieves the 'subject' field.
511  *
512  * @param query querystring passed in REST request
513  * @param subject subject UUID parsed from query string
514  *
515  * @return true if query parsed successfully and found 'subject', else false.
516  */
517 static bool GetSubjectFromQueryString(const char *query, OicUuid_t *subject)
518 {
519     OicParseQueryIter_t parseIter = {.attrPos=NULL};
520
521     ParseQueryIterInit((unsigned char *)query, &parseIter);
522
523     while(GetNextQuery(&parseIter))
524     {
525         if(strncasecmp((char *)parseIter.attrPos, OIC_JSON_SUBJECT_NAME, parseIter.attrLen) == 0)
526         {
527             VERIFY_SUCCESS(TAG, 0 != parseIter.valLen, ERROR);
528             unsigned char base64Buff[sizeof(((OicUuid_t*)0)->id)] = {};
529             uint32_t outLen = 0;
530             B64Result b64Ret = B64_OK;
531             b64Ret = b64Decode((char *)parseIter.valPos, parseIter.valLen, base64Buff,
532                     sizeof(base64Buff), &outLen);
533             VERIFY_SUCCESS(TAG, (B64_OK == b64Ret && outLen <= sizeof(subject->id)), ERROR);
534             memcpy(subject->id, base64Buff, outLen);
535
536             return true;
537         }
538     }
539
540 exit:
541    return false;
542 }
543
544 /*
545  * This method parses the query string received for REST requests and
546  * retrieves the 'resource' field.
547  *
548  * @param query querystring passed in REST request
549  * @param resource resource parsed from query string
550  * @param resourceSize size of the memory pointed to resource
551  *
552  * @return true if query parsed successfully and found 'resource', else false.
553  */
554 static bool GetResourceFromQueryString(const char *query, char *resource, size_t resourceSize)
555 {
556     OicParseQueryIter_t parseIter = {.attrPos=NULL};
557
558     ParseQueryIterInit((unsigned char *)query, &parseIter);
559
560     while(GetNextQuery(&parseIter))
561     {
562         if(strncasecmp((char *)parseIter.attrPos, OIC_JSON_RESOURCES_NAME, parseIter.attrLen) == 0)
563         {
564             VERIFY_SUCCESS(TAG, 0 != parseIter.valLen, ERROR);
565             OICStrcpy(resource, resourceSize, (char *)parseIter.valPos);
566
567             return true;
568         }
569     }
570
571 exit:
572    return false;
573 }
574
575
576
577 static OCEntityHandlerResult HandleACLGetRequest (const OCEntityHandlerRequest * ehRequest)
578 {
579     OCEntityHandlerResult ehRet = OC_EH_ERROR;
580     char* jsonStr = NULL;
581
582     // Process the REST querystring parameters
583     if(ehRequest->query)
584     {
585         OC_LOG (INFO, TAG, "HandleACLGetRequest processing query");
586
587         OicUuid_t subject = {.id={0}};
588         char resource[MAX_URI_LENGTH] = {0};
589
590         OicSecAcl_t *savePtr = NULL;
591         const OicSecAcl_t *currentAce = NULL;
592
593         // 'Subject' field is MUST for processing a querystring in REST request.
594         VERIFY_SUCCESS(TAG,
595                        true == GetSubjectFromQueryString(ehRequest->query, &subject),
596                        ERROR);
597
598         GetResourceFromQueryString(ehRequest->query, resource, sizeof(resource));
599
600         /*
601          * TODO : Currently, this code only provides one ACE for a Subject.
602          * Below code needs to be updated for scenarios when Subject have
603          * multiple ACE's in ACL resource.
604          */
605         while((currentAce = GetACLResourceData(&subject, &savePtr)))
606         {
607             /*
608              * If REST querystring contains a specific resource, we need
609              * to search for that resource in ACE.
610              */
611             if (resource[0] != '\0')
612             {
613                 for(size_t n = 0; n < currentAce->resourcesLen; n++)
614                 {
615                     if((currentAce->resources[n]) &&
616                             (0 == strcmp(resource, currentAce->resources[n]) ||
617                              0 == strcmp(WILDCARD_RESOURCE_URI, currentAce->resources[n])))
618                     {
619                         // Convert ACL data into JSON for transmission
620                         jsonStr = BinToAclJSON(currentAce);
621                         goto exit;
622                     }
623                 }
624             }
625             else
626             {
627                 // Convert ACL data into JSON for transmission
628                 jsonStr = BinToAclJSON(currentAce);
629                 goto exit;
630             }
631         }
632     }
633     else
634     {
635         // Convert ACL data into JSON for transmission
636         jsonStr = BinToAclJSON(gAcl);
637     }
638
639 exit:
640     ehRet = (jsonStr ? OC_EH_OK : OC_EH_ERROR);
641
642     // Send response payload to request originator
643     SendSRMResponse(ehRequest, ehRet, jsonStr);
644
645     OICFree(jsonStr);
646
647     OC_LOG_V (INFO, TAG, "%s RetVal %d", __func__ , ehRet);
648     return ehRet;
649 }
650
651 static OCEntityHandlerResult HandleACLPostRequest (const OCEntityHandlerRequest * ehRequest)
652 {
653     OCEntityHandlerResult ehRet = OC_EH_ERROR;
654
655     // Convert JSON ACL data into binary. This will also validate the ACL data received.
656     OicSecAcl_t* newAcl = JSONToAclBin(((OCSecurityPayload*)ehRequest->payload)->securityData);
657
658     if (newAcl)
659     {
660         // Append the new ACL to existing ACL
661         LL_APPEND(gAcl, newAcl);
662
663         if(UpdatePersistentStorage(gAcl))
664         {
665             ehRet = OC_EH_RESOURCE_CREATED;
666         }
667     }
668
669     // Send payload to request originator
670     SendSRMResponse(ehRequest, ehRet, NULL);
671
672     OC_LOG_V (INFO, TAG, "%s RetVal %d", __func__ , ehRet);
673     return ehRet;
674 }
675
676 static OCEntityHandlerResult HandleACLDeleteRequest(const OCEntityHandlerRequest *ehRequest)
677 {
678     OC_LOG (INFO, TAG, "Processing ACLDeleteRequest");
679     OCEntityHandlerResult ehRet = OC_EH_ERROR;
680     OicUuid_t subject = {.id={0}};
681     char resource[MAX_URI_LENGTH] = {0};
682
683     VERIFY_NON_NULL(TAG, ehRequest->query, ERROR);
684
685     // 'Subject' field is MUST for processing a querystring in REST request.
686     VERIFY_SUCCESS(TAG,
687             true == GetSubjectFromQueryString(ehRequest->query, &subject),
688             ERROR);
689
690     GetResourceFromQueryString(ehRequest->query, resource, sizeof(resource));
691
692     if(OC_STACK_RESOURCE_DELETED == RemoveACE(&subject, resource))
693     {
694         ehRet = OC_EH_RESOURCE_DELETED;
695     }
696
697 exit:
698     // Send payload to request originator
699     SendSRMResponse(ehRequest, ehRet, NULL);
700
701     return ehRet;
702 }
703
704 /*
705  * This internal method is the entity handler for ACL resources and
706  * will handle REST request (GET/PUT/POST/DEL) for them.
707  */
708 OCEntityHandlerResult ACLEntityHandler (OCEntityHandlerFlag flag,
709                                         OCEntityHandlerRequest * ehRequest,
710                                         void* callbackParameter)
711 {
712     OC_LOG(INFO, TAG, "Received request ACLEntityHandler");
713     (void)callbackParameter;
714     OCEntityHandlerResult ehRet = OC_EH_ERROR;
715
716     if (!ehRequest)
717     {
718         return ehRet;
719     }
720
721     if (flag & OC_REQUEST_FLAG)
722     {
723         // TODO :  Handle PUT method
724         OC_LOG (INFO, TAG, "Flag includes OC_REQUEST_FLAG");
725         switch (ehRequest->method)
726         {
727             case OC_REST_GET:
728                 ehRet = HandleACLGetRequest(ehRequest);
729                 break;
730
731             case OC_REST_POST:
732                 ehRet = HandleACLPostRequest(ehRequest);
733                 break;
734
735             case OC_REST_DELETE:
736                 ehRet = HandleACLDeleteRequest(ehRequest);
737                 break;
738
739             default:
740                 ehRet = OC_EH_ERROR;
741                 SendSRMResponse(ehRequest, ehRet, NULL);
742         }
743     }
744
745     return ehRet;
746 }
747
748 /*
749  * This internal method is used to create '/oic/sec/acl' resource.
750  */
751 OCStackResult CreateACLResource()
752 {
753     OCStackResult ret;
754
755     ret = OCCreateResource(&gAclHandle,
756                            OIC_RSRC_TYPE_SEC_ACL,
757                            OIC_MI_DEF,
758                            OIC_RSRC_ACL_URI,
759                            ACLEntityHandler,
760                            NULL,
761                            OC_OBSERVABLE | OC_SECURE | OC_EXPLICIT_DISCOVERABLE);
762
763     if (OC_STACK_OK != ret)
764     {
765         OC_LOG (FATAL, TAG, "Unable to instantiate ACL resource");
766         DeInitACLResource();
767     }
768     return ret;
769 }
770
771 /*
772  * This internal method is to retrieve the default ACL.
773  * If SVR database in persistent storage got corrupted or
774  * is not available for some reason, a default ACL is created
775  * which allows user to initiate ACL provisioning again.
776  */
777 OCStackResult  GetDefaultACL(OicSecAcl_t** defaultAcl)
778 {
779     OCStackResult ret = OC_STACK_ERROR;
780
781     OicUuid_t ownerId = {.id = {0}};
782
783     /*
784      * TODO In future, when new virtual resources will be added in OIC
785      * specification, Iotivity stack should be able to add them in
786      * existing SVR database. To support this, we need to add 'versioning'
787      * mechanism in SVR database.
788      */
789
790     const char *rsrcs[] = {
791         OC_RSRVD_WELL_KNOWN_URI,
792         OC_RSRVD_DEVICE_URI,
793         OC_RSRVD_PLATFORM_URI,
794         OC_RSRVD_RESOURCE_TYPES_URI,
795 #ifdef WITH_PRESENCE
796         OC_RSRVD_PRESENCE_URI,
797 #endif //WITH_PRESENCE
798         OIC_RSRC_ACL_URI,
799         OIC_RSRC_DOXM_URI,
800         OIC_RSRC_PSTAT_URI,
801     };
802
803     if (!defaultAcl)
804     {
805         return OC_STACK_INVALID_PARAM;
806     }
807
808     OicSecAcl_t *acl = (OicSecAcl_t *)OICCalloc(1, sizeof(OicSecAcl_t));
809     VERIFY_NON_NULL(TAG, acl, ERROR);
810
811     // Subject -- Mandatory
812     memcpy(&(acl->subject), &WILDCARD_SUBJECT_ID, sizeof(acl->subject));
813
814     // Resources -- Mandatory
815     acl->resourcesLen = sizeof(rsrcs)/sizeof(rsrcs[0]);
816
817     acl->resources = (char**)OICCalloc(acl->resourcesLen, sizeof(char*));
818     VERIFY_NON_NULL(TAG, (acl->resources), ERROR);
819
820     for (size_t i = 0; i <  acl->resourcesLen; i++)
821     {
822         size_t len = strlen(rsrcs[i]) + 1;
823         acl->resources[i] = (char*)OICMalloc(len * sizeof(char));
824         VERIFY_NON_NULL(TAG, (acl->resources[i]), ERROR);
825         OICStrcpy(acl->resources[i], len, rsrcs[i]);
826     }
827
828     acl->permission = PERMISSION_READ;
829     acl->prdRecrLen = 0;
830     acl->periods = NULL;
831     acl->recurrences = NULL;
832
833     // Device ID is the owner of this default ACL
834     ret = GetDoxmDeviceID( &ownerId);
835     VERIFY_SUCCESS(TAG, OC_STACK_OK == ret, FATAL);
836
837     acl->ownersLen = 1;
838     acl->owners = (OicUuid_t*)OICMalloc(sizeof(OicUuid_t));
839     VERIFY_NON_NULL(TAG, (acl->owners), ERROR);
840     memcpy(acl->owners, &ownerId, sizeof(OicUuid_t));
841
842     acl->next = NULL;
843
844     *defaultAcl = acl;
845     ret = OC_STACK_OK;
846
847 exit:
848
849     if (ret != OC_STACK_OK)
850     {
851         DeleteACLList(acl);
852         acl = NULL;
853     }
854
855     return ret;
856 }
857
858 /**
859  * Initialize ACL resource by loading data from persistent storage.
860  *
861  * @retval  OC_STACK_OK for Success, otherwise some error value
862  */
863 OCStackResult InitACLResource()
864 {
865     OCStackResult ret = OC_STACK_ERROR;
866
867     // Read ACL resource from PS
868     char* jsonSVRDatabase = GetSVRDatabase();
869
870     if (jsonSVRDatabase)
871     {
872         // Convert JSON ACL into binary format
873         gAcl = JSONToAclBin(jsonSVRDatabase);
874         OICFree(jsonSVRDatabase);
875     }
876     /*
877      * If SVR database in persistent storage got corrupted or
878      * is not available for some reason, a default ACL is created
879      * which allows user to initiate ACL provisioning again.
880      */
881     if (!jsonSVRDatabase || !gAcl)
882     {
883         GetDefaultACL(&gAcl);
884         // TODO Needs to update persistent storage
885     }
886     VERIFY_NON_NULL(TAG, gAcl, FATAL);
887
888     // Instantiate 'oic.sec.acl'
889     ret = CreateACLResource();
890
891 exit:
892     if (OC_STACK_OK != ret)
893     {
894         DeInitACLResource();
895     }
896     return ret;
897 }
898
899 /**
900  * Perform cleanup for ACL resources.
901  *
902  * @retval  none
903  */
904 void DeInitACLResource()
905 {
906     OCDeleteResource(gAclHandle);
907     gAclHandle = NULL;
908
909     DeleteACLList(gAcl);
910     gAcl = NULL;
911 }
912
913 /**
914  * This method is used by PolicyEngine to retrieve ACL for a Subject.
915  *
916  * @param subjectId ID of the subject for which ACL is required.
917  * @param savePtr is used internally by @ref GetACLResourceData to maintain index between
918  *                successive calls for same subjectId.
919  *
920  * @retval  reference to @ref OicSecAcl_t if ACL is found, else NULL
921  *
922  * @note On the first call to @ref GetACLResourceData, savePtr should point to NULL
923  */
924 const OicSecAcl_t* GetACLResourceData(const OicUuid_t* subjectId, OicSecAcl_t **savePtr)
925 {
926     OicSecAcl_t *acl = NULL;
927     OicSecAcl_t *begin = NULL;
928
929     if ( NULL == subjectId)
930     {
931         return NULL;
932     }
933
934     /*
935      * savePtr MUST point to NULL if this is the 'first' call to retrieve ACL for
936      * subjectID.
937      */
938     if (NULL == *savePtr)
939     {
940         begin = gAcl;
941     }
942     else
943     {
944         /*
945          * If this is a 'successive' call, search for location pointed by
946          * savePtr and assign 'begin' to the next ACL after it in the linked
947          * list and start searching from there.
948          */
949         LL_FOREACH(gAcl, acl)
950         {
951             if (acl == *savePtr)
952             {
953                 begin = acl->next;
954             }
955         }
956     }
957
958     // Find the next ACL corresponding to the 'subjectID' and return it.
959     LL_FOREACH(begin, acl)
960     {
961         if (memcmp(&(acl->subject), subjectId, sizeof(OicUuid_t)) == 0)
962         {
963             *savePtr = acl;
964             return acl;
965         }
966     }
967
968     // Cleanup in case no ACL is found
969     *savePtr = NULL;
970     return NULL;
971 }