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.cmdline.h"
39 /** The osl tables used by afs. \sa blob.c. */
41 /** Contains audio file information. See aft.c. */
43 /** The table for the paraslash attributes. See attribute.c. */
46 * Paraslash's scoring system is based on Gaussian normal
47 * distributions, and the relevant data is stored in the rbtrees of an
48 * osl table containing only volatile columns. See score.c for
53 * A standard blob table containing the mood definitions. For details
57 /** A blob table containing lyrics on a per-song basis. */
59 /** Another blob table for images (for example album cover art). */
61 /** Yet another blob table for storing standard playlists. */
63 /** How many tables are in use? */
67 static struct afs_table afs_tables[NUM_AFS_TABLES] = {
68 [TBLNUM_AUDIO_FILES] = {.init = aft_init, .name = "audio_files"},
69 [TBLNUM_ATTRIBUTES] = {.init = attribute_init, .name = "attributes"},
70 [TBLNUM_SCORES] = {.init = score_init, .name = "scores"},
71 [TBLNUM_MOODS] = {.init = moods_init, .name = "moods"},
72 [TBLNUM_LYRICS] = {.init = lyrics_init, .name = "lyrics"},
73 [TBLNUM_IMAGES] = {.init = images_init, .name = "images"},
74 [TBLNUM_PLAYLIST] = {.init = playlists_init, .name = "playlists"},
78 /** The file descriptor for the local socket. */
81 * Value sent by the command handlers to identify themselves as
82 * children of the running para_server.
85 /** The associated task structure. */
90 extern struct misc_meta_data *mmd;
92 static int server_socket;
93 static struct command_task command_task_struct;
94 static struct signal_task *signal_task;
96 static enum play_mode current_play_mode;
97 static char *current_mop; /* mode or playlist specifier. NULL means dummy mood */
100 * A random number used to "authenticate" the connection.
102 * para_server picks this number by random before it forks the afs process. The
103 * command handlers know this number as well and write it to the afs socket,
104 * together with the id of the shared memory area which contains the payload of
105 * the afs command. A local process has to know this number to abuse the afs
106 * service provided by the local socket.
108 extern uint32_t afs_socket_cookie;
111 * Struct to let command handlers execute a callback in afs context.
113 * Commands that need to change the state of afs can't change the relevant data
114 * structures directly because commands are executed in a child process, i.e.
115 * they get their own virtual address space.
117 * This structure is used by \p send_callback_request() (executed from handler
118 * context) in order to let the afs process call the specified function. An
119 * instance of that structure is written to a shared memory area together with
120 * the arguments to the callback function. The identifier of the shared memory
121 * area is written to the command socket.
123 * The afs process accepts connections on the command socket and reads the
124 * shared memory id, attaches the corresponding area, calls the given handler to
125 * perform the desired action and to optionally compute a result.
127 * The result and a \p callback_result structure is then written to another
128 * shared memory area. The identifier for that area is written to the handler's
129 * command socket, so that the handler process can read the id, attach the
130 * shared memory area and use the result.
132 * \sa struct callback_result.
134 struct callback_query {
135 /** The function to be called. */
136 afs_callback *handler;
137 /** The number of bytes of the query */
142 * Structure embedded in the result of a callback.
144 * If the callback produced a result, an instance of that structure is embedded
145 * into the shared memory area holding the result, mainly to let the command
146 * handler know the size of the result.
148 * \sa struct callback_query.
150 struct callback_result {
151 /** The number of bytes of the result. */
153 /** The band designator (loglevel for the result). */
157 static int dispatch_result(int result_shmid, callback_result_handler *handler,
158 void *private_result_data)
160 struct osl_object result;
162 /* must attach r/w as result.data might get encrypted in-place. */
163 int ret2, ret = shm_attach(result_shmid, ATTACH_RW, &result_shm);
164 struct callback_result *cr = result_shm;
167 PARA_ERROR_LOG("attach failed: %s\n", para_strerror(-ret));
170 result.size = cr->result_size;
171 result.data = result_shm + sizeof(*cr);
173 ret = handler(&result, cr->band, private_result_data);
174 ret2 = shm_detach(result_shm);
176 PARA_ERROR_LOG("detach failed: %s\n", para_strerror(-ret2));
184 * Ask the afs process to call a given function.
186 * \param f The function to be called.
187 * \param query Pointer to arbitrary data for the callback.
188 * \param result_handler Called for each shm area sent by the callback.
189 * \param private_result_data Passed verbatim to \a result_handler.
191 * This function creates a socket for communication with the afs process and a
192 * shared memory area (sma) to which the buffer pointed to by \a query is
193 * copied. It then notifies the afs process that the callback function \a f
194 * should be executed by sending the shared memory identifier (shmid) to the
197 * If the callback produces a result, it sends any number of shared memory
198 * identifiers back via the socket. For each such identifier received, \a
199 * result_handler is called. The contents of the sma identified by the received
200 * shmid are passed to that function as an osl object. The private_result_data
201 * pointer is passed as the second argument to \a result_handler.
203 * \return Number of shared memory areas dispatched on success, negative on errors.
205 * \sa send_option_arg_callback_request(), send_standard_callback_request().
207 int send_callback_request(afs_callback *f, struct osl_object *query,
208 callback_result_handler *result_handler,
209 void *private_result_data)
211 struct callback_query *cq;
212 int ret, fd = -1, query_shmid, result_shmid;
214 char buf[sizeof(afs_socket_cookie) + sizeof(int)];
215 size_t query_shm_size = sizeof(*cq);
216 int dispatch_error = 0, num_dispatched = 0;
219 query_shm_size += query->size;
220 ret = shm_new(query_shm_size);
224 ret = shm_attach(query_shmid, ATTACH_RW, &query_shm);
229 cq->query_size = query_shm_size - sizeof(*cq);
232 memcpy(query_shm + sizeof(*cq), query->data, query->size);
233 ret = shm_detach(query_shm);
237 *(uint32_t *)buf = afs_socket_cookie;
238 *(int *)(buf + sizeof(afs_socket_cookie)) = query_shmid;
240 ret = connect_local_socket(conf.afs_socket_arg);
244 ret = write_all(fd, buf, sizeof(buf));
248 * Read all shmids from afs.
250 * Even if the dispatcher returns an error we _must_ continue to read
251 * shmids from fd so that we can destroy all shared memory areas that
252 * have been created for us by the afs process.
255 ret = recv_bin_buffer(fd, buf, sizeof(int));
258 assert(ret == sizeof(int));
262 ret = dispatch_result(result_shmid, result_handler,
263 private_result_data);
264 if (ret < 0 && dispatch_error >= 0)
265 dispatch_error = ret;
266 ret = shm_destroy(result_shmid);
268 PARA_CRIT_LOG("destroy result failed: %s\n",
269 para_strerror(-ret));
273 if (shm_destroy(query_shmid) < 0)
274 PARA_CRIT_LOG("shm destroy error\n");
277 if (dispatch_error < 0)
278 return dispatch_error;
281 return num_dispatched;
285 * Wrapper for send_callback_request() which passes a lopsub parse result.
287 * \param f The callback function.
288 * \param cmd Needed for (de-)serialization.
289 * \param lpr Must match cmd.
290 * \param private_result_data Passed to send_callback_request().
292 * This function serializes the parse result given by the lpr pointer into a
293 * buffer. The buffer is sent as the query to the afs process with the callback
296 * \return The return value of the underlying call to send_callback_request().
298 int send_lls_callback_request(afs_callback *f,
299 const struct lls_command * const cmd,
300 struct lls_parse_result *lpr, void *private_result_data)
302 struct osl_object query;
304 int ret = lls_serialize_parse_result(lpr, cmd, &buf, &query.size);
308 ret = send_callback_request(f, &query, afs_cb_result_handler,
309 private_result_data);
315 * Send a callback request passing an options structure and an argument vector.
317 * \param options pointer to an arbitrary data structure.
318 * \param argc Argument count.
319 * \param argv Standard argument vector.
320 * \param f The callback function.
321 * \param result_handler See \ref send_callback_request.
322 * \param private_result_data See \ref send_callback_request.
324 * Some command handlers pass command-specific options to a callback, together
325 * with a list of further arguments (often a list of audio files). This
326 * function allows to pass an arbitrary structure (given as an osl object) and
327 * a usual argument vector to the specified callback.
329 * \return The return value of the underlying call to \ref
330 * send_callback_request().
332 * \sa send_standard_callback_request(), send_callback_request().
334 int send_option_arg_callback_request(struct osl_object *options,
335 int argc, char * const * const argv, afs_callback *f,
336 callback_result_handler *result_handler,
337 void *private_result_data)
341 struct osl_object query = {.size = options? options->size : 0};
343 for (i = 0; i < argc; i++)
344 query.size += strlen(argv[i]) + 1;
345 query.data = para_malloc(query.size);
348 memcpy(query.data, options->data, options->size);
351 for (i = 0; i < argc; i++) {
352 strcpy(p, argv[i]); /* OK */
353 p += strlen(argv[i]) + 1;
355 ret = send_callback_request(f, &query, result_handler,
356 private_result_data);
362 * Send a callback request with an argument vector only.
364 * \param argc The same meaning as in send_option_arg_callback_request().
365 * \param argv The same meaning as in send_option_arg_callback_request().
366 * \param f The same meaning as in send_option_arg_callback_request().
367 * \param result_handler See \ref send_callback_request.
368 * \param private_result_data See \ref send_callback_request.
370 * This is similar to send_option_arg_callback_request(), but no options buffer
371 * is passed to the parent process.
373 * \return The return value of the underlying call to
374 * send_option_arg_callback_request().
376 int send_standard_callback_request(int argc, char * const * const argv,
377 afs_callback *f, callback_result_handler *result_handler,
378 void *private_result_data)
380 return send_option_arg_callback_request(NULL, argc, argv, f, result_handler,
381 private_result_data);
384 static int action_if_pattern_matches(struct osl_row *row, void *data)
386 struct pattern_match_data *pmd = data;
387 struct osl_object name_obj;
388 const char *p, *name;
389 int i, ret = osl(osl_get_object(pmd->table, row, pmd->match_col_num, &name_obj));
390 const char *pattern_txt = (const char *)pmd->patterns.data;
394 name = (char *)name_obj.data;
395 if ((!name || !*name) && (pmd->pm_flags & PM_SKIP_EMPTY_NAME))
397 if ((pmd->lpr && lls_num_inputs(pmd->lpr) == 0) || pmd->patterns.size == 0) {
398 if (pmd->pm_flags & PM_NO_PATTERN_MATCHES_EVERYTHING) {
400 return pmd->action(pmd->table, row, name, pmd->data);
407 if (i >= lls_num_inputs(pmd->lpr))
409 p = lls_input(i, pmd->lpr);
411 if (p >= pattern_txt + pmd->patterns.size)
414 ret = fnmatch(p, name, pmd->fnmatch_flags);
415 if (ret != FNM_NOMATCH) {
418 ret = pmd->action(pmd->table, row, name, pmd->data);
433 * Execute the given function for each matching row.
435 * \param pmd Describes what to match and how.
439 int for_each_matching_row(struct pattern_match_data *pmd)
441 if (pmd->pm_flags & PM_REVERSE_LOOP)
442 return osl(osl_rbtree_loop_reverse(pmd->table, pmd->loop_col_num, pmd,
443 action_if_pattern_matches));
444 return osl(osl_rbtree_loop(pmd->table, pmd->loop_col_num, pmd,
445 action_if_pattern_matches));
449 * Compare two osl objects of string type.
451 * \param obj1 Pointer to the first object.
452 * \param obj2 Pointer to the second object.
454 * In any case, only \p MIN(obj1->size, obj2->size) characters of each string
455 * are taken into account.
457 * \return It returns an integer less than, equal to, or greater than zero if
458 * \a obj1 is found, respectively, to be less than, to match, or be greater than
461 * \sa strcmp(3), strncmp(3), osl_compare_func.
463 int string_compare(const struct osl_object *obj1, const struct osl_object *obj2)
465 const char *str1 = (const char *)obj1->data;
466 const char *str2 = (const char *)obj2->data;
467 return strncmp(str1, str2, PARA_MIN(obj1->size, obj2->size));
470 static int pass_afd(int fd, char *buf, size_t size)
472 struct msghdr msg = {.msg_iov = NULL};
473 struct cmsghdr *cmsg;
474 char control[255] __a_aligned(8);
484 msg.msg_control = control;
485 msg.msg_controllen = sizeof(control);
487 cmsg = CMSG_FIRSTHDR(&msg);
488 cmsg->cmsg_level = SOL_SOCKET;
489 cmsg->cmsg_type = SCM_RIGHTS;
490 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
491 *(int *)CMSG_DATA(cmsg) = fd;
493 /* Sum of the length of all control messages in the buffer */
494 msg.msg_controllen = cmsg->cmsg_len;
495 PARA_DEBUG_LOG("passing %zu bytes and fd %d\n", size, fd);
496 ret = sendmsg(server_socket, &msg, 0);
498 ret = -ERRNO_TO_PARA_ERROR(errno);
505 * Pass the fd of the next audio file to the server process.
507 * This stores all information for streaming the "best" audio file in a shared
508 * memory area. The id of that area and an open file descriptor for the next
509 * audio file are passed to the server process.
513 * \sa open_and_update_audio_file().
515 static int open_next_audio_file(void)
517 struct audio_file_data afd;
521 ret = open_and_update_audio_file(&afd);
523 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
524 goto no_admissible_files;
527 if (!write_ok(server_socket)) {
531 *(uint32_t *)buf = NEXT_AUDIO_FILE;
532 *(uint32_t *)(buf + 4) = (uint32_t)shmid;
533 ret = pass_afd(afd.fd, buf, 8);
541 *(uint32_t *)buf = NO_ADMISSIBLE_FILES;
542 *(uint32_t *)(buf + 4) = (uint32_t)0;
543 return write_all(server_socket, buf, 8);
546 /* Never fails if arg == NULL */
547 static int activate_mood_or_playlist(const char *arg, int *num_admissible)
553 ret = change_current_mood(NULL); /* always successful */
554 mode = PLAY_MODE_MOOD;
556 if (!strncmp(arg, "p/", 2)) {
557 ret = playlist_open(arg + 2);
558 mode = PLAY_MODE_PLAYLIST;
559 } else if (!strncmp(arg, "m/", 2)) {
560 ret = change_current_mood(arg + 2);
561 mode = PLAY_MODE_MOOD;
563 return -E_AFS_SYNTAX;
568 *num_admissible = ret;
569 current_play_mode = mode;
570 if (arg != current_mop) {
573 current_mop = para_strdup(arg);
574 mutex_lock(mmd_mutex);
575 strncpy(mmd->afs_mode_string, arg,
576 sizeof(mmd->afs_mode_string));
577 mmd->afs_mode_string[sizeof(mmd->afs_mode_string) - 1] = '\0';
578 mutex_unlock(mmd_mutex);
580 mutex_lock(mmd_mutex);
581 strcpy(mmd->afs_mode_string, "dummy");
582 mutex_unlock(mmd_mutex);
590 * Result handler for sending data to the para_client process.
592 * \param result The data to be sent.
593 * \param band The band designator.
594 * \param private Pointer to the command context.
596 * \return The return value of the underlying call to \ref command.c::send_sb.
598 * \sa \ref callback_result_handler, \ref command.c::send_sb.
600 int afs_cb_result_handler(struct osl_object *result, uint8_t band,
603 struct command_context *cc = private;
611 case SBD_WARNING_LOG:
615 assert(result->size > 0);
616 return send_sb(&cc->scc, result->data, result->size, band, true);
617 case SBD_AFS_CB_FAILURE:
618 return *(int *)(result->data);
624 static void flush_and_free_pb(struct para_buffer *pb)
627 struct afs_max_size_handler_data *amshd = pb->private_data;
629 if (pb->buf && pb->size > 0) {
630 ret = pass_buffer_as_shm(amshd->fd, amshd->band, pb->buf,
633 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
638 static int com_select_callback(struct afs_callback_arg *aca)
640 const char *arg = aca->query.data;
641 int num_admissible, ret;
643 ret = clear_score_table();
645 para_printf(&aca->pbout, "could not clear score table: %s\n",
646 para_strerror(-ret));
649 if (current_play_mode == PLAY_MODE_MOOD)
650 close_current_mood();
653 ret = activate_mood_or_playlist(arg, &num_admissible);
656 /* ignore subsequent errors (but log them) */
657 para_printf(&aca->pbout, "could not activate %s\n", arg);
660 para_printf(&aca->pbout, "switching back to %s\n", current_mop);
661 ret2 = activate_mood_or_playlist(current_mop, &num_admissible);
664 para_printf(&aca->pbout, "could not reactivate %s: %s\n",
665 current_mop, para_strerror(-ret2));
667 para_printf(&aca->pbout, "activating dummy mood\n");
668 activate_mood_or_playlist(NULL, &num_admissible);
670 para_printf(&aca->pbout, "activated %s (%d admissible files)\n",
671 current_mop? current_mop : "dummy mood", num_admissible);
675 int com_select(struct command_context *cc)
677 struct osl_object query;
680 return -E_AFS_SYNTAX;
681 query.data = cc->argv[1];
682 query.size = strlen(cc->argv[1]) + 1;
683 return send_callback_request(com_select_callback, &query,
684 &afs_cb_result_handler, cc);
687 static void init_admissible_files(char *arg)
689 if (activate_mood_or_playlist(arg, NULL) < 0)
690 activate_mood_or_playlist(NULL, NULL); /* always successful */
693 static int setup_command_socket_or_die(void)
696 char *socket_name = conf.afs_socket_arg;
699 ret = create_local_socket(socket_name, 0);
701 ret = create_local_socket(socket_name,
702 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IROTH);
704 PARA_EMERG_LOG("%s: %s\n", para_strerror(-ret),
710 PARA_INFO_LOG("listening on socket %s (fd %d)\n", socket_name,
715 static void close_afs_tables(void)
718 PARA_NOTICE_LOG("closing afs_tables\n");
719 for (i = 0; i < NUM_AFS_TABLES; i++)
720 afs_tables[i].close();
723 static char *database_dir;
725 static void get_database_dir(void)
728 if (conf.afs_database_dir_given)
729 database_dir = para_strdup(conf.afs_database_dir_arg);
731 char *home = para_homedir();
732 database_dir = make_message(
733 "%s/.paraslash/afs_database-0.4", home);
737 PARA_INFO_LOG("afs_database dir %s\n", database_dir);
740 static int make_database_dir(void)
745 ret = para_mkdir(database_dir, 0777);
746 if (ret >= 0 || ret == -ERRNO_TO_PARA_ERROR(EEXIST))
751 static int open_afs_tables(void)
756 PARA_NOTICE_LOG("opening %d osl tables in %s\n", NUM_AFS_TABLES,
758 for (i = 0; i < NUM_AFS_TABLES; i++) {
759 ret = afs_tables[i].open(database_dir);
762 PARA_ERROR_LOG("%s init: %s\n", afs_tables[i].name,
763 para_strerror(-ret));
769 afs_tables[--i].close();
773 static int afs_signal_post_select(struct sched *s, __a_unused void *context)
777 if (getppid() == 1) {
778 PARA_EMERG_LOG("para_server died\n");
781 signum = para_next_signal(&s->rfds);
784 if (signum == SIGHUP) {
786 parse_config_or_die(1);
787 ret = open_afs_tables();
790 init_admissible_files(current_mop);
793 PARA_EMERG_LOG("terminating on signal %d\n", signum);
795 task_notify_all(s, E_AFS_SIGNAL);
796 return -E_AFS_SIGNAL;
799 static void register_signal_task(struct sched *s)
801 para_sigaction(SIGPIPE, SIG_IGN);
802 signal_task = signal_init_or_die();
803 para_install_sighandler(SIGINT);
804 para_install_sighandler(SIGTERM);
805 para_install_sighandler(SIGHUP);
807 signal_task->task = task_register(&(struct task_info) {
809 .pre_select = signal_pre_select,
810 .post_select = afs_signal_post_select,
811 .context = signal_task,
816 static struct list_head afs_client_list;
818 /** Describes one connected afs client. */
820 /** Position in the afs client list. */
821 struct list_head node;
822 /** The socket file descriptor for this client. */
824 /** The time the client connected. */
825 struct timeval connect_time;
828 static void command_pre_select(struct sched *s, void *context)
830 struct command_task *ct = context;
831 struct afs_client *client;
833 para_fd_set(server_socket, &s->rfds, &s->max_fileno);
834 para_fd_set(ct->fd, &s->rfds, &s->max_fileno);
835 list_for_each_entry(client, &afs_client_list, node)
836 para_fd_set(client->fd, &s->rfds, &s->max_fileno);
840 * Send data as shared memory to a file descriptor.
842 * \param fd File descriptor to send the shmid to.
843 * \param band The band designator for this data.
844 * \param buf The buffer holding the data to be sent.
845 * \param size The size of \a buf.
847 * This function creates a shared memory area large enough to hold
848 * the content given by \a buf and \a size and sends the identifier
849 * of this area to the file descriptor \a fd.
851 * It is called by the AFS max_size handler as well as directly by the AFS
852 * command callbacks to send command output to the command handlers.
854 * \return Zero if \a buf is \p NULL or \a size is zero. Negative on errors,
855 * and positive on success.
857 int pass_buffer_as_shm(int fd, uint8_t band, const char *buf, size_t size)
861 struct callback_result *cr;
864 assert(band != SBD_OUTPUT);
865 ret = shm_new(size + sizeof(*cr));
869 ret = shm_attach(shmid, ATTACH_RW, &shm);
873 cr->result_size = size;
876 memcpy(shm + sizeof(*cr), buf, size);
877 ret = shm_detach(shm);
880 ret = write_all(fd, (char *)&shmid, sizeof(int));
884 if (shm_destroy(shmid) < 0)
885 PARA_ERROR_LOG("destroy result failed\n");
889 static int call_callback(int fd, int query_shmid)
892 struct callback_query *cq;
894 struct afs_callback_arg aca = {.fd = fd};
896 ret = shm_attach(query_shmid, ATTACH_RW, &query_shm);
900 aca.query.data = (char *)query_shm + sizeof(*cq);
901 aca.query.size = cq->query_size;
902 aca.pbout.max_size = shm_get_shmmax();
903 aca.pbout.max_size_handler = afs_max_size_handler;
904 aca.pbout.private_data = &(struct afs_max_size_handler_data) {
908 ret = cq->handler(&aca);
909 ret2 = shm_detach(query_shm);
911 if (ret < 0) /* ignore (but log) detach error */
912 PARA_ERROR_LOG("could not detach sma: %s\n",
913 para_strerror(-ret2));
917 flush_and_free_pb(&aca.pbout);
919 ret2 = pass_buffer_as_shm(fd, SBD_AFS_CB_FAILURE,
920 (const char *)&ret, sizeof(ret));
922 PARA_ERROR_LOG("could not pass cb failure packet: %s\n",
923 para_strerror(-ret));
928 static int execute_server_command(fd_set *rfds)
932 int ret = read_nonblock(server_socket, buf, sizeof(buf) - 1, rfds, &n);
934 if (ret < 0 || n == 0)
937 if (strcmp(buf, "new"))
938 return -ERRNO_TO_PARA_ERROR(EINVAL);
939 return open_next_audio_file();
942 /* returns 0 if no data available, 1 else */
943 static int execute_afs_command(int fd, fd_set *rfds, uint32_t expected_cookie)
947 char buf[sizeof(cookie) + sizeof(query_shmid)];
949 int ret = read_nonblock(fd, buf, sizeof(buf), rfds, &n);
955 if (n != sizeof(buf)) {
956 PARA_NOTICE_LOG("short read (%d bytes, expected %lu)\n",
957 ret, (long unsigned) sizeof(buf));
960 cookie = *(uint32_t *)buf;
961 if (cookie != expected_cookie) {
962 PARA_NOTICE_LOG("received invalid cookie (got %u, expected %u)\n",
963 (unsigned)cookie, (unsigned)expected_cookie);
966 query_shmid = *(int *)(buf + sizeof(cookie));
967 if (query_shmid < 0) {
968 PARA_WARNING_LOG("received invalid query shmid %d)\n",
972 ret = call_callback(fd, query_shmid);
976 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
980 /** Shutdown connection if query has not arrived until this many seconds. */
981 #define AFS_CLIENT_TIMEOUT 3
983 static int command_post_select(struct sched *s, void *context)
985 struct command_task *ct = context;
986 struct sockaddr_un unix_addr;
987 struct afs_client *client, *tmp;
990 ret = task_get_notification(ct->task);
993 ret = execute_server_command(&s->rfds);
995 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
996 task_notify_all(s, -ret);
999 /* Check the list of connected clients. */
1000 list_for_each_entry_safe(client, tmp, &afs_client_list, node) {
1001 ret = execute_afs_command(client->fd, &s->rfds, ct->cookie);
1002 if (ret == 0) { /* prevent bogus connection flooding */
1003 struct timeval diff;
1004 tv_diff(now, &client->connect_time, &diff);
1005 if (diff.tv_sec < AFS_CLIENT_TIMEOUT)
1007 PARA_WARNING_LOG("connection timeout\n");
1010 list_del(&client->node);
1013 /* Accept connections on the local socket. */
1014 ret = para_accept(ct->fd, &s->rfds, &unix_addr, sizeof(unix_addr), &fd);
1016 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
1019 ret = mark_fd_nonblocking(fd);
1021 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
1025 client = para_malloc(sizeof(*client));
1027 client->connect_time = *now;
1028 para_list_add(&client->node, &afs_client_list);
1032 static void register_command_task(uint32_t cookie, struct sched *s)
1034 struct command_task *ct = &command_task_struct;
1035 ct->fd = setup_command_socket_or_die();
1036 ct->cookie = cookie;
1038 ct->task = task_register(&(struct task_info) {
1039 .name = "afs command",
1040 .pre_select = command_pre_select,
1041 .post_select = command_post_select,
1047 * Initialize the audio file selector process.
1049 * \param cookie The value used for "authentication".
1050 * \param socket_fd File descriptor used for communication with the server.
1052 __noreturn void afs_init(uint32_t cookie, int socket_fd)
1054 static struct sched s;
1057 register_signal_task(&s);
1058 INIT_LIST_HEAD(&afs_client_list);
1059 for (i = 0; i < NUM_AFS_TABLES; i++)
1060 afs_tables[i].init(&afs_tables[i]);
1061 ret = open_afs_tables();
1064 server_socket = socket_fd;
1065 ret = mark_fd_nonblocking(server_socket);
1068 PARA_INFO_LOG("server_socket: %d, afs_socket_cookie: %u\n",
1069 server_socket, (unsigned) cookie);
1070 init_admissible_files(conf.afs_initial_mode_arg);
1071 register_command_task(cookie, &s);
1072 s.default_timeout.tv_sec = 0;
1073 s.default_timeout.tv_usec = 999 * 1000;
1074 ret = write(socket_fd, "\0", 1);
1078 ret = -ERRNO_TO_PARA_ERROR(errno);
1087 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1091 static int com_init_callback(struct afs_callback_arg *aca)
1093 uint32_t table_mask = *(uint32_t *)aca->query.data;
1097 for (i = 0; i < NUM_AFS_TABLES; i++) {
1098 struct afs_table *t = &afs_tables[i];
1100 if (!(table_mask & (1 << i)))
1104 ret = t->create(database_dir);
1106 para_printf(&aca->pbout, "cannot create table %s\n",
1110 para_printf(&aca->pbout, "successfully created %s table\n",
1113 ret = open_afs_tables();
1115 para_printf(&aca->pbout, "cannot open afs tables\n");
1120 static int com_init(struct command_context *cc, struct lls_parse_result *lpr)
1123 uint32_t table_mask = (1 << (NUM_AFS_TABLES + 1)) - 1;
1124 struct osl_object query = {.data = &table_mask,
1125 .size = sizeof(table_mask)};
1126 unsigned num_inputs = lls_num_inputs(lpr);
1128 ret = make_database_dir();
1131 if (num_inputs > 0) {
1133 for (i = 0; i < num_inputs; i++) {
1134 for (j = 0; j < NUM_AFS_TABLES; j++) {
1135 struct afs_table *t = &afs_tables[j];
1137 if (strcmp(lls_input(i, lpr), t->name))
1139 table_mask |= (1 << j);
1142 if (j == NUM_AFS_TABLES)
1143 return -E_BAD_TABLE_NAME;
1146 return send_callback_request(com_init_callback, &query,
1147 afs_cb_result_handler, cc);
1149 EXPORT_SERVER_CMD_HANDLER(init);
1152 * Flags for the check command.
1156 enum com_check_flags {
1157 /** Check the audio file table. */
1159 /** Check the mood table. */
1161 /** Check the playlist table. */
1162 CHECK_PLAYLISTS = 4,
1163 /** Check the attribute table against the audio file table. */
1167 int com_check(struct command_context *cc)
1172 for (i = 1; i < cc->argc; i++) {
1173 const char *arg = cc->argv[i];
1176 if (!strcmp(arg, "--")) {
1180 if (!strcmp(arg, "-a")) {
1184 if (!strcmp(arg, "-A")) {
1185 flags |= CHECK_ATTS;
1188 if (!strcmp(arg, "-p")) {
1189 flags |= CHECK_PLAYLISTS;
1192 if (!strcmp(arg, "-m")) {
1193 flags |= CHECK_MOODS;
1196 return -E_AFS_SYNTAX;
1199 return -E_AFS_SYNTAX;
1202 if (flags & CHECK_AFT) {
1203 ret = send_callback_request(aft_check_callback, NULL,
1204 afs_cb_result_handler, cc);
1208 if (flags & CHECK_ATTS) {
1209 ret = send_callback_request(attribute_check_callback, NULL,
1210 afs_cb_result_handler, cc);
1214 if (flags & CHECK_PLAYLISTS) {
1215 ret = send_callback_request(playlist_check_callback,
1216 NULL, afs_cb_result_handler, cc);
1220 if (flags & CHECK_MOODS) {
1221 ret = send_callback_request(mood_check_callback, NULL,
1222 afs_cb_result_handler, cc);
1230 * The afs event dispatcher.
1232 * \param event Type of the event.
1233 * \param pb May be \p NULL.
1234 * \param data Type depends on \a event.
1236 * This function calls each table event handler, passing \a pb and \a data
1237 * verbatim. It's up to the handlers to interpret the \a data pointer. If a
1238 * handler returns negative, the loop is aborted.
1240 * \return The (negative) error code of the first handler that failed, or non-negative
1241 * if all handlers succeeded.
1243 __must_check int afs_event(enum afs_events event, struct para_buffer *pb,
1248 for (i = 0; i < NUM_AFS_TABLES; i++) {
1249 struct afs_table *t = &afs_tables[i];
1250 if (!t->event_handler)
1252 ret = t->event_handler(event, pb, data);
1254 PARA_CRIT_LOG("table %s, event %u: %s\n", t->name,
1255 event, para_strerror(-ret));
1263 * Dummy event handler for the images table.
1265 * \param event Unused.
1267 * \param data Unused.
1269 * \return The images table does not honor events, so this handler always
1272 __a_const int images_event_handler(__a_unused enum afs_events event,
1273 __a_unused struct para_buffer *pb, __a_unused void *data)
1279 * Dummy event handler for the lyrics table.
1281 * \param event Unused.
1283 * \param data Unused.
1285 * \return The lyrics table does not honor events, so this handler always
1288 __a_const int lyrics_event_handler(__a_unused enum afs_events event,
1289 __a_unused struct para_buffer *pb, __a_unused void *data)