Let afs_event() return int.
[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         daemon_init_colors_or_die(conf.color_arg, color_arg_auto, color_arg_no,
211                 conf.logfile_given, conf.log_color_arg, conf.log_color_given);
212         daemon_set_flag(DF_LOG_PID);
213         daemon_set_flag(DF_LOG_LL);
214         daemon_set_flag(DF_LOG_TIME);
215         if (conf.log_timing_given)
216                 daemon_set_flag(DF_LOG_TIMING);
217         ret = 1;
218 out:
219         free(cf);
220         free(home);
221         if (ret > 0)
222                 return;
223         free(user_list_file);
224         user_list_file = NULL;
225         exit(EXIT_FAILURE);
226 }
227
228 /*
229  * called when server gets SIGHUP or when client invokes hup command.
230  */
231 static void handle_sighup(void)
232 {
233         PARA_NOTICE_LOG("SIGHUP\n");
234         parse_config_or_die(1); /* reopens log */
235         init_user_list(user_list_file); /* reload user list */
236         if (mmd->afs_pid)
237                 kill(mmd->afs_pid, SIGHUP);
238 }
239
240 static int signal_post_select(struct sched *s, __a_unused void *context)
241 {
242         int signum = para_next_signal(&s->rfds);
243
244         switch (signum) {
245         case 0:
246                 return 0;
247         case SIGHUP:
248                 handle_sighup();
249                 break;
250         case SIGCHLD:
251                 for (;;) {
252                         pid_t pid;
253                         int ret = para_reap_child(&pid);
254                         if (ret <= 0)
255                                 break;
256                         if (pid != mmd->afs_pid)
257                                 continue;
258                         PARA_EMERG_LOG("fatal: afs died\n");
259                         kill(0, SIGTERM);
260                         goto cleanup;
261                 }
262                 break;
263         /* die on sigint/sigterm. Kill all children too. */
264         case SIGINT:
265         case SIGTERM:
266                 PARA_EMERG_LOG("terminating on signal %d\n", signum);
267                 kill(0, SIGTERM);
268                 /*
269                  * We must wait for afs because afs catches SIGINT/SIGTERM.
270                  * Before reacting to the signal, afs might want to use the
271                  * shared memory area and the mmd mutex.  If we destroy this
272                  * mutex too early and afs tries to lock the shared memory
273                  * area, the call to mutex_lock() will fail and terminate the
274                  * afs process. This leads to dirty osl tables.
275                  *
276                  * There's no such problem with the other children of the
277                  * server process (the command handlers) as these reset their
278                  * SIGINT/SIGTERM handlers to the default action, i.e.  these
279                  * processes get killed immediately by the above kill().
280                  */
281                 PARA_INFO_LOG("waiting for afs (pid %d) to die\n",
282                         (int)mmd->afs_pid);
283                 waitpid(mmd->afs_pid, NULL, 0);
284 cleanup:
285                 free(mmd->afd.afhi.chunk_table);
286                 close_listed_fds();
287                 mutex_destroy(mmd_mutex);
288                 shm_detach(mmd);
289                 exit(EXIT_FAILURE);
290         }
291         return 0;
292 }
293
294 static void init_signal_task(void)
295 {
296         signal_task = signal_init_or_die();
297         para_install_sighandler(SIGINT);
298         para_install_sighandler(SIGTERM);
299         para_install_sighandler(SIGHUP);
300         para_install_sighandler(SIGCHLD);
301         para_sigaction(SIGPIPE, SIG_IGN);
302         add_close_on_fork_list(signal_task->fd);
303         signal_task->task = task_register(&(struct task_info) {
304                 .name = "signal",
305                 .pre_select = signal_pre_select,
306                 .post_select = signal_post_select,
307                 .context = signal_task,
308
309         }, &sched);
310 }
311
312 static void command_pre_select(struct sched *s, void *context)
313 {
314         struct server_command_task *sct = context;
315         para_fd_set(sct->listen_fd, &s->rfds, &s->max_fileno);
316 }
317
318 static int command_post_select(struct sched *s, void *context)
319 {
320         struct server_command_task *sct = context;
321
322         int new_fd, ret, i;
323         char *peer_name;
324         pid_t child_pid;
325         uint32_t *chunk_table;
326
327         ret = para_accept(sct->listen_fd, &s->rfds, NULL, 0, &new_fd);
328         if (ret <= 0)
329                 goto out;
330         peer_name = remote_name(new_fd);
331         PARA_INFO_LOG("got connection from %s, forking\n", peer_name);
332         mmd->num_connects++;
333         mmd->active_connections++;
334         /*
335          * The chunk table is a pointer located in the mmd struct that points
336          * to dynamically allocated memory, i.e. it must be freed by the parent
337          * and the child. However, as the mmd struct is in a shared memory
338          * area, there's no guarantee that after the fork this pointer is still
339          * valid in child context. As it is not used in the child anyway, we
340          * save it to a local variable before the fork and free the memory via
341          * that copy in the child directly after the fork.
342          */
343         chunk_table = mmd->afd.afhi.chunk_table;
344         child_pid = fork();
345         if (child_pid < 0) {
346                 ret = -ERRNO_TO_PARA_ERROR(errno);
347                 goto out;
348         }
349         if (child_pid) {
350                 /* avoid problems with non-fork-safe PRNGs */
351                 unsigned char buf[16];
352                 get_random_bytes_or_die(buf, sizeof(buf));
353                 close(new_fd);
354                 /* parent keeps accepting connections */
355                 return 0;
356         }
357         /* mmd might already have changed at this point */
358         free(chunk_table);
359         alarm(ALARM_TIMEOUT);
360         close_listed_fds();
361         signal_shutdown(signal_task);
362         /*
363          * put info on who we are serving into argv[0] to make
364          * client ip visible in top/ps
365          */
366         for (i = sct->argc - 1; i >= 0; i--)
367                 memset(sct->argv[i], 0, strlen(sct->argv[i]));
368         sprintf(sct->argv[0], "para_server (serving %s)", peer_name);
369         handle_connect(new_fd, peer_name);
370         /* never reached*/
371 out:
372         if (ret < 0)
373                 PARA_CRIT_LOG("%s\n", para_strerror(-ret));
374         return 0;
375 }
376
377 static void init_server_command_task(int argc, char **argv)
378 {
379         int ret;
380         static struct server_command_task server_command_task_struct,
381                 *sct = &server_command_task_struct;
382
383         PARA_NOTICE_LOG("initializing tcp command socket\n");
384         sct->argc = argc;
385         sct->argv = argv;
386         ret = para_listen_simple(IPPROTO_TCP, conf.port_arg);
387         if (ret < 0)
388                 goto err;
389         sct->listen_fd = ret;
390         ret = mark_fd_nonblocking(sct->listen_fd);
391         if (ret < 0)
392                 goto err;
393         add_close_on_fork_list(sct->listen_fd); /* child doesn't need the listener */
394         sct->task = task_register(&(struct task_info) {
395                 .name = "server command",
396                 .pre_select = command_pre_select,
397                 .post_select = command_post_select,
398                 .context = sct,
399         }, &sched);
400         return;
401 err:
402         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
403         exit(EXIT_FAILURE);
404 }
405
406 static int init_afs(int argc, char **argv)
407 {
408         int ret, afs_server_socket[2];
409         pid_t afs_pid;
410
411         ret = socketpair(PF_UNIX, SOCK_DGRAM, 0, afs_server_socket);
412         if (ret < 0)
413                 exit(EXIT_FAILURE);
414         get_random_bytes_or_die((unsigned char *)&afs_socket_cookie,
415                 sizeof(afs_socket_cookie));
416         afs_pid = fork();
417         if (afs_pid < 0)
418                 exit(EXIT_FAILURE);
419         if (afs_pid == 0) { /* child (afs) */
420                 int i;
421                 for (i = argc - 1; i >= 0; i--)
422                         memset(argv[i], 0, strlen(argv[i]));
423                 sprintf(argv[0], "para_server (afs)");
424                 close(afs_server_socket[0]);
425                 afs_init(afs_socket_cookie, afs_server_socket[1]);
426         }
427         mmd->afs_pid = afs_pid;
428         close(afs_server_socket[1]);
429         ret = mark_fd_nonblocking(afs_server_socket[0]);
430         if (ret < 0)
431                 exit(EXIT_FAILURE);
432         add_close_on_fork_list(afs_server_socket[0]);
433         PARA_INFO_LOG("afs_socket: %d, afs_socket_cookie: %u\n",
434                 afs_server_socket[0], (unsigned) afs_socket_cookie);
435         return afs_server_socket[0];
436 }
437
438 __noreturn static void print_help_and_die(void)
439 {
440         struct ggo_help h = DEFINE_GGO_HELP(server);
441         bool d = conf.detailed_help_given;
442
443         ggo_print_help(&h, d? GPH_STANDARD_FLAGS_DETAILED : GPH_STANDARD_FLAGS);
444         exit(0);
445 }
446
447 static void server_init(int argc, char **argv)
448 {
449         struct server_cmdline_parser_params params = {
450                 .override = 0,
451                 .initialize = 1,
452                 .check_required = 0,
453                 .check_ambiguity = 0,
454                 .print_errors = 1
455         };
456         int afs_socket;
457
458         valid_fd_012();
459         init_random_seed_or_die();
460         /* parse command line options */
461         server_cmdline_parser_ext(argc, argv, &conf, &params);
462         daemon_set_loglevel(conf.loglevel_arg);
463         version_handle_flag("server", conf.version_given);
464         if (conf.help_given || conf.detailed_help_given)
465                 print_help_and_die();
466         daemon_drop_privileges_or_die(conf.user_arg, conf.group_arg);
467         /* parse config file, open log and set defaults */
468         parse_config_or_die(0);
469         daemon_log_welcome("server");
470         init_ipc_or_die(); /* init mmd struct and mmd->lock */
471         daemon_set_start_time();
472         init_user_list(user_list_file);
473         /* become daemon */
474         if (conf.daemon_given)
475                 daemonize(true /* parent waits for SIGTERM */);
476         PARA_NOTICE_LOG("initializing audio format handlers\n");
477         afh_init();
478
479         /*
480          * Although afs uses its own signal handling we must ignore SIGUSR1
481          * _before_ the afs child process gets born by init_afs() below.  It's
482          * racy to do this in the child because the parent might send SIGUSR1
483          * before the child gets a chance to ignore this signal -- only the
484          * good die young.
485          */
486         para_sigaction(SIGUSR1, SIG_IGN);
487         /*
488          * We have to block SIGCHLD before the afs process is being forked off.
489          * Otherwise, para_server does not notice if afs dies before the
490          * SIGCHLD handler has been installed for the parent process by
491          * init_signal_task() below.
492          */
493         para_block_signal(SIGCHLD);
494         PARA_NOTICE_LOG("initializing the audio file selector\n");
495         afs_socket = init_afs(argc, argv);
496         init_signal_task();
497         para_unblock_signal(SIGCHLD);
498         PARA_NOTICE_LOG("initializing virtual streaming system\n");
499         init_vss_task(afs_socket, &sched);
500         init_server_command_task(argc, argv);
501         if (conf.daemon_given)
502                 kill(getppid(), SIGTERM);
503         PARA_NOTICE_LOG("server init complete\n");
504 }
505
506 static void status_refresh(void)
507 {
508         static int prev_uptime = -1, prev_events = -1;
509         int uptime = daemon_get_uptime(now);
510
511         if (prev_events != mmd->events)
512                 goto out;
513         if (mmd->new_vss_status_flags != mmd->vss_status_flags)
514                 goto out_inc_events;
515         if (uptime / 60 != prev_uptime / 60)
516                 goto out_inc_events;
517         return;
518 out_inc_events:
519         mmd->events++;
520 out:
521         prev_uptime = uptime;
522         prev_events = mmd->events;
523         mmd->vss_status_flags = mmd->new_vss_status_flags;
524         PARA_DEBUG_LOG("%d events, forcing status update\n", mmd->events);
525         killpg(0, SIGUSR1);
526 }
527
528 static int server_select(int max_fileno, fd_set *readfds, fd_set *writefds,
529                 struct timeval *timeout_tv)
530 {
531         int ret;
532
533         status_refresh();
534         mutex_unlock(mmd_mutex);
535         ret = para_select(max_fileno + 1, readfds, writefds, timeout_tv);
536         mutex_lock(mmd_mutex);
537         return ret;
538 }
539
540 /**
541  * The main function of para_server.
542  *
543  * \param argc Usual argument count.
544  * \param argv Usual argument vector.
545  *
546  * \return EXIT_SUCCESS or EXIT_FAILURE.
547  */
548 int main(int argc, char *argv[])
549 {
550         int ret;
551
552         sched.default_timeout.tv_sec = 1;
553         sched.select_function = server_select;
554
555         server_init(argc, argv);
556         mutex_lock(mmd_mutex);
557         ret = schedule(&sched);
558         sched_shutdown(&sched);
559         if (ret < 0) {
560                 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
561                 exit(EXIT_FAILURE);
562         }
563         exit(EXIT_SUCCESS);
564 }