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. */
10 #include "server.cmdline.h"
15 #include <dirent.h> /* readdir() */
27 /** The osl tables used by afs. \sa blob.c. */
29 /** Contains audio file information. See aft.c. */
31 /** The table for the paraslash attributes. See attribute.c. */
34 * Paraslash's scoring system is based on Gaussian normal
35 * distributions, and the relevant data is stored in the rbtrees of an
36 * osl table containing only volatile columns. See score.c for
41 * A standard blob table containing the mood definitions. For details
45 /** A blob table containing lyrics on a per-song basis. */
47 /** Another blob table for images (for example album cover art). */
49 /** Yet another blob table for storing standard playlists. */
51 /** How many tables are in use? */
55 static struct table_info afs_tables[NUM_AFS_TABLES];
58 /** The file descriptor for the local socket. */
61 * Value sent by the command handlers to identify themselves as
62 * children of the running para_server.
65 /** The associated task structure. */
70 * A random number used to "authenticate" the connection.
72 * para_server picks this number by random before forking the afs process. The
73 * command handlers write this number together with the id of the shared memory
74 * area containing the query. This way, a malicious local user has to know this
75 * number to be able to cause the afs process to crash by sending fake queries.
77 extern uint32_t afs_socket_cookie;
80 * Struct to let command handlers execute a callback in afs context.
82 * Commands that need to change the state of afs can't change the relevant data
83 * structures directly because commands are executed in a child process, i.e.
84 * they get their own virtual address space.
86 * This structure is used by \p send_callback_request() (executed from handler
87 * context) in order to let the afs process call the specified function. An
88 * instance of that structure is written to a shared memory area together with
89 * the arguments to the callback function. The identifier of the shared memory
90 * area is written to the command socket.
92 * The afs process accepts connections on the command socket and reads the
93 * shared memory id, attaches the corresponing area, calls the given handler to
94 * perform the desired action and to optionally compute a result.
96 * The result and a \p callback_result structure is then written to another
97 * shared memory area. The identifier for that area is written to the handler's
98 * command socket, so that the handler process can read the id, attach the
99 * shared memory area and use the result.
101 * \sa struct callback_result.
103 struct callback_query {
104 /** The function to be called. */
105 callback_function *handler;
106 /** The number of bytes of the query */
111 * Structure embedded in the result of a callback.
113 * If the callback produced a result, an instance of that structure is embeeded
114 * into the shared memory area holding the result, mainly to let the command
115 * handler know the size of the result.
117 * \sa struct callback_query.
119 struct callback_result {
120 /** The number of bytes of the result. */
125 * Ask the parent process to call a given function.
127 * \param f The function to be called.
128 * \param query Pointer to arbitrary data for the callback.
129 * \param result Callback result will be stored here.
131 * This function creates a shared memory area, copies the buffer pointed to by
132 * \a buf to that area and notifies the afs process that \a f should be
135 * \return Negative, on errors, the return value of the callback function
138 * \sa send_option_arg_callback_request(), send_standard_callback_request().
140 int send_callback_request(callback_function *f, struct osl_object *query,
141 struct osl_object *result)
143 struct callback_query *cq;
144 struct callback_result *cr;
145 int ret, fd = -1, query_shmid, result_shmid;
146 void *query_shm, *result_shm;
147 char buf[sizeof(afs_socket_cookie) + sizeof(int)];
148 struct sockaddr_un unix_addr;
149 size_t query_shm_size = sizeof(*cq);
152 query_shm_size += query->size;
153 ret = shm_new(query_shm_size);
157 ret = shm_attach(query_shmid, ATTACH_RW, &query_shm);
162 cq->query_size = query_shm_size - sizeof(*cq);
165 memcpy(query_shm + sizeof(*cq), query->data, query->size);
166 ret = shm_detach(query_shm);
170 *(uint32_t *) buf = afs_socket_cookie;
171 *(int *) (buf + sizeof(afs_socket_cookie)) = query_shmid;
173 ret = get_stream_socket(PF_UNIX);
177 ret = init_unix_addr(&unix_addr, conf.afs_socket_arg);
180 ret = PARA_CONNECT(fd, &unix_addr);
183 ret = send_bin_buffer(fd, buf, sizeof(buf));
186 ret = recv_bin_buffer(fd, buf, sizeof(buf));
189 if (ret != sizeof(int)) {
197 ret = shm_attach(result_shmid, ATTACH_RO, &result_shm);
201 result->size = cr->result_size;
202 result->data = para_malloc(result->size);
203 memcpy(result->data, result_shm + sizeof(*cr), result->size);
204 ret = shm_detach(result_shm);
206 PARA_ERROR_LOG("can not detach result\n");
208 PARA_ERROR_LOG("attach result failed: %d\n", ret);
209 if (shm_destroy(result_shmid) < 0)
210 PARA_ERROR_LOG("destroy result failed\n");
213 if (shm_destroy(query_shmid) < 0)
214 PARA_ERROR_LOG("%s\n", "shm destroy error");
217 // PARA_DEBUG_LOG("callback_ret: %d\n", ret);
222 * Send a callback request passing an options structure and an argument vector.
224 * \param options pointer to an arbitrary data structure.
225 * \param argc Argument count.
226 * \param argv Standard argument vector.
227 * \param f The callback function.
228 * \param result The result of the query is stored here.
230 * Some commands have a couple of options that are parsed in child context for
231 * syntactic correctness and are stored in a special options structure for that
232 * command. This function allows to pass such a structure together with a list
233 * of further arguments (often a list of audio files) to the parent process.
235 * \sa send_standard_callback_request(), send_callback_request().
237 int send_option_arg_callback_request(struct osl_object *options,
238 int argc, char * const * const argv, callback_function *f,
239 struct osl_object *result)
243 struct osl_object query = {.size = options? options->size : 0};
245 for (i = 0; i < argc; i++)
246 query.size += strlen(argv[i]) + 1;
247 query.data = para_malloc(query.size);
250 memcpy(query.data, options->data, options->size);
253 for (i = 0; i < argc; i++) {
254 strcpy(p, argv[i]); /* OK */
255 p += strlen(argv[i]) + 1;
257 ret = send_callback_request(f, &query, result);
263 * Send a callback request with an argument vector only.
265 * \param argc The same meaning as in send_option_arg_callback_request().
266 * \param argv The same meaning as in send_option_arg_callback_request().
267 * \param f The same meaning as in send_option_arg_callback_request().
268 * \param result The same meaning as in send_option_arg_callback_request().
270 * This is similar to send_option_arg_callback_request(), but no options buffer
271 * is passed to the parent process.
273 * \return The return value of the underlying call to
274 * send_option_arg_callback_request().
276 int send_standard_callback_request(int argc, char * const * const argv,
277 callback_function *f, struct osl_object *result)
279 return send_option_arg_callback_request(NULL, argc, argv, f, result);
282 static int action_if_pattern_matches(struct osl_row *row, void *data)
284 struct pattern_match_data *pmd = data;
285 struct osl_object name_obj;
286 const char *p, *name;
287 int ret = osl_get_object(pmd->table, row, pmd->match_col_num, &name_obj);
288 const char *pattern_txt = (const char *)pmd->patterns.data;
292 name = (char *)name_obj.data;
293 if ((!name || !*name) && (pmd->pm_flags & PM_SKIP_EMPTY_NAME))
295 if (!pmd->patterns.size && (pmd->pm_flags & PM_NO_PATTERN_MATCHES_EVERYTHING))
296 return pmd->action(pmd->table, row, name, pmd->data);
297 for (p = pattern_txt; p < pattern_txt + pmd->patterns.size;
298 p += strlen(p) + 1) {
299 ret = fnmatch(p, name, pmd->fnmatch_flags);
300 if (ret == FNM_NOMATCH)
304 return pmd->action(pmd->table, row, name, pmd->data);
309 int for_each_matching_row(struct pattern_match_data *pmd)
311 if (pmd->pm_flags & PM_REVERSE_LOOP)
312 return osl_rbtree_loop_reverse(pmd->table, pmd->loop_col_num, pmd,
313 action_if_pattern_matches);
314 return osl_rbtree_loop(pmd->table, pmd->loop_col_num, pmd,
315 action_if_pattern_matches);
319 * Compare two osl objects of string type.
321 * \param obj1 Pointer to the first object.
322 * \param obj2 Pointer to the second object.
324 * In any case, only \p MIN(obj1->size, obj2->size) characters of each string
325 * are taken into account.
327 * \return It returns an integer less than, equal to, or greater than zero if
328 * \a obj1 is found, respectively, to be less than, to match, or be greater than
331 * \sa strcmp(3), strncmp(3), osl_compare_func.
333 int string_compare(const struct osl_object *obj1, const struct osl_object *obj2)
335 const char *str1 = (const char *)obj1->data;
336 const char *str2 = (const char *)obj2->data;
337 return strncmp(str1, str2, PARA_MIN(obj1->size, obj2->size));
341 * A wrapper for strtol(3).
343 * \param str The string to be converted to a long integer.
344 * \param result The converted value is stored here.
346 * \return Positive on success, -E_ATOL on errors.
348 * \sa strtol(3), atoi(3).
350 int para_atol(const char *str, long *result)
356 errno = 0; /* To distinguish success/failure after call */
357 val = strtol(str, &endptr, base);
359 if (errno == ERANGE && (val == LONG_MAX || val == LONG_MIN))
360 goto out; /* overflow */
361 if (errno != 0 && val == 0)
362 goto out; /* other error */
364 goto out; /* No digits were found */
366 goto out; /* Further characters after number */
375 * write input from fd to dynamically allocated buffer,
376 * but maximal max_size byte.
378 static int fd2buf(int fd, unsigned max_size, struct osl_object *obj)
380 const size_t chunk_size = 1024;
381 size_t size = 2048, received = 0;
383 char *buf = para_malloc(size);
386 ret = recv_bin_buffer(fd, buf + received, chunk_size);
390 if (received + chunk_size >= size) {
392 ret = -E_INPUT_TOO_LARGE;
395 buf = para_realloc(buf, size);
399 obj->size = received;
406 * Read data from a file descriptor, and send it to the afs process.
408 * \param fd File descriptor to read data from.
409 * \param arg_obj Pointer to the arguments to \a f.
410 * \param f The callback function.
411 * \param max_len Don't read more than that many bytes from stdin.
412 * \param result The result of the query is stored here.
414 * This function is used by commands that wish to let para_server store
415 * arbitrary data specified by the user (for instance the add_blob family of
416 * commands). First, at most \a max_len bytes are read from \a fd, the result
417 * is concatenated with the buffer given by \a arg_obj, and the combined buffer
418 * is made available to the parent process via shared memory.
420 * \return Negative on errors, the return value of the underlying call to
421 * send_callback_request() otherwise.
423 int stdin_command(int fd, struct osl_object *arg_obj, callback_function *f,
424 unsigned max_len, struct osl_object *result)
426 struct osl_object query, stdin_obj;
429 ret = send_buffer(fd, AWAITING_DATA_MSG);
432 ret = fd2buf(fd, max_len, &stdin_obj);
435 query.size = arg_obj->size + stdin_obj.size;
436 query.data = para_malloc(query.size);
437 memcpy(query.data, arg_obj->data, arg_obj->size);
438 memcpy((char *)query.data + arg_obj->size, stdin_obj.data, stdin_obj.size);
439 free(stdin_obj.data);
440 ret = send_callback_request(f, &query, result);
446 * Open the audio file with highest score.
448 * \param afd Audio file data is returned here.
450 * This stores all information for streaming the "best" audio file
451 * in the \a afd structure.
453 * \return Positive on success, negative on errors.
455 * \sa close_audio_file(), open_and_update_audio_file().
457 int open_next_audio_file(struct audio_file_data *afd)
459 struct osl_row *aft_row;
462 ret = score_get_best(&aft_row, &afd->score);
465 ret = open_and_update_audio_file(aft_row, afd);
472 * Free all resources which were allocated by open_next_audio_file().
474 * \param afd The structure previously filled in by open_next_audio_file().
476 * \return The return value of the underlying call to para_munmap().
478 * \sa open_next_audio_file().
480 int close_audio_file(struct audio_file_data *afd)
482 free(afd->afhi.chunk_table);
483 return para_munmap(afd->map.data, afd->map.size);
487 static void play_loop(enum play_mode current_play_mode)
490 struct audio_file_data afd;
492 afd.current_play_mode = current_play_mode;
493 for (i = 0; i < 0; i++) {
494 ret = open_next_audio_file(&afd);
496 PARA_ERROR_LOG("failed to open next audio file: %d\n", ret);
499 PARA_NOTICE_LOG("next audio file: %s, score: %li\n", afd.path, afd.score);
501 close_audio_file(&afd);
507 static enum play_mode init_admissible_files(void)
510 char *given_mood, *given_playlist;
512 given_mood = "mood_that_was_given_at_the_command_line";
513 given_playlist = "given_playlist";
516 ret = change_current_mood(given_mood);
519 PARA_WARNING_LOG("ignoring playlist %s\n",
521 return PLAY_MODE_MOOD;
524 if (given_playlist) {
525 ret = playlist_open(given_playlist);
527 return PLAY_MODE_PLAYLIST;
529 ret = change_current_mood(NULL); /* open first available mood */
531 return PLAY_MODE_MOOD;
532 change_current_mood(""); /* open dummy mood, always successful */
533 return PLAY_MODE_MOOD;
536 static int setup_command_socket_or_die(void)
539 char *socket_name = conf.afs_socket_arg;
540 struct sockaddr_un unix_addr;
543 ret = create_local_socket(socket_name, &unix_addr,
544 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IWOTH);
546 PARA_EMERG_LOG("%s: %s\n", PARA_STRERROR(-ret), socket_name);
549 if (listen(ret , 5) < 0) {
550 PARA_EMERG_LOG("%s", "can not listen on socket\n");
553 PARA_INFO_LOG("listening on command socket %s (fd %d)\n", socket_name,
558 static int server_socket;
559 static struct command_task command_task_struct;
560 static struct signal_task signal_task_struct;
562 static void unregister_tasks(void)
564 unregister_task(&command_task_struct.task);
565 unregister_task(&signal_task_struct.task);
568 static void close_afs_tables(enum osl_close_flags flags)
570 PARA_NOTICE_LOG("closing afs_tables\n");
571 score_shutdown(flags);
572 attribute_shutdown(flags);
573 close_current_mood();
575 moods_shutdown(flags);
576 playlists_shutdown(flags);
577 lyrics_shutdown(flags);
578 images_shutdown(flags);
582 static void signal_pre_select(struct sched *s, struct task *t)
584 struct signal_task *st = t->private_data;
586 para_fd_set(st->fd, &s->rfds, &s->max_fileno);
589 static void signal_post_select(struct sched *s, struct task *t)
591 struct signal_task *st = t->private_data;
593 if (!FD_ISSET(st->fd, &s->rfds))
595 st->signum = para_next_signal();
597 if (st->signum == SIGUSR1)
598 return; /* ignore SIGUSR1 */
599 PARA_NOTICE_LOG("caught signal %d\n", st->signum);
600 t->ret = -E_SIGNAL_CAUGHT;
604 static void register_signal_task(void)
606 struct signal_task *st = &signal_task_struct;
607 st->fd = para_signal_init();
608 PARA_INFO_LOG("signal pipe: fd %d\n", st->fd);
609 para_install_sighandler(SIGINT);
610 para_install_sighandler(SIGTERM);
611 para_install_sighandler(SIGPIPE);
613 st->task.pre_select = signal_pre_select;
614 st->task.post_select = signal_post_select;
615 st->task.private_data = st;
616 sprintf(st->task.status, "signal task");
617 register_task(&st->task);
620 static void command_pre_select(struct sched *s, struct task *t)
622 struct command_task *ct = t->private_data;
624 para_fd_set(ct->fd, &s->rfds, &s->max_fileno);
628 * On errors, negative value is written to fd.
629 * On success: If query produced a result, the result_shmid is written to fd.
630 * Otherwise, zero is written.
632 static int call_callback(int fd, int query_shmid)
634 void *query_shm, *result_shm;
635 struct callback_query *cq;
636 struct callback_result *cr;
637 struct osl_object query, result = {.data = NULL};
638 int result_shmid = -1, ret, ret2;
640 ret = shm_attach(query_shmid, ATTACH_RW, &query_shm);
644 query.data = (char *)query_shm + sizeof(*cq);
645 query.size = cq->query_size;
646 ret = cq->handler(&query, &result);
647 ret2 = shm_detach(query_shm);
648 if (ret2 < 0 && ret >= 0)
653 if (!result.data || !result.size)
655 ret = shm_new(result.size + sizeof(struct callback_result));
659 ret = shm_attach(result_shmid, ATTACH_RW, &result_shm);
663 cr->result_size = result.size;
664 memcpy(result_shm + sizeof(*cr), result.data, result.size);
665 ret = shm_detach(result_shm);
671 ret2 = send_bin_buffer(fd, (char *)&ret, sizeof(int));
672 if (ret < 0 || ret2 < 0) {
673 if (result_shmid >= 0)
674 if (shm_destroy(result_shmid) < 0)
675 PARA_ERROR_LOG("destroy result failed\n");
682 static void command_post_select(struct sched *s, struct task *t)
684 struct command_task *ct = t->private_data;
685 struct sockaddr_un unix_addr;
686 char buf[sizeof(uint32_t) + sizeof(int)];
691 if (!FD_ISSET(ct->fd, &s->rfds))
693 t->ret = para_accept(ct->fd, &unix_addr, sizeof(unix_addr));
697 * The following errors may be caused by a malicious local user. So do
698 * not return an error in this case as this would terminate para_afs
702 /* FIXME: This is easily dosable (peer doesn't send data) */
703 t->ret = recv_bin_buffer(fd, buf, sizeof(buf));
705 PARA_NOTICE_LOG("%s (%d)\n", PARA_STRERROR(-t->ret), t->ret);
708 if (t->ret != sizeof(buf)) {
709 PARA_NOTICE_LOG("short read (%d bytes, expected %lu)\n",
710 t->ret, (long unsigned) sizeof(buf));
713 cookie = *(uint32_t *)buf;
714 if (cookie != ct->cookie) {
715 PARA_NOTICE_LOG("received invalid cookie(got %u, expected %u)\n",
716 (unsigned)cookie, (unsigned)ct->cookie);
719 query_shmid = *(int *)(buf + sizeof(cookie));
720 if (query_shmid < 0) {
721 PARA_WARNING_LOG("received invalid query shmid %d)\n",
725 /* Ignore return value: Errors might be ok here. */
726 call_callback(fd, query_shmid);
732 static void register_command_task(uint32_t cookie)
734 struct command_task *ct = &command_task_struct;
735 ct->fd = setup_command_socket_or_die();
738 ct->task.pre_select = command_pre_select;
739 ct->task.post_select = command_post_select;
740 ct->task.private_data = ct;
741 sprintf(ct->task.status, "command task");
742 register_task(&ct->task);
745 void register_tasks(uint32_t cookie)
747 register_signal_task();
748 register_command_task(cookie);
751 static char *database_dir;
753 static int make_database_dir(void)
758 if (conf.afs_database_dir_given)
759 database_dir = para_strdup(conf.afs_database_dir_arg);
761 char *home = para_homedir();
762 database_dir = make_message(
763 "%s/.paraslash/afs_database", home);
767 PARA_INFO_LOG("afs_database dir %s\n", database_dir);
768 ret = para_mkdir(database_dir, 0777);
769 if (ret >= 0 || ret == -E_EXIST)
776 static int open_afs_tables(void)
778 int ret = make_database_dir();
782 ret = attribute_init(&afs_tables[TBLNUM_ATTRIBUTES], database_dir);
785 ret = moods_init(&afs_tables[TBLNUM_MOODS], database_dir);
787 goto moods_init_error;
788 ret = playlists_init(&afs_tables[TBLNUM_PLAYLIST], database_dir);
790 goto playlists_init_error;
791 ret = lyrics_init(&afs_tables[TBLNUM_LYRICS], database_dir);
793 goto lyrics_init_error;
794 ret = images_init(&afs_tables[TBLNUM_IMAGES], database_dir);
796 goto images_init_error;
797 ret = score_init(&afs_tables[TBLNUM_SCORES], database_dir);
799 goto score_init_error;
800 ret = aft_init(&afs_tables[TBLNUM_AUDIO_FILES], database_dir);
806 score_shutdown(OSL_MARK_CLEAN);
808 images_shutdown(OSL_MARK_CLEAN);
810 lyrics_shutdown(OSL_MARK_CLEAN);
812 playlists_shutdown(OSL_MARK_CLEAN);
813 playlists_init_error:
814 moods_shutdown(OSL_MARK_CLEAN);
816 attribute_shutdown(OSL_MARK_CLEAN);
820 __noreturn int afs_init(uint32_t cookie, int socket_fd)
822 enum play_mode current_play_mode;
824 int ret = open_afs_tables();
827 PARA_EMERG_LOG("%s\n", PARA_STRERROR(-ret));
830 server_socket = socket_fd;
831 ret = mark_fd_nonblock(server_socket);
834 PARA_INFO_LOG("server_socket: %d, afs_socket_cookie: %u\n",
835 server_socket, (unsigned) cookie);
836 current_play_mode = init_admissible_files();
837 register_tasks(cookie);
838 s.default_timeout.tv_sec = 0;
839 s.default_timeout.tv_usec = 99 * 1000;
842 PARA_EMERG_LOG("%s\n", PARA_STRERROR(-ret));
843 close_afs_tables(OSL_MARK_CLEAN);
847 static int create_tables_callback(const struct osl_object *query,
848 __a_unused struct osl_object *result)
850 uint32_t table_mask = *(uint32_t *)query->data;
853 close_afs_tables(OSL_MARK_CLEAN);
854 for (i = 0; i < NUM_AFS_TABLES; i++) {
855 struct table_info *ti = afs_tables + i;
857 if (ti->flags & TBLFLAG_SKIP_CREATE)
859 if (!(table_mask & (1 << i)))
861 ret = osl_create_table(ti->desc);
865 ret = open_afs_tables();
866 return ret < 0? ret: 0;
869 int com_init(int fd, int argc, char * const * const argv)
872 uint32_t table_mask = (1 << (NUM_AFS_TABLES + 1)) - 1;
873 struct osl_object query = {.data = &table_mask,
874 .size = sizeof(table_mask)};
878 for (i = 1; i < argc; i++) {
879 for (j = 0; j < NUM_AFS_TABLES; j++) {
880 struct table_info *ti = afs_tables + j;
882 if (ti->flags & TBLFLAG_SKIP_CREATE)
884 if (strcmp(argv[i], ti->desc->name))
886 table_mask |= (1 << j);
889 if (j == NUM_AFS_TABLES)
890 return -E_BAD_TABLE_NAME;
893 ret = send_callback_request(create_tables_callback, &query, NULL);
896 return send_va_buffer(fd, "successfully created afs table(s)\n");
899 enum com_check_flags {
905 int com_check(int fd, int argc, char * const * const argv)
909 struct osl_object result;
911 for (i = 1; i < argc; i++) {
912 const char *arg = argv[i];
915 if (!strcmp(arg, "--")) {
919 if (!strcmp(arg, "-a")) {
923 if (!strcmp(arg, "-p")) {
924 flags |= CHECK_PLAYLISTS;
927 if (!strcmp(arg, "-m")) {
928 flags |= CHECK_MOODS;
931 return -E_AFS_SYNTAX;
934 return -E_AFS_SYNTAX;
937 if (flags & CHECK_AFT) {
938 ret = send_callback_request(aft_check_callback, NULL, &result);
942 ret = send_buffer(fd, (char *) result.data);
948 if (flags & CHECK_PLAYLISTS) {
949 ret = send_callback_request(playlist_check_callback, NULL, &result);
953 ret = send_buffer(fd, (char *) result.data);
959 if (flags & CHECK_MOODS) {
960 ret = send_callback_request(mood_check_callback, NULL, &result);
964 ret = send_buffer(fd, (char *) result.data);