server: Implement --listen-address for control service.
[paraslash.git] / server.c
1 /* Copyright (C) 1997 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
2
3 /** \file server.c Paraslash's main server. */
4
5 /**
6 * \mainpage Main data structures and selected APIs:
7 *
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.
28 */
29
30 #include <netinet/in.h>
31 #include <sys/socket.h>
32 #include <signal.h>
33 #include <regex.h>
34 #include <osl.h>
35 #include <sys/types.h>
36 #include <arpa/inet.h>
37 #include <sys/un.h>
38 #include <netdb.h>
39 #include <lopsub.h>
40
41 #include "server.lsg.h"
42 #include "para.h"
43 #include "error.h"
44 #include "crypt.h"
45 #include "afh.h"
46 #include "string.h"
47 #include "afs.h"
48 #include "net.h"
49 #include "server.h"
50 #include "list.h"
51 #include "send.h"
52 #include "sched.h"
53 #include "vss.h"
54 #include "config.h"
55 #include "close_on_fork.h"
56 #include "daemon.h"
57 #include "ipc.h"
58 #include "fd.h"
59 #include "signal.h"
60 #include "user_list.h"
61 #include "color.h"
62 #include "version.h"
63
64 /** Array of error strings. */
65 DEFINE_PARA_ERRLIST;
66
67 __printf_2_3 void (*para_log)(int, const char*, ...) = daemon_log;
68
69 /** Shut down non-authorized connections after that many seconds. */
70 #define ALARM_TIMEOUT 10
71
72 /**
73 * Pointer to shared memory area for communication between para_server
74 * and its children. Exported to vss.c, command.c and to afs.
75 */
76 struct misc_meta_data *mmd;
77
78 /**
79 * The active value for all config options of para_server.
80 *
81 * It is computed by merging the parse result of the command line options with
82 * the parse result of the config file.
83 */
84 struct lls_parse_result *server_lpr = NULL;
85
86 /* Command line options (no config file options). Used in handle_sighup(). */
87 static struct lls_parse_result *cmdline_lpr;
88
89 /**
90 * A random number used to "authenticate" the afs connection.
91 *
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.
97 */
98 uint32_t afs_socket_cookie;
99
100 /** The mutex protecting the shared memory area containing the mmd struct. */
101 int mmd_mutex;
102
103 static struct sched sched;
104 static struct signal_task *signal_task;
105
106 /** The process id of the audio file selector process. */
107 pid_t afs_pid = 0;
108
109 /** The task responsible for server command handling. */
110 struct server_command_task {
111 unsigned num_listen_fds; /* only one by default */
112 /** TCP socket(s) on which para_server listens for connections. */
113 int *listen_fds;
114 /** Copied from para_server's main function. */
115 int argc;
116 /** Argument vector passed to para_server's main function. */
117 char **argv;
118 /** The command task structure for scheduling. */
119 struct task *task;
120 };
121
122 /**
123 * Return the list of tasks for the server process.
124 *
125 * This is called from \a com_tasks(). The helper is necessary since command
126 * handlers can not access the scheduler structure directly.
127 *
128 * \return A dynamically allocated string that must be freed by the caller.
129 */
130 char *server_get_tasks(void)
131 {
132 return get_task_list(&sched);
133 }
134
135 /*
136 * setup shared memory area and get mutex for locking
137 */
138 static void init_ipc_or_die(void)
139 {
140 void *shm;
141 int shmid, ret = shm_new(sizeof(struct misc_meta_data));
142
143 if (ret < 0)
144 goto err_out;
145 shmid = ret;
146 ret = shm_attach(shmid, ATTACH_RW, &shm);
147 shm_destroy(shmid);
148 if (ret < 0)
149 goto err_out;
150 mmd = shm;
151
152 ret = mutex_new();
153 if (ret < 0)
154 goto err_out;
155 mmd_mutex = ret;
156
157 mmd->num_played = 0;
158 mmd->num_commands = 0;
159 mmd->events = 0;
160 mmd->num_connects = 0;
161 mmd->active_connections = 0;
162 mmd->vss_status_flags = VSS_NEXT;
163 mmd->new_vss_status_flags = VSS_NEXT;
164 return;
165 err_out:
166 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
167 exit(EXIT_FAILURE);
168 }
169
170 /**
171 * (Re-)read the server configuration files.
172 *
173 * \param reload Whether config file overrides command line.
174 *
175 * This function also re-opens the logfile and the user list. On SIGHUP it is
176 * called from both server and afs context.
177 */
178 void parse_config_or_die(bool reload)
179 {
180 int ret;
181 char *cf = NULL, *errctx = NULL, *user_list_file = NULL;
182 void *map;
183 size_t sz;
184 int cf_argc;
185 char **cf_argv;
186 struct lls_parse_result *cf_lpr, *merged_lpr;
187 char *home = para_homedir();
188
189 if (OPT_GIVEN(CONFIG_FILE))
190 cf = para_strdup(OPT_STRING_VAL(CONFIG_FILE));
191 else
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));
196 else
197 user_list_file = make_message("%s/.paraslash/server.users", home);
198 }
199 free(home);
200 ret = mmap_full_file(cf, O_RDONLY, &map, &sz, NULL);
201 if (ret < 0) {
202 if (ret != -E_EMPTY && ret != -ERRNO_TO_PARA_ERROR(ENOENT))
203 goto free_cf;
204 if (ret == -ERRNO_TO_PARA_ERROR(ENOENT) && OPT_GIVEN(CONFIG_FILE))
205 goto free_cf;
206 server_lpr = cmdline_lpr;
207 goto success;
208 }
209 ret = lls(lls_convert_config(map, sz, NULL, &cf_argv, &errctx));
210 para_munmap(map, sz);
211 if (ret < 0)
212 goto free_cf;
213 cf_argc = ret;
214 ret = lls(lls_parse(cf_argc, cf_argv, CMD_PTR, &cf_lpr, &errctx));
215 lls_free_argv(cf_argv);
216 if (ret < 0)
217 goto free_cf;
218 if (reload) /* config file overrides command line */
219 ret = lls(lls_merge(cf_lpr, cmdline_lpr, CMD_PTR, &merged_lpr,
220 &errctx));
221 else /* command line options override config file options */
222 ret = lls(lls_merge(cmdline_lpr, cf_lpr, CMD_PTR, &merged_lpr,
223 &errctx));
224 lls_free_parse_result(cf_lpr, CMD_PTR);
225 if (ret < 0)
226 goto free_cf;
227 if (server_lpr != cmdline_lpr)
228 lls_free_parse_result(server_lpr, CMD_PTR);
229 server_lpr = merged_lpr;
230 success:
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();
235 }
236 if (daemon_init_colors_or_die(OPT_UINT32_VAL(COLOR), COLOR_AUTO,
237 COLOR_NO, OPT_GIVEN(LOGFILE))) {
238 int i;
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)));
242 }
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));
249 if (user_list_file)
250 init_user_list(user_list_file);
251 ret = 1;
252 free_cf:
253 free(cf);
254 free(user_list_file);
255 if (ret < 0) {
256 if (errctx)
257 PARA_ERROR_LOG("%s\n", errctx);
258 free(errctx);
259 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
260 exit(EXIT_FAILURE);
261 }
262 }
263
264 /*
265 * called when server gets SIGHUP or when client invokes hup command.
266 */
267 static void handle_sighup(void)
268 {
269
270 PARA_NOTICE_LOG("SIGHUP\n");
271 parse_config_or_die(true);
272 if (afs_pid != 0)
273 kill(afs_pid, SIGHUP);
274 }
275
276 static int signal_post_select(struct sched *s, __a_unused void *context)
277 {
278 int signum = para_next_signal(&s->rfds);
279
280 switch (signum) {
281 case 0:
282 return 0;
283 case SIGHUP:
284 handle_sighup();
285 break;
286 case SIGCHLD:
287 for (;;) {
288 pid_t pid;
289 int ret = para_reap_child(&pid);
290 if (ret <= 0)
291 break;
292 if (pid != afs_pid)
293 continue;
294 PARA_EMERG_LOG("fatal: afs died\n");
295 kill(0, SIGTERM);
296 goto cleanup;
297 }
298 break;
299 /* die on sigint/sigterm. Kill all children too. */
300 case SIGINT:
301 case SIGTERM:
302 PARA_EMERG_LOG("terminating on signal %d\n", signum);
303 kill(0, SIGTERM);
304 /*
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.
311 *
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().
316 */
317 PARA_INFO_LOG("waiting for afs (pid %d) to die\n",
318 (int)afs_pid);
319 waitpid(afs_pid, NULL, 0);
320 cleanup:
321 free(mmd->afd.afhi.chunk_table);
322 close_listed_fds();
323 mutex_destroy(mmd_mutex);
324 shm_detach(mmd);
325 exit(EXIT_FAILURE);
326 }
327 return 0;
328 }
329
330 static void init_signal_task(void)
331 {
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) {
340 .name = "signal",
341 .pre_select = signal_pre_select,
342 .post_select = signal_post_select,
343 .context = signal_task,
344
345 }, &sched);
346 }
347
348 static void command_pre_select(struct sched *s, void *context)
349 {
350 unsigned n;
351 struct server_command_task *sct = context;
352
353 for (n = 0; n < sct->num_listen_fds; n++)
354 para_fd_set(sct->listen_fds[n], &s->rfds, &s->max_fileno);
355 }
356
357 static int command_task_accept(unsigned listen_idx, fd_set *rfds,
358 struct server_command_task *sct)
359 {
360 int new_fd, ret, i;
361 char *peer_name;
362 pid_t child_pid;
363 uint32_t *chunk_table;
364
365 ret = para_accept(sct->listen_fds[listen_idx], rfds, NULL, 0, &new_fd);
366 if (ret <= 0)
367 goto out;
368 mmd->num_connects++;
369 mmd->active_connections++;
370 /*
371 * The chunk table is a pointer located in the mmd struct that points
372 * to dynamically allocated memory, i.e. it must be freed by the parent
373 * and the child. However, as the mmd struct is in a shared memory
374 * area, there's no guarantee that after the fork this pointer is still
375 * valid in child context. As it is not used in the child anyway, we
376 * save it to a local variable before the fork and free the memory via
377 * that copy in the child directly after the fork.
378 */
379 chunk_table = mmd->afd.afhi.chunk_table;
380 child_pid = fork();
381 if (child_pid < 0) {
382 ret = -ERRNO_TO_PARA_ERROR(errno);
383 goto out;
384 }
385 if (child_pid) {
386 /* avoid problems with non-fork-safe PRNGs */
387 unsigned char buf[16];
388 get_random_bytes_or_die(buf, sizeof(buf));
389 close(new_fd);
390 /* parent keeps accepting connections */
391 return 0;
392 }
393 peer_name = remote_name(new_fd);
394 PARA_INFO_LOG("accepted connection from %s\n", peer_name);
395 /* mmd might already have changed at this point */
396 free(chunk_table);
397 alarm(ALARM_TIMEOUT);
398 close_listed_fds();
399 signal_shutdown(signal_task);
400 /*
401 * put info on who we are serving into argv[0] to make
402 * client ip visible in top/ps
403 */
404 for (i = sct->argc - 1; i >= 0; i--)
405 memset(sct->argv[i], 0, strlen(sct->argv[i]));
406 i = sct->argc - 1 - lls_num_inputs(cmdline_lpr);
407 sprintf(sct->argv[i], "para_server (serving %s)", peer_name);
408 handle_connect(new_fd);
409 /* never reached*/
410 out:
411 if (ret < 0)
412 PARA_CRIT_LOG("%s\n", para_strerror(-ret));
413 return 0;
414 }
415
416 static int command_post_select(struct sched *s, void *context)
417 {
418 struct server_command_task *sct = context;
419 unsigned n;
420 int ret;
421
422 for (n = 0; n < sct->num_listen_fds; n++) {
423 ret = command_task_accept(n, &s->rfds, sct);
424 if (ret < 0) {
425 free(sct->listen_fds);
426 return ret;
427 }
428 }
429 return 0;
430 }
431
432 static void init_server_command_task(int argc, char **argv)
433 {
434 int ret;
435 static struct server_command_task server_command_task_struct,
436 *sct = &server_command_task_struct;
437 unsigned n;
438 uint32_t port = OPT_UINT32_VAL(PORT);
439
440
441 PARA_NOTICE_LOG("initializing tcp command socket\n");
442 sct->argc = argc;
443 sct->argv = argv;
444 if (!OPT_GIVEN(LISTEN_ADDRESS)) {
445 sct->num_listen_fds = 1;
446 sct->listen_fds = para_malloc(sizeof(int));
447 ret = para_listen_simple(IPPROTO_TCP, port);
448 if (ret < 0)
449 goto err;
450 sct->listen_fds[0] = ret;
451 } else {
452 sct->num_listen_fds = OPT_GIVEN(LISTEN_ADDRESS);
453 sct->listen_fds = para_malloc(sct->num_listen_fds * sizeof(int));
454 for (n = 0; n < OPT_GIVEN(LISTEN_ADDRESS); n++) {
455 const char *arg;
456 arg = lls_string_val(n, OPT_RESULT(LISTEN_ADDRESS));
457 ret = para_listen(IPPROTO_TCP, arg, port);
458 if (ret < 0)
459 goto err;
460 sct->listen_fds[n] = ret;
461 }
462 }
463 for (n = 0; n < sct->num_listen_fds; n++) {
464 ret = mark_fd_nonblocking(sct->listen_fds[n]);
465 if (ret < 0)
466 goto err;
467 /* child doesn't need the listener */
468 add_close_on_fork_list(sct->listen_fds[n]);
469 }
470
471 sct->task = task_register(&(struct task_info) {
472 .name = "server command",
473 .pre_select = command_pre_select,
474 .post_select = command_post_select,
475 .context = sct,
476 }, &sched);
477 return;
478 err:
479 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
480 exit(EXIT_FAILURE);
481 }
482
483 static int init_afs(int argc, char **argv)
484 {
485 int ret, afs_server_socket[2];
486 char c;
487
488 ret = socketpair(PF_UNIX, SOCK_STREAM, 0, afs_server_socket);
489 if (ret < 0)
490 exit(EXIT_FAILURE);
491 get_random_bytes_or_die((unsigned char *)&afs_socket_cookie,
492 sizeof(afs_socket_cookie));
493 afs_pid = fork();
494 if (afs_pid < 0)
495 exit(EXIT_FAILURE);
496 if (afs_pid == 0) { /* child (afs) */
497 int i;
498
499 afs_pid = getpid();
500 for (i = argc - 1; i >= 0; i--)
501 memset(argv[i], 0, strlen(argv[i]));
502 i = argc - lls_num_inputs(cmdline_lpr) - 1;
503 sprintf(argv[i], "para_server (afs)");
504 close(afs_server_socket[0]);
505 afs_init(afs_server_socket[1]);
506 }
507 close(afs_server_socket[1]);
508 if (read(afs_server_socket[0], &c, 1) <= 0) {
509 PARA_EMERG_LOG("early afs exit\n");
510 exit(EXIT_FAILURE);
511 }
512 ret = mark_fd_nonblocking(afs_server_socket[0]);
513 if (ret < 0)
514 exit(EXIT_FAILURE);
515 add_close_on_fork_list(afs_server_socket[0]);
516 PARA_INFO_LOG("afs_socket: %d, afs_socket_cookie: %u\n",
517 afs_server_socket[0], (unsigned) afs_socket_cookie);
518 return afs_server_socket[0];
519 }
520
521 static void handle_help_flags(void)
522 {
523 char *help;
524 bool d = OPT_GIVEN(DETAILED_HELP);
525
526 if (d)
527 help = lls_long_help(CMD_PTR);
528 else if (OPT_GIVEN(HELP))
529 help = lls_short_help(CMD_PTR);
530 else
531 return;
532 printf("%s\n", help);
533 free(help);
534 exit(EXIT_SUCCESS);
535 }
536
537 static void server_init(int argc, char **argv)
538 {
539 int ret, afs_socket, daemon_pipe = -1;
540 char *errctx;
541
542 valid_fd_012();
543 /* parse command line options */
544 ret = lls(lls_parse(argc, argv, CMD_PTR, &cmdline_lpr, &errctx));
545 if (ret < 0)
546 goto fail;
547 server_lpr = cmdline_lpr;
548 daemon_set_loglevel(ENUM_STRING_VAL(LOGLEVEL));
549 daemon_drop_privileges_or_die(OPT_STRING_VAL(USER),
550 OPT_STRING_VAL(GROUP));
551 version_handle_flag("server", OPT_GIVEN(VERSION));
552 handle_help_flags();
553 parse_config_or_die(false);
554 /* become daemon */
555 if (OPT_GIVEN(DAEMON))
556 daemon_pipe = daemonize(true /* parent waits for SIGTERM */);
557 init_random_seed_or_die();
558 daemon_log_welcome("server");
559 init_ipc_or_die(); /* init mmd struct and mmd->lock */
560 daemon_set_start_time();
561 PARA_NOTICE_LOG("initializing audio format handlers\n");
562 afh_init();
563
564 /*
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.
569 *
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.
574 */
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);
579 init_signal_task();
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(argc, argv);
584 if (daemon_pipe >= 0) {
585 if (write(daemon_pipe, "\0", 1) < 0) {
586 PARA_EMERG_LOG("daemon_pipe: %s", strerror(errno));
587 exit(EXIT_FAILURE);
588 }
589 close(daemon_pipe);
590 }
591 PARA_NOTICE_LOG("server init complete\n");
592 return;
593 fail:
594 assert(ret < 0);
595 if (errctx)
596 PARA_ERROR_LOG("%s\n", errctx);
597 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
598 exit(EXIT_FAILURE);
599 }
600
601 static void status_refresh(void)
602 {
603 static int prev_uptime = -1, prev_events = -1;
604 int uptime = daemon_get_uptime(now);
605
606 if (prev_events != mmd->events)
607 goto out;
608 if (mmd->new_vss_status_flags != mmd->vss_status_flags)
609 goto out_inc_events;
610 if (uptime / 60 != prev_uptime / 60)
611 goto out_inc_events;
612 return;
613 out_inc_events:
614 mmd->events++;
615 out:
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);
620 killpg(0, SIGUSR1);
621 }
622
623 static int server_select(int max_fileno, fd_set *readfds, fd_set *writefds,
624 struct timeval *timeout_tv)
625 {
626 int ret;
627
628 status_refresh();
629 mutex_unlock(mmd_mutex);
630 ret = para_select(max_fileno + 1, readfds, writefds, timeout_tv);
631 mutex_lock(mmd_mutex);
632 return ret;
633 }
634
635 /**
636 * The main function of para_server.
637 *
638 * \param argc Usual argument count.
639 * \param argv Usual argument vector.
640 *
641 * \return EXIT_SUCCESS or EXIT_FAILURE.
642 */
643 int main(int argc, char *argv[])
644 {
645 int ret;
646
647 sched.default_timeout.tv_sec = 1;
648 sched.select_function = server_select;
649
650 server_init(argc, argv);
651 mutex_lock(mmd_mutex);
652 ret = schedule(&sched);
653 sched_shutdown(&sched);
654 lls_free_parse_result(server_lpr, CMD_PTR);
655 if (server_lpr != cmdline_lpr)
656 lls_free_parse_result(cmdline_lpr, CMD_PTR);
657 if (ret < 0)
658 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
659 exit(ret < 0? EXIT_FAILURE : EXIT_SUCCESS);
660 }