Merge branch 't/cmd_improvements'
[paraslash.git] / server.c
1 /*
2  * Copyright (C) 1997-2013 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 /**
11  * \mainpage Starting points for getting an overview:
12  *
13  *      - The main programs: \ref server.c, \ref audiod.c, \ref client.c,
14  *        \ref audioc.c, \ref afh.c, \ref play.c,
15  *      - Server: \ref server_command, \ref sender,
16  *      - Audio file selector: \ref audio_format_handler, \ref afs_table,
17  *      - Client: \ref receiver, \ref receiver_node, \ref filter,
18  *        \ref filter_node, \ref writer_node.
19  *
20  *
21  * The gory details, listed by topic:
22  *
23  *      - Audio format handlers: \ref send_common.c \ref mp3_afh.c,
24  *        \ref ogg_afh.c, \ref aac_afh.c, \ref wma_afh.c, \ref spx_afh.c
25  *      - Decoders: \ref mp3dec_filter.c, \ref oggdec_filter.c,
26  *        \ref aacdec_filter.c, \ref wmadec_filter.c, spxdec_filter.c,
27  *        \ref flacdec_filter.c,
28  *      - Volume normalizer: \ref compress_filter.c,
29  *      - Output: \ref alsa_write.c, \ref osx_write.c, \ref oss_write.c,
30  *      - http: \ref http_recv.c, \ref http_send.c,
31  *      - udp: \ref udp_recv.c, \ref udp_send.c,
32  *      - dccp: \ref dccp_recv.c, \ref dccp_send.c,
33  *      - Audio file selector: \ref afs.c, \ref aft.c, \ref mood.c,
34  *      - Afs structures: \ref afs_table, \ref audio_file_data,
35  *        \ref afs_info \ref afh_info,
36  *      - Afs tables: \ref aft.c, \ref mood.c, \ref playlist.c,
37  *        \ref attribute.c, \ref score.c,
38  *      - The virtual streaming system: \ref vss.c, \ref chunk_queue.c.
39  *
40  * Lower levels:
41  *
42  *      - Scheduling: \ref sched.c, \ref sched.h,
43  *      - Networking: \ref net.c,
44  *      - File descriptors: \ref fd.c,
45  *      - Signals: \ref signal.c,
46  *      - Daemons: \ref daemon.c,
47  *      - Strings: \ref string.c, \ref string.h,
48  *      - Time: \ref time.c,
49  *      - Spawning processes: \ref exec.c,
50  *      - Inter process communication: \ref ipc.c,
51  *      - Blob tables: \ref blob.c,
52  *      - The error subsystem: \ref error.h.
53  *      - Access control for paraslash senders: \ref acl.c, \ref acl.h.
54  *      - Internal crypto API: \ref crypt.h.
55  *      - interactive sessions (libreadline): \ref interactive.c.
56  *
57  * Low-level data structures:
58  *
59  *      - Doubly linked lists: \ref list.h,
60  *      - Ring buffer: \ref ringbuffer.c, \ref ringbuffer.h,
61  *      - openssl: \ref crypt.c
62  *      - libgcrypt: \ref gcrypt.c
63  *      - Forward error correction: \ref fec.c.
64  */
65
66 #include <netinet/in.h>
67 #include <sys/socket.h>
68 #include <signal.h>
69 #include <regex.h>
70 #include <osl.h>
71 #include <sys/types.h>
72 #include <arpa/inet.h>
73 #include <sys/un.h>
74 #include <netdb.h>
75
76 #include "para.h"
77 #include "error.h"
78 #include "crypt.h"
79 #include "server.cmdline.h"
80 #include "afh.h"
81 #include "string.h"
82 #include "afs.h"
83 #include "server.h"
84 #include "list.h"
85 #include "send.h"
86 #include "sched.h"
87 #include "vss.h"
88 #include "config.h"
89 #include "close_on_fork.h"
90 #include "net.h"
91 #include "daemon.h"
92 #include "ipc.h"
93 #include "fd.h"
94 #include "signal.h"
95 #include "user_list.h"
96 #include "color.h"
97 #include "ggo.h"
98 #include "version.h"
99
100 __printf_2_3 void (*para_log)(int, const char*, ...) = daemon_log;
101
102 /** Define the array of error lists needed by para_server. */
103 INIT_SERVER_ERRLISTS;
104
105 /** Shut down non-authorized connections after that many seconds. */
106 #define ALARM_TIMEOUT 10
107
108 /**
109  * Pointer to shared memory area for communication between para_server
110  * and its children. Exported to vss.c. command.c and to afs.
111  */
112 struct misc_meta_data *mmd;
113
114 /**
115  * The configuration of para_server
116  *
117  * It also contains the options for the audio file selector, audio format
118  * handler and all supported senders.
119  */
120 struct server_args_info conf;
121
122 /** A random value used in child context for authentication. */
123 uint32_t afs_socket_cookie;
124
125 /** The mutex protecting the shared memory area containing the mmd struct. */
126 int mmd_mutex;
127
128 /** The file containing user information (public key, permissions). */
129 static char *user_list_file = NULL;
130
131 static struct sched sched;
132
133 /** The task responsible for server command handling. */
134 struct server_command_task {
135         /** TCP port on which para_server listens for connections. */
136         int listen_fd;
137         /** Copied from para_server's main function. */
138         int argc;
139         /** Argument vector passed to para_server's main function. */
140         char **argv;
141         /** The command task structure for scheduling. */
142         struct task task;
143 };
144
145 static int want_colors(void)
146 {
147         if (conf.color_arg == color_arg_no)
148                 return 0;
149         if (conf.color_arg == color_arg_yes)
150                 return 1;
151         if (conf.logfile_given)
152                 return 0;
153         return isatty(STDERR_FILENO);
154 }
155
156 static void init_colors_or_die(void)
157 {
158         int i;
159
160         if (!want_colors())
161                 return;
162         daemon_set_flag(DF_COLOR_LOG);
163         daemon_set_default_log_colors();
164         for (i = 0; i < conf.log_color_given; i++)
165                 daemon_set_log_color_or_die(conf.log_color_arg[i]);
166 }
167
168 /*
169  * setup shared memory area and get mutex for locking
170  */
171 static void init_ipc_or_die(void)
172 {
173         void *shm;
174         int shmid, ret = shm_new(sizeof(struct misc_meta_data));
175
176         if (ret < 0)
177                 goto err_out;
178         shmid = ret;
179         ret = shm_attach(shmid, ATTACH_RW, &shm);
180         shm_destroy(shmid);
181         if (ret < 0)
182                 goto err_out;
183         mmd = shm;
184
185         ret = mutex_new();
186         if (ret < 0)
187                 goto err_out;
188         mmd_mutex = ret;
189
190         mmd->num_played = 0;
191         mmd->num_commands = 0;
192         mmd->events = 0;
193         mmd->num_connects = 0;
194         mmd->active_connections = 0;
195         mmd->vss_status_flags = VSS_NEXT;
196         mmd->new_vss_status_flags = VSS_NEXT;
197         return;
198 err_out:
199         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
200         exit(EXIT_FAILURE);
201 }
202
203 /**
204  * (Re-)read the server configuration files.
205  *
206  * \param override Passed to gengetopt to activate the override feature.
207  *
208  * This function also re-opens the logfile and sets the global \a
209  * user_list_file variable.
210  */
211 void parse_config_or_die(int override)
212 {
213         char *home = para_homedir();
214         int ret;
215         char *cf;
216
217         daemon_close_log();
218         if (conf.config_file_given)
219                 cf = para_strdup(conf.config_file_arg);
220         else
221                 cf = make_message("%s/.paraslash/server.conf", home);
222         free(user_list_file);
223         if (!conf.user_list_given)
224                 user_list_file = make_message("%s/.paraslash/server.users", home);
225         else
226                 user_list_file = para_strdup(conf.user_list_arg);
227         ret = file_exists(cf);
228         if (conf.config_file_given && !ret)  {
229                 ret = -1;
230                 PARA_EMERG_LOG("can not read config file %s\n", cf);
231                 goto out;
232         }
233         if (ret) {
234                 int tmp = conf.daemon_given;
235                 struct server_cmdline_parser_params params = {
236                         .override = override,
237                         .initialize = 0,
238                         .check_required = 1,
239                         .check_ambiguity = 0,
240                         .print_errors = !conf.daemon_given
241                 };
242                 server_cmdline_parser_config_file(cf, &conf, &params);
243                 daemon_set_loglevel(conf.loglevel_arg);
244                 conf.daemon_given = tmp;
245         }
246         if (conf.logfile_given) {
247                 daemon_set_logfile(conf.logfile_arg);
248                 daemon_open_log_or_die();
249         }
250         init_colors_or_die();
251         daemon_set_flag(DF_LOG_PID);
252         daemon_set_flag(DF_LOG_LL);
253         daemon_set_flag(DF_LOG_TIME);
254         if (conf.log_timing_given)
255                 daemon_set_flag(DF_LOG_TIMING);
256         ret = 1;
257 out:
258         free(cf);
259         free(home);
260         if (ret > 0)
261                 return;
262         free(user_list_file);
263         user_list_file = NULL;
264         exit(EXIT_FAILURE);
265 }
266
267 static void signal_pre_select(struct sched *s, struct task *t)
268 {
269         struct signal_task *st = container_of(t, struct signal_task, task);
270         para_fd_set(st->fd, &s->rfds, &s->max_fileno);
271 }
272
273 /*
274  * called when server gets SIGHUP or when client invokes hup command.
275  */
276 static void handle_sighup(void)
277 {
278         PARA_NOTICE_LOG("SIGHUP\n");
279         parse_config_or_die(1); /* reopens log */
280         init_user_list(user_list_file); /* reload user list */
281         if (mmd->afs_pid)
282                 kill(mmd->afs_pid, SIGHUP);
283 }
284
285 static int signal_post_select(struct sched *s, __a_unused struct task *t)
286 {
287         int signum = para_next_signal(&s->rfds);
288
289         switch (signum) {
290         case 0:
291                 return 0;
292         case SIGHUP:
293                 handle_sighup();
294                 break;
295         case SIGCHLD:
296                 for (;;) {
297                         pid_t pid;
298                         int ret = para_reap_child(&pid);
299                         if (ret <= 0)
300                                 break;
301                         if (pid != mmd->afs_pid)
302                                 continue;
303                         PARA_EMERG_LOG("fatal: afs died\n");
304                         kill(0, SIGTERM);
305                         goto cleanup;
306                 }
307                 break;
308         /* die on sigint/sigterm. Kill all children too. */
309         case SIGINT:
310         case SIGTERM:
311                 PARA_EMERG_LOG("terminating on signal %d\n", signum);
312                 kill(0, SIGTERM);
313                 /*
314                  * We must wait for afs because afs catches SIGINT/SIGTERM.
315                  * Before reacting to the signal, afs might want to use the
316                  * shared memory area and the mmd mutex.  If we destroy this
317                  * mutex too early and afs tries to lock the shared memory
318                  * area, the call to mutex_lock() will fail and terminate the
319                  * afs process. This leads to dirty osl tables.
320                  *
321                  * There's no such problem with the other children of the
322                  * server process (the command handlers) as these reset their
323                  * SIGINT/SIGTERM handlers to the default action, i.e.  these
324                  * processes get killed immediately by the above kill().
325                  */
326                 PARA_INFO_LOG("waiting for afs (pid %d) to die\n",
327                         (int)mmd->afs_pid);
328                 waitpid(mmd->afs_pid, NULL, 0);
329 cleanup:
330                 free(mmd->afd.afhi.chunk_table);
331                 close_listed_fds();
332                 mutex_destroy(mmd_mutex);
333                 shm_detach(mmd);
334                 exit(EXIT_FAILURE);
335         }
336         return 0;
337 }
338
339 static void init_signal_task(void)
340 {
341         static struct signal_task signal_task_struct,
342                 *st = &signal_task_struct;
343
344         st->task.pre_select = signal_pre_select;
345         st->task.post_select = signal_post_select;
346         sprintf(st->task.status, "signal task");
347
348         PARA_NOTICE_LOG("setting up signal handling\n");
349         st->fd = para_signal_init(); /* always successful */
350         para_install_sighandler(SIGINT);
351         para_install_sighandler(SIGTERM);
352         para_install_sighandler(SIGHUP);
353         para_install_sighandler(SIGCHLD);
354         para_sigaction(SIGPIPE, SIG_IGN);
355         add_close_on_fork_list(st->fd);
356         register_task(&sched, &st->task);
357 }
358
359 static void command_pre_select(struct sched *s, struct task *t)
360 {
361         struct server_command_task *sct = container_of(t, struct server_command_task, task);
362         para_fd_set(sct->listen_fd, &s->rfds, &s->max_fileno);
363 }
364
365 static int command_post_select(struct sched *s, struct task *t)
366 {
367         struct server_command_task *sct = container_of(t, struct server_command_task, task);
368
369         int new_fd, ret, i;
370         char *peer_name;
371         pid_t child_pid;
372         uint32_t *chunk_table;
373
374         ret = para_accept(sct->listen_fd, &s->rfds, NULL, 0, &new_fd);
375         if (ret <= 0)
376                 goto out;
377         peer_name = remote_name(new_fd);
378         PARA_INFO_LOG("got connection from %s, forking\n", peer_name);
379         mmd->num_connects++;
380         mmd->active_connections++;
381         /*
382          * The chunk table is a pointer located in the mmd struct that points
383          * to dynamically allocated memory, i.e. it must be freed by the parent
384          * and the child. However, as the mmd struct is in a shared memory
385          * area, there's no guarantee that after the fork this pointer is still
386          * valid in child context. As it is not used in the child anyway, we
387          * save it to a local variable before the fork and free the memory via
388          * that copy in the child directly after the fork.
389          */
390         chunk_table = mmd->afd.afhi.chunk_table;
391         child_pid = fork();
392         if (child_pid < 0) {
393                 ret = -ERRNO_TO_PARA_ERROR(errno);
394                 goto out;
395         }
396         if (child_pid) {
397                 /* avoid problems with non-fork-safe PRNGs */
398                 unsigned char buf[16];
399                 get_random_bytes_or_die(buf, sizeof(buf));
400                 close(new_fd);
401                 /* parent keeps accepting connections */
402                 return 0;
403         }
404         /* mmd might already have changed at this point */
405         free(chunk_table);
406         alarm(ALARM_TIMEOUT);
407         close_listed_fds();
408         para_signal_shutdown();
409         /*
410          * put info on who we are serving into argv[0] to make
411          * client ip visible in top/ps
412          */
413         for (i = sct->argc - 1; i >= 0; i--)
414                 memset(sct->argv[i], 0, strlen(sct->argv[i]));
415         sprintf(sct->argv[0], "para_server (serving %s)", peer_name);
416         handle_connect(new_fd, peer_name);
417         /* never reached*/
418 out:
419         if (ret < 0)
420                 PARA_CRIT_LOG("%s\n", para_strerror(-ret));
421         return 0;
422 }
423
424 static void init_server_command_task(int argc, char **argv)
425 {
426         int ret;
427         static struct server_command_task server_command_task_struct,
428                 *sct = &server_command_task_struct;
429
430         PARA_NOTICE_LOG("initializing tcp command socket\n");
431         sct->task.pre_select = command_pre_select;
432         sct->task.post_select = command_post_select;
433         sct->argc = argc;
434         sct->argv = argv;
435         ret = para_listen_simple(IPPROTO_TCP, conf.port_arg);
436         if (ret < 0)
437                 goto err;
438         sct->listen_fd = ret;
439         ret = mark_fd_nonblocking(sct->listen_fd);
440         if (ret < 0)
441                 goto err;
442         add_close_on_fork_list(sct->listen_fd); /* child doesn't need the listener */
443         sprintf(sct->task.status, "server command task");
444         register_task(&sched, &sct->task);
445         return;
446 err:
447         PARA_EMERG_LOG("%s\n", para_strerror(-ret));
448         exit(EXIT_FAILURE);
449 }
450
451 static int init_afs(int argc, char **argv)
452 {
453         int ret, afs_server_socket[2];
454         pid_t afs_pid;
455
456         ret = socketpair(PF_UNIX, SOCK_DGRAM, 0, afs_server_socket);
457         if (ret < 0)
458                 exit(EXIT_FAILURE);
459         get_random_bytes_or_die((unsigned char *)&afs_socket_cookie,
460                 sizeof(afs_socket_cookie));
461         afs_pid = fork();
462         if (afs_pid < 0)
463                 exit(EXIT_FAILURE);
464         if (afs_pid == 0) { /* child (afs) */
465                 int i;
466                 for (i = argc - 1; i >= 0; i--)
467                         memset(argv[i], 0, strlen(argv[i]));
468                 sprintf(argv[0], "para_server (afs)");
469                 close(afs_server_socket[0]);
470                 afs_init(afs_socket_cookie, afs_server_socket[1]);
471         }
472         mmd->afs_pid = afs_pid;
473         close(afs_server_socket[1]);
474         ret = mark_fd_nonblocking(afs_server_socket[0]);
475         if (ret < 0)
476                 exit(EXIT_FAILURE);
477         add_close_on_fork_list(afs_server_socket[0]);
478         PARA_INFO_LOG("afs_socket: %d, afs_socket_cookie: %u\n",
479                 afs_server_socket[0], (unsigned) afs_socket_cookie);
480         return afs_server_socket[0];
481 }
482
483 __noreturn static void print_help_and_die(void)
484 {
485         struct ggo_help h = DEFINE_GGO_HELP(server);
486         bool d = conf.detailed_help_given;
487
488         ggo_print_help(&h, d? GPH_STANDARD_FLAGS_DETAILED : GPH_STANDARD_FLAGS);
489         exit(0);
490 }
491
492 static void server_init(int argc, char **argv)
493 {
494         struct server_cmdline_parser_params params = {
495                 .override = 0,
496                 .initialize = 1,
497                 .check_required = 0,
498                 .check_ambiguity = 0,
499                 .print_errors = 1
500         };
501         int afs_socket;
502
503         valid_fd_012();
504         init_random_seed_or_die();
505         /* parse command line options */
506         server_cmdline_parser_ext(argc, argv, &conf, &params);
507         daemon_set_loglevel(conf.loglevel_arg);
508         version_handle_flag("server", conf.version_given);
509         if (conf.help_given || conf.detailed_help_given)
510                 print_help_and_die();
511         drop_privileges_or_die(conf.user_arg, conf.group_arg);
512         /* parse config file, open log and set defaults */
513         parse_config_or_die(0);
514         log_welcome("para_server");
515         init_ipc_or_die(); /* init mmd struct and mmd->lock */
516         /* make sure, the global now pointer is uptodate */
517         clock_get_realtime(now);
518         set_server_start_time(now);
519         init_user_list(user_list_file);
520         /* become daemon */
521         if (conf.daemon_given)
522                 daemonize(true /* parent waits for SIGTERM */);
523         PARA_NOTICE_LOG("initializing audio format handlers\n");
524         afh_init();
525
526         /*
527          * Although afs uses its own signal handling we must ignore SIGUSR1
528          * _before_ the afs child process gets born by init_afs() below.  It's
529          * racy to do this in the child because the parent might send SIGUSR1
530          * before the child gets a chance to ignore this signal -- only the
531          * good die young.
532          */
533         para_sigaction(SIGUSR1, SIG_IGN);
534         /*
535          * We have to block SIGCHLD before the afs process is being forked off.
536          * Otherwise, para_server does not notice if afs dies before the
537          * SIGCHLD handler has been installed for the parent process by
538          * init_signal_task() below.
539          */
540         para_block_signal(SIGCHLD);
541         PARA_NOTICE_LOG("initializing the audio file selector\n");
542         afs_socket = init_afs(argc, argv);
543         init_signal_task();
544         para_unblock_signal(SIGCHLD);
545         PARA_NOTICE_LOG("initializing virtual streaming system\n");
546         init_vss_task(afs_socket, &sched);
547         init_server_command_task(argc, argv);
548         if (conf.daemon_given)
549                 kill(getppid(), SIGTERM);
550         PARA_NOTICE_LOG("server init complete\n");
551 }
552
553 static void status_refresh(void)
554 {
555         static int prev_uptime = -1, prev_events = -1;
556         int uptime = get_server_uptime(now);
557
558         if (prev_events != mmd->events)
559                 goto out;
560         if (mmd->new_vss_status_flags != mmd->vss_status_flags)
561                 goto out_inc_events;
562         if (uptime / 60 != prev_uptime / 60)
563                 goto out_inc_events;
564         return;
565 out_inc_events:
566         mmd->events++;
567 out:
568         prev_uptime = uptime;
569         prev_events = mmd->events;
570         mmd->vss_status_flags = mmd->new_vss_status_flags;
571         PARA_DEBUG_LOG("%d events, forcing status update\n", mmd->events);
572         killpg(0, SIGUSR1);
573 }
574
575 static int server_select(int max_fileno, fd_set *readfds, fd_set *writefds,
576                 struct timeval *timeout_tv)
577 {
578         int ret;
579
580         status_refresh();
581         mutex_unlock(mmd_mutex);
582         ret = para_select(max_fileno + 1, readfds, writefds, timeout_tv);
583         mutex_lock(mmd_mutex);
584         return ret;
585 }
586
587 /**
588  * The main function of para_server.
589  *
590  * \param argc Usual argument count.
591  * \param argv Usual argument vector.
592  *
593  * \return EXIT_SUCCESS or EXIT_FAILURE.
594  */
595 int main(int argc, char *argv[])
596 {
597         int ret;
598
599         sched.default_timeout.tv_sec = 1;
600         sched.select_function = server_select;
601
602         server_init(argc, argv);
603         mutex_lock(mmd_mutex);
604         ret = schedule(&sched);
605         if (ret < 0) {
606                 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
607                 exit(EXIT_FAILURE);
608         }
609         exit(EXIT_SUCCESS);
610 }