2 * Copyright (C) 1997 Andre Noll <maan@tuebingen.mpg.de>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file server.c Paraslash's main server. */
10 * \mainpage Main data structures and selected APIs:
12 * - Senders: \ref sender,
13 * - Audio file selector: \ref afs_info, \ref afs_table,
14 * - Audio format handler: \ref audio_format_handler, \ref afh_info
15 * - Receivers/filters/writers: \ref receiver, \ref receiver_node,
16 * \ref filter, \ref filter_node, \ref writer_node, \ref writer.
17 * - Scheduling: \ref sched.h,
18 * - Buffer trees: \ref buffer_tree.h,
19 * - Sideband API: \ref sideband.h,
20 * - Crypto: \ref crypt.h, \ref crypt_backend.h,
21 * - Error subsystem: \ref error.h,
22 * - Inter process communication: \ref ipc.h,
23 * - Forward error correction: \ref fec.h,
24 * - Daemons: \ref daemon.h,
25 * - Mixer API: \ref mix.h,
26 * - Interactive sessions: \ref interactive.h,
27 * - File descriptors: \ref fd.h,
28 * - Signals: \ref signal.h,
29 * - Networking: \ref net.h,
30 * - Time: \ref time.c,
31 * - Doubly linked lists: \ref list.h.
34 #include <netinet/in.h>
35 #include <sys/socket.h>
39 #include <sys/types.h>
40 #include <arpa/inet.h>
45 #include "server.lsg.h"
58 #include "close_on_fork.h"
64 #include "user_list.h"
68 /** Array of error strings. */
71 __printf_2_3 void (*para_log)(int, const char*, ...) = daemon_log;
73 /** Shut down non-authorized connections after that many seconds. */
74 #define ALARM_TIMEOUT 10
77 * Pointer to shared memory area for communication between para_server
78 * and its children. Exported to vss.c, command.c and to afs.
80 struct misc_meta_data *mmd;
83 * The active value for all config options of para_server.
85 * It is computed by merging the parse result of the command line options with
86 * the parse result of the config file.
88 struct lls_parse_result *server_lpr = NULL;
90 /* Command line options (no config file options). Used in handle_sighup(). */
91 static struct lls_parse_result *cmdline_lpr;
93 /** A random value used in child context for authentication. */
94 uint32_t afs_socket_cookie;
96 /** The mutex protecting the shared memory area containing the mmd struct. */
99 static struct sched sched;
100 static struct signal_task *signal_task;
102 /** The task responsible for server command handling. */
103 struct server_command_task {
104 /** TCP port on which para_server listens for connections. */
106 /** Copied from para_server's main function. */
108 /** Argument vector passed to para_server's main function. */
110 /** The command task structure for scheduling. */
115 * Return the list of tasks for the server process.
117 * This is called from \a com_tasks(). The helper is necessary since command
118 * handlers can not access the scheduler structure directly.
120 * \return A dynamically allocated string that must be freed by the caller.
122 char *server_get_tasks(void)
124 return get_task_list(&sched);
128 * setup shared memory area and get mutex for locking
130 static void init_ipc_or_die(void)
133 int shmid, ret = shm_new(sizeof(struct misc_meta_data));
138 ret = shm_attach(shmid, ATTACH_RW, &shm);
150 mmd->num_commands = 0;
152 mmd->num_connects = 0;
153 mmd->active_connections = 0;
154 mmd->vss_status_flags = VSS_NEXT;
155 mmd->new_vss_status_flags = VSS_NEXT;
158 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
163 * (Re-)read the server configuration files.
165 * \param reload Whether config file overrides command line.
167 * This function also re-opens the logfile and the user list. On SIGHUP it is
168 * called from both server and afs context.
170 void parse_config_or_die(bool reload)
173 char *cf = NULL, *errctx = NULL, *user_list_file = NULL;
178 struct lls_parse_result *cf_lpr, *merged_lpr;
179 char *home = para_homedir();
182 if (OPT_GIVEN(CONFIG_FILE))
183 cf = para_strdup(OPT_STRING_VAL(CONFIG_FILE));
185 cf = make_message("%s/.paraslash/server.conf", home);
186 if (!mmd || getpid() != mmd->afs_pid) {
187 if (OPT_GIVEN(USER_LIST))
188 user_list_file = para_strdup(OPT_STRING_VAL(USER_LIST));
190 user_list_file = make_message("%s/.paraslash/server.users", home);
193 ret = mmap_full_file(cf, O_RDONLY, &map, &sz, NULL);
195 if (ret != -E_EMPTY && ret != -ERRNO_TO_PARA_ERROR(ENOENT))
197 if (ret == -ERRNO_TO_PARA_ERROR(ENOENT) && OPT_GIVEN(CONFIG_FILE))
200 server_lpr = cmdline_lpr;
203 ret = lls(lls_convert_config(map, sz, NULL, &cf_argv, &errctx));
204 para_munmap(map, sz);
208 ret = lls(lls_parse(cf_argc, cf_argv, CMD_PTR, &cf_lpr, &errctx));
209 lls_free_argv(cf_argv);
212 if (reload) /* config file overrides command line */
213 ret = lls(lls_merge(cf_lpr, cmdline_lpr, CMD_PTR, &merged_lpr,
215 else /* command line options overrride config file options */
216 ret = lls(lls_merge(cmdline_lpr, cf_lpr, CMD_PTR, &merged_lpr,
218 lls_free_parse_result(cf_lpr, CMD_PTR);
221 if (server_lpr != cmdline_lpr)
222 lls_free_parse_result(server_lpr, CMD_PTR);
223 server_lpr = merged_lpr;
225 daemon_set_loglevel(ENUM_STRING_VAL(LOGLEVEL));
226 if (OPT_GIVEN(LOGFILE)) {
227 daemon_set_logfile(OPT_STRING_VAL(LOGFILE));
228 daemon_open_log_or_die();
230 if (daemon_init_colors_or_die(OPT_UINT32_VAL(COLOR), COLOR_AUTO,
231 COLOR_NO, OPT_GIVEN(LOGFILE))) {
233 for (i = 0; i < OPT_GIVEN(LOG_COLOR); i++)
234 daemon_set_log_color_or_die(lls_string_val(i,
235 OPT_RESULT(LOG_COLOR)));
237 daemon_set_flag(DF_LOG_PID);
238 daemon_set_flag(DF_LOG_LL);
239 daemon_set_flag(DF_LOG_TIME);
240 if (OPT_GIVEN(LOG_TIMING))
241 daemon_set_flag(DF_LOG_TIMING);
242 daemon_set_priority(OPT_UINT32_VAL(PRIORITY));
244 init_user_list(user_list_file);
248 free(user_list_file);
251 PARA_ERROR_LOG("%s\n", errctx);
253 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
259 * called when server gets SIGHUP or when client invokes hup command.
261 static void handle_sighup(void)
264 PARA_NOTICE_LOG("SIGHUP\n");
265 parse_config_or_die(true);
267 kill(mmd->afs_pid, SIGHUP);
270 static int signal_post_select(struct sched *s, __a_unused void *context)
272 int signum = para_next_signal(&s->rfds);
283 int ret = para_reap_child(&pid);
286 if (pid != mmd->afs_pid)
288 PARA_EMERG_LOG("fatal: afs died\n");
293 /* die on sigint/sigterm. Kill all children too. */
296 PARA_EMERG_LOG("terminating on signal %d\n", signum);
299 * We must wait for afs because afs catches SIGINT/SIGTERM.
300 * Before reacting to the signal, afs might want to use the
301 * shared memory area and the mmd mutex. If we destroy this
302 * mutex too early and afs tries to lock the shared memory
303 * area, the call to mutex_lock() will fail and terminate the
304 * afs process. This leads to dirty osl tables.
306 * There's no such problem with the other children of the
307 * server process (the command handlers) as these reset their
308 * SIGINT/SIGTERM handlers to the default action, i.e. these
309 * processes get killed immediately by the above kill().
311 PARA_INFO_LOG("waiting for afs (pid %d) to die\n",
313 waitpid(mmd->afs_pid, NULL, 0);
315 free(mmd->afd.afhi.chunk_table);
317 mutex_destroy(mmd_mutex);
324 static void init_signal_task(void)
326 signal_task = signal_init_or_die();
327 para_install_sighandler(SIGINT);
328 para_install_sighandler(SIGTERM);
329 para_install_sighandler(SIGHUP);
330 para_install_sighandler(SIGCHLD);
331 para_sigaction(SIGPIPE, SIG_IGN);
332 add_close_on_fork_list(signal_task->fd);
333 signal_task->task = task_register(&(struct task_info) {
335 .pre_select = signal_pre_select,
336 .post_select = signal_post_select,
337 .context = signal_task,
342 static void command_pre_select(struct sched *s, void *context)
344 struct server_command_task *sct = context;
345 para_fd_set(sct->listen_fd, &s->rfds, &s->max_fileno);
348 static int command_post_select(struct sched *s, void *context)
350 struct server_command_task *sct = context;
355 uint32_t *chunk_table;
357 ret = para_accept(sct->listen_fd, &s->rfds, NULL, 0, &new_fd);
360 peer_name = remote_name(new_fd);
361 PARA_INFO_LOG("got connection from %s, forking\n", peer_name);
363 mmd->active_connections++;
365 * The chunk table is a pointer located in the mmd struct that points
366 * to dynamically allocated memory, i.e. it must be freed by the parent
367 * and the child. However, as the mmd struct is in a shared memory
368 * area, there's no guarantee that after the fork this pointer is still
369 * valid in child context. As it is not used in the child anyway, we
370 * save it to a local variable before the fork and free the memory via
371 * that copy in the child directly after the fork.
373 chunk_table = mmd->afd.afhi.chunk_table;
376 ret = -ERRNO_TO_PARA_ERROR(errno);
380 /* avoid problems with non-fork-safe PRNGs */
381 unsigned char buf[16];
382 get_random_bytes_or_die(buf, sizeof(buf));
384 /* parent keeps accepting connections */
387 /* mmd might already have changed at this point */
389 alarm(ALARM_TIMEOUT);
391 signal_shutdown(signal_task);
393 * put info on who we are serving into argv[0] to make
394 * client ip visible in top/ps
396 for (i = sct->argc - 1; i >= 0; i--)
397 memset(sct->argv[i], 0, strlen(sct->argv[i]));
398 i = sct->argc - 1 - lls_num_inputs(cmdline_lpr);
399 sprintf(sct->argv[i], "para_server (serving %s)", peer_name);
400 handle_connect(new_fd, peer_name);
404 PARA_CRIT_LOG("%s\n", para_strerror(-ret));
408 static void init_server_command_task(int argc, char **argv)
411 static struct server_command_task server_command_task_struct,
412 *sct = &server_command_task_struct;
414 PARA_NOTICE_LOG("initializing tcp command socket\n");
417 ret = para_listen_simple(IPPROTO_TCP, OPT_UINT32_VAL(PORT));
420 sct->listen_fd = ret;
421 ret = mark_fd_nonblocking(sct->listen_fd);
424 add_close_on_fork_list(sct->listen_fd); /* child doesn't need the listener */
425 sct->task = task_register(&(struct task_info) {
426 .name = "server command",
427 .pre_select = command_pre_select,
428 .post_select = command_post_select,
433 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
437 static int init_afs(int argc, char **argv)
439 int ret, afs_server_socket[2];
443 ret = socketpair(PF_UNIX, SOCK_STREAM, 0, afs_server_socket);
446 get_random_bytes_or_die((unsigned char *)&afs_socket_cookie,
447 sizeof(afs_socket_cookie));
451 if (afs_pid == 0) { /* child (afs) */
454 for (i = argc - 1; i >= 0; i--)
455 memset(argv[i], 0, strlen(argv[i]));
456 i = argc - lls_num_inputs(cmdline_lpr) - 1;
457 sprintf(argv[i], "para_server (afs)");
458 close(afs_server_socket[0]);
459 afs_init(afs_socket_cookie, afs_server_socket[1]);
461 mmd->afs_pid = afs_pid;
462 close(afs_server_socket[1]);
463 if (read(afs_server_socket[0], &c, 1) <= 0) {
464 PARA_EMERG_LOG("early afs exit\n");
467 ret = mark_fd_nonblocking(afs_server_socket[0]);
470 add_close_on_fork_list(afs_server_socket[0]);
471 PARA_INFO_LOG("afs_socket: %d, afs_socket_cookie: %u\n",
472 afs_server_socket[0], (unsigned) afs_socket_cookie);
473 return afs_server_socket[0];
476 static void handle_help_flags(void)
479 bool d = OPT_GIVEN(DETAILED_HELP);
482 help = lls_long_help(CMD_PTR);
483 else if (OPT_GIVEN(HELP))
484 help = lls_short_help(CMD_PTR);
487 printf("%s\n", help);
492 static void server_init(int argc, char **argv)
494 int ret, afs_socket, daemon_pipe = -1;
498 /* parse command line options */
499 ret = lls(lls_parse(argc, argv, CMD_PTR, &cmdline_lpr, &errctx));
502 server_lpr = cmdline_lpr;
503 daemon_set_loglevel(ENUM_STRING_VAL(LOGLEVEL));
504 daemon_drop_privileges_or_die(OPT_STRING_VAL(USER),
505 OPT_STRING_VAL(GROUP));
506 version_handle_flag("server", OPT_GIVEN(VERSION));
508 parse_config_or_die(false);
510 if (OPT_GIVEN(DAEMON))
511 daemon_pipe = daemonize(true /* parent waits for SIGTERM */);
512 init_random_seed_or_die();
513 daemon_log_welcome("server");
514 init_ipc_or_die(); /* init mmd struct and mmd->lock */
515 daemon_set_start_time();
516 PARA_NOTICE_LOG("initializing audio format handlers\n");
520 * Although afs uses its own signal handling we must ignore SIGUSR1
521 * _before_ the afs child process gets born by init_afs() below. It's
522 * racy to do this in the child because the parent might send SIGUSR1
523 * before the child gets a chance to ignore this signal.
525 * We also have to block SIGCHLD before the afs process is created
526 * because otherwise para_server does not notice if afs dies before the
527 * SIGCHLD handler has been installed for the parent process by
528 * init_signal_task() below.
530 para_sigaction(SIGUSR1, SIG_IGN);
531 para_block_signal(SIGCHLD);
532 PARA_NOTICE_LOG("initializing the audio file selector\n");
533 afs_socket = init_afs(argc, argv);
535 para_unblock_signal(SIGCHLD);
536 PARA_NOTICE_LOG("initializing virtual streaming system\n");
537 init_vss_task(afs_socket, &sched);
538 init_server_command_task(argc, argv);
539 if (daemon_pipe >= 0) {
540 if (write(daemon_pipe, "\0", 1) < 0) {
541 PARA_EMERG_LOG("daemon_pipe: %s", strerror(errno));
546 PARA_NOTICE_LOG("server init complete\n");
551 PARA_ERROR_LOG("%s\n", errctx);
552 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
556 static void status_refresh(void)
558 static int prev_uptime = -1, prev_events = -1;
559 int uptime = daemon_get_uptime(now);
561 if (prev_events != mmd->events)
563 if (mmd->new_vss_status_flags != mmd->vss_status_flags)
565 if (uptime / 60 != prev_uptime / 60)
571 prev_uptime = uptime;
572 prev_events = mmd->events;
573 mmd->vss_status_flags = mmd->new_vss_status_flags;
574 PARA_DEBUG_LOG("%u events, forcing status update\n", mmd->events);
578 static int server_select(int max_fileno, fd_set *readfds, fd_set *writefds,
579 struct timeval *timeout_tv)
584 mutex_unlock(mmd_mutex);
585 ret = para_select(max_fileno + 1, readfds, writefds, timeout_tv);
586 mutex_lock(mmd_mutex);
591 * The main function of para_server.
593 * \param argc Usual argument count.
594 * \param argv Usual argument vector.
596 * \return EXIT_SUCCESS or EXIT_FAILURE.
598 int main(int argc, char *argv[])
602 sched.default_timeout.tv_sec = 1;
603 sched.select_function = server_select;
605 server_init(argc, argv);
606 mutex_lock(mmd_mutex);
607 ret = schedule(&sched);
608 sched_shutdown(&sched);
609 lls_free_parse_result(server_lpr, CMD_PTR);
610 if (server_lpr != cmdline_lpr)
611 lls_free_parse_result(cmdline_lpr, CMD_PTR);
613 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
614 exit(ret < 0? EXIT_FAILURE : EXIT_SUCCESS);