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