Merge commit 'remotes/fml/master'
[paraslash.git] / afs.c
diff --git a/afs.c b/afs.c
index f5de6609e4f9c87058676068f3172888106393b9..bc42026e460ac7ba5f38f992ae17e1f18a3c5ce9 100644 (file)
--- a/afs.c
+++ b/afs.c
 /*
- * Copyright (C) 2005-2007 Andre Noll <maan@systemlinux.org>
+ * Copyright (C) 2007-2008 Andre Noll <maan@systemlinux.org>
  *
- *     This program is free software; you can redistribute it and/or modify
- *     it under the terms of the GNU General Public License as published by
- *     the Free Software Foundation; either version 2 of the License, or
- *     (at your option) any later version.
- *
- *     This program is distributed in the hope that it will be useful,
- *     but WITHOUT ANY WARRANTY; without even the implied warranty of
- *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- *     GNU General Public License for more details.
- *
- *     You should have received a copy of the GNU General Public License
- *     along with this program; if not, write to the Free Software
- *     Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111, USA.
+ * Licensed under the GPL v2. For licencing details see COPYING.
  */
 
+/** \file afs.c Paraslash's audio file selector. */
 
-/** \file afs.c functions common to all audio file selectors */
-
+#include <signal.h>
+#include <fnmatch.h>
 #include "server.cmdline.h"
-#include "server.h"
-#include "vss.h"
-#include <dirent.h> /* readdir() */
-#include <sys/stat.h> /* stat */
-#include <sys/types.h> /* mode_t */
+#include "para.h"
 #include "error.h"
 #include "string.h"
+#include "afh.h"
+#include "afs.h"
+#include "server.h"
+#include <dirent.h> /* readdir() */
+#include <sys/mman.h>
+#include <sys/time.h>
+#include "net.h"
+#include "ipc.h"
+#include "list.h"
+#include "sched.h"
+#include "signal.h"
+#include "fd.h"
+
+/** The osl tables used by afs. \sa blob.c. */
+enum afs_table_num {
+       /** Contains audio file information. See aft.c. */
+       TBLNUM_AUDIO_FILES,
+       /** The table for the paraslash attributes. See attribute.c. */
+       TBLNUM_ATTRIBUTES,
+       /**
+        * Paraslash's scoring system is based on Gaussian normal
+        * distributions, and the relevant data is stored in the rbtrees of an
+        * osl table containing only volatile columns.  See score.c for
+        * details.
+        */
+       TBLNUM_SCORES,
+       /**
+        * A standard blob table containing the mood definitions. For details
+        * see mood.c.
+        */
+       TBLNUM_MOODS,
+       /** A blob table containing lyrics on a per-song basis. */
+       TBLNUM_LYRICS,
+       /** Another blob table for images (for example album cover art). */
+       TBLNUM_IMAGES,
+       /** Yet another blob table for storing standard playlists. */
+       TBLNUM_PLAYLIST,
+       /** How many tables are in use? */
+       NUM_AFS_TABLES
+};
+
+static struct afs_table afs_tables[NUM_AFS_TABLES] = {
+       [TBLNUM_AUDIO_FILES] = {.init = aft_init},
+       [TBLNUM_ATTRIBUTES] = {.init = attribute_init},
+       [TBLNUM_SCORES] = {.init = score_init},
+       [TBLNUM_MOODS] = {.init = moods_init},
+       [TBLNUM_LYRICS] = {.init = lyrics_init},
+       [TBLNUM_IMAGES] = {.init = images_init},
+       [TBLNUM_PLAYLIST] = {.init = playlists_init},
+};
+
+struct command_task {
+       /** The file descriptor for the local socket. */
+       int fd;
+       /**
+        * Value sent by the command handlers to identify themselves as
+        * children of the running para_server.
+        */
+       uint32_t cookie;
+       /** The associated task structure. */
+       struct task task;
+};
+
+extern struct misc_meta_data *mmd;
+
+static int server_socket;
+static struct command_task command_task_struct;
+static struct signal_task signal_task_struct;
+
+static enum play_mode current_play_mode;
+static char *current_mop; /* mode or playlist specifier. NULL means dummy mooe */
+
+
+/**
+ * A random number used to "authenticate" the connection.
+ *
+ * para_server picks this number by random before forking the afs process.  The
+ * command handlers write this number together with the id of the shared memory
+ * area containing the query. This way, a malicious local user has to know this
+ * number to be able to cause the afs process to crash by sending fake queries.
+ */
+extern uint32_t afs_socket_cookie;
 
 /**
- * traverse the given directory recursively
+ * Struct to let command handlers execute a callback in afs context.
  *
- * @param dirname the directory to traverse
- * @param f: the function to call for each entry.
+ * Commands that need to change the state of afs can't change the relevant data
+ * structures directly because commands are executed in a child process, i.e.
+ * they get their own virtual address space.
  *
- * for each regular file whose filename ends in .yyy, where yyy is a supported
- * audio format, the supplied function \a f is called.  The directory and
- * filename component of the regular file are passed to \a f.
+ * This structure is used by \p send_callback_request() (executed from handler
+ * context) in order to let the afs process call the specified function. An
+ * instance of that structure is written to a shared memory area together with
+ * the arguments to the callback function. The identifier of the shared memory
+ * area is written to the command socket.
  *
- * \return On success, 1 is returned. Otherwise, this function returns a
- * negative value which indicates the kind of the error.
+ * The afs process accepts connections on the command socket and reads the
+ * shared memory id, attaches the corresponing area, calls the given handler to
+ * perform the desired action and to optionally compute a result.
+ *
+ * The result and a \p callback_result structure is then written to another
+ * shared memory area. The identifier for that area is written to the handler's
+ * command socket, so that the handler process can read the id, attach the
+ * shared memory area and use the result.
+ *
+ * \sa struct callback_result.
  */
