Merge topic branch t/ff-compat into master
[paraslash.git] / server.c
1 /* Copyright (C) 1997 Andre Noll <maan@tuebingen.mpg.de>, see file COPYING. */
2
3 /** \file server.c Paraslash's main server. */
4
5 #include <netinet/in.h>
6 #include <sys/socket.h>
7 #include <signal.h>
8 #include <regex.h>
9 #include <osl.h>
10 #include <sys/types.h>
11 #include <arpa/inet.h>
12 #include <sys/un.h>
13 #include <netdb.h>
14 #include <lopsub.h>
15
16 #include "server.lsg.h"
17 #include "para.h"
18 #include "error.h"
19 #include "lsu.h"
20 #include "crypt.h"
21 #include "afh.h"
22 #include "string.h"
23 #include "afs.h"
24 #include "net.h"
25 #include "server.h"
26 #include "list.h"
27 #include "send.h"
28 #include "sched.h"
29 #include "vss.h"
30 #include "config.h"
31 #include "close_on_fork.h"
32 #include "daemon.h"
33 #include "ipc.h"
34 #include "fd.h"
35 #include "signal.h"
36 #include "user_list.h"
37 #include "color.h"
38 #include "version.h"
39
40 /** Array of error strings. */
41 DEFINE_PARA_ERRLIST;
42
43 __printf_2_3 void (*para_log)(int, const char*, ...) = daemon_log;
44
45 /** Shut down non-authorized connections after that many seconds. */
46 #define ALARM_TIMEOUT 10
47
48 /**
49 * Pointer to shared memory area for communication between para_server
50 * and its children. Exported to vss.c, command.c and to afs.
51 */
52 struct misc_meta_data *mmd;
53
54 /**
55 * The active value for all config options of para_server.
56 *
57 * It is computed by merging the parse result of the command line options with
58 * the parse result of the config file.
59 */
60 struct lls_parse_result *server_lpr = NULL;
61
62 /* Command line options (no config file options). Used in handle_sighup(). */
63 static struct lls_parse_result *cmdline_lpr;
64
65 /**
66 * A random number used to "authenticate" the afs connection.
67 *
68 * para_server picks this number by random before it forks the afs process. The
69 * command handlers know this number as well and write it to the afs socket,
70 * together with the id of the shared memory area which contains the payload of
71 * the afs command. A local process has to know this number to abuse the afs
72 * service provided by the local socket.
73 */
74 uint32_t afs_socket_cookie;
75
76 /** The mutex protecting the shared memory area containing the mmd struct. */
77 int mmd_mutex;
78
79 /* Serializes log output. */
80 static int log_mutex;
81
82 static struct sched sched;
83 static struct signal_task *signal_task;
84
85 /** The process id of the audio file selector process. */
86 pid_t afs_pid = 0;
87
88 /* The main server process (parent of afs and the command handlers). */
89 static pid_t server_pid;
90
91 /**
92 * Tell whether the executing process is a command handler.
93 *
94 * Cleanup on exit must be performed differently for command handlers.
95 *
96 * \return True if the pid of the executing process is neither the server pid
97 * nor the afs pid.
98 */
99 bool process_is_command_handler(void)
100 {
101 pid_t pid = getpid();
102
103 return pid != afs_pid && pid != server_pid;
104 }
105
106 /** The task responsible for server command handling. */
107 struct server_command_task {
108 unsigned num_listen_fds; /* only one by default */
109 /** TCP socket(s) on which para_server listens for connections. */
110 int *listen_fds;
111 /* File descriptor for the accepted socket. */
112 int child_fd;
113 /** Copied from para_server's main function. */
114 int argc;
115 /** Argument vector passed to para_server's main function. */
116 char **argv;
117 /** The command task structure for scheduling. */
118 struct task *task;
119 };
120
121 /**
122 * Return the list of tasks for the server process.
123 *
124 * This is called from \a com_tasks(). The helper is necessary since command
125 * handlers can not access the scheduler structure directly.
126 *
127 * \return A dynamically allocated string that must be freed by the caller.
128 */
129 char *server_get_tasks(void)
130 {
131 return get_task_list(&sched);
132 }
133
134 static void pre_log_hook(void)
135 {
136 mutex_lock(log_mutex);
137 }
138
139 static void post_log_hook(void)
140 {
141 mutex_unlock(log_mutex);
142 }
143
144 /* Setup shared memory area and init mutexes */
145 static void init_ipc_or_die(void)
146 {
147 void *shm;
148 int shmid, ret = shm_new(sizeof(struct misc_meta_data));
149
150 if (ret < 0)
151 goto err_out;
152 shmid = ret;
153 ret = shm_attach(shmid, ATTACH_RW, &shm);
154 shm_destroy(shmid);
155 if (ret < 0)
156 goto err_out;
157 mmd = shm;
158
159 ret = mutex_new();
160 if (ret < 0)
161 goto err_out;
162 mmd_mutex = ret;
163 ret = mutex_new();
164 if (ret < 0)
165 goto destroy_mmd_mutex;
166 log_mutex = ret;
167
168 mmd->num_played = 0;
169 mmd->num_commands = 0;
170 mmd->events = 0;
171 mmd->num_connects = 0;
172 mmd->active_connections = 0;
173 mmd->vss_status_flags = VSS_NEXT;
174 mmd->new_vss_status_flags = VSS_NEXT;
175 return;
176 destroy_mmd_mutex:
177 mutex_destroy(mmd_mutex);
178 err_out:
179 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
180 exit(EXIT_FAILURE);
181 }
182
183 /**
184 * (Re-)read the server configuration files.
185 *
186 * \param reload Whether config file overrides command line.
187 *
188 * This function also re-opens the logfile and the user list. On SIGHUP it is
189 * called from both server and afs context.
190 */
191 void parse_config_or_die(bool reload)
192 {
193 int ret;
194 unsigned flags = MCF_DONT_FREE;
195
196 if (server_lpr != cmdline_lpr)
197 lls_free_parse_result(server_lpr, CMD_PTR);
198 server_lpr = cmdline_lpr;
199 if (reload)
200 flags |= MCF_OVERRIDE;
201 ret = lsu_merge_config_file_options(OPT_STRING_VAL(CONFIG_FILE),
202 "server.conf", &server_lpr, CMD_PTR, server_suite, flags);
203 if (ret < 0) {
204 PARA_EMERG_LOG("failed to parse config file: %s\n",
205 para_strerror(-ret));
206 exit(EXIT_FAILURE);
207 }
208 daemon_set_loglevel(ENUM_STRING_VAL(LOGLEVEL));
209 if (OPT_GIVEN(LOGFILE)) {
210 daemon_set_logfile(OPT_STRING_VAL(LOGFILE));
211 daemon_open_log_or_die();
212 }
213 if (daemon_init_colors_or_die(OPT_UINT32_VAL(COLOR), COLOR_AUTO,
214 COLOR_NO, OPT_GIVEN(LOGFILE))) {
215 int i;
216 for (i = 0; i < OPT_GIVEN(LOG_COLOR); i++)
217 daemon_set_log_color_or_die(lls_string_val(i,
218 OPT_RESULT(LOG_COLOR)));
219 }
220 daemon_set_flag(DF_LOG_PID);
221 daemon_set_flag(DF_LOG_LL);
222 daemon_set_flag(DF_LOG_TIME);
223 if (OPT_GIVEN(LOG_TIMING))
224 daemon_set_flag(DF_LOG_TIMING);
225 daemon_set_priority(OPT_UINT32_VAL(PRIORITY));
226 if (!reload || getpid() != afs_pid) {
227 char *user_list_file;
228 if (OPT_GIVEN(USER_LIST))
229 user_list_file = para_strdup(OPT_STRING_VAL(USER_LIST));
230 else {
231 char *home = para_homedir();
232 user_list_file = make_message("%s/.paraslash/server.users", home);
233 free(home);
234 }
235 user_list_init(user_list_file);
236 free(user_list_file);
237 }
238 return;
239 }
240
241 /*
242 * called when server gets SIGHUP or when client invokes hup command.
243 */
244 static void handle_sighup(void)
245 {
246
247 PARA_NOTICE_LOG("SIGHUP\n");
248 parse_config_or_die(true);
249 if (afs_pid != 0)
250 kill(afs_pid, SIGHUP);
251 }
252
253 static int signal_post_select(struct sched *s, __a_unused void *context)
254 {
255 int ret, signum;
256
257 ret = task_get_notification(signal_task->task);
258 if (ret < 0)
259 return ret;
260 signum = para_next_signal(&s->rfds);
261 switch (signum) {
262 case 0:
263 return 0;
264 case SIGHUP:
265 handle_sighup();
266 break;
267 case SIGCHLD:
268 for (;;) {
269 pid_t pid;
270 ret = para_reap_child(&pid);
271 if (ret <= 0)
272 break;
273 if (pid != afs_pid)
274 continue;
275 PARA_EMERG_LOG("fatal: afs died\n");
276 goto genocide;
277 }
278 break;
279 /* die on sigint/sigterm. Kill all children too. */
280 case SIGINT:
281 case SIGTERM:
282 PARA_EMERG_LOG("terminating on signal %d\n", signum);
283 genocide:
284 kill(0, SIGTERM);
285 /*
286 * We must wait for all of our children to die. For the afs
287 * process or a command handler might want to use the
288 * shared memory area and the mmd mutex. If we destroy this
289 * mutex too early and afs tries to lock the shared memory
290 * area, the call to mutex_lock() will fail and terminate the
291 * afs process. This leads to dirty osl tables.
292 */
293 PARA_INFO_LOG("waiting for child processes to die\n");
294 mutex_unlock(mmd_mutex);
295 while (wait(NULL) != -1 || errno != ECHILD)
296 ; /* still at least one child alive */
297 mutex_lock(mmd_mutex);
298 free(mmd->afd.afhi.chunk_table);
299 task_notify_all(s, E_DEADLY_SIGNAL);
300 return -E_DEADLY_SIGNAL;
301 }
302 return 0;
303 }
304
305 static void init_signal_task(void)
306 {
307 signal_task = signal_init_or_die();
308 para_install_sighandler(SIGINT);
309 para_install_sighandler(SIGTERM);
310 para_install_sighandler(SIGHUP);
311 para_install_sighandler(SIGCHLD);
312 para_sigaction(SIGPIPE, SIG_IGN);
313 add_close_on_fork_list(signal_task->fd);
314 signal_task->task = task_register(&(struct task_info) {
315 .name = "signal",
316 .pre_select = signal_pre_select,
317 .post_select = signal_post_select,
318 .context = signal_task,
319
320 }, &sched);
321 }
322
323 static void command_pre_select(struct sched *s, void *context)
324 {
325 unsigned n;
326 struct server_command_task *sct = context;
327
328 for (n = 0; n < sct->num_listen_fds; n++)
329 para_fd_set(sct->listen_fds[n], &s->rfds, &s->max_fileno);
330 }
331
332 static int command_task_accept(unsigned listen_idx, struct sched *s,
333 struct server_command_task *sct)
334 {
335 int new_fd, ret, i;
336 char *peer_name;
337 pid_t child_pid;
338 uint32_t *chunk_table;
339
340 ret = para_accept(sct->listen_fds[listen_idx], &s->rfds, NULL, 0, &new_fd);
341 if (ret <= 0)
342 goto out;
343 mmd->num_connects++;
344 mmd->active_connections++;
345 /*
346 * The chunk table is a pointer located in the mmd struct that points
347 * to dynamically allocated memory, i.e. it must be freed by the parent
348 * and the child. However, as the mmd struct is in a shared memory
349 * area, there's no guarantee that after the fork this pointer is still
350 * valid in child context. As it is not used in the child anyway, we
351 * save it to a local variable before the fork and free the memory via
352 * that copy in the child directly after the fork.
353 */
354 chunk_table = mmd->afd.afhi.chunk_table;
355 child_pid = fork();
356 if (child_pid < 0) {
357 ret = -ERRNO_TO_PARA_ERROR(errno);
358 goto out;
359 }
360 if (child_pid) {
361 /* avoid problems with non-fork-safe PRNGs */
362 unsigned char buf[16];
363 get_random_bytes_or_die(buf, sizeof(buf));
364 close(new_fd);
365 /* parent keeps accepting connections */
366 return 0;
367 }
368 peer_name = remote_name(new_fd);
369 PARA_INFO_LOG("accepted connection from %s\n", peer_name);
370 /* mmd might already have changed at this point */
371 free(chunk_table);
372 sct->child_fd = new_fd;
373 /*
374 * put info on who we are serving into argv[0] to make
375 * client ip visible in top/ps
376 */
377 for (i = sct->argc - 1; i >= 0; i--)
378 memset(sct->argv[i], 0, strlen(sct->argv[i]));
379 i = sct->argc - 1 - lls_num_inputs(cmdline_lpr);
380 sprintf(sct->argv[i], "para_server (serving %s)", peer_name);
381 /* ask other tasks to terminate */
382 task_notify_all(s, E_CHILD_CONTEXT);
383 /*
384 * After we return, the scheduler calls server_select() with a minimal
385 * timeout value, because the remaining tasks have a notification
386 * pending. Next it calls the ->post_select method of these tasks,
387 * which will return negative in view of the notification. This causes
388 * schedule() to return as there are no more runnable tasks.
389 *
390 * Note that semaphores are not inherited across a fork(), so we don't
391 * hold the lock at this point. Since server_select() drops the lock
392 * prior to calling para_select(), we need to acquire it here.
393 */
394 mutex_lock(mmd_mutex);
395 return -E_CHILD_CONTEXT;
396 out:
397 if (ret < 0)
398 PARA_CRIT_LOG("%s\n", para_strerror(-ret));
399 return 0;
400 }
401
402 static int command_post_select(struct sched *s, void *context)
403 {
404 struct server_command_task *sct = context;
405 unsigned n;
406 int ret;
407
408 ret = task_get_notification(sct->task);
409 if (ret < 0)
410 goto fail;
411 for (n = 0; n < sct->num_listen_fds; n++) {
412 ret = command_task_accept(n, s, sct);
413 if (ret < 0)
414 goto fail;
415 }
416 return 0;
417 fail:
418 free(sct->listen_fds);
419 return ret;
420 }
421
422 static void init_server_command_task(struct server_command_task *sct,
423 int argc, char **argv)
424 {
425 int ret;
426 unsigned n;
427 uint32_t port = OPT_UINT32_VAL(PORT);
428
429 PARA_NOTICE_LOG("initializing tcp command socket\n");
430 sct->child_fd = -1;
431 sct->argc = argc;
432 sct->argv = argv;
433 if (!OPT_GIVEN(LISTEN_ADDRESS)) {
434 sct->num_listen_fds = 1;
435 sct->listen_fds = para_malloc(sizeof(int));
436 ret = para_listen_simple(IPPROTO_TCP, port);
437 if (ret < 0)
438 goto err;
439 sct->listen_fds[0] = ret;
440 } else {
441 sct->num_listen_fds = OPT_GIVEN(LISTEN_ADDRESS);
442 sct->listen_fds = para_malloc(sct->num_listen_fds * sizeof(int));
443 for (n = 0; n < OPT_GIVEN(LISTEN_ADDRESS); n++) {
444 const char *arg;
445 arg = lls_string_val(n, OPT_RESULT(LISTEN_ADDRESS));
446 ret = para_listen(IPPROTO_TCP, arg, port);
447 if (ret < 0)
448 goto err;
449 sct->listen_fds[n] = ret;
450 }
451 }
452 for (n = 0; n < sct->num_listen_fds; n++) {
453 ret = mark_fd_nonblocking(sct->listen_fds[n]);
454 if (ret < 0)
455 goto err;
456 /* child doesn't need the listener */
457 add_close_on_fork_list(sct->listen_fds[n]);
458 }
459
460 sct->task = task_register(&(struct task_info) {
461 .name = "server command",
462 .pre_select = command_pre_select,
463 .post_select = command_post_select,
464 .context = sct,
465 }, &sched);
466 /*
467 * Detect whether the abstract Unix domain socket space is supported,
468 * but do not create the socket. We check this once in server context
469 * so that the command handlers inherit this bit of information and
470 * don't need to check again.
471 */
472 create_local_socket(NULL);
473 return;
474 err:
475 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
476 exit(EXIT_FAILURE);
477 }
478
479 static int init_afs(int argc, char **argv)
480 {
481 int ret, afs_server_socket[2];
482 char c;
483
484 ret = socketpair(PF_UNIX, SOCK_STREAM, 0, afs_server_socket);
485 if (ret < 0)
486 exit(EXIT_FAILURE);
487 get_random_bytes_or_die((unsigned char *)&afs_socket_cookie,
488 sizeof(afs_socket_cookie));
489 afs_pid = fork();
490 if (afs_pid < 0)
491 exit(EXIT_FAILURE);
492 if (afs_pid == 0) { /* child (afs) */
493 int i;
494
495 afs_pid = getpid();
496 crypt_shutdown();
497 user_list_deplete();
498 for (i = argc - 1; i >= 0; i--)
499 memset(argv[i], 0, strlen(argv[i]));
500 i = argc - lls_num_inputs(cmdline_lpr) - 1;
501 sprintf(argv[i], "para_server (afs)");
502 close(afs_server_socket[0]);
503 afs_init(afs_server_socket[1]);
504 }
505 close(afs_server_socket[1]);
506 if (read(afs_server_socket[0], &c, 1) <= 0) {
507 PARA_EMERG_LOG("early afs exit\n");
508 exit(EXIT_FAILURE);
509 }
510 ret = mark_fd_nonblocking(afs_server_socket[0]);
511 if (ret < 0)
512 exit(EXIT_FAILURE);
513 add_close_on_fork_list(afs_server_socket[0]);
514 PARA_INFO_LOG("afs_socket: %d, afs_socket_cookie: %u\n",
515 afs_server_socket[0], (unsigned) afs_socket_cookie);
516 return afs_server_socket[0];
517 }
518
519 static void handle_help_flags(void)
520 {
521 char *help;
522 bool d = OPT_GIVEN(DETAILED_HELP);
523
524 if (d)
525 help = lls_long_help(CMD_PTR);
526 else if (OPT_GIVEN(HELP))
527 help = lls_short_help(CMD_PTR);
528 else
529 return;
530 printf("%s\n", help);
531 free(help);
532 exit(EXIT_SUCCESS);
533 }
534
535 static void server_init(int argc, char **argv, struct server_command_task *sct)
536 {
537 int ret, afs_socket, daemon_pipe = -1;
538 char *errctx;
539
540 valid_fd_012();
541 /* parse command line options */
542 ret = lls(lls_parse(argc, argv, CMD_PTR, &cmdline_lpr, &errctx));
543 if (ret < 0)
544 goto fail;
545 server_lpr = cmdline_lpr;
546 daemon_set_loglevel(ENUM_STRING_VAL(LOGLEVEL));
547 daemon_drop_privileges_or_die(OPT_STRING_VAL(USER),
548 OPT_STRING_VAL(GROUP));
549 version_handle_flag("server", OPT_GIVEN(VERSION));
550 handle_help_flags();
551 parse_config_or_die(false);
552 /* become daemon */
553 if (OPT_GIVEN(DAEMON))
554 daemon_pipe = daemonize(true /* parent waits for SIGTERM */);
555 server_pid = getpid();
556 crypt_init();
557 daemon_log_welcome("server");
558 init_ipc_or_die(); /* init mmd struct, mmd and log mutex */
559 daemon_set_start_time();
560 daemon_set_hooks(pre_log_hook, post_log_hook);
561 /*
562 * Although afs uses its own signal handling we must ignore SIGUSR1
563 * _before_ the afs child process gets born by init_afs() below. It's
564 * racy to do this in the child because the parent might send SIGUSR1
565 * before the child gets a chance to ignore this signal.
566 *
567 * We also have to block SIGCHLD before the afs process is created
568 * because otherwise para_server does not notice if afs dies before the
569 * SIGCHLD handler has been installed for the parent process by
570 * init_signal_task() below.
571 */
572 para_sigaction(SIGUSR1, SIG_IGN);
573 para_block_signal(SIGCHLD);
574 PARA_NOTICE_LOG("initializing the audio file selector\n");
575 afs_socket = init_afs(argc, argv);
576 init_signal_task();
577 para_unblock_signal(SIGCHLD);
578 PARA_NOTICE_LOG("initializing virtual streaming system\n");
579 vss_init(afs_socket, &sched);
580 init_server_command_task(sct, argc, argv);
581 if (daemon_pipe >= 0) {
582 if (write(daemon_pipe, "\0", 1) < 0) {
583 PARA_EMERG_LOG("daemon_pipe: %s", strerror(errno));
584 exit(EXIT_FAILURE);
585 }
586 close(daemon_pipe);
587 }
588 PARA_NOTICE_LOG("server init complete\n");
589 return;
590 fail:
591 assert(ret < 0);
592 if (errctx)
593 PARA_ERROR_LOG("%s\n", errctx);
594 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
595 exit(EXIT_FAILURE);
596 }
597
598 static void status_refresh(void)
599 {
600 static int prev_uptime = -1, prev_events = -1;
601 int uptime = daemon_get_uptime(now);
602
603 if (prev_events != mmd->events)
604 goto out;
605 if (mmd->new_vss_status_flags != mmd->vss_status_flags)
606 goto out_inc_events;
607 if (uptime / 60 != prev_uptime / 60)
608 goto out_inc_events;
609 return;
610 out_inc_events:
611 mmd->events++;
612 out:
613 prev_uptime = uptime;
614 prev_events = mmd->events;
615 mmd->vss_status_flags = mmd->new_vss_status_flags;
616 PARA_DEBUG_LOG("%u events, forcing status update\n", mmd->events);
617 killpg(0, SIGUSR1);
618 }
619
620 static int server_select(int max_fileno, fd_set *readfds, fd_set *writefds,
621 struct timeval *timeout_tv)
622 {
623 int ret;
624
625 status_refresh();
626 mutex_unlock(mmd_mutex);
627 ret = para_select(max_fileno + 1, readfds, writefds, timeout_tv);
628 mutex_lock(mmd_mutex);
629 return ret;
630 }
631
632 /**
633 * Deallocate all lopsub parse results.
634 *
635 * The server allocates a parse result for command line options and optionally
636 * a second parse result for the effective configuration, defined by merging
637 * the command line options with the options stored in the configuration file.
638 * This function frees both structures.
639 */
640 void free_lpr(void)
641 {
642 lls_free_parse_result(server_lpr, CMD_PTR);
643 if (server_lpr != cmdline_lpr)
644 lls_free_parse_result(cmdline_lpr, CMD_PTR);
645 }
646
647 /**
648 * The main function of para_server.
649 *
650 * \param argc Usual argument count.
651 * \param argv Usual argument vector.
652 *
653 * \return EXIT_SUCCESS or EXIT_FAILURE.
654 */
655 int main(int argc, char *argv[])
656 {
657 int ret;
658 struct server_command_task server_command_task_struct,
659 *sct = &server_command_task_struct;
660
661 sched.default_timeout.tv_sec = 1;
662 sched.select_function = server_select;
663
664 server_init(argc, argv, sct);
665 mutex_lock(mmd_mutex);
666 ret = schedule(&sched);
667 /*
668 * We hold the mmd lock: it was re-acquired in server_select()
669 * after the select call.
670 */
671 mutex_unlock(mmd_mutex);
672 sched_shutdown(&sched);
673 crypt_shutdown();
674 signal_shutdown(signal_task);
675 if (!process_is_command_handler()) { /* parent (server) */
676 mutex_destroy(mmd_mutex);
677 daemon_set_hooks(NULL, NULL); /* only one process remaining */
678 mutex_destroy(log_mutex);
679 deplete_close_on_fork_list();
680 if (ret < 0)
681 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
682 vss_shutdown();
683 } else {
684 vss_shutdown();
685 alarm(ALARM_TIMEOUT);
686 close_listed_fds();
687 ret = handle_connect(sct->child_fd);
688 }
689 shm_detach(mmd);
690 user_list_deplete();
691 free_lpr();
692 exit(ret < 0? EXIT_FAILURE : EXIT_SUCCESS);
693 }