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