]> git.tuebingen.mpg.de Git - paraslash.git/blob - afs.c
Add test to check whether empty mood arguments are rejected.
[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  * Passed from command handlers to afs.
94  *
95  * Command handlers cannot change the afs database directly because they run in
96  * a separate process. The callback query structure circumvents this
97  * restriction as follows. To instruct the afs process to execute a particular
98  * function, the command hander writes an instance of this structure to a
99  * shared memory area, along with the arguments to the callback function. The
100  * identifier of the shared memory area is transferred to the afs process via
101  * the command socket.
102  *
103  * The afs process reads the shared memory id from the command socket, attaches
104  * the corresponding area, and calls the callback function whose address is
105  * stored in the area.
106  *
107  * The command output, if any, is transferred back to the command handler in
108  * the same way: The afs process writes the output to a second shared memory
109  * area together with a fixed size metadata header whose format corresponds to
110  * the \ref callback_result structure. The identifier of this area is sent back
111  * to the command handler which attaches the area and forwards the output to
112  * the remote client.
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         /*
485          * We get called with arg == current_mop from the signal dispatcher
486          * after SIGHUP and from the error path of the select command to
487          * re-select the current mood or playlist. In this case the assignment
488          * to current_mop below would result in a use-after-free condition.
489          */
490         if (arg != current_mop) {
491                 free(current_mop);
492                 if (arg) {
493                         current_mop = para_strdup(arg);
494                         mutex_lock(mmd_mutex);
495                         strncpy(mmd->afs_mode_string, arg,
496                                 sizeof(mmd->afs_mode_string));
497                         mmd->afs_mode_string[sizeof(mmd->afs_mode_string) - 1] = '\0';
498                         mmd->events++;
499                         mutex_unlock(mmd_mutex);
500                 } else {
501                         mutex_lock(mmd_mutex);
502                         strcpy(mmd->afs_mode_string, "dummy");
503                         mmd->events++;
504                         mutex_unlock(mmd_mutex);
505                         current_mop = NULL;
506                 }
507         }
508         return 1;
509 }
510
511 /**
512  * Result handler for sending data to the para_client process.
513  *
514  * \param result The data to be sent.
515  * \param band The band designator.
516  * \param private Pointer to the command context.
517  *
518  * \return The return value of the underlying call to \ref command.c::send_sb.
519  *
520  * \sa \ref callback_result_handler, \ref command.c::send_sb.
521  */
522 int afs_cb_result_handler(struct osl_object *result, uint8_t band,
523                 void *private)
524 {
525         struct command_context *cc = private;
526
527         assert(cc);
528         switch (band) {
529         case SBD_OUTPUT:
530         case SBD_DEBUG_LOG:
531         case SBD_INFO_LOG:
532         case SBD_NOTICE_LOG:
533         case SBD_WARNING_LOG:
534         case SBD_ERROR_LOG:
535         case SBD_CRIT_LOG:
536         case SBD_EMERG_LOG:
537                 assert(result->size > 0);
538                 return send_sb(&cc->scc, result->data, result->size, band, true);
539         case SBD_AFS_CB_FAILURE:
540                 return *(int *)(result->data);
541         default:
542                 return -E_BAD_BAND;
543         }
544 }
545
546 static void flush_and_free_pb(struct para_buffer *pb)
547 {
548         int ret;
549         struct afs_max_size_handler_data *amshd = pb->private_data;
550
551         if (pb->buf && pb->size > 0) {
552                 ret = pass_buffer_as_shm(amshd->fd, amshd->band, pb->buf,
553                         pb->offset);
554                 if (ret < 0)
555                         PARA_ERROR_LOG("%s\n", para_strerror(-ret));
556         }
557         free(pb->buf);
558 }
559
560 static int com_select_callback(struct afs_callback_arg *aca)
561 {
562         const struct lls_command *cmd = SERVER_CMD_CMD_PTR(SELECT);
563         const char *arg;
564         int num_admissible, ret;
565         char *errmsg;
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, &errmsg);
580         if (ret >= 0)
581                 goto out;
582         /* ignore subsequent errors (but log them) */
583         para_printf(&aca->pbout, "%s\n", errmsg);
584         free(errmsg);
585         para_printf(&aca->pbout, "could not activate %s\n", arg);
586         if (current_mop && strcmp(current_mop, arg) != 0) {
587                 int ret2;
588                 para_printf(&aca->pbout, "switching back to %s\n", current_mop);
589                 ret2 = activate_mood_or_playlist(current_mop, &num_admissible,
590                         &errmsg);
591                 if (ret2 >= 0)
592                         goto out;
593                 para_printf(&aca->pbout, "%s\n", errmsg);
594                 free(errmsg);
595                 para_printf(&aca->pbout, "could not reactivate %s: %s\n",
596                         current_mop, para_strerror(-ret2));
597         }
598         para_printf(&aca->pbout, "activating dummy mood\n");
599         activate_mood_or_playlist(NULL, &num_admissible, NULL);
600 out:
601         para_printf(&aca->pbout, "activated %s (%d admissible file%s)\n",
602                 current_mop? current_mop : "dummy mood", num_admissible,
603                         num_admissible == 1? "" : "s");
604 free_lpr:
605         lls_free_parse_result(aca->lpr, cmd);
606         return ret;
607 }
608
609 static int com_select(struct command_context *cc, struct lls_parse_result *lpr)
610 {
611         const struct lls_command *cmd = SERVER_CMD_CMD_PTR(SELECT);
612         char *errctx;
613         int ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
614
615         if (ret < 0) {
616                 send_errctx(cc, errctx);
617                 return ret;
618         }
619         return send_lls_callback_request(com_select_callback, cmd, lpr, cc);
620 }
621 EXPORT_SERVER_CMD_HANDLER(select);
622
623 static void init_admissible_files(const char *arg)
624 {
625         int ret = activate_mood_or_playlist(arg, NULL, NULL);
626         if (ret < 0) {
627                 PARA_WARNING_LOG("could not activate %s: %s\n", arg,
628                         para_strerror(-ret));
629                 if (arg)
630                         activate_mood_or_playlist(NULL, NULL, NULL);
631         }
632 }
633
634 static int setup_command_socket_or_die(void)
635 {
636         int ret, socket_fd;
637         const char *socket_name = OPT_STRING_VAL(AFS_SOCKET);
638
639         unlink(socket_name);
640         ret = create_local_socket(socket_name);
641         if (ret < 0) {
642                 PARA_EMERG_LOG("%s: %s\n", para_strerror(-ret), socket_name);
643                 exit(EXIT_FAILURE);
644         }
645         socket_fd = ret;
646         PARA_INFO_LOG("listening on socket %s (fd %d)\n", socket_name,
647                 socket_fd);
648         return socket_fd;
649 }
650
651 static char *database_dir;
652
653 static void close_afs_tables(void)
654 {
655         int i;
656         PARA_NOTICE_LOG("closing afs tables\n");
657         for (i = 0; i < NUM_AFS_TABLES; i++)
658                 afs_tables[i].close();
659         free(database_dir);
660         database_dir = NULL;
661 }
662
663 static void get_database_dir(void)
664 {
665         if (!database_dir) {
666                 if (OPT_GIVEN(AFS_DATABASE_DIR))
667                         database_dir = para_strdup(OPT_STRING_VAL(AFS_DATABASE_DIR));
668                 else {
669                         char *home = para_homedir();
670                         database_dir = make_message(
671                                 "%s/.paraslash/afs_database-0.7", home);
672                         free(home);
673                 }
674         }
675         PARA_INFO_LOG("afs_database dir %s\n", database_dir);
676 }
677
678 static int make_database_dir(void)
679 {
680         int ret;
681
682         get_database_dir();
683         ret = para_mkdir(database_dir, 0777);
684         if (ret >= 0 || ret == -ERRNO_TO_PARA_ERROR(EEXIST))
685                 return 1;
686         return ret;
687 }
688
689 static int open_afs_tables(void)
690 {
691         int i, ret;
692
693         get_database_dir();
694         PARA_NOTICE_LOG("opening %d osl tables in %s\n", NUM_AFS_TABLES,
695                 database_dir);
696         for (i = 0; i < NUM_AFS_TABLES; i++) {
697                 ret = afs_tables[i].open(database_dir);
698                 if (ret >= 0)
699                         continue;
700                 PARA_ERROR_LOG("could not open %s\n", afs_tables[i].name);
701                 break;
702         }
703         if (ret >= 0)
704                 return ret;
705         while (i)
706                 afs_tables[--i].close();
707         return ret;
708 }
709
710 static int afs_signal_post_select(struct sched *s, __a_unused void *context)
711 {
712         int signum, ret;
713
714         if (getppid() == 1) {
715                 PARA_EMERG_LOG("para_server died\n");
716                 goto shutdown;
717         }
718         signum = para_next_signal(&s->rfds);
719         if (signum == 0)
720                 return 0;
721         if (signum == SIGHUP) {
722                 close_afs_tables();
723                 parse_config_or_die(1);
724                 ret = open_afs_tables();
725                 if (ret < 0)
726                         return ret;
727                 init_admissible_files(current_mop);
728                 return 0;
729         }
730         PARA_EMERG_LOG("terminating on signal %d\n", signum);
731 shutdown:
732         task_notify_all(s, E_AFS_SIGNAL);
733         return -E_AFS_SIGNAL;
734 }
735
736 static void register_signal_task(struct sched *s)
737 {
738         para_sigaction(SIGPIPE, SIG_IGN);
739         signal_task = signal_init_or_die();
740         para_install_sighandler(SIGINT);
741         para_install_sighandler(SIGTERM);
742         para_install_sighandler(SIGHUP);
743
744         signal_task->task = task_register(&(struct task_info) {
745                 .name = "signal",
746                 .pre_select = signal_pre_select,
747                 .post_select = afs_signal_post_select,
748                 .context = signal_task,
749
750         }, s);
751 }
752
753 static struct list_head afs_client_list;
754
755 /** Describes one connected afs client. */
756 struct afs_client {
757         /** Position in the afs client list. */
758         struct list_head node;
759         /** The socket file descriptor for this client. */
760         int fd;
761         /** The time the client connected. */
762         struct timeval connect_time;
763 };
764
765 static void command_pre_select(struct sched *s, void *context)
766 {
767         struct command_task *ct = context;
768         struct afs_client *client;
769
770         para_fd_set(server_socket, &s->rfds, &s->max_fileno);
771         para_fd_set(ct->fd, &s->rfds, &s->max_fileno);
772         list_for_each_entry(client, &afs_client_list, node)
773                 para_fd_set(client->fd, &s->rfds, &s->max_fileno);
774 }
775
776 /**
777  * Send data as shared memory to a file descriptor.
778  *
779  * \param fd File descriptor to send the shmid to.
780  * \param band The band designator for this data.
781  * \param buf The buffer holding the data to be sent.
782  * \param size The size of \a buf.
783  *
784  * This function creates a shared memory area large enough to hold
785  * the content given by \a buf and \a size and sends the identifier
786  * of this area to the file descriptor \a fd.
787  *
788  * It is called by the AFS max_size handler as well as directly by the AFS
789  * command callbacks to send command output to the command handlers.
790  *
791  * \return Zero if \a buf is \p NULL or \a size is zero. Negative on errors,
792  * and positive on success.
793  */
794 int pass_buffer_as_shm(int fd, uint8_t band, const char *buf, size_t size)
795 {
796         int ret, shmid;
797         void *shm;
798         struct callback_result *cr;
799
800         if (size == 0)
801                 assert(band != SBD_OUTPUT);
802         ret = shm_new(size + sizeof(*cr));
803         if (ret < 0)
804                 return ret;
805         shmid = ret;
806         ret = shm_attach(shmid, ATTACH_RW, &shm);
807         if (ret < 0)
808                 goto err;
809         cr = shm;
810         cr->result_size = size;
811         cr->band = band;
812         if (size > 0)
813                 memcpy(shm + sizeof(*cr), buf, size);
814         ret = shm_detach(shm);
815         if (ret < 0)
816                 goto err;
817         ret = write_all(fd, (char *)&shmid, sizeof(int));
818         if (ret >= 0)
819                 return ret;
820 err:
821         if (shm_destroy(shmid) < 0)
822                 PARA_ERROR_LOG("destroy result failed\n");
823         return ret;
824 }
825
826 static int call_callback(int fd, int query_shmid)
827 {
828         void *query_shm;
829         struct callback_query *cq;
830         int ret, ret2;
831         struct afs_callback_arg aca = {.fd = fd};
832
833         ret = shm_attach(query_shmid, ATTACH_RW, &query_shm);
834         if (ret < 0)
835                 return ret;
836         cq = query_shm;
837         aca.query.data = (char *)query_shm + sizeof(*cq);
838         aca.query.size = cq->query_size;
839         aca.pbout.max_size = shm_get_shmmax();
840         aca.pbout.max_size_handler = afs_max_size_handler;
841         aca.pbout.private_data = &(struct afs_max_size_handler_data) {
842                 .fd = fd,
843                 .band = SBD_OUTPUT
844         };
845         ret = cq->handler(&aca);
846         ret2 = shm_detach(query_shm);
847         if (ret2 < 0) {
848                 if (ret < 0) /* ignore (but log) detach error */
849                         PARA_ERROR_LOG("could not detach sma: %s\n",
850                                 para_strerror(-ret2));
851                 else
852                         ret = ret2;
853         }
854         flush_and_free_pb(&aca.pbout);
855         if (ret < 0) {
856                 ret2 = pass_buffer_as_shm(fd, SBD_AFS_CB_FAILURE,
857                         (const char *)&ret, sizeof(ret));
858                 if (ret2 < 0)
859                         PARA_ERROR_LOG("could not pass cb failure packet: %s\n",
860                                 para_strerror(-ret));
861         }
862         return ret;
863 }
864
865 static int execute_server_command(fd_set *rfds)
866 {
867         char buf[8];
868         size_t n;
869         int ret = read_nonblock(server_socket, buf, sizeof(buf) - 1, rfds, &n);
870
871         if (ret < 0 || n == 0)
872                 return ret;
873         buf[n] = '\0';
874         if (strcmp(buf, "new"))
875                 return -ERRNO_TO_PARA_ERROR(EINVAL);
876         return open_next_audio_file();
877 }
878
879 /* returns 0 if no data available, 1 else */
880 static int execute_afs_command(int fd, fd_set *rfds)
881 {
882         uint32_t cookie;
883         int query_shmid;
884         char buf[sizeof(cookie) + sizeof(query_shmid)];
885         size_t n;
886         int ret = read_nonblock(fd, buf, sizeof(buf), rfds, &n);
887
888         if (ret < 0)
889                 goto err;
890         if (n == 0)
891                 return 0;
892         if (n != sizeof(buf)) {
893                 PARA_NOTICE_LOG("short read (%d bytes, expected %lu)\n",
894                         ret, (long unsigned) sizeof(buf));
895                 return 1;
896         }
897         cookie = *(uint32_t *)buf;
898         if (cookie != afs_socket_cookie) {
899                 PARA_NOTICE_LOG("received invalid cookie (got %u, expected %u)\n",
900                         (unsigned)cookie, (unsigned)afs_socket_cookie);
901                 return 1;
902         }
903         query_shmid = *(int *)(buf + sizeof(cookie));
904         if (query_shmid < 0) {
905                 PARA_WARNING_LOG("received invalid query shmid %d)\n",
906                         query_shmid);
907                 return 1;
908         }
909         ret = call_callback(fd, query_shmid);
910         if (ret >= 0)
911                 return 1;
912 err:
913         PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
914         return 1;
915 }
916
917 /** Shutdown connection if query has not arrived until this many seconds. */
918 #define AFS_CLIENT_TIMEOUT 3
919
920 static int command_post_select(struct sched *s, void *context)
921 {
922         struct command_task *ct = context;
923         struct sockaddr_un unix_addr;
924         struct afs_client *client, *tmp;
925         int fd, ret;
926
927         ret = task_get_notification(ct->task);
928         if (ret < 0)
929                 return ret;
930         ret = execute_server_command(&s->rfds);
931         if (ret < 0) {
932                 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
933                 task_notify_all(s, -ret);
934                 return ret;
935         }
936         /* Check the list of connected clients. */
937         list_for_each_entry_safe(client, tmp, &afs_client_list, node) {
938                 ret = execute_afs_command(client->fd, &s->rfds);
939                 if (ret == 0) { /* prevent bogus connection flooding */
940                         struct timeval diff;
941                         tv_diff(now, &client->connect_time, &diff);
942                         if (diff.tv_sec < AFS_CLIENT_TIMEOUT)
943                                 continue;
944                         PARA_WARNING_LOG("connection timeout\n");
945                 }
946                 close(client->fd);
947                 list_del(&client->node);
948                 free(client);
949         }
950         /* Accept connections on the local socket. */
951         ret = para_accept(ct->fd, &s->rfds, &unix_addr, sizeof(unix_addr), &fd);
952         if (ret < 0)
953                 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
954         if (ret <= 0)
955                 return 0;
956         ret = mark_fd_nonblocking(fd);
957         if (ret < 0) {
958                 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
959                 close(fd);
960                 return 0;
961         }
962         client = para_malloc(sizeof(*client));
963         client->fd = fd;
964         client->connect_time = *now;
965         para_list_add(&client->node, &afs_client_list);
966         return 0;
967 }
968
969 static void register_command_task(struct sched *s)
970 {
971         struct command_task *ct = &command_task_struct;
972         ct->fd = setup_command_socket_or_die();
973
974         ct->task = task_register(&(struct task_info) {
975                 .name = "afs command",
976                 .pre_select = command_pre_select,
977                 .post_select = command_post_select,
978                 .context = ct,
979         }, s);
980 }
981
982 /**
983  * Initialize the audio file selector process.
984  *
985  * \param socket_fd File descriptor used for communication with the server.
986  */
987 __noreturn void afs_init(int socket_fd)
988 {
989         static struct sched s;
990         int i, ret;
991
992         register_signal_task(&s);
993         init_list_head(&afs_client_list);
994         for (i = 0; i < NUM_AFS_TABLES; i++)
995                 afs_tables[i].init(&afs_tables[i]);
996         ret = open_afs_tables();
997         if (ret < 0)
998                 goto out;
999         server_socket = socket_fd;
1000         ret = mark_fd_nonblocking(server_socket);
1001         if (ret < 0)
1002                 goto out_close;
1003         PARA_INFO_LOG("server_socket: %d\n", server_socket);
1004         init_admissible_files(OPT_STRING_VAL(AFS_INITIAL_MODE));
1005         register_command_task(&s);
1006         s.default_timeout.tv_sec = 0;
1007         s.default_timeout.tv_usec = 999 * 1000;
1008         ret = write(socket_fd, "\0", 1);
1009         if (ret != 1) {
1010                 if (ret == 0)
1011                         errno = EINVAL;
1012                 ret = -ERRNO_TO_PARA_ERROR(errno);
1013                 goto out_close;
1014         }
1015         ret = schedule(&s);
1016         sched_shutdown(&s);
1017         close_current_mood();
1018 out_close:
1019         close_afs_tables();
1020 out:
1021         signal_shutdown(signal_task);
1022         free_status_items();
1023         free(current_mop);
1024         free_lpr();
1025         if (ret < 0)
1026                 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1027         exit(EXIT_FAILURE);
1028 }
1029
1030 static int com_init_callback(struct afs_callback_arg *aca)
1031 {
1032         uint32_t table_mask = *(uint32_t *)aca->query.data;
1033         int i, ret;
1034
1035         close_afs_tables();
1036         get_database_dir();
1037         for (i = 0; i < NUM_AFS_TABLES; i++) {
1038                 struct afs_table *t = &afs_tables[i];
1039
1040                 if (!(table_mask & (1 << i)))
1041                         continue;
1042                 if (!t->create)
1043                         continue;
1044                 ret = t->create(database_dir);
1045                 if (ret < 0) {
1046                         para_printf(&aca->pbout, "cannot create table %s\n",
1047                                 t->name);
1048                         goto out;
1049                 }
1050                 para_printf(&aca->pbout, "successfully created %s table\n",
1051                         t->name);
1052         }
1053         ret = open_afs_tables();
1054         if (ret < 0)
1055                 para_printf(&aca->pbout, "cannot open afs tables: %s\n",
1056                         para_strerror(-ret));
1057 out:
1058         return ret;
1059 }
1060
1061 static int com_init(struct command_context *cc, struct lls_parse_result *lpr)
1062 {
1063         int i, j, ret;
1064         uint32_t table_mask = (1 << (NUM_AFS_TABLES + 1)) - 1;
1065         struct osl_object query = {.data = &table_mask,
1066                 .size = sizeof(table_mask)};
1067         unsigned num_inputs = lls_num_inputs(lpr);
1068
1069         ret = make_database_dir();
1070         if (ret < 0)
1071                 return ret;
1072         if (num_inputs > 0) {
1073                 table_mask = 0;
1074                 for (i = 0; i < num_inputs; i++) {
1075                         for (j = 0; j < NUM_AFS_TABLES; j++) {
1076                                 struct afs_table *t = &afs_tables[j];
1077
1078                                 if (strcmp(lls_input(i, lpr), t->name))
1079                                         continue;
1080                                 table_mask |= (1 << j);
1081                                 break;
1082                         }
1083                         if (j == NUM_AFS_TABLES)
1084                                 return -E_BAD_TABLE_NAME;
1085                 }
1086         }
1087         return send_callback_request(com_init_callback, &query,
1088                 afs_cb_result_handler, cc);
1089 }
1090 EXPORT_SERVER_CMD_HANDLER(init);
1091
1092 static int com_check(struct command_context *cc, struct lls_parse_result *lpr)
1093 {
1094         const struct lls_opt_result *r_a = SERVER_CMD_OPT_RESULT(CHECK, AFT, lpr);
1095         const struct lls_opt_result *r_A = SERVER_CMD_OPT_RESULT(CHECK, ATTRIBUTE, lpr);
1096         const struct lls_opt_result *r_m = SERVER_CMD_OPT_RESULT(CHECK, MOOD, lpr);
1097         const struct lls_opt_result *r_p = SERVER_CMD_OPT_RESULT(CHECK, PLAYLIST, lpr);
1098         bool noopt = !lls_opt_given(r_a) && !lls_opt_given(r_A)
1099                 && !lls_opt_given(r_m) && !lls_opt_given(r_p);
1100         int ret;
1101
1102         if (noopt || lls_opt_given(r_a)) {
1103                 ret = send_callback_request(aft_check_callback, NULL,
1104                         afs_cb_result_handler, cc);
1105                 if (ret < 0)
1106                         return ret;
1107         }
1108         if (noopt || lls_opt_given(r_A)) {
1109                 ret = send_callback_request(attribute_check_callback, NULL,
1110                         afs_cb_result_handler, cc);
1111                 if (ret < 0)
1112                         return ret;
1113         }
1114         if (noopt || lls_opt_given(r_p)) {
1115                 ret = send_callback_request(playlist_check_callback,
1116                         NULL, afs_cb_result_handler, cc);
1117                 if (ret < 0)
1118                         return ret;
1119         }
1120         if (noopt || lls_opt_given(r_m)) {
1121                 ret = send_callback_request(mood_check_callback, NULL,
1122                         afs_cb_result_handler, cc);
1123                 if (ret < 0)
1124                         return ret;
1125         }
1126         return 1;
1127 }
1128 EXPORT_SERVER_CMD_HANDLER(check);
1129
1130 /**
1131  * The afs event dispatcher.
1132  *
1133  * \param event Type of the event.
1134  * \param pb May be \p NULL.
1135  * \param data Type depends on \a event.
1136  *
1137  * This function calls each table event handler, passing \a pb and \a data
1138  * verbatim. It's up to the handlers to interpret the \a data pointer. If a
1139  * handler returns negative, the loop is aborted.
1140  *
1141  * \return The (negative) error code of the first handler that failed, or non-negative
1142  * if all handlers succeeded.
1143  */
1144 __must_check int afs_event(enum afs_events event, struct para_buffer *pb,
1145                 void *data)
1146 {
1147         int i, ret;
1148
1149         for (i = 0; i < NUM_AFS_TABLES; i++) {
1150                 struct afs_table *t = &afs_tables[i];
1151                 if (!t->event_handler)
1152                         continue;
1153                 ret = t->event_handler(event, pb, data);
1154                 if (ret < 0) {
1155                         PARA_CRIT_LOG("table %s, event %u: %s\n", t->name,
1156                                 event, para_strerror(-ret));
1157                         return ret;
1158                 }
1159         }
1160         return 1;
1161 }
1162
1163 /**
1164  * Dummy event handler for the images table.
1165  *
1166  * \param event Unused.
1167  * \param pb Unused.
1168  * \param data Unused.
1169  *
1170  * \return The images table does not honor events, so this handler always
1171  * returns success.
1172  */
1173 __a_const int images_event_handler(__a_unused enum afs_events event,
1174         __a_unused  struct para_buffer *pb, __a_unused void *data)
1175 {
1176         return 1;
1177 }
1178
1179 /**
1180  * Dummy event handler for the lyrics table.
1181  *
1182  * \param event Unused.
1183  * \param pb Unused.
1184  * \param data Unused.
1185  *
1186  * \return The lyrics table does not honor events, so this handler always
1187  * returns success.
1188  */
1189 __a_const int lyrics_event_handler(__a_unused enum afs_events event,
1190         __a_unused struct para_buffer *pb, __a_unused void *data)
1191 {
1192         return 1;
1193 }