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 Starting points for getting an overview:
13 * - The main programs: \ref server.c, \ref audiod.c, \ref client.c,
14 * \ref audioc.c, \ref afh.c, \ref play.c,
15 * - Server: \ref server_command, \ref sender,
16 * - Audio file selector: \ref audio_format_handler, \ref afs_table,
17 * - Client: \ref receiver, \ref receiver_node, \ref filter,
18 * \ref filter_node, \ref writer_node.
21 * The gory details, listed by topic:
23 * - Audio format handlers: \ref send_common.c \ref mp3_afh.c,
24 * \ref ogg_afh.c, \ref aac_afh.c, \ref wma_afh.c, \ref spx_afh.c
25 * - Decoders: \ref mp3dec_filter.c, \ref oggdec_filter.c,
26 * \ref aacdec_filter.c, \ref wmadec_filter.c, spxdec_filter.c,
27 * \ref flacdec_filter.c,
28 * - Volume normalizer: \ref compress_filter.c,
29 * - Output: \ref alsa_write.c, \ref osx_write.c, \ref oss_write.c,
30 * - http: \ref http_recv.c, \ref http_send.c,
31 * - udp: \ref udp_recv.c, \ref udp_send.c,
32 * - dccp: \ref dccp_recv.c, \ref dccp_send.c,
33 * - Audio file selector: \ref afs.c, \ref aft.c, \ref mood.c,
34 * - Afs structures: \ref afs_table, \ref audio_file_data,
35 * \ref afs_info \ref afh_info,
36 * - Afs tables: \ref aft.c, \ref mood.c, \ref playlist.c,
37 * \ref attribute.c, \ref score.c,
38 * - The virtual streaming system: \ref vss.c, \ref chunk_queue.c.
42 * - Scheduling: \ref sched.c, \ref sched.h,
43 * - Networking: \ref net.c,
44 * - File descriptors: \ref fd.c,
45 * - Signals: \ref signal.c,
46 * - Daemons: \ref daemon.c,
47 * - Strings: \ref string.c, \ref string.h,
48 * - Time: \ref time.c,
49 * - Spawning processes: \ref exec.c,
50 * - Inter process communication: \ref ipc.c,
51 * - Blob tables: \ref blob.c,
52 * - The error subsystem: \ref error.h.
53 * - Access control for paraslash senders: \ref acl.c, \ref acl.h.
54 * - Internal crypto API: \ref crypt.h.
55 * - interactive sessions (libreadline): \ref interactive.c.
57 * Low-level data structures:
59 * - Doubly linked lists: \ref list.h,
60 * - Ring buffer: \ref ringbuffer.c, \ref ringbuffer.h,
61 * - openssl: \ref crypt.c
62 * - libgcrypt: \ref gcrypt.c
63 * - Forward error correction: \ref fec.c.
66 #include <netinet/in.h>
67 #include <sys/socket.h>
71 #include <sys/types.h>
72 #include <arpa/inet.h>
79 #include "server.cmdline.h"
89 #include "close_on_fork.h"
95 #include "user_list.h"
100 __printf_2_3 void (*para_log)(int, const char*, ...) = daemon_log;
102 /** Define the array of error lists needed by para_server. */
103 INIT_SERVER_ERRLISTS;
105 /** Shut down non-authorized connections after that many seconds. */
106 #define ALARM_TIMEOUT 10
109 * Pointer to shared memory area for communication between para_server
110 * and its children. Exported to vss.c. command.c and to afs.
112 struct misc_meta_data *mmd;
115 * The configuration of para_server
117 * It also contains the options for the audio file selector, audio format
118 * handler and all supported senders.
120 struct server_args_info conf;
122 /** A random value used in child context for authentication. */
123 uint32_t afs_socket_cookie;
125 /** The mutex protecting the shared memory area containing the mmd struct. */
128 /** The file containing user information (public key, permissions). */
129 static char *user_list_file = NULL;
131 static struct sched sched;
133 /** The task responsible for server command handling. */
134 struct server_command_task {
135 /** TCP port on which para_server listens for connections. */
137 /** Copied from para_server's main function. */
139 /** Argument vector passed to para_server's main function. */
141 /** The command task structure for scheduling. */
145 static int want_colors(void)
147 if (conf.color_arg == color_arg_no)
149 if (conf.color_arg == color_arg_yes)
151 if (conf.logfile_given)
153 return isatty(STDERR_FILENO);
156 static void init_colors_or_die(void)
162 daemon_set_flag(DF_COLOR_LOG);
163 daemon_set_default_log_colors();
164 for (i = 0; i < conf.log_color_given; i++)
165 daemon_set_log_color_or_die(conf.log_color_arg[i]);
169 * setup shared memory area and get mutex for locking
171 static void init_ipc_or_die(void)
174 int shmid, ret = shm_new(sizeof(struct misc_meta_data));
179 ret = shm_attach(shmid, ATTACH_RW, &shm);
191 mmd->num_commands = 0;
193 mmd->num_connects = 0;
194 mmd->active_connections = 0;
195 mmd->vss_status_flags = VSS_NEXT;
196 mmd->new_vss_status_flags = VSS_NEXT;
199 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
204 * (Re-)read the server configuration files.
206 * \param override Passed to gengetopt to activate the override feature.
208 * This function also re-opens the logfile and sets the global \a
209 * user_list_file variable.
211 void parse_config_or_die(int override)
213 char *home = para_homedir();
218 if (conf.config_file_given)
219 cf = para_strdup(conf.config_file_arg);
221 cf = make_message("%s/.paraslash/server.conf", home);
222 free(user_list_file);
223 if (!conf.user_list_given)
224 user_list_file = make_message("%s/.paraslash/server.users", home);
226 user_list_file = para_strdup(conf.user_list_arg);
227 ret = file_exists(cf);
228 if (conf.config_file_given && !ret) {
230 PARA_EMERG_LOG("can not read config file %s\n", cf);
234 int tmp = conf.daemon_given;
235 struct server_cmdline_parser_params params = {
236 .override = override,
239 .check_ambiguity = 0,
240 .print_errors = !conf.daemon_given
242 server_cmdline_parser_config_file(cf, &conf, ¶ms);
243 daemon_set_loglevel(conf.loglevel_arg);
244 conf.daemon_given = tmp;
246 if (conf.logfile_given) {
247 daemon_set_logfile(conf.logfile_arg);
248 daemon_open_log_or_die();
250 init_colors_or_die();
251 daemon_set_flag(DF_LOG_PID);
252 daemon_set_flag(DF_LOG_LL);
253 daemon_set_flag(DF_LOG_TIME);
254 if (conf.log_timing_given)
255 daemon_set_flag(DF_LOG_TIMING);
262 free(user_list_file);
263 user_list_file = NULL;
267 static void signal_pre_select(struct sched *s, struct task *t)
269 struct signal_task *st = container_of(t, struct signal_task, task);
270 para_fd_set(st->fd, &s->rfds, &s->max_fileno);
274 * called when server gets SIGHUP or when client invokes hup command.
276 static void handle_sighup(void)
278 PARA_NOTICE_LOG("SIGHUP\n");
279 parse_config_or_die(1); /* reopens log */
280 init_user_list(user_list_file); /* reload user list */
282 kill(mmd->afs_pid, SIGHUP);
285 static int signal_post_select(struct sched *s, __a_unused struct task *t)
287 int signum = para_next_signal(&s->rfds);
298 int ret = para_reap_child(&pid);
301 if (pid != mmd->afs_pid)
303 PARA_EMERG_LOG("fatal: afs died\n");
308 /* die on sigint/sigterm. Kill all children too. */
311 PARA_EMERG_LOG("terminating on signal %d\n", signum);
314 * We must wait for afs because afs catches SIGINT/SIGTERM.
315 * Before reacting to the signal, afs might want to use the
316 * shared memory area and the mmd mutex. If we destroy this
317 * mutex too early and afs tries to lock the shared memory
318 * area, the call to mutex_lock() will fail and terminate the
319 * afs process. This leads to dirty osl tables.
321 * There's no such problem with the other children of the
322 * server process (the command handlers) as these reset their
323 * SIGINT/SIGTERM handlers to the default action, i.e. these
324 * processes get killed immediately by the above kill().
326 PARA_INFO_LOG("waiting for afs (pid %d) to die\n",
328 waitpid(mmd->afs_pid, NULL, 0);
330 free(mmd->afd.afhi.chunk_table);
332 mutex_destroy(mmd_mutex);
339 static void init_signal_task(void)
341 static struct signal_task signal_task_struct,
342 *st = &signal_task_struct;
344 st->task.pre_select = signal_pre_select;
345 st->task.post_select = signal_post_select;
346 sprintf(st->task.status, "signal task");
348 PARA_NOTICE_LOG("setting up signal handling\n");
349 st->fd = para_signal_init(); /* always successful */
350 para_install_sighandler(SIGINT);
351 para_install_sighandler(SIGTERM);
352 para_install_sighandler(SIGHUP);
353 para_install_sighandler(SIGCHLD);
354 para_sigaction(SIGPIPE, SIG_IGN);
355 add_close_on_fork_list(st->fd);
356 register_task(&sched, &st->task);
359 static void command_pre_select(struct sched *s, struct task *t)
361 struct server_command_task *sct = container_of(t, struct server_command_task, task);
362 para_fd_set(sct->listen_fd, &s->rfds, &s->max_fileno);
365 static int command_post_select(struct sched *s, struct task *t)
367 struct server_command_task *sct = container_of(t, struct server_command_task, task);
372 uint32_t *chunk_table;
374 ret = para_accept(sct->listen_fd, &s->rfds, NULL, 0, &new_fd);
377 peer_name = remote_name(new_fd);
378 PARA_INFO_LOG("got connection from %s, forking\n", peer_name);
380 mmd->active_connections++;
382 * The chunk table is a pointer located in the mmd struct that points
383 * to dynamically allocated memory, i.e. it must be freed by the parent
384 * and the child. However, as the mmd struct is in a shared memory
385 * area, there's no guarantee that after the fork this pointer is still
386 * valid in child context. As it is not used in the child anyway, we
387 * save it to a local variable before the fork and free the memory via
388 * that copy in the child directly after the fork.
390 chunk_table = mmd->afd.afhi.chunk_table;
393 ret = -ERRNO_TO_PARA_ERROR(errno);
397 /* avoid problems with non-fork-safe PRNGs */
398 unsigned char buf[16];
399 get_random_bytes_or_die(buf, sizeof(buf));
401 /* parent keeps accepting connections */
404 /* mmd might already have changed at this point */
406 alarm(ALARM_TIMEOUT);
408 para_signal_shutdown();
410 * put info on who we are serving into argv[0] to make
411 * client ip visible in top/ps
413 for (i = sct->argc - 1; i >= 0; i--)
414 memset(sct->argv[i], 0, strlen(sct->argv[i]));
415 sprintf(sct->argv[0], "para_server (serving %s)", peer_name);
416 handle_connect(new_fd, peer_name);
420 PARA_CRIT_LOG("%s\n", para_strerror(-ret));
424 static void init_server_command_task(int argc, char **argv)
427 static struct server_command_task server_command_task_struct,
428 *sct = &server_command_task_struct;
430 PARA_NOTICE_LOG("initializing tcp command socket\n");
431 sct->task.pre_select = command_pre_select;
432 sct->task.post_select = command_post_select;
435 ret = para_listen_simple(IPPROTO_TCP, conf.port_arg);
438 sct->listen_fd = ret;
439 ret = mark_fd_nonblocking(sct->listen_fd);
442 add_close_on_fork_list(sct->listen_fd); /* child doesn't need the listener */
443 sprintf(sct->task.status, "server command task");
444 register_task(&sched, &sct->task);
447 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
451 static int init_afs(int argc, char **argv)
453 int ret, afs_server_socket[2];
456 ret = socketpair(PF_UNIX, SOCK_DGRAM, 0, afs_server_socket);
459 get_random_bytes_or_die((unsigned char *)&afs_socket_cookie,
460 sizeof(afs_socket_cookie));
464 if (afs_pid == 0) { /* child (afs) */
466 for (i = argc - 1; i >= 0; i--)
467 memset(argv[i], 0, strlen(argv[i]));
468 sprintf(argv[0], "para_server (afs)");
469 close(afs_server_socket[0]);
470 afs_init(afs_socket_cookie, afs_server_socket[1]);
472 mmd->afs_pid = afs_pid;
473 close(afs_server_socket[1]);
474 ret = mark_fd_nonblocking(afs_server_socket[0]);
477 add_close_on_fork_list(afs_server_socket[0]);
478 PARA_INFO_LOG("afs_socket: %d, afs_socket_cookie: %u\n",
479 afs_server_socket[0], (unsigned) afs_socket_cookie);
480 return afs_server_socket[0];
483 __noreturn static void print_help_and_die(void)
485 struct ggo_help h = DEFINE_GGO_HELP(server);
486 bool d = conf.detailed_help_given;
488 ggo_print_help(&h, d? GPH_STANDARD_FLAGS_DETAILED : GPH_STANDARD_FLAGS);
492 static void server_init(int argc, char **argv)
494 struct server_cmdline_parser_params params = {
498 .check_ambiguity = 0,
504 init_random_seed_or_die();
505 /* parse command line options */
506 server_cmdline_parser_ext(argc, argv, &conf, ¶ms);
507 daemon_set_loglevel(conf.loglevel_arg);
508 version_handle_flag("server", conf.version_given);
509 if (conf.help_given || conf.detailed_help_given)
510 print_help_and_die();
511 drop_privileges_or_die(conf.user_arg, conf.group_arg);
512 /* parse config file, open log and set defaults */
513 parse_config_or_die(0);
514 log_welcome("para_server");
515 init_ipc_or_die(); /* init mmd struct and mmd->lock */
516 /* make sure, the global now pointer is uptodate */
517 clock_get_realtime(now);
518 set_server_start_time(now);
519 init_user_list(user_list_file);
521 if (conf.daemon_given)
522 daemonize(true /* parent waits for SIGTERM */);
523 PARA_NOTICE_LOG("initializing audio format handlers\n");
527 * Although afs uses its own signal handling we must ignore SIGUSR1
528 * _before_ the afs child process gets born by init_afs() below. It's
529 * racy to do this in the child because the parent might send SIGUSR1
530 * before the child gets a chance to ignore this signal -- only the
533 para_sigaction(SIGUSR1, SIG_IGN);
535 * We have to block SIGCHLD before the afs process is being forked off.
536 * Otherwise, para_server does not notice if afs dies before the
537 * SIGCHLD handler has been installed for the parent process by
538 * init_signal_task() below.
540 para_block_signal(SIGCHLD);
541 PARA_NOTICE_LOG("initializing the audio file selector\n");
542 afs_socket = init_afs(argc, argv);
544 para_unblock_signal(SIGCHLD);
545 PARA_NOTICE_LOG("initializing virtual streaming system\n");
546 init_vss_task(afs_socket, &sched);
547 init_server_command_task(argc, argv);
548 if (conf.daemon_given)
549 kill(getppid(), SIGTERM);
550 PARA_NOTICE_LOG("server init complete\n");
553 static void status_refresh(void)
555 static int prev_uptime = -1, prev_events = -1;
556 int uptime = get_server_uptime(now);
558 if (prev_events != mmd->events)
560 if (mmd->new_vss_status_flags != mmd->vss_status_flags)
562 if (uptime / 60 != prev_uptime / 60)
568 prev_uptime = uptime;
569 prev_events = mmd->events;
570 mmd->vss_status_flags = mmd->new_vss_status_flags;
571 PARA_DEBUG_LOG("%d events, forcing status update\n", mmd->events);
575 static int server_select(int max_fileno, fd_set *readfds, fd_set *writefds,
576 struct timeval *timeout_tv)
581 mutex_unlock(mmd_mutex);
582 ret = para_select(max_fileno + 1, readfds, writefds, timeout_tv);
583 mutex_lock(mmd_mutex);
588 * The main function of para_server.
590 * \param argc Usual argument count.
591 * \param argv Usual argument vector.
593 * \return EXIT_SUCCESS or EXIT_FAILURE.
595 int main(int argc, char *argv[])
599 sched.default_timeout.tv_sec = 1;
600 sched.select_function = server_select;
602 server_init(argc, argv);
603 mutex_lock(mmd_mutex);
604 ret = schedule(&sched);
606 PARA_EMERG_LOG("%s\n", para_strerror(-ret));