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