Also save the header length and offset in the aft.
[paraslash.git] / afs.c
diff --git a/afs.c b/afs.c
index 17557e5eaa789831f136e758a3a31fe5903e7271..20f2455e30a3d1fe940d84d9d5616fd97e5ee30d 100644 (file)
--- a/afs.c
+++ b/afs.c
 #include <fnmatch.h>
 #include "server.cmdline.h"
 #include "para.h"
+#include "error.h"
+#include "string.h"
 #include "afh.h"
+#include "afs.h"
 #include "server.h"
-#include "error.h"
 #include <dirent.h> /* readdir() */
 #include <sys/mman.h>
 #include <sys/time.h>
 #include "net.h"
-#include "afs.h"
 #include "ipc.h"
-#include "string.h"
 #include "list.h"
 #include "sched.h"
 #include "signal.h"
@@ -53,7 +53,15 @@ enum afs_table_num {
        NUM_AFS_TABLES
 };
 
-static struct table_info afs_tables[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. */
@@ -67,6 +75,16 @@ struct command_task {
        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.
  *
@@ -130,7 +148,7 @@ struct callback_result {
  * \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
+ * query 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
@@ -417,75 +435,184 @@ int stdin_command(int fd, struct osl_object *arg_obj, callback_function *f,
        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.
  *
- * \param afd Audio file data is returned here.
- *
- * This stores all information for streaming the "best" audio file
- * in the \a afd structure.
+ * 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 Positive on success, negative on errors.
+ * \return Standard.
  *
- * \sa close_audio_file(), open_and_update_audio_file().
+ * \sa open_and_update_audio_file().
  */
-int open_next_audio_file(struct audio_file_data *afd)
+int open_next_audio_file(void)
 {
        struct osl_row *aft_row;
+       struct audio_file_data afd;
+       int ret, shmid;
+       char buf[8];
+
+       PARA_NOTICE_LOG("getting next audio file\n");
+       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;
+       shmid = ret;
+       if (!write_ok(server_socket)) {
+               PARA_EMERG_LOG("afs_socket not writable\n");
+               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;
+       PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));
+destroy:
+       shm_destroy(shmid);
+       return ret;
+}
+
+/* Never fails if arg == NULL */
+static int activate_mood_or_playlist(char *arg, int *num_admissible)
+{
+       enum play_mode mode;
        int ret;
-       for (;;) {
-               ret = score_get_best(&aft_row, &afd->score);
+
+       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
+                       ret = -E_AFS_SYNTAX;
                if (ret < 0)
                        return ret;
-               ret = open_and_update_audio_file(aft_row, afd);
-               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;
 }
 
-/**
- * Free all resources which were allocated by open_next_audio_file().
- *
- * \param afd The structure previously filled in by open_next_audio_file().
- *
- * \return The return value of the underlying call to para_munmap().
- *
- * \sa open_next_audio_file().
- */
-int close_audio_file(struct audio_file_data *afd)
+static int com_select_callback(const struct osl_object *query,
+               struct osl_object *result)
 {
-       free(afd->afhi.chunk_table);
-       return para_munmap(afd->map.data, afd->map.size);
+       struct para_buffer pb = {.buf = NULL};
+       char *arg = query->data;
+       int num_admissible, ret;
+
+       ret = clear_score_table();
+       if (ret < 0)
+               return ret;
+       if (current_play_mode == PLAY_MODE_MOOD)
+               close_current_mood();
+       else
+               playlist_close();
+       ret = activate_mood_or_playlist(arg, &num_admissible);
+       if (ret < 0) {
+               para_printf(&pb, "%s\n", PARA_STRERROR(-ret));
+               para_printf(&pb, "switching back to %s\n", current_mop?
+                       current_mop : "dummy");
+               ret = activate_mood_or_playlist(current_mop, &num_admissible);
+               if (ret < 0) {
+                       para_printf(&pb, "failed, switching to dummy\n");
+                       activate_mood_or_playlist(NULL, &num_admissible);
+               }
+       }
+       para_printf(&pb, "activated %s (%d admissible files)\n", current_mop?
+               current_mop : "dummy mood", num_admissible);
+       result->data = pb.buf;
+       result->size = pb.size;
+       return 1;
 }
 
-static enum play_mode init_admissible_files(void)
+int com_select(int fd, int argc, char * const * const argv)
 {
        int ret;
+       struct osl_object query, result;
 
-       if (conf.mood_given) {
-               ret = change_current_mood(conf.mood_arg);
-               if (ret >= 0) {
-                       if (conf.playlist_given)
-                               PARA_WARNING_LOG("ignoring playlist %s\n",
-                                       conf.playlist_arg);
-                       return PLAY_MODE_MOOD;
-               }
-       }
-       if (conf.playlist_given) {
-               ret = playlist_open(conf.playlist_arg);
-               if (ret >= 0)
-                       return PLAY_MODE_PLAYLIST;
+       if (argc != 2)
+               return -E_AFS_SYNTAX;
+       query.data = argv[1];
+       query.size = strlen(argv[1]) + 1;
+       ret = send_callback_request(com_select_callback, &query,
+               &result);
+       if (ret > 0 && result.data && result.size) {
+               ret = send_va_buffer(fd, "%s", (char *)result.data);
+               free(result.data);
        }
-       ret = change_current_mood(NULL); /* open first available mood */
-       if (ret >= 0)
-               return PLAY_MODE_MOOD;
-       change_current_mood(""); /* open dummy mood, always successful */
-       return PLAY_MODE_MOOD;
+       return ret;
+}
+
+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;
+       int ret, socket_fd;
        char *socket_name = conf.afs_socket_arg;
        struct sockaddr_un unix_addr;
 
@@ -496,35 +623,32 @@ static int setup_command_socket_or_die(void)
                PARA_EMERG_LOG("%s: %s\n", PARA_STRERROR(-ret), socket_name);
                exit(EXIT_FAILURE);
        }
-       if (listen(ret , 5) < 0) {
-               PARA_EMERG_LOG("%s", "can not listen on socket\n");
+       socket_fd = ret;
+       if (listen(socket_fd , 5) < 0) {
+               PARA_EMERG_LOG("can not listen on socket\n");
                exit(EXIT_FAILURE);
        }
-       PARA_INFO_LOG("listening on command socket %s (fd %d)\n", socket_name,
-               ret);
-       return ret;
+       ret = mark_fd_nonblock(socket_fd);
+       if (ret < 0) {
+               close(socket_fd);
+               return ret;
+       }
+       PARA_INFO_LOG("listening on socket %s (fd %d)\n", socket_name, ret);
+       return socket_fd;
 }
 
-static void close_afs_tables(enum osl_close_flags flags)
+static void close_afs_tables(void)
 {
+       int i;
        PARA_NOTICE_LOG("closing afs_tables\n");
-       score_shutdown(flags);
-       attribute_shutdown(flags);
-       close_current_mood();
-       playlist_close();
-       moods_shutdown(flags);
-       playlists_shutdown(flags);
-       lyrics_shutdown(flags);
-       images_shutdown(flags);
-       aft_shutdown(flags);
+       for (i = 0; i < NUM_AFS_TABLES; i++)
+               afs_tables[i].close();
 }
 
 static char *database_dir;
 
-static int make_database_dir(void)
+static void get_database_dir(void)
 {
-       int ret;
-
        if (!database_dir) {
                if (conf.afs_database_dir_given)
                        database_dir = para_strdup(conf.afs_database_dir_arg);
@@ -536,63 +660,41 @@ static int make_database_dir(void)
                }
        }
        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;
-       free(database_dir);
-       database_dir = NULL;
        return ret;
 }
 
-
 static int open_afs_tables(void)
 {
-       int ret = make_database_dir();
+       int i, ret;
 
-       if (ret < 0)
-               return ret;
-       ret = attribute_init(&afs_tables[TBLNUM_ATTRIBUTES], database_dir);
-       if (ret < 0)
+       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;
+               PARA_ERROR_LOG("%s init: %s\n", afs_tables[i].name,
+                       PARA_STRERROR(-ret));
+               break;
+       }
+       if (ret >= 0)
                return ret;
-       ret = moods_init(&afs_tables[TBLNUM_MOODS], database_dir);
-       if (ret < 0)
-               goto moods_init_error;
-       ret = playlists_init(&afs_tables[TBLNUM_PLAYLIST], database_dir);
-       if (ret < 0)
-               goto playlists_init_error;
-       ret = lyrics_init(&afs_tables[TBLNUM_LYRICS], database_dir);
-       if (ret < 0)
-               goto lyrics_init_error;
-       ret = images_init(&afs_tables[TBLNUM_IMAGES], database_dir);
-       if (ret < 0)
-               goto images_init_error;
-       ret = score_init(&afs_tables[TBLNUM_SCORES], database_dir);
-       if (ret < 0)
-               goto score_init_error;
-       ret = aft_init(&afs_tables[TBLNUM_AUDIO_FILES], database_dir);
-       if (ret < 0)
-               goto aft_init_error;
-       return 1;
-
-aft_init_error:
-       score_shutdown(OSL_MARK_CLEAN);
-score_init_error:
-       images_shutdown(OSL_MARK_CLEAN);
-images_init_error:
-       lyrics_shutdown(OSL_MARK_CLEAN);
-lyrics_init_error:
-       playlists_shutdown(OSL_MARK_CLEAN);
-playlists_init_error:
-       moods_shutdown(OSL_MARK_CLEAN);
-moods_init_error:
-       attribute_shutdown(OSL_MARK_CLEAN);
+       while (i)
+               afs_tables[--i].close();
        return ret;
 }
 
-static int server_socket;
-static struct command_task command_task_struct;
-static struct signal_task signal_task_struct;
-
 static void unregister_tasks(void)
 {
        unregister_task(&command_task_struct.task);
@@ -609,6 +711,9 @@ static void signal_pre_select(struct sched *s, struct task *t)
 static void signal_post_select(struct sched *s, struct task *t)
 {
        struct signal_task *st = t->private_data;
+       t->ret = -E_AFS_PARENT_DIED;
+       if (getppid() == 1)
+               goto err;
        t->ret = 1;
        if (!FD_ISSET(st->fd, &s->rfds))
                return;
@@ -617,12 +722,16 @@ static void signal_post_select(struct sched *s, struct task *t)
        if (st->signum == SIGUSR1)
                return; /* ignore SIGUSR1 */
        if (st->signum == SIGHUP) {
-               close_afs_tables(OSL_MARK_CLEAN);
+               close_afs_tables();
                t->ret = open_afs_tables();
+               if (t->ret < 0)
+                       goto err;
+               init_admissible_files(current_mop);
                return;
        }
-       PARA_NOTICE_LOG("caught signal %d\n", st->signum);
        t->ret = -E_AFS_SIGNAL;
+err:
+       PARA_NOTICE_LOG("%s\n", PARA_STRERROR(-t->ret));
        unregister_tasks();
 }
 
@@ -645,9 +754,13 @@ static void register_signal_task(void)
 
 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;
 };
 
@@ -656,6 +769,7 @@ static void command_pre_select(struct sched *s, struct task *t)
        struct command_task *ct = t->private_data;
        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);
@@ -717,6 +831,28 @@ out:
        return ret;
 }
 
