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. */
9 #include "server.cmdline.h"
14 #include <dirent.h> /* readdir() */
26 /** The osl tables used by afs. \sa blob.c. */
28 /** Contains audio file information. See aft.c. */
30 /** The table for the paraslash attributes. See attribute.c. */
33 * Paraslash's scoring system is based on Gaussian normal
34 * distributions, and the relevant data is stored in the rbtrees of an
35 * osl table containing only volatile columns. See score.c for
40 * A standard blob table containing the mood definitions. For details
44 /** A blob table containing lyrics on a per-song basis. */
46 /** Another blob table for images (for example album cover art). */
48 /** Yet another blob table for storing standard playlists. */
50 /** How many tables are in use? */
54 static struct table_info afs_tables[NUM_AFS_TABLES];
57 /** The file descriptor for the local socket. */
60 * Value sent by the command handlers to identify themselves as
61 * children of the running para_server.
64 /** The associated task structure. */
69 * A random number used to "authenticate" the connection.
71 * para_server picks this number by random before forking the afs process. The
72 * command handlers write this number together with the id of the shared memory
73 * area containing the query. This way, a malicious local user has to know this
74 * number to be able to cause the afs process to crash by sending fake queries.
76 extern uint32_t afs_socket_cookie;
79 * Struct to let command handlers execute a callback in afs context.
81 * Commands that need to change the state of afs can't change the relevant data
82 * structures directly because commands are executed in a child process, i.e.
83 * they get their own virtual address space.
85 * This structure is used by \p send_callback_request() (executed from handler
86 * context) in order to let the afs process call the specified function. An
87 * instance of that structure is written to a shared memory area together with
88 * the arguments to the callback function. The identifier of the shared memory
89 * area is written to the command socket.
91 * The afs process accepts connections on the command socket and reads the
92 * shared memory id, attaches the corresponing area, calls the given handler to
93 * perform the desired action and to optionally compute a result.
95 * The result and a \p callback_result structure is then written to another
96 * shared memory area. The identifier for that area is written to the handler's
97 * command socket, so that the handler process can read the id, attach the
98 * shared memory area and use the result.
100 * \sa struct callback_result.
102 struct callback_query {
103 /** The function to be called. */
104 callback_function *handler;
105 /** The number of bytes of the query */
110 * Structure embedded in the result of a callback.
112 * If the callback produced a result, an instance of that structure is embeeded
113 * into the shared memory area holding the result, mainly to let the command
114 * handler know the size of the result.
116 * \sa struct callback_query.
118 struct callback_result {
119 /** The number of bytes of the result. */
124 * Ask the parent process to call a given function.
126 * \param f The function to be called.
127 * \param query Pointer to arbitrary data for the callback.
128 * \param result Callback result will be stored here.
130 * This function creates a shared memory area, copies the buffer pointed to by
131 * \a buf to that area and notifies the afs process that \a f should be
134 * \return Negative, on errors, the return value of the callback function
137 * \sa send_option_arg_callback_request(), send_standard_callback_request().
139 int send_callback_request(callback_function *f, struct osl_object *query,
140 struct osl_object *result)
142 struct callback_query *cq;
143 struct callback_result *cr;
144 int ret, fd = -1, query_shmid, result_shmid;
145 void *query_shm, *result_shm;
146 char buf[sizeof(afs_socket_cookie) + sizeof(int)];
147 // char *tmpsocket_name;
148 struct sockaddr_un unix_addr;
150 assert(query->data && query->size);
151 ret = shm_new(query->size + sizeof(*cq));
155 ret = shm_attach(query_shmid, ATTACH_RW, &query_shm);
160 cq->query_size = query->size;
162 memcpy(query_shm + sizeof(*cq), query->data, query->size);
163 ret = shm_detach(query_shm);
167 *(uint32_t *) buf = afs_socket_cookie;
168 *(int *) (buf + sizeof(afs_socket_cookie)) = query_shmid;
170 ret = get_stream_socket(PF_UNIX);
174 ret = init_unix_addr(&unix_addr, conf.afs_socket_arg);
178 if (connect(fd, (struct sockaddr *)&unix_addr, sizeof(unix_addr)) < 0) /* FIXME: Use para_connect() */
180 ret = send_bin_buffer(fd, buf, sizeof(buf));
183 ret = recv_bin_buffer(fd, buf, sizeof(buf));
186 if (ret != sizeof(int)) {
194 ret = shm_attach(result_shmid, ATTACH_RO, &result_shm);
198 result->size = cr->result_size;
199 result->data = para_malloc(result->size);
200 memcpy(result->data, result_shm + sizeof(*cr), result->size);
201 ret = shm_detach(result_shm);
203 PARA_ERROR_LOG("can not detach result\n");
205 PARA_ERROR_LOG("attach result failed: %d\n", ret);
206 if (shm_destroy(result_shmid) < 0)
207 PARA_ERROR_LOG("destroy result failed\n");
210 if (shm_destroy(query_shmid) < 0)
211 PARA_ERROR_LOG("%s\n", "shm destroy error");
214 // PARA_DEBUG_LOG("callback_ret: %d\n", ret);
219 * Send a callback request passing an options structure and an argument vector.
221 * \param options pointer to an arbitrary data structure.
222 * \param argc Argument count.
223 * \param argv Standard argument vector.
224 * \param f The callback function.
225 * \param result The result of the query is stored here.
227 * Some commands have a couple of options that are parsed in child context for
228 * syntactic correctness and are stored in a special options structure for that
229 * command. This function allows to pass such a structure together with a list
230 * of further arguments (often a list of audio files) to the parent process.
232 * \sa send_standard_callback_request(), send_callback_request().
234 int send_option_arg_callback_request(struct osl_object *options,
235 int argc, char * const * const argv, callback_function *f,
236 struct osl_object *result)
240 struct osl_object query = {.size = options? options->size : 0};
242 for (i = 0; i < argc; i++)
243 query.size += strlen(argv[i]) + 1;
244 query.data = para_malloc(query.size);
247 memcpy(query.data, options->data, options->size);
250 for (i = 0; i < argc; i++) {
251 strcpy(p, argv[i]); /* OK */
252 p += strlen(argv[i]) + 1;
254 ret = send_callback_request(f, &query, result);
260 * Send a callback request with an argument vector only.
262 * \param argc The same meaning as in send_option_arg_callback_request().
263 * \param argv The same meaning as in send_option_arg_callback_request().
264 * \param f The same meaning as in send_option_arg_callback_request().
265 * \param result The same meaning as in send_option_arg_callback_request().
267 * This is similar to send_option_arg_callback_request(), but no options buffer
268 * is passed to the parent process.
270 * \return The return value of the underlying call to
271 * send_option_arg_callback_request().
273 int send_standard_callback_request(int argc, char * const * const argv,
274 callback_function *f, struct osl_object *result)
276 return send_option_arg_callback_request(NULL, argc, argv, f, result);
280 * Compare two osl objects of string type.
282 * \param obj1 Pointer to the first object.
283 * \param obj2 Pointer to the second object.
285 * In any case, only \p MIN(obj1->size, obj2->size) characters of each string
286 * are taken into account.
288 * \return It returns an integer less than, equal to, or greater than zero if
289 * \a obj1 is found, respectively, to be less than, to match, or be greater than
292 * \sa strcmp(3), strncmp(3), osl_compare_func.
294 int string_compare(const struct osl_object *obj1, const struct osl_object *obj2)
296 const char *str1 = (const char *)obj1->data;
297 const char *str2 = (const char *)obj2->data;
298 return strncmp(str1, str2, PARA_MIN(obj1->size, obj2->size));
302 * A wrapper for strtol(3).
304 * \param str The string to be converted to a long integer.
305 * \param result The converted value is stored here.
307 * \return Positive on success, -E_ATOL on errors.
309 * \sa strtol(3), atoi(3).
311 int para_atol(const char *str, long *result)
317 errno = 0; /* To distinguish success/failure after call */
318 val = strtol(str, &endptr, base);
320 if (errno == ERANGE && (val == LONG_MAX || val == LONG_MIN))
321 goto out; /* overflow */
322 if (errno != 0 && val == 0)
323 goto out; /* other error */
325 goto out; /* No digits were found */
327 goto out; /* Further characters after number */
336 * write input from fd to dynamically allocated char array,
337 * but maximal max_size byte. Return size.
339 static int fd2buf(int fd, char **buf, int max_size)
341 const size_t chunk_size = 1024;
346 *buf = para_malloc(size * sizeof(char));
348 while ((ret = read(fd, p, chunk_size)) > 0) {
350 if ((p - *buf) + chunk_size >= size) {
354 if (size > max_size) {
355 ret = -E_INPUT_TOO_LARGE;
358 tmp = para_realloc(*buf, size);
359 p = (p - *buf) + tmp;
375 * Read from stdin, and send the result to the parent process.
377 * \param arg_obj Pointer to the arguments to \a f.
378 * \param f The callback function.
379 * \param max_len Don't read more than that many bytes from stdin.
380 * \param result The result of the query is stored here.
382 * This function is used by commands that wish to let para_server store
383 * arbitrary data specified by the user (for instance the add_blob family of
384 * commands). First, at most \a max_len bytes are read from stdin, the result
385 * is concatenated with the buffer given by \a arg_obj, and the combined buffer
386 * is made available to the parent process via shared memory.
388 * \return Negative on errors, the return value of the underlying call to
389 * send_callback_request() otherwise.
391 int stdin_command(struct osl_object *arg_obj, callback_function *f,
392 unsigned max_len, struct osl_object *result)
396 struct osl_object query;
397 int ret = fd2buf(STDIN_FILENO, &stdin_buf, max_len);
402 query.size = arg_obj->size + stdin_len;
403 query.data = para_malloc(query.size);
404 memcpy(query.data, arg_obj->data, arg_obj->size);
405 memcpy((char *)query.data + arg_obj->size, stdin_buf, stdin_len);
407 ret = send_callback_request(f, &query, result);
413 * Open the audio file with highest score.
415 * \param afd Audio file data is returned here.
417 * This stores all information for streaming the "best" audio file
418 * in the \a afd structure.
420 * \return Positive on success, negative on errors.
422 * \sa close_audio_file(), open_and_update_audio_file().
424 int open_next_audio_file(struct audio_file_data *afd)
426 struct osl_row *aft_row;
429 ret = score_get_best(&aft_row, &afd->score);
432 ret = open_and_update_audio_file(aft_row, afd);
439 * Free all resources which were allocated by open_next_audio_file().
441 * \param afd The structure previously filled in by open_next_audio_file().
443 * \return The return value of the underlying call to para_munmap().
445 * \sa open_next_audio_file().
447 int close_audio_file(struct audio_file_data *afd)
449 free(afd->afhi.chunk_table);
450 return para_munmap(afd->map.data, afd->map.size);
454 static void play_loop(enum play_mode current_play_mode)
457 struct audio_file_data afd;
459 afd.current_play_mode = current_play_mode;
460 for (i = 0; i < 0; i++) {
461 ret = open_next_audio_file(&afd);
463 PARA_ERROR_LOG("failed to open next audio file: %d\n", ret);
466 PARA_NOTICE_LOG("next audio file: %s, score: %li\n", afd.path, afd.score);
468 close_audio_file(&afd);
474 static enum play_mode init_admissible_files(void)
477 char *given_mood, *given_playlist;
479 given_mood = "mood_that_was_given_at_the_command_line";
480 given_playlist = "given_playlist";
483 ret = mood_open(given_mood);
486 PARA_WARNING_LOG("ignoring playlist %s\n",
488 return PLAY_MODE_MOOD;
491 if (given_playlist) {
492 ret = playlist_open(given_playlist);
494 return PLAY_MODE_PLAYLIST;
496 ret = mood_open(NULL); /* open first available mood */
498 return PLAY_MODE_MOOD;
499 mood_open(""); /* open dummy mood, always successful */
500 return PLAY_MODE_MOOD;
503 static int setup_command_socket_or_die(void)
506 char *socket_name = conf.afs_socket_arg;
507 struct sockaddr_un unix_addr;
510 ret = create_local_socket(socket_name, &unix_addr,
511 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IWOTH);
513 PARA_EMERG_LOG("%s: %s\n", PARA_STRERROR(-ret), socket_name);
516 if (listen(ret , 5) < 0) {
517 PARA_EMERG_LOG("%s", "can not listen on socket\n");
520 PARA_INFO_LOG("listening on command socket %s (fd %d)\n", socket_name,
525 static int server_socket;
526 static struct command_task command_task_struct;
527 static struct signal_task signal_task_struct;
529 static void unregister_tasks(void)
531 unregister_task(&command_task_struct.task);
532 unregister_task(&signal_task_struct.task);
535 static void close_afs_tables(enum osl_close_flags flags)
537 PARA_NOTICE_LOG("closing afs_tables\n");
538 score_shutdown(flags);
539 attribute_shutdown(flags);
542 moods_shutdown(flags);
543 playlists_shutdown(flags);
544 lyrics_shutdown(flags);
545 images_shutdown(flags);
549 static void signal_pre_select(struct sched *s, struct task *t)
551 struct signal_task *st = t->private_data;
553 para_fd_set(st->fd, &s->rfds, &s->max_fileno);
556 static void signal_post_select(struct sched *s, struct task *t)
558 struct signal_task *st = t->private_data;
560 if (!FD_ISSET(st->fd, &s->rfds))
562 st->signum = para_next_signal();
563 PARA_NOTICE_LOG("caught signal %d\n", st->signum);
565 if (st->signum == SIGUSR1)
566 return; /* ignore SIGUSR1 */
567 t->ret = -E_SIGNAL_CAUGHT;
571 static void register_signal_task(void)
573 struct signal_task *st = &signal_task_struct;
574 st->fd = para_signal_init();
575 PARA_INFO_LOG("signal pipe: fd %d\n", st->fd);
576 para_install_sighandler(SIGINT);
577 para_install_sighandler(SIGTERM);
578 para_install_sighandler(SIGPIPE);
580 st->task.pre_select = signal_pre_select;
581 st->task.post_select = signal_post_select;
582 st->task.private_data = st;
583 sprintf(st->task.status, "signal task");
584 register_task(&st->task);
587 static void command_pre_select(struct sched *s, struct task *t)
589 struct command_task *ct = t->private_data;
591 para_fd_set(ct->fd, &s->rfds, &s->max_fileno);
595 * On errors, negative value is written to fd.
596 * On success: If query produced a result, the result_shmid is written to fd.
597 * Otherwise, zero is written.
599 static int call_callback(int fd, int query_shmid)
601 void *query_shm, *result_shm;
602 struct callback_query *cq;
603 struct callback_result *cr;
604 struct osl_object query, result = {.data = NULL};
605 int result_shmid = -1, ret, ret2;
607 ret = shm_attach(query_shmid, ATTACH_RW, &query_shm);
611 query.data = (char *)query_shm + sizeof(*cq);
612 query.size = cq->query_size;
613 ret = cq->handler(&query, &result);
614 ret2 = shm_detach(query_shm);
615 if (ret2 < 0 && ret >= 0)
620 if (!result.data || !result.size)
622 ret = shm_new(result.size + sizeof(struct callback_result));
626 ret = shm_attach(result_shmid, ATTACH_RW, &result_shm);
630 cr->result_size = result.size;
631 memcpy(result_shm + sizeof(*cr), result.data, result.size);
632 ret = shm_detach(result_shm);
638 ret2 = send_bin_buffer(fd, (char *)&ret, sizeof(int));
639 if (ret < 0 || ret2 < 0) {
640 if (result_shmid >= 0)
641 if (shm_destroy(result_shmid) < 0)
642 PARA_ERROR_LOG("destroy result failed\n");
649 static void command_post_select(struct sched *s, struct task *t)
651 struct command_task *ct = t->private_data;
652 struct sockaddr_un unix_addr;
653 char buf[sizeof(uint32_t) + sizeof(int)];
658 if (!FD_ISSET(ct->fd, &s->rfds))
660 t->ret = para_accept(ct->fd, &unix_addr, sizeof(unix_addr));
664 * The following errors may be caused by a malicious local user. So do
665 * not return an error in this case as this would terminate para_afs
669 /* FIXME: This is easily dosable (peer doesn't send data) */
670 t->ret = recv_bin_buffer(fd, buf, sizeof(buf));
672 PARA_NOTICE_LOG("%s (%d)\n", PARA_STRERROR(-t->ret), t->ret);
675 if (t->ret != sizeof(buf)) {
676 PARA_NOTICE_LOG("short read (%d bytes, expected %lu)\n",
677 t->ret, (long unsigned) sizeof(buf));
680 cookie = *(uint32_t *)buf;
681 if (cookie != ct->cookie) {
682 PARA_NOTICE_LOG("received invalid cookie(got %u, expected %u)\n",
683 (unsigned)cookie, (unsigned)ct->cookie);
686 query_shmid = *(int *)(buf + sizeof(cookie));
687 if (query_shmid < 0) {
688 PARA_WARNING_LOG("received invalid query shmid %d)\n",
692 /* Ignore return value: Errors might be ok here. */
693 call_callback(fd, query_shmid);
699 static void register_command_task(uint32_t cookie)
701 struct command_task *ct = &command_task_struct;
702 ct->fd = setup_command_socket_or_die();
705 ct->task.pre_select = command_pre_select;
706 ct->task.post_select = command_post_select;
707 ct->task.private_data = ct;
708 sprintf(ct->task.status, "command task");
709 register_task(&ct->task);
712 void register_tasks(uint32_t cookie)
714 register_signal_task();
715 register_command_task(cookie);
718 static char *database_dir;
720 static int make_database_dir(void)
725 if (conf.afs_database_dir_given)
726 database_dir = para_strdup(conf.afs_database_dir_arg);
728 char *home = para_homedir();
729 database_dir = make_message(
730 "%s/.paraslash/afs_database", home);
734 PARA_INFO_LOG("afs_database dir %s\n", database_dir);
735 ret = para_mkdir(database_dir, 0777);
736 if (ret >= 0 || ret == -E_EXIST)
743 static int open_afs_tables(void)
745 int ret = make_database_dir();
749 ret = attribute_init(&afs_tables[TBLNUM_ATTRIBUTES], database_dir);
752 ret = moods_init(&afs_tables[TBLNUM_MOODS], database_dir);
754 goto moods_init_error;
755 ret = playlists_init(&afs_tables[TBLNUM_PLAYLIST], database_dir);
757 goto playlists_init_error;
758 ret = lyrics_init(&afs_tables[TBLNUM_LYRICS], database_dir);
760 goto lyrics_init_error;
761 ret = images_init(&afs_tables[TBLNUM_IMAGES], database_dir);
763 goto images_init_error;
764 ret = score_init(&afs_tables[TBLNUM_SCORES], database_dir);
766 goto score_init_error;
767 ret = aft_init(&afs_tables[TBLNUM_AUDIO_FILES], database_dir);
773 score_shutdown(OSL_MARK_CLEAN);
775 images_shutdown(OSL_MARK_CLEAN);
777 lyrics_shutdown(OSL_MARK_CLEAN);
779 playlists_shutdown(OSL_MARK_CLEAN);
780 playlists_init_error:
781 moods_shutdown(OSL_MARK_CLEAN);
783 attribute_shutdown(OSL_MARK_CLEAN);
787 __noreturn int afs_init(uint32_t cookie, int socket_fd)
789 enum play_mode current_play_mode;
791 int ret = open_afs_tables();
794 PARA_EMERG_LOG("%s\n", PARA_STRERROR(-ret));
797 server_socket = socket_fd;
798 PARA_INFO_LOG("server_socket: %d, afs_socket_cookie: %u\n",
799 server_socket, (unsigned) cookie);
800 current_play_mode = init_admissible_files();
801 register_tasks(cookie);
802 s.default_timeout.tv_sec = 0;
803 s.default_timeout.tv_usec = 99 * 1000;
806 PARA_EMERG_LOG("%s\n", PARA_STRERROR(-ret));
807 close_afs_tables(OSL_MARK_CLEAN);
811 static int create_tables_callback(const struct osl_object *query,
812 __a_unused struct osl_object *result)
814 uint32_t table_mask = *(uint32_t *)query->data;
817 close_afs_tables(OSL_MARK_CLEAN);
818 for (i = 0; i < NUM_AFS_TABLES; i++) {
819 struct table_info *ti = afs_tables + i;
821 if (ti->flags & TBLFLAG_SKIP_CREATE)
823 if (!(table_mask & (1 << i)))
825 ret = osl_create_table(ti->desc);
829 ret = open_afs_tables();
830 return ret < 0? ret: 0;
833 int com_init(int fd, int argc, char * const * const argv)
836 uint32_t table_mask = (1 << (NUM_AFS_TABLES + 1)) - 1;
837 struct osl_object query = {.data = &table_mask,
838 .size = sizeof(table_mask)};
842 for (i = 1; i < argc; i++) {
843 for (j = 0; j < NUM_AFS_TABLES; j++) {
844 struct table_info *ti = afs_tables + j;
846 if (ti->flags & TBLFLAG_SKIP_CREATE)
848 if (strcmp(argv[i], ti->desc->name))
850 table_mask |= (1 << j);
853 if (j == NUM_AFS_TABLES)
854 return -E_BAD_TABLE_NAME;
857 ret = send_callback_request(create_tables_callback, &query, NULL);
860 return send_va_buffer(fd, "successfully created afs table(s)\n");