summaryrefslogtreecommitdiff
path: root/tizen/src/ecs/ecs.c
blob: 758579281c0a84c3e90833dcf1a34002b9e439fc (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
/*
 * Emulator Control Server
 *
 * Copyright (c) 2013 Samsung Electronics Co., Ltd All Rights Reserved
 *
 * Contact:
 *  Chulho Song     <ch81.song@samsung.com>
 *  Jinhyung Choi   <jinh0.choi@samsung.com>
 *  MunKyu Im       <munkyu.im@samsung.com>
 *  Daiyoung Kim    <daiyoung777.kim@samsung.com>
 *  YeongKyoon Lee  <yeongkyoon.lee@samsung.com>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 *
 * Contributors:
 * - S-Core Co., Ltd
 *
 */

#include <stdbool.h>
#include <stdlib.h>

#include "qemu/osdep.h"
#include "hw/qdev.h"
#include "net/net.h"
#include "ui/console.h"

#include "qemu-common.h"
#include "qemu/queue.h"
#include "qemu/sockets.h"
#include "qemu/option.h"
#include "qemu/timer.h"
#include "qemu/main-loop.h"
#include "sysemu/char.h"
#include "qapi/qmp/qint.h"

#include "emulator.h"
#include "util/net_helper.h"
#include "ecs.h"
#include "emul_state.h"

#include "hw/virtio/maru_virtio_sensor.h"
#include "hw/virtio/maru_virtio_nfc.h"

#include "debug_ch.h"
MULTI_DEBUG_CHANNEL(qemu, ecs);

#define DEBUG

#ifndef min
#define min(a, b) ((a) < (b) ? (a) : (b))
#endif

static QTAILQ_HEAD(ECS_ClientHead, ECS_Client)
clients = QTAILQ_HEAD_INITIALIZER(clients);

static ECS_State *current_ecs;

static void *keepalive_buf;
static int payloadsize;

static int g_client_id = 1;

static QemuMutex mutex_clilist;
QemuMutex mutex_location_data;

static QemuThread ecs_thread_id;

static int suspend_state = 1;

static char device_capabilities [16];

enum ecs_check_cap_list {
    CHECK_CAP_BATTERY = 0,
    CHECK_CAP_LOCATION,
    CHECK_CAP_NFC,
    CHECK_CAP_TELEPHONY,
    CHECK_CAP_ACCEL,
    CHECK_CAP_GYRO,
    CHECK_CAP_GEO,
    CHECK_CAP_PROXI,
    CHECK_CAP_LIGHT,
    CHECK_CAP_PRESSURE,
    CHECK_CAP_HEARTRATE,
    CHECK_CAP_UV,
    CHECK_CAP_PEDO
};

static int cap_device_list[] = {
    0x0001,             // Battery
    0x0002,             // Location
    0x0004,             // NFC
    0x0008,             // Telephony
    0x0010,             // Accelerometer
    0x0020,             // Gyroscope
    0x0040,             // Magnetometer
    0x0080,             // Proximity
    0x0100,             // Light
    0x0200,             // Pressure
    0x0400,             // HeartRate
    0x0800,             // Ultraviolet
    0x1000,             // Pedometer
};

void ecs_set_suspend_state(int state)
{
    suspend_state = state;
}

int ecs_get_suspend_state(void)
{
    return suspend_state;
}

static void check_sensor_capability(int* capacity)
{
    int sensor_cap = get_sensor_capability();
    if ((sensor_cap & sensor_cap_accel) == 0) {
        *capacity &= ~cap_device_list[CHECK_CAP_ACCEL];
    }
    if ((sensor_cap & sensor_cap_geo) == 0) {
        *capacity &= ~cap_device_list[CHECK_CAP_GEO];
    }

    if ((sensor_cap & sensor_cap_gyro) == 0) {
        *capacity &= ~cap_device_list[CHECK_CAP_GYRO];
    }

    if ((sensor_cap & sensor_cap_proxi) == 0) {
        *capacity &= ~cap_device_list[CHECK_CAP_PROXI];
    }

    if ((sensor_cap & sensor_cap_light) == 0) {
        *capacity &= ~cap_device_list[CHECK_CAP_LIGHT];
    }

    if ((sensor_cap & sensor_cap_pressure) == 0) {
        *capacity &= ~cap_device_list[CHECK_CAP_PRESSURE];
    }

    if ((sensor_cap & sensor_cap_uv) == 0) {
        *capacity &= ~cap_device_list[CHECK_CAP_UV];
    }

    if ((sensor_cap & sensor_cap_hrm) == 0) {
        *capacity &= ~cap_device_list[CHECK_CAP_HEARTRATE];
    }

    if ((sensor_cap & sensor_cap_pedo) == 0) {
        *capacity &= ~cap_device_list[CHECK_CAP_PEDO];
    }
}

extern VirtIONFC *vio_nfc;
static void check_nfc_capability(int* capacity)
{
    if (!vio_nfc) {
        *capacity &= ~cap_device_list[CHECK_CAP_NFC];
    }
}

void ecs_set_device_capabilities(const char* cap)
{
    int capability = 0;

    memset(device_capabilities, 0, sizeof(device_capabilities));

    if (cap != NULL) {
        capability = atoi(cap);
        // check sensor capability
        check_sensor_capability(&capability);
        // check nfc capability
        check_nfc_capability(&capability);

        LOG_INFO("check_sensor_capability: %04x\n", capability);
        snprintf(device_capabilities, sizeof(device_capabilities), "%d", capability);
    }

    make_send_device_ntf((char*)MSG_TYPE_CAP, MSG_GROUP_STATUS, 0, device_capabilities);
}

const char* ecs_get_device_capabilities(void)
{
    return device_capabilities;
}

int ecs_write(int fd, const uint8_t *buf, int len)
{
    int ret, remain;

    LOG_TRACE("write fd: %d, buflen : %d, buf : %s\n", fd, len, (char *)buf);
    if (fd < 0) {
        LOG_SEVERE("fd is corrupted : %d\n", fd);
        return -1;
    }

    remain = len;
    while (len > 0) {
        ret = send(fd, buf, remain, 0);
        if (ret < 0) {
#ifdef _WIN32
            errno = WSAGetLastError();
            if (errno != WSAEWOULDBLOCK) {
                LOG_SEVERE("write error: %d\n", errno);
                return -1;
            }
#else
            if (errno != EINTR && errno != EAGAIN) {
                LOG_SEVERE("write error: %d\n", errno);
                return -1;
            }
#endif
        } else if (ret == 0) {
            break;
        } else {
            buf += ret;
            remain -= ret;
        }
    }

    return len - remain;
}

void ecs_client_close(ECS_Client *clii)
{
    if (clii == NULL) {
        return;
    }

    qemu_mutex_lock(&mutex_clilist);

    if (clii->client_fd > 0) {
        LOG_INFO("ecs client closed with fd: %d\n", clii->client_fd);
        closesocket(clii->client_fd);
#ifndef CONFIG_LINUX
        FD_CLR(clii->client_fd, &clii->cs->reads);
#endif
        clii->client_fd = -1;
    }

    QTAILQ_REMOVE(&clients, clii, next);

    g_free(clii);
    clii = NULL;

    qemu_mutex_unlock(&mutex_clilist);
}

bool send_to_all_client(const char *data, const int len)
{
    LOG_TRACE("data len: %d, data: %s\n", len, data);
    qemu_mutex_lock(&mutex_clilist);

    ECS_Client *clii, *next;

    QTAILQ_FOREACH_SAFE(clii, &clients, next, next)
    {
        send_to_client(clii->client_fd, data, len);
    }
    qemu_mutex_unlock(&mutex_clilist);

    return true;
}

void send_to_single_client(ECS_Client *clii, const char *data, const int len)
{
    qemu_mutex_lock(&mutex_clilist);
    send_to_client(clii->client_fd, data, len);
    qemu_mutex_unlock(&mutex_clilist);
}

void send_to_client(int fd, const char *data, const int len)
{
    ecs_write(fd, (const uint8_t *) data, len);
}

void read_val_short(const char *data, unsigned short *ret_val)
{
    memcpy(ret_val, data, sizeof(unsigned short));
}

void read_val_char(const char *data, unsigned char *ret_val)
{
    memcpy(ret_val, data, sizeof(unsigned char));
}

void read_val_str(const char *data, char *ret_val, int len)
{
    memcpy(ret_val, data, len);
}

bool ntf_to_control(const char *data, const int len)
{
    return true;
}

bool ntf_to_monitor(const char *data, const int len)
{
    return true;
}

void print_binary(const char *data, const int len)
{
    int i;
    printf("[DATA: ");
    for (i = 0; i < len; i++) {
        if (i == len - 1) {
            printf("%02x]\n", data[i]);
        } else {
            printf("%02x,", data[i]);
        }
    }
}

void ecs_make_header(QDict *obj, type_length length, type_group group,
        type_action action)
{
    qdict_put(obj, "length", qint_from_int((int64_t)length));
    qdict_put(obj, "group", qint_from_int((int64_t)group));
    qdict_put(obj, "action", qint_from_int((int64_t)action));
}

static Monitor *monitor_create(void)
{
    Monitor *mon;

    mon = g_malloc0(sizeof(*mon));
    if (NULL == mon) {
        LOG_SEVERE("monitor allocation failed.\n");
        return NULL;
    }

    return mon;
}

static void ecs_close(ECS_State *cs)
{
    ECS_Client *clii, *next;
    LOG_INFO("### Good bye! ECS ###\n");

    if (cs == NULL) {
        return;
    }

    if (0 <= cs->listen_fd) {
        LOG_INFO("close listen_fd: %d\n", cs->listen_fd);
        closesocket(cs->listen_fd);
        cs->listen_fd = -1;
    }

    g_free(cs->mon);
    cs->mon = NULL;

    g_free(keepalive_buf);
    keepalive_buf = NULL;

    if (cs->alive_timer != NULL) {
        timer_del(cs->alive_timer);
        timer_free(cs->alive_timer);
        cs->alive_timer = NULL;
    }

    QTAILQ_FOREACH_SAFE(clii, &clients, next, next)
    {
        ecs_client_close(clii);
    }

    g_free(cs);
    cs = NULL;
    current_ecs = NULL;

    qemu_mutex_destroy(&mutex_clilist);
    qemu_mutex_destroy(&mutex_location_data);
}

#ifndef _WIN32
static ssize_t ecs_recv(int fd, char *buf, size_t len)
{
    struct msghdr msg = { NULL, };
    struct iovec iov[1];
    union {
        struct cmsghdr cmsg;
        char control[CMSG_SPACE(sizeof(int))];
    } msg_control;
    int flags = 0;

    iov[0].iov_base = buf;
    iov[0].iov_len = len;

    msg.msg_iov = iov;
    msg.msg_iovlen = 1;
    msg.msg_control = &msg_control;
    msg.msg_controllen = sizeof(msg_control);

#ifdef MSG_CMSG_CLOEXEC
    flags |= MSG_CMSG_CLOEXEC;
#endif
    return recvmsg(fd, &msg, flags);
}

#else
static ssize_t ecs_recv(int fd, char *buf, size_t len)
{
    return qemu_recv(fd, buf, len, 0);
}
#endif

static void reset_sbuf(sbuf *sbuf)
{
    memset(sbuf->_buf, 0, 4096);
    sbuf->_use = 0;
    sbuf->_netlen = 0;
}

static bool handle_protobuf_msg(ECS_Client *cli, char *data, int len)
{
    ECS__Master *master = ecs__master__unpack(NULL, (size_t)len, (const uint8_t *)data);
    if (!master) {
        return false;
    }

    if (master->type == ECS__MASTER__TYPE__INJECTOR_REQ) {
        ECS__InjectorReq *msg = master->injector_req;
        if (!msg) {
            goto fail;
        }
        msgproc_injector_req(cli, msg);
    } else if (master->type == ECS__MASTER__TYPE__MONITOR_REQ) {
        ECS__MonitorReq *msg = master->monitor_req;
        if (!msg) {
            goto fail;
        }
        msgproc_monitor_req(cli, msg);
    } else if (master->type == ECS__MASTER__TYPE__DEVICE_REQ) {
        cli->client_type = TYPE_ECP;
        ECS__DeviceReq *msg = master->device_req;
        if (!msg) {
            goto fail;
        }
        msgproc_device_req(cli, msg);
    } else if (master->type == ECS__MASTER__TYPE__NFC_REQ) {
        ECS__NfcReq *msg = master->nfc_req;
        if (!msg) {
            goto fail;
        }
        qemu_mutex_lock(&mutex_clilist);
        if (cli->client_type == TYPE_NONE) {
            if (!strncmp(msg->category, MSG_TYPE_NFC, 3)) {
                QTAILQ_REMOVE(&clients, cli, next);
                cli->client_type = TYPE_ECP;
                if (g_client_id > 255) {
                    g_client_id = 1;
                }
                cli->client_id = g_client_id++;

                QTAILQ_INSERT_TAIL(&clients, cli, next);
            } else if (!strncmp(msg->category, MSG_TYPE_SIMUL_NFC, 9)) {
                QTAILQ_REMOVE(&clients, cli, next);
                cli->client_type = TYPE_SIMUL_NFC;
                if (g_client_id > 255) {
                    g_client_id = 1;
                }
                cli->client_id = g_client_id++;
                QTAILQ_INSERT_TAIL(&clients, cli, next);
            } else {
                LOG_SEVERE("unsupported category is found: %s\n", msg->category);
                qemu_mutex_unlock(&mutex_clilist);
                goto fail;
            }
        }
        qemu_mutex_unlock(&mutex_clilist);

        msgproc_nfc_req(cli, msg);
    } else if (master->type == ECS__MASTER__TYPE__KEEPALIVE_ANS) {
        ECS__KeepAliveAns *msg = master->keepalive_ans;
        if (!msg) {
            goto fail;
        }
        msgproc_keepalive_ans(cli, msg);
    } else if (master->type == ECS__MASTER__TYPE__EVENTCAST_REQ) {
        ECS__EventCastReq *msg = master->eventcast_req;
        if (!msg) {
            goto fail;
        }
        msgproc_eventcast_req(cli, msg);
    } else {
        goto fail;
    }

    ecs__master__free_unpacked(master, NULL);
    return true;
fail:
    LOG_SEVERE("invalid message type : %d\n", master->type);
    ecs__master__free_unpacked(master, NULL);
    return false;
}

static void ecs_read(ECS_Client *cli)
{

    int read = 0;
    int to_read_bytes = 0;

    if (cli == NULL) {
        LOG_SEVERE("client is null.\n");
        return;
    }

#ifndef __WIN32
    if (ioctl(cli->client_fd, FIONREAD, &to_read_bytes) < 0) {
        LOG_SEVERE("ioctl failed\n");
        return;
    }
#else
    unsigned long to_read_bytes_long = 0;
    if (ioctlsocket(cli->client_fd, FIONREAD, &to_read_bytes_long) < 0) {
        LOG_SEVERE("ioctl failed\n");
         return;
    }
    to_read_bytes = (int)to_read_bytes_long;
#endif

    if (to_read_bytes == 0) {
        LOG_TRACE("ioctl FIONREAD: 0\n");
        goto fail;
    }

    if (cli->sbuf._netlen == 0) {
        if (to_read_bytes < 4) {
            return;
        }

        long payloadsize = 0;
        read = ecs_recv(cli->client_fd, (char *) &payloadsize, 4);

        if (read < 4) {
            LOG_SEVERE("insufficient header size\n");
            goto fail;
        }

        payloadsize = ntohl(payloadsize);

        cli->sbuf._netlen = payloadsize;

        LOG_TRACE("payload size: %ld\n", payloadsize);

        to_read_bytes -= 4;
    }

    if (to_read_bytes == 0) {
        return;
    }

    to_read_bytes = min(to_read_bytes, cli->sbuf._netlen - cli->sbuf._use);

    read = ecs_recv(cli->client_fd, (char *)(cli->sbuf._buf + cli->sbuf._use), to_read_bytes);
    if (read == 0) {
        goto fail;
    }

    cli->sbuf._use += read;

    if (cli->sbuf._netlen == cli->sbuf._use) {
        handle_protobuf_msg(cli, (char *)cli->sbuf._buf, cli->sbuf._use);
        reset_sbuf(&cli->sbuf);
    }

    return;
fail:
    ecs_client_close(cli);
}

#ifdef CONFIG_LINUX
static void epoll_cli_add(ECS_State *cs, int fd)
{
    struct epoll_event events;

    /* event control set for read event */
    events.events = EPOLLIN;
    events.data.fd = fd;

    if (epoll_ctl(cs->epoll_fd, EPOLL_CTL_ADD, fd, &events) < 0) {
        LOG_SEVERE("Epoll control fails.in epoll_cli_add.\n");
    }
}
#endif

static ECS_Client *ecs_find_client(int fd)
{
    ECS_Client *clii, *next;

    QTAILQ_FOREACH_SAFE(clii, &clients, next, next)
    {
        if (clii->client_fd == fd) {
            return clii;
        }
    }
    return NULL;
}

ECS_Client *find_client(unsigned char id, unsigned char type)
{
    ECS_Client *clii, *next;

    QTAILQ_FOREACH_SAFE(clii, &clients, next, next)
    {
        if (clii->client_id == id && clii->client_type == type) {
            return clii;
        }
    }
    return NULL;
}

static int ecs_add_client(ECS_State *cs, int fd)
{
    ECS_Client *clii = g_malloc0(sizeof(ECS_Client));
    if (NULL == clii) {
        LOG_SEVERE("ECS_Client allocation failed.\n");
        return -1;
    }

    reset_sbuf(&clii->sbuf);

    qemu_set_nonblock(fd);

    clii->client_fd = fd;
    clii->cs = cs;
    clii->client_type = TYPE_NONE;

    ecs_json_message_parser_init(&clii->parser, handle_qmp_command, clii);

#ifdef CONFIG_LINUX
    epoll_cli_add(cs, fd);
#else
    FD_SET(fd, &cs->reads);
#endif

    qemu_mutex_lock(&mutex_clilist);

    QTAILQ_INSERT_TAIL(&clients, clii, next);

    LOG_TRACE("Add an ecs client. fd: %d\n", fd);

    qemu_mutex_unlock(&mutex_clilist);

#if 0
    send_ecs_version_check(clii);
#endif

    return 0;
}

static void ecs_accept(ECS_State *cs)
{
    struct sockaddr_in saddr;
#ifndef _WIN32
    struct sockaddr_un uaddr;
#endif
    struct sockaddr *addr;
    socklen_t len;
    int fd;

    for (;;) {
#ifndef _WIN32
        if (cs->is_unix) {
            len = sizeof(uaddr);
            addr = (struct sockaddr *) &uaddr;
        } else
#endif
        {
            len = sizeof(saddr);
            addr = (struct sockaddr *) &saddr;
        }
        fd = qemu_accept(cs->listen_fd, addr, &len);
        if (0 > fd && EINTR != errno) {
            return;
        } else if (0 <= fd) {
            break;
        }
    }
    if (0 > ecs_add_client(cs, fd)) {
        LOG_SEVERE("failed to add client.\n");
    }
}

#ifdef CONFIG_LINUX
static void epoll_init(ECS_State *cs)
{
    struct epoll_event events;

    cs->epoll_fd = epoll_create(MAX_EVENTS);
    if (cs->epoll_fd < 0) {
        closesocket(cs->listen_fd);
    }

    events.events = EPOLLIN;
    events.data.fd = cs->listen_fd;

    if (epoll_ctl(cs->epoll_fd, EPOLL_CTL_ADD, cs->listen_fd, &events) < 0) {
        close(cs->listen_fd);
        close(cs->epoll_fd);
    }
}
#endif

static void send_keep_alive_msg(ECS_Client *clii)
{
    send_to_single_client(clii, keepalive_buf, payloadsize);
}

static void make_keep_alive_msg(void)
{
    int len_pack = 0;
    char msg[5] = {'s', 'e', 'l', 'f'};

    ECS__Master master = ECS__MASTER__INIT;
    ECS__KeepAliveReq req = ECS__KEEP_ALIVE_REQ__INIT;

    req.time_str = (char *) g_malloc(5);

    strncpy(req.time_str, msg, 4);

    master.type = ECS__MASTER__TYPE__KEEPALIVE_REQ;
    master.keepalive_req = &req;

    len_pack = ecs__master__get_packed_size(&master);
    payloadsize = len_pack + 4;

    keepalive_buf = g_malloc(len_pack + 4);
    if (!keepalive_buf) {
        LOG_SEVERE("keep alive message creation is failed.\n");
        return;
    }

    ecs__master__pack(&master, keepalive_buf + 4);

    len_pack = htonl(len_pack);
    memcpy(keepalive_buf, &len_pack, 4);
}

static void alive_checker(void *opaque)
{
    ECS_Client *clii, *next;

    if (NULL != current_ecs && !current_ecs->ecs_running) {
        return;
    }

    QTAILQ_FOREACH_SAFE(clii, &clients, next, next)
    {
        if (1 == clii->keep_alive) {
            LOG_INFO("get client fd %d - keep alive fail\n", clii->client_fd);
            ecs_client_close(clii);
            continue;
        }
        LOG_TRACE("set client fd %d - keep alive 1\n", clii->client_fd);
        clii->keep_alive = 1;
        send_keep_alive_msg(clii);
    }

    if (current_ecs == NULL) {
        LOG_SEVERE("alive checking is failed because current ecs is null.\n");
        return;
    }

    timer_mod(current_ecs->alive_timer,
            qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + NANOSECONDS_PER_SECOND * TIMER_ALIVE_S);

}

#ifdef CONFIG_LINUX
static int ecs_loop(ECS_State *cs)
{
    int i, nfds;

    nfds = epoll_wait(cs->epoll_fd, cs->events, MAX_EVENTS, 100);
    if (0 == nfds) {
        return 0;
    }

    if (0 > nfds) {
        if (errno == EINTR) {
            return 0;
        }
        perror("epoll wait error");
        return -1;
    }

    for (i = 0; i < nfds; i++) {
        if (cs->events[i].data.fd == cs->listen_fd) {
            ecs_accept(cs);
            continue;
        }
        ecs_read(ecs_find_client(cs->events[i].data.fd));
    }

    return 0;
}
#elif defined(CONFIG_WIN32)
static int ecs_loop(ECS_State *cs)
{
    int index = 0;
    TIMEVAL timeout;
    fd_set temps = cs->reads;

    timeout.tv_sec = 5;
    timeout.tv_usec = 0;

    if (select(0, &temps, 0, 0, &timeout) < 0) {
        LOG_SEVERE("select error.\n");
        return -1;
    }

    for (index = 0; index < cs->reads.fd_count; index++) {
        if (cs->reads.fd_array == NULL) {
            continue;
        }
        if (FD_ISSET(cs->reads.fd_array[index], &temps)) {
            if (cs->reads.fd_array[index] == cs->listen_fd) {
                ecs_accept(cs);
                continue;
            }
            ecs_read(ecs_find_client(cs->reads.fd_array[index]));
        }
    }
    return 0;
}
#elif defined(CONFIG_DARWIN)
static int ecs_loop(ECS_State *cs)
{
    int index = 0;
    int res = 0;
    struct timeval timeout;
    fd_set temps = cs->reads;

    timeout.tv_sec = 5;
    timeout.tv_usec = 0;

    res = select(MAX_FD_NUM + 1, &temps, NULL, NULL, &timeout);
    if (res < 0) {
        LOG_SEVERE("select failed..\n");
        return -1;
    }

    for (index = 0; index < MAX_FD_NUM; index++) {
        if (FD_ISSET(index, &temps)) {
            if (index == cs->listen_fd) {
                ecs_accept(cs);
                continue;
            }

            ecs_read(ecs_find_client(index));
        }
    }

    return 0;
}
#endif

static int socket_initialize(ECS_State *cs)
{
    LOG_INFO("Listen fd is %d\n", emul_vm_base_socket);
    g_assert(emul_vm_base_socket >= 0);

    cs->listen_fd = emul_vm_base_socket;

#ifdef CONFIG_LINUX
    epoll_init(cs);
#else
    FD_ZERO(&cs->reads);
    FD_SET(cs->listen_fd, &cs->reads);
#endif

    make_keep_alive_msg();

    cs->alive_timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, alive_checker, cs);

    timer_mod(cs->alive_timer,
            qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + NANOSECONDS_PER_SECOND * TIMER_ALIVE_S);

    return 0;
}

