signal: Provide generic signal_pre_select().
[paraslash.git] / server.c
1 /*
2 * Copyright (C) 1997 Andre Noll <maan@tuebingen.mpg.de>
3 *
4 * Licensed under the GPL v2. For licencing details see COPYING.
5 */
6
7 /** \file server.c Paraslash's main server. */
8
9 /**
10 * \mainpage Main data structures:
11 *
12 * - Server: \ref server_command, \ref sender,
13 * - Audio file selector: \ref afs_info, \ref afs_table,
14 * - Audio format handler: \ref audio_format_handler, \ref afh_info
15 * - Receivers/filters/writers: \ref receiver, \ref receiver_node,
16 * \ref filter, \ref filter_node, \ref writer_node, \ref writer.
17 *
18 * Selected APIs:
19 *
20 * - Scheduling: \ref sched.h,
21 * - Buffer trees: \ref buffer_tree.h,
22 * - Sideband API: \ref sideband.h,
23 * - Crypto: \ref crypt.h, \ref crypt_backend.h,
24 * - Error subsystem: \ref error.h, \ref error2.c,
25 * - Inter process communication: \ref ipc.h,
26 * - Forward error correction: \ref fec.h,
27 * - Daemons: \ref daemon.h,
28 * - Mixer API: \ref mix.h,
29 * - Interactive sessions: \ref interactive.h,
30 * - File descriptors: \ref fd.h,
31 * - Signals: \ref signal.h,
32 * - Networking: \ref net.h,
33 * - Time: \ref time.c,
34 * - Doubly linked lists: \ref list.h.
35 */
36
37 #include <netinet/in.h>
38 #include <sys/socket.h>
39 #include <signal.h>
40 #include <regex.h>
41 #include <osl.h>
42 #include <sys/types.h>
43 #include <arpa/inet.h>
44 #include <sys/un.h>
45 #include <netdb.h>
46
47 #include "para.h"
48 #include "error.h"
49 #include "crypt.h"
50 #include "server.cmdline.h"
51 #include "afh.h"
52 #include "string.h"
53 #include "afs.h"
54 #include "server.h"
55 #include "list.h"
56 #include "send.h"
57 #include "sched.h"
58 #include "vss.h"
59 #include "config.h"
60 #include "close_on_fork.h"
61 #include "net.h"
62 #include "daemon.h"
63 #include "ipc.h"
64 #include "fd.h"
65 #include "signal.h"
66 #include "user_list.h"
67 #include "color.h"
68 #include "ggo.h"
69 #include "version.h"
70
71 __printf_2_3 void (*para_log)(int, const char*, ...) = daemon_log;
72
73 /** Define the array of error lists needed by para_server. */
74 INIT_SERVER_ERRLISTS;
75
76 /** Shut down non-authorized connections after that many seconds. */
77 #define ALARM_TIMEOUT 10
78
79 /**
80 * Pointer to shared memory area for communication between para_server
81 * and its children. Exported to vss.c. command.c and to afs.
82 */
83 struct misc_meta_data *mmd;
84
85 /**
86 * The configuration of para_server
87 *
88 * It also contains the options for the audio file selector, audio format
89 * handler and all supported senders.
90 */
91 struct server_args_info conf;
92
93 /** A random value used in child context for authentication. */
94 uint32_t afs_socket_cookie;
95
96 /** The mutex protecting the shared memory area containing the mmd struct. */
97 int mmd_mutex;
98
99 /** The file containing user information (public key, permissions). */
100 static char *user_list_file = NULL;
101
102 static struct sched sched;
103
104 /** The task responsible for server command handling. */
105 struct server_command_task {
106 /** TCP port on which para_server listens for connections. */
107 int listen_fd;
108 /** Copied from para_server's main function. */
109 int argc;
110 /** Argument vector passed to para_server's main function. */
111 char **argv;
112 /** The command task structure for scheduling. */
113 struct task *task;
114 };
115
116 /**
117 * Return the list of tasks for the server process.
118 *
119 * This is called from \a com_tasks(). The helper is necessary since command
120 * handlers can not access the scheduler structure directly.
121 *
122 * \return A dynamically allocated string that must be freed by the caller.
123 */
124 char *server_get_tasks(void)
125 {
126 return get_task_list(&sched);
127 }
128
129 /*
130 * setup shared memory area and get mutex for locking
131 */
132 static void init_ipc_or_die(void)
133 {
134 void *shm;
135 int shmid, ret = shm_new(sizeof(struct misc_meta_data));
136
137 if (ret < 0)
138 goto err_out;
139 shmid = ret;
140 ret = shm_attach(shmid, ATTACH_RW, &shm);
141 shm_destroy(shmid);
142 if (ret < 0)
143 goto err_out;
144 mmd = shm;
145
146 ret = mutex_new();
147 if (ret < 0)
148 goto err_out;
149 mmd_mutex = ret;
150
151 mmd->num_played = 0;
152 mmd->num_commands = 0;
153 mmd->events = 0;
154 mmd->num_connects = 0;
155 mmd->active_connections = 0;
156 mmd->vss_status_flags = VSS_NEXT;
157 mmd->new_vss_status_flags = VSS_NEXT;
158 return;
159 err_out:
160 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
161 exit(EXIT_FAILURE);
162 }
163
164 /**
165 * (Re-)read the server configuration files.
166 *
167 * \param override Passed to gengetopt to activate the override feature.
168 *
169 * This function also re-opens the logfile and sets the global \a
170 * user_list_file variable.
171 */
172 void parse_config_or_die(int override)
173 {
174 char *home = para_homedir();
175 int ret;
176 char *cf;
177
178 daemon_close_log();
179 if (conf.config_file_given)
180 cf = para_strdup(conf.config_file_arg);
181 else
182 cf = make_message("%s/.paraslash/server.conf", home);
183 free(user_list_file);
184 if (!conf.user_list_given)
185 user_list_file = make_message("%s/.paraslash/server.users", home);
186 else
187 user_list_file = para_strdup(conf.user_list_arg);
188 ret = file_exists(cf);
189 if (conf.config_file_given && !ret) {
190 ret = -1;
191 PARA_EMERG_LOG("can not read config file %s\n", cf);
192 goto out;
193 }
194 if (ret) {
195 int tmp = conf.daemon_given;
196 struct server_cmdline_parser_params params = {
197 .override = override,
198 .initialize = 0,
199 .check_required = 1,
200 .check_ambiguity = 0,
201 .print_errors = !conf.daemon_given
202 };
203 server_cmdline_parser_config_file(cf, &conf, &params);
204 daemon_set_loglevel(conf.loglevel_arg);
205 conf.daemon_given = tmp;
206 }
207 if (conf.logfile_given) {
208 daemon_set_logfile(conf.logfile_arg);
209 daemon_open_log_or_die();
210 }
211
212 daemon_init_colors_or_die(conf.color_arg, color_arg_auto, color_arg_no,
213 conf.logfile_given, conf.log_color_arg, conf.log_color_given);
214 daemon_set_flag(DF_LOG_PID);
215 daemon_set_flag(DF_LOG_LL);
216 daemon_set_flag(DF_LOG_TIME);
217 if (conf.log_timing_given)
218 daemon_set_flag(DF_LOG_TIMING);
219 ret = 1;
220 out:
221 free(cf);
222 free(home);
223 if (ret > 0)
224 return;
225 free(user_list_file);
226 user_list_file = NULL;
227 exit(EXIT_FAILURE);
228 }
229
230 /*
231 * called when server gets SIGHUP or when client invokes hup command.
232 */
233 static void handle_sighup(void)
234 {
235 PARA_NOTICE_LOG("SIGHUP\n");
236 parse_config_or_die(1); /* reopens log */
237 init_user_list(user_list_file); /* reload user list */
238 if (mmd->afs_pid)
239 kill(mmd->afs_pid, SIGHUP);
240 }
241
242 static int signal_post_select(struct sched *s, __a_unused void *context)
243 {
244 int signum = para_next_signal(&s->rfds);
245
246 switch (signum) {
247 case 0:
248 return 0;
249 case SIGHUP:
250 handle_sighup();
251 break;
252 case SIGCHLD:
253 for (;;) {
254 pid_t pid;
255 int ret = para_reap_child(&pid);
256 if (ret <= 0)
257 break;
258 if (pid != mmd->afs_pid)
259 continue;
260 PARA_EMERG_LOG("fatal: afs died\n");
261 kill(0, SIGTERM);
262 goto cleanup;
263 }
264 break;
265 /* die on sigint/sigterm. Kill all children too. */
266 case SIGINT:
267 case SIGTERM:
268 PARA_EMERG_LOG("terminating on signal %d\n", signum);
269 kill(0, SIGTERM);
270 /*
271 * We must wait for afs because afs catches SIGINT/SIGTERM.
272 * Before reacting to the signal, afs might want to use the
273 * shared memory area and the mmd mutex. If we destroy this
274 * mutex too early and afs tries to lock the shared memory
275 * area, the call to mutex_lock() will fail and terminate the
276 * afs process. This leads to dirty osl tables.
277 *
278 * There's no such problem with the other children of the
279 * server process (the command handlers) as these reset their
280 * SIGINT/SIGTERM handlers to the default action, i.e. these
281 * processes get killed immediately by the above kill().
282 */
283 PARA_INFO_LOG("waiting for afs (pid %d) to die\n",
284 (int)mmd->afs_pid);
285 waitpid(mmd->afs_pid, NULL, 0);
286 cleanup:
287 free(mmd->afd.afhi.chunk_table);
288 close_listed_fds();
289 mutex_destroy(mmd_mutex);
290 shm_detach(mmd);
291 exit(EXIT_FAILURE);
292 }
293 return 0;
294 }
295
296 static void init_signal_task(void)
297 {
298 static struct signal_task signal_task_struct,
299 *st = &signal_task_struct;
300
301 PARA_NOTICE_LOG("setting up signal handling\n");
302 st->fd = para_signal_init(); /* always successful */
303 para_install_sighandler(SIGINT);
304 para_install_sighandler(SIGTERM);
305 para_install_sighandler(SIGHUP);
306 para_install_sighandler(SIGCHLD);
307 para_sigaction(SIGPIPE, SIG_IGN);
308 add_close_on_fork_list(st->fd);
309 st->task = task_register(&(struct task_info) {
310 .name = "signal",
311 .pre_select = signal_pre_select,
312 .post_select = signal_post_select,
313 .context = st,
314
315 }, &sched);
316 }
317
318 static void command_pre_select(struct sched *s, void *context)
319 {
320 struct server_command_task *sct = context;
321 para_fd_set(sct->listen_fd, &s->rfds, &s->max_fileno);
322 }
323
324 static int command_post_select(struct sched *s, void *context)
325 {
326 struct server_command_task *sct = context;
327
328 int new_fd, ret, i;
329 char *peer_name;
330 pid_t child_pid;
331 uint32_t *chunk_table;
332
333 ret = para_accept(sct->listen_fd, &s->rfds, NULL, 0, &new_fd);
334 if (ret <= 0)
335 goto out;
336 peer_name = remote_name(new_fd);
337 PARA_INFO_LOG("got connection from %s, forking\n", peer_name);
338 mmd->num_connects++;
339 mmd->active_connections++;
340 /*
341 * The chunk table is a pointer located in the mmd struct that points
342 * to dynamically allocated memory, i.e. it must be freed by the parent
343 * and the child. However, as the mmd struct is in a shared memory
344 * area, there's no guarantee that after the fork this pointer is still
345 * valid in child context. As it is not used in the child anyway, we
346 * save it to a local variable before the fork and free the memory via
347 * that copy in the child directly after the fork.
348 */
349 chunk_table = mmd->afd.afhi.chunk_table;
350 child_pid = fork();
351 if (child_pid < 0) {
352 ret = -ERRNO_TO_PARA_ERROR(errno);
353 goto out;
354 }
355 if (child_pid) {
356 /* avoid problems with non-fork-safe PRNGs */
357 unsigned char buf[16];
358 get_random_bytes_or_die(buf, sizeof(buf));
359 close(new_fd);
360 /* parent keeps accepting connections */
361 return 0;
362 }
363 /* mmd might already have changed at this point */
364 free(chunk_table);
365 alarm(ALARM_TIMEOUT);
366 close_listed_fds();
367 para_signal_shutdown();
368 /*
369 * put info on who we are serving into argv[0] to make
370 * client ip visible in top/ps
371 */
372 for (i = sct->argc - 1; i >= 0; i--)
373 memset(sct->argv[i], 0, strlen(sct->argv[i]));
374 sprintf(sct->argv[0], "para_server (serving %s)", peer_name);
375 handle_connect(new_fd, peer_name);
376 /* never reached*/
377 out:
378 if (ret < 0)
379 PARA_CRIT_LOG("%s\n", para_strerror(-ret));
380 return 0;
381 }
382
383 static void init_server_command_task(int argc, char **argv)
384 {
385 int ret;
386 static struct server_command_task server_command_task_struct,
387 *sct = &server_command_task_struct;
388
389 PARA_NOTICE_LOG("initializing tcp command socket\n");
390 sct->argc = argc;
391 sct->argv = argv;
392 ret = para_listen_simple(IPPROTO_TCP, conf.port_arg);
393 if (ret < 0)
394 goto err;
395 sct->listen_fd = ret;
396 ret = mark_fd_nonblocking(sct->listen_fd);
397 if (ret < 0)
398 goto err;
399 add_close_on_fork_list(sct->listen_fd); /* child doesn't need the listener */
400 sct->task = task_register(&(struct task_info) {
401 .name = "server command",
402 .pre_select = command_pre_select,
403 .post_select = command_post_select,
404 .context = sct,
405 }, &sched);
406 return;
407 err:
408 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
409 exit(EXIT_FAILURE);
410 }
411
412 static int init_afs(int argc, char **argv)
413 {
414 int ret, afs_server_socket[2];
415 pid_t afs_pid;
416
417 ret = socketpair(PF_UNIX, SOCK_DGRAM, 0, afs_server_socket);
418 if (ret < 0)
419 exit(EXIT_FAILURE);
420 get_random_bytes_or_die((unsigned char *)&afs_socket_cookie,
421 sizeof(afs_socket_cookie));
422 afs_pid = fork();
423 if (afs_pid < 0)
424 exit(EXIT_FAILURE);
425 if (afs_pid == 0) { /* child (afs) */
426 int i;
427 for (i = argc - 1; i >= 0; i--)
428 memset(argv[i], 0, strlen(argv[i]));
429 sprintf(argv[0], "para_server (afs)");
430 close(afs_server_socket[0]);
431 afs_init(afs_socket_cookie, afs_server_socket[1]);
432 }
433 mmd->afs_pid = afs_pid;
434 close(afs_server_socket[1]);
435 ret = mark_fd_nonblocking(afs_server_socket[0]);
436 if (ret < 0)
437 exit(EXIT_FAILURE);
438 add_close_on_fork_list(afs_server_socket[0]);
439 PARA_INFO_LOG("afs_socket: %d, afs_socket_cookie: %u\n",
440 afs_server_socket[0], (unsigned) afs_socket_cookie);
441 return afs_server_socket[0];
442 }
443
444 __noreturn static void print_help_and_die(void)
445 {
446 struct ggo_help h = DEFINE_GGO_HELP(server);
447 bool d = conf.detailed_help_given;
448
449 ggo_print_help(&h, d? GPH_STANDARD_FLAGS_DETAILED : GPH_STANDARD_FLAGS);
450 exit(0);
451 }
452
453 static void server_init(int argc, char **argv)
454 {
455 struct server_cmdline_parser_params params = {
456 .override = 0,
457 .initialize = 1,
458 .check_required = 0,
459 .check_ambiguity = 0,
460 .print_errors = 1
461 };
462 int afs_socket;
463
464 valid_fd_012();
465 init_random_seed_or_die();
466 /* parse command line options */
467 server_cmdline_parser_ext(argc, argv, &conf, &params);
468 daemon_set_loglevel(conf.loglevel_arg);
469 version_handle_flag("server", conf.version_given);
470 if (conf.help_given || conf.detailed_help_given)
471 print_help_and_die();
472 daemon_drop_privileges_or_die(conf.user_arg, conf.group_arg);
473 /* parse config file, open log and set defaults */
474 parse_config_or_die(0);
475 daemon_log_welcome("para_server");
476 init_ipc_or_die(); /* init mmd struct and mmd->lock */
477 daemon_set_start_time();
478 init_user_list(user_list_file);
479 /* become daemon */
480 if (conf.daemon_given)
481 daemonize(true /* parent waits for SIGTERM */);
482 PARA_NOTICE_LOG("initializing audio format handlers\n");
483 afh_init();
484
485 /*
486 * Although afs uses its own signal handling we must ignore SIGUSR1
487 * _before_ the afs child process gets born by init_afs() below. It's
488 * racy to do this in the child because the parent might send SIGUSR1
489 * before the child gets a chance to ignore this signal -- only the
490 * good die young.
491 */
492 para_sigaction(SIGUSR1, SIG_IGN);
493 /*
494 * We have to block SIGCHLD before the afs process is being forked off.
495 * Otherwise, para_server does not notice if afs dies before the
496 * SIGCHLD handler has been installed for the parent process by
497 * init_signal_task() below.
498 */
499 para_block_signal(SIGCHLD);
500 PARA_NOTICE_LOG("initializing the audio file selector\n");
501 afs_socket = init_afs(argc, argv);
502 init_signal_task();
503 para_unblock_signal(SIGCHLD);
504 PARA_NOTICE_LOG("initializing virtual streaming system\n");
505 init_vss_task(afs_socket, &sched);
506 init_server_command_task(argc, argv);
507 if (conf.daemon_given)
508 kill(getppid(), SIGTERM);
509 PARA_NOTICE_LOG("server init complete\n");
510 }
511
512 static void status_refresh(void)
513 {
514 static int prev_uptime = -1, prev_events = -1;
515 int uptime = daemon_get_uptime(now);
516
517 if (prev_events != mmd->events)
518 goto out;
519 if (mmd->new_vss_status_flags != mmd->vss_status_flags)
520 goto out_inc_events;
521 if (uptime / 60 != prev_uptime / 60)
522 goto out_inc_events;
523 return;
524 out_inc_events:
525 mmd->events++;
526 out:
527 prev_uptime = uptime;
528 prev_events = mmd->events;
529 mmd->vss_status_flags = mmd->new_vss_status_flags;
530 PARA_DEBUG_LOG("%d events, forcing status update\n", mmd->events);
531 killpg(0, SIGUSR1);
532 }
533
534 static int server_select(int max_fileno, fd_set *readfds, fd_set *writefds,
535 struct timeval *timeout_tv)
536 {
537 int ret;
538
539 status_refresh();
540 mutex_unlock(mmd_mutex);
541 ret = para_select(max_fileno + 1, readfds, writefds, timeout_tv);
542 mutex_lock(mmd_mutex);
543 return ret;
544 }
545
546 /**
547 * The main function of para_server.
548 *
549 * \param argc Usual argument count.
550 * \param argv Usual argument vector.
551 *
552 * \return EXIT_SUCCESS or EXIT_FAILURE.
553 */
554 int main(int argc, char *argv[])
555 {
556 int ret;
557
558 sched.default_timeout.tv_sec = 1;
559 sched.select_function = server_select;
560
561 server_init(argc, argv);
562 mutex_lock(mmd_mutex);
563 ret = schedule(&sched);
564 sched_shutdown(&sched);
565 if (ret < 0) {
566 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
567 exit(EXIT_FAILURE);
568 }
569 exit(EXIT_SUCCESS);
570 }