Merge branch 'master' into easysetup
[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 "OICGROUP"
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     OC_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     OC_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                 OC_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         OC_LOG(INFO, TAG, "Cannot Find Call Info.");
174     }
175     return tmp;
176 }
177
178 ScheduledResourceInfo* GetScheduledResourceByActionSetName(ScheduledResourceInfo *head, char *setName)
179 {
180     OC_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                 OC_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         OC_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     OC_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 DeleteActionSets(OCResource** resource)
500 {
501     OCActionSet *pointer = (*resource)->actionsetHead;
502     OCActionSet *pDel = pointer;
503
504     while (pointer)
505     {
506         pDel = pointer;
507         pointer = pointer->next;
508
509         DeleteActionSet(&pDel);
510         pDel->next = NULL;
511     }
512
513     (*resource)->actionsetHead = NULL;
514     return OC_STACK_OK;
515 }
516
517 OCStackResult GetActionSet(const char *actionName, OCActionSet *head,
518         OCActionSet** actionset)
519 {
520     OCActionSet *pointer = head;
521
522     while (pointer)
523     {
524         if (strcmp(pointer->actionsetName, actionName) == 0)
525         {
526             *actionset = pointer;
527             return OC_STACK_OK;
528         }
529
530         pointer = pointer->next;
531     }
532
533     return OC_STACK_ERROR;
534
535 }
536
537 OCStackResult ExtractKeyValueFromRequest(OCEntityHandlerRequest *ehRequest,
538                                         char **key, char **value)
539 {
540     OCStackResult result = OC_STACK_OK;
541
542     char *actionSetStr = NULL;
543
544     if( NULL == ehRequest->payload )
545     {
546         result = OC_STACK_ERROR;
547         goto exit;
548     }
549
550     OCRepPayload* input;
551
552     input = (OCRepPayload*)(ehRequest->payload);
553
554     if(OCRepPayloadGetPropString(input, ACTIONSET, &actionSetStr))
555     {
556         *key = OICStrdup(ACTIONSET);
557         VARIFY_POINTER_NULL(*key, result, exit);
558
559         *value = OICStrdup(actionSetStr);
560         VARIFY_POINTER_NULL(*value, result, exit);
561     }
562     else if(OCRepPayloadGetPropString(input, DO_ACTION, &actionSetStr))
563     {
564         *key = OICStrdup(DO_ACTION);
565         VARIFY_POINTER_NULL(*key, result, exit);
566
567         *value = OICStrdup(actionSetStr);
568         VARIFY_POINTER_NULL(*value, result, exit);
569     }
570     else if(OCRepPayloadGetPropString(input, GET_ACTIONSET, &actionSetStr))
571     {
572         *key = OICStrdup(GET_ACTIONSET);
573         VARIFY_POINTER_NULL(*key, result, exit);
574
575         *value = OICStrdup(actionSetStr);
576         VARIFY_POINTER_NULL(*value, result, exit);
577     }
578     else if(OCRepPayloadGetPropString(input, DELETE_ACTIONSET, &actionSetStr))
579     {
580         *key = OICStrdup(DELETE_ACTIONSET);
581         VARIFY_POINTER_NULL(*key, result, exit);
582
583         *value = OICStrdup(actionSetStr);
584         VARIFY_POINTER_NULL(*value, result, exit);
585     }
586     else if(OCRepPayloadGetPropString(input, CANCEL_ACTIONSET, &actionSetStr))
587     {
588         *key = OICStrdup(CANCEL_ACTIONSET);
589         VARIFY_POINTER_NULL(*key, result, exit);
590
591         *value = OICStrdup(actionSetStr);
592         VARIFY_POINTER_NULL(*value, result, exit);
593     }
594     else
595     {
596         result = OC_STACK_ERROR;
597     }
598
599 exit:
600     if (result != OC_STACK_OK)
601     {
602         OCFREE(*key)
603         OCFREE(*value)
604     }
605
606     OCFREE(actionSetStr);
607
608     return result;
609 }
610
611 OCStackResult ExtractActionSetNameAndDelaytime(char *pChar, char **setName,
612         long int *pa)
613 {
614     char *token = NULL, *tokenPtr = NULL;
615     OCStackResult result = OC_STACK_OK;
616
617     token = (char*) strtok_r(pChar, ACTION_DELIMITER, &tokenPtr);
618     VARIFY_POINTER_NULL(token, result, exit)
619
620     *setName = (char *) OICMalloc(strlen(token) + 1);
621     VARIFY_POINTER_NULL(*setName, result, exit)
622     VARIFY_PARAM_NULL(token, result, exit)
623     strncpy(*setName, token, strlen(token) + 1);
624
625     token = strtok_r(NULL, ACTION_DELIMITER, &tokenPtr);
626     VARIFY_POINTER_NULL(pa, result, exit)
627     VARIFY_PARAM_NULL(token, result, exit)
628     *pa = atoi(token);
629
630     return OC_STACK_OK;
631
632 exit:
633     OCFREE(*setName);
634     return result;
635 }
636
637 OCStackResult BuildActionSetFromString(OCActionSet **set, char* actiondesc)
638 {
639     OCStackResult result = OC_STACK_OK;
640
641     char *iterToken = NULL, *iterTokenPtr = NULL;
642     char *descIterToken = NULL, *descIterTokenPtr = NULL;
643     char *attrIterToken = NULL, *attrIterTokenPtr = NULL;
644     char *desc = NULL, *attr = NULL;
645     char *key = NULL, *value = NULL;
646
647     OCAction *action = NULL;
648     OCCapability *capa = NULL;
649
650     OC_LOG(INFO, TAG, "Build ActionSet Instance.");
651
652     *set = (OCActionSet*) OICMalloc(sizeof(OCActionSet));
653     VARIFY_POINTER_NULL(*set, result, exit)
654
655     iterToken = (char *) strtok_r(actiondesc, ACTION_DELIMITER, &iterTokenPtr);
656
657     // ActionSet Name
658     memset(*set, 0, sizeof(OCActionSet));
659     (*set)->actionsetName = (char *) OICMalloc(strlen(iterToken) + 1);
660     VARIFY_POINTER_NULL((*set)->actionsetName, result, exit)
661     VARIFY_PARAM_NULL(iterToken, result, exit)
662     strncpy((*set)->actionsetName, iterToken, strlen(iterToken) + 1);
663
664     // Time info. for Scheduled/Recursive Group action.
665     // d is meant Day of the week.
666     // T is meant ActionType.
667     // yyyy-mm-dd hh:mm:ss d
668     iterToken = (char *) strtok_r(NULL, ACTION_DELIMITER, &iterTokenPtr);
669     VARIFY_PARAM_NULL(iterToken, result, exit)
670 #ifndef WITH_ARDUINO
671     if( 2 != sscanf(iterToken, "%ld %u", &(*set)->timesteps, &(*set)->type) )
672     {
673         // If the return value should be 2, the number of items in the argument. Otherwise, it fails.
674         goto exit;
675     }
676 #endif
677
678     OC_LOG_V(INFO, TAG, "ActionSet Name : %s", (*set)->actionsetName);
679
680     iterToken = (char *) strtok_r(NULL, ACTION_DELIMITER, &iterTokenPtr);
681     while (iterToken)
682     {
683         desc = (char *) OICMalloc(strlen(iterToken) + 1);
684         VARIFY_POINTER_NULL(desc, result, exit)
685         VARIFY_PARAM_NULL(desc, result, exit)
686         strncpy(desc, iterToken, strlen(iterToken) + 1);
687         descIterToken = (char *) strtok_r(desc, ATTR_DELIMITER,
688                 &descIterTokenPtr);
689         while (descIterToken)
690         {
691             attr = (char *) OICMalloc(strlen(descIterToken) + 1);
692             VARIFY_POINTER_NULL(attr, result, exit)
693             VARIFY_PARAM_NULL(descIterToken, result, exit)
694             strncpy(attr, descIterToken, strlen(descIterToken) + 1);
695
696             attrIterToken = (char *) strtok_r(attr, ATTR_ASSIGN,
697                     &attrIterTokenPtr);
698             VARIFY_POINTER_NULL(attrIterToken, result, exit);
699
700             key = (char *) OICMalloc(strlen(attrIterToken) + 1);
701             VARIFY_POINTER_NULL(key, result, exit)
702             VARIFY_PARAM_NULL(attrIterToken, result, exit)
703             strncpy(key, attrIterToken, strlen(attrIterToken) + 1);
704
705             attrIterToken = (char *) strtok_r(NULL, ATTR_ASSIGN,
706                     &attrIterTokenPtr);
707             value = (char *) OICMalloc(strlen(attrIterToken) + 1);
708             VARIFY_POINTER_NULL(value, result, exit)
709             VARIFY_PARAM_NULL(attrIterToken, result, exit)
710             strncpy(value, attrIterToken, strlen(attrIterToken) + 1);
711
712             if (strcmp(key, "uri") == 0)
713             {
714                 OC_LOG(INFO, TAG, "Build OCAction Instance.");
715
716                 action = (OCAction*) OICMalloc(sizeof(OCAction));
717                 VARIFY_POINTER_NULL(action, result, exit)
718                 memset(action, 0, sizeof(OCAction));
719                 action->resourceUri = (char *) OICMalloc(strlen(value) + 1);
720                 VARIFY_POINTER_NULL(action->resourceUri, result, exit)
721                 VARIFY_PARAM_NULL(value, result, exit)
722                 strncpy(action->resourceUri, value, strlen(value) + 1);
723             }
724             else
725             {
726                 if ((key != NULL) && (value != NULL))
727                 {
728                     OC_LOG(INFO, TAG, "Build OCCapability Instance.");
729
730                     capa = (OCCapability*) OICMalloc(sizeof(OCCapability));
731                     VARIFY_POINTER_NULL(capa, result, exit)
732                     memset(capa, 0, sizeof(OCCapability));
733
734                     capa->capability = (char *) OICMalloc(strlen(key) + 1);
735                     VARIFY_POINTER_NULL(capa->capability, result, exit)
736                     VARIFY_PARAM_NULL(key, result, exit)
737                     strncpy(capa->capability, key, strlen(key) + 1);
738
739                     capa->status = (char *) OICMalloc(strlen(value) + 1);
740                     VARIFY_POINTER_NULL(capa->status, result, exit)
741                     VARIFY_PARAM_NULL(value, result, exit)
742                     strncpy(capa->status, value, strlen(value) + 1);
743
744                     VARIFY_POINTER_NULL(action, result, exit)
745
746                     AddCapability(&action->head, capa);
747                 }
748             }
749
750             OCFREE(key)
751             OCFREE(value)
752             OCFREE(attr)
753
754             descIterToken = (char *) strtok_r(NULL, ATTR_DELIMITER,
755                     &descIterTokenPtr);
756         }
757
758         AddAction(&(*set)->head, action);
759         iterToken = (char *) strtok_r(NULL, ACTION_DELIMITER, &iterTokenPtr);
760         OCFREE(desc);
761     }
762
763     return OC_STACK_OK;
764 exit:
765     OCFREE(attr)
766     OCFREE(desc)
767     OCFREE(capa)
768     OCFREE(action)
769     OCFREE(*set)
770     OCFREE(key)
771     OCFREE(value)
772     OCFREE(attr)
773
774     return result;
775 }
776
777 OCStackResult BuildStringFromActionSet(OCActionSet* actionset, char** desc)
778 {
779     // Can't use the macros here as they are hardcoded to 'exit' and will
780     // result in dereferencing a null pointer.
781     if (!actionset || !desc)
782     {
783         return OC_STACK_INVALID_PARAM;
784     }
785     char temp[1024] = { 0 };
786     size_t remaining = sizeof(temp) - 1;
787     OCStackResult res = OC_STACK_ERROR;
788
789     OCAction *action = actionset->head;
790
791     if (remaining >= strlen(actionset->actionsetName) + 1)
792     {
793         strcat(temp, actionset->actionsetName);
794         remaining -= strlen(actionset->actionsetName);
795         strcat(temp, ACTION_DELIMITER);
796         remaining--;
797     }
798     else
799     {
800         res = OC_STACK_ERROR;
801         goto exit;
802     }
803
804     while (action != NULL)
805     {
806         if (remaining < (strlen("uri=") + strlen(action->resourceUri) + 1))
807         {
808             res = OC_STACK_ERROR;
809             goto exit;
810         }
811         strcat(temp, "uri=");
812         remaining -= strlen("uri=");
813         strcat(temp, action->resourceUri);
814         remaining -= strlen(action->resourceUri);
815         strcat(temp, "|");
816         remaining--;
817
818         OCCapability *capas = action->head;
819         while (capas != NULL)
820         {
821             if (remaining < (strlen(capas->capability)
822                              + 1 + strlen(capas->status)))
823             {
824                 res = OC_STACK_ERROR;
825                 goto exit;
826             }
827
828             strcat(temp, capas->capability);
829             remaining -= strlen(capas->capability);
830             strcat(temp, "=");
831             remaining--;
832             strcat(temp, capas->status);
833             remaining -= strlen(capas->status);
834
835             capas = capas->next;
836             if (capas != NULL)
837             {
838                 if (remaining < 1)
839                 {
840                     res = OC_STACK_ERROR;
841                     goto exit;
842                 }
843                 strcat(temp, "|");
844             }
845         }
846
847         action = action->next;
848         if (action != NULL)
849         {
850             if (remaining < strlen(ACTION_DELIMITER))
851             {
852                 res = OC_STACK_ERROR;
853                 goto exit;
854             }
855             strcat(temp, ACTION_DELIMITER);
856             remaining--;
857         }
858     }
859
860     *desc = OICStrdup(temp);
861     VARIFY_POINTER_NULL(*desc, res, exit);
862
863     return OC_STACK_OK;
864
865 exit:
866     OCFREE(*desc);
867     return res;
868 }
869
870 OCStackApplicationResult ActionSetCB(void* context, OCDoHandle handle,
871         OCClientResponse* clientResponse)
872 {
873     (void)context;
874     (void)clientResponse;
875     OC_LOG(INFO, TAG, "Entering ActionSetCB");
876
877     ClientRequestInfo *info = GetClientRequestInfo(clientRequstList, handle);
878
879     if (info)
880     {
881         OCEntityHandlerResponse response = { 0 };
882
883         response.ehResult = OC_EH_OK;
884
885         if(NULL == clientResponse->payload)
886         {
887             OC_LOG(ERROR, TAG, "Error sending response");
888             return OC_STACK_DELETE_TRANSACTION;
889         }
890
891         // Format the response.  Note this requires some info about the request
892         response.requestHandle = info->ehRequest;
893         response.resourceHandle = info->collResource;
894         response.payload = clientResponse->payload;
895         response.numSendVendorSpecificHeaderOptions = 0;
896         memset(response.sendVendorSpecificHeaderOptions, 0,
897                 sizeof response.sendVendorSpecificHeaderOptions);
898         memset(response.resourceUri, 0, sizeof response.resourceUri);
899         // Indicate that response is NOT in a persistent buffer
900         response.persistentBufferFlag = 0;
901
902         // Send the response
903         if (OCDoResponse(&response) != OC_STACK_OK)
904         {
905             OC_LOG(ERROR, TAG, "Error sending response");
906             return OC_STACK_DELETE_TRANSACTION;
907         }
908
909         RemoveClientRequestInfo(&clientRequstList, info);
910         OCFREE(info)
911     }
912
913     return OC_STACK_KEEP_TRANSACTION;
914 }
915
916 void ActionSetCD(void *context)
917 {
918     (void)context;
919 }
920
921 OCStackResult BuildActionJSON(OCAction* action, unsigned char* bufferPtr,
922         uint16_t *remaining)
923 {
924     OCStackResult ret = OC_STACK_ERROR;
925     cJSON *json;
926     cJSON *body;
927
928     char *jsonStr;
929     uint16_t jsonLen;
930
931     OC_LOG(INFO, TAG, "Entering BuildActionJSON");
932     json = cJSON_CreateObject();
933
934     cJSON_AddItemToObject(json, "rep", body = cJSON_CreateObject());
935
936     OCCapability* pointerCapa = action->head;
937     while (pointerCapa)
938     {
939         cJSON_AddStringToObject(body, pointerCapa->capability,
940                 pointerCapa->status);
941         pointerCapa = pointerCapa->next;
942     }
943
944     jsonStr = cJSON_PrintUnformatted(json);
945
946     jsonLen = strlen(jsonStr);
947     if (jsonLen < *remaining)
948     {
949         strcat((char*) bufferPtr, jsonStr);
950         *remaining -= jsonLen;
951         bufferPtr += jsonLen;
952         ret = OC_STACK_OK;
953     }
954
955     cJSON_Delete(json);
956     free(jsonStr);
957
958     return ret;
959 }
960
961 OCPayload* BuildActionCBOR(OCAction* action)
962 {
963     OCRepPayload* payload = OCRepPayloadCreate();
964
965     if (!payload)
966     {
967         OC_LOG(INFO, TAG, "Failed to create put payload object");
968         return NULL;
969     }
970
971     OCCapability* pointerCapa = action->head;
972     while (pointerCapa)
973     {
974         OCRepPayloadSetPropString(payload, pointerCapa->capability, pointerCapa->status);
975         pointerCapa = pointerCapa->next;
976     }
977
978     return (OCPayload*) payload;
979 }
980
981 unsigned int GetNumOfTargetResource(OCAction *actionset)
982 {
983     int numOfResource = 0;
984
985     OCAction *pointerAction = actionset;
986
987     while (pointerAction != NULL)
988     {
989         numOfResource++;
990         pointerAction = pointerAction->next;
991     }
992
993     return numOfResource;
994 }
995
996 OCStackResult SendAction(OCDoHandle *handle, OCServerRequest* requestHandle, const char *targetUri,
997         OCPayload *payload)
998 {
999
1000     OCCallbackData cbData;
1001     cbData.cb = &ActionSetCB;
1002     cbData.context = (void*)DEFAULT_CONTEXT_VALUE;
1003     cbData.cd = NULL;
1004
1005     return OCDoResource(handle, OC_REST_PUT, targetUri, &requestHandle->devAddr,
1006                        payload, CT_ADAPTER_IP, OC_NA_QOS, &cbData, NULL, 0);
1007 }
1008
1009 OCStackResult DoAction(OCResource* resource, OCActionSet* actionset,
1010         OCServerRequest* requestHandle)
1011 {
1012     OCStackResult result = OC_STACK_ERROR;
1013
1014     if( NULL == actionset->head)
1015     {
1016         return result;
1017     }
1018
1019     OCAction *pointerAction = actionset->head;
1020
1021     while (pointerAction != NULL)
1022     {
1023         OCPayload* payload;
1024         payload = BuildActionCBOR(pointerAction);
1025
1026         if(payload == NULL)
1027         {
1028             return result;
1029         }
1030
1031         ClientRequestInfo *info = (ClientRequestInfo *) OICMalloc(
1032                 sizeof(ClientRequestInfo));
1033
1034         if( info == NULL )
1035         {
1036             OCFREE(payload);
1037             return OC_STACK_NO_MEMORY;
1038         }
1039
1040         memset(info, 0, sizeof(ClientRequestInfo));
1041
1042         info->collResource = resource;
1043         info->ehRequest = requestHandle;
1044
1045         result = SendAction(&info->required, info->ehRequest, pointerAction->resourceUri,
1046                 payload);
1047
1048         if (result != OC_STACK_OK)
1049         {
1050             OICFree(info);
1051             return result;
1052         }
1053
1054         AddClientRequestInfo(&clientRequstList, info);
1055
1056         pointerAction = pointerAction->next;
1057     }
1058
1059     return result;
1060 }
1061
1062 void DoScheduledGroupAction()
1063 {
1064     OC_LOG(INFO, TAG, "DoScheduledGroupAction Entering...");
1065     ScheduledResourceInfo* info = GetScheduledResource(scheduleResourceList);
1066
1067     if (info == NULL)
1068     {
1069         OC_LOG(INFO, TAG, "Target resource is NULL");
1070         goto exit;
1071     }
1072     else if (info->resource == NULL)
1073     {
1074         OC_LOG(INFO, TAG, "Target resource is NULL");
1075         goto exit;
1076     }
1077     else if (info->actionset == NULL)
1078     {
1079         OC_LOG(INFO, TAG, "Target ActionSet is NULL");
1080         goto exit;
1081     }
1082     else if (info->ehRequest == NULL)
1083     {
1084         OC_LOG(INFO, TAG, "Target ActionSet is NULL");
1085         goto exit;
1086     }
1087 #ifndef WITH_ARDUINO
1088     pthread_mutex_lock(&lock);
1089 #endif
1090     DoAction(info->resource, info->actionset, info->ehRequest);
1091 #ifndef WITH_ARDUINO
1092     pthread_mutex_unlock(&lock);
1093 #endif
1094
1095     if (info->actionset->type == RECURSIVE)
1096     {
1097         ScheduledResourceInfo *schedule;
1098         schedule = (ScheduledResourceInfo *) OICMalloc(
1099                 sizeof(ScheduledResourceInfo));
1100
1101         if (schedule)
1102         {
1103             OC_LOG(INFO, TAG, "Building New Call Info.");
1104             memset(schedule, 0, sizeof(ScheduledResourceInfo));
1105
1106             if (info->actionset->timesteps > 0)
1107             {
1108 #ifndef WITH_ARDUINO
1109                 pthread_mutex_lock(&lock);
1110 #endif
1111                 schedule->resource = info->resource;
1112                 schedule->actionset = info->actionset;
1113                 schedule->ehRequest = info->ehRequest;
1114
1115                 schedule->time = registerTimer(info->actionset->timesteps,
1116                         &schedule->timer_id,
1117                         &DoScheduledGroupAction);
1118
1119                 OC_LOG(INFO, TAG, "Reregisteration.");
1120 #ifndef WITH_ARDUINO
1121                 pthread_mutex_unlock(&lock);
1122 #endif
1123                 AddScheduledResource(&scheduleResourceList, schedule);
1124             }
1125             else
1126             {
1127                 OICFree(schedule);
1128             }
1129         }
1130     }
1131
1132     RemoveScheduledResource(&scheduleResourceList, info);
1133
1134     exit:
1135
1136     return;
1137 }
1138
1139 OCStackResult BuildCollectionGroupActionCBORResponse(
1140         OCMethod method/*OCEntityHandlerFlag flag*/, OCResource *resource,
1141         OCEntityHandlerRequest *ehRequest)
1142 {
1143     OCStackResult stackRet = OC_STACK_ERROR;
1144
1145     OC_LOG(INFO, TAG, "Group Action is requested.");
1146
1147     char *doWhat = NULL;
1148     char *details = NULL;
1149
1150     stackRet = ExtractKeyValueFromRequest(ehRequest, &doWhat, &details);
1151
1152     if(stackRet != OC_STACK_OK)
1153     {
1154         OC_LOG_V(ERROR, TAG, "ExtractKeyValueFromRequest failed: %d", stackRet);
1155         return stackRet;
1156     }
1157
1158     stackRet = OC_STACK_ERROR;
1159
1160     if (method == OC_REST_PUT)
1161     {
1162         OC_LOG(INFO, TAG, "Group Action[PUT].");
1163
1164         if (strcmp(doWhat, ACTIONSET) == 0)
1165         {
1166             OCActionSet *actionSet = NULL;
1167             stackRet = BuildActionSetFromString(&actionSet, details);
1168
1169             if(stackRet == OC_STACK_OK)
1170             {
1171                 if (actionSet != NULL)
1172                 {
1173                     stackRet = AddActionSet(&resource->actionsetHead,
1174                             actionSet);
1175                     if (stackRet == OC_STACK_ERROR)
1176                     {
1177                         if(actionSet != NULL)
1178                         {
1179                             DeleteActionSet( &actionSet );
1180                         }
1181                         OC_LOG(INFO, TAG, "Duplicated ActionSet ");
1182                     }
1183                 }
1184                 else
1185                 {
1186                     stackRet = OC_STACK_ERROR;
1187                     goto exit;
1188                 }
1189             }
1190             else
1191             {
1192                 stackRet = OC_STACK_ERROR;
1193             }
1194
1195         }
1196         else if (strcmp(doWhat, DELETE_ACTIONSET) == 0)
1197         {
1198             if (FindAndDeleteActionSet(&resource, details) == OC_STACK_OK)
1199             {
1200                 stackRet = OC_STACK_OK;
1201             }
1202             else
1203             {
1204                 stackRet = OC_STACK_ERROR;
1205             }
1206         }
1207
1208         OCRepPayload* payload = OCRepPayloadCreate();
1209
1210         if(!payload)
1211         {
1212             OC_LOG(ERROR, TAG, "Failed to allocate Payload");
1213             stackRet = OC_STACK_ERROR;
1214         }
1215         else
1216         {
1217             OCEntityHandlerResponse response = { 0 };
1218
1219             if(stackRet == OC_STACK_OK)
1220                 response.ehResult = OC_EH_OK;
1221             else
1222                 response.ehResult = OC_EH_ERROR;
1223
1224             // Format the response.  Note this requires some info about the request
1225             response.requestHandle = ehRequest->requestHandle;
1226             response.resourceHandle = ehRequest->resource;
1227             response.payload = (OCPayload*) payload;
1228             response.numSendVendorSpecificHeaderOptions = 0;
1229             memset(response.sendVendorSpecificHeaderOptions, 0,
1230                     sizeof response.sendVendorSpecificHeaderOptions);
1231             memset(response.resourceUri, 0, sizeof response. resourceUri);
1232             // Indicate that response is NOT in a persistent buffer
1233             response.persistentBufferFlag = 0;
1234             response.ehResult = (stackRet == OC_STACK_OK)?OC_EH_OK:OC_EH_ERROR;
1235
1236             // Send the response
1237             if (OCDoResponse(&response) != OC_STACK_OK)
1238             {
1239                 OC_LOG(ERROR, TAG, "Error sending response");
1240                 stackRet = OC_STACK_ERROR;
1241             }
1242         }
1243     }
1244     else if (method == OC_REST_POST)
1245     {
1246         OCActionSet *actionset = NULL;
1247
1248         OCRepPayload* payload = OCRepPayloadCreate();
1249         OCRepPayloadSetUri(payload, resource->uri);
1250
1251         if ((strcmp(doWhat, DO_ACTION) == 0)
1252                 || (strcmp(doWhat, "DoScheduledAction") == 0))
1253         {
1254             char *pActionsetName = NULL;
1255             long int delay = -1;
1256
1257             if (strcmp(doWhat, "DoScheduledAction") == 0)
1258             {
1259                 stackRet = ExtractActionSetNameAndDelaytime(details,
1260                         &pActionsetName, &delay);
1261
1262                 OCFREE(details)
1263                 details = pActionsetName;
1264             }
1265             else
1266             {
1267                 stackRet = OC_STACK_OK;
1268             }
1269
1270             if (stackRet == OC_STACK_OK)
1271             {
1272                 if (GetActionSet(details, resource->actionsetHead,
1273                         &actionset) != OC_STACK_OK)
1274                 {
1275                     OC_LOG(INFO, TAG, "ERROR");
1276                     stackRet = OC_STACK_ERROR;
1277                 }
1278
1279                 if (actionset == NULL)
1280                 {
1281                     OC_LOG(INFO, TAG, "Cannot Find ActionSet");
1282                     stackRet = OC_STACK_ERROR;
1283                 }
1284                 else
1285                 {
1286                     OC_LOG(INFO, TAG, "Group Action[POST].");
1287                     if (actionset->type == NONE)
1288                     {
1289                         OC_LOG_V(INFO, TAG, "Execute ActionSet : %s",
1290                                 actionset->actionsetName);
1291                         unsigned int num = GetNumOfTargetResource(
1292                                 actionset->head);
1293
1294                         ((OCServerRequest *) ehRequest->requestHandle)->ehResponseHandler =
1295                                 HandleAggregateResponse;
1296                         ((OCServerRequest *) ehRequest->requestHandle)->numResponses =
1297                                 num + 1;
1298
1299                         DoAction(resource, actionset,
1300                                 (OCServerRequest*) ehRequest->requestHandle);
1301                         stackRet = OC_STACK_OK;
1302                     }
1303                     else
1304                     {
1305                         OC_LOG_V(INFO, TAG, "Execute Scheduled ActionSet : %s",
1306                                 actionset->actionsetName);
1307
1308                         delay =
1309                                 (delay == -1 ? actionset->timesteps : delay);
1310
1311                         ScheduledResourceInfo *schedule;
1312                         schedule = (ScheduledResourceInfo *) OICMalloc(
1313                                 sizeof(ScheduledResourceInfo));
1314
1315                         if (schedule)
1316                         {
1317                             OC_LOG(INFO, TAG, "Building New Call Info.");
1318                             memset(schedule, 0,
1319                                     sizeof(ScheduledResourceInfo));
1320 #ifndef WITH_ARDUINO
1321                             pthread_mutex_lock(&lock);
1322 #endif
1323                             schedule->resource = resource;
1324                             schedule->actionset = actionset;
1325                             schedule->ehRequest =
1326                                     (OCServerRequest*) ehRequest->requestHandle;
1327 #ifndef WITH_ARDUINO
1328                             pthread_mutex_unlock(&lock);
1329 #endif
1330                             if (delay > 0)
1331                             {
1332                                 OC_LOG_V(INFO, TAG, "delay_time is %ld seconds.",
1333                                         actionset->timesteps);
1334 #ifndef WITH_ARDUINO
1335                                 pthread_mutex_lock(&lock);
1336 #endif
1337                                 schedule->time = registerTimer(delay,
1338                                         &schedule->timer_id,
1339                                         &DoScheduledGroupAction);
1340 #ifndef WITH_ARDUINO
1341                                 pthread_mutex_unlock(&lock);
1342 #endif
1343                                 AddScheduledResource(&scheduleResourceList,
1344                                         schedule);
1345                                 stackRet = OC_STACK_OK;
1346                             }
1347                             else
1348                             {
1349                                 stackRet = OC_STACK_ERROR;
1350                             }
1351                         }
1352                     }
1353                 }
1354             }
1355         }
1356         else if (strcmp(doWhat, "CancelAction") == 0)
1357         {
1358             ScheduledResourceInfo *info =
1359                     GetScheduledResourceByActionSetName(scheduleResourceList, details);
1360
1361             if(info != NULL)
1362             {
1363                 unregisterTimer(info->timer_id);
1364
1365                 RemoveScheduledResource(&scheduleResourceList, info);
1366                 stackRet = OC_STACK_OK;
1367             }
1368             else
1369             {
1370                 stackRet = OC_STACK_ERROR;
1371             }
1372         }
1373
1374         else if (strcmp(doWhat, GET_ACTIONSET) == 0)
1375         {
1376             char *plainText = NULL;
1377             OCActionSet *actionset = NULL;
1378
1379             GetActionSet(details, resource->actionsetHead, &actionset);
1380             if (actionset != NULL)
1381             {
1382                 BuildStringFromActionSet(actionset, &plainText);
1383
1384                 if (plainText != NULL)
1385                 {
1386                     OCRepPayloadSetPropString(payload, ACTIONSET, plainText);
1387                 }
1388                 OICFree(plainText);
1389                 stackRet = OC_STACK_OK;
1390             }
1391         }
1392
1393         if(!payload)
1394         {
1395             OC_LOG(ERROR, TAG, "Failed to allocate Payload");
1396             stackRet = OC_STACK_ERROR;
1397         }
1398         else
1399         {
1400             OCEntityHandlerResponse response = { 0 };
1401             if(stackRet == OC_STACK_OK)
1402                 response.ehResult = OC_EH_OK;
1403             else
1404                 response.ehResult = OC_EH_ERROR;
1405
1406             // Format the response.  Note this requires some info about the request
1407             response.requestHandle = ehRequest->requestHandle;
1408             response.resourceHandle = ehRequest->resource;
1409             response.payload = (OCPayload*) payload;
1410             response.numSendVendorSpecificHeaderOptions = 0;
1411             memset(response.sendVendorSpecificHeaderOptions, 0,
1412                     sizeof response.sendVendorSpecificHeaderOptions);
1413             memset(response.resourceUri, 0, sizeof response.resourceUri);
1414             // Indicate that response is NOT in a persistent buffer
1415             response.persistentBufferFlag = 0;
1416             response.ehResult = (stackRet == OC_STACK_OK)?OC_EH_OK:OC_EH_ERROR;
1417
1418             // Send the response
1419             if (OCDoResponse(&response) != OC_STACK_OK)
1420             {
1421                 OC_LOG(ERROR, TAG, "Error sending response");
1422                 stackRet = OC_STACK_ERROR;
1423             }
1424         }
1425     }
1426
1427 exit:
1428
1429     OCFREE(doWhat)
1430     OCFREE(details)
1431
1432     return stackRet;
1433 }