1 /* Copyright (C) 1997 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
3 /** \file server.c Paraslash's main server. */
5 #include <netinet/in.h>
6 #include <sys/socket.h>
10 #include <sys/types.h>
11 #include <arpa/inet.h>
16 #include "server.lsg.h"
31 #include "close_on_fork.h"
36 #include "user_list.h"
40 /** Array of error strings. */
43 __printf_2_3 void (*para_log)(int, const char*, ...) = daemon_log;
45 /** Shut down non-authorized connections after that many seconds. */
46 #define ALARM_TIMEOUT 10
49 * Pointer to shared memory area for communication between para_server
50 * and its children. Exported to vss.c, command.c and to afs.
52 struct misc_meta_data *mmd;
55 * The active value for all config options of para_server.
57 * It is computed by merging the parse result of the command line options with
58 * the parse result of the config file.
60 struct lls_parse_result *server_lpr = NULL;
62 /* Command line options (no config file options). Used in handle_sighup(). */
63 static struct lls_parse_result *cmdline_lpr;
66 * A random number used to "authenticate" the afs connection.
68 * para_server picks this number by random before it forks the afs process. The
69 * command handlers know this number as well and write it to the afs socket,
70 * together with the id of the shared memory area which contains the payload of
71 * the afs command. A local process has to know this number to abuse the afs
72 * service provided by the local socket.
74 uint32_t afs_socket_cookie;
76 /** The mutex protecting the shared memory area containing the mmd struct. */
79 /* Serializes log output. */
82 static struct sched sched;
83 static struct signal_task *signal_task;
85 /** The process id of the audio file selector process. */
88 /* The main server process (parent of afs and the command handlers). */
89 static pid_t server_pid;
92 * Tell whether the executing process is a command handler.
94 * Cleanup on exit must be performed differently for command handlers.
96 * \return True if the pid of the executing process is neither the server pid
99 bool process_is_command_handler(void)
101 pid_t pid = getpid();
103 return pid != afs_pid && pid != server_pid;
106 /** The task responsible for server command handling. */
107 struct server_command_task {
108 unsigned num_listen_fds; /* only one by default */
109 /** TCP socket(s) on which para_server listens for connections. */
111 /* File descriptor for the accepted socket. */
113 /** Copied from para_server's main function. */
115 /** Argument vector passed to para_server's main function. */
117 /** The command task structure for scheduling. */
122 * Return the list of tasks for the server process.
124 * This is called from \a com_tasks(). The helper is necessary since command
125 * handlers can not access the scheduler structure directly.
127 * \return A dynamically allocated string that must be freed by the caller.
129 char *server_get_tasks(void)
131 return get_task_list(&sched);
134 static void pre_log_hook(void)
136 mutex_lock(log_mutex);
139 static void post_log_hook(void)
141 mutex_unlock(log_mutex);
144 /* Setup shared memory area and init mutexes */
145 static void init_ipc_or_die(void)
148 int shmid, ret = shm_new(sizeof(struct misc_meta_data));
153 ret = shm_attach(shmid, ATTACH_RW, &shm);
165 goto destroy_mmd_mutex;
169 mmd->num_commands = 0;
171 mmd->num_connects = 0;
172 mmd->active_connections = 0;
173 mmd->vss_status_flags = VSS_NEXT;
174 mmd->new_vss_status_flags = VSS_NEXT;
175 mmd->loglevel = OPT_UINT32_VAL(LOGLEVEL);
178 mutex_destroy(mmd_mutex);
180 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
184 /** Get a reference to the supercommand of para_server. */
185 #define CMD_PTR (lls_cmd(0, server_suite))
188 * (Re-)read the server configuration files.
190 * \param reload Whether config file overrides command line.
192 * This function also re-opens the logfile and the user list. On SIGHUP it is
193 * called from both server and afs context.
195 void parse_config_or_die(bool reload)
198 unsigned flags = MCF_DONT_FREE;
200 if (server_lpr != cmdline_lpr)
201 lls_free_parse_result(server_lpr, CMD_PTR);
202 server_lpr = cmdline_lpr;
204 flags |= MCF_OVERRIDE;
205 ret = lsu_merge_config_file_options(OPT_STRING_VAL(CONFIG_FILE),
206 "server.conf", &server_lpr, CMD_PTR, server_suite, flags);
208 PARA_EMERG_LOG("failed to parse config file: %s\n",
209 para_strerror(-ret));
212 daemon_set_loglevel(OPT_UINT32_VAL(LOGLEVEL));
213 if (OPT_GIVEN(LOGFILE)) {
214 daemon_set_logfile(OPT_STRING_VAL(LOGFILE));
215 daemon_open_log_or_die();
217 if (daemon_init_colors_or_die(OPT_UINT32_VAL(COLOR), COLOR_AUTO,
218 COLOR_NO, OPT_GIVEN(LOGFILE))) {
220 for (i = 0; i < OPT_GIVEN(LOG_COLOR); i++)
221 daemon_set_log_color_or_die(lls_string_val(i,
222 OPT_RESULT(LOG_COLOR)));
224 daemon_set_flag(DF_LOG_PID);
225 daemon_set_flag(DF_LOG_LL);
226 daemon_set_flag(DF_LOG_TIME);
227 if (OPT_GIVEN(LOG_TIMING))
228 daemon_set_flag(DF_LOG_TIMING);
229 daemon_set_priority(OPT_UINT32_VAL(PRIORITY));
230 if (!reload || getpid() != afs_pid) {
231 char *user_list_file;
232 if (OPT_GIVEN(USER_LIST))
233 user_list_file = para_strdup(OPT_STRING_VAL(USER_LIST));
235 const char *home = get_homedir();
236 user_list_file = make_message("%s/.paraslash/server.users", home);
238 user_list_init(user_list_file);
239 free(user_list_file);
245 * called when server gets SIGHUP or when client invokes hup command.
247 static void handle_sighup(void)
250 PARA_NOTICE_LOG("SIGHUP\n");
251 parse_config_or_die(true);
253 kill(afs_pid, SIGHUP);
256 static int signal_post_monitor(struct sched *s, __a_unused void *context)
260 ret = task_get_notification(signal_task->task);
263 signum = para_next_signal();
273 ret = para_reap_child(&pid);
278 PARA_EMERG_LOG("fatal: afs died\n");
282 /* die on sigint/sigterm. Kill all children too. */
285 PARA_EMERG_LOG("terminating on signal %d\n", signum);
289 * We must wait for all of our children to die. For the afs
290 * process or a command handler might want to use the
291 * shared memory area and the mmd mutex. If we destroy this
292 * mutex too early and afs tries to lock the shared memory
293 * area, the call to mutex_lock() will fail and terminate the
294 * afs process. This leads to dirty osl tables.
296 PARA_INFO_LOG("waiting for child processes to die\n");
297 mutex_unlock(mmd_mutex);
298 while (wait(NULL) != -1 || errno != ECHILD)
299 ; /* still at least one child alive */
300 mutex_lock(mmd_mutex);
301 free(mmd->afd.afhi.chunk_table);
302 task_notify_all(s, E_DEADLY_SIGNAL);
303 return -E_DEADLY_SIGNAL;
308 static void init_signal_task(void)
310 signal_task = signal_init_or_die();
311 para_install_sighandler(SIGINT);
312 para_install_sighandler(SIGTERM);
313 para_install_sighandler(SIGHUP);
314 para_install_sighandler(SIGCHLD);
315 para_sigaction(SIGPIPE, SIG_IGN);
316 add_close_on_fork_list(signal_task->fd);
317 signal_task->task = task_register(&(struct task_info) {
319 .pre_monitor = signal_pre_monitor,
320 .post_monitor = signal_post_monitor,
321 .context = signal_task,
326 static void command_pre_monitor(struct sched *s, void *context)
329 struct server_command_task *sct = context;
331 for (n = 0; n < sct->num_listen_fds; n++)
332 sched_monitor_readfd(sct->listen_fds[n], s);
335 static int command_task_accept(unsigned listen_idx, struct sched *s,
336 struct server_command_task *sct)
341 uint32_t *chunk_table;
343 ret = para_accept(sct->listen_fds[listen_idx], NULL, 0, &new_fd);
347 mmd->active_connections++;
349 * The chunk table is a pointer located in the mmd struct that points
350 * to dynamically allocated memory, i.e. it must be freed by the parent
351 * and the child. However, as the mmd struct is in a shared memory
352 * area, there's no guarantee that after the fork this pointer is still
353 * valid in child context. As it is not used in the child anyway, we
354 * save it to a local variable before the fork and free the memory via
355 * that copy in the child directly after the fork.
357 chunk_table = mmd->afd.afhi.chunk_table;
360 ret = -ERRNO_TO_PARA_ERROR(errno);
364 /* avoid problems with non-fork-safe PRNGs */
365 unsigned char buf[16];
366 get_random_bytes_or_die(buf, sizeof(buf));
368 /* parent keeps accepting connections */
371 peer_name = remote_name(new_fd);
372 PARA_INFO_LOG("accepted connection from %s\n", peer_name);
373 /* mmd might already have changed at this point */
375 sct->child_fd = new_fd;
377 * put info on who we are serving into argv[0] to make
378 * client ip visible in top/ps
380 for (i = sct->argc - 1; i >= 0; i--)
381 memset(sct->argv[i], 0, strlen(sct->argv[i]));
382 i = sct->argc - 1 - lls_num_inputs(cmdline_lpr);
383 sprintf(sct->argv[i], "para_server (serving %s)", peer_name);
384 /* ask other tasks to terminate */
385 task_notify_all(s, E_CHILD_CONTEXT);
387 * After we return, the scheduler calls server_select() with a minimal
388 * timeout value, because the remaining tasks have a notification
389 * pending. Next it calls the ->post_monitor method of these tasks,
390 * which will return negative in view of the notification. This causes
391 * schedule() to return as there are no more runnable tasks.
393 * Note that semaphores are not inherited across a fork(), so we don't
394 * hold the lock at this point. Since server_poll() drops the lock
395 * prior to calling poll(), we need to acquire it here.
397 mutex_lock(mmd_mutex);
398 return -E_CHILD_CONTEXT;
401 PARA_CRIT_LOG("%s\n", para_strerror(-ret));
405 static int command_post_monitor(struct sched *s, void *context)
407 struct server_command_task *sct = context;
411 ret = task_get_notification(sct->task);
414 for (n = 0; n < sct->num_listen_fds; n++) {
415 ret = command_task_accept(n, s, sct);
421 free(sct->listen_fds);
425 static void init_server_command_task(struct server_command_task *sct,
426 int argc, char **argv)
430 uint32_t port = OPT_UINT32_VAL(PORT);
432 PARA_NOTICE_LOG("initializing tcp command socket\n");
436 if (!OPT_GIVEN(LISTEN_ADDRESS)) {
437 sct->num_listen_fds = 1;
438 sct->listen_fds = alloc(sizeof(int));
439 ret = para_listen_simple(IPPROTO_TCP, port);
442 sct->listen_fds[0] = ret;
444 sct->num_listen_fds = OPT_GIVEN(LISTEN_ADDRESS);
445 sct->listen_fds = alloc(sct->num_listen_fds * sizeof(int));
446 for (n = 0; n < OPT_GIVEN(LISTEN_ADDRESS); n++) {
448 arg = lls_string_val(n, OPT_RESULT(LISTEN_ADDRESS));
449 ret = para_listen(IPPROTO_TCP, arg, port);
452 sct->listen_fds[n] = ret;
455 for (n = 0; n < sct->num_listen_fds; n++) {
456 ret = mark_fd_nonblocking(sct->listen_fds[n]);
459 /* child doesn't need the listener */
460 add_close_on_fork_list(sct->listen_fds[n]);
463 sct->task = task_register(&(struct task_info) {
464 .name = "server command",
465 .pre_monitor = command_pre_monitor,
466 .post_monitor = command_post_monitor,
470 * Detect whether the abstract Unix domain socket space is supported,
471 * but do not create the socket. We check this once in server context
472 * so that the command handlers inherit this bit of information and
473 * don't need to check again.
475 create_local_socket(NULL);
478 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
482 static int init_afs(int argc, char **argv)
484 int ret, afs_server_socket[2];
487 ret = socketpair(PF_UNIX, SOCK_STREAM, 0, afs_server_socket);
490 get_random_bytes_or_die((unsigned char *)&afs_socket_cookie,
491 sizeof(afs_socket_cookie));
495 if (afs_pid == 0) { /* child (afs) */
501 for (i = argc - 1; i >= 0; i--)
502 memset(argv[i], 0, strlen(argv[i]));
503 i = argc - lls_num_inputs(cmdline_lpr) - 1;
504 sprintf(argv[i], "para_server (afs)");
505 close(afs_server_socket[0]);
506 afs_init(afs_server_socket[1]);
508 close(afs_server_socket[1]);
509 if (read(afs_server_socket[0], &c, 1) <= 0) {
510 PARA_EMERG_LOG("early afs exit\n");
513 ret = mark_fd_nonblocking(afs_server_socket[0]);
516 add_close_on_fork_list(afs_server_socket[0]);
517 PARA_INFO_LOG("afs_socket: %d, afs_socket_cookie: %u\n",
518 afs_server_socket[0], (unsigned) afs_socket_cookie);
519 return afs_server_socket[0];
522 static void handle_help_flags(void)
525 bool d = OPT_GIVEN(DETAILED_HELP);
528 help = lls_long_help(CMD_PTR);
529 else if (OPT_GIVEN(HELP))
530 help = lls_short_help(CMD_PTR);
533 printf("%s\n", help);
538 static void server_init(int argc, char **argv, struct server_command_task *sct)
540 int ret, afs_socket, daemon_pipe = -1;
544 /* parse command line options */
545 ret = lls(lls_parse(argc, argv, CMD_PTR, &cmdline_lpr, &errctx));
548 server_lpr = cmdline_lpr;
549 daemon_set_loglevel(OPT_UINT32_VAL(LOGLEVEL));
550 daemon_drop_privileges_or_die(OPT_STRING_VAL(USER),
551 OPT_STRING_VAL(GROUP));
552 version_handle_flag("server", OPT_GIVEN(VERSION));
554 parse_config_or_die(false);
556 if (OPT_GIVEN(DAEMON))
557 daemon_pipe = daemonize(true /* parent waits for SIGTERM */);
558 server_pid = getpid();
560 daemon_log_welcome("server");
561 init_ipc_or_die(); /* init mmd struct, mmd and log mutex */
562 daemon_set_start_time();
563 daemon_set_hooks(pre_log_hook, post_log_hook);
565 * Although afs uses its own signal handling we must ignore SIGUSR1
566 * _before_ the afs child process gets born by init_afs() below. It's
567 * racy to do this in the child because the parent might send SIGUSR1
568 * before the child gets a chance to ignore this signal.
570 * We also have to block SIGCHLD before the afs process is created
571 * because otherwise para_server does not notice if afs dies before the
572 * SIGCHLD handler has been installed for the parent process by
573 * init_signal_task() below.
575 para_sigaction(SIGUSR1, SIG_IGN);
576 para_block_signal(SIGCHLD);
577 PARA_NOTICE_LOG("initializing the audio file selector\n");
578 afs_socket = init_afs(argc, argv);
580 para_unblock_signal(SIGCHLD);
581 PARA_NOTICE_LOG("initializing virtual streaming system\n");
582 vss_init(afs_socket, &sched);
583 init_server_command_task(sct, argc, argv);
584 if (daemon_pipe >= 0) {
585 if (write(daemon_pipe, "\0", 1) < 0) {
586 PARA_EMERG_LOG("daemon_pipe: %s", strerror(errno));
591 PARA_NOTICE_LOG("server init complete\n");
596 PARA_ERROR_LOG("%s\n", errctx);
597 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
601 static void status_refresh(void)
603 static int prev_uptime = -1, prev_events = -1;
604 int uptime = daemon_get_uptime(now);
606 if (prev_events != mmd->events)
608 if (mmd->new_vss_status_flags != mmd->vss_status_flags)
610 if (uptime / 60 != prev_uptime / 60)
616 prev_uptime = uptime;
617 prev_events = mmd->events;
618 mmd->vss_status_flags = mmd->new_vss_status_flags;
619 PARA_DEBUG_LOG("%u events, forcing status update\n", mmd->events);
623 static int server_poll(struct pollfd *fds, nfds_t nfds, int timeout)
627 daemon_set_loglevel(mmd->loglevel);
629 mutex_unlock(mmd_mutex);
630 ret = xpoll(fds, nfds, timeout);
631 mutex_lock(mmd_mutex);
636 * Deallocate all lopsub parse results.
638 * The server allocates a parse result for command line options and optionally
639 * a second parse result for the effective configuration, defined by merging
640 * the command line options with the options stored in the configuration file.
641 * This function frees both structures.
645 lls_free_parse_result(server_lpr, CMD_PTR);
646 if (server_lpr != cmdline_lpr)
647 lls_free_parse_result(cmdline_lpr, CMD_PTR);
651 * The main function of para_server.
653 * \param argc Usual argument count.
654 * \param argv Usual argument vector.
656 * \return EXIT_SUCCESS or EXIT_FAILURE.
658 int main(int argc, char *argv[])
661 struct server_command_task server_command_task_struct,
662 *sct = &server_command_task_struct;
664 sched.default_timeout = 1000;
665 sched.poll_function = server_poll;
667 server_init(argc, argv, sct);
668 mutex_lock(mmd_mutex);
669 ret = schedule(&sched);
671 * We hold the mmd lock: it was re-acquired in server_poll()
672 * after the poll(2) call.
674 mutex_unlock(mmd_mutex);
675 sched_shutdown(&sched);
677 signal_shutdown(signal_task);
678 if (!process_is_command_handler()) { /* parent (server) */
679 mutex_destroy(mmd_mutex);
680 daemon_set_hooks(NULL, NULL); /* only one process remaining */
681 mutex_destroy(log_mutex);
682 deplete_close_on_fork_list();
684 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
688 alarm(ALARM_TIMEOUT);
690 ret = handle_connect(sct->child_fd);
695 exit(ret < 0? EXIT_FAILURE : EXIT_SUCCESS);