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