[FIX] daemon cannot finish
[platform/core/system/swap-manager.git] / daemon / daemon.c
1 /*
2  *  DA manager
3  *
4  * Copyright (c) 2000 - 2013 Samsung Electronics Co., Ltd. All rights reserved.
5  *
6  * Contact:
7  *
8  * Jaewon Lim <jaewon81.lim@samsung.com>
9  * Woojin Jung <woojin2.jung@samsung.com>
10  * Juyoung Kim <j0.kim@samsung.com>
11  * Cherepanov Vitaliy <v.cherepanov@samsung.com>
12  * Nikita Kalyazin    <n.kalyazin@samsung.com>
13  *
14  * Licensed under the Apache License, Version 2.0 (the "License");
15  * you may not use this file except in compliance with the License.
16  * You may obtain a copy of the License at
17  *
18  * http://www.apache.org/licenses/LICENSE-2.0
19  *
20  * Unless required by applicable law or agreed to in writing, software
21  * distributed under the License is distributed on an "AS IS" BASIS,
22  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
23  * See the License for the specific language governing permissions and
24  * limitations under the License.
25  *
26  * Contributors:
27  * - S-Core Co., Ltd
28  * - Samsung RnD Institute Russia
29  *
30  */
31 #define __STDC_FORMAT_MACROS
32 #include <stdio.h>
33 #include <stdlib.h>                     // for realpath
34 #include <string.h>                     // for strtok, strcpy, strncpy
35 #include <limits.h>                     // for realpath
36 #include <inttypes.h>
37
38 #include <errno.h>                      // for errno
39 #include <sys/types.h>          // for accept, mkdir, opendir, readdir
40 #include <sys/socket.h>         // for accept
41 #include <sys/stat.h>           // for mkdir
42 #include <sys/eventfd.h>        // for eventfd
43 #include <sys/epoll.h>          // for epoll apis
44 #include <sys/timerfd.h>        // for timerfd
45 #include <unistd.h>                     // for access, sleep
46 #include <stdbool.h>
47
48 #include <ctype.h>
49
50 #ifndef LOCALTEST
51 #include <attr/xattr.h>         // for fsetxattr
52 #include <sys/smack.h>
53 #endif
54
55 #include <linux/input.h>
56 #include <dirent.h>
57 #include <fcntl.h>
58 #include "daemon.h"
59 #include "sys_stat.h"
60 #include "utils.h"
61 #include "da_protocol.h"
62 #include "da_data.h"
63 #include "debug.h"
64 #include "process_info.h"
65
66 #define DA_WORK_DIR                             "/home/developer/sdk_tools/da/"
67 #define DA_READELF_PATH                 "/home/developer/sdk_tools/da/readelf"
68 #define SCREENSHOT_DIR                  "/tmp/da"
69
70 #define EPOLL_SIZE                              10
71 #define MAX_APP_LAUNCH_TIME             60
72 #define MAX_CONNECT_TIMEOUT_TIME        5*60
73
74 #define MAX_DEVICE                              10
75 #define MAX_FILENAME                    128
76 #define BUF_SIZE                                1024
77 #define ARRAY_END                               (-11)
78
79 input_dev g_key_dev[MAX_DEVICE];
80 input_dev g_touch_dev[MAX_DEVICE];
81
82 // return bytes size of readed data
83 // return 0 if no data readed or error occurred
84 static int _file_read(FILE* fp, char *buffer, int size)
85 {
86         int ret = 0;
87
88         if(fp != NULL && size > 0)
89         {
90                 ret = fread((void*)buffer, sizeof(char), size, fp);
91                 buffer[ret] = '\0';
92         }
93         else
94         {
95                 // fp is null
96                 if(size > 0)
97                         buffer[0] = '\0';
98
99                 ret = 0;        // error case
100         }
101
102         return ret;
103 }
104
105 // get input id of given input device
106 static int get_input_id(char* inputname)
107 {
108         static int query_cmd_type = 0;  // 1 if /lib/udev/input_id, 2 if udevadm
109         FILE* cmd_fp = NULL;
110         char buffer[BUF_SIZE];
111         char command[MAX_FILENAME];
112         int ret = -1;
113
114         // determine input_id query command
115         if(unlikely(query_cmd_type == 0))
116         {
117                 if(access("/lib/udev/input_id", F_OK) == 0)             // there is /lib/udev/input_id
118                 {
119                         query_cmd_type = 1;
120                 }
121                 else    // there is not /lib/udev/input_id
122                 {
123                         query_cmd_type = 2;
124                 }
125         }
126
127         // make command string
128         if(query_cmd_type == 1)
129         {
130                 sprintf(command, "/lib/udev/input_id /class/input/%s", inputname);
131         }
132         else
133         {
134                 sprintf(command, "udevadm info --name=input/%s --query=property", inputname);
135         }
136
137         // run command
138         cmd_fp = popen(command, "r");
139         if(_file_read(cmd_fp, buffer, BUF_SIZE) < 0)
140         {
141                 LOGE("Failed to read input_id\n");
142                 if(cmd_fp != NULL)
143                         pclose(cmd_fp);
144                 return ret;
145         }
146
147
148         // determine input id
149         if(strstr(buffer, INPUT_ID_STR_KEY))                    // key
150         {
151                 ret = INPUT_ID_KEY;
152         }
153         else if(strstr(buffer, INPUT_ID_STR_TOUCH))             // touch
154         {
155                 ret = INPUT_ID_TOUCH;
156         }
157         else if(strstr(buffer, INPUT_ID_STR_KEYBOARD))  // keyboard
158         {
159                 ret = INPUT_ID_KEY;
160         }
161         else if(strstr(buffer, INPUT_ID_STR_TABLET))    // touch (emulator)
162         {
163                 ret = INPUT_ID_TOUCH;
164         }
165
166         if(cmd_fp != NULL)
167                 pclose(cmd_fp);
168         return ret;
169 }
170
171 // get filename and fd of given input type devices
172 static void _get_fds(input_dev *dev, int input_id)
173 {
174         DIR *dp;
175         struct dirent *d;
176         int count = 0;
177
178         dp = opendir("/sys/class/input");
179
180         if(dp != NULL)
181         {
182                 while((d = readdir(dp)) != NULL)
183                 {
184                         if(!strncmp(d->d_name, "event", 5))     // start with "event"
185                         {
186                                 // event file
187                                 if(input_id == get_input_id(d->d_name))
188                                 {
189                                         sprintf(dev[count].fileName, "/dev/input/%s", d->d_name);
190                                         dev[count].fd = open(dev[count].fileName, O_RDWR | O_NONBLOCK);
191                                         count++;
192                                 }
193                         }
194                 }
195
196                 closedir(dp);
197         }
198         dev[count].fd = ARRAY_END;      // end of input_dev array
199 }
200
201 //static
202 void _device_write(input_dev *dev, struct input_event* in_ev)
203 {
204         int i;
205         for(i = 0; dev[i].fd != ARRAY_END; i++)
206         {
207                 if(dev[i].fd >= 0)
208                 {
209                         write(dev[i].fd, in_ev, sizeof(struct input_event));
210                         LOGI("write(%d, %d, %d)\n",
211                                         dev[i].fd, (int)in_ev, sizeof(struct input_event));
212                 }
213         }
214 }
215
216 long long get_total_alloc_size()
217 {
218         int i;
219         long long allocsize = 0;
220
221         for(i = 0; i < MAX_TARGET_COUNT; i++)
222         {
223                 if(manager.target[i].socket != -1 && manager.target[i].allocmem > 0)
224                         allocsize += manager.target[i].allocmem;
225         }
226         return allocsize;
227 }
228
229 static int getEmptyTargetSlot()
230 {
231         int i;
232         for(i = 0; i < MAX_TARGET_COUNT; i++)
233         {
234                 if(manager.target[i].socket == -1)
235                         break;
236         }
237
238         return i;
239 }
240
241 static void setEmptyTargetSlot(int index)
242 {
243         if(index >= 0 && index < MAX_TARGET_COUNT)
244         {
245                 manager.target[index].pid = -1;
246                 manager.target[index].recv_thread = -1;
247                 manager.target[index].allocmem = 0;
248                 manager.target[index].starttime = 0;
249                 manager.target[index].initial_log = 0;
250                 if(manager.target[index].event_fd != -1)
251                         close(manager.target[index].event_fd);
252                 manager.target[index].event_fd = -1;
253                 if(manager.target[index].socket != -1)
254                         close(manager.target[index].socket);
255                 manager.target[index].socket = -1;
256         }
257 }
258
259 // =============================================================================
260 // start and terminate control functions
261 // =============================================================================
262
263 //start application launch timer function
264 static int start_app_launch_timer()
265 {
266         int res = 0;
267         struct epoll_event ev;
268
269         manager.app_launch_timerfd = timerfd_create(CLOCK_REALTIME, TFD_CLOEXEC);
270         if(manager.app_launch_timerfd > 0)
271         {
272                 struct itimerspec ctime;
273                 ctime.it_value.tv_sec = MAX_APP_LAUNCH_TIME;
274                 ctime.it_value.tv_nsec = 0;
275                 ctime.it_interval.tv_sec = 0;
276                 ctime.it_interval.tv_nsec = 0;
277                 if (timerfd_settime(manager.app_launch_timerfd, 0, &ctime, NULL) < 0)
278                 {
279                         LOGE("fail to set app launch timer\n");
280                         close(manager.app_launch_timerfd);
281                         manager.app_launch_timerfd = -1;
282                         res = -1;
283                 }
284                 else
285                 {
286                         // add event fd to epoll list
287                         ev.events = EPOLLIN;
288                         ev.data.fd = manager.app_launch_timerfd;
289                         if (epoll_ctl(manager.efd, EPOLL_CTL_ADD,
290                                                 manager.app_launch_timerfd, &ev) < 0)
291                         {
292                                 // fail to add event fd
293                                 LOGE("fail to add app launch timer fd to epoll list\n");
294                                 close(manager.app_launch_timerfd);
295                                 manager.app_launch_timerfd = -1;
296                                 res = -2;
297                         } else {
298                                 LOGI("application launch time started\n");
299                         }
300                 }
301         } else {
302                 LOGE("cannot create launch timer\n");
303                 res = -3;
304         }
305
306         return res;
307 }
308
309 //stop application launch timer
310 static int stop_app_launch_timer()
311 {
312         if (0 > epoll_ctl(manager.efd, EPOLL_CTL_DEL,
313                           manager.app_launch_timerfd, NULL))
314                 LOGW("fail to EPOLL DEL of app launch timerfd\n");
315         close(manager.app_launch_timerfd);
316         manager.app_launch_timerfd = -1;
317         return 0;
318 }
319
320 static int exec_app(const struct app_info_t *app_info)
321 {
322         int res = 0;
323         static struct epoll_event ev;
324
325
326         switch (app_info->app_type) {
327         case APP_TYPE_TIZEN:
328                 kill_app(app_info->exe_path);
329                 if (exec_app_tizen(app_info->app_id, app_info->exe_path)) {
330                         LOGE("Cannot exec tizen app %s\n", app_info->app_id);
331                         res = -1;
332                 }
333                 break;
334         case APP_TYPE_RUNNING:
335                 // TODO: nothing, it's running
336                 LOGI("already started\n");
337                 write_process_info(atoi(app_info->app_id), 0);
338                 break;
339         case APP_TYPE_COMMON:
340                 kill_app(app_info->exe_path);
341                 if (exec_app_common(app_info->exe_path)) {
342                         LOGE("Cannot exec common app %s\n", app_info->exe_path);
343                         res = -1;
344                 }
345                 break;
346         default:
347                 LOGE("Unknown app type %d\n", app_info->app_type);
348                 res = -1;
349                 break;
350         }
351
352         if (res == 0 && app_info->app_type != APP_TYPE_RUNNING)
353                 if (start_app_launch_timer()<0)
354                         res = -1;
355
356         LOGI("ret=%d\n", res);
357         return res;
358 }
359
360 int launch_timer_start()
361 {
362         static struct epoll_event ev;
363         int res = 0;
364
365         manager.connect_timeout_timerfd = timerfd_create(CLOCK_REALTIME, TFD_CLOEXEC);
366         if(manager.connect_timeout_timerfd > 0)
367         {
368                 struct itimerspec ctime;
369                 ctime.it_value.tv_sec = MAX_CONNECT_TIMEOUT_TIME;
370                 ctime.it_value.tv_nsec = 0;
371                 ctime.it_interval.tv_sec = 0;
372                 ctime.it_interval.tv_nsec = 0;
373                 if (timerfd_settime(manager.connect_timeout_timerfd, 0, &ctime, NULL) < 0)
374                 {
375                         LOGE("fail to set connect timeout timer\n");
376                         close(manager.connect_timeout_timerfd);
377                         manager.connect_timeout_timerfd = -1;
378                 }
379                 else
380                 {
381                         // add event fd to epoll list
382                         ev.events = EPOLLIN;
383                         ev.data.fd = manager.connect_timeout_timerfd;
384                         if (epoll_ctl(manager.efd, EPOLL_CTL_ADD,
385                                                 manager.connect_timeout_timerfd, &ev) < 0)
386                         {
387                                 // fail to add event fd
388                                 LOGE("fail to add app connection timeout timer fd to epoll list\n");
389                                 close(manager.connect_timeout_timerfd);
390                                 manager.connect_timeout_timerfd = -1;
391                         } else {
392                                 LOGI("connection timeout timer started\n");
393                         }
394                 }
395         } else {
396                 LOGE("cannot create connection timeout timer\n");
397         }
398
399         LOGI("ret=%d\n", res);
400         return res;
401 }
402
403 static void epoll_add_input_events();
404 static void epoll_del_input_events();
405
406 int start_profiling()
407 {
408         const struct app_info_t *app_info = &prof_session.app_info;
409         int res = 0;
410
411         // remove previous screen capture files
412         remove_indir(SCREENSHOT_DIR);
413         if(mkdir(SCREENSHOT_DIR, 0777) < 0)
414         {
415                 LOGE("Failed to create directory for screenshot : errno(%d)\n", errno);
416         }
417
418
419 #ifndef LOCALTEST
420         smack_lsetlabel(SCREENSHOT_DIR, "*", SMACK_LABEL_ACCESS);
421 #endif
422
423         if (samplingStart() < 0) {
424                 LOGE("Cannot start sampling\n");
425                 res = -1;
426                 goto exit;
427         }
428
429         if (IS_OPT_SET(FL_RECORDING))
430                 epoll_add_input_events();
431
432         if (exec_app(app_info)) {
433                 LOGE("Cannot exec app\n");
434                 res = -1;
435                 goto recording_stop;
436         }
437
438         goto exit;
439
440 recording_stop:
441         if (IS_OPT_SET(FL_RECORDING))
442                 epoll_del_input_events();
443         samplingStop();
444
445 exit:
446         LOGI("return %d\n", res);
447         return res;
448 }
449
450 void stop_profiling(void)
451 {
452         if (IS_OPT_SET(FL_RECORDING))
453                 epoll_del_input_events();
454         samplingStop();
455 }
456
457 static void reconfigure_recording(struct conf_t conf)
458 {
459         uint64_t old_features = prof_session.conf.use_features0;
460         uint64_t new_features = conf.use_features0;
461         uint64_t to_enable = (new_features ^ old_features) & new_features;
462         uint64_t to_disable = (new_features ^ old_features) & old_features;
463
464         if (IS_OPT_SET_IN(FL_RECORDING, to_disable)) {
465                 epoll_del_input_events();
466                 prof_session.conf.use_features0 &= ~FL_RECORDING;
467         }
468
469         if (IS_OPT_SET_IN(FL_RECORDING, to_enable)) {
470                 epoll_add_input_events();
471                 prof_session.conf.use_features0 |= FL_RECORDING;
472         }
473
474 }
475
476 int reconfigure(struct conf_t conf)
477 {
478         reconfigure_recording(conf);
479
480         samplingStop();
481         memcpy(&prof_session.conf, &conf, sizeof(conf));
482         if (samplingStart() < 0) {
483                 LOGE("Cannot start sampling\n");
484                 return -1;
485         }
486
487         return 0;
488 }
489
490 // just send stop message to all target process
491 static void terminate_all_target()
492 {
493         int i;
494         ssize_t sendlen;
495         msg_target_t sendlog;
496
497         sendlog.type = MSG_STOP;
498         sendlog.length = 0;
499
500         for (i = 0; i < MAX_TARGET_COUNT; i++)
501         {
502                 if(manager.target[i].socket != -1)
503                 {
504                         sendlen = send(manager.target[i].socket, &sendlog,
505                                                         sizeof(sendlog.type) + sizeof(sendlog.length),
506                                                         MSG_NOSIGNAL);
507                         if(sendlen != -1)
508                         {
509                                 // send to only first main target proces
510                                 LOGI("TERMINATE send exit msg (socket %d) "
511                                      "by terminate_all_target()\n",
512                                      manager.target[i].socket);
513                                 break;
514                         }
515                 }
516         }
517 }
518
519 // terminate all target and wait for threads
520 void terminate_all()
521 {
522         int i;
523         terminate_all_target();
524
525         // wait for all other thread exit
526         for(i = 0; i < MAX_TARGET_COUNT; i++)
527         {
528                 if(manager.target[i].recv_thread != -1)
529                 {
530                         pthread_join(manager.target[i].recv_thread, NULL);
531                 }
532         }
533 }
534
535 // terminate all profiling by critical error
536 // TODO: don't send data to host
537 static void terminate_error(char* errstr, int send_to_host)
538 {
539         LOGE("termination all with err '%s'\n", errstr);
540         struct msg_data_t *msg = NULL;
541         if (send_to_host != 0){
542                 msg = gen_message_error(errstr);
543                 if (msg) {
544                         write_to_buf(msg);
545                         free_msg_data(msg);
546                 } else {
547                         LOGI("cannot generate error message\n");
548                 }
549         }
550         terminate_all();
551 }
552
553 #define MAX_EVENTS_NUM 10
554 static int deviceEventHandler(input_dev* dev, int input_type)
555 {
556         int ret = 0;
557         ssize_t size = 0;
558         int count = 0;
559         struct input_event in_ev[MAX_EVENTS_NUM];
560         struct msg_data_t *log;
561
562         if(input_type == INPUT_ID_TOUCH || input_type == INPUT_ID_KEY)
563         {
564                 do {
565                         size = read(dev->fd, &in_ev[count], sizeof(*in_ev) );
566                         if (size >0)
567                                 count++;
568                 } while (count < MAX_EVENTS_NUM && size > 0);
569
570                 if (count) {
571                         LOGI("read %d %s events\n",
572                              count,
573                              input_type == INPUT_ID_KEY ? STR_KEY : STR_TOUCH);
574                         log = gen_message_event(in_ev, count, input_type);
575                         printBuf((char *)log, MSG_DATA_HDR_LEN + log->len);
576                         write_to_buf(log);
577                         free_msg_data(log);
578                 }
579         }
580         else
581         {
582                 LOGW("unknown input_type\n");
583                 ret = 1; // it is not error
584         }
585         return ret;
586 }
587
588 static int target_event_pid_handler(int index, uint64_t msg)
589 {
590         if (index == 0) {       // main application
591                 if (!is_same_app_process(prof_session.app_info.exe_path,
592                                          manager.target[index].pid)) {
593                         LOGE("is same error: '%s' is not %d\n",
594                              prof_session.app_info.exe_path,
595                              manager.target[index].pid);
596                         return -1;
597                 }
598
599                 if (start_replay() != 0) {
600                         LOGE("Cannot start replay thread\n");
601                         return -1;
602                 }
603         }
604         manager.target[index].initial_log = 1;
605         return 0;
606 }
607
608 static int target_event_stop_handler(int epollfd,
609                                                   int index, uint64_t msg)
610 {
611         LOGI("target close, socket(%d), pid(%d) : (remaining %d target)\n",
612              manager.target[index].socket, manager.target[index].pid,
613              manager.target_count - 1);
614
615         if (index == 0)         // main application
616                 stop_replay();
617
618         if (0 > epoll_ctl(epollfd, EPOLL_CTL_DEL,
619                           manager.target[index].event_fd, NULL))
620                 LOGW("fail to EPOLL DEL of event fd(%d)\n", index);
621
622         setEmptyTargetSlot(index);
623         // all target client are closed
624         if (0 == __sync_sub_and_fetch(&manager.target_count, 1))
625                 return -11;
626
627         return 0;
628 }
629
630
631 // return 0 if normal case
632 // return plus value if non critical error occur
633 // return minus value if critical error occur
634 // return -11 if all target process closed
635 static int target_event_handler(int epollfd, int index, uint64_t msg)
636 {
637         int err = 0;
638         if (msg & EVENT_PID)
639                 err = target_event_pid_handler(index, msg);
640         if (err)
641                 return err;
642
643         if (msg & EVENT_STOP || msg & EVENT_ERROR)
644                 err = target_event_stop_handler(epollfd, index, msg);
645
646         return 0;
647 }
648 #ifndef LOCALTEST
649 static void target_setup_smack_attributes(int target_index)
650 {
651         fsetxattr(manager.target[target_index].socket,
652                   "security.SMACK64IPIN", "*", 1, 0);
653         fsetxattr(manager.target[target_index].socket,
654                   "security.SMACK64IPOUT", "*", 1, 0);
655 }
656 #else
657 static void target_setup_smack_attributes(int unused) {}
658 #endif
659
660 // return 0 if normal case
661 // return plus value if non critical error occur
662 // return minus value if critical error occur
663 static int targetServerHandler(int efd)
664 {
665         msg_target_t log;
666         struct epoll_event ev;
667
668         int index = getEmptyTargetSlot();
669         if(index == MAX_TARGET_COUNT)
670         {
671                 LOGW("Max target number(8) reached, no more target can connected\n");
672                 return 1;
673         }
674
675         manager.target[index].socket =
676                 accept(manager.target_server_socket, NULL, NULL);
677
678         if(manager.target[index].socket >= 0)   // accept succeed
679         {
680                 target_setup_smack_attributes(index);
681
682                 // send config message to target process
683                 log.type = MSG_OPTION;
684                 log.length = sprintf(log.data, "%lu",
685                                      (unsigned long int) prof_session.conf.use_features0);
686                 if (0 > send(manager.target[index].socket, &log,
687                              sizeof(log.type) + sizeof(log.length) + log.length,
688                              MSG_NOSIGNAL))
689                         LOGE("fail to send data to target index(%d)\n", index);
690
691                 // make event fd
692                 manager.target[index].event_fd = eventfd(0, EFD_NONBLOCK);
693                 if(manager.target[index].event_fd == -1)
694                 {
695                         // fail to make event fd
696                         LOGE("fail to make event fd for socket (%d)\n",
697                                         manager.target[index].socket);
698                         goto TARGET_CONNECT_FAIL;
699                 }
700
701                 // add event fd to epoll list
702                 ev.events = EPOLLIN;
703                 ev.data.fd = manager.target[index].event_fd;
704                 if(epoll_ctl(efd, EPOLL_CTL_ADD, manager.target[index].event_fd, &ev) < 0)
705                 {
706                         // fail to add event fd
707                         LOGE("fail to add event fd to epoll list for socket (%d)\n",
708                                         manager.target[index].socket);
709                         goto TARGET_CONNECT_FAIL;
710                 }
711
712                 // make recv thread for target
713                 if(makeRecvThread(index) != 0)
714                 {
715                         // fail to make recv thread
716                         LOGE("fail to make recv thread for socket (%d)\n",
717                                         manager.target[index].socket);
718                         if (0 > epoll_ctl(efd, EPOLL_CTL_DEL,
719                                           manager.target[index].event_fd, NULL))
720                                 LOGW("fail to EPOLL DEL of event fd(%d)\n", index);
721                         goto TARGET_CONNECT_FAIL;
722                 }
723
724                 if(manager.app_launch_timerfd >= 0)
725                 {
726                         LOGI("release launch timer\n");
727                         if (stop_app_launch_timer()<0)
728                                 LOGE("cannot stop app launch timer\n");
729                 }
730
731                 LOGI("target connected = %d(running %d target)\n",
732                                 manager.target[index].socket, manager.target_count + 1);
733
734                 manager.target_count++;
735                 return 0;
736         }
737         else    // accept error
738         {
739                 LOGE("Failed to accept at target server socket\n");
740         }
741
742 TARGET_CONNECT_FAIL:
743         if(manager.target_count == 0)   // if this connection is main connection
744         {
745                 return -1;
746         }
747         else
748         {
749                 // if this connection is not main connection then ignore process by error
750                 setEmptyTargetSlot(index);
751                 return 1;
752         }
753 }
754
755 // return 0 if normal case
756 // return plus value if non critical error occur
757 // return minus value if critical error occur
758 static int hostServerHandler(int efd)
759 {
760         static int hostserverorder = 0;
761         int csocket;
762         struct epoll_event ev;
763
764         if(hostserverorder > 1) // control and data socket connected already
765                 return 1;                       // ignore
766
767         csocket = accept(manager.host_server_socket, NULL, NULL);
768
769         if(csocket >= 0)                // accept succeed
770         {
771                 ev.events = EPOLLIN;
772                 ev.data.fd = csocket;
773                 if(epoll_ctl(efd, EPOLL_CTL_ADD, csocket, &ev) < 0)
774                 {
775                         // consider as accept fail
776                         LOGE("Failed to add socket fd to epoll list\n");
777                         close(csocket);
778                         return -1;
779                 }
780
781                 if(hostserverorder == 0)
782                 {
783                         manager.host.control_socket = csocket;
784                         unlink_portfile();
785                         LOGI("host control socket connected = %d\n", csocket);
786                 }
787                 else
788                 {
789                         manager.host.data_socket = csocket;
790                         LOGI("host data socket connected = %d\n", csocket);
791                 }
792
793                 hostserverorder++;
794                 return 0;
795         }
796         else    // accept error
797         {
798                 LOGE("Failed to accept from host server socket\n");
799                 return -1;
800         }
801 }
802
803
804 // return 0 if normal case
805 // return plus value if non critical error occur
806 // return minus value if critical error occur
807 // return -11 if socket closed
808
809 static int controlSocketHandler(int efd)
810 {
811         ssize_t recv_len;
812         struct msg_t msg_head;
813         struct msg_t *msg;
814         int res = 0;
815
816         if(manager.connect_timeout_timerfd >= 0)
817         {
818                 LOGI("release connect timeout timer\n");
819                 if (0 > epoll_ctl(efd, EPOLL_CTL_DEL,
820                                   manager.connect_timeout_timerfd, NULL))
821                         LOGW("fail to EPOLL DEL of timeout timer fd\n");
822                 close(manager.connect_timeout_timerfd);
823                 manager.connect_timeout_timerfd = -1;
824         }
825
826         // Receive header
827         recv_len = recv(manager.host.control_socket,
828                        &msg_head,
829                        MSG_CMD_HDR_LEN, 0);
830         // error or close request from host
831         if (recv_len == -1 || recv_len == 0)
832                 return -11;
833         else {
834                 msg = malloc(MSG_CMD_HDR_LEN + msg_head.len);
835                 if (!msg) {
836                         LOGE("Cannot alloc msg\n");
837                         sendACKToHost(msg_head.id, ERR_WRONG_MESSAGE_FORMAT, 0, 0);
838                         return -1;
839                 }
840                 msg->id = msg_head.id;
841                 msg->len = msg_head.len;
842                 if (msg->len > 0) {
843                         // Receive payload (if exists)
844                         recv_len = recv(manager.host.control_socket,
845                                         msg->payload,
846                                         msg->len, MSG_WAITALL);
847                         if (recv_len == -1)
848                                 return -11;
849                 }
850                 printBuf(msg, MSG_DATA_HDR_LEN + msg->len);
851                 res = host_message_handler(msg);
852                 free(msg);
853         }
854
855         return res;
856 }
857
858 static void epoll_add_input_events()
859 {
860         struct epoll_event ev;
861         int i;
862
863         // add device fds to epoll event pool
864         ev.events = EPOLLIN;
865         for (i = 0; g_key_dev[i].fd != ARRAY_END; i++) {
866                 if (g_key_dev[i].fd >= 0) {
867                         ev.data.fd = g_key_dev[i].fd;
868                         if (epoll_ctl(manager.efd,
869                                       EPOLL_CTL_ADD,
870                                       g_key_dev[i].fd, &ev) < 0)
871                                 LOGE("keyboard device file epoll_ctl error\n");
872                 }
873         }
874
875         ev.events = EPOLLIN;
876         for (i = 0; g_touch_dev[i].fd != ARRAY_END; i++) {
877                 if (g_touch_dev[i].fd >= 0) {
878                         ev.data.fd = g_touch_dev[i].fd;
879                         if (epoll_ctl(manager.efd,
880                                       EPOLL_CTL_ADD,
881                                       g_touch_dev[i].fd, &ev) < 0)
882                                 LOGE("touch device file epoll_ctl error\n");
883                 }
884         }
885 }
886
887 static void epoll_del_input_events()
888 {
889         int i;
890
891         // remove device fds from epoll event pool
892         for (i = 0; g_key_dev[i].fd != ARRAY_END; i++)
893                 if (g_key_dev[i].fd >= 0)
894                         if (epoll_ctl(manager.efd,
895                                       EPOLL_CTL_DEL,
896                                       g_key_dev[i].fd, NULL) < 0)
897                                 LOGE("keyboard device file epoll_ctl error\n");
898
899         for (i = 0; g_touch_dev[i].fd != ARRAY_END; i++)
900                 if (g_touch_dev[i].fd >= 0)
901                         if (epoll_ctl(manager.efd,
902                                       EPOLL_CTL_DEL,
903                                       g_touch_dev[i].fd, NULL) < 0)
904                                 LOGE("touch device file epoll_ctl error\n");
905 }
906 static bool initialize_epoll_events(void)
907 {
908         struct epoll_event ev;
909
910         if ((manager.efd = epoll_create1(0)) < 0) {
911           LOGE("epoll creation error\n");
912           return false;
913         }
914
915         // add server sockets to epoll event pool
916         ev.events = EPOLLIN;
917         ev.data.fd = manager.host_server_socket;
918         if (epoll_ctl(manager.efd, EPOLL_CTL_ADD,
919                      manager.host_server_socket, &ev) < 0)
920         {
921                 LOGE("Host server socket epoll_ctl error\n");
922                 return false;
923         }
924         ev.events = EPOLLIN;
925         ev.data.fd = manager.target_server_socket;
926         if (epoll_ctl(manager.efd, EPOLL_CTL_ADD,
927                       manager.target_server_socket, &ev) < 0)
928         {
929                 LOGE("Target server socket epoll_ctl error\n");
930                 return false;
931         }
932         return true;
933 }
934
935 // return 0 for normal case
936 int daemonLoop()
937 {
938         int return_value = 0;
939         struct epoll_event *events = malloc(EPOLL_SIZE * sizeof(*events));
940
941         _get_fds(g_key_dev, INPUT_ID_KEY);
942         _get_fds(g_touch_dev, INPUT_ID_TOUCH);
943
944         if (!events) {
945                 LOGE("Out of memory when allocate epoll event pool\n");
946                 return_value = -1;
947                 goto END_EVENT;
948         }
949         if (!initialize_epoll_events()) {
950                 return_value = -1;
951                 goto END_EFD;
952         }
953
954         if (launch_timer_start() < 0) {
955                 LOGE("Launch timer start failed\n");
956                 return_value = -1;
957                 goto END_EFD;
958         }
959
960
961         // handler loop
962         while (1) {
963                 int i, k;
964                 ssize_t recvLen;
965                 // number of occured events
966                 int numevent = epoll_wait(manager.efd, events, EPOLL_SIZE, -1);
967                 if (numevent <= 0) {
968                         LOGE("Failed to epoll_wait : num of event(%d), errno(%d)\n", numevent, errno);
969                         continue;
970                 }
971
972                 for(i = 0; i < numevent; i++)
973                 {
974                         // check for request from event fd
975                         for(k = 0; k < MAX_TARGET_COUNT; k++)
976                         {
977                                 if(manager.target[k].socket != -1 &&
978                                                 events[i].data.fd == manager.target[k].event_fd)
979                                 {
980                                         uint64_t u;
981                                         recvLen = read(manager.target[k].event_fd, &u, sizeof(uint64_t));
982                                         if(recvLen != sizeof(uint64_t))
983                                         {
984                                                 // maybe closed, but ignoring is more safe then
985                                                 // removing fd from epoll list
986                                         }
987                                         else
988                                         {
989                                                 if(-11 == target_event_handler(manager.efd, k, u))
990                                                 {
991                                                         LOGI("all target process is closed\n");
992                                                         continue;
993                                                 }
994                                         }
995                                         break;
996                                 }
997                         }
998
999                         if(k != MAX_TARGET_COUNT)
1000                                 continue;
1001
1002                         // check for request from device fd
1003                         for(k = 0; g_touch_dev[k].fd != ARRAY_END; k++)
1004                         {
1005                                 if(g_touch_dev[k].fd >= 0 &&
1006                                                 events[i].data.fd == g_touch_dev[k].fd)
1007                                 {
1008                                         if(deviceEventHandler(&g_touch_dev[k], INPUT_ID_TOUCH) < 0)
1009                                         {
1010                                                 LOGE("Internal DA framework error, "
1011                                                          "Please re-run the profiling (touch dev)\n");
1012                                                 continue;
1013                                         }
1014                                         break;
1015                                 }
1016                         }
1017
1018                         if(g_touch_dev[k].fd != ARRAY_END)
1019                                 continue;
1020
1021                         for(k = 0; g_key_dev[k].fd != ARRAY_END; k++)
1022                         {
1023                                 if(g_key_dev[k].fd >= 0 &&
1024                                                 events[i].data.fd == g_key_dev[k].fd)
1025                                 {
1026                                         if(deviceEventHandler(&g_key_dev[k], INPUT_ID_KEY) < 0)
1027                                         {
1028                                                 LOGE("Internal DA framework error, "
1029                                                          "Please re-run the profiling (key dev)\n");
1030                                                 continue;
1031                                         }
1032                                         break;
1033                                 }
1034                         }
1035
1036                         if(g_key_dev[k].fd != ARRAY_END)
1037                                 continue;
1038
1039                         // connect request from target
1040                         if (events[i].data.fd == manager.target_server_socket)
1041                         {
1042                                 if (targetServerHandler(manager.efd) < 0)       // critical error
1043                                 {
1044                                         terminate_error("Internal DA framework error, "
1045                                                                         "Please re-run the profiling (targetServerHandler)\n", 1);
1046                                         continue;
1047                                 }
1048                         }
1049                         // connect request from host
1050                         else if (events[i].data.fd == manager.host_server_socket)
1051                         {
1052                                 int result = hostServerHandler(manager.efd);
1053                                 if (result < 0)
1054                                 {
1055                                         LOGE("Internal DA framework error (hostServerHandler)\n");
1056                                         continue;
1057                                 }
1058                         }
1059                         // control message from host
1060                         else if (events[i].data.fd == manager.host.control_socket)
1061                         {
1062                                 int result = controlSocketHandler(manager.efd);
1063                                 if (result == -11)      // socket close
1064                                 {
1065                                         //if the host disconnected.
1066                                         //In all other cases daemon must report an error and continue the loop
1067                                         //close connect_timeoutt and host socket and quit
1068                                         LOGI("Connection closed. Termination. (%d)\n",
1069                                              manager.host.control_socket);
1070                                         return_value = 0;
1071                                         goto END_EFD;
1072                                 }
1073                                 else if (result < 0)
1074                                 {
1075                                         LOGE("Control socket handler.\n");
1076                                 }
1077                         }
1078                         else if (events[i].data.fd == manager.host.data_socket)
1079                         {
1080                                 char recvBuf[32];
1081                                 recvLen = recv(manager.host.data_socket, recvBuf, 32, MSG_DONTWAIT);
1082                                 if (recvLen == 0)
1083                                 {       // close data socket
1084                                         if (0 > epoll_ctl(manager.efd, EPOLL_CTL_DEL,
1085                                                           manager.host.data_socket,
1086                                                           NULL))
1087                                                 LOGW("fail to EPOLL DEL of host data socket\n");
1088                                         close(manager.host.data_socket);
1089                                         manager.host.data_socket = -1;
1090                                         // TODO: finish transfer thread
1091                                 }
1092
1093                                 LOGI("host message from data socket %d\n", recvLen);
1094                         }
1095                         // check for application launch timerfd
1096                         else if (events[i].data.fd == manager.app_launch_timerfd)
1097                         {
1098                                 // send to host timeout error message for launching application
1099                                 LOGE("Failed to launch application\n");
1100                                 if (stop_app_launch_timer()<0)
1101                                         LOGE("cannot stop app launch timer\n");
1102                                 continue;
1103                         }
1104                         // check for connection timeout timerfd
1105                         else if (events[i].data.fd == manager.connect_timeout_timerfd)
1106                         {
1107                                 // send to host timeout error message for launching application
1108                                 terminate_error("no incoming connections", 1);
1109                                 if (0 > epoll_ctl(manager.efd, EPOLL_CTL_DEL,
1110                                                   manager.connect_timeout_timerfd, NULL))
1111                                         LOGW("fail to EPOLL DEL of timeout timer fd\n");
1112                                 close(manager.connect_timeout_timerfd);
1113                                 manager.connect_timeout_timerfd = -1;
1114                                 LOGE("No connection in %d sec. shutdown.\n",MAX_CONNECT_TIMEOUT_TIME);
1115                                 goto END_EFD;
1116                         }
1117                         // unknown socket
1118                         else
1119                         {
1120                                 // never happened
1121                                 LOGW("Unknown socket fd (%d)\n", events[i].data.fd);
1122                         }
1123                 }
1124         }
1125
1126 END_EFD:
1127         LOGI("close efd\n");
1128         close(manager.efd);
1129 END_EVENT:
1130         free(events);
1131         return return_value;
1132 }