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