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