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