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