-int find_audio_files(const char *dirname, int (*f)(const char *, const char *))
+struct callback_query {
+       /** The function to be called. */
+       callback_function *handler;
+       /** The number of bytes of the query */
+       size_t query_size;
+};
+
+/**
+ * Structure embedded in the result of a callback.
+ *
+ * If the callback produced a result, an instance of that structure is embeeded
+ * into the shared memory area holding the result, mainly to let the command
+ * handler know the size of the result.
+ *
+ * \sa struct callback_query.
+ */
+struct callback_result {
+       /** The number of bytes of the result. */
+       size_t result_size;
+};
+
+/**
+ * Ask the afs process to call a given function.
+ *
+ * \param f The function to be called.
+ * \param query Pointer to arbitrary data for the callback.
+ * \param result_handler Called for each shm area sent by the callback.
+ * \param private_result_data Passed verbatim to \a result_handler.
+ *
+ * This function creates a socket for communication with the afs process and a
+ * shared memory area (sma) to which the buffer pointed to by \a query is
+ * copied.  It then notifies the afs process that the callback function \a f
+ * should be executed by sending the shared memory identifier (shmid) to the
+ * socket.
+
+ * If the callback produces a result, it sends any number of shared memory
+ * identifiers back via the socket. For each such identifier received, \a
+ * result_handler is called. The contents of the sma identified by the received
+ * shmid are passed to that function as an osl object. The private_result_data
+ * pointer is passed as the second argument to \a result_handler.
+ *
+ * \return Negative, on errors, the return value of the callback function
+ * otherwise.
+ *
+ * \sa send_option_arg_callback_request(), send_standard_callback_request().
+ */
+int send_callback_request(callback_function *f, struct osl_object *query,
+               callback_result_handler *result_handler,
+               void *private_result_data)
 {
-       DIR *dir = NULL;
-       struct dirent *entry;
-       /*
-        * Opening the current directory (".") and calling fchdir() to return
-        * is usually faster and more reliable than saving cwd in some buffer
-        * and calling chdir() afterwards (see man 3 getcwd).
-        */
-       int cwd_fd = open(".", O_RDONLY);
-       struct stat s;
-       int ret = -1;
-
-//     PARA_DEBUG_LOG("dirname: %s\n", dirname);
-       if (cwd_fd < 0)
-               return -E_GETCWD;
-       ret = -E_CHDIR;
-       if (chdir(dirname) < 0)
+       struct callback_query *cq;
+       int num_results = 0, ret, fd = -1, query_shmid, result_shmid;
+       void *query_shm, *result_shm;
+       char buf[sizeof(afs_socket_cookie) + sizeof(int)];
+       size_t query_shm_size = sizeof(*cq);
+
+       if (query)
+               query_shm_size += query->size;
+       ret = shm_new(query_shm_size);
+       if (ret < 0)
+               return ret;
+       query_shmid = ret;
+       ret = shm_attach(query_shmid, ATTACH_RW, &query_shm);
+       if (ret < 0)
+               goto out;
+       cq = query_shm;
+       cq->handler = f;
+       cq->query_size = query_shm_size - sizeof(*cq);
+
+       if (query)
+               memcpy(query_shm + sizeof(*cq), query->data, query->size);
+       ret = shm_detach(query_shm);
+       if (ret < 0)
+               goto out;
+
+       *(uint32_t *) buf = afs_socket_cookie;
+       *(int *) (buf + sizeof(afs_socket_cookie)) = query_shmid;
+
+       ret = create_remote_socket(conf.afs_socket_arg);
+       if (ret < 0)
                goto out;
-       ret = -E_OPENDIR;
-       dir = opendir(".");
-       if (!dir)
+       fd = ret;
+       ret = send_bin_buffer(fd, buf, sizeof(buf));
+       if (ret < 0)
                goto out;
-       /* scan cwd recursively */
-       while ((entry = readdir(dir))) {
-               mode_t m;
-               char *tmp;
+       for (;;) {
+               ret = recv_bin_buffer(fd, buf, sizeof(int));
+               if (ret <= 0)
+                       goto out;
+               if (ret != sizeof(int)) {
+                       ret = -E_AFS_SHORT_READ;
+                       goto out;
+               }
+               ret = *(int *) buf;
+               if (ret <= 0)
+                       goto out;
+               result_shmid = ret;
+               ret = shm_attach(result_shmid, ATTACH_RO, &result_shm);
+               if (ret >= 0) {
+                       struct callback_result *cr = result_shm;
+                       struct osl_object result;
+                       num_results++;
+                       result.size = cr->result_size;
+                       result.data = result_shm + sizeof(*cr);
+                       if (result.size) {
+                               assert(result_handler);
+                               ret = result_handler(&result, private_result_data);
+                               if (shm_detach(result_shm) < 0)
+                                       PARA_ERROR_LOG("can not detach result\n");
+                       }
+               } else
+                       PARA_ERROR_LOG("attach result failed: %d\n", ret);
+               if (shm_destroy(result_shmid) < 0)
+                       PARA_ERROR_LOG("destroy result failed\n");
+               if (ret < 0)
+                       break;
+       }
+out:
+       if (shm_destroy(query_shmid) < 0)
+               PARA_ERROR_LOG("%s\n", "shm destroy error");
+       if (fd >= 0)
+               close(fd);
+       if (ret >= 0)
+               ret = num_results;
+//     PARA_DEBUG_LOG("callback_ret: %d\n", ret);
+       return ret;
+}
 
-               if (!strcmp(entry->d_name, "."))
-                       continue;
-               if (!strcmp(entry->d_name, ".."))
-                       continue;
-               ret = -E_LSTAT;
-               if (lstat(entry->d_name, &s) == -1)
+/**
+ * Send a callback request passing an options structure and an argument vector.
+ *
+ * \param options pointer to an arbitrary data structure.
+ * \param argc Argument count.
+ * \param argv Standard argument vector.
+ * \param f The callback function.
+ * \param result_handler See \ref send_callback_request.
+ * \param private_result_data See \ref send_callback_request.
+ *
+ * Some commands have a couple of options that are parsed in child context for
+ * syntactic correctness and are stored in a special options structure for that
+ * command. This function allows to pass such a structure together with a list
+ * of further arguments (often a list of audio files) to the parent process.
+ *
+ * \sa send_standard_callback_request(), send_callback_request().
+ */
+int send_option_arg_callback_request(struct osl_object *options,
+               int argc,  char * const * const argv, callback_function *f,
+               callback_result_handler *result_handler,
+               void *private_result_data)
+{
+       char *p;
+       int i, ret;
+       struct osl_object query = {.size = options? options->size : 0};
+
+       for (i = 0; i < argc; i++)
+               query.size += strlen(argv[i]) + 1;
+       query.data = para_malloc(query.size);
+       p = query.data;
+       if (options) {
+               memcpy(query.data, options->data, options->size);
+               p += options->size;
+       }
+       for (i = 0; i < argc; i++) {
+               strcpy(p, argv[i]); /* OK */
+               p += strlen(argv[i]) + 1;
+       }
+       ret = send_callback_request(f, &query, result_handler,
+               private_result_data);
+       free(query.data);
+       return ret;
+}
+
+/**
+ * Send a callback request with an argument vector only.
+ *
+ * \param argc The same meaning as in send_option_arg_callback_request().
+ * \param argv The same meaning as in send_option_arg_callback_request().
+ * \param f The same meaning as in send_option_arg_callback_request().
+ * \param result_handler See \ref send_callback_request.
+ * \param private_result_data See \ref send_callback_request.
+ *
+ * This is similar to send_option_arg_callback_request(), but no options buffer
+ * is passed to the parent process.
+ *
+ * \return The return value of the underlying call to
+ * send_option_arg_callback_request().
+ */
+int send_standard_callback_request(int argc,  char * const * const argv,
+               callback_function *f, callback_result_handler *result_handler,
+               void *private_result_data)
+{
+       return send_option_arg_callback_request(NULL, argc, argv, f, result_handler,
+               private_result_data);
+}
+
+static int action_if_pattern_matches(struct osl_row *row, void *data)
+{
+       struct pattern_match_data *pmd = data;
+       struct osl_object name_obj;
+       const char *p, *name;
+       int ret = osl_get_object(pmd->table, row, pmd->match_col_num, &name_obj);
+       const char *pattern_txt = (const char *)pmd->patterns.data;
+
+       if (ret < 0)
+               return ret;
+       name = (char *)name_obj.data;
+       if ((!name || !*name) && (pmd->pm_flags & PM_SKIP_EMPTY_NAME))
+               return 1;
+       if (!pmd->patterns.size && (pmd->pm_flags & PM_NO_PATTERN_MATCHES_EVERYTHING))
+               return pmd->action(pmd->table, row, name, pmd->data);
+       for (p = pattern_txt; p < pattern_txt + pmd->patterns.size;
+                       p += strlen(p) + 1) {
+               ret = fnmatch(p, name, pmd->fnmatch_flags);
+               if (ret == FNM_NOMATCH)
                        continue;
-               m = s.st_mode;
-               if (!S_ISREG(m) && !S_ISDIR(m)) /* skip links, sockets, ... */
+               if (ret)
+                       return -E_FNMATCH;
+               return pmd->action(pmd->table, row, name, pmd->data);
+       }
+       return 1;
+}
+
+/**
+ * Execute the given function for each matching row.
+ *
+ * \param pmd Describes what to match and how.
+ *
+ * \return The return value of the underlying call to osl_rbtree_loop()
+ * or osl_rbtree_loop_reverse().
+ */
+int for_each_matching_row(struct pattern_match_data *pmd)
+{
+       if (pmd->pm_flags & PM_REVERSE_LOOP)
+               return osl_rbtree_loop_reverse(pmd->table, pmd->loop_col_num, pmd,
+                       action_if_pattern_matches);
+       return osl_rbtree_loop(pmd->table, pmd->loop_col_num, pmd,
+                       action_if_pattern_matches);
+}
+
+/**
+ * Compare two osl objects of string type.
+ *
+ * \param obj1 Pointer to the first object.
+ * \param obj2 Pointer to the second object.
+ *
+ * In any case, only \p MIN(obj1->size, obj2->size) characters of each string
+ * are taken into account.
+ *
+ * \return It returns an integer less than, equal to, or greater than zero if
+ * \a obj1 is found, respectively, to be less than, to match, or be greater than
+ * obj2.
+ *
+ * \sa strcmp(3), strncmp(3), osl_compare_func.
+ */
+int string_compare(const struct osl_object *obj1, const struct osl_object *obj2)
+{
+       const char *str1 = (const char *)obj1->data;
+       const char *str2 = (const char *)obj2->data;
+       return strncmp(str1, str2, PARA_MIN(obj1->size, obj2->size));
+}
+
+/*
+ * write input from fd to dynamically allocated buffer,
+ * but maximal max_size byte.
+ */
+static int fd2buf(int fd, unsigned max_size, struct osl_object *obj)
+{
+       const size_t chunk_size = 1024;
+       size_t size = 2048, received = 0;
+       int ret;
+       char *buf = para_malloc(size);
+
+       for (;;) {
+               ret = recv_bin_buffer(fd, buf + received, chunk_size);
+               if (ret <= 0)
+                       break;
+               received += ret;
+               if (received + chunk_size >= size) {
+                       size *= 2;
+                       ret = -E_INPUT_TOO_LARGE;
+                       if (size > max_size)
+                               break;
+                       buf = para_realloc(buf, size);
+               }
+       }
+       obj->data = buf;
+       obj->size = received;
+       if (ret < 0)
+               free(buf);
+       return ret;
+}
+
+/**
+ * Read data from a file descriptor, and send it to the afs process.
+ *
+ * \param fd File descriptor to read data from.
+ * \param arg_obj Pointer to the arguments to \a f.
+ * \param f The callback function.
+ * \param max_len Don't read more than that many bytes from stdin.
+ * \param result_handler See \ref send_callback_request.
+ * \param private_result_data See \ref send_callback_request.
+ *
+ * This function is used by commands that wish to let para_server store
+ * arbitrary data specified by the user (for instance the add_blob family of
+ * commands). First, at most \a max_len bytes are read from \a fd, the result
+ * is concatenated with the buffer given by \a arg_obj, and the combined buffer
+ * is made available to the afs process via the callback method. See \ref
+ * send_callback_request for details.
+ *
+ * \return Negative on errors, the return value of the underlying call to
+ * send_callback_request() otherwise.
+ */
+int stdin_command(int fd, struct osl_object *arg_obj, callback_function *f,
+               unsigned max_len, callback_result_handler *result_handler,
+               void *private_result_data)
+{
+       struct osl_object query, stdin_obj;
+       int ret;
+
+       ret = send_buffer(fd, AWAITING_DATA_MSG);
+       if (ret < 0)
+               return ret;
+       ret = fd2buf(fd, max_len, &stdin_obj);
+       if (ret < 0)
+               return ret;
+       query.size = arg_obj->size + stdin_obj.size;
+       query.data = para_malloc(query.size);
+       memcpy(query.data, arg_obj->data, arg_obj->size);
+       memcpy((char *)query.data + arg_obj->size, stdin_obj.data, stdin_obj.size);
+       free(stdin_obj.data);
+       ret = send_callback_request(f, &query, result_handler, private_result_data);
+       free(query.data);
+       return ret;
+}
+
+static int pass_afd(int fd, char *buf, size_t size)
+{
+       struct msghdr msg = {.msg_iov = NULL};
+       struct cmsghdr *cmsg;
+       char control[255];
+       int ret;
+       struct iovec iov;
+
+       iov.iov_base = buf;
+       iov.iov_len  = size;
+
+       msg.msg_iov = &iov;
+       msg.msg_iovlen = 1;
+
+       msg.msg_control = control;
+       msg.msg_controllen = sizeof(control);
+
+       cmsg = CMSG_FIRSTHDR(&msg);
+       cmsg->cmsg_level = SOL_SOCKET;
+       cmsg->cmsg_type = SCM_RIGHTS;
+       cmsg->cmsg_len = CMSG_LEN(sizeof(int));
+       *(int *)CMSG_DATA(cmsg) = fd;
+
+       /* Sum of the length of all control messages in the buffer */
+       msg.msg_controllen = cmsg->cmsg_len;
+       PARA_DEBUG_LOG("passing %zu bytes and fd %d\n", size, fd);
+       ret = sendmsg(server_socket, &msg, 0);
+       if (ret < 0) {
+               ret = -ERRNO_TO_PARA_ERROR(errno);
+               return ret;
+       }
+       return 1;
+}
+
+/**
+ * Open the audio file with highest score.
+ *
+ * This stores all information for streaming the "best" audio file in a shared
+ * memory area. The id of that area and an open file descriptor for the next
+ * audio file are passed to the server process.
+ *
+ * \return Standard.
+ *
+ * \sa open_and_update_audio_file().
+ */
+static int open_next_audio_file(void)
+{
+       struct osl_row *aft_row;
+       struct audio_file_data afd;
+       int ret, shmid;
+       char buf[8];
+       long score;
+again:
+       PARA_NOTICE_LOG("getting next audio file\n");
+       ret = score_get_best(&aft_row, &score);
+       if (ret < 0) {
+               PARA_ERROR_LOG("%s\n", para_strerror(-ret));
+               goto no_admissible_files;
+       }
+       ret = open_and_update_audio_file(aft_row, score, &afd);
+       if (ret < 0) {
+               PARA_ERROR_LOG("%s\n", para_strerror(-ret));
+               ret = score_delete(aft_row);
+               if (ret < 0) {
+                       PARA_ERROR_LOG("%s\n", para_strerror(-ret));
+                       goto no_admissible_files;
+               }
+               goto again;
+       }
+       shmid = ret;
+       if (!write_ok(server_socket)) {
+               ret = -E_AFS_SOCKET;
+               goto destroy;
+       }
+       *(uint32_t *)buf = NEXT_AUDIO_FILE;
+       *(uint32_t *)(buf + 4) = (uint32_t)shmid;
+       ret = pass_afd(afd.fd, buf, 8);
+       close(afd.fd);
+       if (ret >= 0)
+               return ret;
+destroy:
+       shm_destroy(shmid);
+       return ret;
+no_admissible_files:
+       *(uint32_t *)buf = NO_ADMISSIBLE_FILES;
+       *(uint32_t *)(buf + 4) = (uint32_t)0;
+       return send_bin_buffer(server_socket, buf, 8);
+}
+
+/* Never fails if arg == NULL */
+static int activate_mood_or_playlist(char *arg, int *num_admissible)
+{
+       enum play_mode mode;
+       int ret;
+
+       if (!arg) {
+               ret = change_current_mood(NULL); /* always successful */
+               mode = PLAY_MODE_MOOD;
+       } else {
+               if (!strncmp(arg, "p/", 2)) {
+                       ret = playlist_open(arg + 2);
+                       mode = PLAY_MODE_PLAYLIST;
+               } else if (!strncmp(arg, "m/", 2)) {
+                       ret = change_current_mood(arg + 2);
+                       mode = PLAY_MODE_MOOD;
+               } else
+                       return -E_AFS_SYNTAX;
+               if (ret < 0)
+                       return ret;
+       }
+       if (num_admissible)
+               *num_admissible = ret;
+       current_play_mode = mode;
+       if (arg != current_mop) {
+               free(current_mop);
+               if (arg) {
+                       current_mop = para_strdup(arg);
+                       mmd_lock();
+                       strncpy(mmd->afs_mode_string, arg,
+                               sizeof(mmd->afs_mode_string));
+                       mmd->afs_mode_string[sizeof(mmd->afs_mode_string) - 1] = '\0';
+                       mmd_unlock();
+               } else {
+                       mmd_lock();
+                       strcpy(mmd->afs_mode_string, "dummy");
+                       mmd_unlock();
+                       current_mop = NULL;
+               }
+       }
+       return 1;
+}
+
+static void com_select_callback(int fd, const struct osl_object *query)
+{
+       struct para_buffer pb = {
+               .max_size = SHMMAX,
+               .private_data = &fd,
+               .max_size_handler = pass_buffer_as_shm
+       };
+       char *arg = query->data;
+       int num_admissible, ret, ret2;
+
+       ret = clear_score_table();
+       if (ret < 0) {
+               ret2 = para_printf(&pb, "%s\n", para_strerror(-ret));
+               goto out;
+       }
+       if (current_play_mode == PLAY_MODE_MOOD)
+               close_current_mood();
+       else
+               playlist_close();
+       ret = activate_mood_or_playlist(arg, &num_admissible);
+       if (ret < 0) {
+               ret2 = para_printf(&pb, "%s\nswitching back to %s\n",
+                       para_strerror(-ret), current_mop?
+                       current_mop : "dummy");
+               ret = activate_mood_or_playlist(current_mop, &num_admissible);
+               if (ret < 0) {
+                       if (ret2 >= 0)
+                               ret2 = para_printf(&pb, "failed, switching to dummy\n");
+                       activate_mood_or_playlist(NULL, &num_admissible);
+               }
+       } else
+               ret2 = para_printf(&pb, "activated %s (%d admissible files)\n", current_mop?
+                       current_mop : "dummy mood", num_admissible);
+out:
+       if (ret2 >= 0 && pb.offset)
+               pass_buffer_as_shm(pb.buf, pb.offset, &fd);
+       free(pb.buf);
+}
+
+/**
+ * Result handler for sending data to the para_client process.
+ *
+ * \param result The data to be sent.
+ * \param fd_ptr Pointer to the file descriptor.
+ *
+ * \return The return value of the underlying call to send_bin_buffer().
+ *
+ * \sa \ref callback_result_handler.
+ */
+int send_result(struct osl_object *result, void *fd_ptr)
+{
+       int fd = *(int *)fd_ptr;
+       if (!result->size)
+               return 1;
+       return send_bin_buffer(fd, result->data, result->size);
+}
+
+int com_select(int fd, int argc, char * const * const argv)
+{
+       struct osl_object query;
+
+       if (argc != 2)
+               return -E_AFS_SYNTAX;
+       query.data = argv[1];
+       query.size = strlen(argv[1]) + 1;
+       return send_callback_request(com_select_callback, &query,
+               &send_result, &fd);
+}
+
+static void init_admissible_files(char *arg)
+{
+       if (activate_mood_or_playlist(arg, NULL) < 0)
+               activate_mood_or_playlist(NULL, NULL); /* always successful */
+}
+
+static int setup_command_socket_or_die(void)
+{
+       int ret, socket_fd;
+       char *socket_name = conf.afs_socket_arg;
+       struct sockaddr_un unix_addr;
+
+       unlink(socket_name);
+       ret = create_local_socket(socket_name, &unix_addr,
+               S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IWOTH);
+       if (ret < 0) {
+               PARA_EMERG_LOG("%s: %s\n", para_strerror(-ret), socket_name);
+               exit(EXIT_FAILURE);
+       }
+       socket_fd = ret;
+       if (listen(socket_fd , 5) < 0) {
+               PARA_EMERG_LOG("can not listen on socket\n");
+               exit(EXIT_FAILURE);
+       }
+       ret = mark_fd_nonblocking(socket_fd);
+       if (ret < 0) {
+               close(socket_fd);
+               return ret;
+       }
+       PARA_INFO_LOG("listening on socket %s (fd %d)\n", socket_name,
+               socket_fd);
+       return socket_fd;
+}
+
+static void close_afs_tables(void)
+{
+       int i;
+       PARA_NOTICE_LOG("closing afs_tables\n");
+       for (i = 0; i < NUM_AFS_TABLES; i++)
+               afs_tables[i].close();
+}
+
+static char *database_dir;
+
+static void get_database_dir(void)
+{
+       if (!database_dir) {
+               if (conf.afs_database_dir_given)
+                       database_dir = para_strdup(conf.afs_database_dir_arg);
+               else {
+                       char *home = para_homedir();
+                       database_dir = make_message(
+                               "%s/.paraslash/afs_database", home);
+                       free(home);
+               }
+       }
+       PARA_INFO_LOG("afs_database dir %s\n", database_dir);
+}
+
+static int make_database_dir(void)
+{
+       int ret;
+
+       get_database_dir();
+       ret = para_mkdir(database_dir, 0777);
+       if (ret >= 0 || is_errno(-ret, EEXIST))
+               return 1;
+       return ret;
+}
+
+static int open_afs_tables(void)
+{
+       int i, ret;
+
+       get_database_dir();
+       PARA_NOTICE_LOG("opening %u osl tables in %s\n", NUM_AFS_TABLES,
+               database_dir);
+       for (i = 0; i < NUM_AFS_TABLES; i++) {
+               ret = afs_tables[i].open(database_dir);
+               if (ret >= 0)
                        continue;
-               if (S_ISREG(m)) { /* regular file */
-                       if (guess_audio_format(entry->d_name) < 0)
+               PARA_ERROR_LOG("%s init: %s\n", afs_tables[i].name,
+                       para_strerror(-ret));
+               break;
+       }
+       if (ret >= 0)
+               return ret;
+       while (i)
+               afs_tables[--i].close();
+       return ret;
+}
+
+static void signal_pre_select(struct sched *s, struct task *t)
+{
+       struct signal_task *st = container_of(t, struct signal_task, task);
+       para_fd_set(st->fd, &s->rfds, &s->max_fileno);
+}
+
+static void signal_post_select(struct sched *s, struct task *t)
+{
+       struct signal_task *st = container_of(t, struct signal_task, task);
+       if (getppid() == 1) {
+               PARA_EMERG_LOG("para_server died\n");
+               goto shutdown;
+       }
+       if (!FD_ISSET(st->fd, &s->rfds))
+               return;
+       st->signum = para_next_signal();
+       if (st->signum == SIGHUP) {
+               close_afs_tables();
+               t->error = open_afs_tables();
+               if (t->error < 0)
+                       return;
+               init_admissible_files(current_mop);
+               return;
+       }
+       PARA_EMERG_LOG("terminating on signal %d\n", st->signum);
+shutdown:
+       sched_shutdown();
+       t->error = -E_AFS_SIGNAL;
+}
+
+static void register_signal_task(void)
+{
+       struct signal_task *st = &signal_task_struct;
+
+       if (signal(SIGPIPE, SIG_IGN) == SIG_ERR) {
+               PARA_EMERG_LOG("failed to ignore SIGPIPE\n");
+               exit(EXIT_FAILURE);
+       }
+       if (signal(SIGUSR1, SIG_IGN) == SIG_ERR) {
+               PARA_EMERG_LOG("failed to ignore SIGUSR1\n");
+               exit(EXIT_FAILURE);
+       }
+       st->fd = para_signal_init();
+       PARA_INFO_LOG("signal pipe: fd %d\n", st->fd);
+       para_install_sighandler(SIGINT);
+       para_install_sighandler(SIGTERM);
+       para_install_sighandler(SIGHUP);
+
+       st->task.pre_select = signal_pre_select;
+       st->task.post_select = signal_post_select;
+       sprintf(st->task.status, "signal task");
+       register_task(&st->task);
+}
+
+static struct list_head afs_client_list;
+
+/** Describes on connected afs client. */
+struct afs_client {
+       /** Position in the afs client list. */
+       struct list_head node;
+       /** The socket file descriptor for this client. */
+       int fd;
+       /** The time the client connected. */
+       struct timeval connect_time;
+};
+
+static void command_pre_select(struct sched *s, struct task *t)
+{
+       struct command_task *ct = container_of(t, struct command_task, task);
+       struct afs_client *client;
+
+       para_fd_set(server_socket, &s->rfds, &s->max_fileno);
+       para_fd_set(ct->fd, &s->rfds, &s->max_fileno);
+       list_for_each_entry(client, &afs_client_list, node)
+               para_fd_set(client->fd, &s->rfds, &s->max_fileno);
+}
+
+/**
+ * Send data as shared memory to a file descriptor.
+ *
+ * \param buf The buffer holding the data to be sent.
+ * \param size The size of \a buf.
+ * \param fd_ptr A pointer to the file descriptor.
+ *
+ * This function is used as the \a max_size handler in a \ref para_buffer
+ * structure. If used this way, it is called by \ref para_printf() whenever
+ * the buffer passed to para_printf() is about to exceed its maximal size.
+ *
+ * This function creates a shared memory area large enough to hold
+ * the content given by \a buf and \a size and sends the identifier
+ * of this area to the file descriptor given by \a fd_ptr.
+ *
+ * \return Zero if \a buf is \p NULL or \a size is zero. Negative on errors,
+ * and positive on success.
+ */
+int pass_buffer_as_shm(char *buf, size_t size, void *fd_ptr)
+{
+       int ret, shmid, fd = *(int *)fd_ptr;
+       void *shm;
+       struct callback_result *cr;
+
+       if (!buf || !size)
+               return 0;
+       ret = shm_new(size + sizeof(struct callback_result));
+       if (ret < 0)
+               return ret;
+       shmid = ret;
+       ret = shm_attach(shmid, ATTACH_RW, &shm);
+       if (ret < 0)
+               goto err;
+       cr = shm;
+       cr->result_size = size;
+       memcpy(shm + sizeof(*cr), buf, size);
+       ret = shm_detach(shm);
+       if (ret < 0)
+               goto err;
+       ret = send_bin_buffer(fd, (char *)&shmid, sizeof(int));
+       if (ret >= 0)
+               return ret;
+err:
+       if (shm_destroy(shmid) < 0)
+               PARA_ERROR_LOG("destroy result failed\n");
+       return ret;
+}
+
+/*
+ * On errors, negative value is written to fd.
+ * On success: If query produced a result, the result_shmid is written to fd.
+ * Otherwise, zero is written.
+ */
+static int call_callback(int fd, int query_shmid)
+{
+       void *query_shm;
+       struct callback_query *cq;
+       struct osl_object query;
+       int ret;
+
+       ret = shm_attach(query_shmid, ATTACH_RW, &query_shm);
+       if (ret < 0)
+               return ret;
+       cq = query_shm;
+       query.data = (char *)query_shm + sizeof(*cq);
+       query.size = cq->query_size;
+       cq->handler(fd, &query);
+       return 1;
+}
+
+static int execute_server_command(void)
+{
+       char buf[8];
+       int ret = recv_bin_buffer(server_socket, buf, sizeof(buf) - 1);
+
+       if (ret <= 0) {
+               if (!ret)
+                       ret = -ERRNO_TO_PARA_ERROR(ECONNRESET);
+               goto err;
+       }
+       buf[ret] = '\0';
+       PARA_DEBUG_LOG("received: %s\n", buf);
+       ret = -E_BAD_CMD;
+       if (strcmp(buf, "new"))
+               goto err;
+       ret = open_next_audio_file();
+err:
+       return ret;
+}
+
+static void execute_afs_command(int fd, uint32_t expected_cookie)
+{
+       uint32_t cookie;
+       int query_shmid;
+       char buf[sizeof(cookie) + sizeof(query_shmid)];
+       int ret = recv_bin_buffer(fd, buf, sizeof(buf));
+
+       if (ret < 0)
+               goto err;
+       if (ret != sizeof(buf)) {
+               PARA_NOTICE_LOG("short read (%d bytes, expected %lu)\n",
+                       ret, (long unsigned) sizeof(buf));
+               return;
+       }
+       cookie = *(uint32_t *)buf;
+       if (cookie != expected_cookie) {
+               PARA_NOTICE_LOG("received invalid cookie(got %u, expected %u)\n",
+                       (unsigned)cookie, (unsigned)expected_cookie);
+               return;
+       }
+       query_shmid = *(int *)(buf + sizeof(cookie));
+       if (query_shmid < 0) {
+               PARA_WARNING_LOG("received invalid query shmid %d)\n",
+                       query_shmid);
+               return;
+       }
+       ret = call_callback(fd, query_shmid);
+       if (ret >= 0)
+               return;
+err:
+       PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
+}
+
+/** Shutdown connection if query has not arrived until this many seconds. */
+#define AFS_CLIENT_TIMEOUT 3
+
+static void command_post_select(struct sched *s, struct task *t)
+{
+       struct command_task *ct = container_of(t, struct command_task, task);
+       struct sockaddr_un unix_addr;
+       struct afs_client *client, *tmp;
+       int fd, ret;
+
+       if (FD_ISSET(server_socket, &s->rfds)) {
+               ret = execute_server_command();
+               if (ret < 0) {
+                       PARA_EMERG_LOG("%s\n", para_strerror(-ret));
+                       sched_shutdown();
+                       return;
+               }
+       }
+
+       /* Check the list of connected clients. */
+       list_for_each_entry_safe(client, tmp, &afs_client_list, node) {
+               if (FD_ISSET(client->fd, &s->rfds))
+                       execute_afs_command(client->fd, ct->cookie);
+               else { /* prevent bogus connection flooding */
+                       struct timeval diff;
+                       tv_diff(now, &client->connect_time, &diff);
+                       if (diff.tv_sec < AFS_CLIENT_TIMEOUT)
                                continue;
-                       ret = f(dirname, entry->d_name);
-                       if (ret < 0)
-                               goto out;
-                       continue;
+                       PARA_WARNING_LOG("connection timeout\n");
                }
-               /* directory */
-               tmp = make_message("%s/%s", dirname, entry->d_name);
-               ret = find_audio_files(tmp, f);
-               free(tmp);
+               close(client->fd);
+               list_del(&client->node);
+               free(client);
+       }
+       /* Accept connections on the local socket. */
+       if (!FD_ISSET(ct->fd, &s->rfds))
+               return;
+       ret = para_accept(ct->fd, &unix_addr, sizeof(unix_addr));
+       if (ret < 0) {
+               PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
+               return;
+       }
+       fd = ret;
+       ret = mark_fd_nonblocking(fd);
+       if (ret < 0) {
+               PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
+               close(fd);
+               return;
+       }
+       client = para_malloc(sizeof(*client));
+       client->fd = fd;
+       client->connect_time = *now;
+       para_list_add(&client->node, &afs_client_list);
+}
+
+static void register_command_task(uint32_t cookie)
+{
+       struct command_task *ct = &command_task_struct;
+       ct->fd = setup_command_socket_or_die();
+       ct->cookie = cookie;
+
+       ct->task.pre_select = command_pre_select;
+       ct->task.post_select = command_post_select;
+       sprintf(ct->task.status, "command task");
+       register_task(&ct->task);
+}
+
+/**
+ * Initialize the audio file selector process.
+ *
+ * \param cookie The value used for "authentication".
+ * \param socket_fd File descriptor used for communication with the server.
+ */
+__noreturn void afs_init(uint32_t cookie, int socket_fd)
+{
+       struct sched s;
+       int i, ret;
+
+       register_signal_task();
+       INIT_LIST_HEAD(&afs_client_list);
+       for (i = 0; i < NUM_AFS_TABLES; i++)
+               afs_tables[i].init(&afs_tables[i]);
+       ret = open_afs_tables();
+       if (ret < 0)
+               goto out;
+       server_socket = socket_fd;
+       ret = mark_fd_nonblocking(server_socket);
+       if (ret < 0)
+               goto out_close;
+       PARA_INFO_LOG("server_socket: %d, afs_socket_cookie: %u\n",
+               server_socket, (unsigned) cookie);
+       init_admissible_files(conf.afs_initial_mode_arg);
+       register_command_task(cookie);
+       s.default_timeout.tv_sec = 0;
+       s.default_timeout.tv_usec = 999 * 1000;
+       ret = schedule(&s);
+out_close:
+       close_afs_tables();
+out:
+       if (ret < 0)
+               PARA_EMERG_LOG("%s\n", para_strerror(-ret));
+       exit(EXIT_FAILURE);
+}
+
+static void create_tables_callback(int fd, const struct osl_object *query)
+{
+       uint32_t table_mask = *(uint32_t *)query->data;
+       int i, ret;
+       char *buf;
+
+       close_afs_tables();
+       for (i = 0; i < NUM_AFS_TABLES; i++) {
+               struct afs_table *t = &afs_tables[i];
+
+               if (!(table_mask & (1 << i)))
+                       continue;
+               if (!t->create)
+                       continue;
+               ret = t->create(database_dir);
                if (ret < 0)
                        goto out;
        }
-       ret = 1;
+       ret = open_afs_tables();
 out:
-       if (dir)
-               closedir(dir);
-       if (fchdir(cwd_fd) < 0)
-               ret = -E_CHDIR;
-       close(cwd_fd);
+       if (ret >= 0)
+               buf = make_message("successfully created afs table(s)\n");
+       else
+               buf = make_message("%s\n", para_strerror(-ret));
+       pass_buffer_as_shm(buf, strlen(buf), &fd);
+       free(buf);
+}
+
+int com_init(int fd, int argc, char * const * const argv)
+{
+       int i, j, ret;
+       uint32_t table_mask = (1 << (NUM_AFS_TABLES + 1)) - 1;
+       struct osl_object query = {.data = &table_mask,
+               .size = sizeof(table_mask)};
+
+       ret = make_database_dir();
+       if (ret < 0)
+               return ret;
+       if (argc != 1) {
+               table_mask = 0;
+               for (i = 1; i < argc; i++) {
+                       for (j = 0; j < NUM_AFS_TABLES; j++) {
+                               struct afs_table *t = &afs_tables[j];
+
+                               if (strcmp(argv[i], t->name))
+                                       continue;
+                               table_mask |= (1 << j);
+                               break;
+                       }
+                       if (j == NUM_AFS_TABLES)
+                               return -E_BAD_TABLE_NAME;
+               }
+       }
+       ret = send_callback_request(create_tables_callback, &query, NULL, NULL);
        if (ret < 0)
-               PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));
+               return send_va_buffer(fd, "%s\n", para_strerror(-ret));
        return ret;
 }
