]> git.tuebingen.mpg.de Git - paraslash.git/blob - afs.c
aft.c: Remove special case code for playlist mode.
[paraslash.git] / afs.c
1 /*
2  * Copyright (C) 2007 Andre Noll <maan@systemlinux.org>
3  *
4  * Licensed under the GPL v2. For licencing details see COPYING.
5  */
6
7 /** \file afs.c Paraslash's audio file selector. */
8
9 #include <signal.h>
10 #include <fnmatch.h>
11 #include "server.cmdline.h"
12 #include "para.h"
13 #include "string.h"
14 #include "afh.h"
15 #include "server.h"
16 #include "error.h"
17 #include <dirent.h> /* readdir() */
18 #include <sys/mman.h>
19 #include <sys/time.h>
20 #include "net.h"
21 #include "afs.h"
22 #include "ipc.h"
23 #include "list.h"
24 #include "sched.h"
25 #include "signal.h"
26 #include "fd.h"
27
28 /** The osl tables used by afs. \sa blob.c. */
29 enum afs_table_num {
30         /** Contains audio file information. See aft.c. */
31         TBLNUM_AUDIO_FILES,
32         /** The table for the paraslash attributes. See attribute.c. */
33         TBLNUM_ATTRIBUTES,
34         /**
35          * Paraslash's scoring system is based on Gaussian normal
36          * distributions, and the relevant data is stored in the rbtrees of an
37          * osl table containing only volatile columns.  See score.c for
38          * details.
39          */
40         TBLNUM_SCORES,
41         /**
42          * A standard blob table containing the mood definitions. For details
43          * see mood.c.
44          */
45         TBLNUM_MOODS,
46         /** A blob table containing lyrics on a per-song basis. */
47         TBLNUM_LYRICS,
48         /** Another blob table for images (for example album cover art). */
49         TBLNUM_IMAGES,
50         /** Yet another blob table for storing standard playlists. */
51         TBLNUM_PLAYLIST,
52         /** How many tables are in use? */
53         NUM_AFS_TABLES
54 };
55
56 static struct afs_table afs_tables[NUM_AFS_TABLES] = {
57         [TBLNUM_AUDIO_FILES] = {.init = aft_init},
58         [TBLNUM_ATTRIBUTES] = {.init = attribute_init},
59         [TBLNUM_SCORES] = {.init = score_init},
60         [TBLNUM_MOODS] = {.init = moods_init},
61         [TBLNUM_LYRICS] = {.init = lyrics_init},
62         [TBLNUM_IMAGES] = {.init = images_init},
63         [TBLNUM_PLAYLIST] = {.init = playlists_init},
64 };
65
66 struct command_task {
67         /** The file descriptor for the local socket. */
68         int fd;
69         /**
70          * Value sent by the command handlers to identify themselves as
71          * children of the running para_server.
72          */
73         uint32_t cookie;
74         /** The associated task structure. */
75         struct task task;
76 };
77
78 /**
79  * A random number used to "authenticate" the connection.
80  *
81  * para_server picks this number by random before forking the afs process.  The
82  * command handlers write this number together with the id of the shared memory
83  * area containing the query. This way, a malicious local user has to know this
84  * number to be able to cause the afs process to crash by sending fake queries.
85  */
86 extern uint32_t afs_socket_cookie;
87
88 /**
89  * Struct to let command handlers execute a callback in afs context.
90  *
91  * Commands that need to change the state of afs can't change the relevant data
92  * structures directly because commands are executed in a child process, i.e.
93  * they get their own virtual address space.
94  *
95  * This structure is used by \p send_callback_request() (executed from handler
96  * context) in order to let the afs process call the specified function. An
97  * instance of that structure is written to a shared memory area together with
98  * the arguments to the callback function. The identifier of the shared memory
99  * area is written to the command socket.
100  *
101  * The afs process accepts connections on the command socket and reads the
102  * shared memory id, attaches the corresponing area, calls the given handler to
103  * perform the desired action and to optionally compute a result.
104  *
105  * The result and a \p callback_result structure is then written to another
106  * shared memory area. The identifier for that area is written to the handler's
107  * command socket, so that the handler process can read the id, attach the
108  * shared memory area and use the result.
109  *
110  * \sa struct callback_result.
111  */
112 struct callback_query {
113         /** The function to be called. */
114         callback_function *handler;
115         /** The number of bytes of the query */
116         size_t query_size;
117 };
118
119 /**
120  * Structure embedded in the result of a callback.
121  *
122  * If the callback produced a result, an instance of that structure is embeeded
123  * into the shared memory area holding the result, mainly to let the command
124  * handler know the size of the result.
125  *
126  * \sa struct callback_query.
127  */
128 struct callback_result {
129         /** The number of bytes of the result. */
130         size_t result_size;
131 };
132
133 /**
134  * Ask the afs process to call a given function.
135  *
136  * \param f The function to be called.
137  * \param query Pointer to arbitrary data for the callback.
138  * \param result Callback result will be stored here.
139  *
140  * This function creates a shared memory area, copies the buffer pointed to by
141  * \a buf to that area and notifies the afs process that \a f should be
142  * called ASAP.
143  *
144  * \return Negative, on errors, the return value of the callback function
145  * otherwise.
146  *
147  * \sa send_option_arg_callback_request(), send_standard_callback_request().
148  */
149 int send_callback_request(callback_function *f, struct osl_object *query,
150                 struct osl_object *result)
151 {
152         struct callback_query *cq;
153         struct callback_result *cr;
154         int ret, fd = -1, query_shmid, result_shmid;
155         void *query_shm, *result_shm;
156         char buf[sizeof(afs_socket_cookie) + sizeof(int)];
157         struct sockaddr_un unix_addr;
158         size_t query_shm_size = sizeof(*cq);
159
160         if (query)
161                 query_shm_size += query->size;
162         ret = shm_new(query_shm_size);
163         if (ret < 0)
164                 return ret;
165         query_shmid = ret;
166         ret = shm_attach(query_shmid, ATTACH_RW, &query_shm);
167         if (ret < 0)
168                 goto out;
169         cq = query_shm;
170         cq->handler = f;
171         cq->query_size = query_shm_size - sizeof(*cq);
172
173         if (query)
174                 memcpy(query_shm + sizeof(*cq), query->data, query->size);
175         ret = shm_detach(query_shm);
176         if (ret < 0)
177                 goto out;
178
179         *(uint32_t *) buf = afs_socket_cookie;
180         *(int *) (buf + sizeof(afs_socket_cookie)) = query_shmid;
181
182         ret = get_stream_socket(PF_UNIX);
183         if (ret < 0)
184                 goto out;
185         fd = ret;
186         ret = init_unix_addr(&unix_addr, conf.afs_socket_arg);
187         if (ret < 0)
188                 goto out;
189         ret = PARA_CONNECT(fd, &unix_addr);
190         if (ret < 0)
191                 goto out;
192         ret = send_bin_buffer(fd, buf, sizeof(buf));
193         if (ret < 0)
194                 goto out;
195         ret = recv_bin_buffer(fd, buf, sizeof(buf));
196         if (ret < 0)
197                 goto out;
198         if (ret != sizeof(int)) {
199                 ret = -E_RECV;
200                 goto out;
201         }
202         ret = *(int *) buf;
203         if (ret <= 0)
204                 goto out;
205         result_shmid = ret;
206         ret = shm_attach(result_shmid, ATTACH_RO, &result_shm);
207         if (ret >= 0) {
208                 assert(result);
209                 cr = result_shm;
210                 result->size = cr->result_size;
211                 result->data = para_malloc(result->size);
212                 memcpy(result->data, result_shm + sizeof(*cr), result->size);
213                 ret = shm_detach(result_shm);
214                 if (ret < 0)
215                         PARA_ERROR_LOG("can not detach result\n");
216         } else
217                 PARA_ERROR_LOG("attach result failed: %d\n", ret);
218         if (shm_destroy(result_shmid) < 0)
219                 PARA_ERROR_LOG("destroy result failed\n");
220         ret = 1;
221 out:
222         if (shm_destroy(query_shmid) < 0)
223                 PARA_ERROR_LOG("%s\n", "shm destroy error");
224         if (fd >= 0)
225                 close(fd);
226 //      PARA_DEBUG_LOG("callback_ret: %d\n", ret);
227         return ret;
228 }
229
230 /**
231  * Send a callback request passing an options structure and an argument vector.
232  *
233  * \param options pointer to an arbitrary data structure.
234  * \param argc Argument count.
235  * \param argv Standard argument vector.
236  * \param f The callback function.
237  * \param result The result of the query is stored here.
238  *
239  * Some commands have a couple of options that are parsed in child context for
240  * syntactic correctness and are stored in a special options structure for that
241  * command. This function allows to pass such a structure together with a list
242  * of further arguments (often a list of audio files) to the parent process.
243  *
244  * \sa send_standard_callback_request(), send_callback_request().
245  */
246 int send_option_arg_callback_request(struct osl_object *options,
247                 int argc,  char * const * const argv, callback_function *f,
248                 struct osl_object *result)
249 {
250         char *p;
251         int i, ret;
252         struct osl_object query = {.size = options? options->size : 0};
253
254         for (i = 0; i < argc; i++)
255                 query.size += strlen(argv[i]) + 1;
256         query.data = para_malloc(query.size);
257         p = query.data;
258         if (options) {
259                 memcpy(query.data, options->data, options->size);
260                 p += options->size;
261         }
262         for (i = 0; i < argc; i++) {
263                 strcpy(p, argv[i]); /* OK */
264                 p += strlen(argv[i]) + 1;
265         }
266         ret = send_callback_request(f, &query, result);
267         free(query.data);
268         return ret;
269 }
270
271 /**
272  * Send a callback request with an argument vector only.
273  *
274  * \param argc The same meaning as in send_option_arg_callback_request().
275  * \param argv The same meaning as in send_option_arg_callback_request().
276  * \param f The same meaning as in send_option_arg_callback_request().
277  * \param result The same meaning as in send_option_arg_callback_request().
278  *
279  * This is similar to send_option_arg_callback_request(), but no options buffer
280  * is passed to the parent process.
281  *
282  * \return The return value of the underlying call to
283  * send_option_arg_callback_request().
284  */
285 int send_standard_callback_request(int argc,  char * const * const argv,
286                 callback_function *f, struct osl_object *result)
287 {
288         return send_option_arg_callback_request(NULL, argc, argv, f, result);
289 }
290
291 static int action_if_pattern_matches(struct osl_row *row, void *data)
292 {
293         struct pattern_match_data *pmd = data;
294         struct osl_object name_obj;
295         const char *p, *name;
296         int ret = osl_get_object(pmd->table, row, pmd->match_col_num, &name_obj);
297         const char *pattern_txt = (const char *)pmd->patterns.data;
298
299         if (ret < 0)
300                 return ret;
301         name = (char *)name_obj.data;
302         if ((!name || !*name) && (pmd->pm_flags & PM_SKIP_EMPTY_NAME))
303                 return 1;
304         if (!pmd->patterns.size && (pmd->pm_flags & PM_NO_PATTERN_MATCHES_EVERYTHING))
305                 return pmd->action(pmd->table, row, name, pmd->data);
306         for (p = pattern_txt; p < pattern_txt + pmd->patterns.size;
307                         p += strlen(p) + 1) {
308                 ret = fnmatch(p, name, pmd->fnmatch_flags);
309                 if (ret == FNM_NOMATCH)
310                         continue;
311                 if (ret)
312                         return -E_FNMATCH;
313                 return pmd->action(pmd->table, row, name, pmd->data);
314         }
315         return 1;
316 }
317
318 /**
319  * Execute the given function for each matching row.
320  *
321  * \param pmd Describes what to match and how.
322  *
323  * \return The return value of the underlying call to osl_rbtree_loop()
324  * or osl_rbtree_loop_reverse().
325  */
326 int for_each_matching_row(struct pattern_match_data *pmd)
327 {
328         if (pmd->pm_flags & PM_REVERSE_LOOP)
329                 return osl_rbtree_loop_reverse(pmd->table, pmd->loop_col_num, pmd,
330                         action_if_pattern_matches);
331         return osl_rbtree_loop(pmd->table, pmd->loop_col_num, pmd,
332                         action_if_pattern_matches);
333 }
334
335 /**
336  * Compare two osl objects of string type.
337  *
338  * \param obj1 Pointer to the first object.
339  * \param obj2 Pointer to the second object.
340  *
341  * In any case, only \p MIN(obj1->size, obj2->size) characters of each string
342  * are taken into account.
343  *
344  * \return It returns an integer less than, equal to, or greater than zero if
345  * \a obj1 is found, respectively, to be less than, to match, or be greater than
346  * obj2.
347  *
348  * \sa strcmp(3), strncmp(3), osl_compare_func.
349  */
350 int string_compare(const struct osl_object *obj1, const struct osl_object *obj2)
351 {
352         const char *str1 = (const char *)obj1->data;
353         const char *str2 = (const char *)obj2->data;
354         return strncmp(str1, str2, PARA_MIN(obj1->size, obj2->size));
355 }
356
357 /*
358  * write input from fd to dynamically allocated buffer,
359  * but maximal max_size byte.
360  */
361 static int fd2buf(int fd, unsigned max_size, struct osl_object *obj)
362 {
363         const size_t chunk_size = 1024;
364         size_t size = 2048, received = 0;
365         int ret;
366         char *buf = para_malloc(size);
367
368         for (;;) {
369                 ret = recv_bin_buffer(fd, buf + received, chunk_size);
370                 if (ret <= 0)
371                         break;
372                 received += ret;
373                 if (received + chunk_size >= size) {
374                         size *= 2;
375                         ret = -E_INPUT_TOO_LARGE;
376                         if (size > max_size)
377                                 break;
378                         buf = para_realloc(buf, size);
379                 }
380         }
381         obj->data = buf;
382         obj->size = received;
383         if (ret < 0)
384                 free(buf);
385         return ret;
386 }
387
388 /**
389  * Read data from a file descriptor, and send it to the afs process.
390  *
391  * \param fd File descriptor to read data from.
392  * \param arg_obj Pointer to the arguments to \a f.
393  * \param f The callback function.
394  * \param max_len Don't read more than that many bytes from stdin.
395  * \param result The result of the query is stored here.
396  *
397  * This function is used by commands that wish to let para_server store
398  * arbitrary data specified by the user (for instance the add_blob family of
399  * commands). First, at most \a max_len bytes are read from \a fd, the result
400  * is concatenated with the buffer given by \a arg_obj, and the combined buffer
401  * is made available to the parent process via shared memory.
402  *
403  * \return Negative on errors, the return value of the underlying call to
404  * send_callback_request() otherwise.
405  */
406 int stdin_command(int fd, struct osl_object *arg_obj, callback_function *f,
407                 unsigned max_len, struct osl_object *result)
408 {
409         struct osl_object query, stdin_obj;
410         int ret;
411
412         ret = send_buffer(fd, AWAITING_DATA_MSG);
413         if (ret < 0)
414                 return ret;
415         ret = fd2buf(fd, max_len, &stdin_obj);
416         if (ret < 0)
417                 return ret;
418         query.size = arg_obj->size + stdin_obj.size;
419         query.data = para_malloc(query.size);
420         memcpy(query.data, arg_obj->data, arg_obj->size);
421         memcpy((char *)query.data + arg_obj->size, stdin_obj.data, stdin_obj.size);
422         free(stdin_obj.data);
423         ret = send_callback_request(f, &query, result);
424         free(query.data);
425         return ret;
426 }
427
428 /**
429  * Open the audio file with highest score.
430  *
431  * \param afd Audio file data is returned here.
432  *
433  * This stores all information for streaming the "best" audio file
434  * in the \a afd structure.
435  *
436  * \return Positive on success, negative on errors.
437  *
438  * \sa close_audio_file(), open_and_update_audio_file().
439  */
440 int open_next_audio_file(struct audio_file_data *afd)
441 {
442         struct osl_row *aft_row;
443         int ret;
444         for (;;) {
445                 ret = score_get_best(&aft_row, &afd->score);
446                 if (ret < 0)
447                         return ret;
448                 ret = open_and_update_audio_file(aft_row, afd);
449                 if (ret >= 0)
450                         return ret;
451         }
452 }
453
454 /**
455  * Free all resources which were allocated by open_next_audio_file().
456  *
457  * \param afd The structure previously filled in by open_next_audio_file().
458  *
459  * \return The return value of the underlying call to para_munmap().
460  *
461  * \sa open_next_audio_file().
462  */
463 int close_audio_file(struct audio_file_data *afd)
464 {
465         free(afd->afhi.chunk_table);
466         return para_munmap(afd->map.data, afd->map.size);
467 }
468
469 static enum play_mode init_admissible_files(void)
470 {
471         int ret = 0;
472         char *arg = conf.afs_initial_mode_arg;
473
474         if (conf.afs_initial_mode_given) {
475                 if (!strncmp(arg, "p:", 2)) {
476                         ret = playlist_open(arg + 2);
477                         if (ret >= 0)
478                                 return PLAY_MODE_PLAYLIST;
479                         goto dummy;
480                 }
481                 if (!strncmp(arg, "m:", 2)) {
482                         ret = change_current_mood(arg + 2);
483                         if (ret >= 0)
484                                 return PLAY_MODE_MOOD;
485                         goto dummy;
486                 }
487                 PARA_ERROR_LOG("bad afs initial mode arg: %s\n", arg);
488         }
489 dummy:
490         if (ret < 0)
491                 PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));
492         PARA_NOTICE_LOG("defaulting to dummy mood\n");
493         change_current_mood(""); /* always successful */
494         return PLAY_MODE_MOOD;
495 }
496
497 static int setup_command_socket_or_die(void)
498 {
499         int ret;
500         char *socket_name = conf.afs_socket_arg;
501         struct sockaddr_un unix_addr;
502
503         unlink(socket_name);
504         ret = create_local_socket(socket_name, &unix_addr,
505                 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IWOTH);
506         if (ret < 0) {
507                 PARA_EMERG_LOG("%s: %s\n", PARA_STRERROR(-ret), socket_name);
508                 exit(EXIT_FAILURE);
509         }
510         if (listen(ret , 5) < 0) {
511                 PARA_EMERG_LOG("%s", "can not listen on socket\n");
512                 exit(EXIT_FAILURE);
513         }
514         PARA_INFO_LOG("listening on command socket %s (fd %d)\n", socket_name,
515                 ret);
516         return ret;
517 }
518
519 static void close_afs_tables(void)
520 {
521         int i;
522         PARA_NOTICE_LOG("closing afs_tables\n");
523         for (i = 0; i < NUM_AFS_TABLES; i++)
524                 afs_tables[i].close();
525 }
526
527 static char *database_dir;
528
529 static void get_database_dir(void)
530 {
531         if (!database_dir) {
532                 if (conf.afs_database_dir_given)
533                         database_dir = para_strdup(conf.afs_database_dir_arg);
534                 else {
535                         char *home = para_homedir();
536                         database_dir = make_message(
537                                 "%s/.paraslash/afs_database", home);
538                         free(home);
539                 }
540         }
541         PARA_INFO_LOG("afs_database dir %s\n", database_dir);
542 }
543
544 static int make_database_dir(void)
545 {
546         int ret;
547
548         get_database_dir();
549         ret = para_mkdir(database_dir, 0777);
550         if (ret >= 0 || is_errno(-ret, EEXIST))
551                 return 1;
552         return ret;
553 }
554
555 static int open_afs_tables(void)
556 {
557         int i, ret;
558
559         get_database_dir();
560         for (i = 0; i < NUM_AFS_TABLES; i++) {
561                 ret = afs_tables[i].open(database_dir);
562                 if (ret >= 0)
563                         continue;
564                 PARA_ERROR_LOG("%s init: %s\n", afs_tables[i].name,
565                         PARA_STRERROR(-ret));
566         }
567         if (ret >= 0)
568                 return ret;
569         do
570                 afs_tables[i].close();
571         while (i--);
572         return ret;
573 }
574
575 static int server_socket;
576 static struct command_task command_task_struct;
577 static struct signal_task signal_task_struct;
578
579 static void unregister_tasks(void)
580 {
581         unregister_task(&command_task_struct.task);
582         unregister_task(&signal_task_struct.task);
583 }
584
585 static void signal_pre_select(struct sched *s, struct task *t)
586 {
587         struct signal_task *st = t->private_data;
588         t->ret = 1;
589         para_fd_set(st->fd, &s->rfds, &s->max_fileno);
590 }
591
592 static void signal_post_select(struct sched *s, struct task *t)
593 {
594         struct signal_task *st = t->private_data;
595         t->ret = 1;
596         if (!FD_ISSET(st->fd, &s->rfds))
597                 return;
598         st->signum = para_next_signal();
599         t->ret = 1;
600         if (st->signum == SIGUSR1)
601                 return; /* ignore SIGUSR1 */
602         if (st->signum == SIGHUP) {
603                 close_afs_tables();
604                 t->ret = open_afs_tables();
605                 return;
606         }
607         PARA_NOTICE_LOG("caught signal %d\n", st->signum);
608         t->ret = -E_AFS_SIGNAL;
609         unregister_tasks();
610 }
611
612 static void register_signal_task(void)
613 {
614         struct signal_task *st = &signal_task_struct;
615         st->fd = para_signal_init();
616         PARA_INFO_LOG("signal pipe: fd %d\n", st->fd);
617         para_install_sighandler(SIGINT);
618         para_install_sighandler(SIGTERM);
619         para_install_sighandler(SIGPIPE);
620         para_install_sighandler(SIGHUP);
621
622         st->task.pre_select = signal_pre_select;
623         st->task.post_select = signal_post_select;
624         st->task.private_data = st;
625         sprintf(st->task.status, "signal task");
626         register_task(&st->task);
627 }
628
629 static struct list_head afs_client_list;
630
631 struct afs_client {
632         struct list_head node;
633         int fd;
634         struct timeval connect_time;
635 };
636
637 static void command_pre_select(struct sched *s, struct task *t)
638 {
639         struct command_task *ct = t->private_data;
640         struct afs_client *client;
641
642         para_fd_set(ct->fd, &s->rfds, &s->max_fileno);
643         list_for_each_entry(client, &afs_client_list, node)
644                 para_fd_set(client->fd, &s->rfds, &s->max_fileno);
645         t->ret = 1;
646 }
647
648 /*
649  * On errors, negative value is written to fd.
650  * On success: If query produced a result, the result_shmid is written to fd.
651  * Otherwise, zero is written.
652  */
653 static int call_callback(int fd, int query_shmid)
654 {
655         void *query_shm, *result_shm;
656         struct callback_query *cq;
657         struct callback_result *cr;
658         struct osl_object query, result = {.data = NULL};
659         int result_shmid = -1, ret, ret2;
660
661         ret = shm_attach(query_shmid, ATTACH_RW, &query_shm);
662         if (ret < 0)
663                 goto out;
664         cq = query_shm;
665         query.data = (char *)query_shm + sizeof(*cq);
666         query.size = cq->query_size;
667         ret = cq->handler(&query, &result);
668         ret2 = shm_detach(query_shm);
669         if (ret2 < 0 && ret >= 0)
670                 ret = ret2;
671         if (ret < 0)
672                 goto out;
673         ret = 0;
674         if (!result.data || !result.size)
675                 goto out;
676         ret = shm_new(result.size + sizeof(struct callback_result));
677         if (ret < 0)
678                 goto out;
679         result_shmid = ret;
680         ret = shm_attach(result_shmid, ATTACH_RW, &result_shm);
681         if (ret < 0)
682                 goto out;
683         cr = result_shm;
684         cr->result_size = result.size;
685         memcpy(result_shm + sizeof(*cr), result.data, result.size);
686         ret = shm_detach(result_shm);
687         if (ret < 0)
688                 goto out;
689         ret = result_shmid;
690 out:
691         free(result.data);
692         ret2 = send_bin_buffer(fd, (char *)&ret, sizeof(int));
693         if (ret < 0 || ret2 < 0) {
694                 if (result_shmid >= 0)
695                         if (shm_destroy(result_shmid) < 0)
696                                 PARA_ERROR_LOG("destroy result failed\n");
697                 if (ret >= 0)
698                         ret = ret2;
699         }
700         return ret;
701 }
702
703 static void execute_afs_command(int fd, uint32_t expected_cookie)
704 {
705         uint32_t cookie;
706         int query_shmid;
707         char buf[sizeof(cookie) + sizeof(query_shmid)];
708         int ret = recv_bin_buffer(fd, buf, sizeof(buf));
709
710         if (ret < 0) {
711                 PARA_NOTICE_LOG("%s\n", PARA_STRERROR(-ret));
712                 return;
713         }
714         if (ret != sizeof(buf)) {
715                 PARA_NOTICE_LOG("short read (%d bytes, expected %lu)\n",
716                         ret, (long unsigned) sizeof(buf));
717                 return;
718         }
719         cookie = *(uint32_t *)buf;
720         if (cookie != expected_cookie) {
721                 PARA_NOTICE_LOG("received invalid cookie(got %u, expected %u)\n",
722                         (unsigned)cookie, (unsigned)expected_cookie);
723                 return;
724         }
725         query_shmid = *(int *)(buf + sizeof(cookie));
726         if (query_shmid < 0) {
727                 PARA_WARNING_LOG("received invalid query shmid %d)\n",
728                         query_shmid);
729                 return;
730         }
731         /* Ignore return value: Errors might be OK here. */
732         call_callback(fd, query_shmid);
733 }
734
735 /** Shutdown connection if query has not arrived until this many seconds. */
736 #define AFS_CLIENT_TIMEOUT 3
737
738 static void command_post_select(struct sched *s, struct task *t)
739 {
740         struct command_task *ct = t->private_data;
741         struct sockaddr_un unix_addr;
742         struct afs_client *client, *tmp;
743
744         /* First, check the list of connected clients. */
745         list_for_each_entry_safe(client, tmp, &afs_client_list, node) {
746                 if (FD_ISSET(client->fd, &s->rfds))
747                         execute_afs_command(client->fd, ct->cookie);
748                 else { /* prevent bogus connection flooding */
749                         struct timeval diff;
750                         tv_diff(now, &client->connect_time, &diff);
751                         if (diff.tv_sec < AFS_CLIENT_TIMEOUT)
752                                 continue;
753                         PARA_WARNING_LOG("connection timeout\n");
754                 }
755                 close(client->fd);
756                 list_del(&client->node);
757                 free(client);
758         }
759         /* Next, accept connections on the local socket. */
760         if (!FD_ISSET(ct->fd, &s->rfds))
761                 goto out;
762         t->ret = para_accept(ct->fd, &unix_addr, sizeof(unix_addr));
763         if (t->ret < 0) {
764                 PARA_NOTICE_LOG("%s\n", PARA_STRERROR(-t->ret));
765                 goto out;
766         }
767         client = para_malloc(sizeof(*client));
768         client->fd = t->ret;
769         client->connect_time = *now;
770         para_list_add(&client->node, &afs_client_list);
771 out:
772         t->ret = 1;
773 }
774
775 static void register_command_task(uint32_t cookie)
776 {
777         struct command_task *ct = &command_task_struct;
778         ct->fd = setup_command_socket_or_die();
779         ct->cookie = cookie;
780
781         ct->task.pre_select = command_pre_select;
782         ct->task.post_select = command_post_select;
783         ct->task.private_data = ct;
784         sprintf(ct->task.status, "command task");
785         register_task(&ct->task);
786 }
787
788 static void register_tasks(uint32_t cookie)
789 {
790         register_signal_task();
791         register_command_task(cookie);
792 }
793
794 /**
795  * Initialize the audio file selector process.
796  *
797  * \param cookie The value used for "authentication".
798  * \param socket_fd File descriptor used for communication with the server.
799  */
800 __noreturn void afs_init(uint32_t cookie, int socket_fd)
801 {
802         enum play_mode current_play_mode;
803         struct sched s;
804         int i, ret;
805
806         INIT_LIST_HEAD(&afs_client_list);
807         for (i = 0; i < NUM_AFS_TABLES; i++)
808                 afs_tables[i].init(&afs_tables[i]);
809         ret = open_afs_tables();
810
811         if (ret < 0) {
812                 PARA_EMERG_LOG("%s\n", PARA_STRERROR(-ret));
813                 exit(EXIT_FAILURE);
814         }
815         server_socket = socket_fd;
816         ret = mark_fd_nonblock(server_socket);
817         if (ret < 0)
818                 exit(EXIT_FAILURE);
819         PARA_INFO_LOG("server_socket: %d, afs_socket_cookie: %u\n",
820                 server_socket, (unsigned) cookie);
821         current_play_mode = init_admissible_files();
822         register_tasks(cookie);
823         s.default_timeout.tv_sec = 0;
824         s.default_timeout.tv_usec = 99 * 1000;
825         ret = sched(&s);
826         if (ret < 0)
827                 PARA_EMERG_LOG("%s\n", PARA_STRERROR(-ret));
828         close_afs_tables();
829         exit(EXIT_FAILURE);
830 }
831
832 static int create_tables_callback(const struct osl_object *query,
833                 __a_unused struct osl_object *result)
834 {
835         uint32_t table_mask = *(uint32_t *)query->data;
836         int i, ret;
837
838         close_afs_tables();
839         for (i = 0; i < NUM_AFS_TABLES; i++) {
840                 struct afs_table *t = &afs_tables[i];
841
842                 if (!(table_mask & (1 << i)))
843                         continue;
844                 if (!t->create)
845                         continue;
846                 ret = t->create(database_dir);
847                 if (ret < 0)
848                         return ret;
849         }
850         ret = open_afs_tables();
851         return ret < 0? ret: 0;
852 }
853
854 int com_init(int fd, int argc, char * const * const argv)
855 {
856         int i, j, ret;
857         uint32_t table_mask = (1 << (NUM_AFS_TABLES + 1)) - 1;
858         struct osl_object query = {.data = &table_mask,
859                 .size = sizeof(table_mask)};
860
861         ret = make_database_dir();
862         if (ret < 0)
863                 return ret;
864         if (argc != 1) {
865                 table_mask = 0;
866                 for (i = 1; i < argc; i++) {
867                         for (j = 0; j < NUM_AFS_TABLES; j++) {
868                                 struct afs_table *t = &afs_tables[j];
869
870                                 if (strcmp(argv[i], t->name))
871                                         continue;
872                                 table_mask |= (1 << j);
873                                 break;
874                         }
875                         if (j == NUM_AFS_TABLES)
876                                 return -E_BAD_TABLE_NAME;
877                 }
878         }
879         ret = send_callback_request(create_tables_callback, &query, NULL);
880         if (ret < 0)
881                 return ret;
882         return send_va_buffer(fd, "successfully created afs table(s)\n");
883 }
884
885 /**
886  * Flags for the check command.
887  *
888  * \sa com_check().
889  */
890 enum com_check_flags {
891         /** Check the audio file table. */
892         CHECK_AFT = 1,
893         /** Check the mood table. */
894         CHECK_MOODS = 2,
895         /** Check the playlist table. */
896         CHECK_PLAYLISTS = 4
897 };
898
899 int com_check(int fd, int argc, char * const * const argv)
900 {
901         unsigned flags = 0;
902         int i, ret;
903         struct osl_object result;
904
905         for (i = 1; i < argc; i++) {
906                 const char *arg = argv[i];
907                 if (arg[0] != '-')
908                         break;
909                 if (!strcmp(arg, "--")) {
910                         i++;
911                         break;
912                 }
913                 if (!strcmp(arg, "-a")) {
914                         flags |= CHECK_AFT;
915                         continue;
916                 }
917                 if (!strcmp(arg, "-p")) {
918                         flags |= CHECK_PLAYLISTS;
919                         continue;
920                 }
921                 if (!strcmp(arg, "-m")) {
922                         flags |= CHECK_MOODS;
923                         continue;
924                 }
925                 return -E_AFS_SYNTAX;
926         }
927         if (i < argc)
928                 return -E_AFS_SYNTAX;
929         if (!flags)
930                 flags = ~0U;
931         if (flags & CHECK_AFT) {
932                 ret = send_callback_request(aft_check_callback, NULL, &result);
933                 if (ret < 0)
934                         return ret;
935                 if (ret > 0) {
936                         ret = send_buffer(fd, (char *) result.data);
937                         free(result.data);
938                         if (ret < 0)
939                                 return ret;
940                 }
941         }
942         if (flags & CHECK_PLAYLISTS) {
943                 ret = send_callback_request(playlist_check_callback, NULL, &result);
944                 if (ret < 0)
945                         return ret;
946                 if (ret > 0) {
947                         ret = send_buffer(fd, (char *) result.data);
948                         free(result.data);
949                         if (ret < 0)
950                                 return ret;
951                 }
952         }
953         if (flags & CHECK_MOODS) {
954                 ret = send_callback_request(mood_check_callback, NULL, &result);
955                 if (ret < 0)
956                         return ret;
957                 if (ret > 0) {
958                         ret = send_buffer(fd, (char *) result.data);
959                         free(result.data);
960                         if (ret < 0)
961                                 return ret;
962                 }
963         }
964         return 1;
965 }
966
967 void afs_event(enum afs_events event, struct para_buffer *pb,
968                 void *data)
969 {
970         int i, ret;
971
972         for (i = 0; i < NUM_AFS_TABLES; i++) {
973                 struct afs_table *t = &afs_tables[i];
974                 if (!t->event_handler)
975                         continue;
976                 ret = t->event_handler(event, pb, data);
977                 if (ret < 0)
978                         PARA_CRIT_LOG("%s\n", PARA_STRERROR(-ret));
979         }
980 }
981
982 int images_event_handler(__a_unused enum afs_events event,
983         __a_unused  struct para_buffer *pb, __a_unused void *data)
984 {
985         return 1;
986 }
987
988 int lyrics_event_handler(__a_unused enum afs_events event,
989         __a_unused struct para_buffer *pb, __a_unused void *data)
990 {
991         return 1;
992 }