2 * Copyright (C) 2007 Andre Noll <maan@tuebingen.mpg.de>
4 * Licensed under the GPL v2. For licencing details see COPYING.
7 /** \file afs.c Paraslash's audio file selector. */
9 #include <netinet/in.h>
10 #include <sys/socket.h>
16 #include <arpa/inet.h>
21 #include "server_cmd.lsg.h"
22 #include "server.cmdline.h"
40 /** The osl tables used by afs. \sa blob.c. */
42 /** Contains audio file information. See aft.c. */
44 /** The table for the paraslash attributes. See attribute.c. */
47 * Paraslash's scoring system is based on Gaussian normal
48 * distributions, and the relevant data is stored in the rbtrees of an
49 * osl table containing only volatile columns. See score.c for
54 * A standard blob table containing the mood definitions. For details
58 /** A blob table containing lyrics on a per-song basis. */
60 /** Another blob table for images (for example album cover art). */
62 /** Yet another blob table for storing standard playlists. */
64 /** How many tables are in use? */
68 static struct afs_table afs_tables[NUM_AFS_TABLES] = {
69 [TBLNUM_AUDIO_FILES] = {.init = aft_init, .name = "audio_files"},
70 [TBLNUM_ATTRIBUTES] = {.init = attribute_init, .name = "attributes"},
71 [TBLNUM_SCORES] = {.init = score_init, .name = "scores"},
72 [TBLNUM_MOODS] = {.init = moods_init, .name = "moods"},
73 [TBLNUM_LYRICS] = {.init = lyrics_init, .name = "lyrics"},
74 [TBLNUM_IMAGES] = {.init = images_init, .name = "images"},
75 [TBLNUM_PLAYLIST] = {.init = playlists_init, .name = "playlists"},
79 /** The file descriptor for the local socket. */
82 * Value sent by the command handlers to identify themselves as
83 * children of the running para_server.
86 /** The associated task structure. */
91 extern struct misc_meta_data *mmd;
93 static int server_socket;
94 static struct command_task command_task_struct;
95 static struct signal_task *signal_task;
97 static enum play_mode current_play_mode;
98 static char *current_mop; /* mode or playlist specifier. NULL means dummy mood */
101 * A random number used to "authenticate" the connection.
103 * para_server picks this number by random before it forks the afs process. The
104 * command handlers know this number as well and write it to the afs socket,
105 * together with the id of the shared memory area which contains the payload of
106 * the afs command. A local process has to know this number to abuse the afs
107 * service provided by the local socket.
109 extern uint32_t afs_socket_cookie;
112 * Struct to let command handlers execute a callback in afs context.
114 * Commands that need to change the state of afs can't change the relevant data
115 * structures directly because commands are executed in a child process, i.e.
116 * they get their own virtual address space.
118 * This structure is used by \p send_callback_request() (executed from handler
119 * context) in order to let the afs process call the specified function. An
120 * instance of that structure is written to a shared memory area together with
121 * the arguments to the callback function. The identifier of the shared memory
122 * area is written to the command socket.
124 * The afs process accepts connections on the command socket and reads the
125 * shared memory id, attaches the corresponding area, calls the given handler to
126 * perform the desired action and to optionally compute a result.
128 * The result and a \p callback_result structure is then written to another
129 * shared memory area. The identifier for that area is written to the handler's
130 * command socket, so that the handler process can read the id, attach the
131 * shared memory area and use the result.
133 * \sa struct callback_result.
135 struct callback_query {
136 /** The function to be called. */
137 afs_callback *handler;
138 /** The number of bytes of the query */
143 * Structure embedded in the result of a callback.
145 * If the callback produced a result, an instance of that structure is embedded
146 * into the shared memory area holding the result, mainly to let the command
147 * handler know the size of the result.
149 * \sa struct callback_query.
151 struct callback_result {
152 /** The number of bytes of the result. */
154 /** The band designator (loglevel for the result). */
158 static int dispatch_result(int result_shmid, callback_result_handler *handler,
159 void *private_result_data)
161 struct osl_object result;
163 /* must attach r/w as result.data might get encrypted in-place. */
164 int ret2, ret = shm_attach(result_shmid, ATTACH_RW, &result_shm);
165 struct callback_result *cr = result_shm;
168 PARA_ERROR_LOG("attach failed: %s\n", para_strerror(-ret));
171 result.size = cr->result_size;
172 result.data = result_shm + sizeof(*cr);
174 ret = handler(&result, cr->band, private_result_data);
175 ret2 = shm_detach(result_shm);
177 PARA_ERROR_LOG("detach failed: %s\n", para_strerror(-ret2));
185 * Ask the afs process to call a given function.
187 * \param f The function to be called.
188 * \param query Pointer to arbitrary data for the callback.
189 * \param result_handler Called for each shm area sent by the callback.
190 * \param private_result_data Passed verbatim to \a result_handler.
192 * This function creates a socket for communication with the afs process and a
193 * shared memory area (sma) to which the buffer pointed to by \a query is
194 * copied. It then notifies the afs process that the callback function \a f
195 * should be executed by sending the shared memory identifier (shmid) to the
198 * If the callback produces a result, it sends any number of shared memory
199 * identifiers back via the socket. For each such identifier received, \a
200 * result_handler is called. The contents of the sma identified by the received
201 * shmid are passed to that function as an osl object. The private_result_data
202 * pointer is passed as the second argument to \a result_handler.
204 * \return Number of shared memory areas dispatched on success, negative on errors.
206 * \sa send_option_arg_callback_request(), send_standard_callback_request().
208 int send_callback_request(afs_callback *f, struct osl_object *query,
209 callback_result_handler *result_handler,
210 void *private_result_data)
212 struct callback_query *cq;
213 int ret, fd = -1, query_shmid, result_shmid;
215 char buf[sizeof(afs_socket_cookie) + sizeof(int)];
216 size_t query_shm_size = sizeof(*cq);
217 int dispatch_error = 0, num_dispatched = 0;
220 query_shm_size += query->size;
221 ret = shm_new(query_shm_size);
225 ret = shm_attach(query_shmid, ATTACH_RW, &query_shm);
230 cq->query_size = query_shm_size - sizeof(*cq);
233 memcpy(query_shm + sizeof(*cq), query->data, query->size);
234 ret = shm_detach(query_shm);
238 *(uint32_t *)buf = afs_socket_cookie;
239 *(int *)(buf + sizeof(afs_socket_cookie)) = query_shmid;
241 ret = connect_local_socket(conf.afs_socket_arg);
245 ret = write_all(fd, buf, sizeof(buf));
249 * Read all shmids from afs.
251 * Even if the dispatcher returns an error we _must_ continue to read
252 * shmids from fd so that we can destroy all shared memory areas that
253 * have been created for us by the afs process.
256 ret = recv_bin_buffer(fd, buf, sizeof(int));
259 assert(ret == sizeof(int));
263 ret = dispatch_result(result_shmid, result_handler,
264 private_result_data);
265 if (ret < 0 && dispatch_error >= 0)
266 dispatch_error = ret;
267 ret = shm_destroy(result_shmid);
269 PARA_CRIT_LOG("destroy result failed: %s\n",
270 para_strerror(-ret));
274 if (shm_destroy(query_shmid) < 0)
275 PARA_CRIT_LOG("shm destroy error\n");
278 if (dispatch_error < 0)
279 return dispatch_error;
282 return num_dispatched;
286 * Wrapper for send_callback_request() which passes a lopsub parse result.
288 * \param f The callback function.
289 * \param cmd Needed for (de-)serialization.
290 * \param lpr Must match cmd.
291 * \param private_result_data Passed to send_callback_request().
293 * This function serializes the parse result given by the lpr pointer into a
294 * buffer. The buffer is sent as the query to the afs process with the callback
297 * \return The return value of the underlying call to send_callback_request().
299 int send_lls_callback_request(afs_callback *f,
300 const struct lls_command * const cmd,
301 struct lls_parse_result *lpr, void *private_result_data)
303 struct osl_object query;
305 int ret = lls_serialize_parse_result(lpr, cmd, &buf, &query.size);
309 ret = send_callback_request(f, &query, afs_cb_result_handler,
310 private_result_data);
316 * Send a callback request passing an options structure and an argument vector.
318 * \param options pointer to an arbitrary data structure.
319 * \param argc Argument count.
320 * \param argv Standard argument vector.
321 * \param f The callback function.
322 * \param result_handler See \ref send_callback_request.
323 * \param private_result_data See \ref send_callback_request.
325 * Some command handlers pass command-specific options to a callback, together
326 * with a list of further arguments (often a list of audio files). This
327 * function allows to pass an arbitrary structure (given as an osl object) and
328 * a usual argument vector to the specified callback.
330 * \return The return value of the underlying call to \ref
331 * send_callback_request().
333 * \sa send_standard_callback_request(), send_callback_request().
335 int send_option_arg_callback_request(struct osl_object *options,
336 int argc, char * const * const argv, afs_callback *f,
337 callback_result_handler *result_handler,
338 void *private_result_data)
342 struct osl_object query = {.size = options? options->size : 0};
344 for (i = 0; i < argc; i++)
345 query.size += strlen(argv[i]) + 1;
346 query.data = para_malloc(query.size);
349 memcpy(query.data, options->data, options->size);
352 for (i = 0; i < argc; i++) {
353 strcpy(p, argv[i]); /* OK */
354 p += strlen(argv[i]) + 1;
356 ret = send_callback_request(f, &query, result_handler,
357 private_result_data);
363 * Send a callback request with an argument vector only.
365 * \param argc The same meaning as in send_option_arg_callback_request().
366 * \param argv The same meaning as in send_option_arg_callback_request().
367 * \param f The same meaning as in send_option_arg_callback_request().
368 * \param result_handler See \ref send_callback_request.
369 * \param private_result_data See \ref send_callback_request.
371 * This is similar to send_option_arg_callback_request(), but no options buffer
372 * is passed to the parent process.
374 * \return The return value of the underlying call to
375 * send_option_arg_callback_request().
377 int send_standard_callback_request(int argc, char * const * const argv,
378 afs_callback *f, callback_result_handler *result_handler,
379 void *private_result_data)
381 return send_option_arg_callback_request(NULL, argc, argv, f, result_handler,
382 private_result_data);
385 static int action_if_pattern_matches(struct osl_row *row, void *data)
387 struct pattern_match_data *pmd = data;
388 struct osl_object name_obj;
389 const char *p, *name;
390 int i, ret = osl(osl_get_object(pmd->table, row, pmd->match_col_num, &name_obj));
391 const char *pattern_txt = (const char *)pmd->patterns.data;
395 name = (char *)name_obj.data;
396 if ((!name || !*name) && (pmd->pm_flags & PM_SKIP_EMPTY_NAME))
398 if ((pmd->lpr && lls_num_inputs(pmd->lpr) == 0) || pmd->patterns.size == 0) {
399 if (pmd->pm_flags & PM_NO_PATTERN_MATCHES_EVERYTHING) {
401 return pmd->action(pmd->table, row, name, pmd->data);
408 if (i >= lls_num_inputs(pmd->lpr))
410 p = lls_input(i, pmd->lpr);
412 if (p >= pattern_txt + pmd->patterns.size)
415 ret = fnmatch(p, name, pmd->fnmatch_flags);
416 if (ret != FNM_NOMATCH) {
419 ret = pmd->action(pmd->table, row, name, pmd->data);
434 * Execute the given function for each matching row.
436 * \param pmd Describes what to match and how.
440 int for_each_matching_row(struct pattern_match_data *pmd)
442 if (pmd->pm_flags & PM_REVERSE_LOOP)
443 return osl(osl_rbtree_loop_reverse(pmd->table, pmd->loop_col_num, pmd,
444 action_if_pattern_matches));
445 return osl(osl_rbtree_loop(pmd->table, pmd->loop_col_num, pmd,
446 action_if_pattern_matches));
450 * Compare two osl objects of string type.
452 * \param obj1 Pointer to the first object.
453 * \param obj2 Pointer to the second object.
455 * In any case, only \p MIN(obj1->size, obj2->size) characters of each string
456 * are taken into account.
458 * \return It returns an integer less than, equal to, or greater than zero if
459 * \a obj1 is found, respectively, to be less than, to match, or be greater than
462 * \sa strcmp(3), strncmp(3), osl_compare_func.
464 int string_compare(const struct osl_object *obj1, const struct osl_object *obj2)
466 const char *str1 = (const char *)obj1->data;
467 const char *str2 = (const char *)obj2->data;
468 return strncmp(str1, str2, PARA_MIN(obj1->size, obj2->size));
471 static int pass_afd(int fd, char *buf, size_t size)
473 struct msghdr msg = {.msg_iov = NULL};
474 struct cmsghdr *cmsg;
475 char control[255] __a_aligned(8);
485 msg.msg_control = control;
486 msg.msg_controllen = sizeof(control);
488 cmsg = CMSG_FIRSTHDR(&msg);
489 cmsg->cmsg_level = SOL_SOCKET;
490 cmsg->cmsg_type = SCM_RIGHTS;
491 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
492 *(int *)CMSG_DATA(cmsg) = fd;
494 /* Sum of the length of all control messages in the buffer */
495 msg.msg_controllen = cmsg->cmsg_len;
496 PARA_DEBUG_LOG("passing %zu bytes and fd %d\n", size, fd);
497 ret = sendmsg(server_socket, &msg, 0);
499 ret = -ERRNO_TO_PARA_ERROR(errno);
506 * Pass the fd of the next audio file to the server process.
508 * This stores all information for streaming the "best" audio file in a shared
509 * memory area. The id of that area and an open file descriptor for the next
510 * audio file are passed to the server process.
514 * \sa open_and_update_audio_file().
516 static int open_next_audio_file(void)
518 struct audio_file_data afd;
522 ret = open_and_update_audio_file(&afd);
524 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
525 goto no_admissible_files;
528 if (!write_ok(server_socket)) {
532 *(uint32_t *)buf = NEXT_AUDIO_FILE;
533 *(uint32_t *)(buf + 4) = (uint32_t)shmid;
534 ret = pass_afd(afd.fd, buf, 8);
542 *(uint32_t *)buf = NO_ADMISSIBLE_FILES;
543 *(uint32_t *)(buf + 4) = (uint32_t)0;
544 return write_all(server_socket, buf, 8);
547 /* Never fails if arg == NULL */
548 static int activate_mood_or_playlist(const char *arg, int *num_admissible)
554 ret = change_current_mood(NULL); /* always successful */
555 mode = PLAY_MODE_MOOD;
557 if (!strncmp(arg, "p/", 2)) {
558 ret = playlist_open(arg + 2);
559 mode = PLAY_MODE_PLAYLIST;
560 } else if (!strncmp(arg, "m/", 2)) {
561 ret = change_current_mood(arg + 2);
562 mode = PLAY_MODE_MOOD;
564 return -E_AFS_SYNTAX;
569 *num_admissible = ret;
570 current_play_mode = mode;
571 if (arg != current_mop) {
574 current_mop = para_strdup(arg);
575 mutex_lock(mmd_mutex);
576 strncpy(mmd->afs_mode_string, arg,
577 sizeof(mmd->afs_mode_string));
578 mmd->afs_mode_string[sizeof(mmd->afs_mode_string) - 1] = '\0';
579 mutex_unlock(mmd_mutex);
581 mutex_lock(mmd_mutex);
582 strcpy(mmd->afs_mode_string, "dummy");
583 mutex_unlock(mmd_mutex);
591 * Result handler for sending data to the para_client process.
593 * \param result The data to be sent.
594 * \param band The band designator.
595 * \param private Pointer to the command context.
597 * \return The return value of the underlying call to \ref command.c::send_sb.
599 * \sa \ref callback_result_handler, \ref command.c::send_sb.
601 int afs_cb_result_handler(struct osl_object *result, uint8_t band,
604 struct command_context *cc = private;
612 case SBD_WARNING_LOG:
616 assert(result->size > 0);
617 return send_sb(&cc->scc, result->data, result->size, band, true);
618 case SBD_AFS_CB_FAILURE:
619 return *(int *)(result->data);
625 static void flush_and_free_pb(struct para_buffer *pb)
628 struct afs_max_size_handler_data *amshd = pb->private_data;
630 if (pb->buf && pb->size > 0) {
631 ret = pass_buffer_as_shm(amshd->fd, amshd->band, pb->buf,
634 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
639 static int com_select_callback(struct afs_callback_arg *aca)
641 const char *arg = aca->query.data;
642 int num_admissible, ret;
644 ret = clear_score_table();
646 para_printf(&aca->pbout, "could not clear score table: %s\n",
647 para_strerror(-ret));
650 if (current_play_mode == PLAY_MODE_MOOD)
651 close_current_mood();
654 ret = activate_mood_or_playlist(arg, &num_admissible);
657 /* ignore subsequent errors (but log them) */
658 para_printf(&aca->pbout, "could not activate %s\n", arg);
661 para_printf(&aca->pbout, "switching back to %s\n", current_mop);
662 ret2 = activate_mood_or_playlist(current_mop, &num_admissible);
665 para_printf(&aca->pbout, "could not reactivate %s: %s\n",
666 current_mop, para_strerror(-ret2));
668 para_printf(&aca->pbout, "activating dummy mood\n");
669 activate_mood_or_playlist(NULL, &num_admissible);
671 para_printf(&aca->pbout, "activated %s (%d admissible files)\n",
672 current_mop? current_mop : "dummy mood", num_admissible);
676 int com_select(struct command_context *cc)
678 struct osl_object query;
681 return -E_AFS_SYNTAX;
682 query.data = cc->argv[1];
683 query.size = strlen(cc->argv[1]) + 1;
684 return send_callback_request(com_select_callback, &query,
685 &afs_cb_result_handler, cc);
688 static void init_admissible_files(char *arg)
690 if (activate_mood_or_playlist(arg, NULL) < 0)
691 activate_mood_or_playlist(NULL, NULL); /* always successful */
694 static int setup_command_socket_or_die(void)
697 char *socket_name = conf.afs_socket_arg;
700 ret = create_local_socket(socket_name, 0);
702 ret = create_local_socket(socket_name,
703 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IROTH);
705 PARA_EMERG_LOG("%s: %s\n", para_strerror(-ret),
711 PARA_INFO_LOG("listening on socket %s (fd %d)\n", socket_name,
716 static void close_afs_tables(void)
719 PARA_NOTICE_LOG("closing afs_tables\n");
720 for (i = 0; i < NUM_AFS_TABLES; i++)
721 afs_tables[i].close();
724 static char *database_dir;
726 static void get_database_dir(void)
729 if (conf.afs_database_dir_given)
730 database_dir = para_strdup(conf.afs_database_dir_arg);
732 char *home = para_homedir();
733 database_dir = make_message(
734 "%s/.paraslash/afs_database-0.4", home);
738 PARA_INFO_LOG("afs_database dir %s\n", database_dir);
741 static int make_database_dir(void)
746 ret = para_mkdir(database_dir, 0777);
747 if (ret >= 0 || ret == -ERRNO_TO_PARA_ERROR(EEXIST))
752 static int open_afs_tables(void)
757 PARA_NOTICE_LOG("opening %d osl tables in %s\n", NUM_AFS_TABLES,
759 for (i = 0; i < NUM_AFS_TABLES; i++) {
760 ret = afs_tables[i].open(database_dir);
763 PARA_ERROR_LOG("%s init: %s\n", afs_tables[i].name,
764 para_strerror(-ret));
770 afs_tables[--i].close();
774 static int afs_signal_post_select(struct sched *s, __a_unused void *context)
778 if (getppid() == 1) {
779 PARA_EMERG_LOG("para_server died\n");
782 signum = para_next_signal(&s->rfds);
785 if (signum == SIGHUP) {
787 parse_config_or_die(1);
788 ret = open_afs_tables();
791 init_admissible_files(current_mop);
794 PARA_EMERG_LOG("terminating on signal %d\n", signum);
796 task_notify_all(s, E_AFS_SIGNAL);
797 return -E_AFS_SIGNAL;
800 static void register_signal_task(struct sched *s)
802 para_sigaction(SIGPIPE, SIG_IGN);
803 signal_task = signal_init_or_die();
804 para_install_sighandler(SIGINT);
805 para_install_sighandler(SIGTERM);
806 para_install_sighandler(SIGHUP);
808 signal_task->task = task_register(&(struct task_info) {
810 .pre_select = signal_pre_select,
811 .post_select = afs_signal_post_select,
812 .context = signal_task,
817 static struct list_head afs_client_list;
819 /** Describes one connected afs client. */
821 /** Position in the afs client list. */
822 struct list_head node;
823 /** The socket file descriptor for this client. */
825 /** The time the client connected. */
826 struct timeval connect_time;
829 static void command_pre_select(struct sched *s, void *context)
831 struct command_task *ct = context;
832 struct afs_client *client;
834 para_fd_set(server_socket, &s->rfds, &s->max_fileno);
835 para_fd_set(ct->fd, &s->rfds, &s->max_fileno);
836 list_for_each_entry(client, &afs_client_list, node)
837 para_fd_set(client->fd, &s->rfds, &s->max_fileno);
841 * Send data as shared memory to a file descriptor.
843 * \param fd File descriptor to send the shmid to.
844 * \param band The band designator for this data.
845 * \param buf The buffer holding the data to be sent.
846 * \param size The size of \a buf.
848 * This function creates a shared memory area large enough to hold
849 * the content given by \a buf and \a size and sends the identifier
850 * of this area to the file descriptor \a fd.
852 * It is called by the AFS max_size handler as well as directly by the AFS
853 * command callbacks to send command output to the command handlers.
855 * \return Zero if \a buf is \p NULL or \a size is zero. Negative on errors,
856 * and positive on success.
858 int pass_buffer_as_shm(int fd, uint8_t band, const char *buf, size_t size)
862 struct callback_result *cr;
865 assert(band != SBD_OUTPUT);
866 ret = shm_new(size + sizeof(*cr));
870 ret = shm_attach(shmid, ATTACH_RW, &shm);
874 cr->result_size = size;
877 memcpy(shm + sizeof(*cr), buf, size);
878 ret = shm_detach(shm);
881 ret = write_all(fd, (char *)&shmid, sizeof(int));
885 if (shm_destroy(shmid) < 0)
886 PARA_ERROR_LOG("destroy result failed\n");
890 static int call_callback(int fd, int query_shmid)
893 struct callback_query *cq;
895 struct afs_callback_arg aca = {.fd = fd};
897 ret = shm_attach(query_shmid, ATTACH_RW, &query_shm);
901 aca.query.data = (char *)query_shm + sizeof(*cq);
902 aca.query.size = cq->query_size;
903 aca.pbout.max_size = shm_get_shmmax();
904 aca.pbout.max_size_handler = afs_max_size_handler;
905 aca.pbout.private_data = &(struct afs_max_size_handler_data) {
909 ret = cq->handler(&aca);
910 ret2 = shm_detach(query_shm);
912 if (ret < 0) /* ignore (but log) detach error */
913 PARA_ERROR_LOG("could not detach sma: %s\n",
914 para_strerror(-ret2));
918 flush_and_free_pb(&aca.pbout);
920 ret2 = pass_buffer_as_shm(fd, SBD_AFS_CB_FAILURE,
921 (const char *)&ret, sizeof(ret));
923 PARA_ERROR_LOG("could not pass cb failure packet: %s\n",
924 para_strerror(-ret));
929 static int execute_server_command(fd_set *rfds)
933 int ret = read_nonblock(server_socket, buf, sizeof(buf) - 1, rfds, &n);
935 if (ret < 0 || n == 0)
938 if (strcmp(buf, "new"))
939 return -ERRNO_TO_PARA_ERROR(EINVAL);
940 return open_next_audio_file();
943 /* returns 0 if no data available, 1 else */
944 static int execute_afs_command(int fd, fd_set *rfds, uint32_t expected_cookie)
948 char buf[sizeof(cookie) + sizeof(query_shmid)];
950 int ret = read_nonblock(fd, buf, sizeof(buf), rfds, &n);
956 if (n != sizeof(buf)) {
957 PARA_NOTICE_LOG("short read (%d bytes, expected %lu)\n",
958 ret, (long unsigned) sizeof(buf));
961 cookie = *(uint32_t *)buf;
962 if (cookie != expected_cookie) {
963 PARA_NOTICE_LOG("received invalid cookie (got %u, expected %u)\n",
964 (unsigned)cookie, (unsigned)expected_cookie);
967 query_shmid = *(int *)(buf + sizeof(cookie));
968 if (query_shmid < 0) {
969 PARA_WARNING_LOG("received invalid query shmid %d)\n",
973 ret = call_callback(fd, query_shmid);
977 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
981 /** Shutdown connection if query has not arrived until this many seconds. */
982 #define AFS_CLIENT_TIMEOUT 3
984 static int command_post_select(struct sched *s, void *context)
986 struct command_task *ct = context;
987 struct sockaddr_un unix_addr;
988 struct afs_client *client, *tmp;
991 ret = task_get_notification(ct->task);
994 ret = execute_server_command(&s->rfds);
996 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
997 task_notify_all(s, -ret);
1000 /* Check the list of connected clients. */
1001 list_for_each_entry_safe(client, tmp, &afs_client_list, node) {
1002 ret = execute_afs_command(client->fd, &s->rfds, ct->cookie);
1003 if (ret == 0) { /* prevent bogus connection flooding */
1004 struct timeval diff;
1005 tv_diff(now, &client->connect_time, &diff);
1006 if (diff.tv_sec < AFS_CLIENT_TIMEOUT)
1008 PARA_WARNING_LOG("connection timeout\n");
1011 list_del(&client->node);
1014 /* Accept connections on the local socket. */
1015 ret = para_accept(ct->fd, &s->rfds, &unix_addr, sizeof(unix_addr), &fd);
1017 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
1020 ret = mark_fd_nonblocking(fd);
1022 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
1026 client = para_malloc(sizeof(*client));
1028 client->connect_time = *now;
1029 para_list_add(&client->node, &afs_client_list);
1033 static void register_command_task(uint32_t cookie, struct sched *s)
1035 struct command_task *ct = &command_task_struct;
1036 ct->fd = setup_command_socket_or_die();
1037 ct->cookie = cookie;
1039 ct->task = task_register(&(struct task_info) {
1040 .name = "afs command",
1041 .pre_select = command_pre_select,
1042 .post_select = command_post_select,
1048 * Initialize the audio file selector process.
1050 * \param cookie The value used for "authentication".
1051 * \param socket_fd File descriptor used for communication with the server.
1053 __noreturn void afs_init(uint32_t cookie, int socket_fd)
1055 static struct sched s;
1058 register_signal_task(&s);
1059 INIT_LIST_HEAD(&afs_client_list);
1060 for (i = 0; i < NUM_AFS_TABLES; i++)
1061 afs_tables[i].init(&afs_tables[i]);
1062 ret = open_afs_tables();
1065 server_socket = socket_fd;
1066 ret = mark_fd_nonblocking(server_socket);
1069 PARA_INFO_LOG("server_socket: %d, afs_socket_cookie: %u\n",
1070 server_socket, (unsigned) cookie);
1071 init_admissible_files(conf.afs_initial_mode_arg);
1072 register_command_task(cookie, &s);
1073 s.default_timeout.tv_sec = 0;
1074 s.default_timeout.tv_usec = 999 * 1000;
1075 ret = write(socket_fd, "\0", 1);
1079 ret = -ERRNO_TO_PARA_ERROR(errno);
1088 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1092 static int com_init_callback(struct afs_callback_arg *aca)
1094 uint32_t table_mask = *(uint32_t *)aca->query.data;
1098 for (i = 0; i < NUM_AFS_TABLES; i++) {
1099 struct afs_table *t = &afs_tables[i];
1101 if (!(table_mask & (1 << i)))
1105 ret = t->create(database_dir);
1107 para_printf(&aca->pbout, "cannot create table %s\n",
1111 para_printf(&aca->pbout, "successfully created %s table\n",
1114 ret = open_afs_tables();
1116 para_printf(&aca->pbout, "cannot open afs tables\n");
1121 static int com_init(struct command_context *cc, struct lls_parse_result *lpr)
1124 uint32_t table_mask = (1 << (NUM_AFS_TABLES + 1)) - 1;
1125 struct osl_object query = {.data = &table_mask,
1126 .size = sizeof(table_mask)};
1127 unsigned num_inputs = lls_num_inputs(lpr);
1129 ret = make_database_dir();
1132 if (num_inputs > 0) {
1134 for (i = 0; i < num_inputs; i++) {
1135 for (j = 0; j < NUM_AFS_TABLES; j++) {
1136 struct afs_table *t = &afs_tables[j];
1138 if (strcmp(lls_input(i, lpr), t->name))
1140 table_mask |= (1 << j);
1143 if (j == NUM_AFS_TABLES)
1144 return -E_BAD_TABLE_NAME;
1147 return send_callback_request(com_init_callback, &query,
1148 afs_cb_result_handler, cc);
1150 EXPORT_SERVER_CMD_HANDLER(init);
1152 static int com_check(struct command_context *cc, struct lls_parse_result *lpr)
1154 const struct lls_opt_result *r_a = SERVER_CMD_OPT_RESULT(CHECK, AFT, lpr);
1155 const struct lls_opt_result *r_A = SERVER_CMD_OPT_RESULT(CHECK, ATTRIBUTE, lpr);
1156 const struct lls_opt_result *r_m = SERVER_CMD_OPT_RESULT(CHECK, MOOD, lpr);
1157 const struct lls_opt_result *r_p = SERVER_CMD_OPT_RESULT(CHECK, PLAYLIST, lpr);
1158 bool noopt = !lls_opt_given(r_a) && !lls_opt_given(r_A)
1159 && !lls_opt_given(r_m) && !lls_opt_given(r_p);
1162 if (noopt || lls_opt_given(r_a)) {
1163 ret = send_callback_request(aft_check_callback, NULL,
1164 afs_cb_result_handler, cc);
1168 if (noopt || lls_opt_given(r_A)) {
1169 ret = send_callback_request(attribute_check_callback, NULL,
1170 afs_cb_result_handler, cc);
1174 if (noopt || lls_opt_given(r_p)) {
1175 ret = send_callback_request(playlist_check_callback,
1176 NULL, afs_cb_result_handler, cc);
1180 if (noopt || lls_opt_given(r_m)) {
1181 ret = send_callback_request(mood_check_callback, NULL,
1182 afs_cb_result_handler, cc);
1188 EXPORT_SERVER_CMD_HANDLER(check);
1191 * The afs event dispatcher.
1193 * \param event Type of the event.
1194 * \param pb May be \p NULL.
1195 * \param data Type depends on \a event.
1197 * This function calls each table event handler, passing \a pb and \a data
1198 * verbatim. It's up to the handlers to interpret the \a data pointer. If a
1199 * handler returns negative, the loop is aborted.
1201 * \return The (negative) error code of the first handler that failed, or non-negative
1202 * if all handlers succeeded.
1204 __must_check int afs_event(enum afs_events event, struct para_buffer *pb,
1209 for (i = 0; i < NUM_AFS_TABLES; i++) {
1210 struct afs_table *t = &afs_tables[i];
1211 if (!t->event_handler)
1213 ret = t->event_handler(event, pb, data);
1215 PARA_CRIT_LOG("table %s, event %u: %s\n", t->name,
1216 event, para_strerror(-ret));
1224 * Dummy event handler for the images table.
1226 * \param event Unused.
1228 * \param data Unused.
1230 * \return The images table does not honor events, so this handler always
1233 __a_const int images_event_handler(__a_unused enum afs_events event,
1234 __a_unused struct para_buffer *pb, __a_unused void *data)
1240 * Dummy event handler for the lyrics table.
1242 * \param event Unused.
1244 * \param data Unused.
1246 * \return The lyrics table does not honor events, so this handler always
1249 __a_const int lyrics_event_handler(__a_unused enum afs_events event,
1250 __a_unused struct para_buffer *pb, __a_unused void *data)