+
+/**
+ * Flags for the check command.
+ *
+ * \sa com_check().
+ */
+enum com_check_flags {
+       /** Check the audio file table. */
+       CHECK_AFT = 1,
+       /** Check the mood table. */
+       CHECK_MOODS = 2,
+       /** Check the playlist table. */
+       CHECK_PLAYLISTS = 4
+};
+
+int com_check(int fd, int argc, char * const * const argv)
+{
+       unsigned flags = 0;
+       int i, ret;
+
+       for (i = 1; i < argc; i++) {
+               const char *arg = argv[i];
+               if (arg[0] != '-')
+                       break;
+               if (!strcmp(arg, "--")) {
+                       i++;
+                       break;
+               }
+               if (!strcmp(arg, "-a")) {
+                       flags |= CHECK_AFT;
+                       continue;
+               }
+               if (!strcmp(arg, "-p")) {
+                       flags |= CHECK_PLAYLISTS;
+                       continue;
+               }
+               if (!strcmp(arg, "-m")) {
+                       flags |= CHECK_MOODS;
+                       continue;
+               }
+               return -E_AFS_SYNTAX;
+       }
+       if (i < argc)
+               return -E_AFS_SYNTAX;
+       if (!flags)
+               flags = ~0U;
+       if (flags & CHECK_AFT) {
+               ret = send_callback_request(aft_check_callback, NULL, send_result, &fd);
+               if (ret < 0)
+                       return ret;
+       }
+       if (flags & CHECK_PLAYLISTS) {
+               ret = send_callback_request(playlist_check_callback, NULL, send_result, &fd);
+               if (ret < 0)
+                       return ret;
+       }
+       if (flags & CHECK_MOODS) {
+               ret = send_callback_request(mood_check_callback, NULL, send_result, &fd);
+               if (ret < 0)
+                       return ret;
+       }
+       return 1;
+}
+
+void afs_event(enum afs_events event, struct para_buffer *pb,
+               void *data)
+{
+       int i, ret;
+
+       for (i = 0; i < NUM_AFS_TABLES; i++) {
+               struct afs_table *t = &afs_tables[i];
+               if (!t->event_handler)
+                       continue;
+               ret = t->event_handler(event, pb, data);
+               if (ret < 0)
+                       PARA_CRIT_LOG("%s\n", para_strerror(-ret));
+       }
+}
+
+int images_event_handler(__a_unused enum afs_events event,
+       __a_unused  struct para_buffer *pb, __a_unused void *data)
+{
+       return 1;
+}
+
+int lyrics_event_handler(__a_unused enum afs_events event,
+       __a_unused struct para_buffer *pb, __a_unused void *data)
+{
+       return 1;
+}