static void *ecs_initialize(void *args)
{
    int ret = 1;
    ECS_State *cs = NULL;
    Monitor *mon = NULL;

    LOG_INFO("ecs starts initializing.\n");

    qemu_mutex_init(&mutex_clilist);
    qemu_mutex_init(&mutex_location_data);

    cs = g_malloc0(sizeof(ECS_State));
    if (NULL == cs) {
        LOG_SEVERE("ECS_State allocation failed.\n");
        return NULL;
    }

    cs->listen_fd = -1;
    ret = socket_initialize(cs);
    if (ret < 0) {
        LOG_SEVERE("Socket initialization is failed.\n");
        ecs_close(cs);
        return NULL;
    }

    mon = monitor_create();
    if (NULL == mon) {
        LOG_SEVERE("monitor initialization failed.\n");
        ecs_close(cs);
        return NULL;
    }

    cs->mon = mon;
    current_ecs = cs;
    cs->ecs_running = 1;

    LOG_TRACE("ecs_loop entered.\n");
    while (cs->ecs_running) {
        ret = ecs_loop(cs);
        if (0 > ret) {
            break;
        }
    }
    LOG_TRACE("ecs_loop exited.\n");

    ecs_close(cs);

    return NULL;
}

bool is_ecs_running(void)
{
    if (current_ecs != NULL) {
        return current_ecs->ecs_running;
    }

    return false;
}

static int stop_ecs(void)
{
    void *ret = NULL;

    LOG_INFO("ecs is closing.\n");
    if (NULL != current_ecs) {
        current_ecs->ecs_running = 0;
    }

    ret = qemu_thread_join(&ecs_thread_id);
    if (ret) {
        LOG_SEVERE("ecs is failed to join thread.\n");
        return -1;
    }

    return 0;
}

static void ecs_notify_exit(Notifier *notifier, void *data)
{
    stop_ecs();
}
static Notifier ecs_exit = { .notify = ecs_notify_exit };

int start_ecs(void)
{
    qemu_thread_create(&ecs_thread_id, "ecs", ecs_initialize, NULL, QEMU_THREAD_JOINABLE);

    emulator_add_exit_notifier(&ecs_exit);

    return 0;
}