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