+static void execute_server_command(void)
+{
+       char buf[8];
+       int ret = recv_bin_buffer(server_socket, buf, sizeof(buf) - 1);
+
+       if (ret <= 0) {
+               if (ret < 0)
+                       PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));
+               return;
+       }
+       buf[ret] = '\0';
+       PARA_DEBUG_LOG("received: %s\n", buf);
+       if (!strcmp(buf, "new")) {
+               ret = open_next_audio_file();
+               if (ret < 0)
+                       PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));
+               return;
+       }
+       PARA_ERROR_LOG("unknown command\n");
+
+}
+
 static void execute_afs_command(int fd, uint32_t expected_cookie)
 {
        uint32_t cookie;
@@ -757,8 +893,11 @@ static void command_post_select(struct sched *s, struct task *t)
        struct command_task *ct = t->private_data;
        struct sockaddr_un unix_addr;
        struct afs_client *client, *tmp;
+       int fd;
+       if (FD_ISSET(server_socket, &s->rfds))
+               execute_server_command();
 
-       /* First, check the list of connected clients. */
+       /* 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);
@@ -773,7 +912,7 @@ static void command_post_select(struct sched *s, struct task *t)
                list_del(&client->node);
                free(client);
        }
-       /* Next, accept connections on the local socket. */
+       /* Accept connections on the local socket. */
        if (!FD_ISSET(ct->fd, &s->rfds))
                goto out;
        t->ret = para_accept(ct->fd, &unix_addr, sizeof(unix_addr));
@@ -781,8 +920,15 @@ static void command_post_select(struct sched *s, struct task *t)
                PARA_NOTICE_LOG("%s\n", PARA_STRERROR(-t->ret));
                goto out;
        }
