Merge branch 'refs/heads/t/rm_v1_moods'
[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 = para_malloc(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         stat_task->current_audio_format_num = -1;
449         tv_add(now, &(struct timeval)EMBRACE(0, 200 * 1000),
450                 &a->restart_barrier);
451 }
452
453 static void writer_cleanup(struct writer_node *wn)
454 {
455         if (!wn)
456                 return;
457         PARA_INFO_LOG("closing %s\n", writer_name(wn->wid));
458         writer_get(wn->wid)->close(wn);
459         btr_remove_node(&wn->btrn);
460         task_reap(&wn->task);
461 }
462
463 static void close_writers(struct slot_info *s)
464 {
465         struct audio_format_info *a;
466         int i;
467
468         if (s->format < 0)
469                 return;
470         assert(s->wns);
471         a = afi + s->format;
472         if (a->num_writers == 0)
473                 writer_cleanup(s->wns);
474         else {
475                 for (i = 0; i < a->num_writers; i++)
476                         writer_cleanup(s->wns + i);
477         }
478         free(s->wns);
479         s->wns = NULL;
480 }
481
482 static void close_filters(struct slot_info *s)
483 {
484         int i;
485         struct audio_format_info *a = afi + s->format;
486         if (a->num_filters == 0)
487                 return;
488         for (i = a->num_filters - 1; i >= 0; i--) {
489                 struct filter_node *fn = s->fns + i;
490                 const struct filter *f;
491
492                 if (!fn)
493                         continue;
494                 f = filter_get(fn->filter_num);
495                 if (f->close)
496                         f->close(fn);
497                 btr_remove_node(&fn->btrn);
498                 task_reap(&fn->task);
499         }
500         free(s->fns);
501         s->fns = NULL;
502 }
503
504 static void notify_receivers(int error)
505 {
506         int i;
507
508         FOR_EACH_SLOT(i) {
509                 struct slot_info *s = slot + i;
510                 if (s->format < 0)
511                         continue;
512                 if (!s->receiver_node)
513                         continue;
514                 task_notify(s->receiver_node->task, error);
515         }
516 }
517
518 static int get_empty_slot(void)
519 {
520         int i;
521         struct slot_info *s;
522
523         FOR_EACH_SLOT(i) {
524                 s = &slot[i];
525                 if (s->format < 0) {
526                         clear_slot(i);
527                         return i;
528                 }
529                 if (s->wns || s->receiver_node || s->fns)
530                         continue;
531                 clear_slot(i);
532                 return i;
533         }
534         return -E_NO_MORE_SLOTS;
535 }
536
537 static void open_filters(struct slot_info *s)
538 {
539         struct audio_format_info *a = afi + s->format;
540         struct filter_node *fn;
541         int nf = a->num_filters;
542         struct btr_node *parent;
543         int i;
544
545         if (nf == 0)
546                 return;
547         PARA_INFO_LOG("opening %s filters\n", audio_formats[s->format]);
548         assert(s->fns == NULL);
549         s->fns = para_calloc(nf * sizeof(struct filter_node));
550         parent = s->receiver_node->btrn;
551         for (i = 0; i < nf; i++) {
552                 char buf[20];
553                 const char *name;
554                 const struct filter *f = filter_get(a->filter_nums[i]);
555                 fn = s->fns + i;
556                 fn->filter_num = a->filter_nums[i];
557                 fn->conf = a->filter_conf[i];
558                 fn->lpr = a->filter_lpr[i];
559                 name = filter_name(fn->filter_num);
560                 fn->btrn = btr_new_node(&(struct btr_node_description)
561                         EMBRACE(.name = name, .parent = parent,
562                                 .handler = f->execute, .context = fn));
563
564                 if (f->open)
565                         f->open(fn);
566                 sprintf(buf, "%s (slot %d)", name, (int)(s - slot));
567                 fn->task = task_register(&(struct task_info) {
568                         .name = buf,
569                         .pre_select = f->pre_select,
570                         .post_select = f->post_select,
571                         .context = fn,
572                 }, &sched);
573                 parent = fn->btrn;
574                 PARA_NOTICE_LOG("%s filter %d/%d (%s) started in slot %d\n",
575                         audio_formats[s->format], i,  nf, name, (int)(s - slot));
576         }
577 }
578
579 static void open_writers(struct slot_info *s)
580 {
581         int i;
582         struct audio_format_info *a = afi + s->format;
583         struct writer_node *wn;
584         struct btr_node *parent = s->fns[a->num_filters - 1].btrn;
585
586         assert(s->wns == NULL);
587         s->wns = para_calloc(PARA_MAX(1U, a->num_writers)
588                 * sizeof(struct writer_node));
589         for (i = 0; i < a->num_writers; i++) {
590                 wn = s->wns + i;
591                 wn->wid = a->wids[i];
592                 wn->lpr = a->writer_lpr[i];
593                 register_writer_node(wn, parent, &sched);
594                 PARA_NOTICE_LOG("%s writer started in slot %d\n",
595                         writer_name(a->wids[i]), (int)(s - slot));
596         }
597 }
598
599 /* returns slot num on success */
600 static int open_receiver(int format)
601 {
602         struct audio_format_info *a = &afi[format];
603         struct slot_info *s;
604         int ret, slot_num;
605         const struct receiver *r = RECEIVER(a);
606         const char *name = lls_command_name(RECEIVER_CMD(a));
607         struct receiver_node *rn;
608
609         tv_add(now, &(struct timeval)EMBRACE(2, 0), &a->restart_barrier);
610         ret = get_empty_slot();
611         if (ret < 0)
612                 return ret;
613         slot_num = ret;
614         rn = para_calloc(sizeof(*rn));
615         rn->receiver = r;
616         rn->lpr = a->receiver_lpr;
617         rn->btrn = btr_new_node(&(struct btr_node_description)
618                 EMBRACE(.name = name, .context = rn));
619         ret = r->open(rn);
620         if (ret < 0) {
621                 PARA_ERROR_LOG("could not open %s receiver\n", name);
622                 btr_remove_node(&rn->btrn);
623                 free(rn);
624                 return ret;
625         }
626         s = &slot[slot_num];
627         s->format = format;
628         s->receiver_node = rn;
629         PARA_NOTICE_LOG("started %s: %s receiver in slot %d\n",
630                 audio_formats[format], name, slot_num);
631         rn->task = task_register(&(struct task_info) {
632                 .name = name,
633                 .pre_select = r->pre_select,
634                 .post_select = r->post_select,
635                 .context = rn,
636         }, &sched);
637         return slot_num;
638 }
639
640 static bool receiver_running(void)
641 {
642         int i;
643         long unsigned ss1 = stat_task->server_stream_start.tv_sec;
644
645         FOR_EACH_SLOT(i) {
646                 struct slot_info *s = &slot[i];
647                 long unsigned ss2 = s->server_stream_start.tv_sec;
648
649                 if (!s->receiver_node)
650                         continue;
651                 if (task_status(s->receiver_node->task) >= 0)
652                         return true;
653                 if (ss1 == ss2)
654                         return true;
655         }
656         return false;
657 }
658
659 /**
660  * Return the root node of the current buffer tree.
661  *
662  * This is only used for stream grabbing.
663  *
664  * \return \p NULL if no slot is currently active. If more than one buffer tree
665  * exists, the node corresponding to the most recently started receiver is
666  * returned.
667  */
668 struct btr_node *audiod_get_btr_root(void)
669 {
670         int i, newest_slot = -1;
671         struct timeval newest_rstime = {0, 0};
672
673         FOR_EACH_SLOT(i) {
674                 struct slot_info *s = &slot[i];
675                 struct timeval rstime;
676                 if (!s->receiver_node)
677                         continue;
678                 if (task_status(s->receiver_node->task) < 0)
679                         continue;
680                 btr_get_node_start(s->receiver_node->btrn, &rstime);
681                 if (newest_slot >= 0 && tv_diff(&rstime, &newest_rstime, NULL) < 0)
682                         continue;
683                 newest_rstime = rstime;
684                 newest_slot = i;
685         }
686         if (newest_slot == -1)
687                 return NULL;
688         return slot[newest_slot].receiver_node->btrn;
689 }
690
691 /* whether a new instance of a decoder should be started. */
692 static bool must_start_decoder(void)
693 {
694         int cafn = stat_task->current_audio_format_num;
695         unsigned vs = stat_task->vss_status;
696
697         if (audiod_status != AUDIOD_ON)
698                 return false;
699         if (cafn < 0)
700                 return false;
701         if (!stat_task->ct)
702                 return false;
703         if (vs & VSS_STATUS_FLAG_NEXT)
704                 return false;
705         if (!(vs & VSS_STATUS_FLAG_PLAYING))
706                 return false;
707         if (receiver_running())
708                 return false;
709         if (tv_diff(now, &afi[cafn].restart_barrier, NULL) < 0)
710                 return false;
711         return true;
712 }
713
714 static void compute_time_diff(const struct timeval *status_time)
715 {
716         struct timeval tmp, diff;
717         static unsigned count;
718         int sign, sa_time_diff_sign = stat_task->sa_time_diff_sign;
719         const struct timeval max_deviation = {0, 500 * 1000};
720         const int time_smooth = 5;
721
722         sign = tv_diff(status_time, now, &diff);
723 //              PARA_NOTICE_LOG("%s: sign = %i, sa_time_diff_sign = %i\n", __func__,
724 //                      sign, sa_time_diff_sign);
725         if (!count) {
726                 sa_time_diff_sign = sign;
727                 stat_task->sa_time_diff = diff;
728                 count++;
729                 goto out;
730         }
731         if (count > 5) {
732                 int s = tv_diff(&diff, &stat_task->sa_time_diff, &tmp);
733                 if (tv_diff(&max_deviation, &tmp, NULL) < 0)
734                         PARA_WARNING_LOG("time diff jump: %lums\n",
735                                 s * tv2ms(&tmp));
736         }
737         count++;
738         sa_time_diff_sign = tv_convex_combination(
739                 sa_time_diff_sign * time_smooth, &stat_task->sa_time_diff,
740                 count > 10? sign : sign * time_smooth, &diff,
741                 &tmp);
742         stat_task->sa_time_diff = tmp;
743         PARA_INFO_LOG("time diff (cur/avg): %s%lums/%s%lums\n",
744                 sign < 0? "-" : "+",
745                 tv2ms(&diff),
746                 sa_time_diff_sign < 0? "-" : "+",
747                 tv2ms(&stat_task->sa_time_diff)
748         );
749 out:
750         stat_task->sa_time_diff_sign = sa_time_diff_sign;
751 }
752
753 static int update_item(int itemnum, char *buf)
754 {
755         long unsigned sec, usec;
756
757         if (stat_task->clock_diff_count && itemnum != SI_current_time)
758                 return 1;
759         free(stat_item_values[itemnum]);
760         stat_item_values[itemnum] = para_strdup(buf);
761         stat_client_write_item(itemnum);
762         switch (itemnum) {
763         case SI_status_flags:
764                 stat_task->vss_status = 0;
765                 if (strchr(buf, 'N'))
766                         stat_task->vss_status |= VSS_STATUS_FLAG_NEXT;
767                 if (strchr(buf, 'P'))
768                         stat_task->vss_status |= VSS_STATUS_FLAG_PLAYING;
769                 break;
770         case SI_offset:
771                 stat_task->offset_seconds = atoi(buf);
772                 break;
773         case SI_seconds_total:
774                 stat_task->length_seconds = atoi(buf);
775                 break;
776         case SI_stream_start:
777                 if (sscanf(buf, "%lu.%lu", &sec, &usec) == 2) {
778                         stat_task->server_stream_start.tv_sec = sec;
779                         stat_task->server_stream_start.tv_usec = usec;
780                 }
781                 break;
782         case SI_current_time:
783                 if (sscanf(buf, "%lu.%lu", &sec, &usec) == 2) {
784                         struct timeval tv = {sec, usec};
785                         compute_time_diff(&tv);
786                 }
787                 break;
788         case SI_format:
789                 stat_task->current_audio_format_num
790                         = get_audio_format_num(buf);
791         }
792         return 1;
793 }
794
795 static int parse_stream_command(const char *txt, const char **cmd)
796 {
797         int ret, len;
798         char *re, *p = strchr(txt, ':');
799
800         if (!p)
801                 return -E_MISSING_COLON;
802         *cmd = p + 1;
803         len = p - txt;
804         re = para_malloc(len + 1);
805         strncpy(re, txt, len);
806         re[len] = '\0';
807         ret = get_matching_audio_format_nums(re);
808         free(re);
809         return ret;
810 }
811
812 static int add_filter(int format, const char *cmdline)
813 {
814         struct audio_format_info *a = &afi[format];
815         int filter_num, nf = a->num_filters;
816         void *cfg;
817         struct lls_parse_result *flpr;
818
819         filter_num = filter_setup(cmdline, &cfg, &flpr);
820         a->filter_lpr = para_realloc(a->filter_lpr,
821                 (nf + 1) * sizeof(flpr));
822         a->filter_conf = para_realloc(a->filter_conf,
823                 (nf + 1) * sizeof(void *));
824         a->filter_nums = para_realloc(a->filter_nums,
825                 (nf + 1) * sizeof(unsigned));
826
827         a->filter_nums[nf] = filter_num;
828         a->filter_conf[nf] = cfg;
829         a->filter_lpr[nf] = flpr;
830         a->num_filters++;
831         PARA_INFO_LOG("%s filter %d: %s\n", audio_formats[format], nf,
832                 filter_name(filter_num));
833         return filter_num;
834 }
835
836 static int parse_writer_args(void)
837 {
838         int i, ret;
839         const char *cmd;
840         struct audio_format_info *a;
841
842         for (i = 0; i < OPT_GIVEN(WRITER); i++) {
843                 int j, nw, af_mask;
844
845                 ret = parse_stream_command(lls_string_val(i,
846                         OPT_RESULT(WRITER)), &cmd);
847                 if (ret < 0)
848                         return ret;
849                 af_mask = ret;
850                 FOR_EACH_AUDIO_FORMAT(j) {
851                         a = afi + j;
852                         if ((af_mask & (1 << j)) == 0) /* no match */
853                                 continue;
854                         nw = a->num_writers;
855                         a->wids = para_realloc(a->wids, (nw + 1) * sizeof(int));
856                         a->writer_lpr = para_realloc(a->writer_lpr,
857                                 (nw + 1) * sizeof(struct lls_parse_result *));
858                         a->wids[nw] = check_writer_arg_or_die(cmd,
859                                 a->writer_lpr + nw);
860                         PARA_INFO_LOG("%s writer #%d: %s\n", audio_formats[j],
861                                 nw, writer_name(a->wids[nw]));
862                         a->num_writers++;
863                 }
864         }
865         /* Use default writer for audio formats which are not yet set up. */
866         FOR_EACH_AUDIO_FORMAT(i) {
867                 a = afi + i;
868                 if (a->num_writers > 0)
869                         continue; /* already set up */
870                 a->num_writers = 1;
871                 a->wids = para_malloc(sizeof(int));
872                 a->writer_lpr = para_malloc(sizeof(struct lls_parse_result *));
873                 a->wids[0] = check_writer_arg_or_die(NULL, a->writer_lpr);
874                 PARA_INFO_LOG("%s writer: %s (default)\n", audio_formats[i],
875                         writer_name(a->wids[0]));
876         }
877         return 1;
878 }
879
880 static int parse_receiver_args(void)
881 {
882         int i, ret;
883         const char *arg;
884         struct audio_format_info *a;
885
886         FOR_EACH_AUDIO_FORMAT(i)
887                 afi[i].receiver_num = -1;
888         for (i = OPT_GIVEN(RECEIVER) - 1; i >= 0; i--) {
889                 int j, af_mask;
890
891                 ret = parse_stream_command(lls_string_val(i,
892                         OPT_RESULT(RECEIVER)), &arg);
893                 if (ret < 0)
894                         goto out;
895                 af_mask = ret;
896                 FOR_EACH_AUDIO_FORMAT(j) {
897                         a = afi + j;
898                         if ((af_mask & (1 << j)) == 0) /* no match */
899                                 continue;
900                         /*
901                          * If multiple receivers are given for this audio format, the
902                          * last one wins and we have to free the previous receiver
903                          * config here. Since we are iterating backwards, the winning
904                          * receiver arg is in fact the first one given.
905                          */
906                         lls_free_parse_result(a->receiver_lpr, RECEIVER_CMD(a));
907                         a->receiver_num = check_receiver_arg(arg, &a->receiver_lpr);
908                 }
909         }
910         /*
911          * Use the default receiver for those audio formats for which no
912          * receiver was specified.
913          */
914         FOR_EACH_AUDIO_FORMAT(i) {
915                 a = afi + i;
916                 if (a->receiver_num >= 0)
917                         continue;
918                 a->receiver_num = check_receiver_arg(NULL, &a->receiver_lpr);
919         }
920         FOR_EACH_AUDIO_FORMAT(i) {
921                 a = afi + i;
922                 PARA_INFO_LOG("receiving %s streams via %s receiver\n",
923                         audio_formats[i], lls_command_name(RECEIVER_CMD(a)));
924         }
925         ret = 1;
926 out:
927         return ret;
928 }
929
930 static int init_default_filters(void)
931 {
932         int i, ret = 1;
933
934         FOR_EACH_AUDIO_FORMAT(i) {
935                 struct audio_format_info *a = &afi[i];
936                 const char *name = lls_command_name(RECEIVER_CMD(a));
937                 char *tmp;
938                 int j;
939
940                 if (a->num_filters)
941                         continue; /* no default -- nothing to to */
942                 /*
943                  * udp and dccp streams are fec-encoded, so add fecdec as the
944                  * first filter.
945                  */
946                 if (strcmp(name, "udp") == 0 || strcmp(name, "dccp") == 0) {
947                         tmp = para_strdup("fecdec");
948                         add_filter(i, tmp);
949                         free(tmp);
950                         if (ret < 0)
951                                 goto out;
952                 }
953                 /* add "dec" to audio format name */
954                 tmp = make_message("%sdec", audio_formats[i]);
955                 for (j = 1; filter_get(j); j++)
956                         if (!strcmp(tmp, filter_name(j)))
957                                 break;
958                 free(tmp);
959                 ret = -E_UNSUPPORTED_FILTER;
960                 if (!filter_get(j))
961                         goto out;
962                 tmp = para_strdup(filter_name(j));
963                 ret = add_filter(i, tmp);
964                 free(tmp);
965                 if (ret < 0)
966                         goto out;
967                 PARA_INFO_LOG("%s -> default filter: %s\n", audio_formats[i],
968                         filter_name(j));
969         }
970 out:
971         return ret;
972 }
973
974 static int parse_filter_args(void)
975 {
976         int i, j, ret, af_mask, num_matches;
977
978         for (i = 0; i < OPT_GIVEN(FILTER); i++) {
979                 const char *arg;
980                 ret = parse_stream_command(lls_string_val(i,
981                         OPT_RESULT(FILTER)), &arg);
982                 if (ret < 0)
983                         goto out;
984                 af_mask = ret;
985                 num_matches = 0;
986                 FOR_EACH_AUDIO_FORMAT(j) {
987                         if ((af_mask & (1 << j)) == 0) /* no match */
988                                 continue;
989                         ret = add_filter(j, arg);
990                         if (ret < 0)
991                                 goto out;
992                         num_matches++;
993                 }
994                 if (num_matches == 0)
995                         PARA_WARNING_LOG("ignoring filter spec: %s\n",
996                                 lls_string_val(i, OPT_RESULT(FILTER)));
997         }
998         ret = init_default_filters(); /* use default values for the rest */
999 out:
1000         return ret;
1001 }
1002
1003 static int parse_stream_args(void)
1004 {
1005         int ret;
1006
1007         ret = parse_receiver_args();
1008         if (ret < 0)
1009                 return ret;
1010         ret = parse_filter_args();
1011         if (ret < 0)
1012                 return ret;
1013         ret = parse_writer_args();
1014         if (ret < 0)
1015                 return ret;
1016         return 1;
1017 }
1018
1019 /* does not unlink socket on errors */
1020 static void init_local_socket(struct command_task *ct)
1021 {
1022         if (OPT_GIVEN(SOCKET))
1023                 socket_name = para_strdup(OPT_STRING_VAL(SOCKET));
1024         else {
1025                 char *hn = para_hostname();
1026                 socket_name = make_message("/var/paraslash/audiod_socket.%s",
1027                         hn);
1028                 free(hn);
1029         }
1030         PARA_NOTICE_LOG("local socket: %s\n", socket_name);
1031         if (OPT_GIVEN(FORCE))
1032                 unlink(socket_name);
1033         ct->fd = create_local_socket(socket_name);
1034         if (ct->fd >= 0)
1035                 return;
1036         PARA_EMERG_LOG("%s\n", para_strerror(-ct->fd));
1037         exit(EXIT_FAILURE);
1038 }
1039
1040 static int signal_post_select(struct sched *s, void *context)
1041 {
1042         struct signal_task *st = context;
1043         int ret, signum;
1044
1045         ret = task_get_notification(st->task);
1046         if (ret < 0)
1047                 return ret;
1048         signum = para_next_signal(&s->rfds);
1049         switch (signum) {
1050         case SIGINT:
1051         case SIGTERM:
1052         case SIGHUP:
1053                 PARA_NOTICE_LOG("received signal %d\n", signum);
1054                 task_notify_all(s, E_AUDIOD_SIGNAL);
1055                 return -E_AUDIOD_SIGNAL;
1056         }
1057         return 0;
1058 }
1059
1060 static void command_pre_select(struct sched *s, void *context)
1061 {
1062         struct command_task *ct = context;
1063         para_fd_set(ct->fd, &s->rfds, &s->max_fileno);
1064 }
1065
1066 static int command_post_select(struct sched *s, void *context)
1067 {
1068         int ret;
1069         struct command_task *ct = context;
1070         static struct timeval last_status_dump;
1071         struct timeval tmp, delay;
1072         bool force = false;
1073
1074         ret = task_get_notification(ct->task);
1075         if (ret < 0)
1076                 return ret;
1077         ret = handle_connect(ct->fd, &s->rfds);
1078         if (ret < 0) {
1079                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1080                 if (ret == -E_AUDIOD_TERM) {
1081                         task_notify_all(s, -ret);
1082                         return ret;
1083                 }
1084         } else if (ret > 0)
1085                 force = true;
1086         if (force == true)
1087                 goto dump;
1088
1089         /* if last status dump was less than 500ms ago, do nothing */
1090         delay.tv_sec = 0;
1091         delay.tv_usec = 500 * 1000;
1092         tv_add(&last_status_dump, &delay, &tmp);
1093         if (tv_diff(now, &tmp, NULL) < 0)
1094                 return 0;
1095
1096         /*
1097          * If last status dump was more than 5s ago, force update. Otherwise,
1098          * update only those items that have changed.
1099          */
1100         delay.tv_sec = 5;
1101         delay.tv_usec = 0;
1102         tv_add(&last_status_dump, &delay, &tmp);
1103         if (tv_diff(now, &tmp, NULL) > 0)
1104                 force = true;
1105 dump:
1106         audiod_status_dump(force);
1107         last_status_dump = *now;
1108         return 1;
1109 }
1110
1111 static void init_command_task(struct command_task *ct)
1112 {
1113         init_local_socket(ct); /* doesn't return on errors */
1114
1115         ct->task = task_register(&(struct task_info) {
1116                 .name = "command",
1117                 .pre_select = command_pre_select,
1118                 .post_select = command_post_select,
1119                 .context = ct,
1120         }, &sched);
1121 }
1122
1123 static void close_stat_pipe(void)
1124 {
1125         if (!stat_task->ct)
1126                 return;
1127         task_reap(&stat_task->ct->task);
1128         client_close(stat_task->ct);
1129         stat_task->ct = NULL;
1130         clear_and_dump_items();
1131         stat_task->length_seconds = 0;
1132         stat_task->offset_seconds = 0;
1133         stat_task->vss_status = 0;
1134         stat_task->current_audio_format_num = -1;
1135         audiod_status_dump(true);
1136 }
1137
1138 /* avoid busy loop if server is down */
1139 static void set_stat_task_restart_barrier(unsigned seconds)
1140 {
1141         struct timeval delay = {seconds, 0};
1142         tv_add(now, &delay, &stat_task->restart_barrier);
1143 }
1144
1145 static bool must_close_slot(int slot_num)
1146 {
1147         struct slot_info *s = &slot[slot_num];
1148         struct audio_format_info *a = afi + s->format;
1149         int i;
1150
1151         if (s->format < 0)
1152                 return false;
1153         if (s->receiver_node && task_status(s->receiver_node->task) >= 0)
1154                 return false;
1155         for (i = 0; i < a->num_filters; i++)
1156                 if (s->fns && task_status(s->fns[i].task) >= 0)
1157                         return false;
1158         if (a->num_writers > 0) {
1159                 for (i = 0; i < a->num_writers; i++)
1160                         if (s->wns && task_status(s->wns[i].task) >= 0)
1161                                 return false;
1162         } else {
1163                 if (s->wns && task_status(s->wns[0].task) >= 0)
1164                         return false;
1165         }
1166         return true;
1167 }
1168
1169 static void close_slot(int slot_num)
1170 {
1171         struct slot_info *s = slot + slot_num;
1172
1173         PARA_INFO_LOG("closing slot %d\n", slot_num);
1174         close_writers(s);
1175         close_filters(s);
1176         close_receiver(slot_num);
1177         clear_slot(slot_num);
1178 }
1179
1180 static void close_unused_slots(void)
1181 {
1182         int i;
1183         bool dump = false;
1184
1185         FOR_EACH_SLOT(i)
1186                 if (must_close_slot(i)) {
1187                         close_slot(i);
1188                         dump = true;
1189                 }
1190         if (dump)
1191                 audiod_status_dump(true);
1192 }
1193
1194 /*
1195  * Cleanup all resources.
1196  *
1197  * This performs various cleanups, removes the audiod socket and closes the
1198  * connection to para_server.
1199  */
1200 static void audiod_cleanup(void)
1201 {
1202         if (socket_name)
1203                 unlink(socket_name);
1204         close_stat_pipe();
1205         close_unused_slots();
1206         close_stat_clients();
1207         free(uid_whitelist);
1208 }
1209
1210 /*
1211  * Check if any receivers/filters/writers need to be started and do so if
1212  * necessary.
1213  */
1214 static void start_stop_decoders(void)
1215 {
1216         int ret;
1217         struct slot_info *sl;
1218
1219         close_unused_slots();
1220         if (audiod_status != AUDIOD_ON ||
1221                         !(stat_task->vss_status & VSS_STATUS_FLAG_PLAYING))
1222                 return notify_receivers(E_NOT_PLAYING);
1223         if (!must_start_decoder())
1224                 return;
1225         ret = open_receiver(stat_task->current_audio_format_num);
1226         if (ret < 0) {
1227                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
1228                 return;
1229         }
1230         sl = slot + ret;
1231         open_filters(sl);
1232         open_writers(sl);
1233         activate_grab_clients(&sched);
1234         btr_log_tree(sl->receiver_node->btrn, LL_NOTICE);
1235         audiod_status_dump(true);
1236 }
1237
1238 static void status_pre_select(struct sched *s, void *context)
1239 {
1240         struct status_task *st = context;
1241         int i, ret, cafn = stat_task->current_audio_format_num;
1242
1243         if (must_start_decoder())
1244                 goto min_delay;
1245         FOR_EACH_SLOT(i)
1246                 if (must_close_slot(i))
1247                         goto min_delay;
1248         ret = btr_node_status(st->btrn, st->min_iqs, BTR_NT_LEAF);
1249         if (ret > 0)
1250                 goto min_delay;
1251         if (st->ct && audiod_status == AUDIOD_OFF)
1252                 goto min_delay;
1253         if (!st->ct && audiod_status != AUDIOD_OFF)
1254                 sched_request_barrier_or_min_delay(&st->restart_barrier, s);
1255         if (cafn >= 0)
1256                 sched_request_barrier(&afi[cafn].restart_barrier, s);
1257         /*
1258          * If para_server is playing we'd like to have a smooth time display
1259          * even if we are running in standby mode. So we request a timeout that
1260          * expires at the next full second.
1261          */
1262         if (stat_task->vss_status & VSS_STATUS_FLAG_PLAYING)
1263                 sched_request_timeout_ms(1000 - now->tv_usec / 1000, s);
1264         return;
1265 min_delay:
1266         sched_min_delay(s);
1267 }
1268
1269 /* restart the client task if necessary */
1270 static int status_post_select(struct sched *s, void *context)
1271 {
1272         struct status_task *st = context;
1273         int ret;
1274
1275         ret = task_get_notification(st->task);
1276         if (ret < 0)
1277                 return ret;
1278         if (audiod_status == AUDIOD_OFF) {
1279                 if (!st->ct)
1280                         goto out;
1281                 if (task_status(st->ct->task) >= 0) {
1282                         task_notify(st->ct->task, E_AUDIOD_OFF);
1283                         goto out;
1284                 }
1285                 close_stat_pipe();
1286                 st->clock_diff_count = OPT_UINT32_VAL(CLOCK_DIFF_COUNT);
1287                 goto out;
1288         }
1289         if (st->ct) {
1290                 char *buf;
1291                 size_t sz;
1292
1293                 ret = btr_node_status(st->btrn, st->min_iqs, BTR_NT_LEAF);
1294                 if (ret < 0) {
1295                         close_stat_pipe();
1296                         goto out;
1297                 }
1298                 if (st->ct->status != CL_EXECUTING)
1299                         goto out;
1300                 if (ret == 0) {
1301                         struct timeval diff;
1302                         tv_diff(now, &st->last_status_read, &diff);
1303                         if (diff.tv_sec > 61)
1304                                 task_notify(st->ct->task, E_STATUS_TIMEOUT);
1305                         goto out;
1306                 }
1307                 btr_merge(st->btrn, st->min_iqs);
1308                 sz = btr_next_buffer(st->btrn, &buf);
1309                 ret = for_each_stat_item(buf, sz, update_item);
1310                 if (ret < 0) {
1311                         task_notify(st->ct->task, -ret);
1312                         goto out;
1313                 }
1314                 if (sz != ret) {
1315                         btr_consume(st->btrn, sz - ret);
1316                         st->last_status_read = *now;
1317                         st->min_iqs = 0;
1318                 } else /* current status item crosses buffers */
1319                         st->min_iqs = sz + 1;
1320                 goto out;
1321         }
1322         btr_drain(st->btrn);
1323         st->current_audio_format_num = -1;
1324         if (tv_diff(now, &st->restart_barrier, NULL) < 0)
1325                 goto out;
1326         if (st->clock_diff_count) { /* get status only one time */
1327                 char *argv[] = {"audiod", "--", "stat", "-p", "-n=1", NULL};
1328                 int argc = 5;
1329                 PARA_INFO_LOG("clock diff count: %u\n", st->clock_diff_count);
1330                 st->clock_diff_count--;
1331                 client_open(argc, argv, &st->ct, NULL, NULL, st->btrn, s);
1332                 set_stat_task_restart_barrier(2);
1333
1334         } else {
1335                 char *argv[] = {"audiod", "--", "stat", "-p", NULL};
1336                 int argc = 4;
1337                 client_open(argc, argv, &st->ct, NULL, NULL, st->btrn, s);
1338                 set_stat_task_restart_barrier(5);
1339         }
1340         free(stat_item_values[SI_basename]);
1341         stat_item_values[SI_basename] = para_strdup(
1342                 "no connection to para_server");
1343         stat_client_write_item(SI_basename);
1344         st->last_status_read = *now;
1345 out:
1346         start_stop_decoders();
1347         return 0;
1348 }
1349
1350 static void init_status_task(struct status_task *st)
1351 {
1352         memset(st, 0, sizeof(struct status_task));
1353         st->sa_time_diff_sign = 1;
1354         st->clock_diff_count = OPT_UINT32_VAL(CLOCK_DIFF_COUNT);
1355         st->current_audio_format_num = -1;
1356         st->btrn = btr_new_node(&(struct btr_node_description)
1357                 EMBRACE(.name = "stat"));
1358
1359         stat_task->task = task_register(&(struct task_info) {
1360                 .name = "stat",
1361                 .pre_select = status_pre_select,
1362                 .post_select = status_post_select,
1363                 .context = stat_task,
1364         }, &sched);
1365 }
1366
1367 static void set_initial_status(void)
1368 {
1369         audiod_status = AUDIOD_ON;
1370         if (!OPT_GIVEN(MODE))
1371                 return;
1372         if (!strcmp(OPT_STRING_VAL(MODE), "sb")) {
1373                 audiod_status = AUDIOD_STANDBY;
1374                 return;
1375         }
1376         if (!strcmp(OPT_STRING_VAL(MODE), "off")) {
1377                 audiod_status = AUDIOD_OFF;
1378                 return;
1379         }
1380         if (strcmp(OPT_STRING_VAL(MODE), "on"))
1381                 PARA_WARNING_LOG("invalid mode\n");
1382 }
1383
1384 /**
1385  * Lookup the given UID in the whitelist.
1386  *
1387  * The whitelist is the array of arguments to the --user-allow opion. If the
1388  * option was not given, the array is empty, in which case the check succeeds.
1389  *
1390  * \param uid User ID to look up.
1391  *
1392  * \return True if --user-allow was not given, or if uid matches an element of
1393  * the whitelist.
1394  */
1395 bool uid_is_whitelisted(uid_t uid)
1396 {
1397         int i;
1398
1399         if (!OPT_GIVEN(USER_ALLOW))
1400                 return true;
1401         for (i = 0; i < OPT_GIVEN(USER_ALLOW); i++)
1402                 if (uid == uid_whitelist[i])
1403                         return true;
1404         return false;
1405 }
1406
1407 static void handle_help_flags(void)
1408 {
1409         char *help;
1410         bool d = OPT_GIVEN(DETAILED_HELP);
1411
1412         if (d)
1413                 help = lls_long_help(CMD_PTR);
1414         else if (OPT_GIVEN(HELP))
1415                 help = lls_short_help(CMD_PTR);
1416         else
1417                 return;
1418         printf("%s\n", help);
1419         free(help);
1420         print_receiver_helps(d);
1421         print_filter_helps(d);
1422         print_writer_helps(d);
1423         exit(EXIT_SUCCESS);
1424 }
1425
1426 /**
1427  * the main function of para_audiod
1428  *
1429  * \param argc usual argument count
1430  * \param argv usual argument vector
1431  *
1432  * \return EXIT_SUCCESS or EXIT_FAILURE
1433  *
1434  * \sa para_audiod(1)
1435  * */
1436 int main(int argc, char *argv[])
1437 {
1438         int ret, i;
1439         struct command_task command_task_struct, *cmd_task = &command_task_struct;
1440         char *errctx;
1441
1442         valid_fd_012();
1443         ret = lls(lls_parse(argc, argv, CMD_PTR, &lpr, &errctx));
1444         if (ret < 0)
1445                 goto out;
1446         daemon_set_loglevel(ENUM_STRING_VAL(LOGLEVEL));
1447         daemon_drop_privileges_or_die(OPT_STRING_VAL(USER),
1448                 OPT_STRING_VAL(GROUP));
1449         version_handle_flag("audiod", OPT_GIVEN(VERSION));
1450         handle_help_flags();
1451         parse_config_or_die();
1452         crypt_init();
1453         daemon_set_priority(OPT_UINT32_VAL(PRIORITY));
1454         if (daemon_init_colors_or_die(OPT_UINT32_VAL(COLOR), COLOR_AUTO,
1455                         COLOR_NO, OPT_GIVEN(LOGFILE))) {
1456                 for (i = 0; i < OPT_GIVEN(LOG_COLOR); i++)
1457                         daemon_set_log_color_or_die(lls_string_val(i,
1458                                 OPT_RESULT(LOG_COLOR)));
1459         }
1460         daemon_set_flag(DF_LOG_TIME);
1461         daemon_set_flag(DF_LOG_HOSTNAME);
1462         daemon_set_flag(DF_LOG_LL);
1463         if (OPT_GIVEN(LOG_TIMING))
1464                 daemon_set_flag(DF_LOG_TIMING);
1465         if (OPT_GIVEN(LOGFILE)) {
1466                 daemon_set_logfile(OPT_STRING_VAL(LOGFILE));
1467                 daemon_open_log_or_die();
1468         }
1469         ret = parse_stream_args();
1470         if (ret < 0) {
1471                 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1472                 exit(EXIT_FAILURE);
1473         }
1474         daemon_log_welcome("audiod");
1475         daemon_set_start_time();
1476         set_initial_status();
1477         FOR_EACH_SLOT(i)
1478                 clear_slot(i);
1479         setup_signal_handling();
1480
1481         init_status_task(stat_task);
1482         init_command_task(cmd_task);
1483
1484         if (OPT_GIVEN(DAEMON))
1485                 daemonize(false /* parent exits immediately */);
1486
1487         signal_task->task = task_register(&(struct task_info) {
1488                 .name = "signal",
1489                 .pre_select = signal_pre_select,
1490                 .post_select = signal_post_select,
1491                 .context = signal_task,
1492         }, &sched);
1493
1494         sched.default_timeout.tv_sec = 2;
1495         sched.default_timeout.tv_usec = 999 * 1000;
1496         ret = schedule(&sched);
1497         audiod_cleanup();
1498         sched_shutdown(&sched);
1499         signal_shutdown(signal_task);
1500         crypt_shutdown();
1501 out:
1502         lls_free_parse_result(lpr, CMD_PTR);
1503         if (errctx)
1504                 PARA_ERROR_LOG("%s\n", errctx);
1505         if (ret < 0)
1506                 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1507         return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;
1508 }