Improve signal init and shutdown.
[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 static struct signal_task *signal_task;
104
105 /** The task responsible for server command handling. */
106 struct server_command_task {
107 /** TCP port on which para_server listens for connections. */
108 int listen_fd;
109 /** Copied from para_server's main function. */
110 int argc;
111 /** Argument vector passed to para_server's main function. */
112 char **argv;
113 /** The command task structure for scheduling. */
114 struct task *task;
115 };
116
117 /**
118 * Return the list of tasks for the server process.
119 *
120 * This is called from \a com_tasks(). The helper is necessary since command
121 * handlers can not access the scheduler structure directly.
122 *
123 * \return A dynamically allocated string that must be freed by the caller.
124 */
125 char *server_get_tasks(void)
126 {
127 return get_task_list(&sched);
128 }
129
130 /*
131 * setup shared memory area and get mutex for locking
132 */
133 static void init_ipc_or_die(void)
134 {
135 void *shm;
136 int shmid, ret = shm_new(sizeof(struct misc_meta_data));
137
138 if (ret < 0)
139 goto err_out;
140 shmid = ret;
141 ret = shm_attach(shmid, ATTACH_RW, &shm);
142 shm_destroy(shmid);
143 if (ret < 0)
144 goto err_out;
145 mmd = shm;
146
147 ret = mutex_new();
148 if (ret < 0)
149 goto err_out;
150 mmd_mutex = ret;
151
152 mmd->num_played = 0;
153 mmd->num_commands = 0;
154 mmd->events = 0;
155 mmd->num_connects = 0;
156 mmd->active_connections = 0;
157 mmd->vss_status_flags = VSS_NEXT;
158 mmd->new_vss_status_flags = VSS_NEXT;
159 return;
160 err_out:
161 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
162 exit(EXIT_FAILURE);
163 }
164
165 /**
166 * (Re-)read the server configuration files.
167 *
168 * \param override Passed to gengetopt to activate the override feature.
169 *
170 * This function also re-opens the logfile and sets the global \a
171 * user_list_file variable.
172 */
173 void parse_config_or_die(int override)
174 {
175 char *home = para_homedir();
176 int ret;
177 char *cf;
178
179 daemon_close_log();
180 if (conf.config_file_given)
181 cf = para_strdup(conf.config_file_arg);
182 else
183 cf = make_message("%s/.paraslash/server.conf", home);
184 free(user_list_file);
185 if (!conf.user_list_given)
186 user_list_file = make_message("%s/.paraslash/server.users", home);
187 else
188 user_list_file = para_strdup(conf.user_list_arg);
189 ret = file_exists(cf);
190 if (conf.config_file_given && !ret) {
191 ret = -1;
192 PARA_EMERG_LOG("can not read config file %s\n", cf);
193 goto out;
194 }
195 if (ret) {
196 int tmp = conf.daemon_given;
197 struct server_cmdline_parser_params params = {
198 .override = override,
199 .initialize = 0,
200 .check_required = 1,
201 .check_ambiguity = 0,
202 .print_errors = !conf.daemon_given
203 };
204 server_cmdline_parser_config_file(cf, &conf, &params);
205 daemon_set_loglevel(conf.loglevel_arg);
206 conf.daemon_given = tmp;
207 }
208 if (conf.logfile_given) {
209 daemon_set_logfile(conf.logfile_arg);
210 daemon_open_log_or_die();
211 }
212
213 daemon_init_colors_or_die(conf.color_arg, color_arg_auto, color_arg_no,
214 conf.logfile_given, conf.log_color_arg, conf.log_color_given);
215 daemon_set_flag(DF_LOG_PID);
216 daemon_set_flag(DF_LOG_LL);
217 daemon_set_flag(DF_LOG_TIME);
218 if (conf.log_timing_given)
219 daemon_set_flag(DF_LOG_TIMING);
220 ret = 1;
221 out:
222 free(cf);
223 free(home);
224 if (ret > 0)
225 return;
226 free(user_list_file);
227 user_list_file = NULL;
228 exit(EXIT_FAILURE);
229 }
230
231 /*
232 * called when server gets SIGHUP or when client invokes hup command.
233 */
234 static void handle_sighup(void)
235 {
236 PARA_NOTICE_LOG("SIGHUP\n");
237 parse_config_or_die(1); /* reopens log */
238 init_user_list(user_list_file); /* reload user list */
239 if (mmd->afs_pid)
240 kill(mmd->afs_pid, SIGHUP);
241 }
242
243 static int signal_post_select(struct sched *s, __a_unused void *context)
244 {
245 int signum = para_next_signal(&s->rfds);
246
247 switch (signum) {
248 case 0:
249 return 0;
250 case SIGHUP:
251 handle_sighup();
252 break;
253 case SIGCHLD:
254 for (;;) {
255 pid_t pid;
256 int ret = para_reap_child(&pid);
257 if (ret <= 0)
258 break;
259 if (pid != mmd->afs_pid)
260 continue;
261 PARA_EMERG_LOG("fatal: afs died\n");
262 kill(0, SIGTERM);
263 goto cleanup;
264 }
265 break;
266 /* die on sigint/sigterm. Kill all children too. */
267 case SIGINT:
268 case SIGTERM:
269 PARA_EMERG_LOG("terminating on signal %d\n", signum);
270 kill(0, SIGTERM);
271 /*
272 * We must wait for afs because afs catches SIGINT/SIGTERM.
273 * Before reacting to the signal, afs might want to use the
274 * shared memory area and the mmd mutex. If we destroy this
275 * mutex too early and afs tries to lock the shared memory
276 * area, the call to mutex_lock() will fail and terminate the
277 * afs process. This leads to dirty osl tables.
278 *
279 * There's no such problem with the other children of the
280 * server process (the command handlers) as these reset their
281 * SIGINT/SIGTERM handlers to the default action, i.e. these
282 * processes get killed immediately by the above kill().
283 */
284 PARA_INFO_LOG("waiting for afs (pid %d) to die\n",
285 (int)mmd->afs_pid);
286 waitpid(mmd->afs_pid, NULL, 0);
287 cleanup:
288 free(mmd->afd.afhi.chunk_table);
289 close_listed_fds();
290 mutex_destroy(mmd_mutex);
291 shm_detach(mmd);
292 exit(EXIT_FAILURE);
293 }
294 return 0;
295 }
296
297 static void init_signal_task(void)
298 {
299 signal_task = signal_init_or_die();
300 para_install_sighandler(SIGINT);
301 para_install_sighandler(SIGTERM);
302 para_install_sighandler(SIGHUP);
303 para_install_sighandler(SIGCHLD);
304 para_sigaction(SIGPIPE, SIG_IGN);
305 add_close_on_fork_list(signal_task->fd);
306 signal_task->task = task_register(&(struct task_info) {
307 .name = "signal",
308 .pre_select = signal_pre_select,
309 .post_select = signal_post_select,
310 .context = signal_task,
311
312 }, &sched);
313 }
314
315 static void command_pre_select(struct sched *s, void *context)
316 {
317 struct server_command_task *sct = context;
318 para_fd_set(sct->listen_fd, &s->rfds, &s->max_fileno);
319 }
320
321 static int command_post_select(struct sched *s, void *context)
322 {
323 struct server_command_task *sct = context;
324
325 int new_fd, ret, i;
326 char *peer_name;
327 pid_t child_pid;
328 uint32_t *chunk_table;
329
330 ret = para_accept(sct->listen_fd, &s->rfds, NULL, 0, &new_fd);
331 if (ret <= 0)
332 goto out;
333 peer_name = remote_name(new_fd);
334 PARA_INFO_LOG("got connection from %s, forking\n", peer_name);
335 mmd->num_connects++;
336 mmd->active_connections++;
337 /*
338 * The chunk table is a pointer located in the mmd struct that points
339 * to dynamically allocated memory, i.e. it must be freed by the parent
340 * and the child. However, as the mmd struct is in a shared memory
341 * area, there's no guarantee that after the fork this pointer is still
342 * valid in child context. As it is not used in the child anyway, we
343 * save it to a local variable before the fork and free the memory via
344 * that copy in the child directly after the fork.
345 */
346 chunk_table = mmd->afd.afhi.chunk_table;
347 child_pid = fork();
348 if (child_pid < 0) {
349 ret = -ERRNO_TO_PARA_ERROR(errno);
350 goto out;
351 }
352 if (child_pid) {
353 /* avoid problems with non-fork-safe PRNGs */
354 unsigned char buf[16];
355 get_random_bytes_or_die(buf, sizeof(buf));
356 close(new_fd);
357 /* parent keeps accepting connections */
358 return 0;
359 }
360 /* mmd might already have changed at this point */
361 free(chunk_table);
362 alarm(ALARM_TIMEOUT);
363 close_listed_fds();
364 signal_shutdown(signal_task);
365 /*
366 * put info on who we are serving into argv[0] to make
367 * client ip visible in top/ps
368 */
369 for (i = sct->argc - 1; i >= 0; i--)
370 memset(sct->argv[i], 0, strlen(sct->argv[i]));
371 sprintf(sct->argv[0], "para_server (serving %s)", peer_name);
372 handle_connect(new_fd, peer_name);
373 /* never reached*/
374 out:
375 if (ret < 0)
376 PARA_CRIT_LOG("%s\n", para_strerror(-ret));
377 return 0;
378 }
379
380 static void init_server_command_task(int argc, char **argv)
381 {
382 int ret;
383 static struct server_command_task server_command_task_struct,
384 *sct = &server_command_task_struct;
385
386 PARA_NOTICE_LOG("initializing tcp command socket\n");
387 sct->argc = argc;
388 sct->argv = argv;
389 ret = para_listen_simple(IPPROTO_TCP, conf.port_arg);
390 if (ret < 0)
391 goto err;
392 sct->listen_fd = ret;
393 ret = mark_fd_nonblocking(sct->listen_fd);
394 if (ret < 0)
395 goto err;
396 add_close_on_fork_list(sct->listen_fd); /* child doesn't need the listener */
397 sct->task = task_register(&(struct task_info) {
398 .name = "server command",
399 .pre_select = command_pre_select,
400 .post_select = command_post_select,
401 .context = sct,
402 }, &sched);
403 return;
404 err:
405 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
406 exit(EXIT_FAILURE);
407 }
408
409 static int init_afs(int argc, char **argv)
410 {
411 int ret, afs_server_socket[2];
412 pid_t afs_pid;
413
414 ret = socketpair(PF_UNIX, SOCK_DGRAM, 0, afs_server_socket);
415 if (ret < 0)
416 exit(EXIT_FAILURE);
417 get_random_bytes_or_die((unsigned char *)&afs_socket_cookie,
418 sizeof(afs_socket_cookie));
419 afs_pid = fork();
420 if (afs_pid < 0)
421 exit(EXIT_FAILURE);
422 if (afs_pid == 0) { /* child (afs) */
423 int i;
424 for (i = argc - 1; i >= 0; i--)
425 memset(argv[i], 0, strlen(argv[i]));
426 sprintf(argv[0], "para_server (afs)");
427 close(afs_server_socket[0]);
428 afs_init(afs_socket_cookie, afs_server_socket[1]);
429 }
430 mmd->afs_pid = afs_pid;
431 close(afs_server_socket[1]);
432 ret = mark_fd_nonblocking(afs_server_socket[0]);
433 if (ret < 0)
434 exit(EXIT_FAILURE);
435 add_close_on_fork_list(afs_server_socket[0]);
436 PARA_INFO_LOG("afs_socket: %d, afs_socket_cookie: %u\n",
437 afs_server_socket[0], (unsigned) afs_socket_cookie);
438 return afs_server_socket[0];
439 }
440
441 __noreturn static void print_help_and_die(void)
442 {
443 struct ggo_help h = DEFINE_GGO_HELP(server);
444 bool d = conf.detailed_help_given;
445
446 ggo_print_help(&h, d? GPH_STANDARD_FLAGS_DETAILED : GPH_STANDARD_FLAGS);
447 exit(0);
448 }
449
450 static void server_init(int argc, char **argv)
451 {
452 struct server_cmdline_parser_params params = {
453 .override = 0,
454 .initialize = 1,
455 .check_required = 0,
456 .check_ambiguity = 0,
457 .print_errors = 1
458 };
459 int afs_socket;
460
461 valid_fd_012();
462 init_random_seed_or_die();
463 /* parse command line options */
464 server_cmdline_parser_ext(argc, argv, &conf, &params);
465 daemon_set_loglevel(conf.loglevel_arg);
466 version_handle_flag("server", conf.version_given);
467 if (conf.help_given || conf.detailed_help_given)
468 print_help_and_die();
469 daemon_drop_privileges_or_die(conf.user_arg, conf.group_arg);
470 /* parse config file, open log and set defaults */
471 parse_config_or_die(0);
472 daemon_log_welcome("para_server");
473 init_ipc_or_die(); /* init mmd struct and mmd->lock */
474 daemon_set_start_time();
475 init_user_list(user_list_file);
476 /* become daemon */
477 if (conf.daemon_given)
478 daemonize(true /* parent waits for SIGTERM */);
479 PARA_NOTICE_LOG("initializing audio format handlers\n");
480 afh_init();
481
482 /*
483 * Although afs uses its own signal handling we must ignore SIGUSR1
484 * _before_ the afs child process gets born by init_afs() below. It's
485 * racy to do this in the child because the parent might send SIGUSR1
486 * before the child gets a chance to ignore this signal -- only the
487 * good die young.
488 */
489 para_sigaction(SIGUSR1, SIG_IGN);
490 /*
491 * We have to block SIGCHLD before the afs process is being forked off.
492 * Otherwise, para_server does not notice if afs dies before the
493 * SIGCHLD handler has been installed for the parent process by
494 * init_signal_task() below.
495 */
496 para_block_signal(SIGCHLD);
497 PARA_NOTICE_LOG("initializing the audio file selector\n");
498 afs_socket = init_afs(argc, argv);
499 init_signal_task();
500 para_unblock_signal(SIGCHLD);
501 PARA_NOTICE_LOG("initializing virtual streaming system\n");
502 init_vss_task(afs_socket, &sched);
503 init_server_command_task(argc, argv);
504 if (conf.daemon_given)
505 kill(getppid(), SIGTERM);
506 PARA_NOTICE_LOG("server init complete\n");
507 }
508
509 static void status_refresh(void)
510 {
511 static int prev_uptime = -1, prev_events = -1;
512 int uptime = daemon_get_uptime(now);
513
514 if (prev_events != mmd->events)
515 goto out;
516 if (mmd->new_vss_status_flags != mmd->vss_status_flags)
517 goto out_inc_events;
518 if (uptime / 60 != prev_uptime / 60)
519 goto out_inc_events;
520 return;
521 out_inc_events:
522 mmd->events++;
523 out:
524 prev_uptime = uptime;
525 prev_events = mmd->events;
526 mmd->vss_status_flags = mmd->new_vss_status_flags;
527 PARA_DEBUG_LOG("%d events, forcing status update\n", mmd->events);
528 killpg(0, SIGUSR1);
529 }
530
531 static int server_select(int max_fileno, fd_set *readfds, fd_set *writefds,
532 struct timeval *timeout_tv)
533 {
534 int ret;
535
536 status_refresh();
537 mutex_unlock(mmd_mutex);
538 ret = para_select(max_fileno + 1, readfds, writefds, timeout_tv);
539 mutex_lock(mmd_mutex);
540 return ret;
541 }
542
543 /**
544 * The main function of para_server.
545 *
546 * \param argc Usual argument count.
547 * \param argv Usual argument vector.
548 *
549 * \return EXIT_SUCCESS or EXIT_FAILURE.
550 */
551 int main(int argc, char *argv[])
552 {
553 int ret;
554
555 sched.default_timeout.tv_sec = 1;
556 sched.select_function = server_select;
557
558 server_init(argc, argv);
559 mutex_lock(mmd_mutex);
560 ret = schedule(&sched);
561 sched_shutdown(&sched);
562 if (ret < 0) {
563 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
564 exit(EXIT_FAILURE);
565 }
566 exit(EXIT_SUCCESS);
567 }