+       fd = t->ret;
+       t->ret = mark_fd_nonblock(fd);
+       if (t->ret < 0) {
+               PARA_NOTICE_LOG("%s\n", PARA_STRERROR(-t->ret));
+               close(fd);
+               goto out;
+       }
        client = para_malloc(sizeof(*client));
-       client->fd = t->ret;
+       client->fd = fd;
        client->connect_time = *now;
        para_list_add(&client->node, &afs_client_list);
 out:
@@ -816,11 +962,12 @@ static void register_tasks(uint32_t cookie)
  */
 __noreturn void afs_init(uint32_t cookie, int socket_fd)
 {
-       enum play_mode current_play_mode;
        struct sched s;
-       int ret;
+       int i, ret;
 
        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) {
@@ -833,14 +980,14 @@ __noreturn void afs_init(uint32_t cookie, int socket_fd)
                exit(EXIT_FAILURE);
        PARA_INFO_LOG("server_socket: %d, afs_socket_cookie: %u\n",
                server_socket, (unsigned) cookie);
-       current_play_mode = init_admissible_files();
+       init_admissible_files(conf.afs_initial_mode_arg);
        register_tasks(cookie);
        s.default_timeout.tv_sec = 0;
-       s.default_timeout.tv_usec = 99 * 1000;
+       s.default_timeout.tv_usec = 999 * 1000;
        ret = sched(&s);
        if (ret < 0)
                PARA_EMERG_LOG("%s\n", PARA_STRERROR(-ret));
-       close_afs_tables(OSL_MARK_CLEAN);
+       close_afs_tables();
        exit(EXIT_FAILURE);
 }
 
