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