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