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