build: Move relevant parts to server section.
[paraslash.git] / audiod_command.c
1 /*
2  * Copyright (C) 2005-2013 Andre Noll <maan@systemlinux.org>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file audiod_command.c Commands for para_audiod. */
8
9 #include <regex.h>
10 #include <sys/types.h>
11
12 #include "para.h"
13 #include "audiod.cmdline.h"
14 #include "list.h"
15 #include "sched.h"
16 #include "ggo.h"
17 #include "buffer_tree.h"
18 #include "filter.h"
19 #include "grab_client.h"
20 #include "error.h"
21 #include "audiod.h"
22 #include "net.h"
23 #include "daemon.h"
24 #include "string.h"
25 #include "write.h"
26 #include "fd.h"
27 #include "audiod_command_list.h"
28
29 extern struct sched sched;
30 extern char *stat_item_values[NUM_STAT_ITEMS];
31
32
33 static struct audiod_command audiod_cmds[] = {DEFINE_AUDIOD_CMD_ARRAY};
34
35 /** Iterate over the array of all audiod commands. */
36 #define FOR_EACH_COMMAND(c) for (c = 0; audiod_cmds[c].name; c++)
37
38 /** The maximal number of simultaneous connections. */
39 #define MAX_STAT_CLIENTS 50
40
41 /** Flags used for the stat command of para_audiod. */
42 enum stat_client_flags {
43         /** Enable parser-friendly output. */
44         SCF_PARSER_FRIENDLY = 1,
45 };
46
47 /**
48  * Describes a status client of para_audiod.
49  *
50  * There's one such structure per audiod client that sent the 'stat' command.
51  *
52  * A status client is identified by its file descriptor.  para_audiod
53  * keeps a list of connected status clients.
54  */
55 struct stat_client {
56         /** The stat client's file descriptor. */
57         int fd;
58         /** Bitmask of those status items the client is interested in. */
59         uint64_t item_mask;
60         /** See \ref stat_client flags. s*/
61         unsigned flags;
62         /** Its entry in the list of stat clients. */
63         struct list_head node;
64 };
65
66 static INITIALIZED_LIST_HEAD(client_list);
67 static int num_clients;
68
69 /** The list of all status items used by para_{server,audiod,gui}. */
70 const char *status_item_list[] = {STATUS_ITEM_ARRAY};
71
72 static void dump_stat_client_list(void)
73 {
74         struct stat_client *sc;
75
76         list_for_each_entry(sc, &client_list, node)
77                 PARA_INFO_LOG("stat client on fd %d\n", sc->fd);
78 }
79 /**
80  * Add a status client to the list.
81  *
82  * \param fd The file descriptor of the client.
83  * \param mask Bitfield of status items for this client.
84  * \param parser_friendly Enable parser-friendly output mode.
85  *
86  * Only those status items having the bit set in \a mask will be
87  * sent to the client.
88  *
89  * \return Positive value on success, or -E_TOO_MANY_CLIENTS if
90  * the number of connected clients exceeds #MAX_STAT_CLIENTS.
91  */
92 static int stat_client_add(int fd, uint64_t mask, int parser_friendly)
93 {
94         struct stat_client *new_client;
95
96         if (num_clients >= MAX_STAT_CLIENTS) {
97                 PARA_ERROR_LOG("maximal number of stat clients (%d) exceeded\n",
98                         MAX_STAT_CLIENTS);
99                 return -E_TOO_MANY_CLIENTS;
100         }
101         PARA_INFO_LOG("adding client on fd %d\n", fd);
102         new_client = para_calloc(sizeof(struct stat_client));
103         new_client->fd = fd;
104         new_client->item_mask = mask;
105         if (parser_friendly)
106                 new_client->flags = SCF_PARSER_FRIENDLY;
107         para_list_add(&new_client->node, &client_list);
108         dump_stat_client_list();
109         num_clients++;
110         return 1;
111 }
112
113 static void close_stat_client(struct stat_client *sc)
114 {
115         PARA_INFO_LOG("closing client fd %d\n", sc->fd);
116         close(sc->fd);
117         list_del(&sc->node);
118         free(sc);
119         num_clients--;
120 }
121
122 /**
123  * Empty the status clients list.
124  *
125  * This iterates over the list of connected status clients, closes each client
126  * file descriptor and frees the resources.
127  */
128 void close_stat_clients(void)
129 {
130         struct stat_client *sc, *tmp;
131
132         list_for_each_entry_safe(sc, tmp, &client_list, node)
133                 close_stat_client(sc);
134         assert(num_clients == 0);
135 }
136
137 /**
138  * Write a message to all connected status clients.
139  *
140  * \param item_num The number of the status item of \a msg.
141  *
142  * On write errors, remove the status client from the client list and close its
143  * file descriptor.
144  */
145 void stat_client_write_item(int item_num)
146 {
147         struct stat_client *sc, *tmp;
148         struct para_buffer pb = {.flags = 0};
149         struct para_buffer pfpb = {.flags = PBF_SIZE_PREFIX};
150         const uint64_t one = 1;
151         char *msg = stat_item_values[item_num];
152         struct para_buffer *b;
153
154         list_for_each_entry_safe(sc, tmp, &client_list, node) {
155                 int ret;
156
157                 if (!((one << item_num) & sc->item_mask))
158                         continue;
159                 b = (sc->flags & SCF_PARSER_FRIENDLY)? &pfpb : &pb;
160                 if (!b->buf)
161                         (void)WRITE_STATUS_ITEM(b, item_num, "%s\n",
162                                 msg? msg : "");
163                 ret = write(sc->fd, b->buf, b->offset);
164                 if (ret == b->offset)
165                         continue;
166                 /* write error or short write */
167                 close_stat_client(sc);
168                 dump_stat_client_list();
169         }
170         free(pb.buf);
171         free(pfpb.buf);
172 }
173
174 /**
175  * Check if string is a known status item.
176  *
177  * \param item Buffer containing the text to check.
178  *
179  * \return If \a item is a valid status item, the number of that status item is
180  * returned. Otherwise, this function returns \p -E_UNKNOWN_STAT_ITEM.
181  */
182 static int stat_item_valid(const char *item)
183 {
184         int i;
185         if (!item || !*item) {
186                 PARA_ERROR_LOG("%s\n", "no item");
187                 return -E_UNKNOWN_STAT_ITEM;
188         }
189         FOR_EACH_STATUS_ITEM(i)
190                 if (!strcmp(status_item_list[i], item))
191                         return i;
192         PARA_ERROR_LOG("invalid stat item: %s\n", item);
193         return -E_UNKNOWN_STAT_ITEM;
194 }
195
196 static int client_write(int fd, const char *buf)
197 {
198         size_t len;
199
200         if (!buf)
201                 return 0;
202         len = strlen(buf);
203         return write(fd, buf, len) != len? -E_CLIENT_WRITE: 1;
204 }
205
206 __malloc static char *audiod_status_string(void)
207 {
208         const char *status = (audiod_status == AUDIOD_ON)?
209                 "on" : (audiod_status == AUDIOD_OFF)? "off": "sb";
210         return para_strdup(status);
211 }
212
213 static int get_play_time_slot_num(void)
214 {
215         int i, oldest_slot = -1;
216         struct timeval oldest_wstime = {0, 0};
217
218         FOR_EACH_SLOT(i) {
219                 struct slot_info *s = &slot[i];
220                 struct timeval wstime;
221                 if (!s->wns || !s->wns[0].btrn)
222                         continue;
223                 btr_get_node_start(s->wns[0].btrn, &wstime);
224                 if (oldest_slot >= 0 && tv_diff(&wstime, &oldest_wstime, NULL) > 0)
225                         continue;
226                 oldest_wstime = wstime;
227                 oldest_slot = i;
228         }
229         //PARA_CRIT_LOG("oldest slot: %d\n", oldest_slot);
230         return oldest_slot;
231 }
232
233 __malloc static char *decoder_flags(void)
234 {
235         int i;
236         char flags[MAX_STREAM_SLOTS + 1];
237
238         FOR_EACH_SLOT(i) {
239                 struct slot_info *s = &slot[i];
240                 char flag = '0';
241                 if (s->receiver_node)
242                         flag += 1;
243                 if (s->fns)
244                         flag += 2;
245                 if (s->wns)
246                         flag += 4;
247                 flags[i] = flag;
248         }
249         flags[MAX_STREAM_SLOTS] = '\0';
250         return para_strdup(flags);
251 }
252
253 static int dump_commands(int fd)
254 {
255         char *buf = para_strdup(""), *tmp = NULL;
256         int i;
257         ssize_t ret;
258
259         FOR_EACH_COMMAND(i) {
260                 tmp = make_message("%s%s\t%s\n", buf, audiod_cmds[i].name,
261                         audiod_cmds[i].description);
262                 free(buf);
263                 buf = tmp;
264         }
265         ret = client_write(fd, buf);
266         free(buf);
267         return ret;
268 }
269
270 /*
271  * command handlers don't close their fd on errors (ret < 0) so that
272  * its caller can send an error message. Otherwise (ret >= 0) it's up
273  * to each individual command to close the fd if necessary.
274  */
275
276 static int com_help(int fd, int argc, char **argv)
277 {
278         int i, ret;
279         char *buf;
280         const char *dflt = "No such command. Available commands:\n";
281
282         if (argc < 2) {
283                 ret = dump_commands(fd);
284                 goto out;
285         }
286         FOR_EACH_COMMAND(i) {
287                 if (strcmp(audiod_cmds[i].name, argv[1]))
288                         continue;
289                 buf = make_message(
290                         "NAME\n\t%s -- %s\n"
291                         "SYNOPSIS\n\tpara_audioc %s\n"
292                         "DESCRIPTION\n%s\n",
293                         argv[1],
294                         audiod_cmds[i].description,
295                         audiod_cmds[i].usage,
296                         audiod_cmds[i].help
297                 );
298                 ret = client_write(fd, buf);
299                 free(buf);
300                 goto out;
301         }
302         ret = client_write(fd, dflt);
303         if (ret > 0)
304                 ret = dump_commands(fd);
305 out:
306         if (ret >= 0)
307                 close(fd);
308         return ret;
309 }
310
311 static int com_tasks(int fd, __a_unused int argc, __a_unused char **argv)
312 {
313         char *tl = get_task_list(&sched);
314         int ret = 1;
315         if (tl)
316                 ret = client_write(fd, tl);
317         free(tl);
318         if (ret > 0)
319                 close(fd);
320         return ret;
321 }
322
323 static int com_stat(int fd, int argc, char **argv)
324 {
325         int i, ret, parser_friendly = 0;
326         uint64_t mask = 0;
327         const uint64_t one = 1;
328         struct para_buffer b = {.flags = 0};
329
330         ret = mark_fd_nonblocking(fd);
331         if (ret < 0)
332                 return ret;
333         for (i = 1; i < argc; i++) {
334                 const char *arg = argv[i];
335                 if (arg[0] != '-')
336                         break;
337                 if (!strcmp(arg, "--")) {
338                         i++;
339                         break;
340                 }
341                 if (!strncmp(arg, "-p", 2)) {
342                         parser_friendly = 1;
343                         b.flags = PBF_SIZE_PREFIX;
344                 }
345         }
346         if (i >= argc)
347                 mask--; /* set all bits */
348         for (; i < argc; i++) {
349                 ret = stat_item_valid(argv[i]);
350                 if (ret < 0)
351                         return ret;
352                 mask |= (one << ret);
353         }
354         PARA_INFO_LOG("mask: 0x%llx\n", (long long unsigned)mask);
355         FOR_EACH_STATUS_ITEM(i) {
356                 char *item = stat_item_values[i];
357                 if (!((one << i) & mask))
358                         continue;
359                 (void)WRITE_STATUS_ITEM(&b, i, "%s\n", item? item : "");
360         }
361         ret = client_write(fd, b.buf);
362         if (ret >= 0)
363                 ret = stat_client_add(fd, mask, parser_friendly);
364         free(b.buf);
365         return ret;
366 }
367
368 static int com_grab(int fd, int argc, char **argv)
369 {
370         return grab_client_new(fd, argc, argv, &sched);
371 }
372
373 __noreturn static int com_term(int fd, __a_unused int argc, __a_unused char **argv)
374 {
375         close(fd);
376         clean_exit(EXIT_SUCCESS, "terminating on user request");
377 }
378
379 static int com_on(int fd, __a_unused int argc, __a_unused char **argv)
380 {
381         audiod_status = AUDIOD_ON;
382         close(fd);
383         return 1;
384 }
385
386 static int com_off(int fd, __a_unused int argc, __a_unused char **argv)
387 {
388         audiod_status = AUDIOD_OFF;
389         close(fd);
390         return 1;
391 }
392
393 static int com_sb(int fd, __a_unused int argc, __a_unused char **argv)
394 {
395         audiod_status = AUDIOD_STANDBY;
396         close(fd);
397         return 1;
398 }
399
400 static int com_cycle(int fd, int argc, char **argv)
401 {
402         switch (audiod_status) {
403                 case  AUDIOD_ON:
404                         return com_sb(fd, argc, argv);
405                         break;
406                 case  AUDIOD_OFF:
407                         return com_on(fd, argc, argv);
408                         break;
409                 case  AUDIOD_STANDBY:
410                         return com_off(fd, argc, argv);
411                         break;
412         }
413         close(fd);
414         return 1;
415 }
416
417 static int check_perms(uid_t uid)
418 {
419         int i;
420
421         if (!conf.user_allow_given)
422                 return 1;
423         for (i = 0; i < conf.user_allow_given; i++)
424                 if (uid == conf.user_allow_arg[i])
425                         return 1;
426         return -E_UCRED_PERM;
427 }
428
429 /**
430  * Handle arriving connections on the local socket.
431  *
432  * \param accept_fd The fd to accept connections on.
433  * \param rfds If \a accept_fd is not set in \a rfds, do nothing.
434  *
435  * This is called in each iteration of the select loop. If there is an incoming
436  * connection on \a accept_fd, this function reads the command sent by the peer,
437  * checks the connecting user's permissions by using unix socket credentials
438  * (if supported by the OS) and calls the corresponding command handler if
439  * permissions are OK.
440  *
441  * \return Positive on success, negative on errors, zero if there was no
442  * connection to accept.
443  *
444  * \sa para_accept(), recv_cred_buffer()
445  * */
446 int handle_connect(int accept_fd, fd_set *rfds)
447 {
448         int i, argc, ret, clifd;
449         char buf[MAXLINE], **argv = NULL;
450         struct sockaddr_un unix_addr;
451         uid_t uid;
452
453         ret = para_accept(accept_fd, rfds, &unix_addr, sizeof(struct sockaddr_un), &clifd);
454         if (ret <= 0)
455                 return ret;
456         ret = recv_cred_buffer(clifd, buf, sizeof(buf) - 1);
457         if (ret < 0)
458                 goto out;
459         uid = ret;
460         PARA_INFO_LOG("connection from user %i, buf: %s\n",  ret, buf);
461         ret = check_perms(uid);
462         if (ret < 0)
463                 goto out;
464         ret = create_argv(buf, "\n", &argv);
465         if (ret <= 0)
466                 goto out;
467         argc = ret;
468         //PARA_INFO_LOG("argv[0]: %s, argc = %d\n", argv[0], argc);
469         FOR_EACH_COMMAND(i) {
470                 if (strcmp(audiod_cmds[i].name, argv[0]))
471                         continue;
472                 ret = audiod_cmds[i].handler(clifd, argc, argv);
473                 goto out;
474         }
475         ret = -E_INVALID_AUDIOD_CMD;
476 out:
477         free_argv(argv);
478         if (clifd > 0 && ret < 0 && ret != -E_CLIENT_WRITE) {
479                 char *tmp = make_message("%s\n", para_strerror(-ret));
480                 client_write(clifd, tmp);
481                 free(tmp);
482                 close(clifd);
483         }
484         return ret;
485 }
486
487 /**
488  * Send the current audiod status to all connected stat clients.
489  *
490  * \param force Whether to write unchanged items.
491  */
492 void audiod_status_dump(bool force)
493 {
494         int slot_num = get_play_time_slot_num();
495         char *old, *new;
496
497         old = stat_item_values[SI_PLAY_TIME];
498         new = get_time_string(slot_num);
499         if (new) {
500                 if (force || !old || strcmp(old, new)) {
501                         free(old);
502                         stat_item_values[SI_PLAY_TIME] = new;
503                         stat_client_write_item(SI_PLAY_TIME);
504                 } else
505                         free(new);
506         }
507
508         new = get_server_uptime_str(now);
509         old = stat_item_values[SI_AUDIOD_UPTIME];
510         if (force || !old || strcmp(old, new)) {
511                 free(old);
512                 stat_item_values[SI_AUDIOD_UPTIME] = new;
513                 stat_client_write_item(SI_AUDIOD_UPTIME);
514         } else
515                 free(new);
516
517         old = stat_item_values[SI_AUDIOD_STATUS];
518         new = audiod_status_string();
519         if (force || !old || strcmp(old, new)) {
520                 free(old);
521                 stat_item_values[SI_AUDIOD_STATUS] = new;
522                 stat_client_write_item(SI_AUDIOD_STATUS);
523         } else
524                 free(new);
525
526         old = stat_item_values[SI_DECODER_FLAGS];
527         new = decoder_flags();
528         if (force || !old || strcmp(old, new)) {
529                 free(old);
530                 stat_item_values[SI_DECODER_FLAGS] = new;
531                 stat_client_write_item(SI_DECODER_FLAGS);
532         } else
533                 free(new);
534 }
535
536 /**
537  * Flush and send all status items.
538  *
539  * Send to  each connected client the full status item list
540  * with empty values.
541  */
542 void clear_and_dump_items(void)
543 {
544         int i;
545
546         FOR_EACH_STATUS_ITEM(i) {
547                 free(stat_item_values[i]);
548                 stat_item_values[i] = NULL;
549                 stat_client_write_item(i);
550         }
551 }