Make rc4 encryption/decryption more explicit.
[paraslash.git] / audiod.c
1 /*
2 * Copyright (C) 2005-2009 Andre Noll <maan@systemlinux.org>
3 *
4 * Licensed under the GPL v2. For licencing details see COPYING.
5 */
6
7 /** \file audiod.c the paraslash's audio daemon */
8 #include <sys/types.h>
9 #include <dirent.h>
10 #include <signal.h>
11 #include <openssl/rc4.h>
12
13 #include "para.h"
14 #include "error.h"
15 #include "crypt.h"
16 #include "audiod.cmdline.h"
17 #include "list.h"
18 #include "sched.h"
19 #include "ggo.h"
20 #include "recv.h"
21 #include "filter.h"
22 #include "grab_client.cmdline.h"
23 #include "grab_client.h"
24 #include "client.cmdline.h"
25 #include "client.h"
26 #include "audiod.h"
27 #include "net.h"
28 #include "daemon.h"
29 #include "string.h"
30 #include "fd.h"
31 #include "write.h"
32 #include "write_common.h"
33 #include "signal.h"
34
35 /** define the array of error lists needed by para_audiod */
36 INIT_AUDIOD_ERRLISTS;
37 /** define the array containing all supported audio formats */
38 const char *audio_formats[] = {AUDIOD_AUDIO_FORMAT_ARRAY NULL};
39
40 /** Defines how audiod handles one supported audio format. */
41 struct audio_format_info {
42 /** pointer to the receiver for this audio format */
43 struct receiver *receiver;
44 /** the receiver configuration */
45 void *receiver_conf;
46 /** the number of filters that should be activated for this audio format */
47 unsigned int num_filters;
48 /** Array of filter numbers to be activated. */
49 unsigned *filter_nums;
50 /** Pointer to the array of filter configurations. */
51 void **filter_conf;
52 /** the number of filters that should be activated for this audio format */
53 unsigned int num_writers;
54 /** Array of writer numbers to be activated. */
55 int *writer_nums;
56 /** pointer to the array of writer configurations */
57 void **writer_conf;
58 /** do not start receiver/filters/writer before this time */
59 struct timeval restart_barrier;
60 };
61
62 /**
63 * para_audiod uses \p MAX_STREAM_SLOTS different slots, each of which may
64 * be associated with a receiver/filter/writer triple. This array holds all
65 * information on the status of these slots.
66 *
67 * \sa struct slot_info
68 * */
69 struct slot_info slot[MAX_STREAM_SLOTS];
70
71 /** The vss status flags audiod is interested in. */
72 enum vss_status_flags {
73 /** Whether the 'N' flag is set. */
74 VSS_STATUS_FLAG_NEXT = 1,
75 /** The 'P' flag is set. */
76 VSS_STATUS_FLAG_PLAYING = 2,
77 };
78
79 /**
80 * The task for obtaining para_server's status (para_client stat).
81 *
82 * \sa struct task, struct sched.
83 */
84 struct status_task {
85 /** The associated task structure of audiod. */
86 struct task task;
87 /** Client data associated with the stat task. */
88 struct client_task *ct;
89 /** Do not restart client command until this time. */
90 struct timeval restart_barrier;
91 /** Last time we received status data from para_server. */
92 struct timeval last_status_read;
93 /** The offset value announced by para_server. */
94 int offset_seconds;
95 /** The length of the current audio file as announced by para_server. */
96 int length_seconds;
97 /** The start of the current stream from the view of para_server. */
98 struct timeval server_stream_start;
99 /** The average time deviation between para_server and para_audiod. */
100 struct timeval sa_time_diff;
101 /** Whether client time is ahead of server time. */
102 int sa_time_diff_sign;
103 /** The 'P' and the 'N' flags as announced by para_server. */
104 enum vss_status_flags vss_status;
105 /** Number of times the clock difference is to be checked. */
106 unsigned clock_diff_count;
107 /** When to start the next check for clock difference. */
108 struct timeval clock_diff_barrier;
109 /** Number of the audio format as announced by para_server. */
110 int current_audio_format_num;
111 };
112
113 /** The array of status items sent by para_server. */
114 char *stat_item_values[NUM_STAT_ITEMS] = {NULL};
115
116 /**
117 * the current mode of operation of which can be changed by the on/off/cycle
118 * commands. It is either, AUDIOD_OFF, AUDIOD_ON or AUDIOD_STANDBY.
119 */
120 int audiod_status = AUDIOD_ON;
121
122 /**
123 * the gengetopt args_info struct that holds information on all command line
124 * arguments
125 */
126 struct audiod_args_info conf;
127
128 static char *socket_name;
129 static struct audio_format_info afi[NUM_AUDIO_FORMATS];
130
131 static struct signal_task signal_task_struct, *sig_task = &signal_task_struct;
132
133 static struct status_task status_task_struct;
134
135 /**
136 * the task that calls the status command of para_server
137 *
138 * \sa struct status_task
139 */
140 static struct status_task *stat_task = &status_task_struct;
141 static struct timeval initial_delay_barrier;
142
143 /**
144 * the task for handling audiod commands
145 *
146 * \sa struct task, struct sched
147 */
148 struct command_task {
149 /** the local listening socket */
150 int fd;
151 /** the associated task structure */
152 struct task task;
153 };
154
155 /** iterate over all supported audio formats */
156 #define FOR_EACH_AUDIO_FORMAT(af) for (af = 0; af < NUM_AUDIO_FORMATS; af++)
157
158 /**
159 * get the audio format number
160 * \param name the name of the audio format
161 *
162 * \return The audio format number on success, -E_UNSUPPORTED_AUDIO_FORMAT if
163 * \a name is not a supported audio format.
164 */
165 int get_audio_format_num(char *name)
166 {
167 int i;
168
169 while (para_isspace(*name))
170 name++;
171 FOR_EACH_AUDIO_FORMAT(i)
172 if (!strcmp(name, audio_formats[i]))
173 return i;
174 return -E_UNSUPPORTED_AUDIO_FORMAT;
175 }
176
177 char *get_time_string(int slot_num)
178 {
179 int ret, seconds = 0, length;
180 struct timeval *tmp, sum, sss, /* server stream start */
181 wtime, /* now - writer start */
182 rskip; /* receiver start - sss */
183 struct slot_info *s = slot_num < 0? NULL : &slot[slot_num];
184
185 if (audiod_status == AUDIOD_OFF)
186 goto empty;
187 if (!(stat_task->vss_status & VSS_STATUS_FLAG_PLAYING)) {
188 if (stat_task->length_seconds) /* paused */
189 return NULL;
190 goto empty; /* stopped */
191 }
192 if (audiod_status == AUDIOD_ON && !s)
193 goto empty;
194 /* valid status items and playing */
195 if (s) { /* writer active in this slot */
196 length = s->seconds_total;
197 tmp = &s->server_stream_start;
198 } else { /* standby mode, rely on status items */
199 length = stat_task->length_seconds;
200 tmp = &stat_task->server_stream_start;
201 }
202 if (stat_task->sa_time_diff_sign > 0)
203 tv_diff(tmp, &stat_task->sa_time_diff, &sss);
204 else
205 tv_add(tmp, &stat_task->sa_time_diff, &sss);
206 if (!s) {
207 struct timeval diff;
208 tv_diff(now, &sss, &diff);
209 seconds = diff.tv_sec + stat_task->offset_seconds;
210 goto out;
211 }
212 tv_diff(now, &s->wstime, &wtime);
213 seconds = s->offset_seconds;
214 ret = tv_diff(&s->rstime, &sss, &rskip);
215 if (ret > 0) { /* audiod was started in the middle of the stream */
216 tv_add(&wtime, &rskip, &sum);
217 seconds += sum.tv_sec;
218 } else
219 seconds += wtime.tv_sec;
220 out:
221 seconds = PARA_MIN(seconds, length);
222 seconds = PARA_MAX(seconds, 0);
223 return make_message(
224 "%s: %s%d:%02d [%d:%02d] (%d%%/%d:%02d)\n",
225 status_item_list[SI_PLAY_TIME],
226 s? "" : "~",
227 seconds / 60,
228 seconds % 60,
229 (length - seconds) / 60,
230 (length - seconds) % 60,
231 length? (seconds * 100 + length / 2) / length : 0,
232 length / 60,
233 length % 60
234 );
235 empty:
236 return make_message("%s:\n", status_item_list[SI_PLAY_TIME]);
237 }
238
239 static int want_colors(void)
240 {
241 if (conf.color_arg == color_arg_no)
242 return 0;
243 if (conf.color_arg == color_arg_yes)
244 return 1;
245 if (conf.logfile_given)
246 return 0;
247 return isatty(STDERR_FILENO);
248 }
249
250 static void parse_config_or_die(void)
251 {
252 int ret;
253 char *config_file;
254 struct audiod_cmdline_parser_params params = {
255 .override = 0,
256 .initialize = 0,
257 .check_required = 1,
258 .check_ambiguity = 0,
259 .print_errors = 1
260 };
261
262 if (conf.config_file_given)
263 config_file = para_strdup(conf.config_file_arg);
264 else {
265 char *home = para_homedir();
266 config_file = make_message("%s/.paraslash/audiod.conf", home);
267 free(home);
268 }
269 ret = file_exists(config_file);
270 if (conf.config_file_given && !ret) {
271 PARA_EMERG_LOG("can not read config file %s\n", config_file);
272 goto err;
273 }
274 if (ret)
275 audiod_cmdline_parser_config_file(config_file, &conf, &params);
276 free(config_file);
277 daemon_set_loglevel(conf.loglevel_arg);
278 return;
279 err:
280 free(config_file);
281 exit(EXIT_FAILURE);
282 }
283
284 static void setup_signal_handling(void)
285 {
286 sig_task->fd = para_signal_init();
287 PARA_INFO_LOG("signal pipe: fd %d\n", sig_task->fd);
288 para_install_sighandler(SIGINT);
289 para_install_sighandler(SIGTERM);
290 para_install_sighandler(SIGHUP);
291 para_sigaction(SIGPIPE, SIG_IGN);
292 }
293
294 static void clear_slot(int slot_num)
295 {
296 struct slot_info *s = &slot[slot_num];
297
298 PARA_INFO_LOG("clearing slot %d\n", slot_num);
299 memset(s, 0, sizeof(struct slot_info));
300 s->format = -1;
301 }
302
303 static void close_receiver(int slot_num)
304 {
305 struct slot_info *s = &slot[slot_num];
306 struct audio_format_info *a;
307
308 if (s->format < 0 || !s->receiver_node)
309 return;
310 a = &afi[s->format];
311 PARA_NOTICE_LOG("closing %s receiver in slot %d\n",
312 audio_formats[s->format], slot_num);
313 a->receiver->close(s->receiver_node);
314 free(s->receiver_node);
315 s->receiver_node = NULL;
316 }
317
318 static void kill_all_decoders(int error)
319 {
320 int i;
321
322 FOR_EACH_SLOT(i) {
323 struct slot_info *s = &slot[i];
324 if (s->wng && s->wng->task.error >= 0) {
325 PARA_INFO_LOG("deactivating wng in slot %d\n",
326 i);
327 s->wng->task.error = error;
328 }
329 if (s->fc && s->fc->task.error >= 0) {
330 PARA_INFO_LOG("deactivatimg filter chain in slot %d\n", i);
331 s->fc->task.error = error;
332 }
333 if (s->receiver_node && s->receiver_node->task.error >= 0) {
334 PARA_INFO_LOG("deactivating receiver_node in slot %d\n", i);
335 s->receiver_node->task.error = error;
336 }
337 }
338 }
339
340 static int get_empty_slot(void)
341 {
342 int i;
343 struct slot_info *s;
344
345 FOR_EACH_SLOT(i) {
346 s = &slot[i];
347 if (s->format < 0) {
348 clear_slot(i);
349 return i;
350 }
351 if (s->wng || s->receiver_node || s->fc)
352 continue;
353 clear_slot(i);
354 return i;
355 }
356 return -E_NO_MORE_SLOTS;
357 }
358
359 /**
360 * get the number of filters
361 *
362 * \param audio_format_num the number identifying the audio format
363 *
364 * \return the number of filters for the given audio format
365 *
366 * \sa struct filter;
367 */
368 int num_filters(int audio_format_num)
369 {
370 return afi[audio_format_num].num_filters;
371 }
372
373 static void open_filters(int slot_num)
374 {
375 struct slot_info *s = &slot[slot_num];
376 struct audio_format_info *a = &afi[s->format];
377 struct filter_node *fn;
378 int nf = a->num_filters;
379 int i;
380
381 s->fc = NULL;
382 if (!nf)
383 return;
384 PARA_INFO_LOG("opening %s filters\n", audio_formats[s->format]);
385 s->fc = para_calloc(sizeof(struct filter_chain));
386 s->fc->filter_nodes = para_malloc(nf * sizeof(struct filter_node));
387 s->fc->inbufp = &s->receiver_node->buf;
388 s->fc->in_loaded = &s->receiver_node->loaded;
389 s->fc->input_error = &s->receiver_node->task.error;
390 s->fc->task.pre_select = filter_pre_select;
391 s->fc->task.post_select = NULL;
392 s->fc->task.error = 0;
393 s->fc->num_filters = nf;
394
395 s->receiver_node->output_error = &s->fc->task.error;
396 sprintf(s->fc->task.status, "filter chain");
397 FOR_EACH_FILTER_NODE(fn, s->fc, i) {
398 struct filter *f = filters + a->filter_nums[i];
399 fn->filter_num = a->filter_nums[i];
400 fn->conf = a->filter_conf[i];
401 fn->fc = s->fc;
402 fn->loaded = 0;
403 INIT_LIST_HEAD(&fn->callbacks);
404 f->open(fn);
405 PARA_NOTICE_LOG("%s filter %d/%d (%s) started in slot %d\n",
406 audio_formats[s->format], i, nf, f->name, slot_num);
407 s->fc->outbufp = &fn->buf;
408 s->fc->out_loaded = &fn->loaded;
409 }
410 register_task(&s->fc->task);
411 }
412
413 static void open_writers(int slot_num)
414 {
415 int ret, i;
416 struct slot_info *s = &slot[slot_num];
417 struct audio_format_info *a = &afi[s->format];
418
419 PARA_INFO_LOG("opening %s writers\n", audio_formats[s->format]);
420 if (!a->num_writers)
421 s->wng = setup_default_wng();
422 else
423 s->wng = wng_new(a->num_writers);
424 if (s->fc) {
425 s->wng->bufp = s->fc->outbufp;
426 s->wng->loaded = s->fc->out_loaded;
427 s->wng->input_error = &s->fc->task.error;
428 s->wng->channels = &s->fc->channels;
429 s->wng->samplerate = &s->fc->samplerate;
430 s->fc->output_error = &s->wng->task.error;
431 PARA_INFO_LOG("samplerate: %d\n", *s->wng->samplerate);
432 } else {
433 s->wng->bufp = &s->receiver_node->buf;
434 s->wng->loaded = &s->receiver_node->loaded;
435 s->wng->input_error = &s->receiver_node->task.error;
436 }
437 for (i = 0; i < a->num_writers; i++) {
438 s->wng->writer_nodes[i].conf = a->writer_conf[i];
439 s->wng->writer_nodes[i].writer_num = a->writer_nums[i];
440 }
441 ret = wng_open(s->wng);
442 if (ret < 0)
443 return;
444 s->wstime = *now;
445 s->server_stream_start = stat_task->server_stream_start.tv_sec?
446 stat_task->server_stream_start : *now;
447 s->offset_seconds = stat_task->offset_seconds;
448 s->seconds_total = stat_task->length_seconds;
449 activate_inactive_grab_clients(slot_num, s->format, s->fc);
450 }
451
452 static int open_receiver(int format)
453 {
454 struct audio_format_info *a = &afi[format];
455 struct slot_info *s;
456 int ret, slot_num;
457 struct receiver_node *rn;
458 const struct timeval restart_delay = {2, 0};
459
460 ret = get_empty_slot();
461 if (ret < 0)
462 goto err;
463 slot_num = ret;
464 s = &slot[slot_num];
465 s->format = format;
466 s->receiver_node = para_calloc(sizeof(struct receiver_node));
467 rn = s->receiver_node;
468 rn->receiver = a->receiver;
469 rn->conf = a->receiver_conf;
470 ret = a->receiver->open(s->receiver_node);
471 if (ret < 0) {
472 free(s->receiver_node);
473 s->receiver_node = NULL;
474 goto err;
475 }
476 PARA_NOTICE_LOG("started %s: %s receiver in slot %d\n",
477 audio_formats[s->format], a->receiver->name, slot_num);
478 rn->task.pre_select = a->receiver->pre_select;
479 rn->task.post_select = a->receiver->post_select;
480 s->rstime = *now;
481 sprintf(rn->task.status, "%s receiver node", rn->receiver->name);
482 register_task(&rn->task);
483 ret = 1;
484 err:
485 if (ret < 0)
486 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
487 tv_add(now, &restart_delay, &afi[format].restart_barrier);
488 return ret;
489 }
490
491 /* return: 0: Not running, 1: Running, -1: Running but eof (or error) */
492 static int receiver_running(int format)
493 {
494 int i, ret = 0;
495
496 FOR_EACH_SLOT(i) {
497 struct slot_info *s = &slot[i];
498 if (s->format != format)
499 continue;
500 if (!s->receiver_node)
501 continue;
502 if (s->receiver_node->task.error >= 0)
503 return 1;
504 ret = -1;
505 }
506 return ret;
507 }
508
509 static void open_current_receiver(struct sched *s)
510 {
511 struct timeval diff;
512 int ret, cafn = stat_task->current_audio_format_num;
513
514 if (cafn < 0 || !stat_task->ct)
515 return;
516 /* Do nothing if the 'N' flag is set or the 'P' flag is unset */
517 if (stat_task->vss_status != VSS_STATUS_FLAG_PLAYING)
518 return;
519 ret = receiver_running(cafn);
520 if (ret > 0) /* already running and not eof */
521 return;
522 if (ret < 0) { /* eof */
523 /*
524 * para_server uses a zero start time during the announcement
525 * period, i.e. before it sends the first chunk. Wait until
526 * this period begins to avoid restarting the receiver that
527 * belongs to the file just completed.
528 */
529 if (stat_task->server_stream_start.tv_sec)
530 return;
531 }
532 if (tv_diff(now, &afi[cafn].restart_barrier, &diff) < 0) {
533 /* avoid busy loop */
534 s->timeout = diff;
535 return;
536 }
537 /* start a new receiver */
538 open_receiver(cafn);
539 }
540
541 static unsigned compute_time_diff(const struct timeval *status_time)
542 {
543 struct timeval tmp, diff;
544 static unsigned count;
545 int sign, sa_time_diff_sign = stat_task->sa_time_diff_sign;
546 const struct timeval max_deviation = {0, 500 * 1000};
547 const int time_smooth = 5;
548
549 if (!status_time)
550 return count;
551 sign = tv_diff(status_time, now, &diff);
552 // PARA_NOTICE_LOG("%s: sign = %i, sa_time_diff_sign = %i\n", __func__,
553 // sign, sa_time_diff_sign);
554 if (!count) {
555 sa_time_diff_sign = sign;
556 stat_task->sa_time_diff = diff;
557 count++;
558 goto out;
559 }
560 if (count > 5) {
561 int s = tv_diff(&diff, &stat_task->sa_time_diff, &tmp);
562 if (tv_diff(&max_deviation, &tmp, NULL) < 0)
563 PARA_WARNING_LOG("time diff jump: %lims\n",
564 s * tv2ms(&tmp));
565 }
566 count++;
567 sa_time_diff_sign = tv_convex_combination(
568 sa_time_diff_sign * time_smooth, &stat_task->sa_time_diff,
569 count > 10? sign : sign * time_smooth, &diff,
570 &tmp);
571 stat_task->sa_time_diff = tmp;
572 PARA_INFO_LOG("time diff (cur/avg): %s%lums/%s%lums\n",
573 sign > 0? "+" : "-",
574 tv2ms(&diff),
575 sa_time_diff_sign ? "+" : "-",
576 tv2ms(&stat_task->sa_time_diff)
577 );
578 out:
579 stat_task->sa_time_diff_sign = sa_time_diff_sign;
580 return count;
581 }
582
583 static int check_stat_line(char *line, __a_unused void *data)
584 {
585 int itemnum;
586 size_t ilen = 0;
587 long unsigned sec, usec;
588 char *tmp;
589
590 //PARA_INFO_LOG("line: %s\n", line);
591 if (!line)
592 return 1;
593 itemnum = stat_line_valid(line);
594 if (itemnum < 0) {
595 PARA_WARNING_LOG("invalid status line: %s\n", line);
596 return 1;
597 }
598 if (stat_task->clock_diff_count && itemnum != SI_CURRENT_TIME)
599 return 1;
600 tmp = make_message("%s\n", line);
601 stat_client_write(tmp, itemnum);
602 free(tmp);
603 free(stat_item_values[itemnum]);
604 stat_item_values[itemnum] = para_strdup(line);
605 ilen = strlen(status_item_list[itemnum]);
606 switch (itemnum) {
607 case SI_STATUS_FLAGS:
608 stat_task->vss_status = 0;
609 if (strchr(line, 'N'))
610 stat_task->vss_status |= VSS_STATUS_FLAG_NEXT;
611 if (strchr(line, 'P'))
612 stat_task->vss_status |= VSS_STATUS_FLAG_PLAYING;
613 break;
614 case SI_OFFSET:
615 stat_task->offset_seconds = atoi(line + ilen + 1);
616 break;
617 case SI_SECONDS_TOTAL:
618 stat_task->length_seconds = atoi(line + ilen + 1);
619 break;
620 case SI_STREAM_START:
621 if (sscanf(line + ilen + 1, "%lu.%lu", &sec, &usec) == 2) {
622 struct timeval a_start, delay;
623 delay.tv_sec = conf.stream_delay_arg / 1000;
624 delay.tv_usec = (conf.stream_delay_arg % 1000) * 1000;
625 stat_task->server_stream_start.tv_sec = sec;
626 stat_task->server_stream_start.tv_usec = usec;
627 if (compute_time_diff(NULL) > 2) {
628 if (stat_task->sa_time_diff_sign < 0)
629 tv_add(&stat_task->server_stream_start,
630 &stat_task->sa_time_diff, &a_start);
631 else
632 tv_diff(&stat_task->server_stream_start,
633 &stat_task->sa_time_diff, &a_start);
634 tv_add(&a_start, &delay, &initial_delay_barrier);
635 }
636 }
637 break;
638 case SI_CURRENT_TIME:
639 if (sscanf(line + ilen + 1, "%lu.%lu", &sec, &usec) == 2) {
640 struct timeval tv = {sec, usec};
641 compute_time_diff(&tv);
642 }
643 break;
644 case SI_FORMAT:
645 stat_task->current_audio_format_num = get_audio_format_num(
646 line + ilen + 1);
647 }
648 return 1;
649 }
650
651 static int parse_stream_command(const char *txt, char **cmd)
652 {
653 char *p = strchr(txt, ':');
654 int i;
655
656 if (!p)
657 return -E_MISSING_COLON;
658 p++;
659 FOR_EACH_AUDIO_FORMAT(i) {
660 if (strncmp(txt, audio_formats[i], strlen(audio_formats[i])))
661 continue;
662 *cmd = p;
663 return i;
664 }
665 return -E_UNSUPPORTED_AUDIO_FORMAT;
666 }
667
668 static int add_filter(int format, char *cmdline)
669 {
670 struct audio_format_info *a = &afi[format];
671 int filter_num, nf = a->num_filters;
672
673 filter_num = check_filter_arg(cmdline, &a->filter_conf[nf]);
674 if (filter_num < 0)
675 return filter_num;
676 a->filter_nums[nf] = filter_num;
677 a->num_filters++;
678 PARA_INFO_LOG("%s filter %d: %s\n", audio_formats[format], nf,
679 filters[filter_num].name);
680 return filter_num;
681 }
682
683 static int parse_writer_args(void)
684 {
685 int i, ret, nw;
686 char *cmd;
687 struct audio_format_info *a;
688
689 nw = PARA_MAX(1U, conf.writer_given);
690 PARA_INFO_LOG("maximal number of writers: %d\n", nw);
691 FOR_EACH_AUDIO_FORMAT(i) {
692 a = &afi[i];
693 a->writer_conf = para_malloc(nw * sizeof(void *));
694 a->writer_nums = para_malloc(nw * sizeof(int));
695 a->num_writers = 0;
696 }
697 for (i = 0; i < conf.writer_given; i++) {
698 void *wconf;
699 int writer_num;
700 ret = parse_stream_command(conf.writer_arg[i], &cmd);
701 if (ret < 0)
702 goto out;
703 a = &afi[ret];
704 nw = a->num_writers;
705 wconf = check_writer_arg(cmd, &writer_num);
706 if (!wconf) {
707 ret = writer_num;
708 goto out;
709 }
710 a->writer_nums[nw] = writer_num;
711 a->writer_conf[nw] = wconf;
712 PARA_INFO_LOG("%s writer #%d: %s\n", audio_formats[ret],
713 nw, writer_names[writer_num]);
714 a->num_writers++;
715 }
716 ret = 1;
717 out:
718 return ret;
719 }
720
721 static int parse_receiver_args(void)
722 {
723 int i, ret, receiver_num;
724 char *cmd = NULL;
725 struct audio_format_info *a;
726
727 for (i = conf.receiver_given - 1; i >= 0; i--) {
728 char *arg = conf.receiver_arg[i];
729 char *recv_arg = strchr(arg, ':');
730 ret = -E_MISSING_COLON;
731 if (!recv_arg)
732 goto out;
733 *recv_arg = '\0';
734 recv_arg++;
735 ret = get_audio_format_num(arg);
736 if (ret < 0)
737 goto out;
738 afi[ret].receiver_conf = check_receiver_arg(recv_arg, &receiver_num);
739 if (!afi[ret].receiver_conf) {
740 ret = -E_RECV_SYNTAX;
741 goto out;
742 }
743 afi[ret].receiver = &receivers[receiver_num];
744 }
745 /* use the first available receiver with no arguments
746 * for those audio formats for which no receiver
747 * was specified
748 */
749 cmd = para_strdup(receivers[0].name);
750 FOR_EACH_AUDIO_FORMAT(i) {
751 a = &afi[i];
752 if (a->receiver_conf)
753 continue;
754 a->receiver_conf = check_receiver_arg(cmd, &receiver_num);
755 if (!a->receiver_conf)
756 return -E_RECV_SYNTAX;
757 a->receiver = &receivers[receiver_num];
758 }
759 ret = 1;
760 out:
761 free(cmd);
762 return ret;
763 }
764
765 static int init_default_filters(void)
766 {
767 int i, ret = 1;
768
769 FOR_EACH_AUDIO_FORMAT(i) {
770 struct audio_format_info *a = &afi[i];
771 char *tmp;
772 int j;
773
774 if (a->num_filters)
775 continue; /* no default -- nothing to to */
776 /* add "dec" to audio format name */
777 tmp = make_message("%sdec", audio_formats[i]);
778 for (j = 0; filters[j].name; j++)
779 if (!strcmp(tmp, filters[j].name))
780 break;
781 free(tmp);
782 ret = -E_UNSUPPORTED_FILTER;
783 if (!filters[j].name)
784 goto out;
785 tmp = para_strdup(filters[j].name);
786 ret = add_filter(i, tmp);
787 free(tmp);
788 if (ret < 0)
789 goto out;
790 PARA_INFO_LOG("%s -> default filter: %s\n", audio_formats[i],
791 filters[j].name);
792 }
793 out:
794 return ret;
795 }
796
797 static int parse_filter_args(void)
798 {
799 int i, ret, nf;
800
801 nf = PARA_MAX(1U, conf.filter_given);
802 PARA_INFO_LOG("maximal number of filters: %d\n", nf);
803 FOR_EACH_AUDIO_FORMAT(i) {
804 afi[i].filter_conf = para_malloc(nf * sizeof(void *));
805 afi[i].filter_nums = para_malloc(nf * sizeof(unsigned));
806 }
807 if (!conf.no_default_filters_given)
808 return init_default_filters();
809 for (i = 0; i < conf.filter_given; i++) {
810 char *arg = conf.filter_arg[i];
811 char *filter_name = strchr(arg, ':');
812 ret = -E_MISSING_COLON;
813 if (!filter_name)
814 goto out;
815 *filter_name = '\0';
816 filter_name++;
817 ret = get_audio_format_num(arg);
818 if (ret < 0)
819 goto out;
820 ret = add_filter(ret, filter_name);
821 if (ret < 0)
822 goto out;
823 }
824 ret = init_default_filters(); /* use default values for the rest */
825 out:
826 return ret;
827 }
828
829 static int parse_stream_args(void)
830 {
831 int ret;
832
833 ret = parse_receiver_args();
834 if (ret < 0)
835 return ret;
836 ret = parse_filter_args();
837 if (ret < 0)
838 return ret;
839 ret = parse_writer_args();
840 if (ret < 0)
841 return ret;
842 return 1;
843 }
844
845 /* does not unlink socket on errors */
846 static int audiod_get_socket(void)
847 {
848 struct sockaddr_un unix_addr;
849 int ret, fd;
850
851 if (conf.socket_given)
852 socket_name = para_strdup(conf.socket_arg);
853 else {
854 char *hn = para_hostname();
855 socket_name = make_message("/var/paraslash/audiod_socket.%s",
856 hn);
857 free(hn);
858 }
859 PARA_NOTICE_LOG("local socket: %s\n", socket_name);
860 if (conf.force_given)
861 unlink(socket_name);
862 ret = create_local_socket(socket_name, &unix_addr,
863 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IWOTH);
864 if (ret < 0)
865 goto err;
866 fd = ret;
867 if (listen(fd , 5) < 0) {
868 ret = -ERRNO_TO_PARA_ERROR(errno);
869 goto err;
870 }
871 ret = mark_fd_nonblocking(fd);
872 if (ret < 0)
873 goto err;
874 return fd;
875 err:
876 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
877 exit(EXIT_FAILURE);
878 }
879
880 static void signal_pre_select(struct sched *s, struct task *t)
881 {
882 struct signal_task *st = container_of(t, struct signal_task, task);
883 para_fd_set(st->fd, &s->rfds, &s->max_fileno);
884 }
885
886 static void signal_post_select(struct sched *s, struct task *t)
887 {
888 struct signal_task *st = container_of(t, struct signal_task, task);
889
890 if (!FD_ISSET(st->fd, &s->rfds))
891 return;
892
893 st->signum = para_next_signal();
894 switch (st->signum) {
895 case SIGINT:
896 case SIGTERM:
897 case SIGHUP:
898 PARA_EMERG_LOG("terminating on signal %d\n", st->signum);
899 clean_exit(EXIT_FAILURE, "caught deadly signal");
900 }
901 }
902
903 static void signal_setup_default(struct signal_task *st)
904 {
905 st->task.pre_select = signal_pre_select;
906 st->task.post_select = signal_post_select;
907 sprintf(st->task.status, "signal task");
908 }
909
910 static void command_pre_select(struct sched *s, struct task *t)
911 {
912 struct command_task *ct = container_of(t, struct command_task, task);
913 para_fd_set(ct->fd, &s->rfds, &s->max_fileno);
914 }
915
916 static void command_post_select(struct sched *s, struct task *t)
917 {
918 int ret;
919 struct command_task *ct = container_of(t, struct command_task, task);
920
921 audiod_status_dump();
922 if (!FD_ISSET(ct->fd, &s->rfds))
923 return;
924 ret = handle_connect(ct->fd);
925 if (ret < 0)
926 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
927 }
928
929 static void init_command_task(struct command_task *ct)
930 {
931 ct->task.pre_select = command_pre_select;
932 ct->task.post_select = command_post_select;
933 ct->task.error = 0;
934 ct->fd = audiod_get_socket(); /* doesn't return on errors */
935 sprintf(ct->task.status, "command task");
936 }
937
938 static void close_stat_pipe(void)
939 {
940 int i;
941
942 if (!stat_task->ct)
943 return;
944 client_close(stat_task->ct);
945 stat_task->ct = NULL;
946 FOR_EACH_STATUS_ITEM(i) {
947 free(stat_item_values[i]);
948 stat_item_values[i] = NULL;
949 }
950 dump_empty_status();
951 stat_task->length_seconds = 0;
952 stat_task->offset_seconds = 0;
953 stat_task->vss_status = 0;
954 audiod_status_dump();
955 }
956
957 /**
958 * close the connection to para_server and exit
959 *
960 * \param status the exit status which is passed to exit(3)
961 * \param msg the log message
962 *
963 * Log \a msg with loglevel \p EMERG, close the connection to para_server if
964 * open, and call \p exit(status). \a status should be either EXIT_SUCCESS or
965 * EXIT_FAILURE.
966 *
967 * \sa exit(3)
968 */
969 void __noreturn clean_exit(int status, const char *msg)
970 {
971 PARA_EMERG_LOG("%s\n", msg);
972 if (socket_name)
973 unlink(socket_name);
974 close_stat_pipe();
975 exit(status);
976 }
977
978 /* avoid busy loop if server is down */
979 static void set_stat_task_restart_barrier(unsigned seconds)
980 {
981 struct timeval delay = {seconds, 0};
982 tv_add(now, &delay, &stat_task->restart_barrier);
983 }
984
985 static void try_to_close_slot(int slot_num)
986 {
987 struct slot_info *s = &slot[slot_num];
988
989 if (s->format < 0)
990 return;
991 if (s->receiver_node && s->receiver_node->task.error != -E_TASK_UNREGISTERED)
992 return;
993 if (s->fc && s->fc->task.error != -E_TASK_UNREGISTERED)
994 return;
995 if (s->wng && s->wng->task.error != -E_TASK_UNREGISTERED)
996 return;
997 PARA_INFO_LOG("closing slot %d\n", slot_num);
998 wng_close(s->wng);
999 close_filters(s->fc);
1000 free(s->fc);
1001 close_receiver(slot_num);
1002 clear_slot(slot_num);
1003 }
1004
1005 /*
1006 * Check if any receivers/filters/writers need to be started and do so if
1007 * necessary.
1008 */
1009 static void start_stop_decoders(struct sched *s)
1010 {
1011 int i;
1012
1013 FOR_EACH_SLOT(i)
1014 try_to_close_slot(i);
1015 if (audiod_status != AUDIOD_ON ||
1016 !(stat_task->vss_status & VSS_STATUS_FLAG_PLAYING))
1017 return kill_all_decoders(-E_NOT_PLAYING);
1018 open_current_receiver(s);
1019 FOR_EACH_SLOT(i) {
1020 struct slot_info *sl = &slot[i];
1021 struct audio_format_info *a;
1022 struct timeval diff;
1023
1024 if (sl->format < 0)
1025 continue;
1026 a = &afi[sl->format];
1027 if (!sl->receiver_node)
1028 continue;
1029 if ((!a->num_filters || sl->fc) && sl->wng)
1030 continue; /* everything already started */
1031 if (!a->num_filters) {
1032 if (sl->receiver_node->loaded && !sl->wng) {
1033 open_writers(i);
1034 }
1035 continue;
1036 }
1037 if (sl->receiver_node->loaded && !sl->fc) {
1038 open_filters(i);
1039 continue;
1040 }
1041 if (sl->wng || !sl->fc || !*sl->fc->out_loaded)
1042 continue;
1043 if (tv_diff(now, &initial_delay_barrier, &diff) > 0) {
1044 open_writers(i);
1045 continue;
1046 }
1047 PARA_INFO_LOG("initial delay: %lu ms left\n", tv2ms(&diff));
1048 if (tv_diff(&s->timeout, &diff, NULL) > 0) {
1049 s->timeout = diff;
1050 }
1051 }
1052 }
1053
1054
1055 /* restart the client task if necessary */
1056 static void status_pre_select(struct sched *s, struct task *t)
1057 {
1058 struct status_task *st = container_of(t, struct status_task, task);
1059
1060 if (audiod_status == AUDIOD_OFF) {
1061 if (!st->ct)
1062 goto out;
1063 if (st->ct->task.error >= 0) {
1064 st->ct->task.error = -E_AUDIOD_OFF;
1065 goto out;
1066 }
1067 if (st->ct->task.error != -E_TASK_UNREGISTERED)
1068 goto out;
1069 close_stat_pipe();
1070 st->clock_diff_count = conf.clock_diff_count_arg;
1071 goto out;
1072 }
1073 if (st->ct) {
1074 unsigned bytes_left;
1075 if (st->ct->task.error < 0) {
1076 if (st->ct->task.error != -E_TASK_UNREGISTERED)
1077 goto out;
1078 close_stat_pipe();
1079 goto out;
1080 }
1081 if (st->ct->status != CL_RECEIVING)
1082 goto out;
1083 bytes_left = for_each_line(st->ct->buf, st->ct->loaded,
1084 &check_stat_line, NULL);
1085 if (st->ct->loaded != bytes_left) {
1086 st->last_status_read = *now;
1087 st->ct->loaded = bytes_left;
1088 } else {
1089 struct timeval diff;
1090 tv_diff(now, &st->last_status_read, &diff);
1091 if (diff.tv_sec > 61)
1092 st->ct->task.error = -E_STATUS_TIMEOUT;
1093 }
1094 goto out;
1095 }
1096 if (tv_diff(now, &st->restart_barrier, NULL) < 0)
1097 goto out;
1098 if (st->clock_diff_count) { /* get status only one time */
1099 char *argv[] = {"audiod", "stat", "1", NULL};
1100 int argc = 3;
1101 PARA_INFO_LOG("clock diff count: %d\n", st->clock_diff_count);
1102 st->clock_diff_count--;
1103 client_open(argc, argv, &st->ct, NULL);
1104 set_stat_task_restart_barrier(2);
1105
1106 } else {
1107 char *argv[] = {"audiod", "stat", NULL};
1108 int argc = 2;
1109 client_open(argc, argv, &st->ct, NULL);
1110 set_stat_task_restart_barrier(5);
1111 }
1112 free(stat_item_values[SI_BASENAME]);
1113 stat_item_values[SI_BASENAME] = make_message(
1114 "%s: no connection to para_server\n",
1115 status_item_list[SI_BASENAME]);
1116 stat_client_write(stat_item_values[SI_BASENAME],
1117 SI_BASENAME);
1118 st->last_status_read = *now;
1119 out:
1120 start_stop_decoders(s);
1121 }
1122
1123 static void init_status_task(struct status_task *st)
1124 {
1125 memset(st, 0, sizeof(struct status_task));
1126 st->task.pre_select = status_pre_select;
1127 st->sa_time_diff_sign = 1;
1128 st->clock_diff_count = conf.clock_diff_count_arg;
1129 st->current_audio_format_num = -1;
1130 sprintf(st->task.status, "status task");
1131 }
1132
1133 static void set_initial_status(void)
1134 {
1135 audiod_status = AUDIOD_ON;
1136 if (!conf.mode_given)
1137 return;
1138 if (!strcmp(conf.mode_arg, "sb")) {
1139 audiod_status = AUDIOD_STANDBY;
1140 return;
1141 }
1142 if (!strcmp(conf.mode_arg, "off")) {
1143 audiod_status = AUDIOD_OFF;
1144 return;
1145 }
1146 if (strcmp(conf.mode_arg, "on"))
1147 PARA_WARNING_LOG("invalid mode\n");
1148 }
1149
1150 __noreturn static void print_help_and_die(void)
1151 {
1152 int d = conf.detailed_help_given;
1153 const char **p = d? audiod_args_info_detailed_help
1154 : audiod_args_info_help;
1155
1156 printf_or_die("%s\n\n", AUDIOD_CMDLINE_PARSER_PACKAGE "-"
1157 AUDIOD_CMDLINE_PARSER_VERSION);
1158 printf_or_die("%s\n\n", audiod_args_info_usage);
1159 for (; *p; p++)
1160 printf_or_die("%s\n", *p);
1161 print_receiver_helps(d);
1162 print_filter_helps(d);
1163 print_writer_helps(d);
1164 exit(0);
1165 }
1166
1167 static void init_colors_or_die(void)
1168 {
1169 int ret, i;
1170
1171 if (!want_colors())
1172 return;
1173 daemon_set_default_log_colors();
1174 daemon_set_flag(DF_COLOR_LOG);
1175 for (i = 0; i < conf.log_color_given; i++) {
1176 ret = daemon_set_log_color(conf.log_color_arg[i]);
1177 if (ret < 0)
1178 exit(EXIT_FAILURE);
1179 }
1180 }
1181
1182 /**
1183 * the main function of para_audiod
1184 *
1185 * \param argc usual argument count
1186 * \param argv usual argument vector
1187 *
1188 * \return EXIT_SUCCESS or EXIT_FAILURE
1189 *
1190 * \sa para_audiod(1)
1191 * */
1192 int main(int argc, char *argv[])
1193 {
1194 int ret, i;
1195 static struct sched s;
1196 struct command_task command_task_struct, *cmd_task = &command_task_struct;
1197 struct audiod_cmdline_parser_params params = {
1198 .override = 0,
1199 .initialize = 1,
1200 .check_required = 0,
1201 .check_ambiguity = 0,
1202 .print_errors = 1
1203 };
1204
1205 valid_fd_012();
1206 if (audiod_cmdline_parser_ext(argc, argv, &conf, &params))
1207 exit(EXIT_FAILURE);
1208 HANDLE_VERSION_FLAG("audiod", conf);
1209 /* init receivers/filters/writers early to make help work */
1210 recv_init();
1211 filter_init();
1212 writer_init();
1213 if (conf.help_given || conf.detailed_help_given)
1214 print_help_and_die();
1215 drop_privileges_or_die(conf.user_arg, conf.group_arg);
1216 parse_config_or_die();
1217 init_colors_or_die();
1218 daemon_set_flag(DF_LOG_TIME);
1219 daemon_set_flag(DF_LOG_HOSTNAME);
1220 daemon_set_flag(DF_LOG_LL);
1221 if (conf.logfile_given) {
1222 daemon_set_logfile(conf.logfile_arg);
1223 daemon_open_log_or_die();
1224 }
1225 ret = parse_stream_args();
1226 if (ret < 0) {
1227 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1228 exit(EXIT_FAILURE);
1229 }
1230 log_welcome("para_audiod");
1231 server_uptime(UPTIME_SET);
1232 set_initial_status();
1233 FOR_EACH_SLOT(i)
1234 clear_slot(i);
1235 init_grabbing();
1236 setup_signal_handling();
1237 signal_setup_default(sig_task);
1238
1239 init_status_task(stat_task);
1240 init_command_task(cmd_task);
1241
1242 if (conf.daemon_given)
1243 daemonize();
1244
1245 register_task(&sig_task->task);
1246 register_task(&cmd_task->task);
1247 register_task(&stat_task->task);
1248 s.default_timeout.tv_sec = 0;
1249 s.default_timeout.tv_usec = 99 * 1000;
1250 ret = schedule(&s);
1251
1252 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1253 return EXIT_FAILURE;
1254 }