play: Convert com_pause() to lopsub.
[paraslash.git] / afs.c
1 /*
2  * Copyright (C) 2007 Andre Noll <maan@tuebingen.mpg.de>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file afs.c Paraslash's audio file selector. */
8
9 #include <netinet/in.h>
10 #include <sys/socket.h>
11 #include <regex.h>
12 #include <signal.h>
13 #include <fnmatch.h>
14 #include <osl.h>
15 #include <lopsub.h>
16 #include <arpa/inet.h>
17 #include <sys/un.h>
18 #include <netdb.h>
19 #include <lopsub.h>
20
21 #include "server_cmd.lsg.h"
22 #include "server.cmdline.h"
23 #include "para.h"
24 #include "error.h"
25 #include "crypt.h"
26 #include "string.h"
27 #include "afh.h"
28 #include "afs.h"
29 #include "server.h"
30 #include "net.h"
31 #include "ipc.h"
32 #include "list.h"
33 #include "sched.h"
34 #include "fd.h"
35 #include "signal.h"
36 #include "mood.h"
37 #include "sideband.h"
38 #include "command.h"
39
40 /** The osl tables used by afs. \sa blob.c. */
41 enum afs_table_num {
42         /** Contains audio file information. See aft.c. */
43         TBLNUM_AUDIO_FILES,
44         /** The table for the paraslash attributes. See attribute.c. */
45         TBLNUM_ATTRIBUTES,
46         /**
47          * Paraslash's scoring system is based on Gaussian normal
48          * distributions, and the relevant data is stored in the rbtrees of an
49          * osl table containing only volatile columns.  See score.c for
50          * details.
51          */
52         TBLNUM_SCORES,
53         /**
54          * A standard blob table containing the mood definitions. For details
55          * see mood.c.
56          */
57         TBLNUM_MOODS,
58         /** A blob table containing lyrics on a per-song basis. */
59         TBLNUM_LYRICS,
60         /** Another blob table for images (for example album cover art). */
61         TBLNUM_IMAGES,
62         /** Yet another blob table for storing standard playlists. */
63         TBLNUM_PLAYLIST,
64         /** How many tables are in use? */
65         NUM_AFS_TABLES
66 };
67
68 static struct afs_table afs_tables[NUM_AFS_TABLES] = {
69         [TBLNUM_AUDIO_FILES] = {.init = aft_init, .name = "audio_files"},
70         [TBLNUM_ATTRIBUTES] = {.init = attribute_init, .name = "attributes"},
71         [TBLNUM_SCORES] = {.init = score_init, .name = "scores"},
72         [TBLNUM_MOODS] = {.init = moods_init, .name = "moods"},
73         [TBLNUM_LYRICS] = {.init = lyrics_init, .name = "lyrics"},
74         [TBLNUM_IMAGES] = {.init = images_init, .name = "images"},
75         [TBLNUM_PLAYLIST] = {.init = playlists_init, .name = "playlists"},
76 };
77
78 struct command_task {
79         /** The file descriptor for the local socket. */
80         int fd;
81         /**
82          * Value sent by the command handlers to identify themselves as
83          * children of the running para_server.
84          */
85         uint32_t cookie;
86         /** The associated task structure. */
87         struct task *task;
88 };
89
90 extern int mmd_mutex;
91 extern struct misc_meta_data *mmd;
92
93 static int server_socket;
94 static struct command_task command_task_struct;
95 static struct signal_task *signal_task;
96
97 static enum play_mode current_play_mode;
98 static char *current_mop; /* mode or playlist specifier. NULL means dummy mood */
99
100 /**
101  * A random number used to "authenticate" the connection.
102  *
103  * para_server picks this number by random before it forks the afs process. The
104  * command handlers know this number as well and write it to the afs socket,
105  * together with the id of the shared memory area which contains the payload of
106  * the afs command. A local process has to know this number to abuse the afs
107  * service provided by the local socket.
108  */
109 extern uint32_t afs_socket_cookie;
110
111 /**
112  * Struct to let command handlers execute a callback in afs context.
113  *
114  * Commands that need to change the state of afs can't change the relevant data
115  * structures directly because commands are executed in a child process, i.e.
116  * they get their own virtual address space.
117  *
118  * This structure is used by \p send_callback_request() (executed from handler
119  * context) in order to let the afs process call the specified function. An
120  * instance of that structure is written to a shared memory area together with
121  * the arguments to the callback function. The identifier of the shared memory
122  * area is written to the command socket.
123  *
124  * The afs process accepts connections on the command socket and reads the
125  * shared memory id, attaches the corresponding area, calls the given handler to
126  * perform the desired action and to optionally compute a result.
127  *
128  * The result and a \p callback_result structure is then written to another
129  * shared memory area. The identifier for that area is written to the handler's
130  * command socket, so that the handler process can read the id, attach the
131  * shared memory area and use the result.
132  *
133  * \sa struct callback_result.
134  */
135 struct callback_query {
136         /** The function to be called. */
137         afs_callback *handler;
138         /** The number of bytes of the query */
139         size_t query_size;
140 };
141
142 /**
143  * Structure embedded in the result of a callback.
144  *
145  * If the callback produced a result, an instance of that structure is embedded
146  * into the shared memory area holding the result, mainly to let the command
147  * handler know the size of the result.
148  *
149  * \sa struct callback_query.
150  */
151 struct callback_result {
152         /** The number of bytes of the result. */
153         size_t result_size;
154         /** The band designator (loglevel for the result). */
155         uint8_t band;
156 };
157
158 static int dispatch_result(int result_shmid, callback_result_handler *handler,
159                 void *private_result_data)
160 {
161         struct osl_object result;
162         void *result_shm;
163         /* must attach r/w as result.data might get encrypted in-place. */
164         int ret2, ret = shm_attach(result_shmid, ATTACH_RW, &result_shm);
165         struct callback_result *cr = result_shm;
166
167         if (ret < 0) {
168                 PARA_ERROR_LOG("attach failed: %s\n", para_strerror(-ret));
169                 return ret;
170         }
171         result.size = cr->result_size;
172         result.data = result_shm + sizeof(*cr);
173         assert(handler);
174         ret = handler(&result, cr->band, private_result_data);
175         ret2 = shm_detach(result_shm);
176         if (ret2 < 0) {
177                 PARA_ERROR_LOG("detach failed: %s\n", para_strerror(-ret2));
178                 if (ret >= 0)
179                         ret = ret2;
180         }
181         return ret;
182 }
183
184 /**
185  * Ask the afs process to call a given function.
186  *
187  * \param f The function to be called.
188  * \param query Pointer to arbitrary data for the callback.
189  * \param result_handler Called for each shm area sent by the callback.
190  * \param private_result_data Passed verbatim to \a result_handler.
191  *
192  * This function creates a socket for communication with the afs process and a
193  * shared memory area (sma) to which the buffer pointed to by \a query is
194  * copied.  It then notifies the afs process that the callback function \a f
195  * should be executed by sending the shared memory identifier (shmid) to the
196  * socket.
197  *
198  * If the callback produces a result, it sends any number of shared memory
199  * identifiers back via the socket. For each such identifier received, \a
200  * result_handler is called. The contents of the sma identified by the received
201  * shmid are passed to that function as an osl object. The private_result_data
202  * pointer is passed as the second argument to \a result_handler.
203  *
204  * \return Number of shared memory areas dispatched on success, negative on errors.
205  *
206  * \sa send_option_arg_callback_request(), send_standard_callback_request().
207  */
208 int send_callback_request(afs_callback *f, struct osl_object *query,
209                 callback_result_handler *result_handler,
210                 void *private_result_data)
211 {
212         struct callback_query *cq;
213         int ret, fd = -1, query_shmid, result_shmid;
214         void *query_shm;
215         char buf[sizeof(afs_socket_cookie) + sizeof(int)];
216         size_t query_shm_size = sizeof(*cq);
217         int dispatch_error = 0, num_dispatched = 0;
218
219         if (query)
220                 query_shm_size += query->size;
221         ret = shm_new(query_shm_size);
222         if (ret < 0)
223                 return ret;
224         query_shmid = ret;
225         ret = shm_attach(query_shmid, ATTACH_RW, &query_shm);
226         if (ret < 0)
227                 goto out;
228         cq = query_shm;
229         cq->handler = f;
230         cq->query_size = query_shm_size - sizeof(*cq);
231
232         if (query)
233                 memcpy(query_shm + sizeof(*cq), query->data, query->size);
234         ret = shm_detach(query_shm);
235         if (ret < 0)
236                 goto out;
237
238         *(uint32_t *)buf = afs_socket_cookie;
239         *(int *)(buf + sizeof(afs_socket_cookie)) = query_shmid;
240
241         ret = connect_local_socket(conf.afs_socket_arg);
242         if (ret < 0)
243                 goto out;
244         fd = ret;
245         ret = write_all(fd, buf, sizeof(buf));
246         if (ret < 0)
247                 goto out;
248         /*
249          * Read all shmids from afs.
250          *
251          * Even if the dispatcher returns an error we _must_ continue to read
252          * shmids from fd so that we can destroy all shared memory areas that
253          * have been created for us by the afs process.
254          */
255         for (;;) {
256                 ret = recv_bin_buffer(fd, buf, sizeof(int));
257                 if (ret <= 0)
258                         goto out;
259                 assert(ret == sizeof(int));
260                 ret = *(int *) buf;
261                 assert(ret > 0);
262                 result_shmid = ret;
263                 ret = dispatch_result(result_shmid, result_handler,
264                         private_result_data);
265                 if (ret < 0 && dispatch_error >= 0)
266                         dispatch_error = ret;
267                 ret = shm_destroy(result_shmid);
268                 if (ret < 0)
269                         PARA_CRIT_LOG("destroy result failed: %s\n",
270                                 para_strerror(-ret));
271                 num_dispatched++;
272         }
273 out:
274         if (shm_destroy(query_shmid) < 0)
275                 PARA_CRIT_LOG("shm destroy error\n");
276         if (fd >= 0)
277                 close(fd);
278         if (dispatch_error < 0)
279                 return dispatch_error;
280         if (ret < 0)
281                 return ret;
282         return num_dispatched;
283 }
284
285 /**
286  * Wrapper for send_callback_request() which passes a lopsub parse result.
287  *
288  * \param f The callback function.
289  * \param cmd Needed for (de-)serialization.
290  * \param lpr Must match cmd.
291  * \param private_result_data Passed to send_callback_request().
292  *
293  * This function serializes the parse result given by the lpr pointer into a
294  * buffer. The buffer is sent as the query to the afs process with the callback
295  * mechanism.
296  *
297  * \return The return value of the underlying call to send_callback_request().
298  */
299 int send_lls_callback_request(afs_callback *f,
300                 const struct lls_command * const cmd,
301                 struct lls_parse_result *lpr, void *private_result_data)
302 {
303         struct osl_object query;
304         char *buf = NULL;
305         int ret = lls_serialize_parse_result(lpr, cmd, &buf, &query.size);
306
307         assert(ret >= 0);
308         query.data = buf;
309         ret = send_callback_request(f, &query, afs_cb_result_handler,
310                 private_result_data);
311         free(buf);
312         return ret;
313 }
314
315 static int action_if_pattern_matches(struct osl_row *row, void *data)
316 {
317         struct pattern_match_data *pmd = data;
318         struct osl_object name_obj;
319         const char *p, *name;
320         int i, ret;
321
322         ret = osl(osl_get_object(pmd->table, row, pmd->match_col_num,
323                 &name_obj));
324         if (ret < 0)
325                 return ret;
326         name = (char *)name_obj.data;
327         if ((!name || !*name) && (pmd->pm_flags & PM_SKIP_EMPTY_NAME))
328                 return 1;
329         if (lls_num_inputs(pmd->lpr) == 0) {
330                 if (pmd->pm_flags & PM_NO_PATTERN_MATCHES_EVERYTHING) {
331                         pmd->num_matches++;
332                         return pmd->action(pmd->table, row, name, pmd->data);
333                 }
334         }
335         i = pmd->input_skip;
336         for (;;) {
337                 if (i >= lls_num_inputs(pmd->lpr))
338                         break;
339                 p = lls_input(i, pmd->lpr);
340                 ret = fnmatch(p, name, pmd->fnmatch_flags);
341                 if (ret != FNM_NOMATCH) {
342                         if (ret != 0)
343                                 return -E_FNMATCH;
344                         ret = pmd->action(pmd->table, row, name, pmd->data);
345                         if (ret >= 0)
346                                 pmd->num_matches++;
347                         return ret;
348
349                 }
350                 i++;
351         }
352         return 1;
353 }
354
355 /**
356  * Execute the given function for each matching row.
357  *
358  * \param pmd Describes what to match and how.
359  *
360  * \return Standard.
361  */
362 int for_each_matching_row(struct pattern_match_data *pmd)
363 {
364         if (pmd->pm_flags & PM_REVERSE_LOOP)
365                 return osl(osl_rbtree_loop_reverse(pmd->table, pmd->loop_col_num, pmd,
366                         action_if_pattern_matches));
367         return osl(osl_rbtree_loop(pmd->table, pmd->loop_col_num, pmd,
368                         action_if_pattern_matches));
369 }
370
371 /**
372  * Compare two osl objects of string type.
373  *
374  * \param obj1 Pointer to the first object.
375  * \param obj2 Pointer to the second object.
376  *
377  * In any case, only \p MIN(obj1->size, obj2->size) characters of each string
378  * are taken into account.
379  *
380  * \return It returns an integer less than, equal to, or greater than zero if
381  * \a obj1 is found, respectively, to be less than, to match, or be greater than
382  * obj2.
383  *
384  * \sa strcmp(3), strncmp(3), osl_compare_func.
385  */
386 int string_compare(const struct osl_object *obj1, const struct osl_object *obj2)
387 {
388         const char *str1 = (const char *)obj1->data;
389         const char *str2 = (const char *)obj2->data;
390         return strncmp(str1, str2, PARA_MIN(obj1->size, obj2->size));
391 }
392
393 static int pass_afd(int fd, char *buf, size_t size)
394 {
395         struct msghdr msg = {.msg_iov = NULL};
396         struct cmsghdr *cmsg;
397         char control[255] __a_aligned(8);
398         int ret;
399         struct iovec iov;
400
401         iov.iov_base = buf;
402         iov.iov_len  = size;
403
404         msg.msg_iov = &iov;
405         msg.msg_iovlen = 1;
406
407         msg.msg_control = control;
408         msg.msg_controllen = sizeof(control);
409
410         cmsg = CMSG_FIRSTHDR(&msg);
411         cmsg->cmsg_level = SOL_SOCKET;
412         cmsg->cmsg_type = SCM_RIGHTS;
413         cmsg->cmsg_len = CMSG_LEN(sizeof(int));
414         *(int *)CMSG_DATA(cmsg) = fd;
415
416         /* Sum of the length of all control messages in the buffer */
417         msg.msg_controllen = cmsg->cmsg_len;
418         PARA_DEBUG_LOG("passing %zu bytes and fd %d\n", size, fd);
419         ret = sendmsg(server_socket, &msg, 0);
420         if (ret < 0) {
421                 ret = -ERRNO_TO_PARA_ERROR(errno);
422                 return ret;
423         }
424         return 1;
425 }
426
427 /**
428  * Pass the fd of the next audio file to the server process.
429  *
430  * This stores all information for streaming the "best" audio file in a shared
431  * memory area. The id of that area and an open file descriptor for the next
432  * audio file are passed to the server process.
433  *
434  * \return Standard.
435  *
436  * \sa open_and_update_audio_file().
437  */
438 static int open_next_audio_file(void)
439 {
440         struct audio_file_data afd;
441         int ret, shmid;
442         char buf[8];
443
444         ret = open_and_update_audio_file(&afd);
445         if (ret < 0) {
446                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
447                 goto no_admissible_files;
448         }
449         shmid = ret;
450         if (!write_ok(server_socket)) {
451                 ret = -E_AFS_SOCKET;
452                 goto destroy;
453         }
454         *(uint32_t *)buf = NEXT_AUDIO_FILE;
455         *(uint32_t *)(buf + 4) = (uint32_t)shmid;
456         ret = pass_afd(afd.fd, buf, 8);
457         close(afd.fd);
458         if (ret >= 0)
459                 return ret;
460 destroy:
461         shm_destroy(shmid);
462         return ret;
463 no_admissible_files:
464         *(uint32_t *)buf = NO_ADMISSIBLE_FILES;
465         *(uint32_t *)(buf + 4) = (uint32_t)0;
466         return write_all(server_socket, buf, 8);
467 }
468
469 /* Never fails if arg == NULL */
470 static int activate_mood_or_playlist(const char *arg, int *num_admissible)
471 {
472         enum play_mode mode;
473         int ret;
474
475         if (!arg) {
476                 ret = change_current_mood(NULL); /* always successful */
477                 mode = PLAY_MODE_MOOD;
478         } else {
479                 if (!strncmp(arg, "p/", 2)) {
480                         ret = playlist_open(arg + 2);
481                         mode = PLAY_MODE_PLAYLIST;
482                 } else if (!strncmp(arg, "m/", 2)) {
483                         ret = change_current_mood(arg + 2);
484                         mode = PLAY_MODE_MOOD;
485                 } else
486                         return -E_AFS_SYNTAX;
487                 if (ret < 0)
488                         return ret;
489         }
490         if (num_admissible)
491                 *num_admissible = ret;
492         current_play_mode = mode;
493         if (arg != current_mop) {
494                 free(current_mop);
495                 if (arg) {
496                         current_mop = para_strdup(arg);
497                         mutex_lock(mmd_mutex);
498                         strncpy(mmd->afs_mode_string, arg,
499                                 sizeof(mmd->afs_mode_string));
500                         mmd->afs_mode_string[sizeof(mmd->afs_mode_string) - 1] = '\0';
501                         mutex_unlock(mmd_mutex);
502                 } else {
503                         mutex_lock(mmd_mutex);
504                         strcpy(mmd->afs_mode_string, "dummy");
505                         mutex_unlock(mmd_mutex);
506                         current_mop = NULL;
507                 }
508         }
509         return 1;
510 }
511
512 /**
513  * Result handler for sending data to the para_client process.
514  *
515  * \param result The data to be sent.
516  * \param band The band designator.
517  * \param private Pointer to the command context.
518  *
519  * \return The return value of the underlying call to \ref command.c::send_sb.
520  *
521  * \sa \ref callback_result_handler, \ref command.c::send_sb.
522  */
523 int afs_cb_result_handler(struct osl_object *result, uint8_t band,
524                 void *private)
525 {
526         struct command_context *cc = private;
527
528         assert(cc);
529         switch (band) {
530         case SBD_OUTPUT:
531         case SBD_DEBUG_LOG:
532         case SBD_INFO_LOG:
533         case SBD_NOTICE_LOG:
534         case SBD_WARNING_LOG:
535         case SBD_ERROR_LOG:
536         case SBD_CRIT_LOG:
537         case SBD_EMERG_LOG:
538                 assert(result->size > 0);
539                 return send_sb(&cc->scc, result->data, result->size, band, true);
540         case SBD_AFS_CB_FAILURE:
541                 return *(int *)(result->data);
542         default:
543                 return -E_BAD_BAND;
544         }
545 }
546
547 static void flush_and_free_pb(struct para_buffer *pb)
548 {
549         int ret;
550         struct afs_max_size_handler_data *amshd = pb->private_data;
551
552         if (pb->buf && pb->size > 0) {
553                 ret = pass_buffer_as_shm(amshd->fd, amshd->band, pb->buf,
554                         pb->offset);
555                 if (ret < 0)
556                         PARA_ERROR_LOG("%s\n", para_strerror(-ret));
557         }
558         free(pb->buf);
559 }
560
561 static int com_select_callback(struct afs_callback_arg *aca)
562 {
563         const struct lls_command *cmd = SERVER_CMD_CMD_PTR(SELECT);
564         const char *arg;
565         int num_admissible, ret;
566
567         ret = lls_deserialize_parse_result(aca->query.data, cmd, &aca->lpr);
568         assert(ret >= 0);
569         arg = lls_input(0, aca->lpr);
570         ret = clear_score_table();
571         if (ret < 0) {
572                 para_printf(&aca->pbout, "could not clear score table\n");
573                 goto free_lpr;
574         }
575         if (current_play_mode == PLAY_MODE_MOOD)
576                 close_current_mood();
577         else
578                 playlist_close();
579         ret = activate_mood_or_playlist(arg, &num_admissible);
580         if (ret >= 0)
581                 goto out;
582         /* ignore subsequent errors (but log them) */
583         para_printf(&aca->pbout, "could not activate %s\n", arg);
584         if (current_mop) {
585                 int ret2;
586                 para_printf(&aca->pbout, "switching back to %s\n", current_mop);
587                 ret2 = activate_mood_or_playlist(current_mop, &num_admissible);
588                 if (ret2 >= 0)
589                         goto out;
590                 para_printf(&aca->pbout, "could not reactivate %s: %s\n",
591                         current_mop, para_strerror(-ret2));
592         }
593         para_printf(&aca->pbout, "activating dummy mood\n");
594         activate_mood_or_playlist(NULL, &num_admissible);
595 out:
596         para_printf(&aca->pbout, "activated %s (%d admissible files)\n",
597                 current_mop? current_mop : "dummy mood", num_admissible);
598 free_lpr:
599         lls_free_parse_result(aca->lpr, cmd);
600         return ret;
601 }
602
603 static int com_select(struct command_context *cc, struct lls_parse_result *lpr)
604 {
605         const struct lls_command *cmd = SERVER_CMD_CMD_PTR(SELECT);
606         char *errctx;
607         int ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
608
609         if (ret < 0) {
610                 send_errctx(cc, errctx);
611                 return ret;
612         }
613         return send_lls_callback_request(com_select_callback, cmd, lpr, cc);
614 }
615 EXPORT_SERVER_CMD_HANDLER(select);
616
617 static void init_admissible_files(char *arg)
618 {
619         if (activate_mood_or_playlist(arg, NULL) < 0)
620                 activate_mood_or_playlist(NULL, NULL); /* always successful */
621 }
622
623 static int setup_command_socket_or_die(void)
624 {
625         int ret, socket_fd;
626         char *socket_name = conf.afs_socket_arg;
627
628         unlink(socket_name);
629         ret = create_local_socket(socket_name, 0);
630         if (ret < 0) {
631                 ret = create_local_socket(socket_name,
632                         S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IROTH);
633                 if (ret < 0) {
634                         PARA_EMERG_LOG("%s: %s\n", para_strerror(-ret),
635                                 socket_name);
636                         exit(EXIT_FAILURE);
637                 }
638         }
639         socket_fd = ret;
640         PARA_INFO_LOG("listening on socket %s (fd %d)\n", socket_name,
641                 socket_fd);
642         return socket_fd;
643 }
644
645 static void close_afs_tables(void)
646 {
647         int i;
648         PARA_NOTICE_LOG("closing afs_tables\n");
649         for (i = 0; i < NUM_AFS_TABLES; i++)
650                 afs_tables[i].close();
651 }
652
653 static char *database_dir;
654
655 static void get_database_dir(void)
656 {
657         if (!database_dir) {
658                 if (conf.afs_database_dir_given)
659                         database_dir = para_strdup(conf.afs_database_dir_arg);
660                 else {
661                         char *home = para_homedir();
662                         database_dir = make_message(
663                                 "%s/.paraslash/afs_database-0.4", home);
664                         free(home);
665                 }
666         }
667         PARA_INFO_LOG("afs_database dir %s\n", database_dir);
668 }
669
670 static int make_database_dir(void)
671 {
672         int ret;
673
674         get_database_dir();
675         ret = para_mkdir(database_dir, 0777);
676         if (ret >= 0 || ret == -ERRNO_TO_PARA_ERROR(EEXIST))
677                 return 1;
678         return ret;
679 }
680
681 static int open_afs_tables(void)
682 {
683         int i, ret;
684
685         get_database_dir();
686         PARA_NOTICE_LOG("opening %d osl tables in %s\n", NUM_AFS_TABLES,
687                 database_dir);
688         for (i = 0; i < NUM_AFS_TABLES; i++) {
689                 ret = afs_tables[i].open(database_dir);
690                 if (ret >= 0)
691                         continue;
692                 PARA_ERROR_LOG("%s init: %s\n", afs_tables[i].name,
693                         para_strerror(-ret));
694                 break;
695         }
696         if (ret >= 0)
697                 return ret;
698         while (i)
699                 afs_tables[--i].close();
700         return ret;
701 }
702
703 static int afs_signal_post_select(struct sched *s, __a_unused void *context)
704 {
705         int signum, ret;
706
707         if (getppid() == 1) {
708                 PARA_EMERG_LOG("para_server died\n");
709                 goto shutdown;
710         }
711         signum = para_next_signal(&s->rfds);
712         if (signum == 0)
713                 return 0;
714         if (signum == SIGHUP) {
715                 close_afs_tables();
716                 parse_config_or_die(1);
717                 ret = open_afs_tables();
718                 if (ret < 0)
719                         return ret;
720                 init_admissible_files(current_mop);
721                 return 0;
722         }
723         PARA_EMERG_LOG("terminating on signal %d\n", signum);
724 shutdown:
725         task_notify_all(s, E_AFS_SIGNAL);
726         return -E_AFS_SIGNAL;
727 }
728
729 static void register_signal_task(struct sched *s)
730 {
731         para_sigaction(SIGPIPE, SIG_IGN);
732         signal_task = signal_init_or_die();
733         para_install_sighandler(SIGINT);
734         para_install_sighandler(SIGTERM);
735         para_install_sighandler(SIGHUP);
736
737         signal_task->task = task_register(&(struct task_info) {
738                 .name = "signal",
739                 .pre_select = signal_pre_select,
740                 .post_select = afs_signal_post_select,
741                 .context = signal_task,
742
743         }, s);
744 }
745
746 static struct list_head afs_client_list;
747
748 /** Describes one connected afs client. */
749 struct afs_client {
750         /** Position in the afs client list. */
751         struct list_head node;
752         /** The socket file descriptor for this client. */
753         int fd;
754         /** The time the client connected. */
755         struct timeval connect_time;
756 };
757
758 static void command_pre_select(struct sched *s, void *context)
759 {
760         struct command_task *ct = context;
761         struct afs_client *client;
762
763         para_fd_set(server_socket, &s->rfds, &s->max_fileno);
764         para_fd_set(ct->fd, &s->rfds, &s->max_fileno);
765         list_for_each_entry(client, &afs_client_list, node)
766                 para_fd_set(client->fd, &s->rfds, &s->max_fileno);
767 }
768
769 /**
770  * Send data as shared memory to a file descriptor.
771  *
772  * \param fd File descriptor to send the shmid to.
773  * \param band The band designator for this data.
774  * \param buf The buffer holding the data to be sent.
775  * \param size The size of \a buf.
776  *
777  * This function creates a shared memory area large enough to hold
778  * the content given by \a buf and \a size and sends the identifier
779  * of this area to the file descriptor \a fd.
780  *
781  * It is called by the AFS max_size handler as well as directly by the AFS
782  * command callbacks to send command output to the command handlers.
783  *
784  * \return Zero if \a buf is \p NULL or \a size is zero. Negative on errors,
785  * and positive on success.
786  */
787 int pass_buffer_as_shm(int fd, uint8_t band, const char *buf, size_t size)
788 {
789         int ret, shmid;
790         void *shm;
791         struct callback_result *cr;
792
793         if (size == 0)
794                 assert(band != SBD_OUTPUT);
795         ret = shm_new(size + sizeof(*cr));
796         if (ret < 0)
797                 return ret;
798         shmid = ret;
799         ret = shm_attach(shmid, ATTACH_RW, &shm);
800         if (ret < 0)
801                 goto err;
802         cr = shm;
803         cr->result_size = size;
804         cr->band = band;
805         if (size > 0)
806                 memcpy(shm + sizeof(*cr), buf, size);
807         ret = shm_detach(shm);
808         if (ret < 0)
809                 goto err;
810         ret = write_all(fd, (char *)&shmid, sizeof(int));
811         if (ret >= 0)
812                 return ret;
813 err:
814         if (shm_destroy(shmid) < 0)
815                 PARA_ERROR_LOG("destroy result failed\n");
816         return ret;
817 }
818
819 static int call_callback(int fd, int query_shmid)
820 {
821         void *query_shm;
822         struct callback_query *cq;
823         int ret, ret2;
824         struct afs_callback_arg aca = {.fd = fd};
825
826         ret = shm_attach(query_shmid, ATTACH_RW, &query_shm);
827         if (ret < 0)
828                 return ret;
829         cq = query_shm;
830         aca.query.data = (char *)query_shm + sizeof(*cq);
831         aca.query.size = cq->query_size;
832         aca.pbout.max_size = shm_get_shmmax();
833         aca.pbout.max_size_handler = afs_max_size_handler;
834         aca.pbout.private_data = &(struct afs_max_size_handler_data) {
835                 .fd = fd,
836                 .band = SBD_OUTPUT
837         };
838         ret = cq->handler(&aca);
839         ret2 = shm_detach(query_shm);
840         if (ret2 < 0) {
841                 if (ret < 0) /* ignore (but log) detach error */
842                         PARA_ERROR_LOG("could not detach sma: %s\n",
843                                 para_strerror(-ret2));
844                 else
845                         ret = ret2;
846         }
847         flush_and_free_pb(&aca.pbout);
848         if (ret < 0) {
849                 ret2 = pass_buffer_as_shm(fd, SBD_AFS_CB_FAILURE,
850                         (const char *)&ret, sizeof(ret));
851                 if (ret2 < 0)
852                         PARA_ERROR_LOG("could not pass cb failure packet: %s\n",
853                                 para_strerror(-ret));
854         }
855         return ret;
856 }
857
858 static int execute_server_command(fd_set *rfds)
859 {
860         char buf[8];
861         size_t n;
862         int ret = read_nonblock(server_socket, buf, sizeof(buf) - 1, rfds, &n);
863
864         if (ret < 0 || n == 0)
865                 return ret;
866         buf[n] = '\0';
867         if (strcmp(buf, "new"))
868                 return -ERRNO_TO_PARA_ERROR(EINVAL);
869         return open_next_audio_file();
870 }
871
872 /* returns 0 if no data available, 1 else */
873 static int execute_afs_command(int fd, fd_set *rfds, uint32_t expected_cookie)
874 {
875         uint32_t cookie;
876         int query_shmid;
877         char buf[sizeof(cookie) + sizeof(query_shmid)];
878         size_t n;
879         int ret = read_nonblock(fd, buf, sizeof(buf), rfds, &n);
880
881         if (ret < 0)
882                 goto err;
883         if (n == 0)
884                 return 0;
885         if (n != sizeof(buf)) {
886                 PARA_NOTICE_LOG("short read (%d bytes, expected %lu)\n",
887                         ret, (long unsigned) sizeof(buf));
888                 return 1;
889         }
890         cookie = *(uint32_t *)buf;
891         if (cookie != expected_cookie) {
892                 PARA_NOTICE_LOG("received invalid cookie (got %u, expected %u)\n",
893                         (unsigned)cookie, (unsigned)expected_cookie);
894                 return 1;
895         }
896         query_shmid = *(int *)(buf + sizeof(cookie));
897         if (query_shmid < 0) {
898                 PARA_WARNING_LOG("received invalid query shmid %d)\n",
899                         query_shmid);
900                 return 1;
901         }
902         ret = call_callback(fd, query_shmid);
903         if (ret >= 0)
904                 return 1;
905 err:
906         PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
907         return 1;
908 }
909
910 /** Shutdown connection if query has not arrived until this many seconds. */
911 #define AFS_CLIENT_TIMEOUT 3
912
913 static int command_post_select(struct sched *s, void *context)
914 {
915         struct command_task *ct = context;
916         struct sockaddr_un unix_addr;
917         struct afs_client *client, *tmp;
918         int fd, ret;
919
920         ret = task_get_notification(ct->task);
921         if (ret < 0)
922                 return ret;
923         ret = execute_server_command(&s->rfds);
924         if (ret < 0) {
925                 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
926                 task_notify_all(s, -ret);
927                 return ret;
928         }
929         /* Check the list of connected clients. */
930         list_for_each_entry_safe(client, tmp, &afs_client_list, node) {
931                 ret = execute_afs_command(client->fd, &s->rfds, ct->cookie);
932                 if (ret == 0) { /* prevent bogus connection flooding */
933                         struct timeval diff;
934                         tv_diff(now, &client->connect_time, &diff);
935                         if (diff.tv_sec < AFS_CLIENT_TIMEOUT)
936                                 continue;
937                         PARA_WARNING_LOG("connection timeout\n");
938                 }
939                 close(client->fd);
940                 list_del(&client->node);
941                 free(client);
942         }
943         /* Accept connections on the local socket. */
944         ret = para_accept(ct->fd, &s->rfds, &unix_addr, sizeof(unix_addr), &fd);
945         if (ret < 0)
946                 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
947         if (ret <= 0)
948                 return 0;
949         ret = mark_fd_nonblocking(fd);
950         if (ret < 0) {
951                 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
952                 close(fd);
953                 return 0;
954         }
955         client = para_malloc(sizeof(*client));
956         client->fd = fd;
957         client->connect_time = *now;
958         para_list_add(&client->node, &afs_client_list);
959         return 0;
960 }
961
962 static void register_command_task(uint32_t cookie, struct sched *s)
963 {
964         struct command_task *ct = &command_task_struct;
965         ct->fd = setup_command_socket_or_die();
966         ct->cookie = cookie;
967
968         ct->task = task_register(&(struct task_info) {
969                 .name = "afs command",
970                 .pre_select = command_pre_select,
971                 .post_select = command_post_select,
972                 .context = ct,
973         }, s);
974 }
975
976 /**
977  * Initialize the audio file selector process.
978  *
979  * \param cookie The value used for "authentication".
980  * \param socket_fd File descriptor used for communication with the server.
981  */
982 __noreturn void afs_init(uint32_t cookie, int socket_fd)
983 {
984         static struct sched s;
985         int i, ret;
986
987         register_signal_task(&s);
988         INIT_LIST_HEAD(&afs_client_list);
989         for (i = 0; i < NUM_AFS_TABLES; i++)
990                 afs_tables[i].init(&afs_tables[i]);
991         ret = open_afs_tables();
992         if (ret < 0)
993                 goto out;
994         server_socket = socket_fd;
995         ret = mark_fd_nonblocking(server_socket);
996         if (ret < 0)
997                 goto out_close;
998         PARA_INFO_LOG("server_socket: %d, afs_socket_cookie: %u\n",
999                 server_socket, (unsigned) cookie);
1000         init_admissible_files(conf.afs_initial_mode_arg);
1001         register_command_task(cookie, &s);
1002         s.default_timeout.tv_sec = 0;
1003         s.default_timeout.tv_usec = 999 * 1000;
1004         ret = write(socket_fd, "\0", 1);
1005         if (ret != 1) {
1006                 if (ret == 0)
1007                         errno = EINVAL;
1008                 ret = -ERRNO_TO_PARA_ERROR(errno);
1009                 goto out_close;
1010         }
1011         ret = schedule(&s);
1012         sched_shutdown(&s);
1013 out_close:
1014         close_afs_tables();
1015 out:
1016         if (ret < 0)
1017                 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1018         exit(EXIT_FAILURE);
1019 }
1020
1021 static int com_init_callback(struct afs_callback_arg *aca)
1022 {
1023         uint32_t table_mask = *(uint32_t *)aca->query.data;
1024         int i, ret;
1025
1026         close_afs_tables();
1027         for (i = 0; i < NUM_AFS_TABLES; i++) {
1028                 struct afs_table *t = &afs_tables[i];
1029
1030                 if (!(table_mask & (1 << i)))
1031                         continue;
1032                 if (!t->create)
1033                         continue;
1034                 ret = t->create(database_dir);
1035                 if (ret < 0) {
1036                         para_printf(&aca->pbout, "cannot create table %s\n",
1037                                 t->name);
1038                         goto out;
1039                 }
1040                 para_printf(&aca->pbout, "successfully created %s table\n",
1041                         t->name);
1042         }
1043         ret = open_afs_tables();
1044         if (ret < 0)
1045                 para_printf(&aca->pbout, "cannot open afs tables\n");
1046 out:
1047         return ret;
1048 }
1049
1050 static int com_init(struct command_context *cc, struct lls_parse_result *lpr)
1051 {
1052         int i, j, ret;
1053         uint32_t table_mask = (1 << (NUM_AFS_TABLES + 1)) - 1;
1054         struct osl_object query = {.data = &table_mask,
1055                 .size = sizeof(table_mask)};
1056         unsigned num_inputs = lls_num_inputs(lpr);
1057
1058         ret = make_database_dir();
1059         if (ret < 0)
1060                 return ret;
1061         if (num_inputs > 0) {
1062                 table_mask = 0;
1063                 for (i = 0; i < num_inputs; i++) {
1064                         for (j = 0; j < NUM_AFS_TABLES; j++) {
1065                                 struct afs_table *t = &afs_tables[j];
1066
1067                                 if (strcmp(lls_input(i, lpr), t->name))
1068                                         continue;
1069                                 table_mask |= (1 << j);
1070                                 break;
1071                         }
1072                         if (j == NUM_AFS_TABLES)
1073                                 return -E_BAD_TABLE_NAME;
1074                 }
1075         }
1076         return send_callback_request(com_init_callback, &query,
1077                 afs_cb_result_handler, cc);
1078 }
1079 EXPORT_SERVER_CMD_HANDLER(init);
1080
1081 static int com_check(struct command_context *cc, struct lls_parse_result *lpr)
1082 {
1083         const struct lls_opt_result *r_a = SERVER_CMD_OPT_RESULT(CHECK, AFT, lpr);
1084         const struct lls_opt_result *r_A = SERVER_CMD_OPT_RESULT(CHECK, ATTRIBUTE, lpr);
1085         const struct lls_opt_result *r_m = SERVER_CMD_OPT_RESULT(CHECK, MOOD, lpr);
1086         const struct lls_opt_result *r_p = SERVER_CMD_OPT_RESULT(CHECK, PLAYLIST, lpr);
1087         bool noopt = !lls_opt_given(r_a) && !lls_opt_given(r_A)
1088                 && !lls_opt_given(r_m) && !lls_opt_given(r_p);
1089         int ret;
1090
1091         if (noopt || lls_opt_given(r_a)) {
1092                 ret = send_callback_request(aft_check_callback, NULL,
1093                         afs_cb_result_handler, cc);
1094                 if (ret < 0)
1095                         return ret;
1096         }
1097         if (noopt || lls_opt_given(r_A)) {
1098                 ret = send_callback_request(attribute_check_callback, NULL,
1099                         afs_cb_result_handler, cc);
1100                 if (ret < 0)
1101                         return ret;
1102         }
1103         if (noopt || lls_opt_given(r_p)) {
1104                 ret = send_callback_request(playlist_check_callback,
1105                         NULL, afs_cb_result_handler, cc);
1106                 if (ret < 0)
1107                         return ret;
1108         }
1109         if (noopt || lls_opt_given(r_m)) {
1110                 ret = send_callback_request(mood_check_callback, NULL,
1111                         afs_cb_result_handler, cc);
1112                 if (ret < 0)
1113                         return ret;
1114         }
1115         return 1;
1116 }
1117 EXPORT_SERVER_CMD_HANDLER(check);
1118
1119 /**
1120  * The afs event dispatcher.
1121  *
1122  * \param event Type of the event.
1123  * \param pb May be \p NULL.
1124  * \param data Type depends on \a event.
1125  *
1126  * This function calls each table event handler, passing \a pb and \a data
1127  * verbatim. It's up to the handlers to interpret the \a data pointer. If a
1128  * handler returns negative, the loop is aborted.
1129  *
1130  * \return The (negative) error code of the first handler that failed, or non-negative
1131  * if all handlers succeeded.
1132  */
1133 __must_check int afs_event(enum afs_events event, struct para_buffer *pb,
1134                 void *data)
1135 {
1136         int i, ret;
1137
1138         for (i = 0; i < NUM_AFS_TABLES; i++) {
1139                 struct afs_table *t = &afs_tables[i];
1140                 if (!t->event_handler)
1141                         continue;
1142                 ret = t->event_handler(event, pb, data);
1143                 if (ret < 0) {
1144                         PARA_CRIT_LOG("table %s, event %u: %s\n", t->name,
1145                                 event, para_strerror(-ret));
1146                         return ret;
1147                 }
1148         }
1149         return 1;
1150 }
1151
1152 /**
1153  * Dummy event handler for the images table.
1154  *
1155  * \param event Unused.
1156  * \param pb Unused.
1157  * \param data Unused.
1158  *
1159  * \return The images table does not honor events, so this handler always
1160  * returns success.
1161  */
1162 __a_const int images_event_handler(__a_unused enum afs_events event,
1163         __a_unused  struct para_buffer *pb, __a_unused void *data)
1164 {
1165         return 1;
1166 }
1167
1168 /**
1169  * Dummy event handler for the lyrics table.
1170  *
1171  * \param event Unused.
1172  * \param pb Unused.
1173  * \param data Unused.
1174  *
1175  * \return The lyrics table does not honor events, so this handler always
1176  * returns success.
1177  */
1178 __a_const int lyrics_event_handler(__a_unused enum afs_events event,
1179         __a_unused struct para_buffer *pb, __a_unused void *data)
1180 {
1181         return 1;
1182 }