]> git.tuebingen.mpg.de Git - paraslash.git/blob - audiod.c
Convert para_fade to lopsub.
[paraslash.git] / audiod.c
1 /*
2  * Copyright (C) 2005 Andre Noll <maan@tuebingen.mpg.de>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file audiod.c The paraslash's audio daemon. */
8
9 #include <netinet/in.h>
10 #include <sys/socket.h>
11 #include <regex.h>
12 #include <sys/types.h>
13 #include <arpa/inet.h>
14 #include <sys/un.h>
15 #include <netdb.h>
16 #include <signal.h>
17 #include <pwd.h>
18 #include <lopsub.h>
19
20 #include "recv_cmd.lsg.h"
21 #include "client.lsg.h"
22 #include "para.h"
23 #include "error.h"
24 #include "crypt.h"
25 #include "audiod.cmdline.h"
26 #include "list.h"
27 #include "sched.h"
28 #include "ggo.h"
29 #include "buffer_tree.h"
30 #include "recv.h"
31 #include "filter.h"
32 #include "grab_client.h"
33 #include "client.h"
34 #include "audiod.h"
35 #include "net.h"
36 #include "daemon.h"
37 #include "string.h"
38 #include "fd.h"
39 #include "write.h"
40 #include "write_common.h"
41 #include "signal.h"
42 #include "version.h"
43
44 /** Array of error strings. */
45 DEFINE_PARA_ERRLIST;
46
47 __printf_2_3 void (*para_log)(int, const char*, ...) = daemon_log;
48 /** define the array containing all supported audio formats */
49 const char *audio_formats[] = {AUDIOD_AUDIO_FORMAT_ARRAY NULL};
50
51 /** Defines how audiod handles one supported audio format. */
52 struct audio_format_info {
53         /** the receiver for this audio format */
54         int receiver_num;
55         /** Parsed receiver command line. */
56         struct lls_parse_result *receiver_lpr;
57         /** the number of filters that should be activated for this audio format */
58         unsigned int num_filters;
59         /** Array of filter numbers to be activated. */
60         unsigned *filter_nums;
61         /** Pointer to the array of filter configurations. */
62         void **filter_conf;
63         /** the number of filters that should be activated for this audio format */
64         unsigned int num_writers;
65         /** Array of writer numbers to be activated. */
66         int *writer_nums;
67         /** pointer to the array of writer configurations */
68         void **writer_conf;
69         /** do not start receiver/filters/writer before this time */
70         struct timeval restart_barrier;
71 };
72
73 /* Describes one instance of a receiver-filter-writer chain. */
74 struct slot_info {
75         /* Number of the audio format in this slot. */
76         int format;
77         /* The stream_start status item announced by para_server.  */
78         struct timeval server_stream_start;
79         /* The offset status item announced by para_server. */
80         unsigned offset_seconds;
81         /* The seconds_total status item announced by para_server. */
82         unsigned seconds_total;
83         /* The receiver info associated with this slot. */
84         struct receiver_node *receiver_node;
85         /* The array of filter nodes. */
86         struct filter_node *fns;
87         /* The array of writers attached to the last filter. */
88         struct writer_node *wns;
89 };
90
91 #define RECEIVER_CMD(_a) lls_cmd((_a)->receiver_num, recv_cmd_suite)
92 #define RECEIVER(_a) ((const struct receiver *)lls_user_data(RECEIVER_CMD(_a)))
93
94 /** Maximal number of simultaneous instances. */
95 #define MAX_STREAM_SLOTS 5
96
97 /** Iterate over all slots. */
98 #define FOR_EACH_SLOT(_slot) for (_slot = 0; _slot < MAX_STREAM_SLOTS; _slot++)
99
100 /**
101  * para_audiod uses \p MAX_STREAM_SLOTS different slots, each of which may
102  * be associated with a receiver/filter/writer triple. This array holds all
103  * information on the status of these slots.
104  *
105  * \sa struct slot_info
106  * */
107 struct slot_info slot[MAX_STREAM_SLOTS];
108
109 /** The vss status flags audiod is interested in. */
110 enum vss_status_flags {
111         /** Whether the 'N' flag is set. */
112         VSS_STATUS_FLAG_NEXT = 1,
113         /** The 'P' flag is set. */
114         VSS_STATUS_FLAG_PLAYING = 2,
115 };
116
117 /**
118  * The scheduler instance of para_audiod.
119  *
120  * This is needed also in audiod_command.c (for the tasks command), so it can
121  * not be made static.
122  */
123 struct sched sched = {.max_fileno = 0};
124
125 /* The task for obtaining para_server's status (para_client stat). */
126 struct status_task {
127         /** The associated task structure of audiod. */
128         struct task *task;
129         /** Client data associated with the stat task. */
130         struct client_task *ct;
131         /** Do not restart client command until this time. */
132         struct timeval restart_barrier;
133         /** Last time we received status data from para_server. */
134         struct timeval last_status_read;
135         size_t min_iqs;
136         /** The offset value announced by para_server. */
137         int offset_seconds;
138         /** The length of the current audio file as announced by para_server. */
139         int length_seconds;
140         /** The start of the current stream from the view of para_server. */
141         struct timeval server_stream_start;
142         /** The average time deviation between para_server and para_audiod. */
143         struct timeval sa_time_diff;
144         /** Whether client time is ahead of server time. */
145         int sa_time_diff_sign;
146         /** The 'P' and the 'N' flags as announced by para_server. */
147         enum vss_status_flags vss_status;
148         /** Number of times the clock difference is to be checked. */
149         unsigned clock_diff_count;
150         /** When to start the next check for clock difference. */
151         struct timeval clock_diff_barrier;
152         /** Number of the audio format as announced by para_server. */
153         int current_audio_format_num;
154         /* The status task btrn is the child of the client task. */
155         struct btr_node *btrn;
156 };
157
158 /** The array of status items sent by para_server. */
159 char *stat_item_values[NUM_STAT_ITEMS] = {NULL};
160
161 /**
162  * the current mode of operation of which can be changed by the on/off/cycle
163  * commands. It is either, AUDIOD_OFF, AUDIOD_ON or AUDIOD_STANDBY.
164  */
165 int audiod_status = AUDIOD_ON;
166
167 /**
168  * the gengetopt args_info struct that holds information on all command line
169  * arguments
170  */
171 static struct audiod_args_info conf;
172
173 static char *socket_name;
174 static struct audio_format_info afi[NUM_AUDIO_FORMATS];
175
176 static struct signal_task *signal_task;
177
178 static struct status_task status_task_struct;
179
180 static uid_t *uid_whitelist;
181
182 /**
183  * the task that calls the status command of para_server
184  *
185  * \sa struct status_task
186  */
187 static struct status_task *stat_task = &status_task_struct;
188
189 /*
190  * The task for handling audiod commands.
191  *
192  * We need two listening sockets for backward compability: on Linux systems
193  * fd[0] is an abstract socket (more precisely, a socket bound to an address in
194  * the abstract namespace), and fd[1] is the usual pathname socket. On other
195  * systems, fd[0] is negative, and only the pathname socket is used.
196  *
197  * For 0.5.x we accept connections on both sockets to make sure that old
198  * para_audioc versions can still connect. New versions use only the abstract
199  * socket. Hence after v0.6.0 we can go back to a single socket, either an
200  * abstract one (Linux) or a pathname socket (all other systems).
201  */
202 struct command_task {
203         /** The local listening sockets. */
204         int fd[2];
205         /** the associated task structure */
206         struct task *task;
207 };
208
209 /** iterate over all supported audio formats */
210 #define FOR_EACH_AUDIO_FORMAT(af) for (af = 0; af < NUM_AUDIO_FORMATS; af++)
211
212 /**
213  * Get the audio format number.
214  *
215  * \param name The name of the audio format.
216  *
217  * \return The audio format number on success, -E_UNSUPPORTED_AUDIO_FORMAT if
218  * \a name is not a supported audio format.
219  */
220 static int get_audio_format_num(const char *name)
221 {
222         int i;
223
224         while (para_isspace(*name))
225                 name++;
226         FOR_EACH_AUDIO_FORMAT(i)
227                 if (!strcmp(name, audio_formats[i]))
228                         return i;
229         return -E_UNSUPPORTED_AUDIO_FORMAT;
230 }
231
232 /**
233  * Return the flags for the \a decoder_flags status item.
234  *
235  * Allocates a string which contains one octal digit per slot.  Bit zero (value
236  * 1) is set if a receiver is active. Bit one (value 2) and bit three (value 4)
237  * have the analogous meaning for filter and writer, respectively.
238  *
239  * \return String that must be freed by the caller.
240  */
241 __malloc char *audiod_get_decoder_flags(void)
242 {
243         int i;
244         char flags[MAX_STREAM_SLOTS + 1];
245
246         FOR_EACH_SLOT(i) {
247                 struct slot_info *s = &slot[i];
248                 char flag = '0';
249                 if (s->receiver_node)
250                         flag += 1;
251                 if (s->fns)
252                         flag += 2;
253                 if (s->wns)
254                         flag += 4;
255                 flags[i] = flag;
256         }
257         flags[MAX_STREAM_SLOTS] = '\0';
258         return para_strdup(flags);
259 }
260
261 static int get_matching_audio_format_nums(const char *re)
262 {
263         int i, ret;
264         regex_t preg;
265
266         ret = para_regcomp(&preg, re, REG_EXTENDED | REG_NOSUB);
267         if (ret < 0)
268                 return ret;
269         ret = 0;
270         FOR_EACH_AUDIO_FORMAT(i)
271                 if (regexec(&preg, audio_formats[i], 0, NULL, 0) != REG_NOMATCH)
272                         ret |= (1 << i);
273         regfree(&preg);
274         return ret;
275 }
276
277 static int get_play_time_slot_num(void)
278 {
279         int i, oldest_slot = -1;
280         struct timeval oldest_wstime = {0, 0};
281
282         FOR_EACH_SLOT(i) {
283                 struct slot_info *s = &slot[i];
284                 struct timeval wstime;
285                 if (!s->wns || !s->wns[0].btrn)
286                         continue;
287                 btr_get_node_start(s->wns[0].btrn, &wstime);
288                 if (oldest_slot >= 0 && tv_diff(&wstime, &oldest_wstime, NULL) > 0)
289                         continue;
290                 oldest_wstime = wstime;
291                 oldest_slot = i;
292         }
293         return oldest_slot;
294 }
295
296 /**
297  * Compute the play time based on information of the current slot.
298  *
299  * This computes a string of the form "0:07 [3:33] (3%/3:40)" using information
300  * from the status items received from para_server and the start time of the
301  * (first) writer of the current slot.
302  *
303  * It has to take into account that the stream was probably not started at
304  * the beginning of the file, that the clock between the server and the client
305  * host may differ and that playback of the stream was delayed, e.g. because
306  * the prebuffer filter is used in the filter configuration.
307  *
308  * If no writer is active, for example because para_audiod runs in standby
309  * mode, an approximation based only on the status items is computed and the
310  * returned string is prefixed with "~".
311  *
312  * \return A string that must be freed by the caller.
313  */
314 char *get_time_string(void)
315 {
316         int ret, seconds = 0, length = stat_task->length_seconds;
317         struct timeval *tmp, sum, sss, /* server stream start */
318                 rstime, /* receiver start time */
319                 wstime, /* writer start time */
320                 wtime, /* now - writer start */
321                 rskip; /* receiver start - sss */
322         int slot_num = get_play_time_slot_num();
323         struct slot_info *s = slot_num < 0? NULL : &slot[slot_num];
324         char *msg;
325
326         if (audiod_status == AUDIOD_OFF)
327                 goto empty;
328         if (stat_task->server_stream_start.tv_sec == 0) {
329                 if (stat_task->vss_status & VSS_STATUS_FLAG_PLAYING)
330                         goto out; /* server is about to change file */
331                 if (length > 0) /* paused */
332                         return NULL;
333                 goto empty; /* stopped */
334         }
335         /*
336          * Valid status items and playing, set length and tmp to the stream
337          * start. We use the slot info and fall back to the info from current
338          * status items if no slot info is available.
339          */
340         tmp = &stat_task->server_stream_start;
341         if (s && s->wns && s->wns[0].btrn) { /* writer active in this slot */
342                 btr_get_node_start(s->wns[0].btrn, &wstime);
343                 if (wstime.tv_sec != 0) { /* writer wrote something */
344                         if (s->server_stream_start.tv_sec == 0) {
345                                 /* copy status info to slot */
346                                 s->server_stream_start = stat_task->server_stream_start;
347                                 s->offset_seconds = stat_task->offset_seconds;
348                                 s->seconds_total = stat_task->length_seconds;
349                         }
350                         length = s->seconds_total;
351                         tmp = &s->server_stream_start;
352                 }
353         }
354         if (stat_task->sa_time_diff_sign > 0)
355                 tv_diff(tmp, &stat_task->sa_time_diff, &sss);
356         else
357                 tv_add(tmp, &stat_task->sa_time_diff, &sss);
358         if (!s || !s->wns || !s->wns[0].btrn || wstime.tv_sec == 0) {
359                 struct timeval diff;
360                 tv_diff(now, &sss, &diff);
361                 seconds = diff.tv_sec + stat_task->offset_seconds;
362                 goto out;
363         }
364         tv_diff(now, &wstime, &wtime);
365         //PARA_CRIT_LOG("offset %d\n", s->offset_seconds);
366         seconds = s->offset_seconds;
367         if (s->receiver_node->btrn) {
368                 btr_get_node_start(s->receiver_node->btrn, &rstime);
369                 ret = tv_diff(&rstime, &sss, &rskip);
370                 if (ret > 0 && rskip.tv_sec > 2) {
371                         /* audiod was started in the middle of the stream */
372                         tv_add(&wtime, &rskip, &sum);
373                         seconds += sum.tv_sec;
374                 } else
375                         seconds += wtime.tv_sec;
376         } else
377                 seconds += wtime.tv_sec;
378 out:
379         seconds = PARA_MIN(seconds, length);
380         seconds = PARA_MAX(seconds, 0);
381         msg = make_message(
382                 "%s%d:%02d [%d:%02d] (%d%%/%d:%02d)",
383                 s? "" : "~",
384                 seconds / 60,
385                 seconds % 60,
386                 (length - seconds) / 60,
387                 (length - seconds) % 60,
388                 length? (seconds * 100 + length / 2) / length : 0,
389                 length / 60,
390                 length % 60
391         );
392         //PARA_DEBUG_LOG("slot %d: %s\n", slot_num, msg);
393         return msg;
394 empty:
395         return para_strdup(NULL);
396 }
397
398 static void parse_config_or_die(void)
399 {
400         int ret, i;
401         char *config_file;
402         struct audiod_cmdline_parser_params params = {
403                 .override = 0,
404                 .initialize = 0,
405                 .check_required = 1,
406                 .check_ambiguity = 0,
407                 .print_errors = 1
408         };
409
410         if (conf.config_file_given)
411                 config_file = para_strdup(conf.config_file_arg);
412         else {
413                 char *home = para_homedir();
414                 config_file = make_message("%s/.paraslash/audiod.conf", home);
415                 free(home);
416         }
417         ret = file_exists(config_file);
418         if (conf.config_file_given && !ret) {
419                 PARA_EMERG_LOG("can not read config file %s\n", config_file);
420                 free(config_file);
421                 goto err;
422         }
423         if (ret) {
424                 audiod_cmdline_parser_config_file(config_file, &conf, &params);
425                 daemon_set_loglevel(conf.loglevel_arg);
426         }
427         free(config_file);
428         if (conf.user_allow_given > 0) {
429                 uid_whitelist = para_malloc(conf.user_allow_given
430                         * sizeof(uid_t));
431                 for (i = 0; i < conf.user_allow_given; i++) {
432                         int32_t val;
433                         struct passwd *pw;
434                         ret = para_atoi32(conf.user_allow_arg[i], &val);
435                         if (ret >= 0) {
436                                 uid_whitelist[i] = val;
437                                 continue;
438                         }
439                         errno = 0; /* see getpwnam(3) */
440                         pw = getpwnam(conf.user_allow_arg[i]);
441                         if (!pw) {
442                                 PARA_EMERG_LOG("invalid username: %s\n",
443                                         conf.user_allow_arg[i]);
444                                 goto err;
445                         }
446                         uid_whitelist[i] = pw->pw_uid;
447                 }
448         }
449         return;
450 err:
451         exit(EXIT_FAILURE);
452 }
453
454 static void setup_signal_handling(void)
455 {
456         signal_task = signal_init_or_die();
457         para_install_sighandler(SIGINT);
458         para_install_sighandler(SIGTERM);
459         para_install_sighandler(SIGHUP);
460         para_sigaction(SIGPIPE, SIG_IGN);
461 }
462
463 static void clear_slot(int slot_num)
464 {
465         struct slot_info *s = &slot[slot_num];
466
467         PARA_INFO_LOG("clearing slot %d\n", slot_num);
468         memset(s, 0, sizeof(struct slot_info));
469         s->format = -1;
470 }
471
472 static void close_receiver(int slot_num)
473 {
474         struct slot_info *s = &slot[slot_num];
475         struct audio_format_info *a;
476
477         if (s->format < 0 || !s->receiver_node)
478                 return;
479         a = &afi[s->format];
480         PARA_NOTICE_LOG("closing %s receiver in slot %d\n",
481                 audio_formats[s->format], slot_num);
482         RECEIVER(a)->close(s->receiver_node);
483         btr_remove_node(&s->receiver_node->btrn);
484         task_reap(&s->receiver_node->task);
485         free(s->receiver_node);
486         s->receiver_node = NULL;
487         stat_task->current_audio_format_num = -1;
488         tv_add(now, &(struct timeval)EMBRACE(0, 200 * 1000),
489                 &a->restart_barrier);
490 }
491
492 static void writer_cleanup(struct writer_node *wn)
493 {
494         struct writer *w;
495
496         if (!wn)
497                 return;
498         w = writers + wn->writer_num;
499         PARA_INFO_LOG("closing %s\n", writer_names[wn->writer_num]);
500         w->close(wn);
501         btr_remove_node(&wn->btrn);
502         task_reap(&wn->task);
503 }
504
505 static void close_writers(struct slot_info *s)
506 {
507         struct audio_format_info *a;
508         int i;
509
510         if (s->format < 0)
511                 return;
512         assert(s->wns);
513         a = afi + s->format;
514         if (a->num_writers == 0)
515                 writer_cleanup(s->wns);
516         else {
517                 for (i = 0; i < a->num_writers; i++)
518                         writer_cleanup(s->wns + i);
519         }
520         free(s->wns);
521         s->wns = NULL;
522 }
523
524 static void close_filters(struct slot_info *s)
525 {
526         int i;
527         struct audio_format_info *a = afi + s->format;
528         if (a->num_filters == 0)
529                 return;
530         for (i = a->num_filters - 1; i >= 0; i--) {
531                 struct filter_node *fn = s->fns + i;
532                 const struct filter *f;
533
534                 if (!fn)
535                         continue;
536                 f = filter_get(fn->filter_num);
537                 if (f->close)
538                         f->close(fn);
539                 btr_remove_node(&fn->btrn);
540                 task_reap(&fn->task);
541         }
542         free(s->fns);
543         s->fns = NULL;
544 }
545
546 static void notify_receivers(int error)
547 {
548         int i;
549
550         FOR_EACH_SLOT(i) {
551                 struct slot_info *s = slot + i;
552                 if (s->format < 0)
553                         continue;
554                 if (!s->receiver_node)
555                         continue;
556                 task_notify(s->receiver_node->task, error);
557         }
558 }
559
560 static int get_empty_slot(void)
561 {
562         int i;
563         struct slot_info *s;
564
565         FOR_EACH_SLOT(i) {
566                 s = &slot[i];
567                 if (s->format < 0) {
568                         clear_slot(i);
569                         return i;
570                 }
571                 if (s->wns || s->receiver_node || s->fns)
572                         continue;
573                 clear_slot(i);
574                 return i;
575         }
576         return -E_NO_MORE_SLOTS;
577 }
578
579 static void open_filters(struct slot_info *s)
580 {
581         struct audio_format_info *a = afi + s->format;
582         struct filter_node *fn;
583         int nf = a->num_filters;
584         struct btr_node *parent;
585         int i;
586
587         if (nf == 0)
588                 return;
589         PARA_INFO_LOG("opening %s filters\n", audio_formats[s->format]);
590         assert(s->fns == NULL);
591         s->fns = para_calloc(nf * sizeof(struct filter_node));
592         parent = s->receiver_node->btrn;
593         for (i = 0; i < nf; i++) {
594                 char buf[20];
595                 const struct filter *f = filter_get(a->filter_nums[i]);
596                 fn = s->fns + i;
597                 fn->filter_num = a->filter_nums[i];
598                 fn->conf = a->filter_conf[i];
599                 fn->btrn = btr_new_node(&(struct btr_node_description)
600                         EMBRACE(.name = f->name, .parent = parent,
601                                 .handler = f->execute, .context = fn));
602
603                 if (f->open)
604                         f->open(fn);
605                 sprintf(buf, "%s (slot %d)", f->name, (int)(s - slot));
606                 fn->task = task_register(&(struct task_info) {
607                         .name = buf,
608                         .pre_select = f->pre_select,
609                         .post_select = f->post_select,
610                         .context = fn,
611                 }, &sched);
612                 parent = fn->btrn;
613                 PARA_NOTICE_LOG("%s filter %d/%d (%s) started in slot %d\n",
614                         audio_formats[s->format], i,  nf, f->name, (int)(s - slot));
615         }
616 }
617
618 static void open_writers(struct slot_info *s)
619 {
620         int i;
621         struct audio_format_info *a = afi + s->format;
622         struct writer_node *wn;
623         struct btr_node *parent = s->fns[a->num_filters - 1].btrn;
624
625         assert(s->wns == NULL);
626         s->wns = para_calloc(PARA_MAX(1U, a->num_writers)
627                 * sizeof(struct writer_node));
628         for (i = 0; i < a->num_writers; i++) {
629                 wn = s->wns + i;
630                 wn->conf = a->writer_conf[i];
631                 wn->writer_num = a->writer_nums[i];
632                 register_writer_node(wn, parent, &sched);
633                 PARA_NOTICE_LOG("%s writer started in slot %d\n",
634                         writer_names[a->writer_nums[i]], (int)(s - slot));
635         }
636 }
637
638 /* returns slot num on success */
639 static int open_receiver(int format)
640 {
641         struct audio_format_info *a = &afi[format];
642         struct slot_info *s;
643         int ret, slot_num;
644         const struct receiver *r = RECEIVER(a);
645         const char *name = lls_command_name(RECEIVER_CMD(a));
646         struct receiver_node *rn;
647
648         tv_add(now, &(struct timeval)EMBRACE(2, 0), &a->restart_barrier);
649         ret = get_empty_slot();
650         if (ret < 0)
651                 return ret;
652         slot_num = ret;
653         rn = para_calloc(sizeof(*rn));
654         rn->receiver = r;
655         rn->lpr = a->receiver_lpr;
656         rn->btrn = btr_new_node(&(struct btr_node_description)
657                 EMBRACE(.name = name, .context = rn));
658         ret = r->open(rn);
659         if (ret < 0) {
660                 btr_remove_node(&rn->btrn);
661                 free(rn);
662                 return ret;
663         }
664         s = &slot[slot_num];
665         s->format = format;
666         s->receiver_node = rn;
667         PARA_NOTICE_LOG("started %s: %s receiver in slot %d\n",
668                 audio_formats[format], name, slot_num);
669         rn->task = task_register(&(struct task_info) {
670                 .name = name,
671                 .pre_select = r->pre_select,
672                 .post_select = r->post_select,
673                 .context = rn,
674         }, &sched);
675         return slot_num;
676 }
677
678 static bool receiver_running(void)
679 {
680         int i;
681         long unsigned ss1 = stat_task->server_stream_start.tv_sec;
682
683         FOR_EACH_SLOT(i) {
684                 struct slot_info *s = &slot[i];
685                 long unsigned ss2 = s->server_stream_start.tv_sec;
686
687                 if (!s->receiver_node)
688                         continue;
689                 if (task_status(s->receiver_node->task) >= 0)
690                         return true;
691                 if (ss1 == ss2)
692                         return true;
693         }
694         return false;
695 }
696
697 /**
698  * Return the root node of the current buffer tree.
699  *
700  * This is only used for stream grabbing.
701  *
702  * \return \p NULL if no slot is currently active. If more than one buffer tree
703  * exists, the node corresponding to the most recently started receiver is
704  * returned.
705  */
706 struct btr_node *audiod_get_btr_root(void)
707 {
708         int i, newest_slot = -1;
709         struct timeval newest_rstime = {0, 0};
710
711         FOR_EACH_SLOT(i) {
712                 struct slot_info *s = &slot[i];
713                 struct timeval rstime;
714                 if (!s->receiver_node)
715                         continue;
716                 if (task_status(s->receiver_node->task) < 0)
717                         continue;
718                 btr_get_node_start(s->receiver_node->btrn, &rstime);
719                 if (newest_slot >= 0 && tv_diff(&rstime, &newest_rstime, NULL) < 0)
720                         continue;
721                 newest_rstime = rstime;
722                 newest_slot = i;
723         }
724         if (newest_slot == -1)
725                 return NULL;
726         return slot[newest_slot].receiver_node->btrn;
727 }
728
729 /* whether a new instance of a decoder should be started. */
730 static bool must_start_decoder(void)
731 {
732         int cafn = stat_task->current_audio_format_num;
733         unsigned vs = stat_task->vss_status;
734
735         if (audiod_status != AUDIOD_ON)
736                 return false;
737         if (cafn < 0)
738                 return false;
739         if (!stat_task->ct)
740                 return false;
741         if (vs & VSS_STATUS_FLAG_NEXT)
742                 return false;
743         if (!(vs & VSS_STATUS_FLAG_PLAYING))
744                 return false;
745         if (receiver_running())
746                 return false;
747         if (tv_diff(now, &afi[cafn].restart_barrier, NULL) < 0)
748                 return false;
749         return true;
750 }
751
752 static void compute_time_diff(const struct timeval *status_time)
753 {
754         struct timeval tmp, diff;
755         static unsigned count;
756         int sign, sa_time_diff_sign = stat_task->sa_time_diff_sign;
757         const struct timeval max_deviation = {0, 500 * 1000};
758         const int time_smooth = 5;
759
760         sign = tv_diff(status_time, now, &diff);
761 //              PARA_NOTICE_LOG("%s: sign = %i, sa_time_diff_sign = %i\n", __func__,
762 //                      sign, sa_time_diff_sign);
763         if (!count) {
764                 sa_time_diff_sign = sign;
765                 stat_task->sa_time_diff = diff;
766                 count++;
767                 goto out;
768         }
769         if (count > 5) {
770                 int s = tv_diff(&diff, &stat_task->sa_time_diff, &tmp);
771                 if (tv_diff(&max_deviation, &tmp, NULL) < 0)
772                         PARA_WARNING_LOG("time diff jump: %lums\n",
773                                 s * tv2ms(&tmp));
774         }
775         count++;
776         sa_time_diff_sign = tv_convex_combination(
777                 sa_time_diff_sign * time_smooth, &stat_task->sa_time_diff,
778                 count > 10? sign : sign * time_smooth, &diff,
779                 &tmp);
780         stat_task->sa_time_diff = tmp;
781         PARA_INFO_LOG("time diff (cur/avg): %s%lums/%s%lums\n",
782                 sign < 0? "-" : "+",
783                 tv2ms(&diff),
784                 sa_time_diff_sign < 0? "-" : "+",
785                 tv2ms(&stat_task->sa_time_diff)
786         );
787 out:
788         stat_task->sa_time_diff_sign = sa_time_diff_sign;
789 }
790
791 static int update_item(int itemnum, char *buf)
792 {
793         long unsigned sec, usec;
794
795         if (stat_task->clock_diff_count && itemnum != SI_CURRENT_TIME)
796                 return 1;
797         free(stat_item_values[itemnum]);
798         stat_item_values[itemnum] = para_strdup(buf);
799         stat_client_write_item(itemnum);
800         switch (itemnum) {
801         case SI_STATUS_FLAGS:
802                 stat_task->vss_status = 0;
803                 if (strchr(buf, 'N'))
804                         stat_task->vss_status |= VSS_STATUS_FLAG_NEXT;
805                 if (strchr(buf, 'P'))
806                         stat_task->vss_status |= VSS_STATUS_FLAG_PLAYING;
807                 break;
808         case SI_OFFSET:
809                 stat_task->offset_seconds = atoi(buf);
810                 break;
811         case SI_SECONDS_TOTAL:
812                 stat_task->length_seconds = atoi(buf);
813                 break;
814         case SI_STREAM_START:
815                 if (sscanf(buf, "%lu.%lu", &sec, &usec) == 2) {
816                         stat_task->server_stream_start.tv_sec = sec;
817                         stat_task->server_stream_start.tv_usec = usec;
818                 }
819                 break;
820         case SI_CURRENT_TIME:
821                 if (sscanf(buf, "%lu.%lu", &sec, &usec) == 2) {
822                         struct timeval tv = {sec, usec};
823                         compute_time_diff(&tv);
824                 }
825                 break;
826         case SI_FORMAT:
827                 stat_task->current_audio_format_num
828                         = get_audio_format_num(buf);
829         }
830         return 1;
831 }
832
833 static int parse_stream_command(const char *txt, const char **cmd)
834 {
835         int ret, len;
836         char *re, *p = strchr(txt, ':');
837
838         if (!p)
839                 return -E_MISSING_COLON;
840         *cmd = p + 1;
841         len = p - txt;
842         re = malloc(len + 1);
843         strncpy(re, txt, len);
844         re[len] = '\0';
845         ret = get_matching_audio_format_nums(re);
846         free(re);
847         return ret;
848 }
849
850 static int add_filter(int format, const char *cmdline)
851 {
852         struct audio_format_info *a = &afi[format];
853         int filter_num, nf = a->num_filters;
854         void *cfg;
855
856         filter_num = check_filter_arg(cmdline, &cfg);
857         if (filter_num < 0)
858                 return filter_num;
859         a->filter_conf = para_realloc(a->filter_conf,
860                 (nf + 1) * sizeof(void *));
861         a->filter_nums = para_realloc(a->filter_nums,
862                 (nf + 1) * sizeof(unsigned));
863         a->filter_nums[nf] = filter_num;
864         a->filter_conf[nf] = cfg;
865         a->num_filters++;
866         PARA_INFO_LOG("%s filter %d: %s\n", audio_formats[format], nf,
867                 filter_get(filter_num)->name);
868         return filter_num;
869 }
870
871 static int parse_writer_args(void)
872 {
873         int i, ret;
874         const char *cmd;
875         struct audio_format_info *a;
876
877         for (i = 0; i < conf.writer_given; i++) {
878                 void *wconf;
879                 int j, nw, writer_num, af_mask;
880
881                 ret = parse_stream_command(conf.writer_arg[i], &cmd);
882                 if (ret < 0)
883                         return ret;
884                 af_mask = ret;
885                 FOR_EACH_AUDIO_FORMAT(j) {
886                         a = afi + j;
887                         if ((af_mask & (1 << j)) == 0) /* no match */
888                                 continue;
889                         wconf = check_writer_arg_or_die(cmd, &writer_num);
890                         nw = a->num_writers;
891                         a->writer_nums = para_realloc(a->writer_nums, (nw + 1) * sizeof(int));
892                         a->writer_conf = para_realloc(a->writer_conf, (nw + 1) * sizeof(void *));
893                         a->writer_nums[nw] = writer_num;
894                         a->writer_conf[nw] = wconf;
895                         PARA_INFO_LOG("%s writer #%d: %s\n", audio_formats[j],
896                                 nw, writer_names[writer_num]);
897                         a->num_writers++;
898                 }
899         }
900         /* Use default writer for audio formats which are not yet set up. */
901         FOR_EACH_AUDIO_FORMAT(i) {
902                 void *writer_conf;
903                 int writer_num;
904                 a = afi + i;
905                 if (a->num_writers > 0)
906                         continue; /* already set up */
907                 writer_conf = check_writer_arg_or_die(NULL, &writer_num);
908                 a->writer_nums = para_malloc(sizeof(int));
909                 a->writer_nums[0] = writer_num;
910                 a->writer_conf = para_malloc(sizeof(void *));
911                 a->writer_conf[0] = writer_conf;
912                 a->num_writers = 1;
913                 PARA_INFO_LOG("%s writer: %s (default)\n", audio_formats[i],
914                         writer_names[writer_num]);
915         }
916         return 1;
917 }
918
919 static int parse_receiver_args(void)
920 {
921         int i, ret;
922         const char *arg;
923         struct audio_format_info *a;
924
925         FOR_EACH_AUDIO_FORMAT(i)
926                 afi[i].receiver_num = -1;
927         for (i = conf.receiver_given - 1; i >= 0; i--) {
928                 int j, af_mask;
929
930                 ret = parse_stream_command(conf.receiver_arg[i], &arg);
931                 if (ret < 0)
932                         goto out;
933                 af_mask = ret;
934                 FOR_EACH_AUDIO_FORMAT(j) {
935                         a = afi + j;
936                         if ((af_mask & (1 << j)) == 0) /* no match */
937                                 continue;
938                         /*
939                          * If multiple receivers are given for this audio format, the
940                          * last one wins and we have to free the previous receiver
941                          * config here. Since we are iterating backwards, the winning
942                          * receiver arg is in fact the first one given.
943                          */
944                         lls_free_parse_result(a->receiver_lpr, RECEIVER_CMD(a));
945                         a->receiver_num = check_receiver_arg(arg, &a->receiver_lpr);
946                 }
947         }
948         /*
949          * Use the default receiver for those audio formats for which no
950          * receiver was specified.
951          */
952         FOR_EACH_AUDIO_FORMAT(i) {
953                 a = afi + i;
954                 if (a->receiver_num >= 0)
955                         continue;
956                 a->receiver_num = check_receiver_arg(NULL, &a->receiver_lpr);
957         }
958         FOR_EACH_AUDIO_FORMAT(i) {
959                 a = afi + i;
960                 PARA_INFO_LOG("receiving %s streams via %s receiver\n",
961                         audio_formats[i], lls_command_name(RECEIVER_CMD(a)));
962         }
963         ret = 1;
964 out:
965         return ret;
966 }
967
968 static int init_default_filters(void)
969 {
970         int i, ret = 1;
971
972         FOR_EACH_AUDIO_FORMAT(i) {
973                 struct audio_format_info *a = &afi[i];
974                 const char *name = lls_command_name(RECEIVER_CMD(a));
975                 char *tmp;
976                 int j;
977
978                 if (a->num_filters)
979                         continue; /* no default -- nothing to to */
980                 /*
981                  * udp and dccp streams are fec-encoded, so add fecdec as the
982                  * first filter.
983                  */
984                 if (strcmp(name, "udp") == 0 || strcmp(name, "dccp") == 0) {
985                         tmp = para_strdup("fecdec");
986                         add_filter(i, tmp);
987                         free(tmp);
988                         if (ret < 0)
989                                 goto out;
990                 }
991                 /* add "dec" to audio format name */
992                 tmp = make_message("%sdec", audio_formats[i]);
993                 for (j = 0; filter_get(j); j++)
994                         if (!strcmp(tmp, filter_get(j)->name))
995                                 break;
996                 free(tmp);
997                 ret = -E_UNSUPPORTED_FILTER;
998                 if (!filter_get(j))
999                         goto out;
1000                 tmp = para_strdup(filter_get(j)->name);
1001                 ret = add_filter(i, tmp);
1002                 free(tmp);
1003                 if (ret < 0)
1004                         goto out;
1005                 PARA_INFO_LOG("%s -> default filter: %s\n", audio_formats[i],
1006                         filter_get(j)->name);
1007         }
1008 out:
1009         return ret;
1010 }
1011
1012 static int parse_filter_args(void)
1013 {
1014         int i, j, ret, af_mask, num_matches;
1015
1016         for (i = 0; i < conf.filter_given; i++) {
1017                 const char *arg;
1018                 ret = parse_stream_command(conf.filter_arg[i], &arg);
1019                 if (ret < 0)
1020                         goto out;
1021                 af_mask = ret;
1022                 num_matches = 0;
1023                 FOR_EACH_AUDIO_FORMAT(j) {
1024                         if ((af_mask & (1 << j)) == 0) /* no match */
1025                                 continue;
1026                         ret = add_filter(j, arg);
1027                         if (ret < 0)
1028                                 goto out;
1029                         num_matches++;
1030                 }
1031                 if (num_matches == 0)
1032                         PARA_WARNING_LOG("ignoring filter spec: %s\n",
1033                                 conf.filter_arg[i]);
1034         }
1035         ret = init_default_filters(); /* use default values for the rest */
1036 out:
1037         return ret;
1038 }
1039
1040 static int parse_stream_args(void)
1041 {
1042         int ret;
1043
1044         ret = parse_receiver_args();
1045         if (ret < 0)
1046                 return ret;
1047         ret = parse_filter_args();
1048         if (ret < 0)
1049                 return ret;
1050         ret = parse_writer_args();
1051         if (ret < 0)
1052                 return ret;
1053         return 1;
1054 }
1055
1056 /* does not unlink socket on errors */
1057 static void init_local_sockets(struct command_task *ct)
1058 {
1059         if (conf.socket_given)
1060                 socket_name = para_strdup(conf.socket_arg);
1061         else {
1062                 char *hn = para_hostname();
1063                 socket_name = make_message("/var/paraslash/audiod_socket.%s",
1064                         hn);
1065                 free(hn);
1066         }
1067         PARA_NOTICE_LOG("local socket: %s\n", socket_name);
1068         if (conf.force_given)
1069                 unlink(socket_name);
1070         ct->fd[0] = create_local_socket(socket_name, 0);
1071         ct->fd[1] = create_local_socket(socket_name,
1072                 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
1073         if (ct->fd[0] >= 0 || ct->fd[1] >= 0)
1074                 return;
1075         PARA_EMERG_LOG("%s\n", para_strerror(-ct->fd[1]));
1076         exit(EXIT_FAILURE);
1077 }
1078
1079 static int signal_post_select(struct sched *s, void *context)
1080 {
1081         struct signal_task *st = context;
1082         int ret, signum;
1083
1084         ret = task_get_notification(st->task);
1085         if (ret < 0)
1086                 return ret;
1087         signum = para_next_signal(&s->rfds);
1088         switch (signum) {
1089         case SIGINT:
1090         case SIGTERM:
1091         case SIGHUP:
1092                 PARA_NOTICE_LOG("received signal %d\n", signum);
1093                 task_notify_all(s, E_AUDIOD_SIGNAL);
1094                 return -E_AUDIOD_SIGNAL;
1095         }
1096         return 0;
1097 }
1098
1099 static void command_pre_select(struct sched *s, void *context)
1100 {
1101         struct command_task *ct = context;
1102         int i;
1103
1104         for (i = 0; i < 2; i++)
1105                 if (ct->fd[i] >= 0)
1106                         para_fd_set(ct->fd[i], &s->rfds, &s->max_fileno);
1107 }
1108
1109 static int command_post_select(struct sched *s, void *context)
1110 {
1111         int ret, i;
1112         struct command_task *ct = context;
1113         static struct timeval last_status_dump;
1114         struct timeval tmp, delay;
1115         bool force = false;
1116
1117         ret = task_get_notification(ct->task);
1118         if (ret < 0)
1119                 return ret;
1120         for (i = 0; i < 2; i++) {
1121                 if (ct->fd[i] < 0)
1122                         continue;
1123                 ret = handle_connect(ct->fd[i], &s->rfds);
1124                 if (ret < 0) {
1125                         PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1126                         if (ret == -E_AUDIOD_TERM) {
1127                                 task_notify_all(s, -ret);
1128                                 return ret;
1129                         }
1130                 } else if (ret > 0)
1131                         force = true;
1132         }
1133         if (force == true)
1134                 goto dump;
1135
1136         /* if last status dump was less than 500ms ago, do nothing */
1137         delay.tv_sec = 0;
1138         delay.tv_usec = 500 * 1000;
1139         tv_add(&last_status_dump, &delay, &tmp);
1140         if (tv_diff(now, &tmp, NULL) < 0)
1141                 return 0;
1142
1143         /*
1144          * If last status dump was more than 5s ago, force update. Otherwise,
1145          * update only those items that have changed.
1146          */
1147         delay.tv_sec = 5;
1148         delay.tv_usec = 0;
1149         tv_add(&last_status_dump, &delay, &tmp);
1150         if (tv_diff(now, &tmp, NULL) > 0)
1151                 force = true;
1152 dump:
1153         audiod_status_dump(force);
1154         last_status_dump = *now;
1155         return 1;
1156 }
1157
1158 static void init_command_task(struct command_task *ct)
1159 {
1160         init_local_sockets(ct); /* doesn't return on errors */
1161
1162         ct->task = task_register(&(struct task_info) {
1163                 .name = "command",
1164                 .pre_select = command_pre_select,
1165                 .post_select = command_post_select,
1166                 .context = ct,
1167         }, &sched);
1168 }
1169
1170 static void close_stat_pipe(void)
1171 {
1172         if (!stat_task->ct)
1173                 return;
1174         task_reap(&stat_task->ct->task);
1175         client_close(stat_task->ct);
1176         stat_task->ct = NULL;
1177         clear_and_dump_items();
1178         stat_task->length_seconds = 0;
1179         stat_task->offset_seconds = 0;
1180         stat_task->vss_status = 0;
1181         stat_task->current_audio_format_num = -1;
1182         audiod_status_dump(true);
1183 }
1184
1185 /* avoid busy loop if server is down */
1186 static void set_stat_task_restart_barrier(unsigned seconds)
1187 {
1188         struct timeval delay = {seconds, 0};
1189         tv_add(now, &delay, &stat_task->restart_barrier);
1190 }
1191
1192 static bool must_close_slot(int slot_num)
1193 {
1194         struct slot_info *s = &slot[slot_num];
1195         struct audio_format_info *a = afi + s->format;
1196         int i;
1197
1198         if (s->format < 0)
1199                 return false;
1200         if (s->receiver_node && task_status(s->receiver_node->task) >= 0)
1201                 return false;
1202         for (i = 0; i < a->num_filters; i++)
1203                 if (s->fns && task_status(s->fns[i].task) >= 0)
1204                         return false;
1205         if (a->num_writers > 0) {
1206                 for (i = 0; i < a->num_writers; i++)
1207                         if (s->wns && task_status(s->wns[i].task) >= 0)
1208                                 return false;
1209         } else {
1210                 if (s->wns && task_status(s->wns[0].task) >= 0)
1211                         return false;
1212         }
1213         return true;
1214 }
1215
1216 static void close_slot(int slot_num)
1217 {
1218         struct slot_info *s = slot + slot_num;
1219
1220         PARA_INFO_LOG("closing slot %d\n", slot_num);
1221         close_writers(s);
1222         close_filters(s);
1223         close_receiver(slot_num);
1224         clear_slot(slot_num);
1225 }
1226
1227 static void close_unused_slots(void)
1228 {
1229         int i;
1230         bool dump = false;
1231
1232         FOR_EACH_SLOT(i)
1233                 if (must_close_slot(i)) {
1234                         close_slot(i);
1235                         dump = true;
1236                 }
1237         if (dump)
1238                 audiod_status_dump(true);
1239 }
1240
1241 /*
1242  * Cleanup all resources.
1243  *
1244  * This performs various cleanups, removes the audiod socket and closes the
1245  * connection to para_server.
1246  */
1247 static void audiod_cleanup(void)
1248 {
1249         if (socket_name)
1250                 unlink(socket_name);
1251         close_stat_pipe();
1252         close_unused_slots();
1253         audiod_cmdline_parser_free(&conf);
1254         close_stat_clients();
1255         free(uid_whitelist);
1256 }
1257
1258 /*
1259  * Check if any receivers/filters/writers need to be started and do so if
1260  * necessary.
1261  */
1262 static void start_stop_decoders(void)
1263 {
1264         int ret;
1265         struct slot_info *sl;
1266
1267         close_unused_slots();
1268         if (audiod_status != AUDIOD_ON ||
1269                         !(stat_task->vss_status & VSS_STATUS_FLAG_PLAYING))
1270                 return notify_receivers(E_NOT_PLAYING);
1271         if (!must_start_decoder())
1272                 return;
1273         ret = open_receiver(stat_task->current_audio_format_num);
1274         if (ret < 0) {
1275                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1276                 return;
1277         }
1278         sl = slot + ret;
1279         open_filters(sl);
1280         open_writers(sl);
1281         activate_grab_clients(&sched);
1282         btr_log_tree(sl->receiver_node->btrn, LL_NOTICE);
1283         audiod_status_dump(true);
1284 }
1285
1286 static void status_pre_select(struct sched *s, void *context)
1287 {
1288         struct status_task *st = context;
1289         int i, ret, cafn = stat_task->current_audio_format_num;
1290
1291         if (must_start_decoder())
1292                 goto min_delay;
1293         FOR_EACH_SLOT(i)
1294                 if (must_close_slot(i))
1295                         goto min_delay;
1296         ret = btr_node_status(st->btrn, st->min_iqs, BTR_NT_LEAF);
1297         if (ret > 0)
1298                 goto min_delay;
1299         if (st->ct && audiod_status == AUDIOD_OFF)
1300                 goto min_delay;
1301         if (!st->ct && audiod_status != AUDIOD_OFF)
1302                 sched_request_barrier_or_min_delay(&st->restart_barrier, s);
1303         if (cafn >= 0)
1304                 sched_request_barrier(&afi[cafn].restart_barrier, s);
1305         /*
1306          * If para_server is playing we'd like to have a smooth time display
1307          * even if we are running in standby mode. So we request a timeout that
1308          * expires at the next full second.
1309          */
1310         if (stat_task->vss_status & VSS_STATUS_FLAG_PLAYING)
1311                 sched_request_timeout_ms(1000 - now->tv_usec / 1000, s);
1312         return;
1313 min_delay:
1314         sched_min_delay(s);
1315 }
1316
1317 /* restart the client task if necessary */
1318 static int status_post_select(struct sched *s, void *context)
1319 {
1320         struct status_task *st = context;
1321         int ret;
1322
1323         ret = task_get_notification(st->task);
1324         if (ret < 0)
1325                 return ret;
1326         if (audiod_status == AUDIOD_OFF) {
1327                 if (!st->ct)
1328                         goto out;
1329                 if (task_status(st->ct->task) >= 0) {
1330                         task_notify(st->ct->task, E_AUDIOD_OFF);
1331                         goto out;
1332                 }
1333                 close_stat_pipe();
1334                 st->clock_diff_count = conf.clock_diff_count_arg;
1335                 goto out;
1336         }
1337         if (st->ct) {
1338                 char *buf;
1339                 size_t sz;
1340
1341                 ret = btr_node_status(st->btrn, st->min_iqs, BTR_NT_LEAF);
1342                 if (ret < 0) {
1343                         close_stat_pipe();
1344                         goto out;
1345                 }
1346                 if (st->ct->status != CL_EXECUTING)
1347                         goto out;
1348                 if (ret == 0) {
1349                         struct timeval diff;
1350                         tv_diff(now, &st->last_status_read, &diff);
1351                         if (diff.tv_sec > 61)
1352                                 task_notify(st->ct->task, E_STATUS_TIMEOUT);
1353                         goto out;
1354                 }
1355                 btr_merge(st->btrn, st->min_iqs);
1356                 sz = btr_next_buffer(st->btrn, &buf);
1357                 ret = for_each_stat_item(buf, sz, update_item);
1358                 if (ret < 0) {
1359                         task_notify(st->ct->task, -ret);
1360                         goto out;
1361                 }
1362                 if (sz != ret) {
1363                         btr_consume(st->btrn, sz - ret);
1364                         st->last_status_read = *now;
1365                         st->min_iqs = 0;
1366                 } else /* current status item crosses buffers */
1367                         st->min_iqs = sz + 1;
1368                 goto out;
1369         }
1370         btr_drain(st->btrn);
1371         st->current_audio_format_num = -1;
1372         if (tv_diff(now, &st->restart_barrier, NULL) < 0)
1373                 goto out;
1374         if (st->clock_diff_count) { /* get status only one time */
1375                 char *argv[] = {"audiod", "--", "stat", "-p", "-n=1", NULL};
1376                 int argc = 5;
1377                 PARA_INFO_LOG("clock diff count: %u\n", st->clock_diff_count);
1378                 st->clock_diff_count--;
1379                 client_open(argc, argv, &st->ct, NULL, NULL, st->btrn, s);
1380                 set_stat_task_restart_barrier(2);
1381
1382         } else {
1383                 char *argv[] = {"audiod", "--", "stat", "-p", NULL};
1384                 int argc = 4;
1385                 client_open(argc, argv, &st->ct, NULL, NULL, st->btrn, s);
1386                 set_stat_task_restart_barrier(5);
1387         }
1388         free(stat_item_values[SI_BASENAME]);
1389         stat_item_values[SI_BASENAME] = para_strdup(
1390                 "no connection to para_server");
1391         stat_client_write_item(SI_BASENAME);
1392         st->last_status_read = *now;
1393 out:
1394         start_stop_decoders();
1395         return 0;
1396 }
1397
1398 static void init_status_task(struct status_task *st)
1399 {
1400         memset(st, 0, sizeof(struct status_task));
1401         st->sa_time_diff_sign = 1;
1402         st->clock_diff_count = conf.clock_diff_count_arg;
1403         st->current_audio_format_num = -1;
1404         st->btrn = btr_new_node(&(struct btr_node_description)
1405                 EMBRACE(.name = "stat"));
1406
1407         stat_task->task = task_register(&(struct task_info) {
1408                 .name = "stat",
1409                 .pre_select = status_pre_select,
1410                 .post_select = status_post_select,
1411                 .context = stat_task,
1412         }, &sched);
1413 }
1414
1415 static void set_initial_status(void)
1416 {
1417         audiod_status = AUDIOD_ON;
1418         if (!conf.mode_given)
1419                 return;
1420         if (!strcmp(conf.mode_arg, "sb")) {
1421                 audiod_status = AUDIOD_STANDBY;
1422                 return;
1423         }
1424         if (!strcmp(conf.mode_arg, "off")) {
1425                 audiod_status = AUDIOD_OFF;
1426                 return;
1427         }
1428         if (strcmp(conf.mode_arg, "on"))
1429                 PARA_WARNING_LOG("invalid mode\n");
1430 }
1431
1432 __noreturn static void print_help_and_die(void)
1433 {
1434         struct ggo_help h = DEFINE_GGO_HELP(audiod);
1435         bool d = conf.detailed_help_given;
1436         unsigned flags;
1437
1438         flags = d? GPH_STANDARD_FLAGS_DETAILED : GPH_STANDARD_FLAGS;
1439         ggo_print_help(&h, flags);
1440
1441         flags = d? GPH_MODULE_FLAGS_DETAILED : GPH_MODULE_FLAGS;
1442         print_receiver_helps(flags);
1443         print_filter_helps(flags);
1444         print_writer_helps(flags);
1445         exit(0);
1446 }
1447
1448 /**
1449  * Lookup the given UID in the whitelist.
1450  *
1451  * The whitelist is the array of arguments to the --user-allow opion. If the
1452  * option was not given, the array is empty, in which case the check succeeds.
1453  *
1454  * \param uid User ID to look up.
1455  *
1456  * \return True if --user-allow was not given, or if uid matches an element of
1457  * the whitelist.
1458  */
1459 bool uid_is_whitelisted(uid_t uid)
1460 {
1461         int i;
1462
1463         if (!conf.user_allow_given)
1464                 return true;
1465         for (i = 0; i < conf.user_allow_given; i++)
1466                 if (uid == uid_whitelist[i])
1467                         return true;
1468         return false;
1469 }
1470
1471 /**
1472  * the main function of para_audiod
1473  *
1474  * \param argc usual argument count
1475  * \param argv usual argument vector
1476  *
1477  * \return EXIT_SUCCESS or EXIT_FAILURE
1478  *
1479  * \sa para_audiod(1)
1480  * */
1481 int main(int argc, char *argv[])
1482 {
1483         int ret, i;
1484         struct command_task command_task_struct, *cmd_task = &command_task_struct;
1485         struct audiod_cmdline_parser_params params = {
1486                 .override = 0,
1487                 .initialize = 1,
1488                 .check_required = 0,
1489                 .check_ambiguity = 0,
1490                 .print_errors = 1
1491         };
1492
1493         valid_fd_012();
1494         audiod_cmdline_parser_ext(argc, argv, &conf, &params);
1495         daemon_set_loglevel(conf.loglevel_arg);
1496         version_handle_flag("audiod", conf.version_given);
1497         /* init receivers/filters/writers early to make help work */
1498         recv_init();
1499         filter_init();
1500         writer_init();
1501         if (conf.help_given || conf.detailed_help_given)
1502                 print_help_and_die();
1503         daemon_set_priority(conf.priority_arg);
1504         daemon_drop_privileges_or_die(conf.user_arg, conf.group_arg);
1505         parse_config_or_die();
1506         if (daemon_init_colors_or_die(conf.color_arg, color_arg_auto, color_arg_no,
1507                 conf.logfile_given)) {
1508                         for (i = 0; i < conf.log_color_given; i++)
1509                                 daemon_set_log_color_or_die(conf.log_color_arg[i]);
1510         }
1511         init_random_seed_or_die();
1512         daemon_set_flag(DF_LOG_TIME);
1513         daemon_set_flag(DF_LOG_HOSTNAME);
1514         daemon_set_flag(DF_LOG_LL);
1515         if (conf.log_timing_given)
1516                 daemon_set_flag(DF_LOG_TIMING);
1517         if (conf.logfile_given) {
1518                 daemon_set_logfile(conf.logfile_arg);
1519                 daemon_open_log_or_die();
1520         }
1521         ret = parse_stream_args();
1522         if (ret < 0) {
1523                 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1524                 exit(EXIT_FAILURE);
1525         }
1526         daemon_log_welcome("audiod");
1527         daemon_set_start_time();
1528         set_initial_status();
1529         FOR_EACH_SLOT(i)
1530                 clear_slot(i);
1531         setup_signal_handling();
1532
1533         init_status_task(stat_task);
1534         init_command_task(cmd_task);
1535
1536         if (conf.daemon_given)
1537                 daemonize(false /* parent exits immediately */);
1538
1539         signal_task->task = task_register(&(struct task_info) {
1540                 .name = "signal",
1541                 .pre_select = signal_pre_select,
1542                 .post_select = signal_post_select,
1543                 .context = signal_task,
1544         }, &sched);
1545
1546         sched.default_timeout.tv_sec = 2;
1547         sched.default_timeout.tv_usec = 999 * 1000;
1548         ret = schedule(&sched);
1549         audiod_cleanup();
1550         sched_shutdown(&sched);
1551         signal_shutdown(signal_task);
1552
1553         if (ret < 0)
1554                 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1555         return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;
1556 }