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