Merge branch 'master' into simulator
[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     OC_LOG(INFO, TAG, PCF("Entering BuildActionJSON"));
803
804     ClientRequestInfo *info = GetClientRequestInfo(clientRequstList, handle);
805
806     if (info)
807     {
808         int idx;
809
810         unsigned char *responseJson = NULL;
811         // TODO: Figure out what this does, change implementation
812         //responseJson = (unsigned char *) OICMalloc(
813         //        (unsigned int) (strlen((char *) clientResponse->resJSONPayload)
814         //                + 1));
815
816         if( responseJson == NULL )
817             return OC_STACK_DELETE_TRANSACTION;
818
819         // We need the body of response.
820         // Copy the body from the response
821         // TODO: Taken out
822         //strcpy((char *) responseJson,
823         //        ((char *) clientResponse->resJSONPayload + OC_JSON_PREFIX_LEN));
824         //idx = strlen((char *) responseJson) - OC_JSON_SUFFIX_LEN;
825         // And insert NULL at the end of body.
826         (responseJson[idx]) = 0;
827
828         OCEntityHandlerResponse response = { 0 };
829         response.ehResult = OC_EH_OK;
830         // TODO: Removing payload size, waht goes here?
831         // response.payload = (char*)responseJson;
832         //response.payloadSize = (unsigned int) strlen((char *) responseJson) + 1;
833         response.persistentBufferFlag = 0;
834         response.requestHandle = (OCRequestHandle) info->ehRequest;
835         response.resourceHandle = (OCResourceHandle) info->collResource;
836
837         OCDoResponse(&response);
838
839         RemoveClientRequestInfo(&clientRequstList, info);
840         OCFREE(info)
841         OCFREE(responseJson)
842     }
843
844     return OC_STACK_KEEP_TRANSACTION;
845 }
846
847 void ActionSetCD(void *context)
848 {
849 }
850
851 OCStackResult BuildActionJSON(OCAction* action, unsigned char* bufferPtr,
852         uint16_t *remaining)
853 {
854     OCStackResult ret = OC_STACK_ERROR;
855     cJSON *json;
856     cJSON *body;
857
858     char *jsonStr;
859     uint16_t jsonLen;
860
861     OC_LOG(INFO, TAG, PCF("Entering BuildActionJSON"));
862     json = cJSON_CreateObject();
863
864     cJSON_AddItemToObject(json, "rep", body = cJSON_CreateObject());
865
866     OCCapability* pointerCapa = action->head;
867     while (pointerCapa)
868     {
869         cJSON_AddStringToObject(body, pointerCapa->capability,
870                 pointerCapa->status);
871         pointerCapa = pointerCapa->next;
872     }
873
874     jsonStr = cJSON_PrintUnformatted(json);
875
876     jsonLen = strlen(jsonStr);
877     if (jsonLen < *remaining)
878     {
879         strcat((char*) bufferPtr, jsonStr);
880         *remaining -= jsonLen;
881         bufferPtr += jsonLen;
882         ret = OC_STACK_OK;
883     }
884
885     cJSON_Delete(json);
886     free(jsonStr);
887
888     return ret;
889 }
890
891 unsigned int GetNumOfTargetResource(OCAction *actionset)
892 {
893     int numOfResource = 0;
894
895     OCAction *pointerAction = actionset;
896
897     while (pointerAction != NULL)
898     {
899         numOfResource++;
900         pointerAction = pointerAction->next;
901     }
902
903     return numOfResource;
904 }
905
906
907 #define DEFAULT_CONTEXT_VALUE 0x99
908
909 OCStackResult SendAction(OCDoHandle *handle, const char *targetUri,
910         const unsigned char *action)
911 {
912     // TODO: disabled since this is no longer compatible
913     return OC_STACK_NOTIMPL;
914 }
915
916 OCStackResult DoAction(OCResource* resource, OCActionSet* actionset,
917         OCServerRequest* requestHandle)
918 {
919     OCStackResult result = OC_STACK_ERROR;
920     OCAction *pointerAction = actionset->head;
921
922     while (pointerAction != NULL)
923     {
924         unsigned char actionDesc[MAX_RESPONSE_LENGTH] = { 0 };
925         unsigned char* actionDescPtr = actionDesc;
926         uint16_t remaining = MAX_RESPONSE_LENGTH;
927
928         strncpy((char *) actionDescPtr, (const char *) OC_JSON_PREFIX,
929                 strlen((const char *) OC_JSON_PREFIX) + 1);
930         BuildActionJSON(pointerAction, actionDescPtr, &remaining);
931         strncat((char *) actionDescPtr, (const char *) OC_JSON_SUFFIX,
932                 strlen((const char *) OC_JSON_SUFFIX));
933
934         ClientRequestInfo *info = (ClientRequestInfo *) OICMalloc(
935                 sizeof(ClientRequestInfo));
936
937         if( info == NULL )
938             return OC_STACK_NO_MEMORY;
939
940         memset(info, 0, sizeof(ClientRequestInfo));
941
942         info->collResource = resource;
943         info->ehRequest = requestHandle;
944
945         result = SendAction(&info->required, pointerAction->resourceUri,
946                 actionDescPtr);
947         if (result != OC_STACK_OK)
948         {
949             OICFree(info);
950             return result;
951         }
952
953         AddClientRequestInfo(&clientRequstList, info);
954
955         pointerAction = pointerAction->next;
956     }
957
958     return result;
959 }
960
961 void DoScheduledGroupAction()
962 {
963     OC_LOG(INFO, TAG, PCF("DoScheduledGroupAction Entering..."));
964     ScheduledResourceInfo* info = GetScheduledResource(scheduleResourceList);
965
966     if (info == NULL)
967     {
968         OC_LOG(INFO, TAG, PCF("Target resource is NULL"));
969         goto exit;
970     }
971     else if (info->resource == NULL)
972     {
973         OC_LOG(INFO, TAG, PCF("Target resource is NULL"));
974         goto exit;
975     }
976     else if (info->actionset == NULL)
977     {
978         OC_LOG(INFO, TAG, PCF("Target ActionSet is NULL"));
979         goto exit;
980     }
981     else if (info->ehRequest == NULL)
982     {
983         OC_LOG(INFO, TAG, PCF("Target ActionSet is NULL"));
984         goto exit;
985     }
986 #ifndef WITH_ARDUINO
987     pthread_mutex_lock(&lock);
988 #endif
989     DoAction(info->resource, info->actionset, info->ehRequest);
990 #ifndef WITH_ARDUINO
991     pthread_mutex_unlock(&lock);
992 #endif
993
994     if (info->actionset->type == RECURSIVE)
995     {
996         ScheduledResourceInfo *schedule;
997         schedule = (ScheduledResourceInfo *) OICMalloc(
998                 sizeof(ScheduledResourceInfo));
999
1000         if (schedule)
1001         {
1002             OC_LOG(INFO, TAG, PCF("Building New Call Info."));
1003             memset(schedule, 0, sizeof(ScheduledResourceInfo));
1004
1005             if (info->actionset->timesteps > 0)
1006             {
1007 #ifndef WITH_ARDUINO
1008                 pthread_mutex_lock(&lock);
1009 #endif
1010                 schedule->resource = info->resource;
1011                 schedule->actionset = info->actionset;
1012                 schedule->ehRequest = info->ehRequest;
1013
1014                 schedule->time = registerTimer(info->actionset->timesteps,
1015                         &schedule->timer_id,
1016                         &DoScheduledGroupAction);
1017
1018                 OC_LOG(INFO, TAG, PCF("Reregisteration."));
1019 #ifndef WITH_ARDUINO
1020                 pthread_mutex_unlock(&lock);
1021 #endif
1022                 AddScheduledResource(&scheduleResourceList, schedule);
1023             }
1024             else
1025             {
1026                 OICFree(schedule);
1027             }
1028         }
1029     }
1030
1031     RemoveScheduledResource(&scheduleResourceList, info);
1032
1033     exit:
1034
1035     return;
1036 }
1037
1038 OCStackResult BuildCollectionGroupActionJSONResponse(
1039         OCMethod method/*OCEntityHandlerFlag flag*/, OCResource *resource,
1040         OCEntityHandlerRequest *ehRequest)
1041 {
1042     OCStackResult stackRet = OC_STACK_ERROR;
1043
1044     OC_LOG(INFO, TAG, PCF("Group Action is requested."));
1045     // if (stackRet == OC_STACK_OK)
1046     {
1047         char *doWhat = NULL;
1048         char *details = NULL;
1049
1050         size_t bufferLength = 0;
1051         unsigned char buffer[MAX_RESPONSE_LENGTH] = { 0 };
1052
1053         OCResource * collResource = (OCResource *) ehRequest->resource;
1054
1055         char *jsonResponse;
1056
1057         stackRet = OC_STACK_NOTIMPL;
1058         // TODO: Fix?
1059         //stackRet = ExtractKeyValueFromRequest((char *) ehRequest->reqJSONPayload,
1060         //        &doWhat, &details);
1061
1062         if(stackRet != OC_STACK_OK)
1063         {
1064             OC_LOG_V(ERROR, TAG, "ExtractKeyValueFromRequest failed: %d", stackRet);
1065             return stackRet;
1066         }
1067
1068         stackRet = OC_STACK_ERROR;
1069
1070         cJSON *json;
1071         cJSON *format;
1072
1073         if (method == OC_REST_PUT)
1074         {
1075             json = cJSON_CreateObject();
1076             cJSON_AddStringToObject(json, "href", resource->uri);
1077             cJSON_AddItemToObject(json, "rep", format = cJSON_CreateObject());
1078
1079             OC_LOG(INFO, TAG, PCF("Group Action[PUT]."));
1080
1081             if (strcmp(doWhat, ACTIONSET) == 0)
1082             {
1083                 OCActionSet *actionSet = NULL;
1084                 stackRet = BuildActionSetFromString(&actionSet, details);
1085
1086                 if(stackRet == OC_STACK_OK)
1087                 {
1088                     if (actionSet != NULL)
1089                     {
1090                         stackRet = AddActionSet(&resource->actionsetHead,
1091                                 actionSet);
1092                         if (stackRet == OC_STACK_ERROR)
1093                         {
1094                             if(actionSet != NULL)
1095                             {
1096                                 DeleteActionSet( &actionSet );
1097                             }
1098                             OC_LOG(INFO, TAG, PCF("Duplicated ActionSet "));
1099                         }
1100                     }
1101                 }
1102                 else
1103                 {
1104                     stackRet = OC_STACK_ERROR;
1105                 }
1106
1107             }
1108             else if (strcmp(doWhat, DELETE_ACTIONSET) == 0)
1109             {
1110                 if (FindAndDeleteActionSet(&resource, details) == OC_STACK_OK)
1111                 {
1112                     stackRet = OC_STACK_OK;
1113                 }
1114                 else
1115                 {
1116                     stackRet = OC_STACK_ERROR;
1117                 }
1118             }
1119
1120             jsonResponse = cJSON_Print(json);
1121             cJSON_Delete(json);
1122
1123             OICStrcat((char*)buffer, sizeof(buffer), jsonResponse);
1124
1125             bufferLength = strlen((const char *) buffer);
1126             if (bufferLength > 0)
1127             {
1128                 OCEntityHandlerResponse response = { 0 };
1129                 if(stackRet == OC_STACK_OK)
1130                     response.ehResult = OC_EH_OK;
1131                 else
1132                     response.ehResult = OC_EH_ERROR;
1133                 // TODO: Fix
1134                 //response.payload = (char*)buffer;
1135                 //response.payloadSize = bufferLength + 1;
1136                 response.persistentBufferFlag = 0;
1137                 response.requestHandle =
1138                         (OCRequestHandle) ehRequest->requestHandle;
1139                 response.resourceHandle = (OCResourceHandle) collResource;
1140                 stackRet = OCDoResponse(&response);
1141             }
1142         }
1143
1144         if (method == OC_REST_POST)
1145         {
1146             OCActionSet *actionset = NULL;
1147
1148             json = cJSON_CreateObject();
1149             cJSON_AddStringToObject(json, "href", resource->uri);
1150
1151             if ((strcmp(doWhat, DO_ACTION) == 0)
1152                     || (strcmp(doWhat, "DoScheduledAction") == 0))
1153             {
1154                 char *pActionsetName = NULL;
1155                 long int delay = -1;
1156
1157                 if (strcmp(doWhat, "DoScheduledAction") == 0)
1158                 {
1159                     stackRet = ExtractActionSetNameAndDelaytime(details,
1160                             &pActionsetName, &delay);
1161
1162                     OCFREE(details)
1163                     details = pActionsetName;
1164                 }
1165                 else
1166                 {
1167                     stackRet = OC_STACK_OK;
1168                 }
1169
1170                 if (stackRet == OC_STACK_OK)
1171                 {
1172                     if (GetActionSet(details, resource->actionsetHead,
1173                             &actionset) != OC_STACK_OK)
1174                     {
1175                         OC_LOG(INFO, TAG, PCF("ERROR"));
1176                         stackRet = OC_STACK_ERROR;
1177                     }
1178
1179                     if (actionset == NULL)
1180                     {
1181                         OC_LOG(INFO, TAG, PCF("Cannot Find ActionSet"));
1182                         stackRet = OC_STACK_ERROR;
1183                     }
1184                     else
1185                     {
1186                         OC_LOG(INFO, TAG, PCF("Group Action[POST]."));
1187                         if (actionset->type == NONE)
1188                         {
1189                             OC_LOG_V(INFO, TAG, "Execute ActionSet : %s",
1190                                     actionset->actionsetName);
1191                             unsigned int num = GetNumOfTargetResource(
1192                                     actionset->head);
1193
1194                             ((OCServerRequest *) ehRequest->requestHandle)->ehResponseHandler =
1195                                     HandleAggregateResponse;
1196                             ((OCServerRequest *) ehRequest->requestHandle)->numResponses =
1197                                     num + 1;
1198
1199                             DoAction(resource, actionset,
1200                                     (OCServerRequest*) ehRequest->requestHandle);
1201                             stackRet = OC_STACK_OK;
1202                         }
1203                         else
1204                         {
1205                             OC_LOG_V(INFO, TAG, "Execute Scheduled ActionSet : %s",
1206                                     actionset->actionsetName);
1207
1208                             delay =
1209                                     (delay == -1 ? actionset->timesteps : delay);
1210
1211                             ScheduledResourceInfo *schedule;
1212                             schedule = (ScheduledResourceInfo *) OICMalloc(
1213                                     sizeof(ScheduledResourceInfo));
1214
1215                             if (schedule)
1216                             {
1217                                 OC_LOG(INFO, TAG, PCF("Building New Call Info."));
1218                                 memset(schedule, 0,
1219                                         sizeof(ScheduledResourceInfo));
1220
1221                                 schedule->resource = resource;
1222                                 schedule->actionset = actionset;
1223                                 schedule->ehRequest =
1224                                         (OCServerRequest*) ehRequest->requestHandle;
1225
1226                                 if (delay > 0)
1227                                 {
1228                                     OC_LOG_V(INFO, TAG, "delay_time is %lf seconds.",
1229                                             actionset->timesteps);
1230
1231                                     schedule->time = registerTimer(delay,
1232                                             &schedule->timer_id,
1233                                             &DoScheduledGroupAction);
1234
1235                                     AddScheduledResource(&scheduleResourceList,
1236                                             schedule);
1237                                     stackRet = OC_STACK_OK;
1238                                 }
1239                                 else
1240                                 {
1241                                     stackRet = OC_STACK_ERROR;
1242                                 }
1243                             }
1244                         }
1245                     }
1246                 }
1247             }
1248             else if (strcmp(doWhat, "CancelAction") == 0)
1249             {
1250                 ScheduledResourceInfo *info =
1251                         GetScheduledResourceByActionSetName(scheduleResourceList, details);
1252
1253                 if(info != NULL)
1254                 {
1255                     unregisterTimer(info->timer_id);
1256
1257                     RemoveScheduledResource(&scheduleResourceList, info);
1258                     stackRet = OC_STACK_OK;
1259                 }
1260                 else
1261                 {
1262                     stackRet = OC_STACK_ERROR;
1263                 }
1264             }
1265
1266             else if (strcmp(doWhat, GET_ACTIONSET) == 0)
1267             {
1268                 char *plainText = NULL;
1269                 OCActionSet *actionset = NULL;
1270
1271                 cJSON_AddItemToObject(json, "rep", format =
1272                         cJSON_CreateObject());
1273                 GetActionSet(details, resource->actionsetHead, &actionset);
1274                 if (actionset != NULL)
1275                 {
1276                     BuildStringFromActionSet(actionset, &plainText);
1277
1278                     if (plainText != NULL)
1279                     {
1280                         cJSON_AddStringToObject(format, ACTIONSET, plainText);
1281                     }
1282                     OICFree(plainText);
1283                     stackRet = OC_STACK_OK;
1284                 }
1285             }
1286
1287
1288             jsonResponse = cJSON_Print(json);
1289             cJSON_Delete(json);
1290
1291             OICStrcat((char*)buffer, sizeof(buffer), jsonResponse);
1292
1293             bufferLength = strlen((const char *) buffer);
1294             if (bufferLength > 0)
1295             {
1296                 OCEntityHandlerResponse response = { 0 };
1297                 if(stackRet == OC_STACK_OK)
1298                     response.ehResult = OC_EH_OK;
1299                 else
1300                     response.ehResult = OC_EH_ERROR;
1301                 // TODO: Implement
1302                 //response.payload = (char *)buffer;
1303                 //response.payloadSize = bufferLength + 1;
1304                 response.persistentBufferFlag = 0;
1305                 response.requestHandle =
1306                         (OCRequestHandle) ehRequest->requestHandle;
1307                 response.resourceHandle = (OCResourceHandle) collResource;
1308                 stackRet = OCDoResponse(&response);
1309             }
1310         }
1311
1312         OCFREE(doWhat)
1313         OCFREE(details)
1314     }
1315
1316     return stackRet;
1317 }