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