+#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 table_info afs_tables[NUM_AFS_TABLES];
+
+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;
+};
+
+/**
+ * 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;
+
+/**
+ * Struct to let command handlers execute a callback in afs context.
+ *
+ * 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.
+ *
+ * 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.
+ *
+ * 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.
+ */
+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 parent process to call a given function.
+ *
+ * \param f The function to be called.
+ * \param query Pointer to arbitrary data for the callback.
+ * \param result Callback result will be stored here.
+ *
+ * This function creates a shared memory area, copies the buffer pointed to by
+ * \a buf to that area and notifies the afs process that \a f should be
+ * called ASAP.
+ *
+ * \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,
+ struct osl_object *result)
+{
+ struct callback_query *cq;
+ struct callback_result *cr;
+ int ret, fd = -1, query_shmid, result_shmid;
+ void *query_shm, *result_shm;
+ char buf[sizeof(afs_socket_cookie) + sizeof(int)];
+ struct sockaddr_un unix_addr;
+ 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 = get_stream_socket(PF_UNIX);
+ if (ret < 0)
+ goto out;
+ fd = ret;
+ ret = init_unix_addr(&unix_addr, conf.afs_socket_arg);
+ if (ret < 0)
+ goto out;
+ ret = PARA_CONNECT(fd, &unix_addr);
+ if (ret < 0)
+ goto out;
+ ret = send_bin_buffer(fd, buf, sizeof(buf));
+ if (ret < 0)
+ goto out;
+ ret = recv_bin_buffer(fd, buf, sizeof(buf));
+ if (ret < 0)
+ goto out;
+ if (ret != sizeof(int)) {
+ ret = -E_RECV;
+ 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) {
+ assert(result);
+ cr = result_shm;
+ result->size = cr->result_size;
+ result->data = para_malloc(result->size);
+ memcpy(result->data, result_shm + sizeof(*cr), result->size);
+ ret = shm_detach(result_shm);
+ if (ret < 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");
+ ret = 1;
+out:
+ if (shm_destroy(query_shmid) < 0)
+ PARA_ERROR_LOG("%s\n", "shm destroy error");
+ if (fd >= 0)
+ close(fd);
+// PARA_DEBUG_LOG("callback_ret: %d\n", ret);
+ return ret;
+}
+
+/**
+ * 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 The result of the query is stored here.
+ *
+ * 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,
+ struct osl_object *result)
+{
+ 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);
+ 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 The same meaning as in send_option_arg_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, struct osl_object *result)
+{
+ return send_option_arg_callback_request(NULL, argc, argv, f, result);
+}
+
+/**
+ * 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));
+}
+
+/**
+ * A wrapper for strtol(3).
+ *
+ * \param str The string to be converted to a long integer.
+ * \param result The converted value is stored here.
+ *
+ * \return Positive on success, -E_ATOL on errors.
+ *
+ * \sa strtol(3), atoi(3).
+ */
+int para_atol(const char *str, long *result)
+{
+ char *endptr;
+ long val;
+ int ret, base = 10;
+
+ errno = 0; /* To distinguish success/failure after call */
+ val = strtol(str, &endptr, base);
+ ret = -E_ATOL;
+ if (errno == ERANGE && (val == LONG_MAX || val == LONG_MIN))
+ goto out; /* overflow */
+ if (errno != 0 && val == 0)
+ goto out; /* other error */
+ if (endptr == str)
+ goto out; /* No digits were found */
+ if (*endptr != '\0')
+ goto out; /* Further characters after number */
+ *result = val;
+ ret = 1;
+out:
+ return ret;
+}
+
+
+/*
+ * 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 The result of the query is stored here.
+ *
+ * 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 parent process via shared memory.
+ *
+ * \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, struct osl_object *result)
+{
+ 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);
+ free(query.data);
+ return ret;
+}
+
+/**
+ * Open the audio file with highest score.
+ *
+ * \param afd Audio file data is returned here.
+ *
+ * This stores all information for streaming the "best" audio file
+ * in the \a afd structure.
+ *
+ * \return Positive on success, negative on errors.
+ *
+ * \sa close_audio_file(), open_and_update_audio_file().
+ */
+int open_next_audio_file(struct audio_file_data *afd)
+{
+ struct osl_row *aft_row;
+ int ret;
+ for (;;) {
+ ret = score_get_best(&aft_row, &afd->score);
+ if (ret < 0)
+ return ret;
+ ret = open_and_update_audio_file(aft_row, afd);
+ if (ret >= 0)
+ return ret;
+ }
+}