4 #include <dirent.h> /* readdir() */
7 //#include <inttypes.h>
18 /** \file afs.c Paraslash's audio file selector. */
21 * Compare two osl objects of string type.
23 * \param obj1 Pointer to the first object.
24 * \param obj2 Pointer to the second object.
26 * In any case, only \p MIN(obj1->size, obj2->size) characters of each string
27 * are taken into account.
29 * \return It returns an integer less than, equal to, or greater than zero if
30 * \a obj1 is found, respectively, to be less than, to match, or be greater than
33 * \sa strcmp(3), strncmp(3), osl_compare_func.
35 int string_compare(const struct osl_object *obj1, const struct osl_object *obj2)
37 const char *str1 = (const char *)obj1->data;
38 const char *str2 = (const char *)obj2->data;
39 return strncmp(str1, str2, PARA_MIN(obj1->size, obj2->size));
42 /** The osl tables used by afs. \sa blob.c */
44 /** Contains audio file information. See aft.c. */
46 /** The table for the paraslash attributes. See attribute.c. */
49 * Paraslash's scoring system is based on Gaussian normal
50 * distributions, and the relevant data is stored in the rbtrees of an
51 * osl table containing only volatile columns. See score.c for
56 * A standard blob table containing the mood definitions. For details
60 /** A blob table containing lyrics on a per-song basis. */
62 /** Another blob table for images (for example album cover art). */
64 /** Yet another blob table for storing standard playlists. */
66 /** How many tables are in use? */
70 static struct table_info afs_tables[NUM_AFS_TABLES];
73 /** The file descriptor for the local socket. */
76 * Value sent by the command handlers to identify themselves as
77 * children of the running para_server.
80 /** The associated task structure. */
86 * A wrapper for strtol(3).
88 * \param str The string to be converted to a long integer.
89 * \param result The converted value is stored here.
91 * \return Positive on success, -E_ATOL on errors.
93 * \sa strtol(3), atoi(3).
95 int para_atol(const char *str, long *result)
101 errno = 0; /* To distinguish success/failure after call */
102 val = strtol(str, &endptr, base);
104 if (errno == ERANGE && (val == LONG_MAX || val == LONG_MIN))
105 goto out; /* overflow */
106 if (errno != 0 && val == 0)
107 goto out; /* other error */
109 goto out; /* No digits were found */
111 goto out; /* Further characters after number */
119 * Struct to let para_server call a function specified from child context.
121 * Commands that need to change the state of para_server can't
122 * change the relevant data structures directly because commands
123 * are executed in a child process, i.e. they get their own
124 * virtual address space. This structure must be used to let
125 * para_server (i.e. the parent process) call a function specified
126 * by the child (the command handler).
128 * \sa fork(2), ipc.c.
130 struct callback_data {
131 /** The function to be called. */
132 callback_function *handler;
133 /** The sma for the parameters of the callback function. */
135 /** The size of the query sma. */
137 /** If the callback produced a result, it is stored in this sma. */
139 /** The size of the result sma. */
141 /** The return value of the callback function. */
143 /** The return value of the callback() procedure. */
147 struct callback_query {
148 /** The function to be called. */
149 callback_function *handler;
150 /** The number of bytes of the query */
154 struct callback_result {
155 /** The number of bytes of the result. */
159 static struct callback_data *shm_callback_data;
160 static int callback_mutex;
161 static int child_mutex;
162 static int result_mutex;
165 * Ask the parent process to call a given function.
167 * \param f The function to be called.
168 * \param query Pointer to arbitrary data for the callback.
169 * \param result Callback result will be stored here.
171 * This function creates a shared memory area, copies the buffer pointed to by
172 * \a buf to that area and notifies the parent process that \a f should be
173 * called ASAP. It provides proper locking via semaphores to protect against
174 * concurent access to the shared memory area and against concurrent access by
175 * another child process that asks to call the same function.
177 * \return Negative, if the shared memory area could not be set up. The return
178 * value of the callback function otherwise.
180 * \sa shm_new(), shm_attach(), shm_detach(), mutex_lock(), mutex_unlock(),
181 * shm_destroy(), struct callback_data, send_option_arg_callback_request(),
182 * send_standard_callback_request().
184 int send_callback_request(callback_function *f, struct osl_object *query,
185 struct osl_object *result)
187 struct callback_data cbd = {.handler = f};
191 assert(query->data && query->size);
192 ret = shm_new(query->size);
195 cbd.query_shmid = ret;
196 cbd.query_size = query->size;
197 ret = shm_attach(cbd.query_shmid, ATTACH_RW, &query_sma);
200 memcpy(query_sma, query->data, query->size);
201 ret = shm_detach(query_sma);
204 /* prevent other children from interacting */
205 mutex_lock(child_mutex);
206 /* prevent parent from messing with shm_callback_data. */
207 mutex_lock(callback_mutex);
208 /* all three mutexes are locked, set parameters for callback */
209 *shm_callback_data = cbd;
211 mutex_unlock(callback_mutex);
212 kill(getppid(), SIGUSR1); /* wake up parent */
214 * At this time only the parent can run. It will execute our callback
215 * and unlock the result_mutex when ready to indicate that the child
216 * may use the result. So let's sleep on this mutex.
218 mutex_lock(result_mutex);
219 /* No need to aquire the callback mutex again */
220 ret = shm_callback_data->sma_ret;
221 if (ret < 0) /* sma problem, callback might not have been executed */
222 goto unlock_child_mutex;
223 if (shm_callback_data->result_shmid >= 0) { /* parent provided a result */
225 ret = shm_attach(shm_callback_data->result_shmid, ATTACH_RO,
228 if (result) { /* copy result */
229 result->size = shm_callback_data->result_size;
230 result->data = para_malloc(result->size);
231 memcpy(result->data, sma, result->size);
232 ret = shm_detach(sma);
234 PARA_ERROR_LOG("can not detach result\n");
236 PARA_WARNING_LOG("no result pointer\n");
238 PARA_ERROR_LOG("attach result failed: %d\n", ret);
239 if (shm_destroy(shm_callback_data->result_shmid) < 0)
240 PARA_ERROR_LOG("destroy result failed\n");
241 } else { /* no result from callback */
243 PARA_WARNING_LOG("callback has no result\n");
248 ret = shm_callback_data->callback_ret;
250 /* give other children a chance */
251 mutex_unlock(child_mutex);
253 if (shm_destroy(cbd.query_shmid) < 0)
254 PARA_ERROR_LOG("%s\n", "shm destroy error");
255 PARA_DEBUG_LOG("callback_ret: %d\n", ret);
260 * Send a callback request passing an options structure and an argument vector.
262 * \param options pointer to an arbitrary data structure.
263 * \param argc Argument count.
264 * \param argv Standard argument vector.
265 * \param f The callback function.
266 * \param result The result of the query is stored here.
268 * Some commands have a couple of options that are parsed in child context for
269 * syntactic correctness and are stored in a special options structure for that
270 * command. This function allows to pass such a structure together with a list
271 * of further arguments (often a list of audio files) to the parent process.
273 * \sa send_standard_callback_request(), send_callback_request().
275 int send_option_arg_callback_request(struct osl_object *options,
276 int argc, const char **argv, callback_function *f,
277 struct osl_object *result)
281 struct osl_object query = {.size = options? options->size : 0};
283 for (i = 0; i < argc; i++)
284 query.size += strlen(argv[i]) + 1;
285 query.data = para_malloc(query.size);
288 memcpy(query.data, options->data, options->size);
291 for (i = 0; i < argc; i++) {
292 strcpy(p, argv[i]); /* OK */
293 p += strlen(argv[i]) + 1;
295 ret = send_callback_request(f, &query, result);
301 * Send a callback request with an argument vector only.
303 * \param argc The same meaning as in send_option_arg_callback_request().
304 * \param argv The same meaning as in send_option_arg_callback_request().
305 * \param f The same meaning as in send_option_arg_callback_request().
306 * \param result The same meaning as in send_option_arg_callback_request().
308 * This is similar to send_option_arg_callback_request(), but no options buffer
309 * is passed to the parent process.
311 * \return The return value of the underlying call to
312 * send_option_arg_callback_request().
314 int send_standard_callback_request(int argc, const char **argv,
315 callback_function *f, struct osl_object *result)
317 return send_option_arg_callback_request(NULL, argc, argv, f, result);
321 * write input from fd to dynamically allocated char array,
322 * but maximal max_size byte. Return size.
324 static int fd2buf(int fd, char **buf, int max_size)
326 const size_t chunk_size = 1024;
331 *buf = para_malloc(size * sizeof(char));
333 while ((ret = read(fd, p, chunk_size)) > 0) {
335 if ((p - *buf) + chunk_size >= size) {
339 if (size > max_size) {
340 ret = -E_INPUT_TOO_LARGE;
343 tmp = para_realloc(*buf, size);
344 p = (p - *buf) + tmp;
360 * Read from stdin, and send the result to the parent process.
362 * \param arg_obj Pointer to the arguments to \a f.
363 * \param f The callback function.
364 * \param max_len Don't read more than that many bytes from stdin.
365 * \param result The result of the query is stored here.
367 * This function is used by commands that wish to let para_server store
368 * arbitrary data specified by the user (for instance the add_blob family of
369 * commands). First, at most \a max_len bytes are read from stdin, the result
370 * is concatenated with the buffer given by \a arg_obj, and the combined buffer
371 * is made available to the parent process via shared memory.
373 * \return Negative on errors, the return value of the underlying call to
374 * send_callback_request() otherwise.
376 int stdin_command(struct osl_object *arg_obj, callback_function *f,
377 unsigned max_len, struct osl_object *result)
381 struct osl_object query;
382 int ret = fd2buf(STDIN_FILENO, &stdin_buf, max_len);
387 query.size = arg_obj->size + stdin_len;
388 query.data = para_malloc(query.size);
389 memcpy(query.data, arg_obj->data, arg_obj->size);
390 memcpy((char *)query.data + arg_obj->size, stdin_buf, stdin_len);
392 ret = send_callback_request(f, &query, result);
398 * Open the audio file with highest score.
400 * \param afd Audio file data is returned here.
402 * This stores all information for streaming the "best" audio file
403 * in the \a afd structure.
405 * \return Positive on success, negative on errors.
407 * \sa close_audio_file(), open_and_update_audio_file().
409 int open_next_audio_file(struct audio_file_data *afd)
411 struct osl_row *aft_row;
414 ret = score_get_best(&aft_row, &afd->score);
417 ret = open_and_update_audio_file(aft_row, afd);
424 * Free all resources which were allocated by open_next_audio_file().
426 * \param afd The structure previously filled in by open_next_audio_file().
428 * \return The return value of the underlying call to para_munmap().
430 * \sa open_next_audio_file().
432 int close_audio_file(struct audio_file_data *afd)
434 free(afd->afhi.chunk_table);
435 return para_munmap(afd->map.data, afd->map.size);
439 static void play_loop(enum play_mode current_play_mode)
442 struct audio_file_data afd;
444 afd.current_play_mode = current_play_mode;
445 for (i = 0; i < 0; i++) {
446 ret = open_next_audio_file(&afd);
448 PARA_ERROR_LOG("failed to open next audio file: %d\n", ret);
451 PARA_NOTICE_LOG("next audio file: %s, score: %li\n", afd.path, afd.score);
453 close_audio_file(&afd);
459 static enum play_mode init_admissible_files(void)
462 char *given_mood, *given_playlist;
464 given_mood = "mood_that_was_given_at_the_command_line";
465 given_playlist = "given_playlist";
468 ret = mood_open(given_mood);
471 PARA_WARNING_LOG("ignoring playlist %s\n",
473 return PLAY_MODE_MOOD;
476 if (given_playlist) {
477 ret = playlist_open(given_playlist);
479 return PLAY_MODE_PLAYLIST;
481 ret = mood_open(NULL); /* open first available mood */
483 return PLAY_MODE_MOOD;
484 mood_open(""); /* open dummy mood, always successful */
485 return PLAY_MODE_MOOD;
488 static int setup_command_socket_or_die(void)
491 char *socket_name = "/tmp/afs_command_socket";
492 struct sockaddr_un unix_addr;
495 ret = create_local_socket(socket_name, &unix_addr,
496 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IWOTH);
499 if (listen(ret , 5) < 0) {
500 PARA_EMERG_LOG("%s", "can not listen on socket\n");
503 PARA_INFO_LOG("listening on command socket %s (fd %d)\n", socket_name,
508 static int server_socket;
516 static void afs_shutdown(enum osl_close_flags flags)
518 PARA_NOTICE_LOG("cleaning up\n");
519 score_shutdown(flags);
520 attribute_shutdown(flags);
523 moods_shutdown(flags);
524 playlists_shutdown(flags);
525 lyrics_shutdown(flags);
526 images_shutdown(flags);
530 static void signal_pre_select(struct sched *s, struct task *t)
532 struct signal_task *st = t->private_data;
534 para_fd_set(st->fd, &s->rfds, &s->max_fileno);
537 static void signal_post_select(struct sched *s, struct task *t)
539 struct signal_task *st = t->private_data;
541 if (!FD_ISSET(st->fd, &s->rfds))
543 st->signum = para_next_signal();
544 PARA_NOTICE_LOG("caught signal %d\n", st->signum);
546 if (st->signum == SIGUSR1)
547 return; /* ignore SIGUSR1 */
548 afs_shutdown(OSL_MARK_CLEAN);
549 t->ret = -E_SIGNAL_CAUGHT;
552 static void register_signal_task(void)
554 static struct signal_task signal_task_struct;
555 struct signal_task *st = &signal_task_struct;
556 st->fd = para_signal_init();
557 PARA_INFO_LOG("signal pipe: fd %d\n", st->fd);
558 para_install_sighandler(SIGINT);
559 para_install_sighandler(SIGTERM);
560 para_install_sighandler(SIGPIPE);
562 st->task.pre_select = signal_pre_select;
563 st->task.post_select = signal_post_select;
564 st->task.private_data = st;
565 sprintf(st->task.status, "signal task");
566 register_task(&st->task);
569 static void command_pre_select(struct sched *s, struct task *t)
571 struct command_task *ct = t->private_data;
573 para_fd_set(ct->fd, &s->rfds, &s->max_fileno);
577 * On errors, negative value is written to fd.
578 * On success: If query produced a result, the result_shmid is written to fd.
579 * Otherwise, zero is written.
581 static int call_callback(int fd, int query_shmid)
583 void *query_shm, *result_shm;
584 struct callback_query *cq;
585 struct callback_result *cr;
586 struct osl_object query, result = {.data = NULL};
587 int result_shmid = -1, ret, ret2;
589 ret = shm_attach(query_shmid, ATTACH_RO, &query_shm);
593 query.data = (char *)query_shm + sizeof(*cq);
594 query.size = cq->query_size;
595 ret = cq->handler(&query, &result);
596 ret2 = shm_detach(query_shm);
597 if (ret2 < 0 && ret >= 0)
602 if (!result.data || !result.size)
604 ret = shm_new(result.size + sizeof(struct callback_result));
608 ret = shm_attach(result_shmid, ATTACH_RW, &result_shm);
612 cr->result_size = result.size;
613 memcpy(result_shm + sizeof(*cr), result.data, result.size);
614 ret = shm_detach(result_shm);
620 ret2 = send_bin_buffer(fd, (char *)ret, sizeof(int));
621 if (ret < 0 || ret2 < 0) {
622 if (result_shmid >= 0)
623 if (shm_destroy(result_shmid) < 0)
624 PARA_ERROR_LOG("destroy result failed\n");
631 static void command_post_select(struct sched *s, struct task *t)
633 struct command_task *ct = t->private_data;
634 struct sockaddr_un unix_addr;
635 char buf[sizeof(uint32_t) + sizeof(int)];
640 if (!FD_ISSET(ct->fd, &s->rfds))
642 t->ret = para_accept(ct->fd, &unix_addr, sizeof(unix_addr));
646 * The following errors may be caused by a malicious local user. So do
647 * not return an error in this case as this would terminate para_afs
651 t->ret = recv_bin_buffer(ct->fd, buf, sizeof(buf));
653 PARA_NOTICE_LOG("%s\n", PARA_STRERROR(-t->ret));
657 if (t->ret != sizeof(buf)) {
658 PARA_NOTICE_LOG("short read (%d bytes, expected %d)\n",
659 t->ret, sizeof(buf));
663 cookie = *(uint32_t *)buf;
664 if (cookie != ct->cookie) {
665 PARA_NOTICE_LOG("received invalid cookie(got %u, expected %u)\n",
666 (unsigned)cookie, (unsigned)ct->cookie);
670 query_shmid = *(int *)(buf + sizeof(cookie));
671 if (query_shmid < 0) {
672 PARA_WARNING_LOG("received invalid query shmid %d)\n",
677 t->ret = call_callback(fd, query_shmid);
679 PARA_NOTICE_LOG("%s\n", PARA_STRERROR(-t->ret));
687 static void register_command_task(uint32_t cookie)
689 static struct command_task command_task_struct;
690 struct command_task *ct = &command_task_struct;
691 ct->fd = setup_command_socket_or_die();
694 ct->task.pre_select = command_pre_select;
695 ct->task.post_select = command_post_select;
696 ct->task.private_data = ct;
697 sprintf(ct->task.status, "command task");
698 register_task(&ct->task);
701 void register_tasks(uint32_t cookie)
703 register_signal_task();
704 register_command_task(cookie);
707 __noreturn int afs_init(uint32_t cookie, int socket_fd)
711 enum play_mode current_play_mode;
714 server_socket = socket_fd;
715 PARA_INFO_LOG("server_socket: %d, afs_socket_cookie: %u\n",
716 server_socket, (unsigned) cookie);
718 ret = attribute_init(&afs_tables[TBLNUM_ATTRIBUTES]);
720 goto attribute_init_error;
721 ret = moods_init(&afs_tables[TBLNUM_MOODS]);
723 goto moods_init_error;
724 ret = playlists_init(&afs_tables[TBLNUM_PLAYLIST]);
726 goto playlists_init_error;
727 ret = lyrics_init(&afs_tables[TBLNUM_LYRICS]);
729 goto lyrics_init_error;
730 ret = images_init(&afs_tables[TBLNUM_IMAGES]);
732 goto images_init_error;
733 ret = score_init(&afs_tables[TBLNUM_SCORES]);
735 goto score_init_error;
736 ret = aft_init(&afs_tables[TBLNUM_AUDIO_FILES]);
740 current_play_mode = init_admissible_files();
741 register_tasks(cookie);
742 s.default_timeout.tv_sec = 0;
743 s.default_timeout.tv_usec = 99 * 1000;
747 ret = shm_new(sizeof(struct callback_data));
751 ret = shm_attach(shmid, ATTACH_RW, &shm_area);
754 shm_callback_data = shm_area;
758 callback_mutex = ret;
767 mutex_lock(result_mutex);
770 score_shutdown(OSL_MARK_CLEAN);
772 images_shutdown(OSL_MARK_CLEAN);
774 lyrics_shutdown(OSL_MARK_CLEAN);
776 playlists_shutdown(OSL_MARK_CLEAN);
777 playlists_init_error:
778 moods_shutdown(OSL_MARK_CLEAN);
780 attribute_shutdown(OSL_MARK_CLEAN);
781 attribute_init_error:
785 static int create_all_tables(void)
789 for (i = 0; i < NUM_AFS_TABLES; i++) {
790 struct table_info *ti = afs_tables + i;
792 if (ti->flags & TBLFLAG_SKIP_CREATE)
794 ret = osl_create_table(ti->desc);
801 /* TODO load tables after init */
802 int com_init(__a_unused int fd, int argc, const char **argv)
806 return create_all_tables();
807 for (i = 1; i < argc; i++) {
808 for (j = 0; j < NUM_AFS_TABLES; j++) {
809 struct table_info *ti = afs_tables + j;
811 if (ti->flags & TBLFLAG_SKIP_CREATE)
813 if (strcmp(argv[i], ti->desc->name))
815 PARA_NOTICE_LOG("creating table %s\n", argv[i]);
816 ret = osl_create_table(ti->desc);
821 if (j == NUM_AFS_TABLES)
822 return -E_BAD_TABLE_NAME;
828 /** Describes a command of para_server. */
830 /** The name of the command. */
832 /** The handler function. */
833 int (*handler)(int fd, int argc, const char **argv);
836 static struct command afs_cmds[] = {
843 .handler = com_addlyr,
847 .handler = com_addimg,
851 .handler = com_addmood,
855 .handler = com_addpl,
859 .handler = com_catlyr,
863 .handler = com_catimg,
867 .handler = com_mvimg,
871 .handler = com_mvlyr,
875 .handler = com_mvmood,
883 .handler = com_catmood,
887 .handler = com_catpl,
891 .handler = com_rmatt,
899 .handler = com_lsatt,
903 .handler = com_afs_ls,
907 .handler = com_lslyr,
911 .handler = com_lsimg,
915 .handler = com_lsmood,
923 .handler = com_setatt,
927 .handler = com_addatt,
931 .handler = com_afs_rm,
935 .handler = com_rmlyr,
939 .handler = com_rmimg,
943 .handler = com_rmmood,
951 .handler = com_touch,
958 static void call_callback(void)
960 struct osl_object query, result = {.data = NULL};
963 shm_callback_data->result_shmid = -1; /* no result */
964 ret = shm_attach(shm_callback_data->query_shmid, ATTACH_RW,
968 query.size = shm_callback_data->query_size;
969 shm_callback_data->callback_ret = shm_callback_data->handler(&query,
971 if (result.data && result.size) {
973 ret = shm_new(result.size);
976 shm_callback_data->result_shmid = ret;
977 shm_callback_data->result_size = result.size;
978 ret = shm_attach(shm_callback_data->result_shmid, ATTACH_RW, &sma);
981 memcpy(sma, result.data, result.size);
982 ret = shm_detach(sma);
984 PARA_ERROR_LOG("detach result failed\n");
991 if (shm_destroy(shm_callback_data->result_shmid) < 0)
992 PARA_ERROR_LOG("destroy result failed\n");
993 shm_callback_data->result_shmid = -1;
996 ret2 = shm_detach(query.data);
998 PARA_ERROR_LOG("detach query failed\n");
1004 PARA_ERROR_LOG("sma error %d\n", ret);
1005 shm_callback_data->sma_ret = ret;
1006 shm_callback_data->handler = NULL;
1007 mutex_unlock(result_mutex); /* wake up child */
1010 static int got_sigchld;
1011 static void server_loop(int child_pid)
1015 PARA_DEBUG_LOG("server pid: %d, child pid: %d\n",
1016 getpid(), child_pid);
1018 mutex_lock(callback_mutex);
1019 if (shm_callback_data->handler)
1021 mutex_unlock(callback_mutex);
1025 mutex_destroy(result_mutex);
1026 mutex_destroy(callback_mutex);
1027 mutex_destroy(child_mutex);
1028 afs_shutdown(OSL_MARK_CLEAN);
1033 int main(int argc, const char **argv)
1035 int i, ret = -E_AFS_SYNTAX;
1037 signal(SIGUSR1, dummy);
1038 signal(SIGCHLD, sigchld_handler);
1042 // ret = afs_init();
1044 PARA_EMERG_LOG("afs_init returned %d\n", ret);
1054 for (i = 0; cmd[i].name; i++) {
1055 if (strcmp(cmd[i].name, argv[1]))
1057 ret = cmd[i].handler(1, argc - 1 , argv + 1);
1061 PARA_ERROR_LOG("unknown command: %s\n", argv[1]);
1065 PARA_ERROR_LOG("error %d\n", ret);
1067 PARA_DEBUG_LOG("%s", "success\n");
1069 return ret < 0? EXIT_FAILURE : EXIT_SUCCESS;