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