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