Remove an vulnerability for using strcat() function in oicgroup
[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 && remaining >= strlen(actionTypeStr) + strlen(ACTION_DELIMITER) + 1)
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 -= strlen(ACTION_DELIMITER);
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
813         strcat(temp, "uri=");
814         remaining -= strlen("uri=");
815         strcat(temp, action->resourceUri);
816         remaining -= strlen(action->resourceUri);
817         strcat(temp, "|");
818         remaining--;
819
820         OCCapability *capas = action->head;
821         while (capas != NULL)
822         {
823             if (remaining < (strlen(capas->capability)
824                              + 1 + strlen(capas->status)))
825             {
826                 res = OC_STACK_ERROR;
827                 goto exit;
828             }
829
830             strcat(temp, capas->capability);
831             remaining -= strlen(capas->capability);
832             strcat(temp, "=");
833             remaining--;
834             strcat(temp, capas->status);
835             remaining -= strlen(capas->status);
836
837             capas = capas->next;
838             if (capas != NULL)
839             {
840                 if (remaining < 1)
841                 {
842                     res = OC_STACK_ERROR;
843                     goto exit;
844                 }
845                 strcat(temp, "|");
846                 remaining --;
847             }
848         }
849
850         action = action->next;
851         if (action != NULL)
852         {
853             if (remaining < strlen(ACTION_DELIMITER))
854             {
855                 res = OC_STACK_ERROR;
856                 goto exit;
857             }
858             strcat(temp, ACTION_DELIMITER);
859             remaining--;
860         }
861     }
862
863     *desc = OICStrdup(temp);
864     VARIFY_POINTER_NULL(*desc, res, exit);
865
866     return OC_STACK_OK;
867
868 exit:
869     OCFREE(*desc);
870     return res;
871 }
872
873 OCStackApplicationResult ActionSetCB(void* context, OCDoHandle handle,
874         OCClientResponse* clientResponse)
875 {
876     (void)context;
877     (void)clientResponse;
878     OIC_LOG(INFO, TAG, "Entering ActionSetCB");
879
880     ClientRequestInfo *info = GetClientRequestInfo(clientRequstList, handle);
881
882     if (info)
883     {
884         OCEntityHandlerResponse response = { 0 };
885
886         response.ehResult = OC_EH_OK;
887
888         if(NULL == clientResponse->payload)
889         {
890             OIC_LOG(ERROR, TAG, "Error sending response");
891             return OC_STACK_DELETE_TRANSACTION;
892         }
893
894         // Format the response.  Note this requires some info about the request
895         response.requestHandle = info->ehRequest;
896         response.resourceHandle = info->collResource;
897         response.payload = clientResponse->payload;
898         response.numSendVendorSpecificHeaderOptions = 0;
899         memset(response.sendVendorSpecificHeaderOptions, 0,
900                 sizeof response.sendVendorSpecificHeaderOptions);
901         memset(response.resourceUri, 0, sizeof response.resourceUri);
902         // Indicate that response is NOT in a persistent buffer
903         response.persistentBufferFlag = 0;
904
905         // Send the response
906         if (OCDoResponse(&response) != OC_STACK_OK)
907         {
908             OIC_LOG(ERROR, TAG, "Error sending response");
909             return OC_STACK_DELETE_TRANSACTION;
910         }
911
912         RemoveClientRequestInfo(&clientRequstList, info);
913         OCFREE(info)
914     }
915
916     return OC_STACK_KEEP_TRANSACTION;
917 }
918
919 void ActionSetCD(void *context)
920 {
921     (void)context;
922 }
923
924 OCStackResult BuildActionJSON(OCAction* action, unsigned char* bufferPtr,
925         uint16_t *remaining)
926 {
927     OCStackResult ret = OC_STACK_ERROR;
928     cJSON *json;
929     cJSON *body;
930
931     char *jsonStr;
932     uint16_t jsonLen;
933
934     OIC_LOG(INFO, TAG, "Entering BuildActionJSON");
935     json = cJSON_CreateObject();
936
937     cJSON_AddItemToObject(json, "rep", body = cJSON_CreateObject());
938
939     OCCapability* pointerCapa = action->head;
940     while (pointerCapa)
941     {
942         cJSON_AddStringToObject(body, pointerCapa->capability,
943                 pointerCapa->status);
944         pointerCapa = pointerCapa->next;
945     }
946
947     jsonStr = cJSON_PrintUnformatted(json);
948
949     jsonLen = strlen(jsonStr);
950     if (jsonLen < *remaining)
951     {
952         strncat((char*) bufferPtr, jsonStr, jsonLen);
953         *remaining -= jsonLen;
954         bufferPtr += jsonLen;
955         ret = OC_STACK_OK;
956     }
957
958     cJSON_Delete(json);
959     free(jsonStr);
960
961     return ret;
962 }
963
964 OCPayload* BuildActionCBOR(OCAction* action)
965 {
966     OCRepPayload* payload = OCRepPayloadCreate();
967
968     if (!payload)
969     {
970         OIC_LOG(INFO, TAG, "Failed to create put payload object");
971         return NULL;
972     }
973
974     OCCapability* pointerCapa = action->head;
975     while (pointerCapa)
976     {
977         OCRepPayloadSetPropString(payload, pointerCapa->capability, pointerCapa->status);
978         pointerCapa = pointerCapa->next;
979     }
980
981     return (OCPayload*) payload;
982 }
983
984 unsigned int GetNumOfTargetResource(OCAction *actionset)
985 {
986     int numOfResource = 0;
987
988     OCAction *pointerAction = actionset;
989
990     while (pointerAction != NULL)
991     {
992         numOfResource++;
993         pointerAction = pointerAction->next;
994     }
995
996     return numOfResource;
997 }
998
999 OCStackResult SendAction(OCDoHandle *handle, OCServerRequest* requestHandle, const char *targetUri,
1000         OCPayload *payload)
1001 {
1002
1003     OCCallbackData cbData;
1004     cbData.cb = &ActionSetCB;
1005     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
1006     cbData.cd = NULL;
1007
1008     return OCDoResource(handle, OC_REST_PUT, targetUri, &requestHandle->devAddr,
1009                        payload, CT_ADAPTER_IP, OC_NA_QOS, &cbData, NULL, 0);
1010 }
1011
1012 OCStackResult DoAction(OCResource* resource, OCActionSet* actionset,
1013         OCServerRequest* requestHandle)
1014 {
1015     OCStackResult result = OC_STACK_ERROR;
1016
1017     if( NULL == actionset->head)
1018     {
1019         return result;
1020     }
1021
1022     OCAction *pointerAction = actionset->head;
1023
1024     while (pointerAction != NULL)
1025     {
1026         OCPayload* payload;
1027         payload = BuildActionCBOR(pointerAction);
1028
1029         if(payload == NULL)
1030         {
1031             return result;
1032         }
1033
1034         ClientRequestInfo *info = (ClientRequestInfo *) OICMalloc(
1035                 sizeof(ClientRequestInfo));
1036
1037         if( info == NULL )
1038         {
1039             OCFREE(payload);
1040             return OC_STACK_NO_MEMORY;
1041         }
1042
1043         memset(info, 0, sizeof(ClientRequestInfo));
1044
1045         info->collResource = resource;
1046         info->ehRequest = requestHandle;
1047
1048         result = SendAction(&info->required, info->ehRequest, pointerAction->resourceUri,
1049                 payload);
1050
1051         if (result != OC_STACK_OK)
1052         {
1053             OICFree(info);
1054             return result;
1055         }
1056
1057         AddClientRequestInfo(&clientRequstList, info);
1058
1059         pointerAction = pointerAction->next;
1060     }
1061
1062     return result;
1063 }
1064
1065 void DoScheduledGroupAction()
1066 {
1067     OIC_LOG(INFO, TAG, "DoScheduledGroupAction Entering...");
1068     ScheduledResourceInfo* info = GetScheduledResource(scheduleResourceList);
1069
1070     if (info == NULL)
1071     {
1072         OIC_LOG(INFO, TAG, "Target resource is NULL");
1073         goto exit;
1074     }
1075     else if (info->resource == NULL)
1076     {
1077         OIC_LOG(INFO, TAG, "Target resource is NULL");
1078         goto exit;
1079     }
1080     else if (info->actionset == NULL)
1081     {
1082         OIC_LOG(INFO, TAG, "Target ActionSet is NULL");
1083         goto exit;
1084     }
1085     else if (info->ehRequest == NULL)
1086     {
1087         OIC_LOG(INFO, TAG, "Target ActionSet is NULL");
1088         goto exit;
1089     }
1090 #ifndef WITH_ARDUINO
1091     pthread_mutex_lock(&lock);
1092 #endif
1093     DoAction(info->resource, info->actionset, info->ehRequest);
1094 #ifndef WITH_ARDUINO
1095     pthread_mutex_unlock(&lock);
1096 #endif
1097
1098     if (info->actionset->type == RECURSIVE)
1099     {
1100         ScheduledResourceInfo *schedule;
1101         schedule = (ScheduledResourceInfo *) OICMalloc(
1102                 sizeof(ScheduledResourceInfo));
1103
1104         if (schedule)
1105         {
1106             OIC_LOG(INFO, TAG, "Building New Call Info.");
1107             memset(schedule, 0, sizeof(ScheduledResourceInfo));
1108
1109             if (info->actionset->timesteps > 0)
1110             {
1111 #ifndef WITH_ARDUINO
1112                 pthread_mutex_lock(&lock);
1113 #endif
1114                 schedule->resource = info->resource;
1115                 schedule->actionset = info->actionset;
1116                 schedule->ehRequest = info->ehRequest;
1117
1118                 schedule->time = registerTimer(info->actionset->timesteps,
1119                         &schedule->timer_id,
1120                         &DoScheduledGroupAction);
1121
1122                 OIC_LOG(INFO, TAG, "Reregisteration.");
1123 #ifndef WITH_ARDUINO
1124                 pthread_mutex_unlock(&lock);
1125 #endif
1126                 AddScheduledResource(&scheduleResourceList, schedule);
1127             }
1128             else
1129             {
1130                 OICFree(schedule);
1131             }
1132         }
1133     }
1134
1135     RemoveScheduledResource(&scheduleResourceList, info);
1136
1137     exit:
1138
1139     return;
1140 }
1141
1142 OCStackResult BuildCollectionGroupActionCBORResponse(
1143         OCMethod method/*OCEntityHandlerFlag flag*/, OCResource *resource,
1144         OCEntityHandlerRequest *ehRequest)
1145 {
1146     OCStackResult stackRet = OC_STACK_ERROR;
1147
1148     OIC_LOG(INFO, TAG, "Group Action is requested.");
1149
1150     char *doWhat = NULL;
1151     char *details = NULL;
1152
1153     stackRet = ExtractKeyValueFromRequest(ehRequest, &doWhat, &details);
1154
1155     if(stackRet != OC_STACK_OK)
1156     {
1157         OIC_LOG_V(ERROR, TAG, "ExtractKeyValueFromRequest failed: %d", stackRet);
1158         return stackRet;
1159     }
1160
1161     stackRet = OC_STACK_ERROR;
1162
1163     if (method == OC_REST_PUT)
1164     {
1165         OIC_LOG(INFO, TAG, "Group Action[PUT].");
1166
1167         if (strcmp(doWhat, ACTIONSET) == 0)
1168         {
1169             OCActionSet *actionSet = NULL;
1170             stackRet = BuildActionSetFromString(&actionSet, details);
1171
1172             if(stackRet == OC_STACK_OK)
1173             {
1174                 if (actionSet != NULL)
1175                 {
1176                     stackRet = AddActionSet(&resource->actionsetHead,
1177                             actionSet);
1178                     if (stackRet == OC_STACK_ERROR)
1179                     {
1180                         if(actionSet != NULL)
1181                         {
1182                             DeleteActionSet( &actionSet );
1183                         }
1184                         OIC_LOG(INFO, TAG, "Duplicated ActionSet ");
1185                     }
1186                 }
1187                 else
1188                 {
1189                     stackRet = OC_STACK_ERROR;
1190                     goto exit;
1191                 }
1192             }
1193             else
1194             {
1195                 stackRet = OC_STACK_ERROR;
1196             }
1197
1198         }
1199         else if (strcmp(doWhat, DELETE_ACTIONSET) == 0)
1200         {
1201             if (FindAndDeleteActionSet(&resource, details) == OC_STACK_OK)
1202             {
1203                 stackRet = OC_STACK_OK;
1204             }
1205             else
1206             {
1207                 stackRet = OC_STACK_ERROR;
1208             }
1209         }
1210
1211         OCRepPayload* payload = OCRepPayloadCreate();
1212
1213         if(!payload)
1214         {
1215             OIC_LOG(ERROR, TAG, "Failed to allocate Payload");
1216             stackRet = OC_STACK_ERROR;
1217         }
1218         else
1219         {
1220             OCEntityHandlerResponse response = { 0 };
1221
1222             if(stackRet == OC_STACK_OK)
1223                 response.ehResult = OC_EH_OK;
1224             else
1225                 response.ehResult = OC_EH_ERROR;
1226
1227             // Format the response.  Note this requires some info about the request
1228             response.requestHandle = ehRequest->requestHandle;
1229             response.resourceHandle = ehRequest->resource;
1230             response.payload = (OCPayload*) payload;
1231             response.numSendVendorSpecificHeaderOptions = 0;
1232             memset(response.sendVendorSpecificHeaderOptions, 0,
1233                     sizeof response.sendVendorSpecificHeaderOptions);
1234             memset(response.resourceUri, 0, sizeof response. resourceUri);
1235             // Indicate that response is NOT in a persistent buffer
1236             response.persistentBufferFlag = 0;
1237             response.ehResult = (stackRet == OC_STACK_OK)?OC_EH_OK:OC_EH_ERROR;
1238
1239             // Send the response
1240             if (OCDoResponse(&response) != OC_STACK_OK)
1241             {
1242                 OIC_LOG(ERROR, TAG, "Error sending response");
1243                 stackRet = OC_STACK_ERROR;
1244             }
1245         }
1246     }
1247     else if (method == OC_REST_POST)
1248     {
1249         OCActionSet *actionset = NULL;
1250
1251         OCRepPayload* payload = OCRepPayloadCreate();
1252         OCRepPayloadSetUri(payload, resource->uri);
1253
1254         if ((strcmp(doWhat, DO_ACTION) == 0)
1255                 || (strcmp(doWhat, "DoScheduledAction") == 0))
1256         {
1257             char *pActionsetName = NULL;
1258             long int delay = -1;
1259
1260             if (strcmp(doWhat, "DoScheduledAction") == 0)
1261             {
1262                 stackRet = ExtractActionSetNameAndDelaytime(details,
1263                         &pActionsetName, &delay);
1264
1265                 OCFREE(details)
1266                 details = pActionsetName;
1267             }
1268             else
1269             {
1270                 stackRet = OC_STACK_OK;
1271             }
1272
1273             if (stackRet == OC_STACK_OK)
1274             {
1275                 if (GetActionSet(details, resource->actionsetHead,
1276                         &actionset) != OC_STACK_OK)
1277                 {
1278                     OIC_LOG(INFO, TAG, "ERROR");
1279                     stackRet = OC_STACK_ERROR;
1280                 }
1281
1282                 if (actionset == NULL)
1283                 {
1284                     OIC_LOG(INFO, TAG, "Cannot Find ActionSet");
1285                     stackRet = OC_STACK_ERROR;
1286                 }
1287                 else
1288                 {
1289                     OIC_LOG(INFO, TAG, "Group Action[POST].");
1290                     if (actionset->type == NONE)
1291                     {
1292                         OIC_LOG_V(INFO, TAG, "Execute ActionSet : %s",
1293                                 actionset->actionsetName);
1294                         unsigned int num = GetNumOfTargetResource(
1295                                 actionset->head);
1296
1297                         ((OCServerRequest *) ehRequest->requestHandle)->ehResponseHandler =
1298                                 HandleAggregateResponse;
1299                         ((OCServerRequest *) ehRequest->requestHandle)->numResponses =
1300                                 num + 1;
1301
1302                         DoAction(resource, actionset,
1303                                 (OCServerRequest*) ehRequest->requestHandle);
1304                         stackRet = OC_STACK_OK;
1305                     }
1306                     else
1307                     {
1308                         OIC_LOG_V(INFO, TAG, "Execute Scheduled ActionSet : %s",
1309                                 actionset->actionsetName);
1310
1311                         delay =
1312                                 (delay == -1 ? actionset->timesteps : delay);
1313
1314                         ScheduledResourceInfo *schedule;
1315                         schedule = (ScheduledResourceInfo *) OICMalloc(
1316                                 sizeof(ScheduledResourceInfo));
1317
1318                         if (schedule)
1319                         {
1320                             OIC_LOG(INFO, TAG, "Building New Call Info.");
1321                             memset(schedule, 0,
1322                                     sizeof(ScheduledResourceInfo));
1323 #ifndef WITH_ARDUINO
1324                             pthread_mutex_lock(&lock);
1325 #endif
1326                             schedule->resource = resource;
1327                             schedule->actionset = actionset;
1328                             schedule->ehRequest =
1329                                     (OCServerRequest*) ehRequest->requestHandle;
1330 #ifndef WITH_ARDUINO
1331                             pthread_mutex_unlock(&lock);
1332 #endif
1333                             if (delay > 0)
1334                             {
1335                                 OIC_LOG_V(INFO, TAG, "delay_time is %ld seconds.",
1336                                         actionset->timesteps);
1337 #ifndef WITH_ARDUINO
1338                                 pthread_mutex_lock(&lock);
1339 #endif
1340                                 schedule->time = registerTimer(delay,
1341                                         &schedule->timer_id,
1342                                         &DoScheduledGroupAction);
1343 #ifndef WITH_ARDUINO
1344                                 pthread_mutex_unlock(&lock);
1345 #endif
1346                                 AddScheduledResource(&scheduleResourceList,
1347                                         schedule);
1348                                 stackRet = OC_STACK_OK;
1349                             }
1350                             else
1351                             {
1352                                 stackRet = OC_STACK_ERROR;
1353                             }
1354                         }
1355                     }
1356                 }
1357             }
1358         }
1359         else if (strcmp(doWhat, "CancelAction") == 0)
1360         {
1361             ScheduledResourceInfo *info =
1362                     GetScheduledResourceByActionSetName(scheduleResourceList, details);
1363
1364             if(info != NULL)
1365             {
1366                 unregisterTimer(info->timer_id);
1367
1368                 RemoveScheduledResource(&scheduleResourceList, info);
1369                 stackRet = OC_STACK_OK;
1370             }
1371             else
1372             {
1373                 stackRet = OC_STACK_ERROR;
1374             }
1375         }
1376
1377         else if (strcmp(doWhat, GET_ACTIONSET) == 0)
1378         {
1379             char *plainText = NULL;
1380             OCActionSet *actionset = NULL;
1381
1382             GetActionSet(details, resource->actionsetHead, &actionset);
1383             if (actionset != NULL)
1384             {
1385                 BuildStringFromActionSet(actionset, &plainText);
1386
1387                 if (plainText != NULL)
1388                 {
1389                     OCRepPayloadSetPropString(payload, ACTIONSET, plainText);
1390                 }
1391                 OICFree(plainText);
1392                 stackRet = OC_STACK_OK;
1393             }
1394         }
1395
1396         if(!payload)
1397         {
1398             OIC_LOG(ERROR, TAG, "Failed to allocate Payload");
1399             stackRet = OC_STACK_ERROR;
1400         }
1401         else
1402         {
1403             OCEntityHandlerResponse response = { 0 };
1404             if(stackRet == OC_STACK_OK)
1405                 response.ehResult = OC_EH_OK;
1406             else
1407                 response.ehResult = OC_EH_ERROR;
1408
1409             // Format the response.  Note this requires some info about the request
1410             response.requestHandle = ehRequest->requestHandle;
1411             response.resourceHandle = ehRequest->resource;
1412             response.payload = (OCPayload*) payload;
1413             response.numSendVendorSpecificHeaderOptions = 0;
1414             memset(response.sendVendorSpecificHeaderOptions, 0,
1415                     sizeof response.sendVendorSpecificHeaderOptions);
1416             memset(response.resourceUri, 0, sizeof response.resourceUri);
1417             // Indicate that response is NOT in a persistent buffer
1418             response.persistentBufferFlag = 0;
1419             response.ehResult = (stackRet == OC_STACK_OK)?OC_EH_OK:OC_EH_ERROR;
1420
1421             // Send the response
1422             if (OCDoResponse(&response) != OC_STACK_OK)
1423             {
1424                 OIC_LOG(ERROR, TAG, "Error sending response");
1425                 stackRet = OC_STACK_ERROR;
1426             }
1427         }
1428     }
1429
1430 exit:
1431
1432     OCFREE(doWhat)
1433     OCFREE(details)
1434
1435     return stackRet;
1436 }