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
;
78 struct callback_data
{
79 /** The function to be called. */
80 callback_function
*handler
;
81 /** The sma for the parameters of the callback function. */
83 /** The size of the query sma. */
85 /** If the callback produced a result, it is stored in this sma. */
87 /** The size of the result sma. */
89 /** The return value of the callback function. */
91 /** The return value of the callback() procedure. */
96 * Struct to let command handlers execute a callback in afs context.
98 * Commands that need to change the state of afs can't change the relevant data
99 * structures directly because commands are executed in a child process, i.e.
100 * they get their own virtual address space.
102 * This structure is used by \p send_callback_request() (executed from handler
103 * context) in order to let the afs process call the specified function. An
104 * instance of that structure is written to a shared memory area together with
105 * the arguments to the callback function. The identifier of the shared memory
106 * area is written to the command socket.
108 * The afs process accepts connections on the command socket and reads the
109 * shared memory id, attaches the corresponing area, calls the given handler to
110 * perform the desired action and to optionally compute a result.
112 * The result and a \p callback_result structure is then written to another
113 * shared memory area. The identifier for that area is written to the handler's
114 * command socket, so that the handler process can read the id, attach the
115 * shared memory area and use the result.
117 * \sa struct callback_result.
119 struct callback_query
{
120 /** The function to be called. */
121 callback_function
*handler
;
122 /** The number of bytes of the query */
127 * Structure embedded in the result of a callback.
129 * If the callback produced a result, an instance of that structure is embeeded
130 * into the shared memory area holding the result, mainly to let the command
131 * handler know the size of the result.
133 * \sa struct callback_query.
135 struct callback_result
{
136 /** The number of bytes of the result. */
141 * Ask the parent process to call a given function.
143 * \param f The function to be called.
144 * \param query Pointer to arbitrary data for the callback.
145 * \param result Callback result will be stored here.
147 * This function creates a shared memory area, copies the buffer pointed to by
148 * \a buf to that area and notifies the afs process that \a f should be
151 * \return Negative, on errors, the return value of the callback function
154 * \sa send_option_arg_callback_request(), send_standard_callback_request().
156 int send_callback_request(callback_function
*f
, struct osl_object
*query
,
157 struct osl_object
*result
)
159 struct callback_query
*cq
;
160 struct callback_result
*cr
;
161 int ret
, fd
= -1, query_shmid
, result_shmid
;
162 void *query_shm
, *result_shm
;
163 char buf
[sizeof(afs_socket_cookie
) + sizeof(int)];
164 // char *tmpsocket_name;
165 struct sockaddr_un unix_addr
;
167 assert(query
->data
&& query
->size
);
168 ret
= shm_new(query
->size
+ sizeof(*cq
));
172 ret
= shm_attach(query_shmid
, ATTACH_RW
, &query_shm
);
177 cq
->query_size
= query
->size
;
179 memcpy(query_shm
+ sizeof(*cq
), query
->data
, query
->size
);
180 ret
= shm_detach(query_shm
);
184 *(uint32_t *) buf
= afs_socket_cookie
;
185 *(int *) (buf
+ sizeof(afs_socket_cookie
)) = query_shmid
;
187 ret
= get_stream_socket(PF_UNIX
);
191 ret
= init_unix_addr(&unix_addr
, conf
.afs_socket_arg
);
195 if (connect(fd
, (struct sockaddr
*)&unix_addr
, sizeof(unix_addr
)) < 0) /* FIXME: Use para_connect() */
197 ret
= send_bin_buffer(fd
, buf
, sizeof(buf
));
198 PARA_NOTICE_LOG("bin buffer ret: %d\n", ret
);
201 ret
= recv_bin_buffer(fd
, buf
, sizeof(buf
));
202 PARA_NOTICE_LOG("ret: %d\n", ret
);
205 if (ret
!= sizeof(int)) {
210 PARA_NOTICE_LOG("result_shmid: %d\n", ret
);
214 ret
= shm_attach(result_shmid
, ATTACH_RO
, &result_shm
);
218 result
->size
= cr
->result_size
;
219 result
->data
= para_malloc(result
->size
);
220 memcpy(result
->data
, result_shm
+ sizeof(*cr
), result
->size
);
221 ret
= shm_detach(result_shm
);
223 PARA_ERROR_LOG("can not detach result\n");
225 PARA_ERROR_LOG("attach result failed: %d\n", ret
);
226 if (shm_destroy(result_shmid
) < 0)
227 PARA_ERROR_LOG("destroy result failed\n");
230 if (shm_destroy(query_shmid
) < 0)
231 PARA_ERROR_LOG("%s\n", "shm destroy error");
234 PARA_DEBUG_LOG("callback_ret: %d\n", ret
);
239 * Send a callback request passing an options structure and an argument vector.
241 * \param options pointer to an arbitrary data structure.
242 * \param argc Argument count.
243 * \param argv Standard argument vector.
244 * \param f The callback function.
245 * \param result The result of the query is stored here.
247 * Some commands have a couple of options that are parsed in child context for
248 * syntactic correctness and are stored in a special options structure for that
249 * command. This function allows to pass such a structure together with a list
250 * of further arguments (often a list of audio files) to the parent process.
252 * \sa send_standard_callback_request(), send_callback_request().
254 int send_option_arg_callback_request(struct osl_object
*options
,
255 int argc
, const char **argv
, callback_function
*f
,
256 struct osl_object
*result
)
260 struct osl_object query
= {.size
= options
? options
->size
: 0};
262 for (i
= 0; i
< argc
; i
++)
263 query
.size
+= strlen(argv
[i
]) + 1;
264 query
.data
= para_malloc(query
.size
);
267 memcpy(query
.data
, options
->data
, options
->size
);
270 for (i
= 0; i
< argc
; i
++) {
271 strcpy(p
, argv
[i
]); /* OK */
272 p
+= strlen(argv
[i
]) + 1;
274 ret
= send_callback_request(f
, &query
, result
);
280 * Send a callback request with an argument vector only.
282 * \param argc The same meaning as in send_option_arg_callback_request().
283 * \param argv The same meaning as in send_option_arg_callback_request().
284 * \param f The same meaning as in send_option_arg_callback_request().
285 * \param result The same meaning as in send_option_arg_callback_request().
287 * This is similar to send_option_arg_callback_request(), but no options buffer
288 * is passed to the parent process.
290 * \return The return value of the underlying call to
291 * send_option_arg_callback_request().
293 int send_standard_callback_request(int argc
, const char **argv
,
294 callback_function
*f
, struct osl_object
*result
)
296 return send_option_arg_callback_request(NULL
, argc
, argv
, f
, result
);
300 * Compare two osl objects of string type.
302 * \param obj1 Pointer to the first object.
303 * \param obj2 Pointer to the second object.
305 * In any case, only \p MIN(obj1->size, obj2->size) characters of each string
306 * are taken into account.
308 * \return It returns an integer less than, equal to, or greater than zero if
309 * \a obj1 is found, respectively, to be less than, to match, or be greater than
312 * \sa strcmp(3), strncmp(3), osl_compare_func.
314 int string_compare(const struct osl_object
*obj1
, const struct osl_object
*obj2
)
316 const char *str1
= (const char *)obj1
->data
;
317 const char *str2
= (const char *)obj2
->data
;
318 return strncmp(str1
, str2
, PARA_MIN(obj1
->size
, obj2
->size
));
322 * A wrapper for strtol(3).
324 * \param str The string to be converted to a long integer.
325 * \param result The converted value is stored here.
327 * \return Positive on success, -E_ATOL on errors.
329 * \sa strtol(3), atoi(3).
331 int para_atol(const char *str
, long *result
)
337 errno
= 0; /* To distinguish success/failure after call */
338 val
= strtol(str
, &endptr
, base
);
340 if (errno
== ERANGE
&& (val
== LONG_MAX
|| val
== LONG_MIN
))
341 goto out
; /* overflow */
342 if (errno
!= 0 && val
== 0)
343 goto out
; /* other error */
345 goto out
; /* No digits were found */
347 goto out
; /* Further characters after number */
356 * write input from fd to dynamically allocated char array,
357 * but maximal max_size byte. Return size.
359 static int fd2buf(int fd
, char **buf
, int max_size
)
361 const size_t chunk_size
= 1024;
366 *buf
= para_malloc(size
* sizeof(char));
368 while ((ret
= read(fd
, p
, chunk_size
)) > 0) {
370 if ((p
- *buf
) + chunk_size
>= size
) {
374 if (size
> max_size
) {
375 ret
= -E_INPUT_TOO_LARGE
;
378 tmp
= para_realloc(*buf
, size
);
379 p
= (p
- *buf
) + tmp
;
395 * Read from stdin, and send the result to the parent process.
397 * \param arg_obj Pointer to the arguments to \a f.
398 * \param f The callback function.
399 * \param max_len Don't read more than that many bytes from stdin.
400 * \param result The result of the query is stored here.
402 * This function is used by commands that wish to let para_server store
403 * arbitrary data specified by the user (for instance the add_blob family of
404 * commands). First, at most \a max_len bytes are read from stdin, the result
405 * is concatenated with the buffer given by \a arg_obj, and the combined buffer
406 * is made available to the parent process via shared memory.
408 * \return Negative on errors, the return value of the underlying call to
409 * send_callback_request() otherwise.
411 int stdin_command(struct osl_object
*arg_obj
, callback_function
*f
,
412 unsigned max_len
, struct osl_object
*result
)
416 struct osl_object query
;
417 int ret
= fd2buf(STDIN_FILENO
, &stdin_buf
, max_len
);
422 query
.size
= arg_obj
->size
+ stdin_len
;
423 query
.data
= para_malloc(query
.size
);
424 memcpy(query
.data
, arg_obj
->data
, arg_obj
->size
);
425 memcpy((char *)query
.data
+ arg_obj
->size
, stdin_buf
, stdin_len
);
427 ret
= send_callback_request(f
, &query
, result
);
433 * Open the audio file with highest score.
435 * \param afd Audio file data is returned here.
437 * This stores all information for streaming the "best" audio file
438 * in the \a afd structure.
440 * \return Positive on success, negative on errors.
442 * \sa close_audio_file(), open_and_update_audio_file().
444 int open_next_audio_file(struct audio_file_data
*afd
)
446 struct osl_row
*aft_row
;
449 ret
= score_get_best(&aft_row
, &afd
->score
);
452 ret
= open_and_update_audio_file(aft_row
, afd
);
459 * Free all resources which were allocated by open_next_audio_file().
461 * \param afd The structure previously filled in by open_next_audio_file().
463 * \return The return value of the underlying call to para_munmap().
465 * \sa open_next_audio_file().
467 int close_audio_file(struct audio_file_data
*afd
)
469 free(afd
->afhi
.chunk_table
);
470 return para_munmap(afd
->map
.data
, afd
->map
.size
);
474 static void play_loop(enum play_mode current_play_mode
)
477 struct audio_file_data afd
;
479 afd
.current_play_mode
= current_play_mode
;
480 for (i
= 0; i
< 0; i
++) {
481 ret
= open_next_audio_file(&afd
);
483 PARA_ERROR_LOG("failed to open next audio file: %d\n", ret
);
486 PARA_NOTICE_LOG("next audio file: %s, score: %li\n", afd
.path
, afd
.score
);
488 close_audio_file(&afd
);
494 static enum play_mode
init_admissible_files(void)
497 char *given_mood
, *given_playlist
;
499 given_mood
= "mood_that_was_given_at_the_command_line";
500 given_playlist
= "given_playlist";
503 ret
= mood_open(given_mood
);
506 PARA_WARNING_LOG("ignoring playlist %s\n",
508 return PLAY_MODE_MOOD
;
511 if (given_playlist
) {
512 ret
= playlist_open(given_playlist
);
514 return PLAY_MODE_PLAYLIST
;
516 ret
= mood_open(NULL
); /* open first available mood */
518 return PLAY_MODE_MOOD
;
519 mood_open(""); /* open dummy mood, always successful */
520 return PLAY_MODE_MOOD
;
523 static int setup_command_socket_or_die(void)
526 char *socket_name
= conf
.afs_socket_arg
;
527 struct sockaddr_un unix_addr
;
530 ret
= create_local_socket(socket_name
, &unix_addr
,
531 S_IRUSR
| S_IWUSR
| S_IRGRP
| S_IWGRP
| S_IWOTH
);
534 if (listen(ret
, 5) < 0) {
535 PARA_EMERG_LOG("%s", "can not listen on socket\n");
538 PARA_INFO_LOG("listening on command socket %s (fd %d)\n", socket_name
,
543 static int server_socket
;
551 static void afs_shutdown(enum osl_close_flags flags
)
553 PARA_NOTICE_LOG("cleaning up\n");
554 score_shutdown(flags
);
555 attribute_shutdown(flags
);
558 moods_shutdown(flags
);
559 playlists_shutdown(flags
);
560 lyrics_shutdown(flags
);
561 images_shutdown(flags
);
565 static void signal_pre_select(struct sched
*s
, struct task
*t
)
567 struct signal_task
*st
= t
->private_data
;
569 para_fd_set(st
->fd
, &s
->rfds
, &s
->max_fileno
);
572 static void signal_post_select(struct sched
*s
, struct task
*t
)
574 struct signal_task
*st
= t
->private_data
;
576 if (!FD_ISSET(st
->fd
, &s
->rfds
))
578 st
->signum
= para_next_signal();
579 PARA_NOTICE_LOG("caught signal %d\n", st
->signum
);
581 if (st
->signum
== SIGUSR1
)
582 return; /* ignore SIGUSR1 */
583 afs_shutdown(OSL_MARK_CLEAN
);
584 t
->ret
= -E_SIGNAL_CAUGHT
;
587 static void register_signal_task(void)
589 static struct signal_task signal_task_struct
;
590 struct signal_task
*st
= &signal_task_struct
;
591 st
->fd
= para_signal_init();
592 PARA_INFO_LOG("signal pipe: fd %d\n", st
->fd
);
593 para_install_sighandler(SIGINT
);
594 para_install_sighandler(SIGTERM
);
595 para_install_sighandler(SIGPIPE
);
597 st
->task
.pre_select
= signal_pre_select
;
598 st
->task
.post_select
= signal_post_select
;
599 st
->task
.private_data
= st
;
600 sprintf(st
->task
.status
, "signal task");
601 register_task(&st
->task
);
604 static void command_pre_select(struct sched
*s
, struct task
*t
)
606 struct command_task
*ct
= t
->private_data
;
608 para_fd_set(ct
->fd
, &s
->rfds
, &s
->max_fileno
);
612 * On errors, negative value is written to fd.
613 * On success: If query produced a result, the result_shmid is written to fd.
614 * Otherwise, zero is written.
616 static int call_callback(int fd
, int query_shmid
)
618 void *query_shm
, *result_shm
;
619 struct callback_query
*cq
;
620 struct callback_result
*cr
;
621 struct osl_object query
, result
= {.data
= NULL
};
622 int result_shmid
= -1, ret
, ret2
;
624 ret
= shm_attach(query_shmid
, ATTACH_RW
, &query_shm
);
628 query
.data
= (char *)query_shm
+ sizeof(*cq
);
629 query
.size
= cq
->query_size
;
630 ret
= cq
->handler(&query
, &result
);
631 ret2
= shm_detach(query_shm
);
632 if (ret2
< 0 && ret
>= 0)
637 if (!result
.data
|| !result
.size
)
639 ret
= shm_new(result
.size
+ sizeof(struct callback_result
));
643 ret
= shm_attach(result_shmid
, ATTACH_RW
, &result_shm
);
647 cr
->result_size
= result
.size
;
648 memcpy(result_shm
+ sizeof(*cr
), result
.data
, result
.size
);
649 ret
= shm_detach(result_shm
);
655 ret2
= send_bin_buffer(fd
, (char *)&ret
, sizeof(int));
656 if (ret
< 0 || ret2
< 0) {
657 if (result_shmid
>= 0)
658 if (shm_destroy(result_shmid
) < 0)
659 PARA_ERROR_LOG("destroy result failed\n");
666 static void command_post_select(struct sched
*s
, struct task
*t
)
668 struct command_task
*ct
= t
->private_data
;
669 struct sockaddr_un unix_addr
;
670 char buf
[sizeof(uint32_t) + sizeof(int)];
675 if (!FD_ISSET(ct
->fd
, &s
->rfds
))
677 t
->ret
= para_accept(ct
->fd
, &unix_addr
, sizeof(unix_addr
));
681 * The following errors may be caused by a malicious local user. So do
682 * not return an error in this case as this would terminate para_afs
686 /* FIXME: This is easily dosable (peer doesn't send data) */
687 t
->ret
= recv_bin_buffer(fd
, buf
, sizeof(buf
));
689 PARA_NOTICE_LOG("%s (%d)\n", PARA_STRERROR(-t
->ret
), t
->ret
);
693 if (t
->ret
!= sizeof(buf
)) {
694 PARA_NOTICE_LOG("short read (%d bytes, expected %d)\n",
695 t
->ret
, sizeof(buf
));
699 cookie
= *(uint32_t *)buf
;
700 if (cookie
!= ct
->cookie
) {
701 PARA_NOTICE_LOG("received invalid cookie(got %u, expected %u)\n",
702 (unsigned)cookie
, (unsigned)ct
->cookie
);
706 query_shmid
= *(int *)(buf
+ sizeof(cookie
));
707 if (query_shmid
< 0) {
708 PARA_WARNING_LOG("received invalid query shmid %d)\n",
713 t
->ret
= call_callback(fd
, query_shmid
);
715 PARA_NOTICE_LOG("%s\n", PARA_STRERROR(-t
->ret
));
723 static void register_command_task(uint32_t cookie
)
725 static struct command_task command_task_struct
;
726 struct command_task
*ct
= &command_task_struct
;
727 ct
->fd
= setup_command_socket_or_die();
730 ct
->task
.pre_select
= command_pre_select
;
731 ct
->task
.post_select
= command_post_select
;
732 ct
->task
.private_data
= ct
;
733 sprintf(ct
->task
.status
, "command task");
734 register_task(&ct
->task
);
737 void register_tasks(uint32_t cookie
)
739 register_signal_task();
740 register_command_task(cookie
);
743 __noreturn
int afs_init(uint32_t cookie
, int socket_fd
)
746 enum play_mode current_play_mode
;
749 server_socket
= socket_fd
;
750 PARA_INFO_LOG("server_socket: %d, afs_socket_cookie: %u\n",
751 server_socket
, (unsigned) cookie
);
753 ret
= attribute_init(&afs_tables
[TBLNUM_ATTRIBUTES
]);
755 goto attribute_init_error
;
756 ret
= moods_init(&afs_tables
[TBLNUM_MOODS
]);
758 goto moods_init_error
;
759 ret
= playlists_init(&afs_tables
[TBLNUM_PLAYLIST
]);
761 goto playlists_init_error
;
762 ret
= lyrics_init(&afs_tables
[TBLNUM_LYRICS
]);
764 goto lyrics_init_error
;
765 ret
= images_init(&afs_tables
[TBLNUM_IMAGES
]);
767 goto images_init_error
;
768 ret
= score_init(&afs_tables
[TBLNUM_SCORES
]);
770 goto score_init_error
;
771 ret
= aft_init(&afs_tables
[TBLNUM_AUDIO_FILES
]);
775 current_play_mode
= init_admissible_files();
776 register_tasks(cookie
);
777 s
.default_timeout
.tv_sec
= 0;
778 s
.default_timeout
.tv_usec
= 99 * 1000;
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
;