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