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