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