4f1d5708f76e997ff8fc5ee477dd97d65a6b3785
[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 "server.h"
49 #include "list.h"
50 #include "send.h"
51 #include "sched.h"
52 #include "vss.h"
53 #include "config.h"
54 #include "close_on_fork.h"
55 #include "net.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 /** TCP port on which para_server listens for connections. */
112 int listen_fd;
113 /* File descriptor for the accepted socket. */
114 int child_fd;
115 /** Copied from para_server's main function. */
116 int argc;
117 /** Argument vector passed to para_server's main function. */
118 char **argv;
119 /** The command task structure for scheduling. */
120 struct task *task;
121 };
122
123 /**
124 * Return the list of tasks for the server process.
125 *
126 * This is called from \a com_tasks(). The helper is necessary since command
127 * handlers can not access the scheduler structure directly.
128 *
129 * \return A dynamically allocated string that must be freed by the caller.
130 */
131 char *server_get_tasks(void)
132 {
133 return get_task_list(&sched);
134 }
135
136 /*
137 * setup shared memory area and get mutex for locking
138 */
139 static void init_ipc_or_die(void)
140 {
141 void *shm;
142 int shmid, ret = shm_new(sizeof(struct misc_meta_data));
143
144 if (ret < 0)
145 goto err_out;
146 shmid = ret;
147 ret = shm_attach(shmid, ATTACH_RW, &shm);
148 shm_destroy(shmid);
149 if (ret < 0)
150 goto err_out;
151 mmd = shm;
152
153 ret = mutex_new();
154 if (ret < 0)
155 goto err_out;
156 mmd_mutex = ret;
157
158 mmd->num_played = 0;
159 mmd->num_commands = 0;
160 mmd->events = 0;
161 mmd->num_connects = 0;
162 mmd->active_connections = 0;
163 mmd->vss_status_flags = VSS_NEXT;
164 mmd->new_vss_status_flags = VSS_NEXT;
165 return;
166 err_out:
167 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
168 exit(EXIT_FAILURE);
169 }
170
171 /**
172 * (Re-)read the server configuration files.
173 *
174 * \param reload Whether config file overrides command line.
175 *
176 * This function also re-opens the logfile and the user list. On SIGHUP it is
177 * called from both server and afs context.
178 */
179 void parse_config_or_die(bool reload)
180 {
181 int ret;
182 char *cf = NULL, *errctx = NULL, *user_list_file = NULL;
183 void *map;
184 size_t sz;
185 int cf_argc;
186 char **cf_argv;
187 struct lls_parse_result *cf_lpr, *merged_lpr;
188 char *home = para_homedir();
189
190 if (OPT_GIVEN(CONFIG_FILE))
191 cf = para_strdup(OPT_STRING_VAL(CONFIG_FILE));
192 else
193 cf = make_message("%s/.paraslash/server.conf", home);
194 if (!mmd || getpid() != afs_pid) {
195 if (OPT_GIVEN(USER_LIST))
196 user_list_file = para_strdup(OPT_STRING_VAL(USER_LIST));
197 else
198 user_list_file = make_message("%s/.paraslash/server.users", home);
199 }
200 free(home);
201 ret = mmap_full_file(cf, O_RDONLY, &map, &sz, NULL);
202 if (ret < 0) {
203 if (ret != -E_EMPTY && ret != -ERRNO_TO_PARA_ERROR(ENOENT))
204 goto free_cf;
205 if (ret == -ERRNO_TO_PARA_ERROR(ENOENT) && OPT_GIVEN(CONFIG_FILE))
206 goto free_cf;
207 server_lpr = cmdline_lpr;
208 goto success;
209 }
210 ret = lls(lls_convert_config(map, sz, NULL, &cf_argv, &errctx));
211 para_munmap(map, sz);
212 if (ret < 0)
213 goto free_cf;
214 cf_argc = ret;
215 ret = lls(lls_parse(cf_argc, cf_argv, CMD_PTR, &cf_lpr, &errctx));
216 lls_free_argv(cf_argv);
217 if (ret < 0)
218 goto free_cf;
219 if (reload) /* config file overrides command line */
220 ret = lls(lls_merge(cf_lpr, cmdline_lpr, CMD_PTR, &merged_lpr,
221 &errctx));
222 else /* command line options override config file options */
223 ret = lls(lls_merge(cmdline_lpr, cf_lpr, CMD_PTR, &merged_lpr,
224 &errctx));
225 lls_free_parse_result(cf_lpr, CMD_PTR);
226 if (ret < 0)
227 goto free_cf;
228 if (server_lpr != cmdline_lpr)
229 lls_free_parse_result(server_lpr, CMD_PTR);
230 server_lpr = merged_lpr;
231 success:
232 daemon_set_loglevel(ENUM_STRING_VAL(LOGLEVEL));
233 if (OPT_GIVEN(LOGFILE)) {
234 daemon_set_logfile(OPT_STRING_VAL(LOGFILE));
235 daemon_open_log_or_die();
236 }
237 if (daemon_init_colors_or_die(OPT_UINT32_VAL(COLOR), COLOR_AUTO,
238 COLOR_NO, OPT_GIVEN(LOGFILE))) {
239 int i;
240 for (i = 0; i < OPT_GIVEN(LOG_COLOR); i++)
241 daemon_set_log_color_or_die(lls_string_val(i,
242 OPT_RESULT(LOG_COLOR)));
243 }
244 daemon_set_flag(DF_LOG_PID);
245 daemon_set_flag(DF_LOG_LL);
246 daemon_set_flag(DF_LOG_TIME);
247 if (OPT_GIVEN(LOG_TIMING))
248 daemon_set_flag(DF_LOG_TIMING);
249 daemon_set_priority(OPT_UINT32_VAL(PRIORITY));
250 if (user_list_file)
251 init_user_list(user_list_file);
252 ret = 1;
253 free_cf:
254 free(cf);
255 free(user_list_file);
256 if (ret < 0) {
257 if (errctx)
258 PARA_ERROR_LOG("%s\n", errctx);
259 free(errctx);
260 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
261 exit(EXIT_FAILURE);
262 }
263 }
264
265 /*
266 * called when server gets SIGHUP or when client invokes hup command.
267 */
268 static void handle_sighup(void)
269 {
270
271 PARA_NOTICE_LOG("SIGHUP\n");
272 parse_config_or_die(true);
273 if (afs_pid != 0)
274 kill(afs_pid, SIGHUP);
275 }
276
277 static int signal_post_select(struct sched *s, __a_unused void *context)
278 {
279 int ret, signum;
280
281 ret = task_get_notification(signal_task->task);
282 if (ret < 0)
283 return ret;
284 signum = para_next_signal(&s->rfds);
285 switch (signum) {
286 case 0:
287 return 0;
288 case SIGHUP:
289 handle_sighup();
290 break;
291 case SIGCHLD:
292 for (;;) {
293 pid_t pid;
294 ret = para_reap_child(&pid);
295 if (ret <= 0)
296 break;
297 if (pid != afs_pid)
298 continue;
299 PARA_EMERG_LOG("fatal: afs died\n");
300 kill(0, SIGTERM);
301 goto cleanup;
302 }
303 break;
304 /* die on sigint/sigterm. Kill all children too. */
305 case SIGINT:
306 case SIGTERM:
307 PARA_EMERG_LOG("terminating on signal %d\n", signum);
308 kill(0, SIGTERM);
309 /*
310 * We must wait for afs because afs catches SIGINT/SIGTERM.
311 * Before reacting to the signal, afs might want to use the
312 * shared memory area and the mmd mutex. If we destroy this
313 * mutex too early and afs tries to lock the shared memory
314 * area, the call to mutex_lock() will fail and terminate the
315 * afs process. This leads to dirty osl tables.
316 *
317 * There's no such problem with the other children of the
318 * server process (the command handlers) as these reset their
319 * SIGINT/SIGTERM handlers to the default action, i.e. these
320 * processes get killed immediately by the above kill().
321 */
322 PARA_INFO_LOG("waiting for afs (pid %d) to die\n",
323 (int)afs_pid);
324 waitpid(afs_pid, NULL, 0);
325 cleanup:
326 free(mmd->afd.afhi.chunk_table);
327 close_listed_fds();
328 mutex_destroy(mmd_mutex);
329 shm_detach(mmd);
330 exit(EXIT_FAILURE);
331 }
332 return 0;
333 }
334
335 static void init_signal_task(void)
336 {
337 signal_task = signal_init_or_die();
338 para_install_sighandler(SIGINT);
339 para_install_sighandler(SIGTERM);
340 para_install_sighandler(SIGHUP);
341 para_install_sighandler(SIGCHLD);
342 para_sigaction(SIGPIPE, SIG_IGN);
343 add_close_on_fork_list(signal_task->fd);
344 signal_task->task = task_register(&(struct task_info) {
345 .name = "signal",
346 .pre_select = signal_pre_select,
347 .post_select = signal_post_select,
348 .context = signal_task,
349
350 }, &sched);
351 }
352
353 static void command_pre_select(struct sched *s, void *context)
354 {
355 struct server_command_task *sct = context;
356 para_fd_set(sct->listen_fd, &s->rfds, &s->max_fileno);
357 }
358
359 static int command_post_select(struct sched *s, void *context)
360 {
361 struct server_command_task *sct = context;
362 int new_fd, ret, i;
363 char *peer_name;
364 pid_t child_pid;
365 uint32_t *chunk_table;
366
367 ret = task_get_notification(sct->task);
368 if (ret < 0)
369 return ret;
370 ret = para_accept(sct->listen_fd, &s->rfds, NULL, 0, &new_fd);
371 if (ret <= 0)
372 goto out;
373 mmd->num_connects++;
374 mmd->active_connections++;
375 /*
376 * The chunk table is a pointer located in the mmd struct that points
377 * to dynamically allocated memory, i.e. it must be freed by the parent
378 * and the child. However, as the mmd struct is in a shared memory
379 * area, there's no guarantee that after the fork this pointer is still
380 * valid in child context. As it is not used in the child anyway, we
381 * save it to a local variable before the fork and free the memory via
382 * that copy in the child directly after the fork.
383 */
384 chunk_table = mmd->afd.afhi.chunk_table;
385 child_pid = fork();
386 if (child_pid < 0) {
387 ret = -ERRNO_TO_PARA_ERROR(errno);
388 goto out;
389 }
390 if (child_pid) {
391 /* avoid problems with non-fork-safe PRNGs */
392 unsigned char buf[16];
393 get_random_bytes_or_die(buf, sizeof(buf));
394 close(new_fd);
395 /* parent keeps accepting connections */
396 return 0;
397 }
398 peer_name = remote_name(new_fd);
399 PARA_INFO_LOG("accepted connection from %s\n", peer_name);
400 /* mmd might already have changed at this point */
401 free(chunk_table);
402 sct->child_fd = new_fd;
403 /*
404 * put info on who we are serving into argv[0] to make
405 * client ip visible in top/ps
406 */
407 for (i = sct->argc - 1; i >= 0; i--)
408 memset(sct->argv[i], 0, strlen(sct->argv[i]));
409 i = sct->argc - 1 - lls_num_inputs(cmdline_lpr);
410 sprintf(sct->argv[i], "para_server (serving %s)", peer_name);
411 /* ask other tasks to terminate */
412 task_notify_all(s, E_CHILD_CONTEXT);
413 /*
414 * After we return, the scheduler calls server_select() with a minimal
415 * timeout value, because the remaining tasks have a notification
416 * pending. Next it calls the ->post_select method of these tasks,
417 * which will return negative in view of the notification. This causes
418 * schedule() to return as there are no more runnable tasks.
419 *
420 * Note that semaphores are not inherited across a fork(), so we don't
421 * hold the lock at this point. Since server_select() drops the lock
422 * prior to calling para_select(), we need to acquire it here.
423 */
424 mutex_lock(mmd_mutex);
425 return -E_CHILD_CONTEXT;
426 out:
427 if (ret < 0)
428 PARA_CRIT_LOG("%s\n", para_strerror(-ret));
429 return 0;
430 }
431
432 static void init_server_command_task(struct server_command_task *sct,
433 int argc, char **argv)
434 {
435 int ret;
436
437 PARA_NOTICE_LOG("initializing tcp command socket\n");
438 sct->child_fd = -1;
439 sct->argc = argc;
440 sct->argv = argv;
441 ret = para_listen_simple(IPPROTO_TCP, OPT_UINT32_VAL(PORT));
442 if (ret < 0)
443 goto err;
444 sct->listen_fd = ret;
445 ret = mark_fd_nonblocking(sct->listen_fd);
446 if (ret < 0)
447 goto err;
448 add_close_on_fork_list(sct->listen_fd); /* child doesn't need the listener */
449 sct->task = task_register(&(struct task_info) {
450 .name = "server command",
451 .pre_select = command_pre_select,
452 .post_select = command_post_select,
453 .context = sct,
454 }, &sched);
455 return;
456 err:
457 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
458 exit(EXIT_FAILURE);
459 }
460
461 static int init_afs(int argc, char **argv)
462 {
463 int ret, afs_server_socket[2];
464 char c;
465
466 ret = socketpair(PF_UNIX, SOCK_STREAM, 0, afs_server_socket);
467 if (ret < 0)
468 exit(EXIT_FAILURE);
469 get_random_bytes_or_die((unsigned char *)&afs_socket_cookie,
470 sizeof(afs_socket_cookie));
471 afs_pid = fork();
472 if (afs_pid < 0)
473 exit(EXIT_FAILURE);
474 if (afs_pid == 0) { /* child (afs) */
475 int i;
476
477 afs_pid = getpid();
478 for (i = argc - 1; i >= 0; i--)
479 memset(argv[i], 0, strlen(argv[i]));
480 i = argc - lls_num_inputs(cmdline_lpr) - 1;
481 sprintf(argv[i], "para_server (afs)");
482 close(afs_server_socket[0]);
483 afs_init(afs_server_socket[1]);
484 }
485 close(afs_server_socket[1]);
486 if (read(afs_server_socket[0], &c, 1) <= 0) {
487 PARA_EMERG_LOG("early afs exit\n");
488 exit(EXIT_FAILURE);
489 }
490 ret = mark_fd_nonblocking(afs_server_socket[0]);
491 if (ret < 0)
492 exit(EXIT_FAILURE);
493 add_close_on_fork_list(afs_server_socket[0]);
494 PARA_INFO_LOG("afs_socket: %d, afs_socket_cookie: %u\n",
495 afs_server_socket[0], (unsigned) afs_socket_cookie);
496 return afs_server_socket[0];
497 }
498
499 static void handle_help_flags(void)
500 {
501 char *help;
502 bool d = OPT_GIVEN(DETAILED_HELP);
503
504 if (d)
505 help = lls_long_help(CMD_PTR);
506 else if (OPT_GIVEN(HELP))
507 help = lls_short_help(CMD_PTR);
508 else
509 return;
510 printf("%s\n", help);
511 free(help);
512 exit(EXIT_SUCCESS);
513 }
514
515 static void server_init(int argc, char **argv, struct server_command_task *sct)
516 {
517 int ret, afs_socket, daemon_pipe = -1;
518 char *errctx;
519
520 valid_fd_012();
521 /* parse command line options */
522 ret = lls(lls_parse(argc, argv, CMD_PTR, &cmdline_lpr, &errctx));
523 if (ret < 0)
524 goto fail;
525 server_lpr = cmdline_lpr;
526 daemon_set_loglevel(ENUM_STRING_VAL(LOGLEVEL));
527 daemon_drop_privileges_or_die(OPT_STRING_VAL(USER),
528 OPT_STRING_VAL(GROUP));
529 version_handle_flag("server", OPT_GIVEN(VERSION));
530 handle_help_flags();
531 parse_config_or_die(false);
532 /* become daemon */
533 if (OPT_GIVEN(DAEMON))
534 daemon_pipe = daemonize(true /* parent waits for SIGTERM */);
535 init_random_seed_or_die();
536 daemon_log_welcome("server");
537 init_ipc_or_die(); /* init mmd struct and mmd->lock */
538 daemon_set_start_time();
539 PARA_NOTICE_LOG("initializing audio format handlers\n");
540 afh_init();
541
542 /*
543 * Although afs uses its own signal handling we must ignore SIGUSR1
544 * _before_ the afs child process gets born by init_afs() below. It's
545 * racy to do this in the child because the parent might send SIGUSR1
546 * before the child gets a chance to ignore this signal.
547 *
548 * We also have to block SIGCHLD before the afs process is created
549 * because otherwise para_server does not notice if afs dies before the
550 * SIGCHLD handler has been installed for the parent process by
551 * init_signal_task() below.
552 */
553 para_sigaction(SIGUSR1, SIG_IGN);
554 para_block_signal(SIGCHLD);
555 PARA_NOTICE_LOG("initializing the audio file selector\n");
556 afs_socket = init_afs(argc, argv);
557 init_signal_task();
558 para_unblock_signal(SIGCHLD);
559 PARA_NOTICE_LOG("initializing virtual streaming system\n");
560 vss_init(afs_socket, &sched);
561 init_server_command_task(sct, argc, argv);
562 if (daemon_pipe >= 0) {
563 if (write(daemon_pipe, "\0", 1) < 0) {
564 PARA_EMERG_LOG("daemon_pipe: %s", strerror(errno));
565 exit(EXIT_FAILURE);
566 }
567 close(daemon_pipe);
568 }
569 PARA_NOTICE_LOG("server init complete\n");
570 return;
571 fail:
572 assert(ret < 0);
573 if (errctx)
574 PARA_ERROR_LOG("%s\n", errctx);
575 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
576 exit(EXIT_FAILURE);
577 }
578
579 static void status_refresh(void)
580 {
581 static int prev_uptime = -1, prev_events = -1;
582 int uptime = daemon_get_uptime(now);
583
584 if (prev_events != mmd->events)
585 goto out;
586 if (mmd->new_vss_status_flags != mmd->vss_status_flags)
587 goto out_inc_events;
588 if (uptime / 60 != prev_uptime / 60)
589 goto out_inc_events;
590 return;
591 out_inc_events:
592 mmd->events++;
593 out:
594 prev_uptime = uptime;
595 prev_events = mmd->events;
596 mmd->vss_status_flags = mmd->new_vss_status_flags;
597 PARA_DEBUG_LOG("%u events, forcing status update\n", mmd->events);
598 killpg(0, SIGUSR1);
599 }
600
601 static int server_select(int max_fileno, fd_set *readfds, fd_set *writefds,
602 struct timeval *timeout_tv)
603 {
604 int ret;
605
606 status_refresh();
607 mutex_unlock(mmd_mutex);
608 ret = para_select(max_fileno + 1, readfds, writefds, timeout_tv);
609 mutex_lock(mmd_mutex);
610 return ret;
611 }
612
613 /**
614 * The main function of para_server.
615 *
616 * \param argc Usual argument count.
617 * \param argv Usual argument vector.
618 *
619 * \return EXIT_SUCCESS or EXIT_FAILURE.
620 */
621 int main(int argc, char *argv[])
622 {
623 int ret;
624 struct server_command_task server_command_task_struct,
625 *sct = &server_command_task_struct;
626
627 sched.default_timeout.tv_sec = 1;
628 sched.select_function = server_select;
629
630 server_init(argc, argv, sct);
631 mutex_lock(mmd_mutex);
632 ret = schedule(&sched);
633 sched_shutdown(&sched);
634 signal_shutdown(signal_task);
635 if (sct->child_fd < 0) { /* parent (server) */
636 if (ret < 0)
637 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
638 } else { /* child (command handler) */
639 /*
640 * We hold the lock: it was re-acquired in server_select()
641 * after the select call.
642 */
643 mutex_unlock(mmd_mutex);
644 alarm(ALARM_TIMEOUT);
645 close_listed_fds();
646 ret = handle_connect(sct->child_fd);
647 }
648 lls_free_parse_result(server_lpr, CMD_PTR);
649 if (server_lpr != cmdline_lpr)
650 lls_free_parse_result(cmdline_lpr, CMD_PTR);
651 exit(ret < 0? EXIT_FAILURE : EXIT_SUCCESS);
652 }