2 * Copyright (C) 1997-2013 Andre Noll <maan@systemlinux.org>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file server.c Paraslash's main server. */
11 * \mainpage Paraslash API Reference
13 * Starting points for getting an overview:
16 * - The main programs: \ref server.c, \ref audiod.c, \ref client.c,
17 * \ref audioc.c, \ref afh.c, \ref play.c,
18 * - Server: \ref server_command, \ref sender,
19 * - Audio file selector: \ref audio_format_handler, \ref afs_table,
20 * - Client: \ref receiver, \ref receiver_node, \ref filter,
21 * \ref filter_node, \ref writer_node.
24 * The gory details, listed by topic:
26 * - Audio format handlers: \ref send_common.c \ref mp3_afh.c,
27 * \ref ogg_afh.c, \ref aac_afh.c, \ref wma_afh.c, \ref spx_afh.c
28 * - Decoders: \ref mp3dec_filter.c, \ref oggdec_filter.c,
29 * \ref aacdec_filter.c, \ref wmadec_filter.c, spxdec_filter.c,
30 * \ref flacdec_filter.c,
31 * - Volume normalizer: \ref compress_filter.c,
32 * - Output: \ref alsa_write.c, \ref osx_write.c, \ref oss_write.c,
33 * - http: \ref http_recv.c, \ref http_send.c,
34 * - udp: \ref udp_recv.c, \ref udp_send.c,
35 * - dccp: \ref dccp_recv.c, \ref dccp_send.c,
36 * - Audio file selector: \ref afs.c, \ref aft.c, \ref mood.c,
37 * - Afs structures: \ref afs_table, \ref audio_file_data,
38 * \ref afs_info \ref afh_info,
39 * - Afs tables: \ref aft.c, \ref mood.c, \ref playlist.c,
40 * \ref attribute.c, \ref score.c,
41 * - The virtual streaming system: \ref vss.c, \ref chunk_queue.c.
45 * - Scheduling: \ref sched.c, \ref sched.h,
46 * - Networking: \ref net.c,
47 * - File descriptors: \ref fd.c,
48 * - Signals: \ref signal.c,
49 * - Daemons: \ref daemon.c,
50 * - Strings: \ref string.c, \ref string.h,
51 * - Time: \ref time.c,
52 * - Spawning processes: \ref exec.c,
53 * - Inter process communication: \ref ipc.c,
54 * - Blob tables: \ref blob.c,
55 * - The error subsystem: \ref error.h.
56 * - Access control for paraslash senders: \ref acl.c, \ref acl.h.
57 * - Internal crypto API: \ref crypt.h.
58 * - interactive sessions (libreadline): \ref interactive.c.
60 * Low-level data structures:
62 * - Doubly linked lists: \ref list.h,
63 * - Ring buffer: \ref ringbuffer.c, \ref ringbuffer.h,
64 * - openssl: \ref crypt.c
65 * - libgcrypt: \ref gcrypt.c
66 * - Forward error correction: \ref fec.c.
77 #include "server.cmdline.h"
87 #include "close_on_fork.h"
93 #include "user_list.h"
97 __printf_2_3 void (*para_log)(int, const char*, ...) = daemon_log;
99 /** Define the array of error lists needed by para_server. */
100 INIT_SERVER_ERRLISTS;
102 /** Shut down non-authorized connections after that many seconds. */
103 #define ALARM_TIMEOUT 10
106 * Pointer to shared memory area for communication between para_server
107 * and its children. Exported to vss.c. command.c and to afs.
109 struct misc_meta_data *mmd;
112 * The configuration of para_server
114 * It also contains the options for the audio file selector, audio format
115 * handler and all supported senders.
117 struct server_args_info conf;
119 /** A random value used in child context for authentication. */
120 uint32_t afs_socket_cookie;
122 /** The mutex protecting the shared memory area containing the mmd struct. */
125 /** The file containing user information (public key, permissions). */
126 static char *user_list_file = NULL;
128 static struct sched sched;
130 /** The task responsible for server command handling. */
131 struct server_command_task {
132 /** TCP port on which para_server listens for connections. */
134 /** Copied from para_server's main function. */
136 /** Argument vector passed to para_server's main function. */
138 /** The command task structure for scheduling. */
142 static int want_colors(void)
144 if (conf.color_arg == color_arg_no)
146 if (conf.color_arg == color_arg_yes)
148 if (conf.logfile_given)
150 return isatty(STDERR_FILENO);
153 static void init_colors_or_die(void)
159 daemon_set_flag(DF_COLOR_LOG);
160 daemon_set_default_log_colors();
161 for (i = 0; i < conf.log_color_given; i++)
162 daemon_set_log_color_or_die(conf.log_color_arg[i]);
166 * setup shared memory area and get mutex for locking
168 static void init_ipc_or_die(void)
171 int shmid, ret = shm_new(sizeof(struct misc_meta_data));
176 ret = shm_attach(shmid, ATTACH_RW, &shm);
188 mmd->num_commands = 0;
190 mmd->num_connects = 0;
191 mmd->active_connections = 0;
192 mmd->vss_status_flags = VSS_NEXT;
193 mmd->new_vss_status_flags = VSS_NEXT;
196 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
201 * (Re-)read the server configuration files.
203 * \param override Passed to gengetopt to activate the override feature.
205 * This function also re-opens the logfile and sets the global \a
206 * user_list_file variable.
208 void parse_config_or_die(int override)
210 char *home = para_homedir();
215 if (conf.config_file_given)
216 cf = para_strdup(conf.config_file_arg);
218 cf = make_message("%s/.paraslash/server.conf", home);
219 free(user_list_file);
220 if (!conf.user_list_given)
221 user_list_file = make_message("%s/.paraslash/server.users", home);
223 user_list_file = para_strdup(conf.user_list_arg);
224 ret = file_exists(cf);
225 if (conf.config_file_given && !ret) {
227 PARA_EMERG_LOG("can not read config file %s\n", cf);
231 int tmp = conf.daemon_given;
232 struct server_cmdline_parser_params params = {
233 .override = override,
236 .check_ambiguity = 0,
237 .print_errors = !conf.daemon_given
239 server_cmdline_parser_config_file(cf, &conf, ¶ms);
240 conf.daemon_given = tmp;
242 if (conf.logfile_given) {
243 daemon_set_logfile(conf.logfile_arg);
244 daemon_open_log_or_die();
246 daemon_set_loglevel(conf.loglevel_arg);
247 init_colors_or_die();
248 daemon_set_flag(DF_LOG_PID);
249 daemon_set_flag(DF_LOG_LL);
250 daemon_set_flag(DF_LOG_TIME);
251 if (conf.log_timing_given)
252 daemon_set_flag(DF_LOG_TIMING);
259 free(user_list_file);
260 user_list_file = NULL;
264 static void signal_pre_select(struct sched *s, struct task *t)
266 struct signal_task *st = container_of(t, struct signal_task, task);
267 para_fd_set(st->fd, &s->rfds, &s->max_fileno);
271 * called when server gets SIGHUP or when client invokes hup command.
273 static void handle_sighup(void)
275 PARA_NOTICE_LOG("SIGHUP\n");
276 parse_config_or_die(1); /* reopens log */
277 init_user_list(user_list_file); /* reload user list */
279 kill(mmd->afs_pid, SIGHUP);
282 static void signal_post_select(struct sched *s, __a_unused struct task *t)
284 int signum = para_next_signal(&s->rfds);
295 int ret = para_reap_child(&pid);
298 if (pid != mmd->afs_pid)
300 PARA_EMERG_LOG("fatal: afs died\n");
305 /* die on sigint/sigterm. Kill all children too. */
308 PARA_EMERG_LOG("terminating on signal %d\n", signum);
311 * We must wait for afs because afs catches SIGINT/SIGTERM.
312 * Before reacting to the signal, afs might want to use the
313 * shared memory area and the mmd mutex. If we destroy this
314 * mutex too early and afs tries to lock the shared memory
315 * area, the call to mutex_lock() will fail and terminate the
316 * afs process. This leads to dirty osl tables.
318 * There's no such problem with the other children of the
319 * server process (the command handlers) as these reset their
320 * SIGINT/SIGTERM handlers to the default action, i.e. these
321 * processes get killed immediately by the above kill().
323 PARA_INFO_LOG("waiting for afs (pid %d) to die\n",
325 waitpid(mmd->afs_pid, NULL, 0);
327 free(mmd->afd.afhi.chunk_table);
329 mutex_destroy(mmd_mutex);
335 static void init_signal_task(void)
337 static struct signal_task signal_task_struct,
338 *st = &signal_task_struct;
340 st->task.pre_select = signal_pre_select;
341 st->task.post_select = signal_post_select;
342 sprintf(st->task.status, "signal task");
344 PARA_NOTICE_LOG("setting up signal handling\n");
345 st->fd = para_signal_init(); /* always successful */
346 para_install_sighandler(SIGINT);
347 para_install_sighandler(SIGTERM);
348 para_install_sighandler(SIGHUP);
349 para_install_sighandler(SIGCHLD);
350 para_sigaction(SIGPIPE, SIG_IGN);
351 add_close_on_fork_list(st->fd);
352 register_task(&sched, &st->task);
355 static void command_pre_select(struct sched *s, struct task *t)
357 struct server_command_task *sct = container_of(t, struct server_command_task, task);
358 para_fd_set(sct->listen_fd, &s->rfds, &s->max_fileno);
361 static void command_post_select(struct sched *s, struct task *t)
363 struct server_command_task *sct = container_of(t, struct server_command_task, task);
368 uint32_t *chunk_table;
370 ret = para_accept(sct->listen_fd, &s->rfds, NULL, 0, &new_fd);
373 peer_name = remote_name(new_fd);
374 PARA_INFO_LOG("got connection from %s, forking\n", peer_name);
376 mmd->active_connections++;
378 * The chunk table is a pointer located in the mmd struct that points
379 * to dynamically allocated memory, i.e. it must be freed by the parent
380 * and the child. However, as the mmd struct is in a shared memory
381 * area, there's no guarantee that after the fork this pointer is still
382 * valid in child context. As it is not used in the child anyway, we
383 * save it to a local variable before the fork and free the memory via
384 * that copy in the child directly after the fork.
386 chunk_table = mmd->afd.afhi.chunk_table;
389 ret = -ERRNO_TO_PARA_ERROR(errno);
394 /* parent keeps accepting connections */
397 /* mmd might already have changed at this point */
399 alarm(ALARM_TIMEOUT);
401 para_signal_shutdown();
403 * put info on who we are serving into argv[0] to make
404 * client ip visible in top/ps
406 for (i = sct->argc - 1; i >= 0; i--)
407 memset(sct->argv[i], 0, strlen(sct->argv[i]));
408 sprintf(sct->argv[0], "para_server (serving %s)", peer_name);
409 return handle_connect(new_fd, peer_name);
412 PARA_CRIT_LOG("%s\n", para_strerror(-ret));
415 static void init_server_command_task(int argc, char **argv)
418 static struct server_command_task server_command_task_struct,
419 *sct = &server_command_task_struct;
421 PARA_NOTICE_LOG("initializing tcp command socket\n");
422 sct->task.pre_select = command_pre_select;
423 sct->task.post_select = command_post_select;
426 ret = para_listen_simple(IPPROTO_TCP, conf.port_arg);
429 sct->listen_fd = ret;
430 ret = mark_fd_nonblocking(sct->listen_fd);
433 add_close_on_fork_list(sct->listen_fd); /* child doesn't need the listener */
434 sprintf(sct->task.status, "server command task");
435 register_task(&sched, &sct->task);
438 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
442 static int init_afs(int argc, char **argv)
444 int ret, afs_server_socket[2];
447 ret = socketpair(PF_UNIX, SOCK_DGRAM, 0, afs_server_socket);
450 get_random_bytes_or_die((unsigned char *)&afs_socket_cookie,
451 sizeof(afs_socket_cookie));
455 if (afs_pid == 0) { /* child (afs) */
457 for (i = argc - 1; i >= 0; i--)
458 memset(argv[i], 0, strlen(argv[i]));
459 sprintf(argv[0], "para_server (afs)");
460 close(afs_server_socket[0]);
461 afs_init(afs_socket_cookie, afs_server_socket[1]);
463 mmd->afs_pid = afs_pid;
464 close(afs_server_socket[1]);
465 ret = mark_fd_nonblocking(afs_server_socket[0]);
468 add_close_on_fork_list(afs_server_socket[0]);
469 PARA_INFO_LOG("afs_socket: %d, afs_socket_cookie: %u\n",
470 afs_server_socket[0], (unsigned) afs_socket_cookie);
471 return afs_server_socket[0];
474 static void server_init(int argc, char **argv)
476 struct server_cmdline_parser_params params = {
480 .check_ambiguity = 0,
486 init_random_seed_or_die();
487 /* parse command line options */
488 server_cmdline_parser_ext(argc, argv, &conf, ¶ms);
489 HANDLE_VERSION_FLAG("server", conf);
490 drop_privileges_or_die(conf.user_arg, conf.group_arg);
491 /* parse config file, open log and set defaults */
492 parse_config_or_die(0);
493 log_welcome("para_server");
494 init_ipc_or_die(); /* init mmd struct and mmd->lock */
495 /* make sure, the global now pointer is uptodate */
496 gettimeofday(now, NULL);
497 set_server_start_time(now);
498 init_user_list(user_list_file);
500 if (conf.daemon_given)
501 daemonize(true /* parent waits for SIGTERM */);
502 PARA_NOTICE_LOG("initializing audio format handlers\n");
506 * Although afs uses its own signal handling we must ignore SIGUSR1
507 * _before_ the afs child process gets born by init_afs() below. It's
508 * racy to do this in the child because the parent might send SIGUSR1
509 * before the child gets a chance to ignore this signal -- only the
512 para_sigaction(SIGUSR1, SIG_IGN);
514 * We have to block SIGCHLD before the afs process is being forked off.
515 * Otherwise, para_server does not notice if afs dies before the
516 * SIGCHLD handler has been installed for the parent process by
517 * init_signal_task() below.
519 para_block_signal(SIGCHLD);
520 PARA_NOTICE_LOG("initializing the audio file selector\n");
521 afs_socket = init_afs(argc, argv);
523 para_unblock_signal(SIGCHLD);
524 PARA_NOTICE_LOG("initializing virtual streaming system\n");
525 init_vss_task(afs_socket, &sched);
526 init_server_command_task(argc, argv);
527 if (conf.daemon_given)
528 kill(getppid(), SIGTERM);
529 PARA_NOTICE_LOG("server init complete\n");
532 static void status_refresh(void)
534 static int prev_uptime = -1, prev_events = -1;
535 int uptime = get_server_uptime(now);
537 if (prev_events != mmd->events)
539 if (mmd->new_vss_status_flags != mmd->vss_status_flags)
541 if (uptime / 60 != prev_uptime / 60)
547 prev_uptime = uptime;
548 prev_events = mmd->events;
549 mmd->vss_status_flags = mmd->new_vss_status_flags;
550 PARA_DEBUG_LOG("%d events, forcing status update\n", mmd->events);
554 static int server_select(int max_fileno, fd_set *readfds, fd_set *writefds,
555 struct timeval *timeout_tv)
560 mutex_unlock(mmd_mutex);
561 ret = para_select(max_fileno + 1, readfds, writefds, timeout_tv);
562 mutex_lock(mmd_mutex);
567 * The main function of para_server.
569 * \param argc Usual argument count.
570 * \param argv Usual argument vector.
572 * \return EXIT_SUCCESS or EXIT_FAILURE.
574 int main(int argc, char *argv[])
578 sched.default_timeout.tv_sec = 1;
579 sched.select_function = server_select;
581 server_init(argc, argv);
582 mutex_lock(mmd_mutex);
583 ret = schedule(&sched);
585 PARA_EMERG_LOG("%s\n", para_strerror(-ret));