1 /* Copyright (C) 1997 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
3 /** \file server.c Paraslash's main server. */
6 * \mainpage Main data structures and selected APIs:
8 * - Senders: \ref sender,
9 * - Audio file selector: \ref afs_info, \ref afs_table,
10 * - Audio format handler: \ref audio_format_handler, \ref afh_info
11 * - Receivers/filters/writers: \ref receiver, \ref receiver_node,
12 * \ref filter, \ref filter_node, \ref writer_node, \ref writer.
13 * - Scheduling: \ref sched.h,
14 * - Buffer trees: \ref buffer_tree.h,
15 * - Sideband API: \ref sideband.h,
16 * - Crypto: \ref crypt.h, \ref crypt_backend.h,
17 * - Error subsystem: \ref error.h,
18 * - Inter process communication: \ref ipc.h,
19 * - Forward error correction: \ref fec.h,
20 * - Daemons: \ref daemon.h,
21 * - Mixer API: \ref mix.h,
22 * - Interactive sessions: \ref interactive.h,
23 * - File descriptors: \ref fd.h,
24 * - Signals: \ref signal.h,
25 * - Networking: \ref net.h,
26 * - Time: \ref time.c,
27 * - Doubly linked lists: \ref list.h.
30 #include <netinet/in.h>
31 #include <sys/socket.h>
35 #include <sys/types.h>
36 #include <arpa/inet.h>
41 #include "server.lsg.h"
54 #include "close_on_fork.h"
60 #include "user_list.h"
64 /** Array of error strings. */
67 __printf_2_3 void (*para_log)(int, const char*, ...) = daemon_log;
69 /** Shut down non-authorized connections after that many seconds. */
70 #define ALARM_TIMEOUT 10
73 * Pointer to shared memory area for communication between para_server
74 * and its children. Exported to vss.c, command.c and to afs.
76 struct misc_meta_data *mmd;
79 * The active value for all config options of para_server.
81 * It is computed by merging the parse result of the command line options with
82 * the parse result of the config file.
84 struct lls_parse_result *server_lpr = NULL;
86 /* Command line options (no config file options). Used in handle_sighup(). */
87 static struct lls_parse_result *cmdline_lpr;
90 * A random number used to "authenticate" the afs connection.
92 * para_server picks this number by random before it forks the afs process. The
93 * command handlers know this number as well and write it to the afs socket,
94 * together with the id of the shared memory area which contains the payload of
95 * the afs command. A local process has to know this number to abuse the afs
96 * service provided by the local socket.
98 uint32_t afs_socket_cookie;
100 /** The mutex protecting the shared memory area containing the mmd struct. */
103 static struct sched sched;
104 static struct signal_task *signal_task;
106 /** The process id of the audio file selector process. */
109 /** The task responsible for server command handling. */
110 struct server_command_task {
111 /** TCP port on which para_server listens for connections. */
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);
135 * setup shared memory area and get mutex for locking
137 static void init_ipc_or_die(void)
140 int shmid, ret = shm_new(sizeof(struct misc_meta_data));
145 ret = shm_attach(shmid, ATTACH_RW, &shm);
157 mmd->num_commands = 0;
159 mmd->num_connects = 0;
160 mmd->active_connections = 0;
161 mmd->vss_status_flags = VSS_NEXT;
162 mmd->new_vss_status_flags = VSS_NEXT;
165 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
170 * (Re-)read the server configuration files.
172 * \param reload Whether config file overrides command line.
174 * This function also re-opens the logfile and the user list. On SIGHUP it is
175 * called from both server and afs context.
177 void parse_config_or_die(bool reload)
180 char *cf = NULL, *errctx = NULL, *user_list_file = NULL;
185 struct lls_parse_result *cf_lpr, *merged_lpr;
186 char *home = para_homedir();
189 if (OPT_GIVEN(CONFIG_FILE))
190 cf = para_strdup(OPT_STRING_VAL(CONFIG_FILE));
192 cf = make_message("%s/.paraslash/server.conf", home);
193 if (!mmd || getpid() != afs_pid) {
194 if (OPT_GIVEN(USER_LIST))
195 user_list_file = para_strdup(OPT_STRING_VAL(USER_LIST));
197 user_list_file = make_message("%s/.paraslash/server.users", home);
200 ret = mmap_full_file(cf, O_RDONLY, &map, &sz, NULL);
202 if (ret != -E_EMPTY && ret != -ERRNO_TO_PARA_ERROR(ENOENT))
204 if (ret == -ERRNO_TO_PARA_ERROR(ENOENT) && OPT_GIVEN(CONFIG_FILE))
206 server_lpr = cmdline_lpr;
209 ret = lls(lls_convert_config(map, sz, NULL, &cf_argv, &errctx));
210 para_munmap(map, sz);
214 ret = lls(lls_parse(cf_argc, cf_argv, CMD_PTR, &cf_lpr, &errctx));
215 lls_free_argv(cf_argv);
218 if (reload) /* config file overrides command line */
219 ret = lls(lls_merge(cf_lpr, cmdline_lpr, CMD_PTR, &merged_lpr,
221 else /* command line options override config file options */
222 ret = lls(lls_merge(cmdline_lpr, cf_lpr, CMD_PTR, &merged_lpr,
224 lls_free_parse_result(cf_lpr, CMD_PTR);
227 if (server_lpr != cmdline_lpr)
228 lls_free_parse_result(server_lpr, CMD_PTR);
229 server_lpr = merged_lpr;
231 daemon_set_loglevel(ENUM_STRING_VAL(LOGLEVEL));
232 if (OPT_GIVEN(LOGFILE)) {
233 daemon_set_logfile(OPT_STRING_VAL(LOGFILE));
234 daemon_open_log_or_die();
236 if (daemon_init_colors_or_die(OPT_UINT32_VAL(COLOR), COLOR_AUTO,
237 COLOR_NO, OPT_GIVEN(LOGFILE))) {
239 for (i = 0; i < OPT_GIVEN(LOG_COLOR); i++)
240 daemon_set_log_color_or_die(lls_string_val(i,
241 OPT_RESULT(LOG_COLOR)));
243 daemon_set_flag(DF_LOG_PID);
244 daemon_set_flag(DF_LOG_LL);
245 daemon_set_flag(DF_LOG_TIME);
246 if (OPT_GIVEN(LOG_TIMING))
247 daemon_set_flag(DF_LOG_TIMING);
248 daemon_set_priority(OPT_UINT32_VAL(PRIORITY));
250 init_user_list(user_list_file);
254 free(user_list_file);
257 PARA_ERROR_LOG("%s\n", errctx);
259 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
265 * called when server gets SIGHUP or when client invokes hup command.
267 static void handle_sighup(void)
270 PARA_NOTICE_LOG("SIGHUP\n");
271 parse_config_or_die(true);
273 kill(afs_pid, SIGHUP);
276 static int signal_post_select(struct sched *s, __a_unused void *context)
278 int signum = para_next_signal(&s->rfds);
289 int ret = para_reap_child(&pid);
294 PARA_EMERG_LOG("fatal: afs died\n");
299 /* die on sigint/sigterm. Kill all children too. */
302 PARA_EMERG_LOG("terminating on signal %d\n", signum);
305 * We must wait for afs because afs catches SIGINT/SIGTERM.
306 * Before reacting to the signal, afs might want to use the
307 * shared memory area and the mmd mutex. If we destroy this
308 * mutex too early and afs tries to lock the shared memory
309 * area, the call to mutex_lock() will fail and terminate the
310 * afs process. This leads to dirty osl tables.
312 * There's no such problem with the other children of the
313 * server process (the command handlers) as these reset their
314 * SIGINT/SIGTERM handlers to the default action, i.e. these
315 * processes get killed immediately by the above kill().
317 PARA_INFO_LOG("waiting for afs (pid %d) to die\n",
319 waitpid(afs_pid, NULL, 0);
321 free(mmd->afd.afhi.chunk_table);
323 mutex_destroy(mmd_mutex);
330 static void init_signal_task(void)
332 signal_task = signal_init_or_die();
333 para_install_sighandler(SIGINT);
334 para_install_sighandler(SIGTERM);
335 para_install_sighandler(SIGHUP);
336 para_install_sighandler(SIGCHLD);
337 para_sigaction(SIGPIPE, SIG_IGN);
338 add_close_on_fork_list(signal_task->fd);
339 signal_task->task = task_register(&(struct task_info) {
341 .pre_select = signal_pre_select,
342 .post_select = signal_post_select,
343 .context = signal_task,
348 static void command_pre_select(struct sched *s, void *context)
350 struct server_command_task *sct = context;
351 para_fd_set(sct->listen_fd, &s->rfds, &s->max_fileno);
354 static int command_post_select(struct sched *s, void *context)
356 struct server_command_task *sct = context;
361 uint32_t *chunk_table;
363 ret = para_accept(sct->listen_fd, &s->rfds, NULL, 0, &new_fd);
367 mmd->active_connections++;
369 * The chunk table is a pointer located in the mmd struct that points
370 * to dynamically allocated memory, i.e. it must be freed by the parent
371 * and the child. However, as the mmd struct is in a shared memory
372 * area, there's no guarantee that after the fork this pointer is still
373 * valid in child context. As it is not used in the child anyway, we
374 * save it to a local variable before the fork and free the memory via
375 * that copy in the child directly after the fork.
377 chunk_table = mmd->afd.afhi.chunk_table;
380 ret = -ERRNO_TO_PARA_ERROR(errno);
384 /* avoid problems with non-fork-safe PRNGs */
385 unsigned char buf[16];
386 get_random_bytes_or_die(buf, sizeof(buf));
388 /* parent keeps accepting connections */
391 peer_name = remote_name(new_fd);
392 PARA_INFO_LOG("accepted connection from %s\n", peer_name);
393 /* mmd might already have changed at this point */
395 alarm(ALARM_TIMEOUT);
397 signal_shutdown(signal_task);
399 * put info on who we are serving into argv[0] to make
400 * client ip visible in top/ps
402 for (i = sct->argc - 1; i >= 0; i--)
403 memset(sct->argv[i], 0, strlen(sct->argv[i]));
404 i = sct->argc - 1 - lls_num_inputs(cmdline_lpr);
405 sprintf(sct->argv[i], "para_server (serving %s)", peer_name);
406 handle_connect(new_fd);
410 PARA_CRIT_LOG("%s\n", para_strerror(-ret));
414 static void init_server_command_task(int argc, char **argv)
417 static struct server_command_task server_command_task_struct,
418 *sct = &server_command_task_struct;
420 PARA_NOTICE_LOG("initializing tcp command socket\n");
423 ret = para_listen_simple(IPPROTO_TCP, OPT_UINT32_VAL(PORT));
426 sct->listen_fd = ret;
427 ret = mark_fd_nonblocking(sct->listen_fd);
430 add_close_on_fork_list(sct->listen_fd); /* child doesn't need the listener */
431 sct->task = task_register(&(struct task_info) {
432 .name = "server command",
433 .pre_select = command_pre_select,
434 .post_select = command_post_select,
439 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
443 static int init_afs(int argc, char **argv)
445 int ret, afs_server_socket[2];
448 ret = socketpair(PF_UNIX, SOCK_STREAM, 0, afs_server_socket);
451 get_random_bytes_or_die((unsigned char *)&afs_socket_cookie,
452 sizeof(afs_socket_cookie));
456 if (afs_pid == 0) { /* child (afs) */
460 for (i = argc - 1; i >= 0; i--)
461 memset(argv[i], 0, strlen(argv[i]));
462 i = argc - lls_num_inputs(cmdline_lpr) - 1;
463 sprintf(argv[i], "para_server (afs)");
464 close(afs_server_socket[0]);
465 afs_init(afs_server_socket[1]);
467 close(afs_server_socket[1]);
468 if (read(afs_server_socket[0], &c, 1) <= 0) {
469 PARA_EMERG_LOG("early afs exit\n");
472 ret = mark_fd_nonblocking(afs_server_socket[0]);
475 add_close_on_fork_list(afs_server_socket[0]);
476 PARA_INFO_LOG("afs_socket: %d, afs_socket_cookie: %u\n",
477 afs_server_socket[0], (unsigned) afs_socket_cookie);
478 return afs_server_socket[0];
481 static void handle_help_flags(void)
484 bool d = OPT_GIVEN(DETAILED_HELP);
487 help = lls_long_help(CMD_PTR);
488 else if (OPT_GIVEN(HELP))
489 help = lls_short_help(CMD_PTR);
492 printf("%s\n", help);
497 static void server_init(int argc, char **argv)
499 int ret, afs_socket, daemon_pipe = -1;
503 /* parse command line options */
504 ret = lls(lls_parse(argc, argv, CMD_PTR, &cmdline_lpr, &errctx));
507 server_lpr = cmdline_lpr;
508 daemon_set_loglevel(ENUM_STRING_VAL(LOGLEVEL));
509 daemon_drop_privileges_or_die(OPT_STRING_VAL(USER),
510 OPT_STRING_VAL(GROUP));
511 version_handle_flag("server", OPT_GIVEN(VERSION));
513 parse_config_or_die(false);
515 if (OPT_GIVEN(DAEMON))
516 daemon_pipe = daemonize(true /* parent waits for SIGTERM */);
517 init_random_seed_or_die();
518 daemon_log_welcome("server");
519 init_ipc_or_die(); /* init mmd struct and mmd->lock */
520 daemon_set_start_time();
521 PARA_NOTICE_LOG("initializing audio format handlers\n");
525 * Although afs uses its own signal handling we must ignore SIGUSR1
526 * _before_ the afs child process gets born by init_afs() below. It's
527 * racy to do this in the child because the parent might send SIGUSR1
528 * before the child gets a chance to ignore this signal.
530 * We also have to block SIGCHLD before the afs process is created
531 * because otherwise para_server does not notice if afs dies before the
532 * SIGCHLD handler has been installed for the parent process by
533 * init_signal_task() below.
535 para_sigaction(SIGUSR1, SIG_IGN);
536 para_block_signal(SIGCHLD);
537 PARA_NOTICE_LOG("initializing the audio file selector\n");
538 afs_socket = init_afs(argc, argv);
540 para_unblock_signal(SIGCHLD);
541 PARA_NOTICE_LOG("initializing virtual streaming system\n");
542 vss_init(afs_socket, &sched);
543 init_server_command_task(argc, argv);
544 if (daemon_pipe >= 0) {
545 if (write(daemon_pipe, "\0", 1) < 0) {
546 PARA_EMERG_LOG("daemon_pipe: %s", strerror(errno));
551 PARA_NOTICE_LOG("server init complete\n");
556 PARA_ERROR_LOG("%s\n", errctx);
557 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
561 static void status_refresh(void)
563 static int prev_uptime = -1, prev_events = -1;
564 int uptime = daemon_get_uptime(now);
566 if (prev_events != mmd->events)
568 if (mmd->new_vss_status_flags != mmd->vss_status_flags)
570 if (uptime / 60 != prev_uptime / 60)
576 prev_uptime = uptime;
577 prev_events = mmd->events;
578 mmd->vss_status_flags = mmd->new_vss_status_flags;
579 PARA_DEBUG_LOG("%u events, forcing status update\n", mmd->events);
583 static int server_select(int max_fileno, fd_set *readfds, fd_set *writefds,
584 struct timeval *timeout_tv)
589 mutex_unlock(mmd_mutex);
590 ret = para_select(max_fileno + 1, readfds, writefds, timeout_tv);
591 mutex_lock(mmd_mutex);
596 * The main function of para_server.
598 * \param argc Usual argument count.
599 * \param argv Usual argument vector.
601 * \return EXIT_SUCCESS or EXIT_FAILURE.
603 int main(int argc, char *argv[])
607 sched.default_timeout.tv_sec = 1;
608 sched.select_function = server_select;
610 server_init(argc, argv);
611 mutex_lock(mmd_mutex);
612 ret = schedule(&sched);
613 sched_shutdown(&sched);
614 lls_free_parse_result(server_lpr, CMD_PTR);
615 if (server_lpr != cmdline_lpr)
616 lls_free_parse_result(cmdline_lpr, CMD_PTR);
618 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
619 exit(ret < 0? EXIT_FAILURE : EXIT_SUCCESS);