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