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