Use clock_gettime() with CLOCK_MONOTONIC which is not affected by changing system...
[platform/core/multimedia/mmsvc-core.git] / server / src / muse_server_private.c
1 /*
2  * muse-server
3  *
4  * Copyright (c) 2017 Samsung Electronics Co., Ltd. All rights reserved.
5  *
6  * Contact: YoungHun Kim <yh8004.kim@samsung.com>
7  *
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  *
20  */
21
22 #include "muse_server_private.h"
23 #include <sys/file.h>
24 #include <sys/syscall.h>
25 #include <gst/gst.h>
26 #include <syslog.h>
27
28 #if !GLIB_CHECK_VERSION(2, 58, 0)
29 #define G_SOURCE_FUNC(f) ((GSourceFunc) (void (*)(void)) (f))
30 #endif
31
32 #ifdef MUSE_REGISTER_VIP
33 #include <proc_stat.h>
34 #endif
35
36 #ifdef MUSE_USE_LWIPC
37 #include <lwipc.h>
38 #define MUSE_LWIPC_WAIT_TIME                    1000
39 #endif
40
41
42 static const char *channel_name[MUSE_CHANNEL_MAX] = {
43         "msg",
44         "data"
45 };
46
47 static const char *UDS_files[MUSE_CHANNEL_MAX] = {MUSE_SOCK_FILE0, MUSE_SOCK_FILE1};
48
49 static muse_server_h muse_server;
50
51 static const char *module_cmd[MUSE_MODULE_COMMAND_MAX] = {
52         "initialize",
53         "shutdown",
54         "debug_info_dump",
55         "create_server_ack",
56         "resource_not_available",
57         "external_storage_state_changed",
58         "create_caution",
59         "resource_manager_shutdown"
60 };
61
62 static bool _ms_attach(int fd, muse_module_callback connection_handler, gpointer module_idx);
63 static void _ms_create_new_server_from_fd(int fd[], int type);
64 static int _ms_new(muse_channel_e channel);
65 static int _ms_get_pid(int fd);
66 static void _ms_get_module_addr(int fd, intptr_t *module_addr);
67 static void _ms_check_idle_state(void);
68 static gpointer _ms_diag_check_idle_state_thread(gpointer data);
69 static gpointer _ms_diag_check_connection_event_thread(gpointer data);
70 static void _ms_lock_state(void);
71 static void _ms_unlock_state(void);
72 static gboolean _ms_connection_handler(GIOChannel *source, GIOCondition condition, gpointer data);
73 #ifdef MUSE_USE_LWIPC
74 static void _ms_wait_event(void);
75 static void _ms_diag_init(void);
76 static void _ms_diag_deinit(void);
77 static gboolean _ms_idle_cb(gpointer user_data);
78 static int _ms_open_lockfile(void);
79
80 static void _ms_wait_event(void)
81 {
82         const char *lw_event_list[] = { "/run/.wm_ready", "/tmp/avoc_ready" };
83         unsigned int count = sizeof(lw_event_list) / sizeof(char *);
84
85         if (LwipcWaitMultiEvents(lw_event_list, count, true, MUSE_LWIPC_WAIT_TIME, NULL, 0) != 0)
86                 LOGE("Fail to receive Multiple Events");
87 }
88 #endif
89
90 static bool _ms_attach(int fd, muse_module_callback connection_handler, gpointer module_idx)
91 {
92         GIOChannel *channel = NULL;
93         GSource *src = NULL;
94
95         LOGI("Enter");
96
97         muse_return_val_if_fail(muse_server, false);
98         muse_return_val_if_fail(muse_core_fd_is_valid(fd), false);
99
100         channel = g_io_channel_unix_new(fd);
101         muse_return_val_if_fail(channel, false);
102
103         src = g_io_create_watch(channel, G_IO_IN);
104         if (!src) {
105                 LOGE("g_io_create_watch() is failed");
106                 g_io_channel_unref(channel);
107                 return false;
108         }
109
110         g_source_set_callback(src, G_SOURCE_FUNC(connection_handler), module_idx, NULL);
111
112         if (g_source_attach(src, g_main_loop_get_context(muse_server->main_loop)) == 0) {
113                 LOGE("g_source_attach() is failed");
114                 g_io_channel_unref(channel);
115                 return false;
116         }
117
118         g_source_unref(src);
119
120         g_io_channel_unref(channel);
121
122         LOGI("Leave");
123
124         return true;
125 }
126
127 static void _ms_create_new_server_from_fd(int fd[], int type)
128 {
129         int i;
130         char err_msg[MUSE_MSG_LEN_MAX] = {'\0',};
131
132         LOGD("Enter");
133
134         muse_return_if_fail(muse_server);
135
136         muse_server->msg_fd = fd[MUSE_CHANNEL_MSG];
137         muse_server->data_fd = fd[MUSE_CHANNEL_DATA];
138         muse_server->type = type;
139
140         for (i = 0; i < MUSE_CHANNEL_MAX; i++) {
141                 if (!_ms_attach(fd[i], _ms_connection_handler, GINT_TO_POINTER(i))) {
142                         snprintf(err_msg, sizeof(err_msg), "Fail to attach server fd %d", fd[i]);
143
144                         LOGE("%s", err_msg);
145                         ms_terminate(SIGABRT);
146                 }
147         }
148
149         LOGD("Leave");
150 }
151
152 static int _ms_new(muse_channel_e channel)
153 {
154         int fd, errsv;
155         struct sockaddr_un addr_un;
156         socklen_t address_len;
157         char err_msg[MUSE_MSG_LEN_MAX] = {'\0',};
158
159         muse_return_val_if_fail(channel < MUSE_CHANNEL_MAX, MM_ERROR_INVALID_ARGUMENT);
160
161         unlink(UDS_files[channel]);
162
163         /* Create Socket */
164         fd = socket(AF_UNIX, SOCK_STREAM, 0); /* Unix Domain Socket */
165         if (!muse_core_fd_is_valid(fd)) {
166                 strerror_r(errno, err_msg, MUSE_MSG_LEN_MAX);
167                 LOGE("socket failed sock (%d) : %s", errno, err_msg);
168                 return MUSE_ERR;
169         }
170
171         LOGD("muse server fd : %d", fd);
172
173         memset(&addr_un, 0, sizeof(addr_un));
174         addr_un.sun_family = AF_UNIX;
175         strncpy(addr_un.sun_path, UDS_files[channel], sizeof(addr_un.sun_path) - 1);
176         address_len = sizeof(addr_un);
177
178         /* Bind to filename */
179         if (bind(fd, (struct sockaddr *)&addr_un, address_len) < 0) {
180                 errsv = errno;
181                 strerror_r(errsv, err_msg, MUSE_MSG_LEN_MAX);
182                 LOGE("[%d] socket bind failed (%d) %s", fd, errsv, err_msg);
183                 muse_core_log_file_list(UDS_files[channel]);
184                 ms_log_user_group_info();
185                 if (errsv == EADDRINUSE)
186                         unlink(addr_un.sun_path);
187                 close(fd);
188                 return MUSE_ERR;
189         }
190
191         /* Setup listen queue */
192         if (listen(fd, 5) == MUSE_ERR) {
193                 strerror_r(errno, err_msg, MUSE_MSG_LEN_MAX);
194                 LOGE("[%d] listen() failed (%d) %s", fd, errno, err_msg);
195                 muse_core_log_file_list(UDS_files[channel]);
196                 ms_log_user_group_info();
197                 close(fd);
198                 return MUSE_ERR;
199         }
200
201         if (muse_core_set_nonblocking(fd, false) < 0) /* blocking */
202                 LOGE("failed to set server socket to blocking");
203
204         return fd;
205 }
206
207 static int _ms_get_pid(int fd)
208 {
209         char err_msg[MUSE_MSG_LEN_MAX] = {'\0',};
210         struct ucred credentials;
211         socklen_t length;
212
213         length = sizeof(struct ucred);
214         if (getsockopt(fd, SOL_SOCKET, SO_PEERCRED, &credentials, &length) < 0) {
215                 strerror_r(errno, err_msg, MUSE_MSG_LEN_MAX);
216                 LOGE("failed to get the value of credential type %s", err_msg);
217                 return MUSE_ERR;
218         }
219
220         muse_core_update_fd_state(fd);
221
222         return credentials.pid;
223 }
224
225 static void _ms_get_module_addr(int fd, intptr_t *module_addr)
226 {
227         void *jobj;
228         int try_count = 0;
229         bool ret = true;
230         char err_msg[MUSE_MSG_LEN_MAX] = {'\0',};
231         char recv_buf[MUSE_MSG_LEN_MAX] = {'\0',};
232
233         do {
234                 if (muse_core_msg_recv_fd(fd, recv_buf, MUSE_MSG_LEN_MAX, NULL) <= 0) {
235                         strerror_r(errno, err_msg, MUSE_MSG_LEN_MAX);
236                         LOGE("failed to receive message for module %s", err_msg);
237                         return;
238                 }
239
240                 jobj = muse_core_msg_object_new(recv_buf, NULL, NULL);
241                 if (jobj) {
242                         ret = muse_core_msg_object_get_value(MSG_KEY_MODULE_ADDR, jobj, MUSE_TYPE_POINTER, module_addr);
243                         muse_core_msg_object_free(jobj);
244                         if (!ret)
245                                 LOGE("[%d] Error - module_addr %s", try_count, recv_buf);
246                         else
247                                 break;
248                 }
249         } while (++try_count < MS_RECV_TRY_COUNT_MAX);
250 }
251
252 static gboolean _ms_connection_handler(GIOChannel *source, GIOCondition condition, gpointer data)
253 {
254         int server_sockfd, client_sockfd, pid, idx, len;
255         socklen_t client_len;
256         struct sockaddr_un client_address;
257         muse_channel_e channel = GPOINTER_TO_INT(data);
258         muse_module_h m = NULL;
259         muse_module_h peeked_m = NULL;
260         muse_module_h candidate_m = NULL;
261         intptr_t module_addr = 0;
262         GQueue *instance_queue = NULL;
263         ms_connection_t *connection = NULL;
264
265         muse_return_val_if_fail(channel == MUSE_CHANNEL_MSG || channel == MUSE_CHANNEL_DATA, FALSE);
266
267         LOGI("Enter [%s channel]", channel_name[channel]);
268
269         muse_return_val_if_fail(muse_server, FALSE);
270
271         connection = muse_server->connection;
272         muse_return_val_if_fail(connection, FALSE);
273
274         _ms_lock_state();
275
276         if (!ms_is_server_ready()) {
277                 LOGW("Now mused state is not ready...");
278                 _ms_unlock_state();
279                 ms_terminate(SIGABRT);
280         }
281
282         server_sockfd = g_io_channel_unix_get_fd(source);
283         if (!muse_core_fd_is_valid(server_sockfd)) {
284                 LOGE("Critical Error : server %d is invalid", server_sockfd);
285                 _ms_unlock_state();
286                 muse_core_dump_fd_state(server_sockfd);
287                 ms_terminate(SIGABRT);
288         }
289
290         client_len = sizeof(client_address);
291
292         LOGI("[%d] Try to accept...", server_sockfd);
293         client_sockfd = accept(server_sockfd, (struct sockaddr *)&client_address, &client_len);
294         if (!muse_core_fd_is_valid(client_sockfd)) {
295                 LOGE("Critical Error : accept %d is invalid", client_sockfd);
296                 muse_core_dump_fd_state(client_sockfd);
297                 close(server_sockfd);
298                 _ms_unlock_state();
299                 ms_terminate(SIGABRT);
300         }
301
302         LOGI("server : %d client [%s channel] : %d", server_sockfd, channel_name[channel], client_sockfd);
303
304         pid = _ms_get_pid(client_sockfd);
305
306         if (channel == MUSE_CHANNEL_MSG) {
307                 m = g_new0(muse_module_t, 1);
308                 SECURE_LOGI("module [%p]", m);
309                 m->ch[MUSE_CHANNEL_MSG].sock_fd = client_sockfd;
310                 m->pid = pid;
311                 g_mutex_init(&m->dispatch_lock);
312
313                 ms_ipc_create_msg_dispatch_worker(m);
314
315         } else {
316                 _ms_get_module_addr(client_sockfd, &module_addr);
317
318                 ms_connection_lock(connection);
319
320                 instance_queue = connection->instance_q;
321                 len = g_queue_get_length(instance_queue);
322
323                 m = (muse_module_h)module_addr;
324
325                 for (idx = 0; idx < len; idx++) {
326                         peeked_m = (muse_module_h)g_queue_peek_nth(instance_queue, idx);
327                         if (!peeked_m) {
328                                 LOGW("[%d] Make sure if the queue length is changed (%d = %d), which means that it was destroyed somewhere",
329                                         idx, len, g_queue_get_length(instance_queue));
330                                 continue;
331                         }
332
333                         if (peeked_m->pid != pid)
334                                 continue;
335
336                         if (!m) {
337                                 if (candidate_m) {
338                                         LOGE("muse-server can't support the error case which there are several modules now");
339                                         ms_connection_unlock(connection);
340                                         goto out;
341                                 }
342
343                                 if (!muse_core_fd_is_valid(peeked_m->ch[MUSE_CHANNEL_DATA].sock_fd))
344                                         candidate_m = peeked_m;
345                                 else
346                                         SECURE_LOGW("already paired module %p", peeked_m);
347
348                                 continue;
349                         }
350
351                         if (m != peeked_m)
352                                 continue;
353
354                         if (muse_core_fd_is_valid(m->ch[MUSE_CHANNEL_DATA].sock_fd)) {
355                                 SECURE_LOGE("[%d] %s pid %d %p you had better check if instance destroy completed properly",
356                                         client_sockfd, ms_config_get_host_name(m->idx), pid, m);
357                                 ms_connection_unlock(connection);
358                                 goto out;
359                         }
360
361                         m->ch[MUSE_CHANNEL_DATA].sock_fd = client_sockfd;
362                         SECURE_LOGI("%s (pid %d) module : %p module addr from client : %p",
363                                 ms_config_get_host_name(m->idx), pid, m, (void *)module_addr);
364                         break;
365                 }
366
367                 if (candidate_m) {
368                         m = candidate_m;
369                         m->ch[MUSE_CHANNEL_DATA].sock_fd = client_sockfd;
370                         SECURE_LOGW("[%d] %s pid %d %p restore module address at the only one null data channel",
371                                 client_sockfd, ms_config_get_host_name(m->idx), pid, m);
372                 }
373
374                 ms_connection_unlock(connection);
375
376                 ms_ipc_create_data_dispatch_worker(m);
377         }
378
379         muse_core_get_cur_time(&muse_server->tv, NULL);
380
381         LOGW("connected time %lu", muse_server->tv.tv_sec);
382
383         _ms_unlock_state();
384
385         LOGI("Leave");
386
387         return TRUE;
388 out:
389         close(server_sockfd);
390         close(client_sockfd);
391
392         if (m) {
393                 if (channel == MUSE_CHANNEL_MSG)
394                         g_free(m);
395                 else
396                         muse_core_connection_close(m->ch[MUSE_CHANNEL_MSG].sock_fd);
397         }
398
399         _ms_unlock_state();
400
401         LOGE("FALSE");
402
403         return FALSE;
404 }
405
406 static void _ms_check_idle_state(void)
407 {
408         ms_connection_t *connection = NULL;
409         ms_config_t *conf = NULL;
410         int instance_number, period;
411         uint32_t elapsed_time;
412         struct timespec tv;
413         static int period_idx = 1;
414
415         muse_return_if_fail(muse_server);
416         muse_return_if_fail(muse_server->state == MUSE_SERVER_STATE_READY);
417
418         connection = muse_server->connection;
419         muse_return_if_fail(connection);
420
421         conf = muse_server->conf;
422         muse_return_if_fail(conf);
423
424         period = ms_config_get_log_period();
425
426         if (muse_server->tv.tv_sec == 0)
427                 return;
428
429         muse_core_get_cur_time(&tv, NULL);
430
431         elapsed_time = tv.tv_sec - muse_server->tv.tv_sec;
432
433         ms_connection_lock(connection);
434
435         instance_number = g_queue_get_length(connection->instance_q);
436
437         if (elapsed_time >= (uint32_t)(period * period_idx)) {
438                 LOGW("[#%d] %u sec [period %d] [last connected time %lu] total number of modules = %d ( %s)", period_idx,
439                         elapsed_time, period, muse_server->tv.tv_sec, instance_number, muse_server->instance_pid_info);
440                 period_idx++;
441         }
442
443         ms_connection_unlock(connection);
444
445         if (conf->is_on_demand) {
446                 if (instance_number == 0 && elapsed_time >= (uint32_t)ms_config_get_max_idle_time()) {
447                         LOGE("Timeout exit !!! [Idle time] %u sec", elapsed_time);
448                         ms_remove_ready_file();
449                         exit(EXIT_SUCCESS);
450                 }
451         }
452 }
453
454 static gpointer _ms_diag_check_idle_state_thread(gpointer data)
455 {
456         int idle_state_wait_time = ms_config_get_idle_state_wait_time();
457
458         muse_return_val_if_fail(muse_server, NULL);
459         muse_return_val_if_fail(idle_state_wait_time > 0, NULL);
460
461         while (ms_is_server_ready()) {
462                 _ms_check_idle_state();
463                 sleep(idle_state_wait_time);
464         }
465
466         return NULL;
467 }
468
469 static gpointer _ms_diag_check_connection_event_thread(gpointer data)
470 {
471         ms_diag_t *d;
472         ms_diag_msg_t *dm = NULL;
473         muse_return_val_if_fail(muse_server, NULL);
474
475         d = &muse_server->diag;
476
477         while (ms_is_server_ready()) {
478                 dm = (ms_diag_msg_t *)g_async_queue_pop(d->msg_aq);
479                 if (!dm)
480                         continue;
481
482                 LOGD("[%p] POP message (thread stop ? %d [%s])", dm, dm->thread_stop, ms_get_command_string(dm->cmd));
483
484                 if (dm->thread_stop) {
485                         g_free(dm);
486                         break;
487                 }
488
489                 if (dm->cmd == API_CREATE) {
490                         /* can be updated if connection at the next patch */
491                 } else if (dm->cmd == API_DESTROY) {
492                         ms_check_cpu_memory();
493                 }
494
495                 g_free(dm);
496         }
497
498         return NULL;
499 }
500
501 static void _ms_lock_state(void)
502 {
503         muse_return_if_fail(muse_server);
504         g_mutex_lock(&muse_server->state_lock);
505 }
506
507 static void _ms_unlock_state(void)
508 {
509         muse_return_if_fail(muse_server);
510         g_mutex_unlock(&muse_server->state_lock);
511 }
512
513 static void _ms_diag_init(void)
514 {
515         ms_diag_t *d;
516         char err_msg[MUSE_MSG_LEN_MAX] = {'\0',};
517         GError *error = NULL;
518
519         muse_return_if_fail(muse_server);
520
521         d = &muse_server->diag;
522
523         d->idle_state_thread = g_thread_try_new("diag_idle_state",
524                 _ms_diag_check_idle_state_thread, muse_server->main_loop, &error);
525         if (!d->idle_state_thread) {
526                 snprintf(err_msg, sizeof(err_msg), "diag_idle_state_thread creation failed : %s", error->message);
527                 LOGE("%s", err_msg);
528                 g_error_free(error);
529                 ms_log_process_info(muse_server->pid);
530         }
531
532         d->msg_aq = g_async_queue_new_full(g_free);
533         muse_return_if_fail(d->msg_aq);
534
535         d->conn_event_thread = g_thread_try_new("diag_connection",
536                 _ms_diag_check_connection_event_thread, muse_server->main_loop, &error);
537         if (!d->conn_event_thread) {
538                 snprintf(err_msg, sizeof(err_msg), "diag_connection_event_thread creation failed : %s", error->message);
539                 LOGE("%s", err_msg);
540                 g_error_free(error);
541                 ms_log_process_info(muse_server->pid);
542         }
543 }
544
545 static void _ms_diag_deinit(void)
546 {
547         ms_diag_t *d;
548         ms_diag_msg_t *dm;
549
550         LOGD("Enter");
551
552         muse_return_if_fail(muse_server);
553
554         d = &muse_server->diag;
555
556         dm = g_new0(ms_diag_msg_t, 1);
557
558         dm->thread_stop = TRUE;
559         LOGI("[%p] g_async_queue_push", dm);
560         g_async_queue_push_front(d->msg_aq, (gpointer)dm);
561
562         if (d->idle_state_thread) {
563                 g_thread_join(d->idle_state_thread);
564                 d->idle_state_thread = NULL;
565         }
566
567         if (d->conn_event_thread) {
568                 g_thread_join(d->conn_event_thread);
569                 d->conn_event_thread = NULL;
570         }
571
572         g_async_queue_unref(d->msg_aq);
573         d->msg_aq = NULL;
574 }
575
576 static gboolean _ms_idle_cb(gpointer user_data)
577 {
578         struct timespec tv;
579
580         if (!ms_create_ready_file())
581                 LOGE("%s file creation is failed", MUSE_SERVER_READY);
582
583         _ms_diag_init();
584
585         muse_core_get_cur_time(&tv, NULL);
586
587         LOGW("muse server is completed to ready %lu", tv.tv_sec);
588
589         return G_SOURCE_REMOVE;
590 }
591
592 static void _ms_init(void)
593 {
594         int idx;
595
596         LOGD("Enter");
597
598         muse_server->system = g_new0(ms_system_t, 1);
599         ms_system_init(muse_server->system);
600
601         muse_server->conf = g_new0(ms_config_t, 1);
602         ms_config_init(muse_server->conf);
603
604         muse_server->log = g_new0(ms_log_t, 1);
605         ms_log_init(muse_server->log);
606
607         muse_server->security = g_new0(ms_security_t, 1);
608         ms_security_init(muse_server->security);
609
610         for (idx = 0; idx < muse_server->conf->host_cnt; idx++) {
611                 muse_server->module[idx] = g_new0(ms_module_t, 1);
612                 muse_server->module[idx]->idx = idx;
613                 ms_module_init(muse_server->module[idx]);
614         }
615
616 #ifdef MUSE_USE_WATCHDOG
617         muse_server->watchdog = g_new0(ms_watchdog_t, 1);
618         if (ms_watchdog_init(muse_server->watchdog) != MM_ERROR_NONE)
619                 LOGE("Fail to initialize server watchdog");
620 #endif
621
622         muse_server->connection = g_new0(ms_connection_t, 1);
623         ms_connection_init(muse_server->connection);
624
625         ms_signal_init();
626
627         g_mutex_init(&muse_server->state_lock);
628
629         muse_core_create_fd_table();
630
631         muse_server->cpu_threshold = ms_config_get_cpu_threshold();
632
633         muse_server->main_loop = g_main_loop_new(NULL, FALSE);
634         muse_return_if_fail(muse_server->main_loop);
635
636         LOGD("Leave");
637 }
638
639 static int _ms_open_lockfile(void)
640 {
641         int fd, already_running;
642         char err_msg[MUSE_MSG_LEN_MAX] = {'\0',};
643         char *lockfile = NULL;
644
645         muse_return_val_if_fail(muse_server, MUSE_ERR);
646
647         lockfile = ms_config_get_lockfile();
648         muse_return_val_if_fail(lockfile, MUSE_ERR);
649
650         muse_core_remove_symlink((const char *)lockfile);
651         fd = open(lockfile, O_RDONLY);
652         if (fd == -1 && errno != ENOENT) {
653                 /* Cannot open file even though file exists. */
654                 snprintf(err_msg, sizeof(err_msg), "Cannot open lock file %s", lockfile);
655                 LOGE("open failed : %s", err_msg);
656                 return MUSE_ERR;
657         } else if (fd != -1) {
658                 already_running = flock(fd, LOCK_EX | LOCK_NB) == -1;
659                 close(fd);
660                 if (already_running) {
661                         LOGE("File already locked. There's already a server running");
662                         return MUSE_ERR;
663                 }
664         }
665
666         /* Lock file does not exist, or is not locked. Create a new lockfile and lock it. */
667         fd = open(lockfile, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
668         if (fd == -1) {
669                 LOGE("dataserver: Cannot create lock file");
670                 return MUSE_ERR;
671         }
672
673         if (flock(fd, LOCK_EX | LOCK_NB) != 0) {
674                 LOGE("Can't lock the lock file \"%s\". " "Is another instance running?", lockfile);
675                 close(fd);
676                 return MUSE_ERR;
677         }
678
679         close(fd);
680
681         return MM_ERROR_NONE;
682 }
683
684 void ms_setup_syslog(void)
685 {
686         int flags = LOG_CONS|LOG_NDELAY|LOG_PID;
687         if (isatty(STDOUT_FILENO))
688                 flags |= LOG_PERROR;
689
690         openlog("mused", flags, LOG_DAEMON);
691         LOGD("openlog - mused");
692 }
693
694 void ms_fork(int *notify_fd)
695 {
696         pid_t pid;
697         int fds[2];
698         char err_msg[MUSE_MSG_LEN_MAX] = {'\0',};
699         char msg[MUSE_MSG_LEN_MAX] = {'\0',};
700
701         if (pipe(fds) == MUSE_ERR) {
702                 strerror_r(errno, err_msg, MUSE_MSG_LEN_MAX);
703                 LOGE("Failed to create pipe to get child status: %s", err_msg);
704                 exit(EXIT_FAILURE);
705         }
706
707         if ((pid = fork()) < 0) {
708                 strerror_r(errno, err_msg, MUSE_MSG_LEN_MAX);
709                 LOGE("Error: fork() failed: %s", err_msg);
710                 exit(EXIT_FAILURE);
711         } else if (pid != 0) {
712                 close(fds[1]);
713                 /* Read in a string from the pipe */
714                 if (read(fds[0], msg, sizeof(msg)) <= 0) {
715                         LOGE("Failed to read from a file descriptor [%d]", fds[0]);
716                         close(fds[0]);
717                         return;
718                 }
719                 close(fds[0]);
720
721                 /* Parent process closes up output side of pipe */
722                 if (!strcmp(msg, MSG_DONE)) {
723                         LOGI("Successfully daemonized");
724                         exit(EXIT_SUCCESS);
725                 } else {
726                         LOGE("Daemonizing failed after fork");
727                         exit(EXIT_FAILURE);
728                 }
729         } else if (pid == 0) {
730                 /* Child process closes up input side of pipe */
731                 close(fds[0]);
732                 *notify_fd = fds[1];
733         }
734 }
735
736 pid_t ms_daemonize(int *notify_fd)
737 {
738         pid_t pid;
739         int fd, result;
740
741         muse_return_val_if_fail(notify_fd, MUSE_ERR);
742
743         ms_fork(notify_fd);
744
745         if ((pid = setsid()) < 0) {
746                 LOGE("create new session");
747                 exit(EXIT_FAILURE);
748         }
749
750         /* change the file mode mask */
751         umask(0);
752
753         result = chdir("/");
754         LOGD("result = %d sid: %d pgid: %d pid: %d ppid: %d", result, (int)getsid(0), (int)getpgid(0), (int)pid, (int)getppid());
755
756         /* redirect fds to /dev/null */
757         fd = open("/dev/null", O_RDWR);
758         if (!muse_core_fd_is_valid(fd)) {
759                 LOGE("Critical Error : %d is invalid", fd);
760                 exit(EXIT_SUCCESS);
761         }
762
763         close(STDIN_FILENO);
764         close(STDOUT_FILENO);
765         close(STDERR_FILENO);
766
767         dup2(fd, STDIN_FILENO);
768         dup2(fd, STDOUT_FILENO);
769         dup2(fd, STDERR_FILENO);
770
771         close(fd);
772
773         return pid;
774 }
775
776 void ms_daemonize_complete(int notify_fd)
777 {
778         LOGD("Enter");
779
780         muse_return_if_fail(muse_core_fd_is_valid(notify_fd));
781
782 #ifdef MUSE_REGISTER_VIP
783         proc_stat_set_vip_process();
784 #endif
785
786         write(notify_fd, MSG_DONE, strlen(MSG_DONE) + 1);
787         LOGW("[%d] Notify parent process that child initialization is done", notify_fd);
788         close(notify_fd);
789
790         LOGD("Leave");
791 }
792
793 void ms_gst_init(char **cmd)
794 {
795         gint argc = 0;
796         gchar **argv = NULL;
797         GError *err = NULL;
798         gboolean ret = FALSE;
799         int gst_param_cnt;
800
801 #ifdef MUSE_TTRACE_LOG
802         trace_begin("MUSE:gst_init");
803 #endif
804
805         gst_param_cnt = ms_config_get_gst_param_cnt();
806
807         /* add gst_param */
808         argv = g_malloc0(sizeof(gchar *) * (gst_param_cnt + 1));
809
810         argv[argc++] = (gchar *)cmd[0];
811         for (; argc <= gst_param_cnt; argc++) {
812                 argv[argc] = ms_config_get_gst_param_str(argc - 1);
813                 LOGI("%d %s", argc, argv[argc]);
814         }
815
816         /* initializing gstreamer */
817         ret = gst_init_check(&argc, &argv, &err);
818         if (!ret) {
819                 LOGE("Could not initialize GStreamer: %s ", err ? err->message : "unknown error occurred");
820                 if (err)
821                         g_error_free(err);
822         }
823
824         LOGI("gst_init_check is completed");
825
826         /* release */
827         g_free(argv);
828
829         LOGI("complete to initialize gstreamer");
830
831 #ifdef MUSE_TTRACE_LOG
832         trace_end();
833 #endif
834 }
835
836 void ms_gst_preload_plugin(void)
837 {
838         char *token = NULL;
839         char *saveptr = NULL;
840         char plugin_path[128];
841         const char *delimeters = " ,";
842         gchar *gst_preload_plugins = g_strdup(ms_config_get_gst_preload_plugins());
843         GstPlugin *plugin = NULL;
844
845         muse_return_if_fail(gst_preload_plugins);
846
847         LOGI("preload plugins [%s]", gst_preload_plugins);
848
849         token = strtok_r(gst_preload_plugins, delimeters, &saveptr);
850         while (token) {
851                 snprintf(plugin_path, sizeof(plugin_path), "%s/gstreamer-1.0/libgst%s.so", LIBDIR, token);
852
853                 LOGI("    plugin path : %s", plugin_path);
854
855                 plugin = gst_plugin_load_file(plugin_path, NULL);
856                 if (plugin)
857                         gst_object_unref(plugin);
858                 else
859                         LOGW("failed to load plugin [%s]", plugin_path);
860
861                 token = strtok_r(NULL, delimeters, &saveptr);
862         }
863
864         g_free(gst_preload_plugins);
865
866         LOGI("Leave");
867 }
868
869 int ms_pidfile_create(const char *path, pid_t pid)
870 {
871         int fd;
872         struct flock lock;
873         char pid_buf[MUSE_MSG_LEN] = {'\0',};
874         char err_msg[MUSE_MSG_LEN_MAX] = {'\0',};
875
876         muse_return_val_if_fail(path, MM_ERROR_INVALID_ARGUMENT);
877         muse_core_remove_symlink(path);
878         fd = open(path, O_WRONLY | O_CREAT, (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH));
879
880         if (!muse_core_fd_is_valid(fd)) {
881                 strerror_r(errno, err_msg, MUSE_MSG_LEN_MAX);
882                 LOGE("Fail to open pidfile [%s] : %s", path, err_msg);
883                 return MM_ERROR_FILE_NOT_FOUND;
884         }
885
886         lock.l_type = F_WRLCK;
887         lock.l_start = 0;
888         lock.l_whence = SEEK_SET;
889         lock.l_len = 0;
890
891         if (fcntl(fd, F_SETLK, &lock) < 0) {
892                 if (errno != EACCES && errno != EAGAIN) {
893                         strerror_r(errno, err_msg, MUSE_MSG_LEN_MAX);
894                         LOGE("Fail to lock pidfile [%s] : %s", path, err_msg);
895                 } else {
896                         LOGE("process is already running");
897                 }
898                 close(fd);
899                 return MM_ERROR_FILE_INTERNAL;
900         }
901
902         if (ftruncate(fd, 0) < 0) {
903                 strerror_r(errno, err_msg, MUSE_MSG_LEN_MAX);
904                 LOGE("Fail to truncate pidfile [%s] : %s", path, err_msg);
905                 close(fd);
906                 return MM_ERROR_FILE_INTERNAL;
907         }
908
909         memset(pid_buf, 0, sizeof(pid_buf));
910         snprintf(pid_buf, sizeof(pid_buf), "%u", pid);
911
912         if (write(fd, pid_buf, strlen(pid_buf)) != (int)strlen(pid_buf)) {
913                 strerror_r(errno, err_msg, MUSE_MSG_LEN_MAX);
914                 LOGE("Fail to write pid to pidfile [%s] : %s", path, err_msg);
915                 close(fd);
916                 return MM_ERROR_FILE_WRITE;
917         }
918
919         close(fd);
920         return MM_ERROR_NONE;
921 }
922
923 void ms_init(char **argv)
924 {
925         int idx;
926         int notify_fd;
927         muse_module_cmd_dispatchfunc *cmd_dispatcher = NULL;
928
929         LOGD("Enter");
930
931         muse_server = g_new0(muse_server_t, 1);
932
933         ms_setup_syslog();
934
935         muse_server->pid = ms_daemonize(&notify_fd);
936
937         if (ms_pidfile_create(MUSE_DEFAULT_PIDFILE, muse_server->pid) != MM_ERROR_NONE)
938                 exit(EXIT_FAILURE);
939         else
940                 LOGD("MUSE_DEFAULT_PIDFILE(%s) file was created", MUSE_DEFAULT_PIDFILE);
941
942         _ms_init();
943
944         muse_return_if_fail(_ms_open_lockfile() == MM_ERROR_NONE);
945
946         ms_new();
947
948         ms_daemonize_complete(notify_fd);
949
950 #ifdef MUSE_TTRACE_LOG
951         trace_end();
952 #endif
953
954         ms_system_subscribe_external_event(muse_server->system);
955
956 #ifdef MUSE_USE_WATCHDOG
957         if (!ms_watchdog_attach(muse_server->watchdog)) {
958                 LOGE("watchdog thread failed");
959                 ms_log_process_info(muse_server->pid);
960                 return;
961         }
962 #endif
963
964         ms_gst_init(argv);
965
966 #ifdef MUSE_TTRACE_LOG
967         trace_begin("MUSE:preloading module");
968 #endif
969         for (idx = 0; idx < ms_config_get_host_cnt(); idx++) {
970                 if (0 == strncmp(ms_config_get_preloaded_value(idx), "yes", strlen("yes") + 1)) {
971                         g_module_symbol(ms_module_open(idx), CMD_DISPATCHER, (gpointer *)&cmd_dispatcher);
972                         if (cmd_dispatcher && cmd_dispatcher[MUSE_MODULE_COMMAND_INITIALIZE])
973                                 cmd_dispatcher[MUSE_MODULE_COMMAND_INITIALIZE](NULL);
974                 }
975         }
976 #ifdef MUSE_TTRACE_LOG
977         trace_end();
978 #endif
979
980 #ifdef MUSE_TTRACE_LOG
981         trace_begin("MUSE:preloading GST module");
982 #endif
983         ms_gst_preload_plugin();
984 #ifdef MUSE_TTRACE_LOG
985         trace_end();
986 #endif
987
988 #ifdef MUSE_GCOV_TEST
989         muse_core_setenv("GCOV_PREFIX", "/tmp", 1);
990 #endif
991
992         LOGD("Leave");
993 }
994
995 muse_server_h ms_get_instance(void)
996 {
997         return muse_server;
998 }
999
1000 gboolean ms_check_module_idx(int idx)
1001 {
1002         int module_cnt = ms_config_get_host_cnt();
1003
1004         if (idx < 0 || idx >= module_cnt) {
1005                 LOGE("%d error - the number of modules is %d", idx, module_cnt);
1006                 return FALSE;
1007         }
1008
1009         return TRUE;
1010 }
1011
1012 ms_module_t *ms_get_module_instance(int idx)
1013 {
1014         muse_return_val_if_fail(ms_check_module_idx(idx), NULL);
1015
1016         return muse_server->module[idx];
1017 }
1018
1019 int ms_deinit(void)
1020 {
1021         int retval = MUSE_ERR;
1022         int idx;
1023
1024         LOGD("Enter");
1025
1026         muse_return_val_if_fail(muse_server, retval);
1027         muse_return_val_if_fail(muse_server->conf, retval);
1028         muse_return_val_if_fail(muse_server->connection, retval);
1029         muse_return_val_if_fail(muse_server->log, retval);
1030         muse_return_val_if_fail(muse_server->security, retval);
1031         muse_return_val_if_fail(muse_server->watchdog, retval);
1032
1033         ms_recursive_rmdir(MUSE_DATA_ROOT_PATH);
1034
1035         ms_set_state(MUSE_SERVER_STATE_IDLE);
1036
1037         _ms_diag_deinit();
1038
1039 #ifdef MUSE_USE_WATCHDOG
1040         ms_watchdog_detach(muse_server->watchdog);
1041
1042         if (ms_watchdog_deinit(muse_server->watchdog) == MM_ERROR_NONE)
1043                 free(muse_server->watchdog);
1044         else
1045                 LOGE("Fail to deinitialize server watchdog");
1046 #endif
1047
1048         ms_remove_ready_file();
1049
1050         retval = muse_server->retval;
1051         muse_core_fd_close(muse_server->msg_fd);
1052         muse_core_fd_close(muse_server->data_fd);
1053         for (idx = 0; idx < MUSE_CHANNEL_MAX; idx++) {
1054                 if (remove(UDS_files[idx]) == MUSE_ERR)
1055                         LOGE("remove %s failed", UDS_files[idx]);
1056         }
1057
1058         if (remove(MUSE_DEFAULT_PIDFILE) == -1)
1059                 LOGE("remove %s failed [errno : %d]", MUSE_DEFAULT_PIDFILE, errno);
1060
1061         for (idx = 0; idx < muse_server->conf->host_cnt; idx++)
1062                 ms_module_deinit(muse_server->module[idx]);
1063
1064         ms_security_deinit(muse_server->security);
1065         muse_server->security = NULL;
1066
1067         ms_system_deinit(muse_server->system);
1068         muse_server->system = NULL;
1069
1070         ms_log_deinit(muse_server->log);
1071         muse_server->log = NULL;
1072
1073         ms_config_deinit(muse_server->conf);
1074         muse_server->conf = NULL;
1075
1076         ms_connection_deinit(muse_server->connection);
1077         muse_server->connection = NULL;
1078
1079         muse_core_destroy_fd_table();
1080
1081         ms_deinit_bufmgr();
1082
1083         g_mutex_clear(&muse_server->state_lock);
1084
1085         g_free(muse_server);
1086         muse_server = NULL;
1087
1088         LOGD("Leave");
1089         return retval;
1090 }
1091
1092 void ms_check_cpu_memory(void)
1093 {
1094         int used_pss, memory_threshold, cpu_usage;
1095         char err_msg[MUSE_MSG_LEN_MAX] = {'\0',};
1096         ms_connection_t *connection = NULL;
1097
1098         muse_return_if_fail(muse_server);
1099
1100         connection = muse_server->connection;
1101         muse_return_if_fail(connection);
1102
1103         ms_connection_lock(connection);
1104
1105         if (g_queue_is_empty(connection->instance_q) && ms_is_server_ready()) {
1106                 used_pss = ms_system_get_memory_usage(muse_server->pid);
1107                 cpu_usage = muse_core_get_process_cpu_usage(muse_server->pid);
1108
1109                 LOGW("[%d] Proportional set size %d (KByte) (CPU %d %%)", muse_server->pid, used_pss, cpu_usage);
1110                 memory_threshold = ms_config_get_memory_threshold();
1111
1112                 if (used_pss >= memory_threshold || cpu_usage >= muse_server->cpu_threshold) {
1113                         ms_set_state(MUSE_SERVER_STATE_IDLE);
1114                         ms_log_process_info(muse_server->pid);
1115
1116                         snprintf(err_msg, sizeof(err_msg), "[Memory Leak] %d >= %d (KByte) [CPU] %d >= %d %%",
1117                                 used_pss, memory_threshold, cpu_usage, muse_server->cpu_threshold);
1118
1119                         LOGE("%s", err_msg);
1120                         ms_connection_unlock(connection);
1121                         ms_terminate(SIGTERM);
1122                 }
1123
1124                 muse_core_remove_all_fd_table();
1125         } else {
1126                 LOGI("skip cpu memory check due to instance queue length : %d", g_queue_get_length(connection->instance_q));
1127         }
1128
1129         ms_connection_unlock(connection);
1130 }
1131
1132 void ms_new(void)
1133 {
1134         int fd[MUSE_CHANNEL_MAX];
1135         int i, j;
1136
1137         for (i = 0; i < MUSE_CHANNEL_MAX; i++) {
1138                 if (ms_config_is_on_demand() && i == MUSE_CHANNEL_MSG)
1139                         fd[i] = SD_LISTEN_FDS_START;
1140                 else
1141                         fd[i] = _ms_new(i);
1142
1143                 if (!muse_core_fd_is_valid(fd[i])) {
1144                         LOGE("Failed to create socket server %d", i);
1145                         for (j = 0; j < i; j++)
1146                                 close(fd[j]);
1147                         return;
1148                 }
1149         }
1150
1151         _ms_create_new_server_from_fd(fd, READ | PERSIST);
1152 }
1153
1154 void ms_run(void)
1155 {
1156         LOGW("Enter");
1157
1158         muse_return_if_fail(muse_server->main_loop);
1159
1160         muse_return_if_fail(g_idle_add_full(G_PRIORITY_HIGH, _ms_idle_cb, NULL, NULL) > 0);
1161
1162         LOGI("g_main_loop_run");
1163         g_main_loop_run(muse_server->main_loop);
1164
1165         LOGW("Leave");
1166 }
1167
1168 void ms_cmd_dispatch(muse_module_h m, muse_module_command_e cmd)
1169 {
1170         muse_module_cmd_dispatchfunc *cmd_dispatcher = NULL;
1171
1172         if (m->ch[MUSE_CHANNEL_MSG].dll_handle &&
1173                 g_module_symbol(m->ch[MUSE_CHANNEL_MSG].dll_handle, CMD_DISPATCHER, (gpointer *)&cmd_dispatcher)) {
1174                 if (cmd_dispatcher && cmd_dispatcher[cmd])
1175                         cmd_dispatcher[cmd](m);
1176         }
1177 }
1178
1179 void ms_terminate(int signo)
1180 {
1181         muse_return_if_fail(muse_server);
1182
1183         ms_set_state(MUSE_SERVER_STATE_IDLE);
1184
1185         LOGE("send signal %d to process %d", signo, muse_server->pid);
1186         raise(signo);
1187 }
1188
1189 int ms_get_pid(muse_module_h m)
1190 {
1191         muse_return_val_if_fail(m, MUSE_ERR);
1192         return m->pid;
1193 }
1194
1195 void ms_log_process_info(int pid)
1196 {
1197         muse_core_log_process_thread_info(pid);
1198
1199         muse_core_log_process_opened_fds(pid);
1200
1201         muse_core_log_process_cpu_memory(pid);
1202 }
1203
1204 void ms_log_user_group_info(void)
1205 {
1206         uid_t uid;
1207         gid_t gid;
1208         char buffer[MUSE_MSG_MAX_LENGTH];
1209         struct passwd pwbuf;
1210         struct passwd *pwbufp;
1211         struct group gbuf;
1212         struct group *gbufp;
1213
1214         uid = getuid();
1215         gid = getgid();
1216
1217         getpwuid_r(uid, &pwbuf, buffer, sizeof(buffer), &pwbufp);
1218         muse_return_if_fail(pwbufp);
1219
1220         getgrgid_r(gid, &gbuf, buffer, sizeof(buffer), &gbufp);
1221         muse_return_if_fail(gbufp);
1222
1223         LOGE("user [%s : %lu] group [%s : %lu]", pwbufp->pw_name, (unsigned long)uid, gbufp->gr_name, (unsigned long)gid);
1224 }
1225
1226 gboolean ms_is_log_enabled(void)
1227 {
1228         return ms_config_is_log_enabled();
1229 }
1230
1231 gboolean ms_init_bufmgr(void)
1232 {
1233         LOGD("Enter");
1234
1235         muse_return_val_if_fail(muse_server, FALSE);
1236
1237         muse_server->bufmgr = tbm_bufmgr_init(-1);
1238         if (!muse_server->bufmgr) {
1239                 LOGE("Error - tbm_bufmgr_init");
1240                 ms_log_user_group_info();
1241                 return FALSE;
1242         }
1243
1244         LOGD("Leave bufmgr: %p", muse_server->bufmgr);
1245
1246         return TRUE;
1247 }
1248
1249 void ms_deinit_bufmgr(void)
1250 {
1251         LOGD("Enter");
1252
1253         muse_return_if_fail(muse_server);
1254         muse_return_if_fail(muse_server->bufmgr);
1255
1256         tbm_bufmgr_deinit(muse_server->bufmgr);
1257
1258         LOGD("Leave");
1259 }
1260
1261 void ms_cmd_dispatch_foreach_func(gpointer data, gpointer user_data)
1262 {
1263         muse_module_h m = (muse_module_h)data;
1264         ms_cmd_dispatcher_info_t *dispatch = (ms_cmd_dispatcher_info_t *)user_data;
1265         muse_module_command_e cmd;
1266         muse_external_storage_info_t *storage;
1267
1268         muse_return_if_fail(muse_server);
1269         muse_return_if_fail(m);
1270         muse_return_if_fail(dispatch);
1271
1272         cmd = dispatch->cmd;
1273
1274         if (cmd == MUSE_MODULE_COMMAND_EXTERNAL_STORAGE_STATE_CHANGED) {
1275                 storage = &dispatch->storage;
1276                 LOGD("external storage id %d state %d path %s", storage->id, storage->state, storage->path);
1277                 muse_server_set_user_data(m, (void *)storage);
1278         }
1279
1280         ms_cmd_dispatch(m, cmd);
1281         SECURE_LOGI("[%s] module %p (%s)", module_cmd[cmd], m, muse_server->conf->host[m->idx]);
1282
1283         if (cmd == MUSE_MODULE_COMMAND_EXTERNAL_STORAGE_STATE_CHANGED)
1284                 muse_server_set_user_data(m, NULL);
1285 }
1286
1287 void ms_set_state(ms_state_e state)
1288 {
1289         muse_return_if_fail(muse_server);
1290
1291         g_mutex_lock(&muse_server->state_lock);
1292         muse_server->state = state;
1293         g_mutex_unlock(&muse_server->state_lock);
1294 }
1295
1296 gboolean ms_is_server_ready(void)
1297 {
1298         muse_return_val_if_fail(muse_server, FALSE);
1299
1300         return muse_server->state == MUSE_SERVER_STATE_READY;
1301 }
1302
1303 gboolean ms_create_ready_file(void)
1304 {
1305         LOGD("Enter");
1306 #ifndef MUSE_USE_LWIPC
1307         int ready_fd;
1308 #endif
1309
1310 #ifdef MUSE_USE_LWIPC
1311         _ms_wait_event();
1312
1313         ms_set_state(MUSE_SERVER_STATE_READY);
1314
1315         if (LwipcEventDone(MUSE_SERVER_READY) < 0) {
1316                 LOGE("Fail to send server ready done event");
1317                 return FALSE;
1318         }
1319 #else
1320         ready_fd = creat(MUSE_SERVER_READY, 0644);
1321         if (muse_core_fd_is_valid(ready_fd)) {
1322                 LOGD("MUSE_SERVER_READY(%s) file was created", MUSE_SERVER_READY);
1323
1324                 close(ready_fd);
1325                 ms_set_state(MUSE_SERVER_STATE_READY);
1326         } else {
1327                 LOGE("[%d] Fail to create MUSE_SERVER_READY(%s)", ready_fd, MUSE_SERVER_READY);
1328                 return FALSE;
1329         }
1330 #endif
1331         LOGD("Leave");
1332
1333         return TRUE;
1334
1335 }
1336
1337 void ms_remove_ready_file(void)
1338 {
1339 #ifdef MUSE_USE_LWIPC
1340         (void)LwipcResetEvent(MUSE_SERVER_READY);
1341 #else
1342         (void)unlink(MUSE_SERVER_READY);
1343         (void)unlink(MUSE_DEFAULT_PIDFILE);
1344 #endif
1345 }
1346
1347 const char *ms_get_command_string(int cmd)
1348 {
1349         if (cmd == API_CREATE)
1350                 return "connect";
1351         else if (cmd == API_DESTROY)
1352                 return "disconnect";
1353         else
1354                 LOGE("Invalid value of cmd (%d)", cmd);
1355
1356         return "Invalid value of cmd";
1357 }
1358