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