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