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