@@ -850,15 +997,15 @@ static int create_tables_callback(const struct osl_object *query,
        uint32_t table_mask = *(uint32_t *)query->data;
        int i, ret;
 
-       close_afs_tables(OSL_MARK_CLEAN);
+       close_afs_tables();
        for (i = 0; i < NUM_AFS_TABLES; i++) {
-               struct table_info *ti = afs_tables + i;
+               struct afs_table *t = &afs_tables[i];
 
-               if (ti->flags & TBLFLAG_SKIP_CREATE)
-                       continue;
                if (!(table_mask & (1 << i)))
                        continue;
-               ret = osl_create_table(ti->desc);
+               if (!t->create)
+                       continue;
+               ret = t->create(database_dir);
                if (ret < 0)
                        return ret;
        }
@@ -873,15 +1020,16 @@ int com_init(int fd, int argc, char * const * const argv)
        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 table_info *ti = afs_tables + j;
+                               struct afs_table *t = &afs_tables[j];
 
-                               if (ti->flags & TBLFLAG_SKIP_CREATE)
-                                       continue;
-                               if (strcmp(argv[i], ti->desc->name))
+                               if (strcmp(argv[i], t->name))
                                        continue;
                                table_mask |= (1 << j);
                                break;
@@ -977,3 +1125,30 @@ int com_check(int fd, int argc, char * const * const argv)
        }
        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;
+}