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