afs: Use correct error code for com_select().
[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,
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 #include <lopsub.h>
44
45 #include "server.lsg.h"
46 #include "para.h"
47 #include "error.h"
48 #include "crypt.h"
49 #include "afh.h"
50 #include "string.h"
51 #include "afs.h"
52 #include "server.h"
53 #include "list.h"
54 #include "send.h"
55 #include "sched.h"
56 #include "vss.h"
57 #include "config.h"
58 #include "close_on_fork.h"
59 #include "net.h"
60 #include "daemon.h"
61 #include "ipc.h"
62 #include "fd.h"
63 #include "signal.h"
64 #include "user_list.h"
65 #include "color.h"
66 #include "version.h"
67
68 /** Array of error strings. */
69 DEFINE_PARA_ERRLIST;
70
71 __printf_2_3 void (*para_log)(int, const char*, ...) = daemon_log;
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 active value for all config options of para_server.
84  *
85  * It is computed by merging the parse result of the command line options with
86  * the parse result of the config file.
87  */
88 struct lls_parse_result *server_lpr = NULL;
89
90 /* Command line options (no config file options). Used in handle_sighup(). */
91 static struct lls_parse_result *cmdline_lpr;
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 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 reload Whether config file overrides command line.
166  *
167  * This function also re-opens the logfile and the user list. On SIGHUP it is
168  * called from both server and afs context.
169  */
170 void parse_config_or_die(bool reload)
171 {
172         int ret;
173         char *cf = NULL, *errctx = NULL, *user_list_file = NULL;
174         void *map;
175         size_t sz;
176         int cf_argc;
177         char **cf_argv;
178         struct lls_parse_result *cf_lpr, *merged_lpr;
179         char *home = para_homedir();
180
181         daemon_close_log();
182         if (OPT_GIVEN(CONFIG_FILE))
183                 cf = para_strdup(OPT_STRING_VAL(CONFIG_FILE));
184         else
185                 cf = make_message("%s/.paraslash/server.conf", home);
186         if (!mmd || getpid() != mmd->afs_pid) {
187                 if (OPT_GIVEN(USER_LIST))
188                         user_list_file = para_strdup(OPT_STRING_VAL(USER_LIST));
189                 else
190                         user_list_file = make_message("%s/.paraslash/server.users", home);
191         }
192         free(home);
193         ret = mmap_full_file(cf, O_RDONLY, &map, &sz, NULL);
194         if (ret < 0) {
195                 if (ret != -E_EMPTY && ret != -ERRNO_TO_PARA_ERROR(ENOENT))
196                         goto free_cf;
197                 if (ret == -ERRNO_TO_PARA_ERROR(ENOENT) && OPT_GIVEN(CONFIG_FILE))
198                         goto free_cf;
199                 server_lpr = cmdline_lpr;
200                 goto success;
201         }
202         ret = lls(lls_convert_config(map, sz, NULL, &cf_argv, &errctx));
203         para_munmap(map, sz);
204         if (ret < 0)
205                 goto free_cf;
206         cf_argc = ret;
207         ret = lls(lls_parse(cf_argc, cf_argv, CMD_PTR, &cf_lpr, &errctx));
208         lls_free_argv(cf_argv);
209         if (ret < 0)
210                 goto free_cf;
211         if (reload) /* config file overrides command line */
212                 ret = lls(lls_merge(cf_lpr, cmdline_lpr, CMD_PTR, &merged_lpr,
213                         &errctx));
214         else /* command line options overrride config file options */
215                 ret = lls(lls_merge(cmdline_lpr, cf_lpr, CMD_PTR, &merged_lpr,
216                         &errctx));
217         lls_free_parse_result(cf_lpr, CMD_PTR);
218         if (ret < 0)
219                 goto free_cf;
220         if (server_lpr != cmdline_lpr)
221                 lls_free_parse_result(server_lpr, CMD_PTR);
222         server_lpr = merged_lpr;
223 success:
224         daemon_set_loglevel(ENUM_STRING_VAL(LOGLEVEL));
225         if (OPT_GIVEN(LOGFILE)) {
226                 daemon_set_logfile(OPT_STRING_VAL(LOGFILE));
227                 daemon_open_log_or_die();
228         }
229         if (daemon_init_colors_or_die(OPT_UINT32_VAL(COLOR), COLOR_AUTO,
230                         COLOR_NO, OPT_GIVEN(LOGFILE))) {
231                 int i;
232                 for (i = 0; i < OPT_GIVEN(LOG_COLOR); i++)
233                         daemon_set_log_color_or_die(lls_string_val(i,
234                                 OPT_RESULT(LOG_COLOR)));
235         }
236         daemon_set_flag(DF_LOG_PID);
237         daemon_set_flag(DF_LOG_LL);
238         daemon_set_flag(DF_LOG_TIME);
239         if (OPT_GIVEN(LOG_TIMING))
240                 daemon_set_flag(DF_LOG_TIMING);
241         daemon_set_priority(OPT_UINT32_VAL(PRIORITY));
242         if (user_list_file)
243                 init_user_list(user_list_file);
244         ret = 1;
245 free_cf:
246         free(cf);
247         free(user_list_file);
248         if (ret < 0) {
249                 if (errctx)
250                         PARA_ERROR_LOG("%s\n", errctx);
251                 free(errctx);
252                 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
253                 exit(EXIT_FAILURE);
254         }
255 }
256
257 /*
258  * called when server gets SIGHUP or when client invokes hup command.
259  */
260 static void handle_sighup(void)
261 {
262
263         PARA_NOTICE_LOG("SIGHUP\n");
264         parse_config_or_die(true);
265         if (mmd->afs_pid)
266                 kill(mmd->afs_pid, SIGHUP);
267 }
268
269 static int signal_post_select(struct sched *s, __a_unused void *context)
270 {
271         int signum = para_next_signal(&s->rfds);
272
273         switch (signum) {
274         case 0:
275                 return 0;
276         case SIGHUP:
277                 handle_sighup();
278                 break;
279         case SIGCHLD:
280                 for (;;) {
281                         pid_t pid;
282                         int ret = para_reap_child(&pid);
283                         if (ret <= 0)
284                                 break;
285                         if (pid != mmd->afs_pid)
286                                 continue;
287                         PARA_EMERG_LOG("fatal: afs died\n");
288                         kill(0, SIGTERM);
289                         goto cleanup;
290                 }
291                 break;
292         /* die on sigint/sigterm. Kill all children too. */
293         case SIGINT:
294         case SIGTERM:
295                 PARA_EMERG_LOG("terminating on signal %d\n", signum);
296                 kill(0, SIGTERM);
297                 /*
298                  * We must wait for afs because afs catches SIGINT/SIGTERM.
299                  * Before reacting to the signal, afs might want to use the
300                  * shared memory area and the mmd mutex.  If we destroy this
301                  * mutex too early and afs tries to lock the shared memory
302                  * area, the call to mutex_lock() will fail and terminate the
303                  * afs process. This leads to dirty osl tables.
304                  *
305                  * There's no such problem with the other children of the
306                  * server process (the command handlers) as these reset their
307                  * SIGINT/SIGTERM handlers to the default action, i.e.  these
308                  * processes get killed immediately by the above kill().
309                  */
310                 PARA_INFO_LOG("waiting for afs (pid %d) to die\n",
311                         (int)mmd->afs_pid);
312                 waitpid(mmd->afs_pid, NULL, 0);
313 cleanup:
314                 free(mmd->afd.afhi.chunk_table);
315                 close_listed_fds();
316                 mutex_destroy(mmd_mutex);
317                 shm_detach(mmd);
318                 exit(EXIT_FAILURE);
319         }
320         return 0;
321 }
322
323 static void init_signal_task(void)
324 {
325         signal_task = signal_init_or_die();
326         para_install_sighandler(SIGINT);
327         para_install_sighandler(SIGTERM);
328         para_install_sighandler(SIGHUP);
329         para_install_sighandler(SIGCHLD);
330         para_sigaction(SIGPIPE, SIG_IGN);
331         add_close_on_fork_list(signal_task->fd);
332         signal_task->task = task_register(&(struct task_info) {
333                 .name = "signal",
334                 .pre_select = signal_pre_select,
335                 .post_select = signal_post_select,
336                 .context = signal_task,
337
338         }, &sched);
339 }
340
341 static void command_pre_select(struct sched *s, void *context)
342 {
343         struct server_command_task *sct = context;
344         para_fd_set(sct->listen_fd, &s->rfds, &s->max_fileno);
345 }
346
347 static int command_post_select(struct sched *s, void *context)
348 {
349         struct server_command_task *sct = context;
350
351         int new_fd, ret, i;
352         char *peer_name;
353         pid_t child_pid;
354         uint32_t *chunk_table;
355
356         ret = para_accept(sct->listen_fd, &s->rfds, NULL, 0, &new_fd);
357         if (ret <= 0)
358                 goto out;
359         mmd->num_connects++;
360         mmd->active_connections++;
361         /*
362          * The chunk table is a pointer located in the mmd struct that points
363          * to dynamically allocated memory, i.e. it must be freed by the parent
364          * and the child. However, as the mmd struct is in a shared memory
365          * area, there's no guarantee that after the fork this pointer is still
366          * valid in child context. As it is not used in the child anyway, we
367          * save it to a local variable before the fork and free the memory via
368          * that copy in the child directly after the fork.
369          */
370         chunk_table = mmd->afd.afhi.chunk_table;
371         child_pid = fork();
372         if (child_pid < 0) {
373                 ret = -ERRNO_TO_PARA_ERROR(errno);
374                 goto out;
375         }
376         if (child_pid) {
377                 /* avoid problems with non-fork-safe PRNGs */
378                 unsigned char buf[16];
379                 get_random_bytes_or_die(buf, sizeof(buf));
380                 close(new_fd);
381                 /* parent keeps accepting connections */
382                 return 0;
383         }
384         peer_name = remote_name(new_fd);
385         PARA_INFO_LOG("accepted connection from %s\n", peer_name);
386         /* mmd might already have changed at this point */
387         free(chunk_table);
388         alarm(ALARM_TIMEOUT);
389         close_listed_fds();
390         signal_shutdown(signal_task);
391         /*
392          * put info on who we are serving into argv[0] to make
393          * client ip visible in top/ps
394          */
395         for (i = sct->argc - 1; i >= 0; i--)
396                 memset(sct->argv[i], 0, strlen(sct->argv[i]));
397         i = sct->argc - 1 - lls_num_inputs(cmdline_lpr);
398         sprintf(sct->argv[i], "para_server (serving %s)", peer_name);
399         handle_connect(new_fd, peer_name);
400         /* never reached*/
401 out:
402         if (ret < 0)
403                 PARA_CRIT_LOG("%s\n", para_strerror(-ret));
404         return 0;
405 }
406
407 static void init_server_command_task(int argc, char **argv)
408 {
409         int ret;
410         static struct server_command_task server_command_task_struct,
411                 *sct = &server_command_task_struct;
412
413         PARA_NOTICE_LOG("initializing tcp command socket\n");
414         sct->argc = argc;
415         sct->argv = argv;
416         ret = para_listen_simple(IPPROTO_TCP, OPT_UINT32_VAL(PORT));
417         if (ret < 0)
418                 goto err;
419         sct->listen_fd = ret;
420         ret = mark_fd_nonblocking(sct->listen_fd);
421         if (ret < 0)
422                 goto err;
423         add_close_on_fork_list(sct->listen_fd); /* child doesn't need the listener */
424         sct->task = task_register(&(struct task_info) {
425                 .name = "server command",
426                 .pre_select = command_pre_select,
427                 .post_select = command_post_select,
428                 .context = sct,
429         }, &sched);
430         return;
431 err:
432         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
433         exit(EXIT_FAILURE);
434 }
435
436 static int init_afs(int argc, char **argv)
437 {
438         int ret, afs_server_socket[2];
439         pid_t afs_pid;
440         char c;
441
442         ret = socketpair(PF_UNIX, SOCK_STREAM, 0, afs_server_socket);
443         if (ret < 0)
444                 exit(EXIT_FAILURE);
445         get_random_bytes_or_die((unsigned char *)&afs_socket_cookie,
446                 sizeof(afs_socket_cookie));
447         afs_pid = fork();
448         if (afs_pid < 0)
449                 exit(EXIT_FAILURE);
450         if (afs_pid == 0) { /* child (afs) */
451                 int i;
452
453                 for (i = argc - 1; i >= 0; i--)
454                         memset(argv[i], 0, strlen(argv[i]));
455                 i = argc - lls_num_inputs(cmdline_lpr) - 1;
456                 sprintf(argv[i], "para_server (afs)");
457                 close(afs_server_socket[0]);
458                 afs_init(afs_socket_cookie, afs_server_socket[1]);
459         }
460         mmd->afs_pid = afs_pid;
461         close(afs_server_socket[1]);
462         if (read(afs_server_socket[0], &c, 1) <= 0) {
463                 PARA_EMERG_LOG("early afs exit\n");
464                 exit(EXIT_FAILURE);
465         }
466         ret = mark_fd_nonblocking(afs_server_socket[0]);
467         if (ret < 0)
468                 exit(EXIT_FAILURE);
469         add_close_on_fork_list(afs_server_socket[0]);
470         PARA_INFO_LOG("afs_socket: %d, afs_socket_cookie: %u\n",
471                 afs_server_socket[0], (unsigned) afs_socket_cookie);
472         return afs_server_socket[0];
473 }
474
475 static void handle_help_flags(void)
476 {
477         char *help;
478         bool d = OPT_GIVEN(DETAILED_HELP);
479
480         if (d)
481                 help = lls_long_help(CMD_PTR);
482         else if (OPT_GIVEN(HELP))
483                 help = lls_short_help(CMD_PTR);
484         else
485                 return;
486         printf("%s\n", help);
487         free(help);
488         exit(EXIT_SUCCESS);
489 }
490
491 static void server_init(int argc, char **argv)
492 {
493         int ret, afs_socket, daemon_pipe = -1;
494         char *errctx;
495
496         valid_fd_012();
497         /* parse command line options */
498         ret = lls(lls_parse(argc, argv, CMD_PTR, &cmdline_lpr, &errctx));
499         if (ret < 0)
500                 goto fail;
501         server_lpr = cmdline_lpr;
502         daemon_set_loglevel(ENUM_STRING_VAL(LOGLEVEL));
503         daemon_drop_privileges_or_die(OPT_STRING_VAL(USER),
504                 OPT_STRING_VAL(GROUP));
505         version_handle_flag("server", OPT_GIVEN(VERSION));
506         handle_help_flags();
507         parse_config_or_die(false);
508         /* become daemon */
509         if (OPT_GIVEN(DAEMON))
510                 daemon_pipe = daemonize(true /* parent waits for SIGTERM */);
511         init_random_seed_or_die();
512         daemon_log_welcome("server");
513         init_ipc_or_die(); /* init mmd struct and mmd->lock */
514         daemon_set_start_time();
515         PARA_NOTICE_LOG("initializing audio format handlers\n");
516         afh_init();
517
518         /*
519          * Although afs uses its own signal handling we must ignore SIGUSR1
520          * _before_ the afs child process gets born by init_afs() below.  It's
521          * racy to do this in the child because the parent might send SIGUSR1
522          * before the child gets a chance to ignore this signal.
523          *
524          * We also have to block SIGCHLD before the afs process is created
525          * because otherwise para_server does not notice if afs dies before the
526          * SIGCHLD handler has been installed for the parent process by
527          * init_signal_task() below.
528          */
529         para_sigaction(SIGUSR1, SIG_IGN);
530         para_block_signal(SIGCHLD);
531         PARA_NOTICE_LOG("initializing the audio file selector\n");
532         afs_socket = init_afs(argc, argv);
533         init_signal_task();
534         para_unblock_signal(SIGCHLD);
535         PARA_NOTICE_LOG("initializing virtual streaming system\n");
536         vss_init(afs_socket, &sched);
537         init_server_command_task(argc, argv);
538         if (daemon_pipe >= 0) {
539                 if (write(daemon_pipe, "\0", 1) < 0) {
540                         PARA_EMERG_LOG("daemon_pipe: %s", strerror(errno));
541                         exit(EXIT_FAILURE);
542                 }
543                 close(daemon_pipe);
544         }
545         PARA_NOTICE_LOG("server init complete\n");
546         return;
547 fail:
548         assert(ret < 0);
549         if (errctx)
550                 PARA_ERROR_LOG("%s\n", errctx);
551         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
552         exit(EXIT_FAILURE);
553 }
554
555 static void status_refresh(void)
556 {
557         static int prev_uptime = -1, prev_events = -1;
558         int uptime = daemon_get_uptime(now);
559
560         if (prev_events != mmd->events)
561                 goto out;
562         if (mmd->new_vss_status_flags != mmd->vss_status_flags)
563                 goto out_inc_events;
564         if (uptime / 60 != prev_uptime / 60)
565                 goto out_inc_events;
566         return;
567 out_inc_events:
568         mmd->events++;
569 out:
570         prev_uptime = uptime;
571         prev_events = mmd->events;
572         mmd->vss_status_flags = mmd->new_vss_status_flags;
573         PARA_DEBUG_LOG("%u events, forcing status update\n", mmd->events);
574         killpg(0, SIGUSR1);
575 }
576
577 static int server_select(int max_fileno, fd_set *readfds, fd_set *writefds,
578                 struct timeval *timeout_tv)
579 {
580         int ret;
581
582         status_refresh();
583         mutex_unlock(mmd_mutex);
584         ret = para_select(max_fileno + 1, readfds, writefds, timeout_tv);
585         mutex_lock(mmd_mutex);
586         return ret;
587 }
588
589 /**
590  * The main function of para_server.
591  *
592  * \param argc Usual argument count.
593  * \param argv Usual argument vector.
594  *
595  * \return EXIT_SUCCESS or EXIT_FAILURE.
596  */
597 int main(int argc, char *argv[])
598 {
599         int ret;
600
601         sched.default_timeout.tv_sec = 1;
602         sched.select_function = server_select;
603
604         server_init(argc, argv);
605         mutex_lock(mmd_mutex);
606         ret = schedule(&sched);
607         sched_shutdown(&sched);
608         lls_free_parse_result(server_lpr, CMD_PTR);
609         if (server_lpr != cmdline_lpr)
610                 lls_free_parse_result(cmdline_lpr, CMD_PTR);
611         if (ret < 0)
612                 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
613         exit(ret < 0? EXIT_FAILURE : EXIT_SUCCESS);
614 }