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