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