]> git.tuebingen.mpg.de Git - paraslash.git/blob - server.c
Merge topic branch t/sf_float into pu
[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 #include <netinet/in.h>
6 #include <sys/socket.h>
7 #include <signal.h>
8 #include <regex.h>
9 #include <osl.h>
10 #include <sys/types.h>
11 #include <arpa/inet.h>
12 #include <sys/un.h>
13 #include <netdb.h>
14 #include <lopsub.h>
15
16 #include "server.lsg.h"
17 #include "para.h"
18 #include "error.h"
19 #include "lsu.h"
20 #include "crypt.h"
21 #include "afh.h"
22 #include "string.h"
23 #include "afs.h"
24 #include "net.h"
25 #include "server.h"
26 #include "list.h"
27 #include "sched.h"
28 #include "send.h"
29 #include "vss.h"
30 #include "config.h"
31 #include "close_on_fork.h"
32 #include "daemon.h"
33 #include "ipc.h"
34 #include "fd.h"
35 #include "signal.h"
36 #include "user_list.h"
37 #include "color.h"
38 #include "version.h"
39
40 /** Array of error strings. */
41 DEFINE_PARA_ERRLIST;
42
43 __printf_2_3 void (*para_log)(int, const char*, ...) = daemon_log;
44
45 /** Shut down non-authorized connections after that many seconds. */
46 #define ALARM_TIMEOUT 10
47
48 /**
49  * Pointer to shared memory area for communication between para_server
50  * and its children. Exported to vss.c, command.c and to afs.
51  */
52 struct misc_meta_data *mmd;
53
54 /**
55  * The active value for all config options of para_server.
56  *
57  * It is computed by merging the parse result of the command line options with
58  * the parse result of the config file.
59  */
60 struct lls_parse_result *server_lpr = NULL;
61
62 /* Command line options (no config file options). Used in handle_sighup(). */
63 static struct lls_parse_result *cmdline_lpr;
64
65 /**
66  * A random number used to "authenticate" the afs connection.
67  *
68  * para_server picks this number by random before it forks the afs process. The
69  * command handlers know this number as well and write it to the afs socket,
70  * together with the id of the shared memory area which contains the payload of
71  * the afs command. A local process has to know this number to abuse the afs
72  * service provided by the local socket.
73  */
74 uint32_t afs_socket_cookie;
75
76 /** The mutex protecting the shared memory area containing the mmd struct. */
77 int mmd_mutex;
78
79 /* Serializes log output. */
80 static int log_mutex;
81
82 static struct sched sched;
83 static struct signal_task *signal_task;
84
85 /** The process id of the audio file selector process. */
86 pid_t afs_pid = 0;
87
88 /* The main server process (parent of afs and the command handlers). */
89 static pid_t server_pid;
90
91 /**
92  * Tell whether the executing process is a command handler.
93  *
94  * Cleanup on exit must be performed differently for command handlers.
95  *
96  * \return True if the pid of the executing process is neither the server pid
97  * nor the afs pid.
98  */
99 bool process_is_command_handler(void)
100 {
101         pid_t pid = getpid();
102
103         return pid != afs_pid && pid != server_pid;
104 }
105
106 /** The task responsible for server command handling. */
107 struct server_command_task {
108         unsigned num_listen_fds; /* only one by default */
109         /** TCP socket(s) on which para_server listens for connections. */
110         int *listen_fds;
111         /* File descriptor for the accepted socket. */
112         int child_fd;
113         /** Copied from para_server's main function. */
114         int argc;
115         /** Argument vector passed to para_server's main function. */
116         char **argv;
117         /** The command task structure for scheduling. */
118         struct task *task;
119 };
120
121 /**
122  * Return the list of tasks for the server process.
123  *
124  * This is called from \a com_tasks(). The helper is necessary since command
125  * handlers can not access the scheduler structure directly.
126  *
127  * \return A dynamically allocated string that must be freed by the caller.
128  */
129 char *server_get_tasks(void)
130 {
131         return get_task_list(&sched);
132 }
133
134 static void pre_log_hook(void)
135 {
136         mutex_lock(log_mutex);
137 }
138
139 static void post_log_hook(void)
140 {
141         mutex_unlock(log_mutex);
142 }
143
144 /* Setup shared memory area and init mutexes */
145 static void init_ipc_or_die(void)
146 {
147         void *shm;
148         int shmid, ret = shm_new(sizeof(struct misc_meta_data));
149
150         if (ret < 0)
151                 goto err_out;
152         shmid = ret;
153         ret = shm_attach(shmid, ATTACH_RW, &shm);
154         shm_destroy(shmid);
155         if (ret < 0)
156                 goto err_out;
157         mmd = shm;
158
159         ret = mutex_new();
160         if (ret < 0)
161                 goto err_out;
162         mmd_mutex = ret;
163         ret = mutex_new();
164         if (ret < 0)
165                 goto destroy_mmd_mutex;
166         log_mutex = ret;
167
168         mmd->num_played = 0;
169         mmd->num_commands = 0;
170         mmd->events = 0;
171         mmd->num_connects = 0;
172         mmd->active_connections = 0;
173         mmd->vss_status_flags = VSS_NEXT;
174         mmd->new_vss_status_flags = VSS_NEXT;
175         mmd->loglevel = OPT_UINT32_VAL(LOGLEVEL);
176         return;
177 destroy_mmd_mutex:
178         mutex_destroy(mmd_mutex);
179 err_out:
180         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
181         exit(EXIT_FAILURE);
182 }
183
184 /** Get a reference to the supercommand of para_server. */
185 #define CMD_PTR (lls_cmd(0, server_suite))
186
187 /**
188  * (Re-)read the server configuration files.
189  *
190  * \param reload Whether config file overrides command line.
191  *
192  * This function also re-opens the logfile and the user list. On SIGHUP it is
193  * called from both server and afs context.
194  */
195 void parse_config_or_die(bool reload)
196 {
197         int ret;
198         unsigned flags = MCF_DONT_FREE;
199
200         if (server_lpr != cmdline_lpr)
201                 lls_free_parse_result(server_lpr, CMD_PTR);
202         server_lpr = cmdline_lpr;
203         if (reload)
204                 flags |= MCF_OVERRIDE;
205         ret = lsu_merge_config_file_options(OPT_STRING_VAL(CONFIG_FILE),
206                 "server.conf", &server_lpr, CMD_PTR, server_suite, flags);
207         if (ret < 0) {
208                 PARA_EMERG_LOG("failed to parse config file: %s\n",
209                         para_strerror(-ret));
210                 exit(EXIT_FAILURE);
211         }
212         daemon_set_loglevel(OPT_UINT32_VAL(LOGLEVEL));
213         if (OPT_GIVEN(LOGFILE)) {
214                 daemon_set_logfile(OPT_STRING_VAL(LOGFILE));
215                 daemon_open_log_or_die();
216         }
217         if (daemon_init_colors_or_die(OPT_UINT32_VAL(COLOR), COLOR_AUTO,
218                         COLOR_NO, OPT_GIVEN(LOGFILE))) {
219                 int i;
220                 for (i = 0; i < OPT_GIVEN(LOG_COLOR); i++)
221                         daemon_set_log_color_or_die(lls_string_val(i,
222                                 OPT_RESULT(LOG_COLOR)));
223         }
224         daemon_set_flag(DF_LOG_PID);
225         daemon_set_flag(DF_LOG_LL);
226         daemon_set_flag(DF_LOG_TIME);
227         if (OPT_GIVEN(LOG_TIMING))
228                 daemon_set_flag(DF_LOG_TIMING);
229         daemon_set_priority(OPT_UINT32_VAL(PRIORITY));
230         if (!reload || getpid() != afs_pid) {
231                 char *user_list_file = OPT_GIVEN(USER_LIST)?
232                         para_strdup(OPT_STRING_VAL(USER_LIST)) :
233                         make_message("%s/server.users", get_confdir());
234                 user_list_init(user_list_file);
235                 free(user_list_file);
236         }
237 }
238
239 /*
240  * called when server gets SIGHUP or when client invokes hup command.
241  */
242 static void handle_sighup(void)
243 {
244
245         PARA_NOTICE_LOG("SIGHUP\n");
246         parse_config_or_die(true);
247         if (afs_pid != 0)
248                 kill(afs_pid, SIGHUP);
249 }
250
251 static int signal_post_monitor(struct sched *s, __a_unused void *context)
252 {
253         int ret, signum;
254
255         ret = task_get_notification(signal_task->task);
256         if (ret < 0)
257                 return ret;
258         signum = para_next_signal();
259         switch (signum) {
260         case 0:
261                 return 0;
262         case SIGHUP:
263                 handle_sighup();
264                 break;
265         case SIGCHLD:
266                 for (;;) {
267                         pid_t pid;
268                         ret = para_reap_child(&pid);
269                         if (ret <= 0)
270                                 break;
271                         if (pid != afs_pid)
272                                 continue;
273                         PARA_EMERG_LOG("fatal: afs died\n");
274                         goto genocide;
275                 }
276                 break;
277         /* die on sigint/sigterm. Kill all children too. */
278         case SIGINT:
279         case SIGTERM:
280                 PARA_EMERG_LOG("terminating on signal %d\n", signum);
281 genocide:
282                 kill(0, SIGTERM);
283                 /*
284                  * We must wait for all of our children to die. For the afs
285                  * process or a command handler might want to use the
286                  * shared memory area and the mmd mutex.  If we destroy this
287                  * mutex too early and afs tries to lock the shared memory
288                  * area, the call to mutex_lock() will fail and terminate the
289                  * afs process. This leads to dirty osl tables.
290                  */
291                 PARA_INFO_LOG("waiting for child processes to die\n");
292                 mutex_unlock(mmd_mutex);
293                 while (wait(NULL) != -1 || errno != ECHILD)
294                         ; /* still at least one child alive */
295                 mutex_lock(mmd_mutex);
296                 free(mmd->afd.afhi.chunk_table);
297                 task_notify_all(s, E_DEADLY_SIGNAL);
298                 return -E_DEADLY_SIGNAL;
299         }
300         return 0;
301 }
302
303 static void init_signal_task(void)
304 {
305         signal_task = signal_init_or_die();
306         para_install_sighandler(SIGINT);
307         para_install_sighandler(SIGTERM);
308         para_install_sighandler(SIGHUP);
309         para_install_sighandler(SIGCHLD);
310         para_sigaction(SIGPIPE, SIG_IGN);
311         add_close_on_fork_list(signal_task->fd);
312         signal_task->task = task_register(&(struct task_info) {
313                 .name = "signal",
314                 .pre_monitor = signal_pre_monitor,
315                 .post_monitor = signal_post_monitor,
316                 .context = signal_task,
317
318         }, &sched);
319 }
320
321 static void command_pre_monitor(struct sched *s, void *context)
322 {
323         unsigned n;
324         struct server_command_task *sct = context;
325
326         for (n = 0; n < sct->num_listen_fds; n++)
327                 sched_monitor_readfd(sct->listen_fds[n], s);
328 }
329
330 static int command_task_accept(unsigned listen_idx, struct sched *s,
331                 struct server_command_task *sct)
332 {
333         int new_fd, ret, i;
334         char *peer_name;
335         pid_t child_pid;
336         uint32_t *chunk_table;
337
338         ret = para_accept(sct->listen_fds[listen_idx], NULL, 0, &new_fd);
339         if (ret <= 0)
340                 goto out;
341         mmd->num_connects++;
342         mmd->active_connections++;
343         /*
344          * The chunk table is a pointer located in the mmd struct that points
345          * to dynamically allocated memory, i.e. it must be freed by the parent
346          * and the child. However, as the mmd struct is in a shared memory
347          * area, there's no guarantee that after the fork this pointer is still
348          * valid in child context. As it is not used in the child anyway, we
349          * save it to a local variable before the fork and free the memory via
350          * that copy in the child directly after the fork.
351          */
352         chunk_table = mmd->afd.afhi.chunk_table;
353         child_pid = fork();
354         if (child_pid < 0) {
355                 ret = -ERRNO_TO_PARA_ERROR(errno);
356                 goto out;
357         }
358         if (child_pid) {
359                 /* avoid problems with non-fork-safe PRNGs */
360                 unsigned char buf[16];
361                 get_random_bytes_or_die(buf, sizeof(buf));
362                 close(new_fd);
363                 /* parent keeps accepting connections */
364                 return 0;
365         }
366         peer_name = remote_name(new_fd);
367         PARA_INFO_LOG("accepted connection from %s\n", peer_name);
368         /* mmd might already have changed at this point */
369         free(chunk_table);
370         sct->child_fd = new_fd;
371         /*
372          * put info on who we are serving into argv[0] to make
373          * client ip visible in top/ps
374          */
375         for (i = sct->argc - 1; i >= 0; i--)
376                 memset(sct->argv[i], 0, strlen(sct->argv[i]));
377         i = sct->argc - 1 - lls_num_inputs(cmdline_lpr);
378         sprintf(sct->argv[i], "para_server (serving %s)", peer_name);
379         /* ask other tasks to terminate */
380         task_notify_all(s, E_CHILD_CONTEXT);
381         /*
382          * After we return, the scheduler calls server_select() with a minimal
383          * timeout value, because the remaining tasks have a notification
384          * pending. Next it calls the ->post_monitor method of these tasks,
385          * which will return negative in view of the notification. This causes
386          * schedule() to return as there are no more runnable tasks.
387          *
388          * Note that semaphores are not inherited across a fork(), so we don't
389          * hold the lock at this point. Since server_poll() drops the lock
390          * prior to calling poll(), we need to acquire it here.
391          */
392         mutex_lock(mmd_mutex);
393         return -E_CHILD_CONTEXT;
394 out:
395         if (ret < 0)
396                 PARA_CRIT_LOG("%s\n", para_strerror(-ret));
397         return 0;
398 }
399
400 static int command_post_monitor(struct sched *s, void *context)
401 {
402         struct server_command_task *sct = context;
403         unsigned n;
404         int ret;
405
406         ret = task_get_notification(sct->task);
407         if (ret < 0)
408                 goto fail;
409         for (n = 0; n < sct->num_listen_fds; n++) {
410                 ret = command_task_accept(n, s, sct);
411                 if (ret < 0)
412                         goto fail;
413         }
414         return 0;
415 fail:
416         free(sct->listen_fds);
417         return ret;
418 }
419
420 static void init_server_command_task(struct server_command_task *sct,
421                 int argc, char **argv)
422 {
423         int ret;
424         unsigned n;
425         uint32_t port = OPT_UINT32_VAL(PORT);
426
427         PARA_NOTICE_LOG("initializing tcp command socket\n");
428         sct->child_fd = -1;
429         sct->argc = argc;
430         sct->argv = argv;
431         if (!OPT_GIVEN(LISTEN_ADDRESS)) {
432                 sct->num_listen_fds = 1;
433                 sct->listen_fds = alloc(sizeof(int));
434                 ret = para_listen_simple(IPPROTO_TCP, port);
435                 if (ret < 0)
436                         goto err;
437                 sct->listen_fds[0] = ret;
438         } else {
439                 sct->num_listen_fds = OPT_GIVEN(LISTEN_ADDRESS);
440                 sct->listen_fds = alloc(sct->num_listen_fds * sizeof(int));
441                 for (n = 0; n < OPT_GIVEN(LISTEN_ADDRESS); n++) {
442                         const char *arg;
443                         arg = lls_string_val(n, OPT_RESULT(LISTEN_ADDRESS));
444                         ret = para_listen(IPPROTO_TCP, arg, port);
445                         if (ret < 0)
446                                 goto err;
447                         sct->listen_fds[n] = ret;
448                 }
449         }
450         for (n = 0; n < sct->num_listen_fds; n++) {
451                 ret = mark_fd_nonblocking(sct->listen_fds[n]);
452                 if (ret < 0)
453                         goto err;
454                 /* child doesn't need the listener */
455                 add_close_on_fork_list(sct->listen_fds[n]);
456         }
457
458         sct->task = task_register(&(struct task_info) {
459                 .name = "server command",
460                 .pre_monitor = command_pre_monitor,
461                 .post_monitor = command_post_monitor,
462                 .context = sct,
463         }, &sched);
464         /*
465          * Detect whether the abstract Unix domain socket space is supported,
466          * but do not create the socket. We check this once in server context
467          * so that the command handlers inherit this bit of information and
468          * don't need to check again.
469          */
470         create_local_socket(NULL);
471         return;
472 err:
473         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
474         exit(EXIT_FAILURE);
475 }
476
477 static int init_afs(int argc, char **argv)
478 {
479         int ret, afs_server_socket[2];
480         char c;
481
482         ret = socketpair(PF_UNIX, SOCK_STREAM, 0, afs_server_socket);
483         if (ret < 0)
484                 exit(EXIT_FAILURE);
485         get_random_bytes_or_die((unsigned char *)&afs_socket_cookie,
486                 sizeof(afs_socket_cookie));
487         afs_pid = fork();
488         if (afs_pid < 0)
489                 exit(EXIT_FAILURE);
490         if (afs_pid == 0) { /* child (afs) */
491                 int i;
492
493                 afs_pid = getpid();
494                 crypt_shutdown();
495                 user_list_deplete();
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(OPT_UINT32_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         crypt_init();
555         daemon_log_welcome("server");
556         init_ipc_or_die(); /* init mmd struct, mmd and log mutex */
557         daemon_set_start_time();
558         daemon_set_hooks(pre_log_hook, post_log_hook);
559         /*
560          * Although afs uses its own signal handling we must ignore SIGUSR1
561          * _before_ the afs child process gets born by init_afs() below.  It's
562          * racy to do this in the child because the parent might send SIGUSR1
563          * before the child gets a chance to ignore this signal.
564          *
565          * We also have to block SIGCHLD before the afs process is created
566          * because otherwise para_server does not notice if afs dies before the
567          * SIGCHLD handler has been installed for the parent process by
568          * init_signal_task() below.
569          */
570         para_sigaction(SIGUSR1, SIG_IGN);
571         para_block_signal(SIGCHLD);
572         PARA_NOTICE_LOG("initializing the audio file selector\n");
573         afs_socket = init_afs(argc, argv);
574         init_signal_task();
575         para_unblock_signal(SIGCHLD);
576         PARA_NOTICE_LOG("initializing virtual streaming system\n");
577         vss_init(afs_socket, &sched);
578         init_server_command_task(sct, argc, argv);
579         if (daemon_pipe >= 0) {
580                 if (write(daemon_pipe, "\0", 1) < 0) {
581                         PARA_EMERG_LOG("daemon_pipe: %s", strerror(errno));
582                         exit(EXIT_FAILURE);
583                 }
584                 close(daemon_pipe);
585         }
586         PARA_NOTICE_LOG("server init complete\n");
587         return;
588 fail:
589         assert(ret < 0);
590         if (errctx)
591                 PARA_ERROR_LOG("%s\n", errctx);
592         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
593         exit(EXIT_FAILURE);
594 }
595
596 static void status_refresh(void)
597 {
598         static int prev_uptime = -1, prev_events = -1;
599         int uptime = daemon_get_uptime(now);
600
601         if (prev_events != mmd->events)
602                 goto out;
603         if (mmd->new_vss_status_flags != mmd->vss_status_flags)
604                 goto out_inc_events;
605         if (uptime / 60 != prev_uptime / 60)
606                 goto out_inc_events;
607         return;
608 out_inc_events:
609         mmd->events++;
610 out:
611         prev_uptime = uptime;
612         prev_events = mmd->events;
613         mmd->vss_status_flags = mmd->new_vss_status_flags;
614         PARA_DEBUG_LOG("%u events, forcing status update\n", mmd->events);
615         killpg(0, SIGUSR1);
616 }
617
618 static int server_poll(struct pollfd *fds, nfds_t nfds, int timeout)
619 {
620         int ret;
621
622         daemon_set_loglevel(mmd->loglevel);
623         status_refresh();
624         mutex_unlock(mmd_mutex);
625         ret = xpoll(fds, nfds, timeout);
626         mutex_lock(mmd_mutex);
627         return ret;
628 }
629
630 /**
631  * Deallocate all lopsub parse results.
632  *
633  * The server allocates a parse result for command line options and optionally
634  * a second parse result for the effective configuration, defined by merging
635  * the command line options with the options stored in the configuration file.
636  * This function frees both structures.
637  */
638 void free_lpr(void)
639 {
640         lls_free_parse_result(server_lpr, CMD_PTR);
641         if (server_lpr != cmdline_lpr)
642                 lls_free_parse_result(cmdline_lpr, CMD_PTR);
643 }
644
645 /**
646  * The main function of para_server.
647  *
648  * \param argc Usual argument count.
649  * \param argv Usual argument vector.
650  *
651  * \return EXIT_SUCCESS or EXIT_FAILURE.
652  */
653 int main(int argc, char *argv[])
654 {
655         int ret;
656         struct server_command_task server_command_task_struct,
657                 *sct = &server_command_task_struct;
658
659         sched.default_timeout = 1000;
660         sched.poll_function = server_poll;
661
662         server_init(argc, argv, sct);
663         mutex_lock(mmd_mutex);
664         ret = schedule(&sched);
665         /*
666          * We hold the mmd lock: it was re-acquired in server_poll()
667          * after the poll(2) call.
668          */
669         mutex_unlock(mmd_mutex);
670         sched_shutdown(&sched);
671         crypt_shutdown();
672         signal_shutdown(signal_task);
673         if (!process_is_command_handler()) { /* parent (server) */
674                 mutex_destroy(mmd_mutex);
675                 daemon_set_hooks(NULL, NULL); /* only one process remaining */
676                 mutex_destroy(log_mutex);
677                 deplete_close_on_fork_list();
678                 if (ret < 0)
679                         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
680                 vss_shutdown();
681         } else {
682                 vss_shutdown();
683                 alarm(ALARM_TIMEOUT);
684                 close_listed_fds();
685                 ret = handle_connect(sct->child_fd);
686         }
687         shm_detach(mmd);
688         user_list_deplete();
689         free_lpr();
690         exit(ret < 0? EXIT_FAILURE : EXIT_SUCCESS);
691 }