2 * Copyright (C) 1997-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 extern uint32_t afs_socket_cookie;
29 * Compare two osl objects of string type.
31 * \param obj1 Pointer to the first object.
32 * \param obj2 Pointer to the second object.
34 * In any case, only \p MIN(obj1->size, obj2->size) characters of each string
35 * are taken into account.
37 * \return It returns an integer less than, equal to, or greater than zero if
38 * \a obj1 is found, respectively, to be less than, to match, or be greater than
41 * \sa strcmp(3), strncmp(3), osl_compare_func.
43 int string_compare(const struct osl_object *obj1, const struct osl_object *obj2)
45 const char *str1 = (const char *)obj1->data;
46 const char *str2 = (const char *)obj2->data;
47 return strncmp(str1, str2, PARA_MIN(obj1->size, obj2->size));
50 /** The osl tables used by afs. \sa blob.c */
52 /** Contains audio file information. See aft.c. */
54 /** The table for the paraslash attributes. See attribute.c. */
57 * Paraslash's scoring system is based on Gaussian normal
58 * distributions, and the relevant data is stored in the rbtrees of an
59 * osl table containing only volatile columns. See score.c for
64 * A standard blob table containing the mood definitions. For details
68 /** A blob table containing lyrics on a per-song basis. */
70 /** Another blob table for images (for example album cover art). */
72 /** Yet another blob table for storing standard playlists. */
74 /** How many tables are in use? */
78 static struct table_info afs_tables[NUM_AFS_TABLES];
81 /** The file descriptor for the local socket. */
84 * Value sent by the command handlers to identify themselves as
85 * children of the running para_server.
88 /** The associated task structure. */
94 * A wrapper for strtol(3).
96 * \param str The string to be converted to a long integer.
97 * \param result The converted value is stored here.
99 * \return Positive on success, -E_ATOL on errors.
101 * \sa strtol(3), atoi(3).
103 int para_atol(const char *str, long *result)
109 errno = 0; /* To distinguish success/failure after call */
110 val = strtol(str, &endptr, base);
112 if (errno == ERANGE && (val == LONG_MAX || val == LONG_MIN))
113 goto out; /* overflow */
114 if (errno != 0 && val == 0)
115 goto out; /* other error */
117 goto out; /* No digits were found */
119 goto out; /* Further characters after number */
127 * Struct to let para_server call a function specified from child context.
129 * Commands that need to change the state of para_server can't
130 * change the relevant data structures directly because commands
131 * are executed in a child process, i.e. they get their own
132 * virtual address space. This structure must be used to let
133 * para_server (i.e. the parent process) call a function specified
134 * by the child (the command handler).
136 * \sa fork(2), ipc.c.
138 struct callback_data {
139 /** The function to be called. */
140 callback_function *handler;
141 /** The sma for the parameters of the callback function. */
143 /** The size of the query sma. */
145 /** If the callback produced a result, it is stored in this sma. */
147 /** The size of the result sma. */
149 /** The return value of the callback function. */
151 /** The return value of the callback() procedure. */
155 struct callback_query {
156 /** The function to be called. */
157 callback_function *handler;
158 /** The number of bytes of the query */
162 struct callback_result {
163 /** The number of bytes of the result. */
167 static struct callback_data *shm_callback_data;
168 static int callback_mutex;
169 static int child_mutex;
170 static int result_mutex;
173 * Ask the parent process to call a given function.
175 * \param f The function to be called.
176 * \param query Pointer to arbitrary data for the callback.
177 * \param result Callback result will be stored here.
179 * This function creates a shared memory area, copies the buffer pointed to by
180 * \a buf to that area and notifies the afs process that \a f should be
183 * \return Negative, on errors, the return value of the callback function
186 * \sa send_option_arg_callback_request(), send_standard_callback_request().
188 int send_callback_request(callback_function *f, struct osl_object *query,
189 struct osl_object *result)
191 struct callback_query *cq;
192 struct callback_result *cr;
193 int ret, fd = -1, query_shmid, result_shmid;
194 void *query_shm, *result_shm;
195 char buf[sizeof(afs_socket_cookie) + sizeof(int)];
196 // char *tmpsocket_name;
197 struct sockaddr_un unix_addr;
199 assert(query->data && query->size);
200 ret = shm_new(query->size + sizeof(*cq));
204 ret = shm_attach(query_shmid, ATTACH_RW, &query_shm);
209 cq->query_size = query->size;
211 memcpy(query_shm + sizeof(*cq), query->data, query->size);
212 ret = shm_detach(query_shm);
216 *(uint32_t *) buf = afs_socket_cookie;
217 *(int *) (buf + sizeof(afs_socket_cookie)) = query_shmid;
219 ret = get_stream_socket(PF_UNIX);
223 ret = init_unix_addr(&unix_addr, conf.afs_socket_arg);
227 if (connect(fd, (struct sockaddr *)&unix_addr, sizeof(unix_addr)) < 0) /* FIXME: Use para_connect() */
229 ret = send_bin_buffer(fd, buf, sizeof(buf));
230 PARA_NOTICE_LOG("bin buffer ret: %d\n", ret);
233 ret = recv_bin_buffer(fd, buf, sizeof(buf));
234 PARA_NOTICE_LOG("ret: %d\n", ret);
237 if (ret != sizeof(int)) {
242 PARA_NOTICE_LOG("result_shmid: %d\n", ret);
246 ret = shm_attach(result_shmid, ATTACH_RO, &result_shm);
250 result->size = cr->result_size;
251 result->data = para_malloc(result->size);
252 memcpy(result->data, result_shm + sizeof(*cr), result->size);
253 ret = shm_detach(result_shm);
255 PARA_ERROR_LOG("can not detach result\n");
257 PARA_ERROR_LOG("attach result failed: %d\n", ret);
258 if (shm_destroy(result_shmid) < 0)
259 PARA_ERROR_LOG("destroy result failed\n");
262 if (shm_destroy(query_shmid) < 0)
263 PARA_ERROR_LOG("%s\n", "shm destroy error");
266 PARA_DEBUG_LOG("callback_ret: %d\n", ret);
271 * Send a callback request passing an options structure and an argument vector.
273 * \param options pointer to an arbitrary data structure.
274 * \param argc Argument count.
275 * \param argv Standard argument vector.
276 * \param f The callback function.
277 * \param result The result of the query is stored here.
279 * Some commands have a couple of options that are parsed in child context for
280 * syntactic correctness and are stored in a special options structure for that
281 * command. This function allows to pass such a structure together with a list
282 * of further arguments (often a list of audio files) to the parent process.
284 * \sa send_standard_callback_request(), send_callback_request().
286 int send_option_arg_callback_request(struct osl_object *options,
287 int argc, const char **argv, callback_function *f,
288 struct osl_object *result)
292 struct osl_object query = {.size = options? options->size : 0};
294 for (i = 0; i < argc; i++)
295 query.size += strlen(argv[i]) + 1;
296 query.data = para_malloc(query.size);
299 memcpy(query.data, options->data, options->size);
302 for (i = 0; i < argc; i++) {
303 strcpy(p, argv[i]); /* OK */
304 p += strlen(argv[i]) + 1;
306 ret = send_callback_request(f, &query, result);
312 * Send a callback request with an argument vector only.
314 * \param argc The same meaning as in send_option_arg_callback_request().
315 * \param argv The same meaning as in send_option_arg_callback_request().
316 * \param f The same meaning as in send_option_arg_callback_request().
317 * \param result The same meaning as in send_option_arg_callback_request().
319 * This is similar to send_option_arg_callback_request(), but no options buffer
320 * is passed to the parent process.
322 * \return The return value of the underlying call to
323 * send_option_arg_callback_request().
325 int send_standard_callback_request(int argc, const char **argv,
326 callback_function *f, struct osl_object *result)
328 return send_option_arg_callback_request(NULL, argc, argv, f, result);
332 * write input from fd to dynamically allocated char array,
333 * but maximal max_size byte. Return size.
335 static int fd2buf(int fd, char **buf, int max_size)
337 const size_t chunk_size = 1024;
342 *buf = para_malloc(size * sizeof(char));
344 while ((ret = read(fd, p, chunk_size)) > 0) {
346 if ((p - *buf) + chunk_size >= size) {
350 if (size > max_size) {
351 ret = -E_INPUT_TOO_LARGE;
354 tmp = para_realloc(*buf, size);
355 p = (p - *buf) + tmp;
371 * Read from stdin, and send the result to the parent process.
373 * \param arg_obj Pointer to the arguments to \a f.
374 * \param f The callback function.
375 * \param max_len Don't read more than that many bytes from stdin.
376 * \param result The result of the query is stored here.
378 * This function is used by commands that wish to let para_server store
379 * arbitrary data specified by the user (for instance the add_blob family of
380 * commands). First, at most \a max_len bytes are read from stdin, the result
381 * is concatenated with the buffer given by \a arg_obj, and the combined buffer
382 * is made available to the parent process via shared memory.
384 * \return Negative on errors, the return value of the underlying call to
385 * send_callback_request() otherwise.
387 int stdin_command(struct osl_object *arg_obj, callback_function *f,
388 unsigned max_len, struct osl_object *result)
392 struct osl_object query;
393 int ret = fd2buf(STDIN_FILENO, &stdin_buf, max_len);
398 query.size = arg_obj->size + stdin_len;
399 query.data = para_malloc(query.size);
400 memcpy(query.data, arg_obj->data, arg_obj->size);
401 memcpy((char *)query.data + arg_obj->size, stdin_buf, stdin_len);
403 ret = send_callback_request(f, &query, result);
409 * Open the audio file with highest score.
411 * \param afd Audio file data is returned here.
413 * This stores all information for streaming the "best" audio file
414 * in the \a afd structure.
416 * \return Positive on success, negative on errors.
418 * \sa close_audio_file(), open_and_update_audio_file().
420 int open_next_audio_file(struct audio_file_data *afd)
422 struct osl_row *aft_row;
425 ret = score_get_best(&aft_row, &afd->score);
428 ret = open_and_update_audio_file(aft_row, afd);
435 * Free all resources which were allocated by open_next_audio_file().
437 * \param afd The structure previously filled in by open_next_audio_file().
439 * \return The return value of the underlying call to para_munmap().
441 * \sa open_next_audio_file().
443 int close_audio_file(struct audio_file_data *afd)
445 free(afd->afhi.chunk_table);
446 return para_munmap(afd->map.data, afd->map.size);
450 static void play_loop(enum play_mode current_play_mode)
453 struct audio_file_data afd;
455 afd.current_play_mode = current_play_mode;
456 for (i = 0; i < 0; i++) {
457 ret = open_next_audio_file(&afd);
459 PARA_ERROR_LOG("failed to open next audio file: %d\n", ret);
462 PARA_NOTICE_LOG("next audio file: %s, score: %li\n", afd.path, afd.score);
464 close_audio_file(&afd);
470 static enum play_mode init_admissible_files(void)
473 char *given_mood, *given_playlist;
475 given_mood = "mood_that_was_given_at_the_command_line";
476 given_playlist = "given_playlist";
479 ret = mood_open(given_mood);
482 PARA_WARNING_LOG("ignoring playlist %s\n",
484 return PLAY_MODE_MOOD;
487 if (given_playlist) {
488 ret = playlist_open(given_playlist);
490 return PLAY_MODE_PLAYLIST;
492 ret = mood_open(NULL); /* open first available mood */
494 return PLAY_MODE_MOOD;
495 mood_open(""); /* open dummy mood, always successful */
496 return PLAY_MODE_MOOD;
499 static int setup_command_socket_or_die(void)
502 char *socket_name = conf.afs_socket_arg;
503 struct sockaddr_un unix_addr;
506 ret = create_local_socket(socket_name, &unix_addr,
507 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IWOTH);
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 int server_socket;
527 static void afs_shutdown(enum osl_close_flags flags)
529 PARA_NOTICE_LOG("cleaning up\n");
530 score_shutdown(flags);
531 attribute_shutdown(flags);
534 moods_shutdown(flags);
535 playlists_shutdown(flags);
536 lyrics_shutdown(flags);
537 images_shutdown(flags);
541 static void signal_pre_select(struct sched *s, struct task *t)
543 struct signal_task *st = t->private_data;
545 para_fd_set(st->fd, &s->rfds, &s->max_fileno);
548 static void signal_post_select(struct sched *s, struct task *t)
550 struct signal_task *st = t->private_data;
552 if (!FD_ISSET(st->fd, &s->rfds))
554 st->signum = para_next_signal();
555 PARA_NOTICE_LOG("caught signal %d\n", st->signum);
557 if (st->signum == SIGUSR1)
558 return; /* ignore SIGUSR1 */
559 afs_shutdown(OSL_MARK_CLEAN);
560 t->ret = -E_SIGNAL_CAUGHT;
563 static void register_signal_task(void)
565 static struct signal_task signal_task_struct;
566 struct signal_task *st = &signal_task_struct;
567 st->fd = para_signal_init();
568 PARA_INFO_LOG("signal pipe: fd %d\n", st->fd);
569 para_install_sighandler(SIGINT);
570 para_install_sighandler(SIGTERM);
571 para_install_sighandler(SIGPIPE);
573 st->task.pre_select = signal_pre_select;
574 st->task.post_select = signal_post_select;
575 st->task.private_data = st;
576 sprintf(st->task.status, "signal task");
577 register_task(&st->task);
580 static void command_pre_select(struct sched *s, struct task *t)
582 struct command_task *ct = t->private_data;
584 para_fd_set(ct->fd, &s->rfds, &s->max_fileno);
588 * On errors, negative value is written to fd.
589 * On success: If query produced a result, the result_shmid is written to fd.
590 * Otherwise, zero is written.
592 static int call_callback(int fd, int query_shmid)
594 void *query_shm, *result_shm;
595 struct callback_query *cq;
596 struct callback_result *cr;
597 struct osl_object query, result = {.data = NULL};
598 int result_shmid = -1, ret, ret2;
600 ret = shm_attach(query_shmid, ATTACH_RW, &query_shm);
604 query.data = (char *)query_shm + sizeof(*cq);
605 query.size = cq->query_size;
606 ret = cq->handler(&query, &result);
607 ret2 = shm_detach(query_shm);
608 if (ret2 < 0 && ret >= 0)
613 if (!result.data || !result.size)
615 ret = shm_new(result.size + sizeof(struct callback_result));
619 ret = shm_attach(result_shmid, ATTACH_RW, &result_shm);
623 cr->result_size = result.size;
624 memcpy(result_shm + sizeof(*cr), result.data, result.size);
625 ret = shm_detach(result_shm);
631 ret2 = send_bin_buffer(fd, (char *)&ret, sizeof(int));
632 if (ret < 0 || ret2 < 0) {
633 if (result_shmid >= 0)
634 if (shm_destroy(result_shmid) < 0)
635 PARA_ERROR_LOG("destroy result failed\n");
642 static void command_post_select(struct sched *s, struct task *t)
644 struct command_task *ct = t->private_data;
645 struct sockaddr_un unix_addr;
646 char buf[sizeof(uint32_t) + sizeof(int)];
651 if (!FD_ISSET(ct->fd, &s->rfds))
653 t->ret = para_accept(ct->fd, &unix_addr, sizeof(unix_addr));
657 * The following errors may be caused by a malicious local user. So do
658 * not return an error in this case as this would terminate para_afs
662 /* FIXME: This is easily dosable (peer doesn't send data) */
663 t->ret = recv_bin_buffer(fd, buf, sizeof(buf));
665 PARA_NOTICE_LOG("%s (%d)\n", PARA_STRERROR(-t->ret), t->ret);
669 if (t->ret != sizeof(buf)) {
670 PARA_NOTICE_LOG("short read (%d bytes, expected %d)\n",
671 t->ret, sizeof(buf));
675 cookie = *(uint32_t *)buf;
676 if (cookie != ct->cookie) {
677 PARA_NOTICE_LOG("received invalid cookie(got %u, expected %u)\n",
678 (unsigned)cookie, (unsigned)ct->cookie);
682 query_shmid = *(int *)(buf + sizeof(cookie));
683 if (query_shmid < 0) {
684 PARA_WARNING_LOG("received invalid query shmid %d)\n",
689 t->ret = call_callback(fd, query_shmid);
691 PARA_NOTICE_LOG("%s\n", PARA_STRERROR(-t->ret));
699 static void register_command_task(uint32_t cookie)
701 static struct command_task command_task_struct;
702 struct command_task *ct = &command_task_struct;
703 ct->fd = setup_command_socket_or_die();
706 ct->task.pre_select = command_pre_select;
707 ct->task.post_select = command_post_select;
708 ct->task.private_data = ct;
709 sprintf(ct->task.status, "command task");
710 register_task(&ct->task);
713 void register_tasks(uint32_t cookie)
715 register_signal_task();
716 register_command_task(cookie);
719 __noreturn int afs_init(uint32_t cookie, int socket_fd)
723 enum play_mode current_play_mode;
726 server_socket = socket_fd;
727 PARA_INFO_LOG("server_socket: %d, afs_socket_cookie: %u\n",
728 server_socket, (unsigned) cookie);
730 ret = attribute_init(&afs_tables[TBLNUM_ATTRIBUTES]);
732 goto attribute_init_error;
733 ret = moods_init(&afs_tables[TBLNUM_MOODS]);
735 goto moods_init_error;
736 ret = playlists_init(&afs_tables[TBLNUM_PLAYLIST]);
738 goto playlists_init_error;
739 ret = lyrics_init(&afs_tables[TBLNUM_LYRICS]);
741 goto lyrics_init_error;
742 ret = images_init(&afs_tables[TBLNUM_IMAGES]);
744 goto images_init_error;
745 ret = score_init(&afs_tables[TBLNUM_SCORES]);
747 goto score_init_error;
748 ret = aft_init(&afs_tables[TBLNUM_AUDIO_FILES]);
752 current_play_mode = init_admissible_files();
753 register_tasks(cookie);
754 s.default_timeout.tv_sec = 0;
755 s.default_timeout.tv_usec = 99 * 1000;
759 ret = shm_new(sizeof(struct callback_data));
763 ret = shm_attach(shmid, ATTACH_RW, &shm_area);
766 shm_callback_data = shm_area;
770 callback_mutex = ret;
779 mutex_lock(result_mutex);
782 score_shutdown(OSL_MARK_CLEAN);
784 images_shutdown(OSL_MARK_CLEAN);
786 lyrics_shutdown(OSL_MARK_CLEAN);
788 playlists_shutdown(OSL_MARK_CLEAN);
789 playlists_init_error:
790 moods_shutdown(OSL_MARK_CLEAN);
792 attribute_shutdown(OSL_MARK_CLEAN);
793 attribute_init_error:
797 static int create_all_tables(void)
801 for (i = 0; i < NUM_AFS_TABLES; i++) {
802 struct table_info *ti = afs_tables + i;
804 if (ti->flags & TBLFLAG_SKIP_CREATE)
806 ret = osl_create_table(ti->desc);
813 /* TODO load tables after init */
814 int com_init(__a_unused int fd, int argc, const char **argv)
818 return create_all_tables();
819 for (i = 1; i < argc; i++) {
820 for (j = 0; j < NUM_AFS_TABLES; j++) {
821 struct table_info *ti = afs_tables + j;
823 if (ti->flags & TBLFLAG_SKIP_CREATE)
825 if (strcmp(argv[i], ti->desc->name))
827 PARA_NOTICE_LOG("creating table %s\n", argv[i]);
828 ret = osl_create_table(ti->desc);
833 if (j == NUM_AFS_TABLES)
834 return -E_BAD_TABLE_NAME;