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