48faeb17fdd153c735105a80a67aa27b1bd216e3
[paraslash.git] / afs.c
1 /*
2 * Copyright (C) 2007 Andre Noll <maan@systemlinux.org>
3 *
4 * Licensed under the GPL v2. For licencing details see COPYING.
5 */
6
7 /** \file afs.c Paraslash's audio file selector. */
8
9 #include <signal.h>
10 #include <fnmatch.h>
11 #include "server.cmdline.h"
12 #include "para.h"
13 #include "error.h"
14 #include "string.h"
15 #include "afh.h"
16 #include "afs.h"
17 #include "server.h"
18 #include <dirent.h> /* readdir() */
19 #include <sys/mman.h>
20 #include <sys/time.h>
21 #include "net.h"
22 #include "ipc.h"
23 #include "list.h"
24 #include "sched.h"
25 #include "signal.h"
26 #include "fd.h"
27
28 /** The osl tables used by afs. \sa blob.c. */
29 enum afs_table_num {
30 /** Contains audio file information. See aft.c. */
31 TBLNUM_AUDIO_FILES,
32 /** The table for the paraslash attributes. See attribute.c. */
33 TBLNUM_ATTRIBUTES,
34 /**
35 * Paraslash's scoring system is based on Gaussian normal
36 * distributions, and the relevant data is stored in the rbtrees of an
37 * osl table containing only volatile columns. See score.c for
38 * details.
39 */
40 TBLNUM_SCORES,
41 /**
42 * A standard blob table containing the mood definitions. For details
43 * see mood.c.
44 */
45 TBLNUM_MOODS,
46 /** A blob table containing lyrics on a per-song basis. */
47 TBLNUM_LYRICS,
48 /** Another blob table for images (for example album cover art). */
49 TBLNUM_IMAGES,
50 /** Yet another blob table for storing standard playlists. */
51 TBLNUM_PLAYLIST,
52 /** How many tables are in use? */
53 NUM_AFS_TABLES
54 };
55
56 static struct afs_table afs_tables[NUM_AFS_TABLES] = {
57 [TBLNUM_AUDIO_FILES] = {.init = aft_init},
58 [TBLNUM_ATTRIBUTES] = {.init = attribute_init},
59 [TBLNUM_SCORES] = {.init = score_init},
60 [TBLNUM_MOODS] = {.init = moods_init},
61 [TBLNUM_LYRICS] = {.init = lyrics_init},
62 [TBLNUM_IMAGES] = {.init = images_init},
63 [TBLNUM_PLAYLIST] = {.init = playlists_init},
64 };
65
66 struct command_task {
67 /** The file descriptor for the local socket. */
68 int fd;
69 /**
70 * Value sent by the command handlers to identify themselves as
71 * children of the running para_server.
72 */
73 uint32_t cookie;
74 /** The associated task structure. */
75 struct task task;
76 };
77
78 static int server_socket;
79 static struct command_task command_task_struct;
80 static struct signal_task signal_task_struct;
81
82 static enum play_mode current_play_mode;
83 static char *current_mop; /* mode or playlist specifier. NULL means dummy mooe */
84
85
86 /**
87 * A random number used to "authenticate" the connection.
88 *
89 * para_server picks this number by random before forking the afs process. The
90 * command handlers write this number together with the id of the shared memory
91 * area containing the query. This way, a malicious local user has to know this
92 * number to be able to cause the afs process to crash by sending fake queries.
93 */
94 extern uint32_t afs_socket_cookie;
95
96 /**
97 * Struct to let command handlers execute a callback in afs context.
98 *
99 * Commands that need to change the state of afs can't change the relevant data
100 * structures directly because commands are executed in a child process, i.e.
101 * they get their own virtual address space.
102 *
103 * This structure is used by \p send_callback_request() (executed from handler
104 * context) in order to let the afs process call the specified function. An
105 * instance of that structure is written to a shared memory area together with
106 * the arguments to the callback function. The identifier of the shared memory
107 * area is written to the command socket.
108 *
109 * The afs process accepts connections on the command socket and reads the
110 * shared memory id, attaches the corresponing area, calls the given handler to
111 * perform the desired action and to optionally compute a result.
112 *
113 * The result and a \p callback_result structure is then written to another
114 * shared memory area. The identifier for that area is written to the handler's
115 * command socket, so that the handler process can read the id, attach the
116 * shared memory area and use the result.
117 *
118 * \sa struct callback_result.
119 */
120 struct callback_query {
121 /** The function to be called. */
122 callback_function *handler;
123 /** The number of bytes of the query */
124 size_t query_size;
125 };
126
127 /**
128 * Structure embedded in the result of a callback.
129 *
130 * If the callback produced a result, an instance of that structure is embeeded
131 * into the shared memory area holding the result, mainly to let the command
132 * handler know the size of the result.
133 *
134 * \sa struct callback_query.
135 */
136 struct callback_result {
137 /** The number of bytes of the result. */
138 size_t result_size;
139 };
140
141 /**
142 * Ask the afs process to call a given function.
143 *
144 * \param f The function to be called.
145 * \param query Pointer to arbitrary data for the callback.
146 * \param result Callback result will be stored here.
147 *
148 * This function creates a shared memory area, copies the buffer pointed to by
149 * query to that area and notifies the afs process that \a f should be
150 * called ASAP.
151 *
152 * \return Negative, on errors, the return value of the callback function
153 * otherwise.
154 *
155 * \sa send_option_arg_callback_request(), send_standard_callback_request().
156 */
157 int send_callback_request(callback_function *f, struct osl_object *query,
158 struct osl_object *result)
159 {
160 struct callback_query *cq;
161 struct callback_result *cr;
162 int ret, fd = -1, query_shmid, result_shmid;
163 void *query_shm, *result_shm;
164 char buf[sizeof(afs_socket_cookie) + sizeof(int)];
165 struct sockaddr_un unix_addr;
166 size_t query_shm_size = sizeof(*cq);
167
168 if (query)
169 query_shm_size += query->size;
170 ret = shm_new(query_shm_size);
171 if (ret < 0)
172 return ret;
173 query_shmid = ret;
174 ret = shm_attach(query_shmid, ATTACH_RW, &query_shm);
175 if (ret < 0)
176 goto out;
177 cq = query_shm;
178 cq->handler = f;
179 cq->query_size = query_shm_size - sizeof(*cq);
180
181 if (query)
182 memcpy(query_shm + sizeof(*cq), query->data, query->size);
183 ret = shm_detach(query_shm);
184 if (ret < 0)
185 goto out;
186
187 *(uint32_t *) buf = afs_socket_cookie;
188 *(int *) (buf + sizeof(afs_socket_cookie)) = query_shmid;
189
190 ret = get_stream_socket(PF_UNIX);
191 if (ret < 0)
192 goto out;
193 fd = ret;
194 ret = init_unix_addr(&unix_addr, conf.afs_socket_arg);
195 if (ret < 0)
196 goto out;
197 ret = PARA_CONNECT(fd, &unix_addr);
198 if (ret < 0)
199 goto out;
200 ret = send_bin_buffer(fd, buf, sizeof(buf));
201 if (ret < 0)
202 goto out;
203 ret = recv_bin_buffer(fd, buf, sizeof(buf));
204 if (ret < 0)
205 goto out;
206 if (ret != sizeof(int)) {
207 ret = -E_RECV;
208 goto out;
209 }
210 ret = *(int *) buf;
211 if (ret <= 0)
212 goto out;
213 result_shmid = ret;
214 ret = shm_attach(result_shmid, ATTACH_RO, &result_shm);
215 if (ret >= 0) {
216 assert(result);
217 cr = 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);
222 if (ret < 0)
223 PARA_ERROR_LOG("can not detach result\n");
224 } else
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");
228 ret = 1;
229 out:
230 if (shm_destroy(query_shmid) < 0)
231 PARA_ERROR_LOG("%s\n", "shm destroy error");
232 if (fd >= 0)
233 close(fd);
234 // PARA_DEBUG_LOG("callback_ret: %d\n", ret);
235 return ret;
236 }
237
238 /**
239 * Send a callback request passing an options structure and an argument vector.
240 *
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.
246 *
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.
251 *
252 * \sa send_standard_callback_request(), send_callback_request().
253 */
254 int send_option_arg_callback_request(struct osl_object *options,
255 int argc, char * const * const argv, callback_function *f,
256 struct osl_object *result)
257 {
258 char *p;
259 int i, ret;
260 struct osl_object query = {.size = options? options->size : 0};
261
262 for (i = 0; i < argc; i++)
263 query.size += strlen(argv[i]) + 1;
264 query.data = para_malloc(query.size);
265 p = query.data;
266 if (options) {
267 memcpy(query.data, options->data, options->size);
268 p += options->size;
269 }
270 for (i = 0; i < argc; i++) {
271 strcpy(p, argv[i]); /* OK */
272 p += strlen(argv[i]) + 1;
273 }
274 ret = send_callback_request(f, &query, result);
275 free(query.data);
276 return ret;
277 }
278
279 /**
280 * Send a callback request with an argument vector only.
281 *
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().
286 *
287 * This is similar to send_option_arg_callback_request(), but no options buffer
288 * is passed to the parent process.
289 *
290 * \return The return value of the underlying call to
291 * send_option_arg_callback_request().
292 */
293 int send_standard_callback_request(int argc, char * const * const argv,
294 callback_function *f, struct osl_object *result)
295 {
296 return send_option_arg_callback_request(NULL, argc, argv, f, result);
297 }
298
299 static int action_if_pattern_matches(struct osl_row *row, void *data)
300 {
301 struct pattern_match_data *pmd = data;
302 struct osl_object name_obj;
303 const char *p, *name;
304 int ret = osl_get_object(pmd->table, row, pmd->match_col_num, &name_obj);
305 const char *pattern_txt = (const char *)pmd->patterns.data;
306
307 if (ret < 0)
308 return ret;
309 name = (char *)name_obj.data;
310 if ((!name || !*name) && (pmd->pm_flags & PM_SKIP_EMPTY_NAME))
311 return 1;
312 if (!pmd->patterns.size && (pmd->pm_flags & PM_NO_PATTERN_MATCHES_EVERYTHING))
313 return pmd->action(pmd->table, row, name, pmd->data);
314 for (p = pattern_txt; p < pattern_txt + pmd->patterns.size;
315 p += strlen(p) + 1) {
316 ret = fnmatch(p, name, pmd->fnmatch_flags);
317 if (ret == FNM_NOMATCH)
318 continue;
319 if (ret)
320 return -E_FNMATCH;
321 return pmd->action(pmd->table, row, name, pmd->data);
322 }
323 return 1;
324 }
325
326 /**
327 * Execute the given function for each matching row.
328 *
329 * \param pmd Describes what to match and how.
330 *
331 * \return The return value of the underlying call to osl_rbtree_loop()
332 * or osl_rbtree_loop_reverse().
333 */
334 int for_each_matching_row(struct pattern_match_data *pmd)
335 {
336 if (pmd->pm_flags & PM_REVERSE_LOOP)
337 return osl_rbtree_loop_reverse(pmd->table, pmd->loop_col_num, pmd,
338 action_if_pattern_matches);
339 return osl_rbtree_loop(pmd->table, pmd->loop_col_num, pmd,
340 action_if_pattern_matches);
341 }
342
343 /**
344 * Compare two osl objects of string type.
345 *
346 * \param obj1 Pointer to the first object.
347 * \param obj2 Pointer to the second object.
348 *
349 * In any case, only \p MIN(obj1->size, obj2->size) characters of each string
350 * are taken into account.
351 *
352 * \return It returns an integer less than, equal to, or greater than zero if
353 * \a obj1 is found, respectively, to be less than, to match, or be greater than
354 * obj2.
355 *
356 * \sa strcmp(3), strncmp(3), osl_compare_func.
357 */
358 int string_compare(const struct osl_object *obj1, const struct osl_object *obj2)
359 {
360 const char *str1 = (const char *)obj1->data;
361 const char *str2 = (const char *)obj2->data;
362 return strncmp(str1, str2, PARA_MIN(obj1->size, obj2->size));
363 }
364
365 /*
366 * write input from fd to dynamically allocated buffer,
367 * but maximal max_size byte.
368 */
369 static int fd2buf(int fd, unsigned max_size, struct osl_object *obj)
370 {
371 const size_t chunk_size = 1024;
372 size_t size = 2048, received = 0;
373 int ret;
374 char *buf = para_malloc(size);
375
376 for (;;) {
377 ret = recv_bin_buffer(fd, buf + received, chunk_size);
378 if (ret <= 0)
379 break;
380 received += ret;
381 if (received + chunk_size >= size) {
382 size *= 2;
383 ret = -E_INPUT_TOO_LARGE;
384 if (size > max_size)
385 break;
386 buf = para_realloc(buf, size);
387 }
388 }
389 obj->data = buf;
390 obj->size = received;
391 if (ret < 0)
392 free(buf);
393 return ret;
394 }
395
396 /**
397 * Read data from a file descriptor, and send it to the afs process.
398 *
399 * \param fd File descriptor to read data from.
400 * \param arg_obj Pointer to the arguments to \a f.
401 * \param f The callback function.
402 * \param max_len Don't read more than that many bytes from stdin.
403 * \param result The result of the query is stored here.
404 *
405 * This function is used by commands that wish to let para_server store
406 * arbitrary data specified by the user (for instance the add_blob family of
407 * commands). First, at most \a max_len bytes are read from \a fd, the result
408 * is concatenated with the buffer given by \a arg_obj, and the combined buffer
409 * is made available to the parent process via shared memory.
410 *
411 * \return Negative on errors, the return value of the underlying call to
412 * send_callback_request() otherwise.
413 */
414 int stdin_command(int fd, struct osl_object *arg_obj, callback_function *f,
415 unsigned max_len, struct osl_object *result)
416 {
417 struct osl_object query, stdin_obj;
418 int ret;
419
420 ret = send_buffer(fd, AWAITING_DATA_MSG);
421 if (ret < 0)
422 return ret;
423 ret = fd2buf(fd, max_len, &stdin_obj);
424 if (ret < 0)
425 return ret;
426 query.size = arg_obj->size + stdin_obj.size;
427 query.data = para_malloc(query.size);
428 memcpy(query.data, arg_obj->data, arg_obj->size);
429 memcpy((char *)query.data + arg_obj->size, stdin_obj.data, stdin_obj.size);
430 free(stdin_obj.data);
431 ret = send_callback_request(f, &query, result);
432 free(query.data);
433 return ret;
434 }
435
436 static int pass_afd(int fd, char *buf, size_t size)
437 {
438 struct msghdr msg = {.msg_iov = NULL};
439 struct cmsghdr *cmsg;
440 char control[255];
441 int ret;
442 struct iovec iov;
443
444 iov.iov_base = buf;
445 iov.iov_len = size;
446
447 msg.msg_iov = &iov;
448 msg.msg_iovlen = 1;
449
450 msg.msg_control = control;
451 msg.msg_controllen = sizeof(control);
452
453 cmsg = CMSG_FIRSTHDR(&msg);
454 cmsg->cmsg_level = SOL_SOCKET;
455 cmsg->cmsg_type = SCM_RIGHTS;
456 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
457 *(int *)CMSG_DATA(cmsg) = fd;
458
459 /* Sum of the length of all control messages in the buffer */
460 msg.msg_controllen = cmsg->cmsg_len;
461 PARA_NOTICE_LOG("passing %zu bytes and fd %d\n", size, fd);
462 ret = sendmsg(server_socket, &msg, 0);
463 if (ret < 0) {
464 ret = -ERRNO_TO_PARA_ERROR(errno);
465 return ret;
466 }
467 return 1;
468 }
469
470 /**
471 * Open the audio file with highest score.
472 *
473 * This stores all information for streaming the "best" audio file in a shared
474 * memory area. The id of that area and an open file descriptor for the next
475 * audio file are passed to the server process.
476 *
477 * \return Standard.
478 *
479 * \sa open_and_update_audio_file().
480 */
481 int open_next_audio_file(void)
482 {
483 struct osl_row *aft_row;
484 struct audio_file_data afd;
485 int ret, shmid;
486 char buf[8];
487
488 PARA_NOTICE_LOG("getting next af\n");
489 ret = score_get_best(&aft_row, &afd.score);
490 if (ret < 0)
491 return ret;
492 ret = open_and_update_audio_file(aft_row, &afd);
493 if (ret < 0)
494 return ret;
495 shmid = ret;
496 PARA_NOTICE_LOG("shmid: %u\n", shmid);
497 if (!write_ok(server_socket)) {
498 PARA_EMERG_LOG("afs_socket not writable\n");
499 goto destroy;
500 }
501 *(uint32_t *)buf = NEXT_AUDIO_FILE;
502 *(uint32_t *)(buf + 4) = (uint32_t)shmid;
503 ret = pass_afd(afd.fd, buf, 8);
504 close(afd.fd);
505 if (ret >= 0)
506 return ret;
507 PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));
508 destroy:
509 shm_destroy(shmid);
510 return ret;
511 }
512
513 /* Never fails if arg == NULL */
514 static int activate_mood_or_playlist(char *arg, int *num_admissible)
515 {
516 enum play_mode mode;
517 int ret;
518
519 if (!arg) {
520 ret = change_current_mood(NULL); /* always successful */
521 mode = PLAY_MODE_MOOD;
522 } else {
523 if (!strncmp(arg, "p:", 2)) {
524 ret = playlist_open(arg + 2);
525 mode = PLAY_MODE_PLAYLIST;
526 } else if (!strncmp(arg, "m:", 2)) {
527 ret = change_current_mood(arg + 2);
528 mode = PLAY_MODE_MOOD;
529 } else
530 ret = -E_AFS_SYNTAX;
531 if (ret < 0)
532 return ret;
533 }
534 if (num_admissible)
535 *num_admissible = ret;
536 current_play_mode = mode;
537 if (arg != current_mop) {
538 free(current_mop);
539 if (arg)
540 current_mop = para_strdup(arg);
541 else
542 current_mop = NULL;
543 }
544 return 1;
545 }
546
547 static int com_select_callback(const struct osl_object *query,
548 struct osl_object *result)
549 {
550 struct para_buffer pb = {.buf = NULL};
551 char *arg = query->data;
552 int num_admissible, ret;
553
554 ret = clear_score_table();
555 if (ret < 0)
556 return ret;
557 if (current_play_mode == PLAY_MODE_MOOD)
558 close_current_mood();
559 else
560 playlist_close();
561 ret = activate_mood_or_playlist(arg, &num_admissible);
562 if (ret < 0) {
563 para_printf(&pb, "%s\n", PARA_STRERROR(-ret));
564 para_printf(&pb, "switching back to %s\n", current_mop?
565 current_mop : "dummy");
566 ret = activate_mood_or_playlist(current_mop, &num_admissible);
567 if (ret < 0) {
568 para_printf(&pb, "failed, switching to dummy\n");
569 activate_mood_or_playlist(NULL, &num_admissible);
570 }
571 }
572 para_printf(&pb, "activated %s (%d admissible files)\n", current_mop?
573 current_mop : "dummy mood", num_admissible);
574 result->data = pb.buf;
575 result->size = pb.size;
576 return 1;
577 }
578
579 int com_select(int fd, int argc, char * const * const argv)
580 {
581 int ret;
582 struct osl_object query, result;
583
584 if (argc != 2)
585 return -E_AFS_SYNTAX;
586 query.data = argv[1];
587 query.size = strlen(argv[1]) + 1;
588 ret = send_callback_request(com_select_callback, &query,
589 &result);
590 if (ret > 0 && result.data && result.size) {
591 ret = send_va_buffer(fd, "%s", (char *)result.data);
592 free(result.data);
593 }
594 return ret;
595 }
596
597 static void init_admissible_files(void)
598 {
599 int ret = 0;
600 char *arg = conf.afs_initial_mode_arg;
601 ret = activate_mood_or_playlist(arg, NULL);
602 if (ret >= 0)
603 return;
604 PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));
605 PARA_NOTICE_LOG("defaulting to dummy mood\n");
606 activate_mood_or_playlist(NULL, NULL); /* always successful */
607 }
608
609 static int setup_command_socket_or_die(void)
610 {
611 int ret;
612 char *socket_name = conf.afs_socket_arg;
613 struct sockaddr_un unix_addr;
614
615 unlink(socket_name);
616 ret = create_local_socket(socket_name, &unix_addr,
617 S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IWOTH);
618 if (ret < 0) {
619 PARA_EMERG_LOG("%s: %s\n", PARA_STRERROR(-ret), socket_name);
620 exit(EXIT_FAILURE);
621 }
622 if (listen(ret , 5) < 0) {
623 PARA_EMERG_LOG("%s", "can not listen on socket\n");
624 exit(EXIT_FAILURE);
625 }
626 PARA_INFO_LOG("listening on command socket %s (fd %d)\n", socket_name,
627 ret);
628 return ret;
629 }
630
631 static void close_afs_tables(void)
632 {
633 int i;
634 PARA_NOTICE_LOG("closing afs_tables\n");
635 for (i = 0; i < NUM_AFS_TABLES; i++)
636 afs_tables[i].close();
637 }
638
639 static char *database_dir;
640
641 static void get_database_dir(void)
642 {
643 if (!database_dir) {
644 if (conf.afs_database_dir_given)
645 database_dir = para_strdup(conf.afs_database_dir_arg);
646 else {
647 char *home = para_homedir();
648 database_dir = make_message(
649 "%s/.paraslash/afs_database", home);
650 free(home);
651 }
652 }
653 PARA_INFO_LOG("afs_database dir %s\n", database_dir);
654 }
655
656 static int make_database_dir(void)
657 {
658 int ret;
659
660 get_database_dir();
661 ret = para_mkdir(database_dir, 0777);
662 if (ret >= 0 || is_errno(-ret, EEXIST))
663 return 1;
664 return ret;
665 }
666
667 static int open_afs_tables(void)
668 {
669 int i, ret;
670
671 get_database_dir();
672 for (i = 0; i < NUM_AFS_TABLES; i++) {
673 ret = afs_tables[i].open(database_dir);
674 if (ret >= 0)
675 continue;
676 PARA_ERROR_LOG("%s init: %s\n", afs_tables[i].name,
677 PARA_STRERROR(-ret));
678 }
679 if (ret >= 0)
680 return ret;
681 do
682 afs_tables[i].close();
683 while (i--);
684 return ret;
685 }
686
687 static void unregister_tasks(void)
688 {
689 unregister_task(&command_task_struct.task);
690 unregister_task(&signal_task_struct.task);
691 }
692
693 static void signal_pre_select(struct sched *s, struct task *t)
694 {
695 struct signal_task *st = t->private_data;
696 t->ret = 1;
697 para_fd_set(st->fd, &s->rfds, &s->max_fileno);
698 }
699
700 static void signal_post_select(struct sched *s, struct task *t)
701 {
702 struct signal_task *st = t->private_data;
703 t->ret = 1;
704 if (!FD_ISSET(st->fd, &s->rfds))
705 return;
706 st->signum = para_next_signal();
707 t->ret = 1;
708 if (st->signum == SIGUSR1)
709 return; /* ignore SIGUSR1 */
710 if (st->signum == SIGHUP) {
711 close_afs_tables();
712 t->ret = open_afs_tables();
713 return;
714 }
715 PARA_NOTICE_LOG("caught signal %d\n", st->signum);
716 t->ret = -E_AFS_SIGNAL;
717 unregister_tasks();
718 }
719
720 static void register_signal_task(void)
721 {
722 struct signal_task *st = &signal_task_struct;
723 st->fd = para_signal_init();
724 PARA_INFO_LOG("signal pipe: fd %d\n", st->fd);
725 para_install_sighandler(SIGINT);
726 para_install_sighandler(SIGTERM);
727 para_install_sighandler(SIGPIPE);
728 para_install_sighandler(SIGHUP);
729
730 st->task.pre_select = signal_pre_select;
731 st->task.post_select = signal_post_select;
732 st->task.private_data = st;
733 sprintf(st->task.status, "signal task");
734 register_task(&st->task);
735 }
736
737 static struct list_head afs_client_list;
738
739 struct afs_client {
740 struct list_head node;
741 int fd;
742 struct timeval connect_time;
743 };
744
745 static void command_pre_select(struct sched *s, struct task *t)
746 {
747 struct command_task *ct = t->private_data;
748 struct afs_client *client;
749
750 para_fd_set(server_socket, &s->rfds, &s->max_fileno);
751 para_fd_set(ct->fd, &s->rfds, &s->max_fileno);
752 list_for_each_entry(client, &afs_client_list, node)
753 para_fd_set(client->fd, &s->rfds, &s->max_fileno);
754 t->ret = 1;
755 }
756
757 /*
758 * On errors, negative value is written to fd.
759 * On success: If query produced a result, the result_shmid is written to fd.
760 * Otherwise, zero is written.
761 */
762 static int call_callback(int fd, int query_shmid)
763 {
764 void *query_shm, *result_shm;
765 struct callback_query *cq;
766 struct callback_result *cr;
767 struct osl_object query, result = {.data = NULL};
768 int result_shmid = -1, ret, ret2;
769
770 ret = shm_attach(query_shmid, ATTACH_RW, &query_shm);
771 if (ret < 0)
772 goto out;
773 cq = query_shm;
774 query.data = (char *)query_shm + sizeof(*cq);
775 query.size = cq->query_size;
776 ret = cq->handler(&query, &result);
777 ret2 = shm_detach(query_shm);
778 if (ret2 < 0 && ret >= 0)
779 ret = ret2;
780 if (ret < 0)
781 goto out;
782 ret = 0;
783 if (!result.data || !result.size)
784 goto out;
785 ret = shm_new(result.size + sizeof(struct callback_result));
786 if (ret < 0)
787 goto out;
788 result_shmid = ret;
789 ret = shm_attach(result_shmid, ATTACH_RW, &result_shm);
790 if (ret < 0)
791 goto out;
792 cr = result_shm;
793 cr->result_size = result.size;
794 memcpy(result_shm + sizeof(*cr), result.data, result.size);
795 ret = shm_detach(result_shm);
796 if (ret < 0)
797 goto out;
798 ret = result_shmid;
799 out:
800 free(result.data);
801 ret2 = send_bin_buffer(fd, (char *)&ret, sizeof(int));
802 if (ret < 0 || ret2 < 0) {
803 if (result_shmid >= 0)
804 if (shm_destroy(result_shmid) < 0)
805 PARA_ERROR_LOG("destroy result failed\n");
806 if (ret >= 0)
807 ret = ret2;
808 }
809 return ret;
810 }
811
812 static void execute_server_command(void)
813 {
814 char buf[8];
815 int ret = recv_bin_buffer(server_socket, buf, sizeof(buf) - 1);
816
817 if (ret <= 0) {
818 if (ret < 0)
819 PARA_ERROR_LOG("%s\n", PARA_STRERROR(-ret));
820 return;
821 }
822 buf[ret] = '\0';
823 PARA_NOTICE_LOG("received: %s\n", buf);
824 if (!strcmp(buf, "new")) {
825 ret = open_next_audio_file();
826 PARA_NOTICE_LOG("ret: %d\n", ret);
827 return;
828 }
829 PARA_ERROR_LOG("unknown command\n");
830
831 }
832
833 static void execute_afs_command(int fd, uint32_t expected_cookie)
834 {
835 uint32_t cookie;
836 int query_shmid;
837 char buf[sizeof(cookie) + sizeof(query_shmid)];
838 int ret = recv_bin_buffer(fd, buf, sizeof(buf));
839
840 if (ret < 0) {
841 PARA_NOTICE_LOG("%s\n", PARA_STRERROR(-ret));
842 return;
843 }
844 if (ret != sizeof(buf)) {
845 PARA_NOTICE_LOG("short read (%d bytes, expected %lu)\n",
846 ret, (long unsigned) sizeof(buf));
847 return;
848 }
849 cookie = *(uint32_t *)buf;
850 if (cookie != expected_cookie) {
851 PARA_NOTICE_LOG("received invalid cookie(got %u, expected %u)\n",
852 (unsigned)cookie, (unsigned)expected_cookie);
853 return;
854 }
855 query_shmid = *(int *)(buf + sizeof(cookie));
856 if (query_shmid < 0) {
857 PARA_WARNING_LOG("received invalid query shmid %d)\n",
858 query_shmid);
859 return;
860 }
861 /* Ignore return value: Errors might be OK here. */
862 call_callback(fd, query_shmid);
863 }
864
865 /** Shutdown connection if query has not arrived until this many seconds. */
866 #define AFS_CLIENT_TIMEOUT 3
867
868 static void command_post_select(struct sched *s, struct task *t)
869 {
870 struct command_task *ct = t->private_data;
871 struct sockaddr_un unix_addr;
872 struct afs_client *client, *tmp;
873
874 if (FD_ISSET(server_socket, &s->rfds))
875 execute_server_command();
876
877 /* Check the list of connected clients. */
878 list_for_each_entry_safe(client, tmp, &afs_client_list, node) {
879 if (FD_ISSET(client->fd, &s->rfds))
880 execute_afs_command(client->fd, ct->cookie);
881 else { /* prevent bogus connection flooding */
882 struct timeval diff;
883 tv_diff(now, &client->connect_time, &diff);
884 if (diff.tv_sec < AFS_CLIENT_TIMEOUT)
885 continue;
886 PARA_WARNING_LOG("connection timeout\n");
887 }
888 close(client->fd);
889 list_del(&client->node);
890 free(client);
891 }
892 /* Accept connections on the local socket. */
893 if (!FD_ISSET(ct->fd, &s->rfds))
894 goto out;
895 t->ret = para_accept(ct->fd, &unix_addr, sizeof(unix_addr));
896 if (t->ret < 0) {
897 PARA_NOTICE_LOG("%s\n", PARA_STRERROR(-t->ret));
898 goto out;
899 }
900 client = para_malloc(sizeof(*client));
901 client->fd = t->ret;
902 client->connect_time = *now;
903 para_list_add(&client->node, &afs_client_list);
904 out:
905 t->ret = 1;
906 }
907
908 static void register_command_task(uint32_t cookie)
909 {
910 struct command_task *ct = &command_task_struct;
911 ct->fd = setup_command_socket_or_die();
912 ct->cookie = cookie;
913
914 ct->task.pre_select = command_pre_select;
915 ct->task.post_select = command_post_select;
916 ct->task.private_data = ct;
917 sprintf(ct->task.status, "command task");
918 register_task(&ct->task);
919 }
920
921 static void register_tasks(uint32_t cookie)
922 {
923 register_signal_task();
924 register_command_task(cookie);
925 }
926
927 /**
928 * Initialize the audio file selector process.
929 *
930 * \param cookie The value used for "authentication".
931 * \param socket_fd File descriptor used for communication with the server.
932 */
933 __noreturn void afs_init(uint32_t cookie, int socket_fd)
934 {
935 struct sched s;
936 int i, ret;
937
938 INIT_LIST_HEAD(&afs_client_list);
939 for (i = 0; i < NUM_AFS_TABLES; i++)
940 afs_tables[i].init(&afs_tables[i]);
941 ret = open_afs_tables();
942
943 if (ret < 0) {
944 PARA_EMERG_LOG("%s\n", PARA_STRERROR(-ret));
945 exit(EXIT_FAILURE);
946 }
947 server_socket = socket_fd;
948 ret = mark_fd_nonblock(server_socket);
949 if (ret < 0)
950 exit(EXIT_FAILURE);
951 PARA_INFO_LOG("server_socket: %d, afs_socket_cookie: %u\n",
952 server_socket, (unsigned) cookie);
953 init_admissible_files();
954 register_tasks(cookie);
955 s.default_timeout.tv_sec = 0;
956 s.default_timeout.tv_usec = 99 * 1000;
957 ret = sched(&s);
958 if (ret < 0)
959 PARA_EMERG_LOG("%s\n", PARA_STRERROR(-ret));
960 close_afs_tables();
961 exit(EXIT_FAILURE);
962 }
963
964 static int create_tables_callback(const struct osl_object *query,
965 __a_unused struct osl_object *result)
966 {
967 uint32_t table_mask = *(uint32_t *)query->data;
968 int i, ret;
969
970 close_afs_tables();
971 for (i = 0; i < NUM_AFS_TABLES; i++) {
972 struct afs_table *t = &afs_tables[i];
973
974 if (!(table_mask & (1 << i)))
975 continue;
976 if (!t->create)
977 continue;
978 ret = t->create(database_dir);
979 if (ret < 0)
980 return ret;
981 }
982 ret = open_afs_tables();
983 return ret < 0? ret: 0;
984 }
985
986 int com_init(int fd, int argc, char * const * const argv)
987 {
988 int i, j, ret;
989 uint32_t table_mask = (1 << (NUM_AFS_TABLES + 1)) - 1;
990 struct osl_object query = {.data = &table_mask,
991 .size = sizeof(table_mask)};
992
993 ret = make_database_dir();
994 if (ret < 0)
995 return ret;
996 if (argc != 1) {
997 table_mask = 0;
998 for (i = 1; i < argc; i++) {
999 for (j = 0; j < NUM_AFS_TABLES; j++) {
1000 struct afs_table *t = &afs_tables[j];
1001
1002 if (strcmp(argv[i], t->name))
1003 continue;
1004 table_mask |= (1 << j);
1005 break;
1006 }
1007 if (j == NUM_AFS_TABLES)
1008 return -E_BAD_TABLE_NAME;
1009 }
1010 }
1011 ret = send_callback_request(create_tables_callback, &query, NULL);
1012 if (ret < 0)
1013 return ret;
1014 return send_va_buffer(fd, "successfully created afs table(s)\n");
1015 }
1016
1017 /**
1018 * Flags for the check command.
1019 *
1020 * \sa com_check().
1021 */
1022 enum com_check_flags {
1023 /** Check the audio file table. */
1024 CHECK_AFT = 1,
1025 /** Check the mood table. */
1026 CHECK_MOODS = 2,
1027 /** Check the playlist table. */
1028 CHECK_PLAYLISTS = 4
1029 };
1030
1031 int com_check(int fd, int argc, char * const * const argv)
1032 {
1033 unsigned flags = 0;
1034 int i, ret;
1035 struct osl_object result;
1036
1037 for (i = 1; i < argc; i++) {
1038 const char *arg = argv[i];
1039 if (arg[0] != '-')
1040 break;
1041 if (!strcmp(arg, "--")) {
1042 i++;
1043 break;
1044 }
1045 if (!strcmp(arg, "-a")) {
1046 flags |= CHECK_AFT;
1047 continue;
1048 }
1049 if (!strcmp(arg, "-p")) {
1050 flags |= CHECK_PLAYLISTS;
1051 continue;
1052 }
1053 if (!strcmp(arg, "-m")) {
1054 flags |= CHECK_MOODS;
1055 continue;
1056 }
1057 return -E_AFS_SYNTAX;
1058 }
1059 if (i < argc)
1060 return -E_AFS_SYNTAX;
1061 if (!flags)
1062 flags = ~0U;
1063 if (flags & CHECK_AFT) {
1064 ret = send_callback_request(aft_check_callback, NULL, &result);
1065 if (ret < 0)
1066 return ret;
1067 if (ret > 0) {
1068 ret = send_buffer(fd, (char *) result.data);
1069 free(result.data);
1070 if (ret < 0)
1071 return ret;
1072 }
1073 }
1074 if (flags & CHECK_PLAYLISTS) {
1075 ret = send_callback_request(playlist_check_callback, NULL, &result);
1076 if (ret < 0)
1077 return ret;
1078 if (ret > 0) {
1079 ret = send_buffer(fd, (char *) result.data);
1080 free(result.data);
1081 if (ret < 0)
1082 return ret;
1083 }
1084 }
1085 if (flags & CHECK_MOODS) {
1086 ret = send_callback_request(mood_check_callback, NULL, &result);
1087 if (ret < 0)
1088 return ret;
1089 if (ret > 0) {
1090 ret = send_buffer(fd, (char *) result.data);
1091 free(result.data);
1092 if (ret < 0)
1093 return ret;
1094 }
1095 }
1096 return 1;
1097 }
1098
1099 void afs_event(enum afs_events event, struct para_buffer *pb,
1100 void *data)
1101 {
1102 int i, ret;
1103
1104 for (i = 0; i < NUM_AFS_TABLES; i++) {
1105 struct afs_table *t = &afs_tables[i];
1106 if (!t->event_handler)
1107 continue;
1108 ret = t->event_handler(event, pb, data);
1109 if (ret < 0)
1110 PARA_CRIT_LOG("%s\n", PARA_STRERROR(-ret));
1111 }
1112 }
1113
1114 int images_event_handler(__a_unused enum afs_events event,
1115 __a_unused struct para_buffer *pb, __a_unused void *data)
1116 {
1117 return 1;
1118 }
1119
1120 int lyrics_event_handler(__a_unused enum afs_events event,
1121 __a_unused struct para_buffer *pb, __a_unused void *data)
1122 {
1123 return 1;
1124 }