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