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