2 * Copyright (C) 2007 Andre Noll <maan@systemlinux.org>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file afs.c Paraslash's audio file selector. */
11 #include "server.cmdline.h"
17 #include <dirent.h> /* readdir() */
28 /** The osl tables used by afs. \sa blob.c. */
30 /** Contains audio file information. See aft.c. */
32 /** The table for the paraslash attributes. See attribute.c. */
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
42 * A standard blob table containing the mood definitions. For details
46 /** A blob table containing lyrics on a per-song basis. */
48 /** Another blob table for images (for example album cover art). */
50 /** Yet another blob table for storing standard playlists. */
52 /** How many tables are in use? */
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},
67 /** The file descriptor for the local socket. */
70 * Value sent by the command handlers to identify themselves as
71 * children of the running para_server.
74 /** The associated task structure. */
79 * A random number used to "authenticate" the connection.
81 * para_server picks this number by random before forking the afs process. The
82 * command handlers write this number together with the id of the shared memory
83 * area containing the query. This way, a malicious local user has to know this
84 * number to be able to cause the afs process to crash by sending fake queries.
86 extern uint32_t afs_socket_cookie;
89 * Struct to let command handlers execute a callback in afs context.
91 * Commands that need to change the state of afs can't change the relevant data
92 * structures directly because commands are executed in a child process, i.e.
93 * they get their own virtual address space.
95 * This structure is used by \p send_callback_request() (executed from handler
96 * context) in order to let the afs process call the specified function. An
97 * instance of that structure is written to a shared memory area together with
98 * the arguments to the callback function. The identifier of the shared memory
99 * area is written to the command socket.
101 * The afs process accepts connections on the command socket and reads the
102 * shared memory id, attaches the corresponing area, calls the given handler to
103 * perform the desired action and to optionally compute a result.
105 * The result and a \p callback_result structure is then written to another
106 * shared memory area. The identifier for that area is written to the handler's
107 * command socket, so that the handler process can read the id, attach the
108 * shared memory area and use the result.
110 * \sa struct callback_result.
112 struct callback_query {
113 /** The function to be called. */
114 callback_function *handler;
115 /** The number of bytes of the query */
120 * Structure embedded in the result of a callback.
122 * If the callback produced a result, an instance of that structure is embeeded
123 * into the shared memory area holding the result, mainly to let the command
124 * handler know the size of the result.
126 * \sa struct callback_query.
128 struct callback_result {
129 /** The number of bytes of the result. */
134 * Ask the afs process to call a given function.
136 * \param f The function to be called.
137 * \param query Pointer to arbitrary data for the callback.
138 * \param result Callback result will be stored here.
140 * This function creates a shared memory area, copies the buffer pointed to by
141 * \a buf to that area and notifies the afs process that \a f should be
144 * \return Negative, on errors, the return value of the callback function
147 * \sa send_option_arg_callback_request(), send_standard_callback_request().
149 int send_callback_request(callback_function *f, struct osl_object *query,
150 struct osl_object *result)
152 struct callback_query *cq;
153 struct callback_result *cr;
154 int ret, fd = -1, query_shmid, result_shmid;
155 void *query_shm, *result_shm;
156 char buf[sizeof(afs_socket_cookie) + sizeof(int)];
157 struct sockaddr_un unix_addr;
158 size_t query_shm_size = sizeof(*cq);
161 query_shm_size += query->size;
162 ret = shm_new(query_shm_size);
166 ret = shm_attach(query_shmid, ATTACH_RW, &query_shm);
171 cq->query_size = query_shm_size - sizeof(*cq);
174 memcpy(query_shm + sizeof(*cq), query->data, query->size);
175 ret = shm_detach(query_shm);
179 *(uint32_t *) buf = afs_socket_cookie;
180 *(int *) (buf + sizeof(afs_socket_cookie)) = query_shmid;
182 ret = get_stream_socket(PF_UNIX);
186 ret = init_unix_addr(&unix_addr, conf.afs_socket_arg);
189 ret = PARA_CONNECT(fd, &unix_addr);
192 ret = send_bin_buffer(fd, buf, sizeof(buf));
195 ret = recv_bin_buffer(fd, buf, sizeof(buf));
198 if (ret != sizeof(int)) {
206 ret = shm_attach(result_shmid, ATTACH_RO, &result_shm);
210 result->size = cr->result_size;
211 result->data = para_malloc(result->size);
212 memcpy(result->data, result_shm + sizeof(*cr), result->size);
213 ret = shm_detach(result_shm);
215 PARA_ERROR_LOG("can not detach result\n");
217 PARA_ERROR_LOG("attach result failed: %d\n", ret);
218 if (shm_destroy(result_shmid) < 0)
219 PARA_ERROR_LOG("destroy result failed\n");
222 if (shm_destroy(query_shmid) < 0)
223 PARA_ERROR_LOG("%s\n", "shm destroy error");
226 // PARA_DEBUG_LOG("callback_ret: %d\n", ret);
231 * Send a callback request passing an options structure and an argument vector.
233 * \param options pointer to an arbitrary data structure.
234 * \param argc Argument count.
235 * \param argv Standard argument vector.
236 * \param f The callback function.
237 * \param result The result of the query is stored here.
239 * Some commands have a couple of options that are parsed in child context for
240 * syntactic correctness and are stored in a special options structure for that
241 * command. This function allows to pass such a structure together with a list
242 * of further arguments (often a list of audio files) to the parent process.
244 * \sa send_standard_callback_request(), send_callback_request().
246 int send_option_arg_callback_request(struct osl_object *options,
247 int argc, char * const * const argv, callback_function *f,
248 struct osl_object *result)
252 struct osl_object query = {.size = options? options->size : 0};
254 for (i = 0; i < argc; i++)
255 query.size += strlen(argv[i]) + 1;
256 query.data = para_malloc(query.size);
259 memcpy(query.data, options->data, options->size);
262 for (i = 0; i < argc; i++) {
263 strcpy(p, argv[i]); /* OK */
264 p += strlen(argv[i]) + 1;
266 ret = send_callback_request(f, &query, result);
272 * Send a callback request with an argument vector only.
274 * \param argc The same meaning as in send_option_arg_callback_request().
275 * \param argv The same meaning as in send_option_arg_callback_request().
276 * \param f The same meaning as in send_option_arg_callback_request().
277 * \param result The same meaning as in send_option_arg_callback_request().
279 * This is similar to send_option_arg_callback_request(), but no options buffer
280 * is passed to the parent process.
282 * \return The return value of the underlying call to
283 * send_option_arg_callback_request().
285 int send_standard_callback_request(int argc, char * const * const argv,
286 callback_function *f, struct osl_object *result)
288 return send_option_arg_callback_request(NULL, argc, argv, f, result);
291 static int action_if_pattern_matches(struct osl_row *row, void *data)
293 struct pattern_match_data *pmd = data;
294 struct osl_object name_obj;
295 const char *p, *name;
296 int ret = osl_get_object(pmd->table, row, pmd->match_col_num, &name_obj);
297 const char *pattern_txt = (const char *)pmd->patterns.data;
301 name = (char *)name_obj.data;
302 if ((!name || !*name) && (pmd->pm_flags & PM_SKIP_EMPTY_NAME))
304 if (!pmd->patterns.size && (pmd->pm_flags & PM_NO_PATTERN_MATCHES_EVERYTHING))
305 return pmd->action(pmd->table, row, name, pmd->data);
306 for (p = pattern_txt; p < pattern_txt + pmd->patterns.size;
307 p += strlen(p) + 1) {
308 ret = fnmatch(p, name, pmd->fnmatch_flags);
309 if (ret == FNM_NOMATCH)
313 return pmd->action(pmd->table, row, name, pmd->data);
319 * Execute the given function for each matching row.
321 * \param pmd Describes what to match and how.
323 * \return The return value of the underlying call to osl_rbtree_loop()
324 * or osl_rbtree_loop_reverse().
326 int for_each_matching_row(struct pattern_match_data *pmd)
328 if (pmd->pm_flags & PM_REVERSE_LOOP)
329 return osl_rbtree_loop_reverse(pmd->table, pmd->loop_col_num, pmd,
330 action_if_pattern_matches);
331 return osl_rbtree_loop(pmd->table, pmd->loop_col_num, pmd,
332 action_if_pattern_matches);
336 * Compare two osl objects of string type.
338 * \param obj1 Pointer to the first object.
339 * \param obj2 Pointer to the second object.
341 * In any case, only \p MIN(obj1->size, obj2->size) characters of each string
342 * are taken into account.
344 * \return It returns an integer less than, equal to, or greater than zero if
345 * \a obj1 is found, respectively, to be less than, to match, or be greater than
348 * \sa strcmp(3), strncmp(3), osl_compare_func.
350 int string_compare(const struct osl_object *obj1, const struct osl_object *obj2)
352 const char *str1 = (const char *)obj1->data;
353 const char *str2 = (const char *)obj2->data;
354 return strncmp(str1, str2, PARA_MIN(obj1->size, obj2->size));
358 * write input from fd to dynamically allocated buffer,
359 * but maximal max_size byte.
361 static int fd2buf(int fd, unsigned max_size, struct osl_object *obj)
363 const size_t chunk_size = 1024;
364 size_t size = 2048, received = 0;
366 char *buf = para_malloc(size);
369 ret = recv_bin_buffer(fd, buf + received, chunk_size);
373 if (received + chunk_size >= size) {
375 ret = -E_INPUT_TOO_LARGE;
378 buf = para_realloc(buf, size);
382 obj->size = received;
389 * Read data from a file descriptor, and send it to the afs process.
391 * \param fd File descriptor to read data from.
392 * \param arg_obj Pointer to the arguments to \a f.
393 * \param f The callback function.
394 * \param max_len Don't read more than that many bytes from stdin.
395 * \param result The result of the query is stored here.
397 * This function is used by commands that wish to let para_server store
398 * arbitrary data specified by the user (for instance the add_blob family of
399 * commands). First, at most \a max_len bytes are read from \a fd, the result
400 * is concatenated with the buffer given by \a arg_obj, and the combined buffer
401 * is made available to the parent process via shared memory.
403 * \return Negative on errors, the return value of the underlying call to
404 * send_callback_request() otherwise.
406 int stdin_command(int fd, struct osl_object *arg_obj, callback_function *f,
407 unsigned max_len, struct osl_object *result)
409 struct osl_object query, stdin_obj;
412 ret = send_buffer(fd, AWAITING_DATA_MSG);
415 ret = fd2buf(fd, max_len, &stdin_obj);
418 query.size = arg_obj->size + stdin_obj.size;
419 query.data = para_malloc(query.size);
420 memcpy(query.data, arg_obj->data, arg_obj->size);
421 memcpy((char *)query.data + arg_obj->size, stdin_obj.data, stdin_obj.size);
422 free(stdin_obj.data);
423 ret = send_callback_request(f, &query, result);
429 * Open the audio file with highest score.
431 * \param afd Audio file data is returned here.
433 * This stores all information for streaming the "best" audio file
434 * in the \a afd structure.
436 * \return Positive on success, negative on errors.
438 * \sa close_audio_file(), open_and_update_audio_file().
440 int open_next_audio_file(struct audio_file_data *afd)
442 struct osl_row *aft_row;
445 ret = score_get_best(&aft_row, &afd->score);
448 ret = open_and_update_audio_file(aft_row, afd);
455 * Free all resources which were allocated by open_next_audio_file().
457 * \param afd The structure previously filled in by open_next_audio_file().
459 * \return The return value of the underlying call to para_munmap().
461 * \sa open_next_audio_file().
463 int close_audio_file(struct audio_file_data *afd)
465 free(afd->afhi.chunk_table);
466 return para_munmap(afd->map.data, afd->map.size);
469 static enum play_mode init_admissible_files(void)
472 char *arg = conf.afs_initial_mode_arg;
474 if (conf.afs_initial_mode_given) {
475 if (!strncmp(arg, "p:", 2)) {
476 ret = playlist_open(arg + 2);
478 return PLAY_MODE_PLAYLIST;
481 if (!strncmp(arg, "m:", 2)) {
482 ret = change_current_mood(arg + 2);
484 return PLAY_MODE_MOOD;
487 PARA_ERROR_LOG("bad afs initial mode arg: %s\n", arg);
491 PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));
492 PARA_NOTICE_LOG("defaulting to dummy mood\n");
493 change_current_mood(""); /* always successful */
494 return PLAY_MODE_MOOD;
497 static int setup_command_socket_or_die(void)
500 char *socket_name = conf.afs_socket_arg;
501 struct sockaddr_un unix_addr;
504 ret = create_local_socket(socket_name, &unix_addr,
505 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IWOTH);
507 PARA_EMERG_LOG("%s: %s\n", PARA_STRERROR(-ret), socket_name);
510 if (listen(ret , 5) < 0) {
511 PARA_EMERG_LOG("%s", "can not listen on socket\n");
514 PARA_INFO_LOG("listening on command socket %s (fd %d)\n", socket_name,
519 static void close_afs_tables(void)
522 PARA_NOTICE_LOG("closing afs_tables\n");
523 for (i = 0; i < NUM_AFS_TABLES; i++)
524 afs_tables[i].close();
527 static char *database_dir;
529 static void get_database_dir(void)
532 if (conf.afs_database_dir_given)
533 database_dir = para_strdup(conf.afs_database_dir_arg);
535 char *home = para_homedir();
536 database_dir = make_message(
537 "%s/.paraslash/afs_database", home);
541 PARA_INFO_LOG("afs_database dir %s\n", database_dir);
544 static int make_database_dir(void)
549 ret = para_mkdir(database_dir, 0777);
550 if (ret >= 0 || is_errno(-ret, EEXIST))
555 static int open_afs_tables(void)
560 for (i = 0; i < NUM_AFS_TABLES; i++) {
561 ret = afs_tables[i].open(database_dir);
564 PARA_ERROR_LOG("%s init: %s\n", afs_tables[i].name,
565 PARA_STRERROR(-ret));
570 afs_tables[i].close();
575 static int server_socket;
576 static struct command_task command_task_struct;
577 static struct signal_task signal_task_struct;
579 static void unregister_tasks(void)
581 unregister_task(&command_task_struct.task);
582 unregister_task(&signal_task_struct.task);
585 static void signal_pre_select(struct sched *s, struct task *t)
587 struct signal_task *st = t->private_data;
589 para_fd_set(st->fd, &s->rfds, &s->max_fileno);
592 static void signal_post_select(struct sched *s, struct task *t)
594 struct signal_task *st = t->private_data;
596 if (!FD_ISSET(st->fd, &s->rfds))
598 st->signum = para_next_signal();
600 if (st->signum == SIGUSR1)
601 return; /* ignore SIGUSR1 */
602 if (st->signum == SIGHUP) {
604 t->ret = open_afs_tables();
607 PARA_NOTICE_LOG("caught signal %d\n", st->signum);
608 t->ret = -E_AFS_SIGNAL;
612 static void register_signal_task(void)
614 struct signal_task *st = &signal_task_struct;
615 st->fd = para_signal_init();
616 PARA_INFO_LOG("signal pipe: fd %d\n", st->fd);
617 para_install_sighandler(SIGINT);
618 para_install_sighandler(SIGTERM);
619 para_install_sighandler(SIGPIPE);
620 para_install_sighandler(SIGHUP);
622 st->task.pre_select = signal_pre_select;
623 st->task.post_select = signal_post_select;
624 st->task.private_data = st;
625 sprintf(st->task.status, "signal task");
626 register_task(&st->task);
629 static struct list_head afs_client_list;
632 struct list_head node;
634 struct timeval connect_time;
637 static void command_pre_select(struct sched *s, struct task *t)
639 struct command_task *ct = t->private_data;
640 struct afs_client *client;
642 para_fd_set(ct->fd, &s->rfds, &s->max_fileno);
643 list_for_each_entry(client, &afs_client_list, node)
644 para_fd_set(client->fd, &s->rfds, &s->max_fileno);
649 * On errors, negative value is written to fd.
650 * On success: If query produced a result, the result_shmid is written to fd.
651 * Otherwise, zero is written.
653 static int call_callback(int fd, int query_shmid)
655 void *query_shm, *result_shm;
656 struct callback_query *cq;
657 struct callback_result *cr;
658 struct osl_object query, result = {.data = NULL};
659 int result_shmid = -1, ret, ret2;
661 ret = shm_attach(query_shmid, ATTACH_RW, &query_shm);
665 query.data = (char *)query_shm + sizeof(*cq);
666 query.size = cq->query_size;
667 ret = cq->handler(&query, &result);
668 ret2 = shm_detach(query_shm);
669 if (ret2 < 0 && ret >= 0)
674 if (!result.data || !result.size)
676 ret = shm_new(result.size + sizeof(struct callback_result));
680 ret = shm_attach(result_shmid, ATTACH_RW, &result_shm);
684 cr->result_size = result.size;
685 memcpy(result_shm + sizeof(*cr), result.data, result.size);
686 ret = shm_detach(result_shm);
692 ret2 = send_bin_buffer(fd, (char *)&ret, sizeof(int));
693 if (ret < 0 || ret2 < 0) {
694 if (result_shmid >= 0)
695 if (shm_destroy(result_shmid) < 0)
696 PARA_ERROR_LOG("destroy result failed\n");
703 static void execute_afs_command(int fd, uint32_t expected_cookie)
707 char buf[sizeof(cookie) + sizeof(query_shmid)];
708 int ret = recv_bin_buffer(fd, buf, sizeof(buf));
711 PARA_NOTICE_LOG("%s\n", PARA_STRERROR(-ret));
714 if (ret != sizeof(buf)) {
715 PARA_NOTICE_LOG("short read (%d bytes, expected %lu)\n",
716 ret, (long unsigned) sizeof(buf));
719 cookie = *(uint32_t *)buf;
720 if (cookie != expected_cookie) {
721 PARA_NOTICE_LOG("received invalid cookie(got %u, expected %u)\n",
722 (unsigned)cookie, (unsigned)expected_cookie);
725 query_shmid = *(int *)(buf + sizeof(cookie));
726 if (query_shmid < 0) {
727 PARA_WARNING_LOG("received invalid query shmid %d)\n",
731 /* Ignore return value: Errors might be OK here. */
732 call_callback(fd, query_shmid);
735 /** Shutdown connection if query has not arrived until this many seconds. */
736 #define AFS_CLIENT_TIMEOUT 3
738 static void command_post_select(struct sched *s, struct task *t)
740 struct command_task *ct = t->private_data;
741 struct sockaddr_un unix_addr;
742 struct afs_client *client, *tmp;
744 /* First, check the list of connected clients. */
745 list_for_each_entry_safe(client, tmp, &afs_client_list, node) {
746 if (FD_ISSET(client->fd, &s->rfds))
747 execute_afs_command(client->fd, ct->cookie);
748 else { /* prevent bogus connection flooding */
750 tv_diff(now, &client->connect_time, &diff);
751 if (diff.tv_sec < AFS_CLIENT_TIMEOUT)
753 PARA_WARNING_LOG("connection timeout\n");
756 list_del(&client->node);
759 /* Next, accept connections on the local socket. */
760 if (!FD_ISSET(ct->fd, &s->rfds))
762 t->ret = para_accept(ct->fd, &unix_addr, sizeof(unix_addr));
764 PARA_NOTICE_LOG("%s\n", PARA_STRERROR(-t->ret));
767 client = para_malloc(sizeof(*client));
769 client->connect_time = *now;
770 para_list_add(&client->node, &afs_client_list);
775 static void register_command_task(uint32_t cookie)
777 struct command_task *ct = &command_task_struct;
778 ct->fd = setup_command_socket_or_die();
781 ct->task.pre_select = command_pre_select;
782 ct->task.post_select = command_post_select;
783 ct->task.private_data = ct;
784 sprintf(ct->task.status, "command task");
785 register_task(&ct->task);
788 static void register_tasks(uint32_t cookie)
790 register_signal_task();
791 register_command_task(cookie);
795 * Initialize the audio file selector process.
797 * \param cookie The value used for "authentication".
798 * \param socket_fd File descriptor used for communication with the server.
800 __noreturn void afs_init(uint32_t cookie, int socket_fd)
802 enum play_mode current_play_mode;
806 INIT_LIST_HEAD(&afs_client_list);
807 for (i = 0; i < NUM_AFS_TABLES; i++)
808 afs_tables[i].init(&afs_tables[i]);
809 ret = open_afs_tables();
812 PARA_EMERG_LOG("%s\n", PARA_STRERROR(-ret));
815 server_socket = socket_fd;
816 ret = mark_fd_nonblock(server_socket);
819 PARA_INFO_LOG("server_socket: %d, afs_socket_cookie: %u\n",
820 server_socket, (unsigned) cookie);
821 current_play_mode = init_admissible_files();
822 register_tasks(cookie);
823 s.default_timeout.tv_sec = 0;
824 s.default_timeout.tv_usec = 99 * 1000;
827 PARA_EMERG_LOG("%s\n", PARA_STRERROR(-ret));
832 static int create_tables_callback(const struct osl_object *query,
833 __a_unused struct osl_object *result)
835 uint32_t table_mask = *(uint32_t *)query->data;
839 for (i = 0; i < NUM_AFS_TABLES; i++) {
840 struct afs_table *t = &afs_tables[i];
842 if (!(table_mask & (1 << i)))
846 ret = t->create(database_dir);
850 ret = open_afs_tables();
851 return ret < 0? ret: 0;
854 int com_init(int fd, int argc, char * const * const argv)
857 uint32_t table_mask = (1 << (NUM_AFS_TABLES + 1)) - 1;
858 struct osl_object query = {.data = &table_mask,
859 .size = sizeof(table_mask)};
861 ret = make_database_dir();
866 for (i = 1; i < argc; i++) {
867 for (j = 0; j < NUM_AFS_TABLES; j++) {
868 struct afs_table *t = &afs_tables[j];
870 if (strcmp(argv[i], t->name))
872 table_mask |= (1 << j);
875 if (j == NUM_AFS_TABLES)
876 return -E_BAD_TABLE_NAME;
879 ret = send_callback_request(create_tables_callback, &query, NULL);
882 return send_va_buffer(fd, "successfully created afs table(s)\n");
886 * Flags for the check command.
890 enum com_check_flags {
891 /** Check the audio file table. */
893 /** Check the mood table. */
895 /** Check the playlist table. */
899 int com_check(int fd, int argc, char * const * const argv)
903 struct osl_object result;
905 for (i = 1; i < argc; i++) {
906 const char *arg = argv[i];
909 if (!strcmp(arg, "--")) {
913 if (!strcmp(arg, "-a")) {
917 if (!strcmp(arg, "-p")) {
918 flags |= CHECK_PLAYLISTS;
921 if (!strcmp(arg, "-m")) {
922 flags |= CHECK_MOODS;
925 return -E_AFS_SYNTAX;
928 return -E_AFS_SYNTAX;
931 if (flags & CHECK_AFT) {
932 ret = send_callback_request(aft_check_callback, NULL, &result);
936 ret = send_buffer(fd, (char *) result.data);
942 if (flags & CHECK_PLAYLISTS) {
943 ret = send_callback_request(playlist_check_callback, NULL, &result);
947 ret = send_buffer(fd, (char *) result.data);
953 if (flags & CHECK_MOODS) {
954 ret = send_callback_request(mood_check_callback, NULL, &result);
958 ret = send_buffer(fd, (char *) result.data);