695a6cfd32077e0ee0477078076ab2f8b8f11d29
[paraslash.git] / audiod.c
1 /*
2  * Copyright (C) 2005-2006 Andre Noll <noll@mathematik.tu-darmstadt.de>
3  *
4  *     This program is free software; you can redistribute it and/or modify
5  *     it under the terms of the GNU General Public License as published by
6  *     the Free Software Foundation; either version 2 of the License, or
7  *     (at your option) any later version.
8  *
9  *     This program is distributed in the hope that it will be useful,
10  *     but WITHOUT ANY WARRANTY; without even the implied warranty of
11  *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  *     GNU General Public License for more details.
13  *
14  *     You should have received a copy of the GNU General Public License
15  *     along with this program; if not, write to the Free Software
16  *     Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
17  */
18
19 /** \file audiod.c the paraslash's audio daemon */
20
21 #include <sys/time.h> /* gettimeofday */
22 #include "para.h"
23
24 #include "audiod.cmdline.h"
25 #include "list.h"
26 #include "close_on_fork.h"
27 #include "recv.h"
28 #include "filter.h"
29 #include "grab_client.cmdline.h"
30 #include "grab_client.h"
31
32 #include "error.h"
33 #include "audiod.h"
34 #include "net.h"
35 #include "daemon.h"
36 #include "string.h"
37
38 /** define the array of error lists needed by para_audiod */
39 INIT_AUDIOD_ERRLISTS;
40 /** define the array containing all supported audio formats */
41 DEFINE_AUDIO_FORMAT_ARRAY;
42
43 /**
44  * the possible modes of operation
45  *
46  * - off: disconnect from para_server
47  * - on: receive status information from para_server and play the audio stream
48  * - sb: only receive status information but not the audio stream
49 */
50 enum {AUDIOD_OFF, AUDIOD_ON, AUDIOD_STANDBY};
51
52 /** defines how to handle one supported audio format */
53 struct audio_format_info {
54 /** pointer to the receiver for this audio format */
55         struct receiver *receiver;
56 /** the receiver configuration */
57         void *receiver_conf;
58 /** the number of filters that should be activated for this audio format */
59         unsigned int num_filters;
60 /** pointer to the array of filters to be activated */
61         struct filter **filters;
62 /** pointer to the array of filter configurations */
63         void **filter_conf;
64 /** output of the last filter is written to stdin of this command */
65         char *write_cmd;
66 /** do not start receiver/filters/writer before this time */
67         struct timeval restart_barrier;
68 };
69
70 /**
71  * describes one instance of a receiver-filter-writer chain
72  *
73  * \sa receier_node, receiver, filter, filter_node, filter_chain_info
74   */
75 struct slot_info {
76 /** number of the audio format in this slot */
77         int format;
78 /** the file descriptor of the writer */
79         int write_fd;
80 /** the process id of the writer */
81         pid_t wpid;
82 /** time of the last successful read from the receiver */
83         struct timeval rtime;
84 /** time the last write to the write fd happend */
85         struct timeval wtime;
86 /** writer start time */
87         struct timeval wstime;
88 /** did we include \a write_fd in the fdset */
89         int  wcheck;
90 /** set to one if we have sent the TERM signal to \a wpid */
91         int wkilled;
92 /** the receiver info associated with this slot */
93         struct receiver_node *receiver_node;
94 /** the active filter chain */
95         struct filter_chain_info *fci;
96 };
97
98 static struct slot_info slot[MAX_STREAM_SLOTS];
99
100 /** defines one command of para_audiod */
101 struct audiod_command {
102 /** the name of the command */
103 const char *name;
104 /** pointer to the function that handles the command */
105 int (*handler)(int, int, char**);
106 /** one-line description of the command */
107 const char *description;
108 /** summary of the command line options */
109 const char *synopsis;
110 /** the long help text */
111 const char *help;
112 };
113
114 extern const char *status_item_list[NUM_STAT_ITEMS];
115
116 static int com_grab(int, int, char **);
117 static int com_cycle(int, int, char **);
118 static int com_help(int, int, char **);
119 static int com_off(int, int, char **);
120 static int com_on(int, int, char **);
121 static int com_sb(int, int, char **);
122 static int com_stat(int, int, char **);
123 static int com_term(int, int, char **);
124 static int stat_pipe = -1, signal_pipe;
125
126 static struct gengetopt_args_info conf;
127 static struct timeval server_stream_start, sa_time_diff;
128 static int playing, current_decoder = -1,
129         audiod_status = AUDIOD_ON, offset_seconds, length_seconds,
130         sa_time_diff_sign = 1, audiod_socket = -1;
131 static char *af_status, /* the audio format announced in server status */
132         *socket_name, *hostname;
133 static char *stat_item_values[NUM_STAT_ITEMS];
134 static FILE *logfile;
135 static const struct timeval restart_delay = {0, 300 * 1000};
136
137 static struct audio_format_info afi[NUM_AUDIO_FORMATS];
138
139 static struct audiod_command cmds[] = {
140 {
141 .name = "cycle",
142 .handler = com_cycle,
143 .description = "switch to next mode",
144 .synopsis = "cycle",
145 .help =
146
147 "on -> standby -> off -> on\n"
148
149 },
150 {
151 .name = "grab",
152 .handler = com_grab,
153 .description = "grab the audio stream",
154 .synopsis = "-- grab [grab_options]",
155 .help =
156
157 "grab ('splice') the audio stream at any position in the filter      \n"
158 "chain and send that data back to the client. Try\n"
159 "\t para_audioc -- grab -h\n"
160 "for the list of available options.\n"
161 },
162
163 {
164 .name = "help",
165 .handler = com_help,
166 .description = "display command list or help for given command",
167 .synopsis = "help [command]",
168 .help =
169
170 "When I was younger, so much younger than today, I never needed\n"
171 "anybody's help in any way. But now these days are gone, I'm not so\n"
172 "self assured. Now I find I've changed my mind and opened up the doors.\n"
173 "\n"
174 "                               -- Beatles: Help\n"
175
176 },
177 {
178 .name = "off",
179 .handler = com_off,
180 .description = "deactivate para_audiod",
181 .synopsis = "off",
182 .help =
183
184 "Close connection to para_server and stop all decoders.\n"
185
186 },
187 {
188 .name = "on",
189 .handler = com_on,
190 .description = "activate para_audiod",
191 .synopsis = "on",
192 .help =
193
194 "Establish connection to para_server, retrieve para_server's current\n"
195 "status. If playing, start corresponding decoder. Otherwise stop\n"
196 "all decoders.\n"
197
198 },
199 {
200 .name = "sb",
201 .handler = com_sb,
202 .description = "enter standby mode",
203 .synopsis = "sb",
204 .help =
205
206 "Stop all decoders but leave connection to para_server open.\n"
207
208 },
209 {
210 .name = "stat",
211 .handler = com_stat,
212 .description = "print status information",
213 .synopsis = "stat [item1 ...]",
214 .help =
215
216 "Dump given status items (all if none given) to stdout.\n"
217
218 },
219 {
220 .name = "term",
221 .handler = com_term,
222 .description = "terminate audiod",
223 .synopsis = "term",
224 .help =
225
226 "Stop all decoders, shut down connection to para_server and exit.\n"
227
228 },
229 {
230 .name = NULL,
231 }
232 };
233
234 /** iterate over all slots */
235 #define FOR_EACH_SLOT(slot) for (slot = 0; slot < MAX_STREAM_SLOTS; slot++)
236 /** iterate over all supported audio formats */
237 #define FOR_EACH_AUDIO_FORMAT(af) for (af = 0; af < NUM_AUDIO_FORMATS; af++)
238 /** iterate over the array of all audiod commands */
239 #define FOR_EACH_COMMAND(c) for (c = 0; cmds[c].name; c++)
240
241 /**
242  * get the audio format number
243  * \param name the name of the audio format
244  *
245  * \return The audio format number on success, -E_UNSUPPORTED_AUDIO_FORMAT if
246  * \a name is not a supported audio format.
247  */
248 int get_audio_format_num(char *name)
249 {
250         int i;
251         FOR_EACH_AUDIO_FORMAT(i)
252                 if (!strcmp(name, audio_formats[i]))
253                         return i;
254         return -E_UNSUPPORTED_AUDIO_FORMAT;
255 }
256
257 /*
258  * log function. first argument is loglevel.
259  */
260 void para_log(int ll, const char* fmt,...)
261 {
262         va_list argp;
263         FILE *outfd;
264         struct tm *tm;
265         time_t t1;
266         char str[MAXLINE] = "";
267
268         if (ll < conf.loglevel_arg)
269                 return;
270         if (!logfile && conf.logfile_given)
271                 logfile = open_log(conf.logfile_arg);
272         if (!logfile && conf.daemon_given)
273                 return;
274         if (!logfile) {
275                 if (ll < WARNING)
276                         outfd = stdout;
277                 else
278                         outfd = stderr;
279         } else
280                 outfd = logfile;
281         time(&t1);
282         tm = localtime(&t1);
283         strftime(str, MAXLINE, "%b %d %H:%M:%S", tm);
284         fprintf(outfd, "%s %s ", str, hostname);
285         if (conf.loglevel_arg <= INFO)
286                 fprintf(outfd, "%i ", ll);
287         va_start(argp, fmt);
288         vfprintf(outfd, fmt, argp);
289         va_end(argp);
290 }
291
292 static int client_write(int fd, const char *buf)
293 {
294         size_t len = strlen(buf);
295         return write(fd, buf, len) != len? -E_CLIENT_WRITE: 1;
296 }
297
298 static char *get_time_string(struct timeval *newest_stime)
299 {
300         struct timeval now, diff, adj_stream_start, tmp;
301         int total = 0, use_server_time = 1;
302
303         if (!playing) {
304                 if (length_seconds)
305                         return NULL;
306                 return make_message("%s:\n", status_item_list[SI_PLAY_TIME]);
307         }
308         if (audiod_status == AUDIOD_OFF)
309                 goto out;
310         if (sa_time_diff_sign > 0)
311                 tv_diff(&server_stream_start, &sa_time_diff,
312                         &adj_stream_start);
313         else
314                 tv_add(&server_stream_start, &sa_time_diff,
315                         &adj_stream_start);
316         tmp = adj_stream_start;
317         if (newest_stime && audiod_status == AUDIOD_ON) {
318                 tv_diff(newest_stime, &adj_stream_start, &diff);
319                 if (tv2ms(&diff) < 5000) {
320                         tmp = *newest_stime;
321                         use_server_time = 0;
322                 }
323         }
324         gettimeofday(&now, NULL);
325         tv_diff(&now, &tmp, &diff);
326         total = diff.tv_sec + offset_seconds;
327         if (total > length_seconds)
328                 total = length_seconds;
329         if (total < 0)
330                 total = 0;
331 out:
332         return make_message(
333                 "%s:%s%d:%02d [%d:%02d] (%d%%/%d:%02d)\n",
334                 status_item_list[SI_PLAY_TIME],
335                 use_server_time? "~" : "",
336                 total / 60,
337                 total % 60,
338                 (length_seconds - total) / 60,
339                 (length_seconds - total) % 60,
340                 length_seconds? (total * 100 + length_seconds / 2) /
341                         length_seconds : 0,
342                 length_seconds / 60,
343                 length_seconds % 60
344         );
345 }
346
347 __malloc static char *audiod_status_string(void)
348 {
349         const char *status = (audiod_status == AUDIOD_ON)?
350                 "on" : (audiod_status == AUDIOD_OFF)? "off": "sb";
351         return make_message("%s:%s\n", status_item_list[SI_AUDIOD_STATUS], status);
352 }
353
354 static struct timeval *wstime(void)
355 {
356         int i;
357         struct timeval *max = NULL;
358         FOR_EACH_SLOT(i) {
359                 struct slot_info *s = &slot[i];
360                 if (s->wpid <= 0)
361                         continue;
362                 if (max && tv_diff(&s->wstime, max, NULL) <= 0)
363                         continue;
364                 max = &s->wstime;
365         }
366         return max;
367 }
368 __malloc static char *decoder_flags(void)
369 {
370         int i;
371         char decoder_flags[MAX_STREAM_SLOTS + 1];
372
373         FOR_EACH_SLOT(i) {
374                 struct slot_info *s = &slot[i];
375                 char flag = '0';
376                 if (s->receiver_node)
377                         flag += 1;
378                 if (s->wpid > 0)
379                         flag += 2;
380                 if (flag != '0')
381                         flag += s->format * 4;
382                 decoder_flags[i] = flag;
383         }
384         decoder_flags[MAX_STREAM_SLOTS] = '\0';
385         return make_message("%s:%s\n", status_item_list[SI_DECODER_FLAGS],
386                 decoder_flags);
387 }
388
389 static char *configfile_exists(void)
390 {
391         static char *config_file;
392
393         if (!config_file) {
394                 char *home = para_homedir();
395                 config_file = make_message("%s/.paraslash/audiod.conf", home);
396                 free(home);
397         }
398         return file_exists(config_file)? config_file : NULL;
399 }
400
401 static void setup_signal_handling(void)
402 {
403         signal_pipe = para_signal_init();
404         PARA_INFO_LOG("signal pipe: fd %d\n", signal_pipe);
405         para_install_sighandler(SIGINT);
406         para_install_sighandler(SIGTERM);
407         para_install_sighandler(SIGCHLD);
408         para_install_sighandler(SIGHUP);
409         signal(SIGPIPE, SIG_IGN);
410 }
411
412 static void audiod_status_dump(void)
413 {
414         static char *p_ts, *p_us, *p_as, *p_df;
415         struct timeval *t = wstime();
416         char *us, *tmp = get_time_string(t);
417
418         if (tmp && (!p_ts || strcmp(tmp, p_ts)))
419                 stat_client_write(tmp, SI_PLAY_TIME);
420         free(p_ts);
421         p_ts = tmp;
422
423         us = uptime_str();
424         tmp = make_message("%s:%s\n", status_item_list[SI_AUDIOD_UPTIME], us);
425         free(us);
426         if (!p_us || strcmp(p_us, tmp))
427                 stat_client_write(tmp, SI_AUDIOD_UPTIME);
428         free(p_us);
429         p_us = tmp;
430
431         tmp = audiod_status_string();
432         if (!p_as || strcmp(p_as, tmp))
433                 stat_client_write(tmp, SI_AUDIOD_STATUS);
434         free(p_as);
435         p_as = tmp;
436
437         tmp = decoder_flags();
438         if (!p_df || strcmp(p_df, tmp))
439                 stat_client_write(tmp, SI_DECODER_FLAGS);
440         free(p_df);
441         p_df = tmp;
442 }
443
444 static void clear_slot(int slot_num)
445 {
446         struct slot_info *s = &slot[slot_num];
447
448         PARA_INFO_LOG("clearing slot %d\n", slot_num);
449         memset(s, 0, sizeof(struct slot_info));
450         s->format = -1;
451 }
452
453 static void kill_stream_writer(int slot_num)
454 {
455         struct slot_info *s = &slot[slot_num];
456
457         if (s->format < 0 || s->wkilled || s->wpid <= 0)
458                 return;
459         PARA_DEBUG_LOG("kill -TERM %d (%s stream writer in slot %d)\n",
460                 s->wpid, audio_formats[s->format], slot_num);
461         kill(s->wpid, SIGTERM);
462         s->wkilled = 1;
463         s->fci->error = 1;
464 }
465
466 static void set_restart_barrier(int format, struct timeval *now)
467 {
468         struct timeval tmp;
469
470         if (now)
471                 tmp = *now;
472         else
473                 gettimeofday(&tmp, NULL);
474         tv_add(&tmp, &restart_delay, &afi[format].restart_barrier);
475 }
476
477 static void close_receiver(int slot_num)
478 {
479         struct slot_info *s = &slot[slot_num];
480         struct audio_format_info *a;
481
482         if (s->format < 0 || !s->receiver_node)
483                 return;
484         a = &afi[s->format];
485         PARA_NOTICE_LOG("closing %s recevier in slot %d\n",
486                 audio_formats[s->format] , slot_num);
487         a->receiver->close(s->receiver_node);
488         free(s->receiver_node);
489         s->receiver_node = NULL;
490         set_restart_barrier(s->format, NULL);
491 }
492
493 static void kill_all_decoders(void)
494 {
495         int i;
496
497         FOR_EACH_SLOT(i)
498                 if (slot[i].format >= 0) {
499                         PARA_INFO_LOG("stopping decoder in slot %d\n", i);
500                         kill_stream_writer(i);
501                 }
502 }
503
504 static void check_sigchld(void)
505 {
506         pid_t pid;
507         int i;
508         struct timeval now;
509         gettimeofday(&now, NULL);
510
511 reap_next_child:
512         pid = para_reap_child();
513         if (pid <= 0)
514                 return;
515         FOR_EACH_SLOT(i) {
516                 struct slot_info *s = &slot[i];
517                 long lifetime;
518                 if (s->format < 0)
519                         continue;
520                 if (pid == s->wpid) {
521                         s->wpid = -1;
522                         lifetime = now.tv_sec - s->wstime.tv_sec;
523                         PARA_INFO_LOG("%s stream writer in slot %d died "
524                                 "after %li secs\n",
525                                 audio_formats[s->format], i, lifetime);
526                         set_restart_barrier(s->format, &now);
527                         goto reap_next_child;
528                 }
529         }
530         PARA_CRIT_LOG("para_client died (pid %d)\n", pid);
531         goto reap_next_child;
532 }
533
534 static int get_empty_slot(void)
535 {
536         int i;
537         struct slot_info *s;
538
539         FOR_EACH_SLOT(i) {
540                 s = &slot[i];
541                 if (s->format < 0) {
542                         clear_slot(i);
543                         return i;
544                 }
545                 if (s->write_fd > 0 || s->wpid > 0)
546                         continue;
547                 if (s->receiver_node)
548                         continue;
549                 if (s->fci)
550                         continue;
551                 clear_slot(i);
552                 return i;
553         }
554         return -E_NO_MORE_SLOTS;
555 }
556
557 static int decoder_running(int format)
558 {
559         int i, ret = 0;
560         struct slot_info *s;
561
562         FOR_EACH_SLOT(i) {
563                 s = &slot[i];
564                 if (s->format == format && s->receiver_node)
565                         ret |= 1;
566                 if (s->format == format && s->wpid > 0)
567                         ret |= 2;
568         }
569         return ret;
570 }
571
572 static void close_stat_pipe(void)
573 {
574         int i;
575
576         if (stat_pipe < 0)
577                 return;
578         PARA_NOTICE_LOG("%s", "closing status pipe\n");
579         close(stat_pipe);
580         del_close_on_fork_list(stat_pipe);
581         stat_pipe = -1;
582         kill_all_decoders();
583         for (i = 0; i < NUM_STAT_ITEMS; i++) {
584                 free(stat_item_values[i]);
585                 stat_item_values[i] = NULL;
586         }
587         dump_empty_status();
588         length_seconds = 0;
589         offset_seconds = 0;
590         audiod_status_dump();
591         playing = 0;
592         stat_item_values[SI_STATUS_BAR] = make_message("%s:no connection to para_server\n",
593                 status_item_list[SI_STATUS_BAR]);
594         stat_client_write(stat_item_values[SI_STATUS_BAR], SI_STATUS_BAR);
595 }
596
597 static void __noreturn clean_exit(int status, const char *msg)
598 {
599         PARA_EMERG_LOG("%s\n", msg);
600         kill_all_decoders();
601         if (socket_name)
602                 unlink(socket_name);
603         if (stat_pipe >= 0)
604                 close_stat_pipe();
605         exit(status);
606 }
607
608 __malloc static char *glob_cmd(char *cmd)
609 {
610         char *ret, *replacement;
611         struct timeval tmp, delay, rss; /* real stream start */
612
613         delay.tv_sec = conf.stream_delay_arg / 1000;
614         delay.tv_usec = (conf.stream_delay_arg % 1000) * 1000;
615 //      PARA_INFO_LOG("delay: %lu:%lu\n", delay.tv_sec, delay.tv_usec);
616         if (sa_time_diff_sign < 0)
617                 tv_add(&server_stream_start, &sa_time_diff, &rss);
618         else
619                 tv_diff(&server_stream_start, &sa_time_diff, &rss);
620         tv_add(&rss, &delay, &tmp);
621         replacement = make_message("%lu:%lu", tmp.tv_sec, tmp.tv_usec);
622         ret = s_a_r(cmd, "STREAM_START", replacement);
623         free(replacement);
624         if (!ret)
625                 goto out;
626         PARA_INFO_LOG("cmd: %s, repl: %s\n", cmd, ret);
627         {
628         struct timeval now;
629         gettimeofday(&now, NULL);
630         PARA_INFO_LOG("now: %lu:%lu\n", now.tv_sec, now.tv_usec);
631         }
632 out:
633         return ret;
634 }
635
636 /** get the number of filters for the given audio format */
637 int num_filters(int audio_format_num)
638 {
639         return afi[audio_format_num].num_filters;
640 }
641
642 static void open_filters(int slot_num)
643 {
644         struct slot_info *s = &slot[slot_num];
645         struct audio_format_info *a = &afi[s->format];
646         int nf = a->num_filters;
647         int i;
648
649         s->fci = para_calloc(sizeof(struct filter_chain_info));
650         INIT_LIST_HEAD(&s->fci->filters);
651         if (!nf)
652                 return;
653         s->fci->inbuf = s->receiver_node->buf;
654         s->fci->in_loaded = &s->receiver_node->loaded;
655         s->fci->outbuf = s->receiver_node->buf;
656         s->fci->out_loaded = &s->receiver_node->loaded;
657         s->fci->eof = &s->receiver_node->eof;
658         for (i = 0; i < nf; i++) {
659                 struct filter_node *fn = para_calloc(sizeof(struct filter_node));
660                 fn->conf = a->filter_conf[i];
661                 fn->fci = s->fci;
662                 fn->filter = a->filters[i];
663                 INIT_LIST_HEAD(&fn->callbacks);
664                 list_add_tail(&fn->node, &s->fci->filters);
665                 fn->filter->open(fn);
666                 PARA_NOTICE_LOG("%s filter %d/%d (%s) started in slot %d\n",
667                         audio_formats[s->format], i + 1,  nf,
668                         fn->filter->name, slot_num);
669                 s->fci->outbuf = fn->buf;
670                 s->fci->out_loaded = &fn->loaded;
671         }
672         PARA_DEBUG_LOG("output buffer for filter chain %p: %p\n", s->fci,
673                 s->fci->outbuf);
674 }
675
676 static struct filter_node *find_filter_node(int slot_num, int format, int filternum)
677 {
678         struct filter_node *fn;
679         int i, j;
680
681         FOR_EACH_SLOT(i) {
682                 struct slot_info *s = &slot[i];
683                 if (s->format < 0 || !s->fci)
684                         continue;
685                 if (slot_num >= 0 && slot_num != i)
686                         continue;
687                 if (format >= 0 && s->format != format)
688                         continue;
689                 if (num_filters(i) < filternum)
690                         continue;
691                 /* success */
692                 j = 1;
693                 list_for_each_entry(fn, &s->fci->filters, node)
694                         if (filternum <= 0 || j++ == filternum)
695                                 break;
696                 return fn;
697         }
698         return NULL;
699 }
700
701 static void start_stream_writer(int slot_num)
702 {
703         int ret, fds[3] = {1, -1, -1};
704         struct slot_info *s = &slot[slot_num];
705         struct audio_format_info *a = &afi[s->format];
706         char *glob = NULL;
707
708         if (a->write_cmd)
709                 glob = glob_cmd(a->write_cmd);
710         if (!glob)
711                 glob = para_strdup("para_play");
712         PARA_INFO_LOG("starting stream writer: %s\n", glob);
713         open_filters(slot_num);
714         ret = para_exec_cmdline_pid(&s->wpid, glob, fds);
715         free(glob);
716         if (ret < 0) {
717                 PARA_ERROR_LOG("exec failed (%d)\n", ret);
718                 return;
719         }
720         s->write_fd = fds[0];
721         add_close_on_fork_list(s->write_fd);
722         /* we write to this fd in do_select, so we need non-blocking */
723         fcntl(s->write_fd, F_SETFL, O_NONBLOCK);
724         gettimeofday(&s->wstime, NULL);
725         current_decoder = slot_num;
726         activate_inactive_grab_clients(slot_num, s->format, &s->fci->filters);
727 }
728
729 static void open_receiver(int format)
730 {
731         struct audio_format_info *a = &afi[format];
732         struct slot_info *s;
733         int ret, slot_num;
734
735         slot_num = get_empty_slot();
736         if (slot_num < 0)
737                 clean_exit(EXIT_FAILURE, PARA_STRERROR(-slot_num));
738         s = &slot[slot_num];
739         s->format = format;
740         gettimeofday(&s->rtime, NULL);
741         s->wtime = s->rtime;
742         s->receiver_node = para_calloc(sizeof(struct receiver_node));
743         s->receiver_node->conf = a->receiver_conf;
744         ret = a->receiver->open(s->receiver_node);
745         if (ret < 0) {
746                 PARA_ERROR_LOG("failed to open receiver (%s)\n",
747                         PARA_STRERROR(-ret));
748                 free(s->receiver_node);
749                 s->receiver_node = NULL;
750                 return;
751         }
752         PARA_NOTICE_LOG("started %s: %s receiver in slot %d\n",
753                 audio_formats[s->format], a->receiver->name, slot_num);
754 }
755
756 static int is_frozen(int format)
757 {
758         struct timeval now;
759         struct audio_format_info *a = &afi[format];
760
761         gettimeofday(&now, NULL);
762         return (tv_diff(&now, &a->restart_barrier, NULL) > 0)? 0 : 1;
763 }
764
765 static void start_current_receiver(void)
766 {
767         int i;
768
769         if (!af_status)
770                 return;
771         i = get_audio_format_num(af_status);
772         if (i < 0)
773                 return;
774         if ((decoder_running(i) & 1) || is_frozen(i))
775                 return;
776         open_receiver(i);
777 }
778
779 static void compute_time_diff(const struct timeval *status_time)
780 {
781         struct timeval now, tmp, diff;
782         static int count;
783         int sign;
784         const struct timeval max_deviation = {0, 500 * 1000};
785         const int time_smooth = 5;
786
787         gettimeofday(&now, NULL);
788         sign = tv_diff(status_time, &now, &diff);
789 //              PARA_NOTICE_LOG("%s: sign = %i, sa_time_diff_sign = %i\n", __func__,
790 //                      sign, sa_time_diff_sign);
791         if (!count) {
792                 sa_time_diff_sign = sign;
793                 sa_time_diff = diff;
794                 count++;
795                 return;
796         }
797         if (count > 5) {
798                 int s = tv_diff(&diff, &sa_time_diff, &tmp);
799                 if (tv_diff(&max_deviation, &tmp, NULL) < 0)
800                         PARA_WARNING_LOG("time diff jump: %lims\n",
801                                 s * tv2ms(&tmp));
802         }
803         count++;
804         sa_time_diff_sign = tv_convex_combination(
805                 sa_time_diff_sign * time_smooth, &sa_time_diff,
806                 count > 10? sign : sign * time_smooth, &diff,
807                 &tmp);
808         sa_time_diff = tmp;
809         PARA_INFO_LOG("time diff (cur/avg): "
810                 "%li:%lu/%li:%lu\n",
811                 sign * diff.tv_sec, (diff.tv_usec + 500) / 1000,
812                 sa_time_diff_sign * sa_time_diff.tv_sec,
813                 (sa_time_diff.tv_usec + 500)/ 1000);
814 }
815
816 static void check_stat_line(char *line)
817 {
818         int itemnum;
819         size_t ilen = 0;
820         struct timeval tv;
821         char *tmp;
822
823         if (!line)
824                 return;
825         itemnum = stat_line_valid(line);
826         if (itemnum < 0) {
827                 PARA_WARNING_LOG("invalid status line: %s\n", line);
828                 return;
829         }
830         tmp = make_message("%s\n", line);
831         stat_client_write(tmp, itemnum);
832         free(tmp);
833         free(stat_item_values[itemnum]);
834         stat_item_values[itemnum] = para_strdup(line);
835         ilen = strlen(status_item_list[itemnum]);
836         switch (itemnum) {
837         case SI_STATUS:
838                 playing = strstr(line, "playing")? 1 : 0;
839                 break;
840         case SI_FORMAT:
841                 free(af_status);
842                 af_status = para_strdup(line + ilen + 1);
843                 break;
844         case SI_OFFSET:
845                 offset_seconds = atoi(line + ilen + 1);
846                 break;
847         case SI_LENGTH:
848                 length_seconds = atoi(line + ilen + 1);
849                 break;
850         case SI_STREAM_START:
851                 if (sscanf(line + ilen + 1, "%lu.%lu",
852                                 &tv.tv_sec, &tv.tv_usec) == 2)
853                         server_stream_start = tv;
854                 break;
855         case SI_CURRENT_TIME:
856                 if (sscanf(line + ilen + 1, "%lu.%lu", &tv.tv_sec,
857                                 &tv.tv_usec) == 2)
858                         compute_time_diff(&tv);
859                 break;
860         }
861 }
862
863 static void handle_signal(int sig)
864 {
865         switch (sig) {
866         case SIGCHLD:
867                 return check_sigchld();
868         case SIGINT:
869         case SIGTERM:
870         case SIGHUP:
871                 PARA_EMERG_LOG("terminating on signal %d\n", sig);
872                 clean_exit(EXIT_FAILURE, "caught deadly signal");
873                 return;
874         }
875 }
876
877 static void check_timeouts(void)
878 {
879         struct timeval now;
880         int slot_num, timeout = conf.stream_timeout_arg;
881
882         gettimeofday(&now, NULL);
883         FOR_EACH_SLOT(slot_num) {
884                 struct slot_info *s = &slot[slot_num];
885                 if (s->format < 0)
886                         continue;
887                 /* check read time */
888                 if (s->receiver_node &&
889                         now.tv_sec > s->rtime.tv_sec + timeout) {
890                         PARA_INFO_LOG("%s input buffer (slot %d) not ready\n",
891                                 audio_formats[s->format], slot_num);
892                         if (s->fci)
893                                 s->fci->error = 42;
894                         else
895                                 close_receiver(slot_num);
896                 }
897                 /* check write time */
898                 if (s->wpid > 0 && !s->wkilled &&
899                         now.tv_sec > s->wtime.tv_sec + timeout) {
900                         PARA_INFO_LOG("%s output buffer (slot %d) not ready\n",
901                                 audio_formats[s->format], slot_num);
902                         if (s->fci)
903                                 s->fci->error = 42;
904                 }
905         }
906 }
907
908 static size_t get_loaded_bytes(int slot_num)
909 {
910         size_t loaded = 0;
911         struct slot_info *s = &slot[slot_num];
912         struct receiver_node *rn = s->receiver_node;
913
914         if (s->format < 0)
915                 goto out;
916
917         if (afi[s->format].num_filters) {
918                 if (s->fci)
919                         loaded = *s->fci->out_loaded;
920         } else {
921                 if (rn)
922                         loaded = rn->loaded;
923         }
924 out:
925         return loaded;
926 }
927
928
929 static void close_decoder_if_idle(int slot_num)
930 {
931         struct slot_info *s = &slot[slot_num];
932         struct receiver_node *rn = s->receiver_node;
933
934         if (s->format < 0)
935                 return;
936         if (!s->fci)
937                 return;
938         if (!rn->eof && !s->fci->error && s->wpid > 0)
939                 return;
940         if (!s->fci->error && s->wpid > 0) { /* eof */
941                 if (filter_io(s->fci) > 0)
942                         return;
943                 if (get_loaded_bytes(slot_num))
944                         return;
945         }
946         if (s->write_fd > 0) {
947                 PARA_INFO_LOG("slot %d: closing write fd %d\n", slot_num,
948                         s->write_fd);
949                 close(s->write_fd);
950                 del_close_on_fork_list(s->write_fd);
951                 s->write_fd = -1;
952         }
953         if (s->wpid > 0)
954                 return; /* wait until writer dies before closing filters */
955         PARA_INFO_LOG("closing all filters in slot %d (filter_chain %p)\n",
956                 slot_num, s->fci);
957         close_filters(s->fci);
958         free(s->fci);
959         close_receiver(slot_num);
960         clear_slot(slot_num);
961 }
962
963 static int set_stream_fds(fd_set *wfds)
964 {
965         int i, max_fileno = -1;
966
967         check_timeouts();
968         FOR_EACH_SLOT(i) {
969                 struct slot_info *s = &slot[i];
970                 struct audio_format_info *a;
971                 struct receiver_node *rn;
972
973                 close_decoder_if_idle(i);
974                 s->wcheck = 0;
975                 if (s->format < 0)
976                         continue;
977                 a = &afi[s->format];
978                 rn = s->receiver_node;
979                 if (rn && rn->loaded && !s->wpid) {
980                         PARA_INFO_LOG("no writer in slot %d\n", i);
981                         start_stream_writer(i);
982                 }
983                 if (s->write_fd <= 0)
984                         continue;
985                 if (!get_loaded_bytes(i))
986                         continue;
987                 FD_SET(s->write_fd, wfds);
988                 s->wcheck = 1;
989                 max_fileno = MAX(s->write_fd, max_fileno);
990         }
991 //      PARA_INFO_LOG("return %d\n", max_fileno);
992         return max_fileno;
993 }
994
995 static int write_audio_data(int slot_num)
996 {
997         struct slot_info *s = &slot[slot_num];
998         struct audio_format_info *a = &afi[s->format];
999         struct receiver_node *rn = s->receiver_node;
1000         int rv;
1001         char **buf;
1002         size_t *len;
1003
1004         if (a->num_filters) {
1005                 buf = &s->fci->outbuf;
1006                 len = s->fci->out_loaded;
1007         } else {
1008                 buf = &rn->buf;
1009                 len = &rn->loaded;
1010         }
1011         PARA_DEBUG_LOG("writing %p (%zd bytes)\n", *buf, *len);
1012         rv = write(s->write_fd, *buf, *len);
1013         PARA_DEBUG_LOG("wrote %d/%zd\n", rv, *len);
1014         if (rv < 0) {
1015                 PARA_WARNING_LOG("write error in slot %d (fd %d): %s\n",
1016                         slot_num, s->write_fd, strerror(errno));
1017                 *len = 0;
1018                 s->fci->error = E_WRITE_AUDIO_DATA;
1019         } else if (rv != *len) {
1020                 PARA_DEBUG_LOG("partial %s write (%i/%zd) for slot %d\n",
1021                         audio_formats[s->format], rv, *len, slot_num);
1022                 *len -= rv;
1023                 memmove(*buf, *buf + rv, *len);
1024         } else
1025                 *len = 0;
1026         if (rv > 0)
1027                 gettimeofday(&s->wtime, NULL);
1028         return rv;
1029 }
1030
1031 static void slot_io(fd_set *wfds)
1032 {
1033         int ret, i;
1034
1035         FOR_EACH_SLOT(i) {
1036                 struct slot_info *s = &slot[i];
1037                 struct receiver_node *rn = s->receiver_node;
1038
1039                 if (rn && rn->loaded)
1040                         gettimeofday(&s->rtime, NULL);
1041                 if (s->format >= 0 && s->write_fd > 0 && s->fci) {
1042                         ret = filter_io(s->fci);
1043                         if (ret < 0)
1044                                 s->fci->error = -ret;
1045 //                      PARA_DEBUG_LOG("slot %d, filter io %d bytes, check write: %d, loaded: %d/%d, eof: %d\n",
1046 //                               i, ret, s->wcheck, rn->loaded, *s->fci->out_loaded, rn->eof);
1047                 }
1048                 if (s->write_fd <= 0 || !s->wcheck || !FD_ISSET(s->write_fd, wfds))
1049                         continue;
1050                 write_audio_data(i);
1051         }
1052 }
1053
1054 static int parse_stream_command(const char *txt, char **cmd)
1055 {
1056         char *p = strchr(txt, ':');
1057         int i;
1058
1059         if (!p)
1060                 return -E_MISSING_COLON;
1061         p++;
1062         FOR_EACH_AUDIO_FORMAT(i) {
1063                 if (strncmp(txt, audio_formats[i], strlen(audio_formats[i])))
1064                         continue;
1065                 *cmd = p;
1066                 return i;
1067         }
1068         return -E_UNSUPPORTED_AUDIO_FORMAT;
1069 }
1070
1071 static int add_filter(int format, char *cmdline)
1072 {
1073         struct audio_format_info *a = &afi[format];
1074         int filter_num, nf = a->num_filters;
1075
1076         filter_num = check_filter_arg(cmdline, &a->filter_conf[nf]);
1077         if (filter_num < 0)
1078                 return filter_num;
1079         a->filters[nf] = &filters[filter_num];
1080         a->num_filters++;
1081         PARA_INFO_LOG("%s filter %d: %s\n", audio_formats[format], nf + 1,
1082                 a->filters[nf]->name);
1083         return filter_num;
1084 }
1085
1086 static int setup_default_filters(void)
1087 {
1088         int i, ret = 1;
1089
1090         FOR_EACH_AUDIO_FORMAT(i) {
1091                 struct audio_format_info *a = &afi[i];
1092                 char *tmp;
1093                 int j;
1094                 if (a->num_filters)
1095                         continue;
1096                 /* add "dec" to audio format name */
1097                 tmp = make_message("%sdec", audio_formats[i]);
1098                 for (j = 0; filters[j].name; j++)
1099                         if (!strcmp(tmp, filters[j].name))
1100                                 break;
1101                 free(tmp);
1102                 ret = -E_UNSUPPORTED_FILTER;
1103                 if (!filters[j].name)
1104                         goto out;
1105                 tmp = para_strdup(filters[j].name);
1106                 ret = add_filter(i, tmp);
1107                 free(tmp);
1108                 if (ret < 0)
1109                         goto out;
1110                 PARA_INFO_LOG("%s -> default filter: %s\n", audio_formats[i], filters[j].name);
1111                 ret = add_filter(i, para_strdup("wav"));
1112                 if (ret < 0)
1113                         goto out;
1114                 PARA_INFO_LOG("%s -> default filter: wav\n", audio_formats[i]);
1115         }
1116 out:
1117         return ret;
1118 }
1119
1120 static int init_stream_io(void)
1121 {
1122         int i, ret, receiver_num;
1123         char *cmd;
1124
1125         for (i = 0; i < conf.stream_write_cmd_given; i++) {
1126                 ret = parse_stream_command(conf.stream_write_cmd_arg[i], &cmd);
1127                 if (ret < 0)
1128                         goto out;
1129                 afi[ret].write_cmd = para_strdup(cmd);
1130                 PARA_INFO_LOG("%s write command: %s\n", audio_formats[ret], afi[ret].write_cmd);
1131         }
1132         for (i = 0; receivers[i].name; i++) {
1133                 PARA_INFO_LOG("initializing %s receiver\n", receivers[i].name);
1134                 receivers[i].init(&receivers[i]);
1135         }
1136         for (i = 0; i < conf.receiver_given; i++) {
1137                 char *arg = conf.receiver_arg[i];
1138                 char *recv = strchr(arg, ':');
1139                 ret = -E_MISSING_COLON;
1140                 if (!recv)
1141                         goto out;
1142                 *recv = '\0';
1143                 recv++;
1144                 ret = get_audio_format_num(arg);
1145                 if (ret < 0)
1146                         goto out;
1147                 afi[ret].receiver_conf = check_receiver_arg(recv, &receiver_num);
1148                 if (!afi[ret].receiver_conf) {
1149                         ret = -E_RECV_SYNTAX;
1150                         goto out;
1151                 }
1152                 afi[ret].receiver = &receivers[receiver_num];
1153         }
1154         /* use the first available receiver with no arguments
1155          * for those audio formats for which no receiver
1156          * was specified
1157          */
1158         cmd = para_strdup(receivers[0].name);
1159         FOR_EACH_AUDIO_FORMAT(i) {
1160                 struct audio_format_info *a = &afi[i];
1161                 if (a->receiver_conf)
1162                         continue;
1163                 a->receiver_conf = check_receiver_arg(cmd, &receiver_num);
1164                 if (!a->receiver_conf)
1165                         return -E_RECV_SYNTAX;
1166                 a->receiver = &receivers[receiver_num];
1167         }
1168         free(cmd);
1169         /* filters */
1170         filter_init(filters);
1171         FOR_EACH_AUDIO_FORMAT(i) {
1172                 afi[i].filter_conf = para_malloc((conf.filter_given + 1) * sizeof(char *));
1173                 afi[i].filters = para_malloc((conf.filter_given + 1) * sizeof(struct filter *));
1174         }
1175         if (!conf.no_default_filters_given)
1176                 return setup_default_filters();
1177         for (i = 0; i < conf.filter_given; i++) {
1178                 char *arg = conf.filter_arg[i];
1179                 char *filter_name = strchr(arg, ':');
1180                 ret = -E_MISSING_COLON;
1181                 if (!filter_name)
1182                         goto out;
1183                 *filter_name = '\0';
1184                 filter_name++;
1185                 ret = get_audio_format_num(arg);
1186                 if (ret < 0)
1187                         goto out;
1188                 ret = add_filter(ret, filter_name);
1189                 if (ret < 0)
1190                         goto out;
1191         }
1192         ret = 1;
1193 out:
1194         return ret;
1195 }
1196
1197 static int dump_commands(int fd)
1198 {
1199         char *buf = para_strdup(""), *tmp = NULL;
1200         int i;
1201         ssize_t ret;
1202
1203         FOR_EACH_COMMAND(i) {
1204                 tmp = make_message("%s%s\t%s\n", buf, cmds[i].name,
1205                         cmds[i].description);
1206                 free(buf);
1207                 buf = tmp;
1208         }
1209         ret = client_write(fd, buf);
1210         free(buf);
1211         return ret;
1212 }
1213
1214 /*
1215  * command handlers don't close their fd on errors (ret < 0) so that
1216  * its caller can send an error message. Otherwise (ret >= 0) it's up
1217  * to each individual command to close the fd if necessary.
1218  */
1219
1220 static int com_help(int fd, int argc, char **argv)
1221 {
1222         int i, ret;
1223         char *buf;
1224         const char *dflt = "No such command. Available commands:\n";
1225
1226         if (argc < 2) {
1227                 ret = dump_commands(fd);
1228                 goto out;
1229         }
1230         FOR_EACH_COMMAND(i) {
1231                 if (strcmp(cmds[i].name, argv[1]))
1232                         continue;
1233                 buf = make_message(
1234                         "NAME\n\t%s -- %s\n"
1235                         "SYNOPSIS\n\tpara_audioc %s\n"
1236                         "DESCRIPTION\n%s\n",
1237                         argv[1],
1238                         cmds[i].description,
1239                         cmds[i].synopsis,
1240                         cmds[i].help
1241                 );
1242                 ret = client_write(fd, buf);
1243                 free(buf);
1244                 goto out;
1245         }
1246         ret = client_write(fd, dflt);
1247         if (ret > 0)
1248                 ret = dump_commands(fd);
1249 out:
1250         if (ret >= 0)
1251                 close(fd);
1252         return ret;
1253 }
1254
1255 static int com_stat(int fd, __unused int argc, __unused char **argv)
1256 {
1257         int i, ret;
1258         char *buf = NULL;
1259         long unsigned mask = ~0LU;
1260
1261         if (argc > 1) {
1262                 mask = 0;
1263                 for (i = 1; i < argc; i++) {
1264                         ret = stat_item_valid(argv[i]);
1265                         if (ret < 0)
1266                                 return ret;
1267                         mask |= (1 << ret);
1268                 }
1269         }
1270         PARA_INFO_LOG("mask: 0x%lx\n", mask);
1271         if (mask & (1 << SI_PLAY_TIME)) {
1272                 struct timeval *t = wstime();
1273                 char *ts = get_time_string(t);
1274                 if (ts) {
1275                         ret = client_write(fd, ts);
1276                         if (ret < 0)
1277                                 goto out;
1278                         free(ts);
1279                 }
1280         }
1281         if (mask & (1 << SI_AUDIOD_UPTIME)) {
1282                 char *tmp, *us = uptime_str();
1283                 tmp = make_message("%s:%s\n",
1284                         status_item_list[SI_AUDIOD_UPTIME], us);
1285                 free(us);
1286                 ret = client_write(fd, tmp);
1287                 if (ret < 0)
1288                         goto out;
1289                 free(tmp);
1290         }
1291         if (mask & (1 << SI_AUDIOD_STATUS)) {
1292                 char *s = audiod_status_string();
1293                 ret = client_write(fd, s);
1294                 if (ret < 0)
1295                         goto out;
1296                 free(s);
1297         }
1298         if (mask & (1 << SI_DECODER_FLAGS)) {
1299                 char *df =decoder_flags();
1300                 ret = client_write(fd, df);
1301                 if (ret < 0)
1302                         goto out;
1303                 free(df);
1304         }
1305
1306         for (i = 0; i < NUM_STAT_ITEMS; i++) {
1307                 char *tmp, *v;
1308                 if (!((1 << i) & mask))
1309                         continue;
1310                 v = stat_item_values[i];
1311                 tmp = make_message("%s%s%s", buf? buf: "",
1312                         v? v : "", v? "\n" : "");
1313                 free(buf);
1314                 buf = tmp;
1315         }
1316         ret = client_write(fd, buf);
1317 out:
1318         if (ret > 0)
1319                 ret = stat_client_add(fd, mask);
1320         free(buf);
1321         return ret;
1322 }
1323
1324 #if 0
1325 static char *list_filters(void)
1326 {
1327         int i, j;
1328         char *tmp, *msg = make_message("format\tnum\tcmd\n");
1329
1330         FOR_EACH_AUDIO_FORMAT(i) {
1331                 for (j = 0; j < afi[i].num_filters; j++) {
1332                         tmp = make_message("%s\t%i\t%s\n",
1333                                 afi[i].name, j, afi[i].filter_cmds[j]);
1334                         msg = para_strcat(msg, tmp);
1335                         free(tmp);
1336                 }
1337                 tmp = make_message("%s\t%i\t%s\n", afi[i].name,
1338                         j, afi[i].write_cmd);
1339                 msg = para_strcat(msg, tmp);
1340                 free(tmp);
1341         }
1342         return msg;
1343 }
1344 #endif
1345
1346 static int com_grab(int fd, int argc, char **argv)
1347 {
1348         struct grab_client *gc;
1349         struct filter_node *fn;
1350         int i, err;
1351         char *msg;
1352
1353         PARA_INFO_LOG("argc: %d, argv[0]: %s, optind: %d\n", argc, argv[0], optind);
1354         gc = grab_client_new(fd, argc, argv, &err);
1355         PARA_INFO_LOG("argc: %d, argv[0]: %s, optind: %d\n", argc, argv[0], optind);
1356         if (!gc)
1357                 goto err_out;
1358         fn = find_filter_node(gc->conf->slot_arg, gc->audio_format_num, gc->conf->filter_num_arg);
1359         if (fn)
1360                 activate_grab_client(gc, fn);
1361         return 1;
1362 err_out:
1363         if (err != -E_GC_HELP_GIVEN && err != -E_GC_VERSION_GIVEN)
1364                 return err;
1365         if (err == -E_GC_HELP_GIVEN) {
1366                 msg = make_message("%s\n\n", grab_client_args_info_usage);
1367                 for (i = 0; grab_client_args_info_help[i]; i++) {
1368                         char *tmp = make_message("%s%s\n", msg,
1369                                 grab_client_args_info_help[i]);
1370                         free(msg);
1371                         msg = tmp;
1372                 }
1373         } else
1374                 msg = make_message("%s %s\n",
1375                         GRAB_CLIENT_CMDLINE_PARSER_PACKAGE,
1376                         GRAB_CLIENT_CMDLINE_PARSER_VERSION);
1377         err = client_write(fd, msg);
1378         free(msg);
1379         if (err < 0)
1380                 return err;
1381         close(fd);
1382         return 1;
1383 }
1384
1385 static int __noreturn com_term(int fd, __unused int argc, __unused char **argv)
1386 {
1387         close(fd);
1388         clean_exit(EXIT_SUCCESS, "terminating on user request");
1389 }
1390
1391 static int com_on(int fd, __unused int argc, __unused char **argv)
1392 {
1393         audiod_status = AUDIOD_ON;
1394         close(fd);
1395         return 1;
1396 }
1397
1398 static int com_off(int fd, __unused int argc, __unused char **argv)
1399 {
1400         audiod_status = AUDIOD_OFF;
1401         close(fd);
1402         return 1;
1403 }
1404
1405 static int com_sb(int fd, __unused int argc, __unused char **argv)
1406 {
1407         audiod_status = AUDIOD_STANDBY;
1408         close(fd);
1409         return 1;
1410 }
1411
1412 static int com_cycle(int fd, int argc, char **argv)
1413 {
1414         switch (audiod_status) {
1415                 case  AUDIOD_ON:
1416                         return com_sb(fd, argc, argv);
1417                         break;
1418                 case  AUDIOD_OFF:
1419                         return com_on(fd, argc, argv);
1420                         break;
1421                 case  AUDIOD_STANDBY:
1422                         return com_off(fd, argc, argv);
1423                         break;
1424         }
1425         close(fd);
1426         return 1;
1427 }
1428
1429 static int check_perms(struct ucred *c)
1430 {
1431         int i;
1432
1433         if (!conf.user_allow_given)
1434                 return 1;
1435         for (i = 0; i < conf.user_allow_given; i++)
1436                 if (c->uid == conf.user_allow_arg[i])
1437                         return 1;
1438         return -E_UCRED_PERM;
1439 }
1440
1441 static int handle_connect(void)
1442 {
1443         int i, argc, ret, clifd = -1;
1444         struct ucred c;
1445         char *buf = para_malloc(MAXLINE), **argv = NULL;
1446         struct sockaddr_un unix_addr;
1447
1448         ret = para_accept(audiod_socket, &unix_addr, sizeof(struct sockaddr_un));
1449         if (ret < 0)
1450                 goto out;
1451         clifd = ret;
1452         ret = recv_cred_buffer(clifd, buf, MAXLINE - 1, &c);
1453         if (ret < 0)
1454                 goto out;
1455         PARA_INFO_LOG("pid: %i, uid: %i, gid: %i, ret: %i, buf: %s\n", c.pid, c.uid, c.gid, ret, buf);
1456         buf[ret] = '\0';
1457         ret = check_perms(&c);
1458         if (ret < 0)
1459                 goto out;
1460         argc = split_args(buf, &argv, '\n');
1461         PARA_INFO_LOG("argv[0]: %s\n", argv[0]);
1462         for (i = 0; cmds[i].name; i++) {
1463                 if (strcmp(cmds[i].name, argv[0]))
1464                         continue;
1465                 ret = cmds[i].handler(clifd, argc + 1, argv);
1466                 goto out;
1467         }
1468         ret = -E_INVALID_AUDIOD_CMD; /* cmd not found */
1469 out:
1470         free(buf);
1471         free(argv);
1472         if (clifd > 0 && ret < 0 && ret != -E_CLIENT_WRITE) {
1473                 char *tmp = make_message("%s\n", PARA_STRERROR(-ret));
1474                 client_write(clifd, tmp);
1475                 free(tmp);
1476                 close(clifd);
1477         }
1478         return ret;
1479 }
1480
1481 static void audiod_get_socket(void)
1482 {
1483         struct sockaddr_un unix_addr;
1484
1485         if (conf.socket_given)
1486                 socket_name = para_strdup(conf.socket_arg);
1487         else {
1488                 char *hn = para_hostname();
1489                 socket_name = make_message("/var/paraslash/audiod_socket.%s",
1490                         hn);
1491                 free(hn);
1492         }
1493         PARA_NOTICE_LOG("connecting to local socket %s\n", socket_name);
1494         if (conf.force_given)
1495                 unlink(socket_name);
1496         audiod_socket = create_pf_socket(socket_name, &unix_addr,
1497                         S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IWOTH);
1498         if (audiod_socket < 0) {
1499                 PARA_EMERG_LOG("%s", "can not connect to socket\n");
1500                 exit(EXIT_FAILURE); /* do not unlink socket */
1501         }
1502         if (listen(audiod_socket, 5) < 0) {
1503                 PARA_EMERG_LOG("%s", "can not listen on socket\n");
1504                 exit(EXIT_FAILURE); /* do not unlink socket */
1505         }
1506         add_close_on_fork_list(audiod_socket);
1507 }
1508
1509 static int open_stat_pipe(void)
1510 {
1511         int ret, fd[3] = {-1, 1, 0};
1512         pid_t pid;
1513         ret = para_exec_cmdline_pid(&pid, BINDIR "/para_client stat", fd);
1514         if (ret >= 0) {
1515                 ret = fd[1];
1516                 PARA_NOTICE_LOG("stat pipe opened, fd %d\n", ret);
1517                 add_close_on_fork_list(ret);
1518         } else
1519                 clean_exit(EXIT_FAILURE, "failed to open status pipe");
1520         return ret;
1521 }
1522
1523 static int audiod_pre_select(fd_set *rfds, fd_set *wfds, struct timeval *tv)
1524 {
1525         int i, ret, max = -1;
1526
1527         FOR_EACH_SLOT(i) {
1528                 struct slot_info *s = &slot[i];
1529                 struct audio_format_info *a;
1530                 struct receiver_node *rn = s->receiver_node;
1531                 if (s->format < 0 || !rn)
1532                         continue;
1533                 a = &afi[s->format];
1534                 ret = a->receiver->pre_select(rn, rfds, wfds, tv);
1535 //              PARA_NOTICE_LOG("%s preselect: %d\n", a->receiver->name, ret);
1536                 max = MAX(max, ret);
1537         }
1538         return max;
1539
1540 }
1541 static void audiod_post_select(int select_ret, fd_set *rfds, fd_set *wfds)
1542 {
1543         int i, ret;
1544
1545         FOR_EACH_SLOT(i) {
1546                 struct slot_info *s = &slot[i];
1547                 struct audio_format_info *a;
1548                 struct receiver_node *rn = s->receiver_node;
1549                 if (s->format < 0 || !rn || rn->eof)
1550                         continue;
1551                 a = &afi[s->format];
1552                 ret = a->receiver->post_select(rn, select_ret, rfds, wfds);
1553                 if (ret <= 0) {
1554                         if (ret)
1555                                 PARA_ERROR_LOG("%s post select failed: %s (slot %d)\n",
1556                                 a->receiver->name, PARA_STRERROR(-ret), i);
1557                         else
1558                                 PARA_INFO_LOG("eof in slot %d\n", i);
1559                         rn->eof = 1;
1560                 }
1561                 if (ret < 0 && s->fci)
1562                         s->fci->error = ret;
1563         }
1564 }
1565
1566 /* TODO: move everything before the select call to pre_select() */
1567 static void __noreturn audiod_mainloop(void)
1568 {
1569         fd_set rfds, wfds;
1570         int ret, max_fileno, sbo = 0;
1571         char status_buf[STRINGSIZE] = "";
1572         struct timeval tv;
1573 repeat:
1574         FD_ZERO(&wfds);
1575         FD_ZERO(&rfds);
1576         /* always check signal pipe and the local socket */
1577         FD_SET(signal_pipe, &rfds);
1578         max_fileno = signal_pipe;
1579         FD_SET(audiod_socket, &rfds);
1580         max_fileno = MAX(max_fileno, audiod_socket);
1581
1582         if (audiod_status != AUDIOD_ON)
1583                 kill_all_decoders();
1584         else if (playing)
1585                 start_current_receiver();
1586
1587         max_fileno = MAX(max_fileno, set_stream_fds(&wfds));
1588         /* status pipe */
1589         if (stat_pipe >= 0 && audiod_status == AUDIOD_OFF)
1590                 close_stat_pipe();
1591         if (stat_pipe < 0 && audiod_status != AUDIOD_OFF) {
1592                 stat_pipe = open_stat_pipe();
1593                 sbo = 0;
1594                 status_buf[0] = '\0';
1595         }
1596         if (stat_pipe >= 0 && audiod_status != AUDIOD_OFF) {
1597                 FD_SET(stat_pipe, &rfds);
1598                 max_fileno = MAX(max_fileno, stat_pipe);
1599         }
1600         /* local socket */
1601         tv.tv_sec = 0;
1602         tv.tv_usec = 200 * 1000;
1603         ret = audiod_pre_select(&rfds, &wfds, &tv);
1604         max_fileno = MAX(max_fileno, ret);
1605
1606         ret = select(max_fileno + 1, &rfds, &wfds, NULL, &tv);
1607         if (ret < 0 && errno != EINTR)
1608                 PARA_ERROR_LOG("select returned %d (%s)\n", ret,
1609                         strerror(errno));
1610         if (audiod_status != AUDIOD_OFF)
1611                 audiod_status_dump();
1612         if (ret < 0)
1613                 goto repeat;
1614         audiod_post_select(ret, &rfds, &wfds);
1615         /* read status pipe */
1616         if (stat_pipe >=0 && FD_ISSET(stat_pipe, &rfds)) {
1617                 ret = read(stat_pipe, status_buf + sbo, STRINGSIZE - 1 - sbo);
1618                 if (ret <= 0) {
1619                         close_stat_pipe();
1620                         /* avoid busy loop if server is down */
1621                         while (sleep(1) > 0)
1622                                 ; /* try again*/
1623                 } else {
1624                         status_buf[ret + sbo] = '\0';
1625                         sbo = for_each_line(status_buf, ret + sbo,
1626                                 &check_stat_line);
1627                 }
1628         }
1629         slot_io(&wfds);
1630         if (FD_ISSET(audiod_socket, &rfds)) {
1631                 ret = handle_connect();
1632                 if (ret < 0) {
1633                         PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));
1634                 }
1635         }
1636         /* signals */
1637         if (FD_ISSET(signal_pipe, &rfds)) {
1638                 int sig_nr = para_next_signal();
1639                 if (sig_nr > 0)
1640                         handle_signal(sig_nr);
1641         }
1642         goto repeat;
1643 }
1644
1645 static void set_initial_status(void)
1646 {
1647         audiod_status = AUDIOD_ON;
1648         if (!conf.mode_given)
1649                 return;
1650         if (!strcmp(conf.mode_arg, "sb")) {
1651                 audiod_status = AUDIOD_STANDBY;
1652                 return;
1653         }
1654         if (!strcmp(conf.mode_arg, "off")) {
1655                 audiod_status = AUDIOD_OFF;
1656                 return;
1657         }
1658         if (strcmp(conf.mode_arg, "on"))
1659                 PARA_WARNING_LOG("%s", "invalid mode\n");
1660 }
1661
1662 int __noreturn main(int argc, char *argv[])
1663 {
1664         char *cf;
1665         int i;
1666
1667         valid_fd_012();
1668         hostname = para_hostname();
1669         cmdline_parser(argc, argv, &conf);
1670         para_drop_privileges(conf.user_arg);
1671         cf = configfile_exists();
1672         if (cf) {
1673                 if (cmdline_parser_configfile(cf, &conf, 0, 0, 0)) {
1674                         fprintf(stderr, "parse error in config file\n");
1675                         exit(EXIT_FAILURE);
1676                 }
1677         }
1678         log_welcome("para_audiod", conf.loglevel_arg);
1679         i = init_stream_io();
1680         if (i < 0) {
1681                 fprintf(stderr, "init stream io error: %s\n",
1682                         PARA_STRERROR(-i));
1683                 exit(EXIT_FAILURE);
1684         }
1685         server_uptime(UPTIME_SET);
1686         set_initial_status();
1687         FOR_EACH_SLOT(i)
1688                 clear_slot(i);
1689         init_grabbing();
1690         setup_signal_handling();
1691         if (conf.daemon_given)
1692                 daemon_init();
1693         audiod_get_socket(); /* doesn't return on errors */
1694         audiod_mainloop();
1695 }