Fix svace defects in things manager
[platform/upstream/iotivity.git] / resource / csdk / stack / src / oicgroup.c
1 //******************************************************************
2 //
3 // Copyright 2014 Samsung Electronics 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 #define _POSIX_C_SOURCE 200112L
22
23 #include <string.h>
24
25 #include "oicgroup.h"
26 #include "cJSON.h"
27 #include "cbor.h"
28 #include "ocpayload.h"
29 #include "oic_malloc.h"
30 #include "oic_string.h"
31 #include "occollection.h"
32 #include "logger.h"
33 #include "timer.h"
34
35 #ifndef WITH_ARDUINO
36 #include <pthread.h>
37 #endif
38
39 #define TAG "OIC_RI_GROUP"
40
41 #define DESC_DELIMITER          "\""
42 #define ACTION_DELIMITER        "*"
43 #define ATTR_DELIMITER          "|"
44 #define ATTR_ASSIGN             "="
45
46 // Definitions for operations related to actions
47 #define DO_ACTION               "DoAction"
48 #define GET_ACTIONSET           "GetActionSet"
49 #define ACTIONSET               "ActionSet"
50 #define CANCEL_ACTIONSET        "CancelAction"
51 #define DELETE_ACTIONSET        "DelActionSet"
52
53 #define DEFAULT_CONTEXT_VALUE 0x99
54
55 #define VARIFY_POINTER_NULL(pointer, result, toExit) \
56     if(pointer == NULL) \
57     {\
58         result = OC_STACK_NO_MEMORY;\
59         goto toExit;\
60     }
61 #define VARIFY_PARAM_NULL(pointer, result, toExit) \
62     if(pointer == NULL)\
63     {\
64         result = OC_STACK_INVALID_PARAM;\
65         goto exit;\
66     }
67
68 #define OCFREE(pointer) \
69     { \
70         OICFree(pointer); \
71         pointer = NULL; \
72     }
73
74 #ifndef WITH_ARDUINO
75 pthread_mutex_t lock;
76 #endif
77
78 enum ACTION_TYPE
79 {
80     NONE = 0, SCHEDULED, RECURSIVE
81 };
82
83 typedef struct scheduledresourceinfo
84 {
85     OCResource *resource;
86     OCActionSet *actionset;
87
88     int timer_id;
89
90     OCServerRequest *ehRequest;
91
92     time_t time;
93     struct scheduledresourceinfo* next;
94 } ScheduledResourceInfo;
95
96 ScheduledResourceInfo *scheduleResourceList = NULL;
97
98 void AddScheduledResource(ScheduledResourceInfo **head,
99         ScheduledResourceInfo* add)
100 {
101     OIC_LOG(INFO, TAG, "AddScheduledResource Entering...");
102
103 #ifndef WITH_ARDUINO
104     pthread_mutex_lock(&lock);
105 #endif
106     ScheduledResourceInfo *tmp = NULL;
107
108     if (*head != NULL)
109     {
110         tmp = *head;
111
112         while (tmp->next)
113         {
114             tmp = tmp->next;
115         }
116         tmp->next = add;
117     }
118     else
119     {
120         *head = add;
121     }
122 #ifndef WITH_ARDUINO
123     pthread_mutex_unlock(&lock);
124 #endif
125 }
126
127 ScheduledResourceInfo* GetScheduledResource(ScheduledResourceInfo *head)
128 {
129     OIC_LOG(INFO, TAG, "GetScheduledResource Entering...");
130
131 #ifndef WITH_ARDUINO
132     pthread_mutex_lock(&lock);
133 #endif
134
135     time_t t_now;
136
137     ScheduledResourceInfo *tmp = NULL;
138     tmp = head;
139
140 #ifndef WITH_ARDUINO
141     time(&t_now);
142 #else
143     t_now = now();
144 #endif
145
146     if (tmp)
147     {
148         while (tmp)
149         {
150             time_t diffTm = 0;
151 #ifndef WITH_ARDUINO
152             diffTm = timespec_diff(tmp->time, t_now);
153 #else
154             diffTm = timespec_diff(tmp->time, t_now);
155 #endif
156
157             if (diffTm <= (time_t) 0)
158             {
159                 OIC_LOG(INFO, TAG, "return Call INFO.");
160                 goto exit;
161             }
162
163             tmp = tmp->next;
164         }
165     }
166
167     exit:
168 #ifndef WITH_ARDUINO
169     pthread_mutex_unlock(&lock);
170 #endif
171     if (tmp == NULL)
172     {
173         OIC_LOG(INFO, TAG, "Cannot Find Call Info.");
174     }
175     return tmp;
176 }
177
178 ScheduledResourceInfo* GetScheduledResourceByActionSetName(ScheduledResourceInfo *head, char *setName)
179 {
180     OIC_LOG(INFO, TAG, "GetScheduledResourceByActionSetName Entering...");
181
182 #ifndef WITH_ARDUINO
183     pthread_mutex_lock(&lock);
184 #endif
185     ScheduledResourceInfo *tmp = NULL;
186     tmp = head;
187
188     if (tmp)
189     {
190         while (tmp)
191         {
192             if (strcmp(tmp->actionset->actionsetName, setName) == 0)
193             {
194                 OIC_LOG(INFO, TAG, "return Call INFO.");
195                 goto exit;
196             }
197             tmp = tmp->next;
198         }
199     }
200
201 exit:
202 #ifndef WITH_ARDUINO
203     pthread_mutex_unlock(&lock);
204 #endif
205     if (tmp == NULL)
206     {
207         OIC_LOG(INFO, TAG, "Cannot Find Call Info.");
208     }
209     return tmp;
210 }
211
212 void RemoveScheduledResource(ScheduledResourceInfo **head,
213         ScheduledResourceInfo* del)
214 {
215 #ifndef WITH_ARDUINO
216     pthread_mutex_lock(&lock);
217 #endif
218     OIC_LOG(INFO, TAG, "RemoveScheduledResource Entering...");
219     ScheduledResourceInfo *tmp = NULL;
220
221     if (del == NULL)
222     {
223 #ifndef WITH_ARDUINO
224     pthread_mutex_unlock(&lock);
225 #endif
226         return;
227     }
228
229     if (*head == del)
230     {
231         *head = (*head)->next;
232     }
233     else
234     {
235         tmp = *head;
236         while (tmp->next && (tmp->next != del))
237         {
238             tmp = tmp->next;
239         }
240         if (tmp->next)
241         {
242             tmp->next = del->next;
243         }
244     }
245
246     OCFREE(del)
247 #ifndef WITH_ARDUINO
248     pthread_mutex_unlock(&lock);
249 #endif
250 }
251
252 typedef struct aggregatehandleinfo
253 {
254     OCServerRequest *ehRequest;
255     OCDoHandle required;
256     OCResource *collResource;
257
258     struct aggregatehandleinfo *next;
259 } ClientRequestInfo;
260
261 ClientRequestInfo *clientRequstList = NULL;
262
263 void AddClientRequestInfo(ClientRequestInfo **head, ClientRequestInfo* add)
264 {
265     ClientRequestInfo *tmp = NULL;
266
267     if (*head != NULL)
268     {
269         tmp = *head;
270
271         while (tmp->next)
272         {
273             tmp = tmp->next;
274         }
275         tmp->next = add;
276     }
277     else
278     {
279         *head = add;
280     }
281 }
282
283 ClientRequestInfo* GetClientRequestInfo(ClientRequestInfo *head,
284         OCDoHandle handle)
285 {
286     ClientRequestInfo *tmp = NULL;
287
288     tmp = head;
289
290     if (tmp)
291     {
292         while (tmp)
293         {
294             if (tmp->required == handle)
295             {
296                 break;
297             }
298
299             tmp = tmp->next;
300         }
301
302         return tmp;
303     }
304     return NULL;
305 }
306
307 void RemoveClientRequestInfo(ClientRequestInfo **head, ClientRequestInfo* del)
308 {
309     ClientRequestInfo *tmp = NULL;
310
311     if (del == NULL)
312         return;
313
314     if (*head == del)
315     {
316         *head = (*head)->next;
317     }
318     else
319     {
320         tmp = *head;
321         while (tmp->next && (tmp->next != del))
322         {
323             tmp = tmp->next;
324         }
325         if (tmp->next)
326         {
327             tmp->next = del->next;
328         }
329     }
330 }
331
332 void AddCapability(OCCapability** head, OCCapability* node)
333 {
334     OCCapability *pointer = *head;
335     if (NULL == pointer)
336     {
337         *head = node;
338     }
339     else
340     {
341         while (pointer->next != NULL)
342         {
343             pointer = pointer->next;
344         }
345
346         pointer->next = node;
347     }
348 }
349
350 void AddAction(OCAction** head, OCAction* node)
351 {
352     OCAction *pointer = *head;
353     if (NULL == pointer)
354     {
355         *head = node;
356     }
357     else
358     {
359
360         while (pointer->next != NULL)
361         {
362             pointer = pointer->next;
363         }
364
365         pointer->next = node;
366     }
367 }
368
369 OCStackResult AddActionSet(OCActionSet **head, OCActionSet* node)
370 {
371     OCActionSet *pointer = *head;
372     OCActionSet *prev = NULL;
373     if(node == NULL)
374     {
375         return OC_STACK_ERROR;
376     }
377     if (NULL == pointer)
378     {
379         *head = node;
380     }
381     else
382     {
383         prev = pointer;
384         while (pointer != NULL)
385         {
386             // check the uniqeness of actionsetname.
387             if (strcmp(pointer->actionsetName, node->actionsetName) == 0)
388             {
389                 return OC_STACK_ERROR;
390             }
391
392             prev = pointer;
393             pointer = pointer->next;
394         }
395
396         prev->next = node;
397     }
398
399     return OC_STACK_OK;
400 }
401
402 void DeleteCapability(OCCapability *del)
403 {
404     OCFREE(del->capability)
405     del->capability = NULL;
406     OCFREE(del->status)
407     del->status = NULL;
408     OCFREE(del)
409 }
410
411 void DeleteAction(OCAction** action)
412 {
413     OCCapability* pointer = (*action)->head;
414     OCCapability* pDel = NULL;
415
416     while (pointer)
417     {
418         pDel = pointer;
419         pointer = pointer->next;
420
421         DeleteCapability(pDel);
422     }
423     OCFREE((*action)->resourceUri)
424     (*action)->next = NULL;
425     OCFREE(*action)
426 }
427
428 void DeleteActionSet(OCActionSet** actionset)
429 {
430     if(*actionset == NULL)
431         return;
432
433     OCAction* pointer = (*actionset)->head;
434     OCAction* pDel = NULL;
435
436     while (pointer)
437     {
438         pDel = pointer;
439         pointer = pointer->next;
440
441         DeleteAction(&pDel);
442     }
443     //    (*actionset)->head = NULL;
444     OCFREE((*actionset)->actionsetName)
445     OCFREE(*actionset)
446 }
447
448 OCStackResult FindAndDeleteActionSet(OCResource **resource,
449         const char * actionsetName)
450 {
451     if (*resource != NULL)
452     {
453         OCActionSet *pointer = NULL;
454         OCActionSet *pDel = NULL;
455
456         pointer = (*resource)->actionsetHead;
457
458         if (pointer == NULL)
459         {
460             return OC_STACK_ERROR;
461         }
462         else
463         {
464             if (strcmp(pointer->actionsetName, actionsetName) == 0)
465             {
466                 if (pointer->next != NULL)
467                     (*resource)->actionsetHead = pointer->next;
468                 else
469                     (*resource)->actionsetHead = NULL;
470
471                 DeleteActionSet(&pointer);
472             }
473             else if (pointer->next != NULL)
474             {
475                 while (pointer)
476                 {
477                     if (pointer->next != NULL)
478                     {
479                         if (strcmp(pointer->next->actionsetName, actionsetName)
480                                 == 0)
481                         {
482                             pDel = pointer->next;
483                             pointer->next = pointer->next->next;
484
485                             DeleteActionSet(&pDel);
486                         }
487                     }
488                     pointer = pointer->next;
489                 }
490             }
491
492             return OC_STACK_OK;
493         }
494
495     }
496     return OC_STACK_ERROR;
497 }
498
499 OCStackResult GetActionSet(const char *actionName, OCActionSet *head,
500         OCActionSet** actionset)
501 {
502     OCActionSet *pointer = head;
503
504     while (pointer)
505     {
506         if (strcmp(pointer->actionsetName, actionName) == 0)
507         {
508             *actionset = pointer;
509             return OC_STACK_OK;
510         }
511
512         pointer = pointer->next;
513     }
514
515     return OC_STACK_ERROR;
516
517 }
518
519 OCStackResult ExtractKeyValueFromRequest(OCEntityHandlerRequest *ehRequest,
520                                         char **key, char **value)
521 {
522     OCStackResult result = OC_STACK_OK;
523
524     char *actionSetStr = NULL;
525
526     if( NULL == ehRequest->payload )
527     {
528         result = OC_STACK_ERROR;
529         goto exit;
530     }
531
532     OCRepPayload* input;
533
534     input = (OCRepPayload*)(ehRequest->payload);
535
536     if(OCRepPayloadGetPropString(input, ACTIONSET, &actionSetStr))
537     {
538         *key = OICStrdup(ACTIONSET);
539         VARIFY_POINTER_NULL(*key, result, exit);
540
541         *value = OICStrdup(actionSetStr);
542         VARIFY_POINTER_NULL(*value, result, exit);
543     }
544     else if(OCRepPayloadGetPropString(input, DO_ACTION, &actionSetStr))
545     {
546         *key = OICStrdup(DO_ACTION);
547         VARIFY_POINTER_NULL(*key, result, exit);
548
549         *value = OICStrdup(actionSetStr);
550         VARIFY_POINTER_NULL(*value, result, exit);
551     }
552     else if(OCRepPayloadGetPropString(input, GET_ACTIONSET, &actionSetStr))
553     {
554         *key = OICStrdup(GET_ACTIONSET);
555         VARIFY_POINTER_NULL(*key, result, exit);
556
557         *value = OICStrdup(actionSetStr);
558         VARIFY_POINTER_NULL(*value, result, exit);
559     }
560     else if(OCRepPayloadGetPropString(input, DELETE_ACTIONSET, &actionSetStr))
561     {
562         *key = OICStrdup(DELETE_ACTIONSET);
563         VARIFY_POINTER_NULL(*key, result, exit);
564
565         *value = OICStrdup(actionSetStr);
566         VARIFY_POINTER_NULL(*value, result, exit);
567     }
568     else if(OCRepPayloadGetPropString(input, CANCEL_ACTIONSET, &actionSetStr))
569     {
570         *key = OICStrdup(CANCEL_ACTIONSET);
571         VARIFY_POINTER_NULL(*key, result, exit);
572
573         *value = OICStrdup(actionSetStr);
574         VARIFY_POINTER_NULL(*value, result, exit);
575     }
576     else
577     {
578         result = OC_STACK_ERROR;
579     }
580
581 exit:
582     if (result != OC_STACK_OK)
583     {
584         OCFREE(*key)
585         OCFREE(*value)
586     }
587
588     OCFREE(actionSetStr);
589
590     return result;
591 }
592
593 OCStackResult ExtractActionSetNameAndDelaytime(char *pChar, char **setName,
594         long int *pa)
595 {
596     char *token = NULL, *tokenPtr = NULL;
597     OCStackResult result = OC_STACK_OK;
598
599     token = (char*) strtok_r(pChar, ACTION_DELIMITER, &tokenPtr);
600     VARIFY_POINTER_NULL(token, result, exit)
601
602     *setName = (char *) OICMalloc(strlen(token) + 1);
603     VARIFY_POINTER_NULL(*setName, result, exit)
604     VARIFY_PARAM_NULL(token, result, exit)
605     strncpy(*setName, token, strlen(token) + 1);
606
607     token = strtok_r(NULL, ACTION_DELIMITER, &tokenPtr);
608     VARIFY_POINTER_NULL(pa, result, exit)
609     VARIFY_PARAM_NULL(token, result, exit)
610     *pa = atoi(token);
611
612     return OC_STACK_OK;
613
614 exit:
615     OCFREE(*setName);
616     return result;
617 }
618
619 OCStackResult BuildActionSetFromString(OCActionSet **set, char* actiondesc)
620 {
621     OCStackResult result = OC_STACK_OK;
622
623     char *iterToken = NULL, *iterTokenPtr = NULL;
624     char *descIterToken = NULL, *descIterTokenPtr = NULL;
625     char *attrIterToken = NULL, *attrIterTokenPtr = NULL;
626     char *desc = NULL, *attr = NULL;
627     char *key = NULL, *value = NULL;
628
629     OCAction *action = NULL;
630     OCCapability *capa = NULL;
631
632     OIC_LOG(INFO, TAG, "Build ActionSet Instance.");
633
634     *set = (OCActionSet*) OICMalloc(sizeof(OCActionSet));
635     VARIFY_POINTER_NULL(*set, result, exit)
636
637     iterToken = (char *) strtok_r(actiondesc, ACTION_DELIMITER, &iterTokenPtr);
638     VARIFY_POINTER_NULL(iterToken, result, exit);
639
640     // ActionSet Name
641     memset(*set, 0, sizeof(OCActionSet));
642     (*set)->actionsetName = (char *) OICMalloc(strlen(iterToken) + 1);
643     VARIFY_POINTER_NULL((*set)->actionsetName, result, exit)
644     VARIFY_PARAM_NULL(iterToken, result, exit)
645     strncpy((*set)->actionsetName, iterToken, strlen(iterToken) + 1);
646
647     // Time info. for Scheduled/Recursive Group action.
648     // d is meant Day of the week.
649     // T is meant ActionType.
650     // yyyy-mm-dd hh:mm:ss d
651     iterToken = (char *) strtok_r(NULL, ACTION_DELIMITER, &iterTokenPtr);
652     VARIFY_PARAM_NULL(iterToken, result, exit)
653 #ifndef WITH_ARDUINO
654     if( 2 != sscanf(iterToken, "%ld %u", &(*set)->timesteps, &(*set)->type) )
655     {
656         // If the return value should be 2, the number of items in the argument. Otherwise, it fails.
657         goto exit;
658     }
659 #endif
660
661     OIC_LOG_V(INFO, TAG, "ActionSet Name : %s", (*set)->actionsetName);
662
663     iterToken = (char *) strtok_r(NULL, ACTION_DELIMITER, &iterTokenPtr);
664     while (iterToken)
665     {
666         desc = (char *) OICMalloc(strlen(iterToken) + 1);
667         VARIFY_POINTER_NULL(desc, result, exit)
668         VARIFY_PARAM_NULL(desc, result, exit)
669         strncpy(desc, iterToken, strlen(iterToken) + 1);
670         descIterToken = (char *) strtok_r(desc, ATTR_DELIMITER,
671                 &descIterTokenPtr);
672         while (descIterToken)
673         {
674             attr = (char *) OICMalloc(strlen(descIterToken) + 1);
675             VARIFY_POINTER_NULL(attr, result, exit)
676             VARIFY_PARAM_NULL(descIterToken, result, exit)
677             strncpy(attr, descIterToken, strlen(descIterToken) + 1);
678
679             attrIterToken = (char *) strtok_r(attr, ATTR_ASSIGN,
680                     &attrIterTokenPtr);
681             VARIFY_POINTER_NULL(attrIterToken, result, exit);
682
683             key = (char *) OICMalloc(strlen(attrIterToken) + 1);
684             VARIFY_POINTER_NULL(key, result, exit)
685             VARIFY_PARAM_NULL(attrIterToken, result, exit)
686             strncpy(key, attrIterToken, strlen(attrIterToken) + 1);
687
688             attrIterToken = (char *) strtok_r(NULL, ATTR_ASSIGN,
689                     &attrIterTokenPtr);
690             VARIFY_POINTER_NULL(attrIterToken, result, exit);
691             value = (char *) OICMalloc(strlen(attrIterToken) + 1);
692             VARIFY_POINTER_NULL(value, result, exit)
693             VARIFY_PARAM_NULL(attrIterToken, result, exit)
694             strncpy(value, attrIterToken, strlen(attrIterToken) + 1);
695
696             if (strcmp(key, "uri") == 0)
697             {
698                 OIC_LOG(INFO, TAG, "Build OCAction Instance.");
699
700                 action = (OCAction*) OICMalloc(sizeof(OCAction));
701                 VARIFY_POINTER_NULL(action, result, exit)
702                 memset(action, 0, sizeof(OCAction));
703                 action->resourceUri = (char *) OICMalloc(strlen(value) + 1);
704                 VARIFY_POINTER_NULL(action->resourceUri, result, exit)
705                 VARIFY_PARAM_NULL(value, result, exit)
706                 strncpy(action->resourceUri, value, strlen(value) + 1);
707             }
708             else
709             {
710                 if ((key != NULL) && (value != NULL))
711                 {
712                     OIC_LOG(INFO, TAG, "Build OCCapability Instance.");
713
714                     capa = (OCCapability*) OICMalloc(sizeof(OCCapability));
715                     VARIFY_POINTER_NULL(capa, result, exit)
716                     memset(capa, 0, sizeof(OCCapability));
717
718                     capa->capability = (char *) OICMalloc(strlen(key) + 1);
719                     VARIFY_POINTER_NULL(capa->capability, result, exit)
720                     VARIFY_PARAM_NULL(key, result, exit)
721                     strncpy(capa->capability, key, strlen(key) + 1);
722
723                     capa->status = (char *) OICMalloc(strlen(value) + 1);
724                     VARIFY_POINTER_NULL(capa->status, result, exit)
725                     VARIFY_PARAM_NULL(value, result, exit)
726                     strncpy(capa->status, value, strlen(value) + 1);
727
728                     VARIFY_POINTER_NULL(action, result, exit)
729
730                     AddCapability(&action->head, capa);
731                 }
732             }
733
734             OCFREE(key)
735             OCFREE(value)
736             OCFREE(attr)
737
738             descIterToken = (char *) strtok_r(NULL, ATTR_DELIMITER,
739                     &descIterTokenPtr);
740         }
741
742         AddAction(&(*set)->head, action);
743         iterToken = (char *) strtok_r(NULL, ACTION_DELIMITER, &iterTokenPtr);
744         OCFREE(desc);
745     }
746
747     return OC_STACK_OK;
748 exit:
749     OCFREE(attr)
750     OCFREE(desc)
751     OCFREE(capa)
752     OCFREE(action)
753     OCFREE(*set)
754     OCFREE(key)
755     OCFREE(value)
756     OCFREE(attr)
757
758     return result;
759 }
760
761 OCStackResult BuildStringFromActionSet(OCActionSet* actionset, char** desc)
762 {
763     // Can't use the macros here as they are hardcoded to 'exit' and will
764     // result in dereferencing a null pointer.
765     if (!actionset || !desc)
766     {
767         return OC_STACK_INVALID_PARAM;
768     }
769     char temp[1024] = { 0 };
770     size_t remaining = sizeof(temp) - 1;
771     OCStackResult res = OC_STACK_ERROR;
772     char* actionTypeStr = NULL;
773
774     OCAction *action = actionset->head;
775
776     if (remaining >= strlen(actionset->actionsetName) + 1)
777     {
778         strncat(temp, actionset->actionsetName, strlen(actionset->actionsetName));
779         remaining -= strlen(actionset->actionsetName);
780         strncat(temp, ACTION_DELIMITER, strlen(ACTION_DELIMITER));
781         remaining--;
782     }
783     else
784     {
785         res = OC_STACK_ERROR;
786         goto exit;
787     }
788
789     actionTypeStr = (char *)malloc(1024);
790     if(actionTypeStr != NULL)
791     {
792         sprintf(actionTypeStr, "%ld %u", actionset->timesteps, actionset->type);
793         strncat(temp, actionTypeStr, strlen(actionTypeStr));
794         remaining -= strlen(actionTypeStr);
795         free(actionTypeStr);
796         strncat(temp, ACTION_DELIMITER, strlen(ACTION_DELIMITER));
797         remaining--;
798     }
799     else
800     {
801         res = OC_STACK_ERROR;
802         goto exit;
803     }
804
805     while (action != NULL)
806     {
807         if (remaining < (strlen("uri=") + strlen(action->resourceUri) + 1))
808         {
809             res = OC_STACK_ERROR;
810             goto exit;
811         }
812         strcat(temp, "uri=");
813         remaining -= strlen("uri=");
814         strcat(temp, action->resourceUri);
815         remaining -= strlen(action->resourceUri);
816         strcat(temp, "|");
817         remaining--;
818
819         OCCapability *capas = action->head;
820         while (capas != NULL)
821         {
822             if (remaining < (strlen(capas->capability)
823                              + 1 + strlen(capas->status)))
824             {
825                 res = OC_STACK_ERROR;
826                 goto exit;
827             }
828
829             strcat(temp, capas->capability);
830             remaining -= strlen(capas->capability);
831             strcat(temp, "=");
832             remaining--;
833             strcat(temp, capas->status);
834             remaining -= strlen(capas->status);
835
836             capas = capas->next;
837             if (capas != NULL)
838             {
839                 if (remaining < 1)
840                 {
841                     res = OC_STACK_ERROR;
842                     goto exit;
843                 }
844                 strcat(temp, "|");
845             }
846         }
847
848         action = action->next;
849         if (action != NULL)
850         {
851             if (remaining < strlen(ACTION_DELIMITER))
852             {
853                 res = OC_STACK_ERROR;
854                 goto exit;
855             }
856             strcat(temp, ACTION_DELIMITER);
857             remaining--;
858         }
859     }
860
861     *desc = OICStrdup(temp);
862     VARIFY_POINTER_NULL(*desc, res, exit);
863
864     return OC_STACK_OK;
865
866 exit:
867     OCFREE(*desc);
868     return res;
869 }
870
871 OCStackApplicationResult ActionSetCB(void* context, OCDoHandle handle,
872         OCClientResponse* clientResponse)
873 {
874     (void)context;
875     (void)clientResponse;
876     OIC_LOG(INFO, TAG, "Entering ActionSetCB");
877
878     ClientRequestInfo *info = GetClientRequestInfo(clientRequstList, handle);
879
880     if (info)
881     {
882         OCEntityHandlerResponse response = { 0 };
883
884         response.ehResult = OC_EH_OK;
885
886         if(NULL == clientResponse->payload)
887         {
888             OIC_LOG(ERROR, TAG, "Error sending response");
889             return OC_STACK_DELETE_TRANSACTION;
890         }
891
892         // Format the response.  Note this requires some info about the request
893         response.requestHandle = info->ehRequest;
894         response.resourceHandle = info->collResource;
895         response.payload = clientResponse->payload;
896         response.numSendVendorSpecificHeaderOptions = 0;
897         memset(response.sendVendorSpecificHeaderOptions, 0,
898                 sizeof response.sendVendorSpecificHeaderOptions);
899         memset(response.resourceUri, 0, sizeof response.resourceUri);
900         // Indicate that response is NOT in a persistent buffer
901         response.persistentBufferFlag = 0;
902
903         // Send the response
904         if (OCDoResponse(&response) != OC_STACK_OK)
905         {
906             OIC_LOG(ERROR, TAG, "Error sending response");
907             return OC_STACK_DELETE_TRANSACTION;
908         }
909
910         RemoveClientRequestInfo(&clientRequstList, info);
911         OCFREE(info)
912     }
913
914     return OC_STACK_KEEP_TRANSACTION;
915 }
916
917 void ActionSetCD(void *context)
918 {
919     (void)context;
920 }
921
922 OCStackResult BuildActionJSON(OCAction* action, unsigned char* bufferPtr,
923         uint16_t *remaining)
924 {
925     OCStackResult ret = OC_STACK_ERROR;
926     cJSON *json;
927     cJSON *body;
928
929     char *jsonStr;
930     uint16_t jsonLen;
931
932     OIC_LOG(INFO, TAG, "Entering BuildActionJSON");
933     json = cJSON_CreateObject();
934
935     cJSON_AddItemToObject(json, "rep", body = cJSON_CreateObject());
936
937     OCCapability* pointerCapa = action->head;
938     while (pointerCapa)
939     {
940         cJSON_AddStringToObject(body, pointerCapa->capability,
941                 pointerCapa->status);
942         pointerCapa = pointerCapa->next;
943     }
944
945     jsonStr = cJSON_PrintUnformatted(json);
946
947     jsonLen = strlen(jsonStr);
948     if (jsonLen < *remaining)
949     {
950         strncat((char*) bufferPtr, jsonStr, jsonLen);
951         *remaining -= jsonLen;
952         bufferPtr += jsonLen;
953         ret = OC_STACK_OK;
954     }
955
956     cJSON_Delete(json);
957     free(jsonStr);
958
959     return ret;
960 }
961
962 OCPayload* BuildActionCBOR(OCAction* action)
963 {
964     OCRepPayload* payload = OCRepPayloadCreate();
965
966     if (!payload)
967     {
968         OIC_LOG(INFO, TAG, "Failed to create put payload object");
969         return NULL;
970     }
971
972     OCCapability* pointerCapa = action->head;
973     while (pointerCapa)
974     {
975         OCRepPayloadSetPropString(payload, pointerCapa->capability, pointerCapa->status);
976         pointerCapa = pointerCapa->next;
977     }
978
979     return (OCPayload*) payload;
980 }
981
982 unsigned int GetNumOfTargetResource(OCAction *actionset)
983 {
984     int numOfResource = 0;
985
986     OCAction *pointerAction = actionset;
987
988     while (pointerAction != NULL)
989     {
990         numOfResource++;
991         pointerAction = pointerAction->next;
992     }
993
994     return numOfResource;
995 }
996
997 OCStackResult SendAction(OCDoHandle *handle, OCServerRequest* requestHandle, const char *targetUri,
998         OCPayload *payload)
999 {
1000
1001     OCCallbackData cbData;
1002     cbData.cb = &ActionSetCB;
1003     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
1004     cbData.cd = NULL;
1005
1006     return OCDoResource(handle, OC_REST_PUT, targetUri, &requestHandle->devAddr,
1007                        payload, CT_ADAPTER_IP, OC_NA_QOS, &cbData, NULL, 0);
1008 }
1009
1010 OCStackResult DoAction(OCResource* resource, OCActionSet* actionset,
1011         OCServerRequest* requestHandle)
1012 {
1013     OCStackResult result = OC_STACK_ERROR;
1014
1015     if( NULL == actionset->head)
1016     {
1017         return result;
1018     }
1019
1020     OCAction *pointerAction = actionset->head;
1021
1022     while (pointerAction != NULL)
1023     {
1024         OCPayload* payload;
1025         payload = BuildActionCBOR(pointerAction);
1026
1027         if(payload == NULL)
1028         {
1029             return result;
1030         }
1031
1032         ClientRequestInfo *info = (ClientRequestInfo *) OICMalloc(
1033                 sizeof(ClientRequestInfo));
1034
1035         if( info == NULL )
1036         {
1037             OCFREE(payload);
1038             return OC_STACK_NO_MEMORY;
1039         }
1040
1041         memset(info, 0, sizeof(ClientRequestInfo));
1042
1043         info->collResource = resource;
1044         info->ehRequest = requestHandle;
1045
1046         result = SendAction(&info->required, info->ehRequest, pointerAction->resourceUri,
1047                 payload);
1048
1049         if (result != OC_STACK_OK)
1050         {
1051             OICFree(info);
1052             return result;
1053         }
1054
1055         AddClientRequestInfo(&clientRequstList, info);
1056
1057         pointerAction = pointerAction->next;
1058     }
1059
1060     return result;
1061 }
1062
1063 void DoScheduledGroupAction()
1064 {
1065     OIC_LOG(INFO, TAG, "DoScheduledGroupAction Entering...");
1066     ScheduledResourceInfo* info = GetScheduledResource(scheduleResourceList);
1067
1068     if (info == NULL)
1069     {
1070         OIC_LOG(INFO, TAG, "Target resource is NULL");
1071         goto exit;
1072     }
1073     else if (info->resource == NULL)
1074     {
1075         OIC_LOG(INFO, TAG, "Target resource is NULL");
1076         goto exit;
1077     }
1078     else if (info->actionset == NULL)
1079     {
1080         OIC_LOG(INFO, TAG, "Target ActionSet is NULL");
1081         goto exit;
1082     }
1083     else if (info->ehRequest == NULL)
1084     {
1085         OIC_LOG(INFO, TAG, "Target ActionSet is NULL");
1086         goto exit;
1087     }
1088 #ifndef WITH_ARDUINO
1089     pthread_mutex_lock(&lock);
1090 #endif
1091     DoAction(info->resource, info->actionset, info->ehRequest);
1092 #ifndef WITH_ARDUINO
1093     pthread_mutex_unlock(&lock);
1094 #endif
1095
1096     if (info->actionset->type == RECURSIVE)
1097     {
1098         ScheduledResourceInfo *schedule;
1099         schedule = (ScheduledResourceInfo *) OICMalloc(
1100                 sizeof(ScheduledResourceInfo));
1101
1102         if (schedule)
1103         {
1104             OIC_LOG(INFO, TAG, "Building New Call Info.");
1105             memset(schedule, 0, sizeof(ScheduledResourceInfo));
1106
1107             if (info->actionset->timesteps > 0)
1108             {
1109 #ifndef WITH_ARDUINO
1110                 pthread_mutex_lock(&lock);
1111 #endif
1112                 schedule->resource = info->resource;
1113                 schedule->actionset = info->actionset;
1114                 schedule->ehRequest = info->ehRequest;
1115
1116                 schedule->time = registerTimer(info->actionset->timesteps,
1117                         &schedule->timer_id,
1118                         &DoScheduledGroupAction);
1119
1120                 OIC_LOG(INFO, TAG, "Reregisteration.");
1121 #ifndef WITH_ARDUINO
1122                 pthread_mutex_unlock(&lock);
1123 #endif
1124                 AddScheduledResource(&scheduleResourceList, schedule);
1125             }
1126             else
1127             {
1128                 OICFree(schedule);
1129             }
1130         }
1131     }
1132
1133     RemoveScheduledResource(&scheduleResourceList, info);
1134
1135     exit:
1136
1137     return;
1138 }
1139
1140 OCStackResult BuildCollectionGroupActionCBORResponse(
1141         OCMethod method/*OCEntityHandlerFlag flag*/, OCResource *resource,
1142         OCEntityHandlerRequest *ehRequest)
1143 {
1144     OCStackResult stackRet = OC_STACK_ERROR;
1145
1146     OIC_LOG(INFO, TAG, "Group Action is requested.");
1147
1148     char *doWhat = NULL;
1149     char *details = NULL;
1150
1151     stackRet = ExtractKeyValueFromRequest(ehRequest, &doWhat, &details);
1152
1153     if(stackRet != OC_STACK_OK)
1154     {
1155         OIC_LOG_V(ERROR, TAG, "ExtractKeyValueFromRequest failed: %d", stackRet);
1156         return stackRet;
1157     }
1158
1159     stackRet = OC_STACK_ERROR;
1160
1161     if (method == OC_REST_PUT)
1162     {
1163         OIC_LOG(INFO, TAG, "Group Action[PUT].");
1164
1165         if (strcmp(doWhat, ACTIONSET) == 0)
1166         {
1167             OCActionSet *actionSet = NULL;
1168             stackRet = BuildActionSetFromString(&actionSet, details);
1169
1170             if(stackRet == OC_STACK_OK)
1171             {
1172                 if (actionSet != NULL)
1173                 {
1174                     stackRet = AddActionSet(&resource->actionsetHead,
1175                             actionSet);
1176                     if (stackRet == OC_STACK_ERROR)
1177                     {
1178                         if(actionSet != NULL)
1179                         {
1180                             DeleteActionSet( &actionSet );
1181                         }
1182                         OIC_LOG(INFO, TAG, "Duplicated ActionSet ");
1183                     }
1184                 }
1185                 else
1186                 {
1187                     stackRet = OC_STACK_ERROR;
1188                     goto exit;
1189                 }
1190             }
1191             else
1192             {
1193                 stackRet = OC_STACK_ERROR;
1194             }
1195
1196         }
1197         else if (strcmp(doWhat, DELETE_ACTIONSET) == 0)
1198         {
1199             if (FindAndDeleteActionSet(&resource, details) == OC_STACK_OK)
1200             {
1201                 stackRet = OC_STACK_OK;
1202             }
1203             else
1204             {
1205                 stackRet = OC_STACK_ERROR;
1206             }
1207         }
1208
1209         OCRepPayload* payload = OCRepPayloadCreate();
1210
1211         if(!payload)
1212         {
1213             OIC_LOG(ERROR, TAG, "Failed to allocate Payload");
1214             stackRet = OC_STACK_ERROR;
1215         }
1216         else
1217         {
1218             OCEntityHandlerResponse response = { 0 };
1219
1220             if(stackRet == OC_STACK_OK)
1221                 response.ehResult = OC_EH_OK;
1222             else
1223                 response.ehResult = OC_EH_ERROR;
1224
1225             // Format the response.  Note this requires some info about the request
1226             response.requestHandle = ehRequest->requestHandle;
1227             response.resourceHandle = ehRequest->resource;
1228             response.payload = (OCPayload*) payload;
1229             response.numSendVendorSpecificHeaderOptions = 0;
1230             memset(response.sendVendorSpecificHeaderOptions, 0,
1231                     sizeof response.sendVendorSpecificHeaderOptions);
1232             memset(response.resourceUri, 0, sizeof response. resourceUri);
1233             // Indicate that response is NOT in a persistent buffer
1234             response.persistentBufferFlag = 0;
1235             response.ehResult = (stackRet == OC_STACK_OK)?OC_EH_OK:OC_EH_ERROR;
1236
1237             // Send the response
1238             if (OCDoResponse(&response) != OC_STACK_OK)
1239             {
1240                 OIC_LOG(ERROR, TAG, "Error sending response");
1241                 stackRet = OC_STACK_ERROR;
1242             }
1243         }
1244     }
1245     else if (method == OC_REST_POST)
1246     {
1247         OCActionSet *actionset = NULL;
1248
1249         OCRepPayload* payload = OCRepPayloadCreate();
1250         OCRepPayloadSetUri(payload, resource->uri);
1251
1252         if ((strcmp(doWhat, DO_ACTION) == 0)
1253                 || (strcmp(doWhat, "DoScheduledAction") == 0))
1254         {
1255             char *pActionsetName = NULL;
1256             long int delay = -1;
1257
1258             if (strcmp(doWhat, "DoScheduledAction") == 0)
1259             {
1260                 stackRet = ExtractActionSetNameAndDelaytime(details,
1261                         &pActionsetName, &delay);
1262
1263                 OCFREE(details)
1264                 details = pActionsetName;
1265             }
1266             else
1267             {
1268                 stackRet = OC_STACK_OK;
1269             }
1270
1271             if (stackRet == OC_STACK_OK)
1272             {
1273                 if (GetActionSet(details, resource->actionsetHead,
1274                         &actionset) != OC_STACK_OK)
1275                 {
1276                     OIC_LOG(INFO, TAG, "ERROR");
1277                     stackRet = OC_STACK_ERROR;
1278                 }
1279
1280                 if (actionset == NULL)
1281                 {
1282                     OIC_LOG(INFO, TAG, "Cannot Find ActionSet");
1283                     stackRet = OC_STACK_ERROR;
1284                 }
1285                 else
1286                 {
1287                     OIC_LOG(INFO, TAG, "Group Action[POST].");
1288                     if (actionset->type == NONE)
1289                     {
1290                         OIC_LOG_V(INFO, TAG, "Execute ActionSet : %s",
1291                                 actionset->actionsetName);
1292                         unsigned int num = GetNumOfTargetResource(
1293                                 actionset->head);
1294
1295                         ((OCServerRequest *) ehRequest->requestHandle)->ehResponseHandler =
1296                                 HandleAggregateResponse;
1297                         ((OCServerRequest *) ehRequest->requestHandle)->numResponses =
1298                                 num + 1;
1299
1300                         DoAction(resource, actionset,
1301                                 (OCServerRequest*) ehRequest->requestHandle);
1302                         stackRet = OC_STACK_OK;
1303                     }
1304                     else
1305                     {
1306                         OIC_LOG_V(INFO, TAG, "Execute Scheduled ActionSet : %s",
1307                                 actionset->actionsetName);
1308
1309                         delay =
1310                                 (delay == -1 ? actionset->timesteps : delay);
1311
1312                         ScheduledResourceInfo *schedule;
1313                         schedule = (ScheduledResourceInfo *) OICMalloc(
1314                                 sizeof(ScheduledResourceInfo));
1315
1316                         if (schedule)
1317                         {
1318                             OIC_LOG(INFO, TAG, "Building New Call Info.");
1319                             memset(schedule, 0,
1320                                     sizeof(ScheduledResourceInfo));
1321 #ifndef WITH_ARDUINO
1322                             pthread_mutex_lock(&lock);
1323 #endif
1324                             schedule->resource = resource;
1325                             schedule->actionset = actionset;
1326                             schedule->ehRequest =
1327                                     (OCServerRequest*) ehRequest->requestHandle;
1328 #ifndef WITH_ARDUINO
1329                             pthread_mutex_unlock(&lock);
1330 #endif
1331                             if (delay > 0)
1332                             {
1333                                 OIC_LOG_V(INFO, TAG, "delay_time is %ld seconds.",
1334                                         actionset->timesteps);
1335 #ifndef WITH_ARDUINO
1336                                 pthread_mutex_lock(&lock);
1337 #endif
1338                                 schedule->time = registerTimer(delay,
1339                                         &schedule->timer_id,
1340                                         &DoScheduledGroupAction);
1341 #ifndef WITH_ARDUINO
1342                                 pthread_mutex_unlock(&lock);
1343 #endif
1344                                 AddScheduledResource(&scheduleResourceList,
1345                                         schedule);
1346                                 stackRet = OC_STACK_OK;
1347                             }
1348                             else
1349                             {
1350                                 stackRet = OC_STACK_ERROR;
1351                             }
1352                         }
1353                     }
1354                 }
1355             }
1356         }
1357         else if (strcmp(doWhat, "CancelAction") == 0)
1358         {
1359             ScheduledResourceInfo *info =
1360                     GetScheduledResourceByActionSetName(scheduleResourceList, details);
1361
1362             if(info != NULL)
1363             {
1364                 unregisterTimer(info->timer_id);
1365
1366                 RemoveScheduledResource(&scheduleResourceList, info);
1367                 stackRet = OC_STACK_OK;
1368             }
1369             else
1370             {
1371                 stackRet = OC_STACK_ERROR;
1372             }
1373         }
1374
1375         else if (strcmp(doWhat, GET_ACTIONSET) == 0)
1376         {
1377             char *plainText = NULL;
1378             OCActionSet *actionset = NULL;
1379
1380             GetActionSet(details, resource->actionsetHead, &actionset);
1381             if (actionset != NULL)
1382             {
1383                 BuildStringFromActionSet(actionset, &plainText);
1384
1385                 if (plainText != NULL)
1386                 {
1387                     OCRepPayloadSetPropString(payload, ACTIONSET, plainText);
1388                 }
1389                 OICFree(plainText);
1390                 stackRet = OC_STACK_OK;
1391             }
1392         }
1393
1394         if(!payload)
1395         {
1396             OIC_LOG(ERROR, TAG, "Failed to allocate Payload");
1397             stackRet = OC_STACK_ERROR;
1398         }
1399         else
1400         {
1401             OCEntityHandlerResponse response = { 0 };
1402             if(stackRet == OC_STACK_OK)
1403                 response.ehResult = OC_EH_OK;
1404             else
1405                 response.ehResult = OC_EH_ERROR;
1406
1407             // Format the response.  Note this requires some info about the request
1408             response.requestHandle = ehRequest->requestHandle;
1409             response.resourceHandle = ehRequest->resource;
1410             response.payload = (OCPayload*) payload;
1411             response.numSendVendorSpecificHeaderOptions = 0;
1412             memset(response.sendVendorSpecificHeaderOptions, 0,
1413                     sizeof response.sendVendorSpecificHeaderOptions);
1414             memset(response.resourceUri, 0, sizeof response.resourceUri);
1415             // Indicate that response is NOT in a persistent buffer
1416             response.persistentBufferFlag = 0;
1417             response.ehResult = (stackRet == OC_STACK_OK)?OC_EH_OK:OC_EH_ERROR;
1418
1419             // Send the response
1420             if (OCDoResponse(&response) != OC_STACK_OK)
1421             {
1422                 OIC_LOG(ERROR, TAG, "Error sending response");
1423                 stackRet = OC_STACK_ERROR;
1424             }
1425         }
1426     }
1427
1428 exit:
1429
1430     OCFREE(doWhat)
1431     OCFREE(details)
1432
1433     return stackRet;
1434 }