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