afs: Improve error diagnostics.
[paraslash.git] / afs.c
1 /*
2 * Copyright (C) 2007 Andre Noll <maan@tuebingen.mpg.de>
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 <netinet/in.h>
10 #include <sys/socket.h>
11 #include <regex.h>
12 #include <signal.h>
13 #include <fnmatch.h>
14 #include <osl.h>
15 #include <lopsub.h>
16 #include <arpa/inet.h>
17 #include <sys/un.h>
18 #include <netdb.h>
19 #include <lopsub.h>
20
21 #include "server.lsg.h"
22 #include "server_cmd.lsg.h"
23 #include "para.h"
24 #include "error.h"
25 #include "crypt.h"
26 #include "string.h"
27 #include "afh.h"
28 #include "afs.h"
29 #include "server.h"
30 #include "net.h"
31 #include "ipc.h"
32 #include "list.h"
33 #include "sched.h"
34 #include "fd.h"
35 #include "signal.h"
36 #include "mood.h"
37 #include "sideband.h"
38 #include "command.h"
39
40 /** The osl tables used by afs. \sa \ref blob.c. */
41 enum afs_table_num {
42 /** Contains audio file information. See \ref aft.c. */
43 TBLNUM_AUDIO_FILES,
44 /** The table for the paraslash attributes. See \ref attribute.c. */
45 TBLNUM_ATTRIBUTES,
46 /**
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 \ref score.c for
50 * details.
51 */
52 TBLNUM_SCORES,
53 /**
54 * A standard blob table containing the mood definitions. For details
55 * see \ref mood.c.
56 */
57 TBLNUM_MOODS,
58 /** A blob table containing lyrics on a per-song basis. */
59 TBLNUM_LYRICS,
60 /** Another blob table for images (for example album cover art). */
61 TBLNUM_IMAGES,
62 /** Yet another blob table for storing standard playlists. */
63 TBLNUM_PLAYLIST,
64 /** How many tables are in use? */
65 NUM_AFS_TABLES
66 };
67
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"},
76 };
77
78 struct command_task {
79 /** The file descriptor for the local socket. */
80 int fd;
81 /**
82 * Value sent by the command handlers to identify themselves as
83 * children of the running para_server.
84 */
85 uint32_t cookie;
86 /** The associated task structure. */
87 struct task *task;
88 };
89
90 extern int mmd_mutex;
91 extern struct misc_meta_data *mmd;
92
93 static int server_socket;
94 static struct command_task command_task_struct;
95 static struct signal_task *signal_task;
96
97 static enum play_mode current_play_mode;
98 static char *current_mop; /* mode or playlist specifier. NULL means dummy mood */
99
100 /**
101 * A random number used to "authenticate" the connection.
102 *
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.
108 */
109 extern uint32_t afs_socket_cookie;
110
111 /**
112 * Struct to let command handlers execute a callback in afs context.
113 *
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.
117 *
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.
123 *
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.
127 *
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.
132 *
133 * \sa \ref struct callback_result.
134 */
135 struct callback_query {
136 /** The function to be called. */
137 afs_callback *handler;
138 /** The number of bytes of the query */
139 size_t query_size;
140 };
141
142 /**
143 * Structure embedded in the result of a callback.
144 *
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.
148 *
149 * \sa \ref struct callback_query.
150 */
151 struct callback_result {
152 /** The number of bytes of the result. */
153 size_t result_size;
154 /** The band designator (loglevel for the result). */
155 uint8_t band;
156 };
157
158 static int dispatch_result(int result_shmid, callback_result_handler *handler,
159 void *private_result_data)
160 {
161 struct osl_object result;
162 void *result_shm;
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;
166
167 if (ret < 0) {
168 PARA_ERROR_LOG("attach failed: %s\n", para_strerror(-ret));
169 return ret;
170 }
171 result.size = cr->result_size;
172 result.data = result_shm + sizeof(*cr);
173 assert(handler);
174 ret = handler(&result, cr->band, private_result_data);
175 ret2 = shm_detach(result_shm);
176 if (ret2 < 0) {
177 PARA_ERROR_LOG("detach failed: %s\n", para_strerror(-ret2));
178 if (ret >= 0)
179 ret = ret2;
180 }
181 return ret;
182 }
183
184 /**
185 * Ask the afs process to call a given function.
186 *
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.
191 *
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
196 * socket.
197 *
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.
203 *
204 * \return Number of shared memory areas dispatched on success, negative on
205 * errors.
206 */
207 int send_callback_request(afs_callback *f, struct osl_object *query,
208 callback_result_handler *result_handler,
209 void *private_result_data)
210 {
211 struct callback_query *cq;
212 int ret, fd = -1, query_shmid, result_shmid;
213 void *query_shm;
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;
217
218 if (query)
219 query_shm_size += query->size;
220 ret = shm_new(query_shm_size);
221 if (ret < 0)
222 return ret;
223 query_shmid = ret;
224 ret = shm_attach(query_shmid, ATTACH_RW, &query_shm);
225 if (ret < 0)
226 goto out;
227 cq = query_shm;
228 cq->handler = f;
229 cq->query_size = query_shm_size - sizeof(*cq);
230
231 if (query)
232 memcpy(query_shm + sizeof(*cq), query->data, query->size);
233 ret = shm_detach(query_shm);
234 if (ret < 0)
235 goto out;
236
237 *(uint32_t *)buf = afs_socket_cookie;
238 *(int *)(buf + sizeof(afs_socket_cookie)) = query_shmid;
239
240 ret = connect_local_socket(OPT_STRING_VAL(AFS_SOCKET));
241 if (ret < 0)
242 goto out;
243 fd = ret;
244 ret = write_all(fd, buf, sizeof(buf));
245 if (ret < 0)
246 goto out;
247 /*
248 * Read all shmids from afs.
249 *
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.
253 */
254 for (;;) {
255 ret = recv_bin_buffer(fd, buf, sizeof(int));
256 if (ret <= 0)
257 goto out;
258 assert(ret == sizeof(int));
259 ret = *(int *) buf;
260 assert(ret > 0);
261 result_shmid = ret;
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);
267 if (ret < 0)
268 PARA_CRIT_LOG("destroy result failed: %s\n",
269 para_strerror(-ret));
270 num_dispatched++;
271 }
272 out:
273 if (shm_destroy(query_shmid) < 0)
274 PARA_CRIT_LOG("shm destroy error\n");
275 if (fd >= 0)
276 close(fd);
277 if (dispatch_error < 0)
278 return dispatch_error;
279 if (ret < 0)
280 return ret;
281 return num_dispatched;
282 }
283
284 /**
285 * Wrapper for send_callback_request() which passes a lopsub parse result.
286 *
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().
291 *
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
294 * mechanism.
295 *
296 * \return The return value of the underlying call to send_callback_request().
297 */
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)
301 {
302 struct osl_object query;
303 char *buf = NULL;
304 int ret = lls_serialize_parse_result(lpr, cmd, &buf, &query.size);
305
306 assert(ret >= 0);
307 query.data = buf;
308 ret = send_callback_request(f, &query, afs_cb_result_handler,
309 private_result_data);
310 free(buf);
311 return ret;
312 }
313
314 static int action_if_pattern_matches(struct osl_row *row, void *data)
315 {
316 struct pattern_match_data *pmd = data;
317 struct osl_object name_obj;
318 const char *p, *name;
319 int i, ret;
320
321 ret = osl(osl_get_object(pmd->table, row, pmd->match_col_num,
322 &name_obj));
323 if (ret < 0)
324 return ret;
325 name = (char *)name_obj.data;
326 if ((!name || !*name) && (pmd->pm_flags & PM_SKIP_EMPTY_NAME))
327 return 1;
328 if (lls_num_inputs(pmd->lpr) == 0) {
329 if (pmd->pm_flags & PM_NO_PATTERN_MATCHES_EVERYTHING) {
330 pmd->num_matches++;
331 return pmd->action(pmd->table, row, name, pmd->data);
332 }
333 }
334 i = pmd->input_skip;
335 for (;;) {
336 if (i >= lls_num_inputs(pmd->lpr))
337 break;
338 p = lls_input(i, pmd->lpr);
339 ret = fnmatch(p, name, pmd->fnmatch_flags);
340 if (ret != FNM_NOMATCH) {
341 if (ret != 0)
342 return -E_FNMATCH;
343 ret = pmd->action(pmd->table, row, name, pmd->data);
344 if (ret >= 0)
345 pmd->num_matches++;
346 return ret;
347
348 }
349 i++;
350 }
351 return 1;
352 }
353
354 /**
355 * Execute the given function for each matching row.
356 *
357 * \param pmd Describes what to match and how.
358 *
359 * \return Standard.
360 */
361 int for_each_matching_row(struct pattern_match_data *pmd)
362 {
363 if (pmd->pm_flags & PM_REVERSE_LOOP)
364 return osl(osl_rbtree_loop_reverse(pmd->table, pmd->loop_col_num, pmd,
365 action_if_pattern_matches));
366 return osl(osl_rbtree_loop(pmd->table, pmd->loop_col_num, pmd,
367 action_if_pattern_matches));
368 }
369
370 /**
371 * Compare two osl objects of string type.
372 *
373 * \param obj1 Pointer to the first object.
374 * \param obj2 Pointer to the second object.
375 *
376 * In any case, only \p MIN(obj1->size, obj2->size) characters of each string
377 * are taken into account.
378 *
379 * \return It returns an integer less than, equal to, or greater than zero if
380 * \a obj1 is found, respectively, to be less than, to match, or be greater than
381 * obj2.
382 *
383 * \sa strcmp(3), strncmp(3).
384 */
385 int string_compare(const struct osl_object *obj1, const struct osl_object *obj2)
386 {
387 const char *str1 = (const char *)obj1->data;
388 const char *str2 = (const char *)obj2->data;
389 return strncmp(str1, str2, PARA_MIN(obj1->size, obj2->size));
390 }
391
392 static int pass_afd(int fd, char *buf, size_t size)
393 {
394 struct msghdr msg = {.msg_iov = NULL};
395 struct cmsghdr *cmsg;
396 char control[255] __a_aligned(8);
397 int ret;
398 struct iovec iov;
399
400 iov.iov_base = buf;
401 iov.iov_len = size;
402
403 msg.msg_iov = &iov;
404 msg.msg_iovlen = 1;
405
406 msg.msg_control = control;
407 msg.msg_controllen = sizeof(control);
408
409 cmsg = CMSG_FIRSTHDR(&msg);
410 cmsg->cmsg_level = SOL_SOCKET;
411 cmsg->cmsg_type = SCM_RIGHTS;
412 cmsg->cmsg_len = CMSG_LEN(sizeof(int));
413 *(int *)CMSG_DATA(cmsg) = fd;
414
415 /* Sum of the length of all control messages in the buffer */
416 msg.msg_controllen = cmsg->cmsg_len;
417 PARA_DEBUG_LOG("passing %zu bytes and fd %d\n", size, fd);
418 ret = sendmsg(server_socket, &msg, 0);
419 if (ret < 0) {
420 ret = -ERRNO_TO_PARA_ERROR(errno);
421 return ret;
422 }
423 return 1;
424 }
425
426 /**
427 * Pass the fd of the next audio file to the server process.
428 *
429 * This stores all information for streaming the "best" audio file in a shared
430 * memory area. The id of that area and an open file descriptor for the next
431 * audio file are passed to the server process.
432 *
433 * \return Standard.
434 *
435 * \sa \ref open_and_update_audio_file().
436 */
437 static int open_next_audio_file(void)
438 {
439 struct audio_file_data afd;
440 int ret, shmid;
441 char buf[8];
442
443 ret = open_and_update_audio_file(&afd);
444 if (ret < 0) {
445 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
446 goto no_admissible_files;
447 }
448 shmid = ret;
449 if (!write_ok(server_socket)) {
450 ret = -E_AFS_SOCKET;
451 goto destroy;
452 }
453 *(uint32_t *)buf = NEXT_AUDIO_FILE;
454 *(uint32_t *)(buf + 4) = (uint32_t)shmid;
455 ret = pass_afd(afd.fd, buf, 8);
456 close(afd.fd);
457 if (ret >= 0)
458 return ret;
459 destroy:
460 shm_destroy(shmid);
461 return ret;
462 no_admissible_files:
463 *(uint32_t *)buf = NO_ADMISSIBLE_FILES;
464 *(uint32_t *)(buf + 4) = (uint32_t)0;
465 return write_all(server_socket, buf, 8);
466 }
467
468 /* Never fails if arg == NULL */
469 static int activate_mood_or_playlist(const char *arg, int *num_admissible)
470 {
471 enum play_mode mode;
472 int ret;
473
474 if (!arg) {
475 ret = change_current_mood(NULL); /* always successful */
476 mode = PLAY_MODE_MOOD;
477 } else {
478 if (!strncmp(arg, "p/", 2)) {
479 ret = playlist_open(arg + 2);
480 mode = PLAY_MODE_PLAYLIST;
481 } else if (!strncmp(arg, "m/", 2)) {
482 ret = change_current_mood(arg + 2);
483 mode = PLAY_MODE_MOOD;
484 } else
485 return -E_AFS_SYNTAX;
486 if (ret < 0)
487 return ret;
488 }
489 if (num_admissible)
490 *num_admissible = ret;
491 current_play_mode = mode;
492 if (arg != current_mop) {
493 free(current_mop);
494 if (arg) {
495 current_mop = para_strdup(arg);
496 mutex_lock(mmd_mutex);
497 strncpy(mmd->afs_mode_string, arg,
498 sizeof(mmd->afs_mode_string));
499 mmd->afs_mode_string[sizeof(mmd->afs_mode_string) - 1] = '\0';
500 mutex_unlock(mmd_mutex);
501 } else {
502 mutex_lock(mmd_mutex);
503 strcpy(mmd->afs_mode_string, "dummy");
504 mutex_unlock(mmd_mutex);
505 current_mop = NULL;
506 }
507 }
508 return 1;
509 }
510
511 /**
512 * Result handler for sending data to the para_client process.
513 *
514 * \param result The data to be sent.
515 * \param band The band designator.
516 * \param private Pointer to the command context.
517 *
518 * \return The return value of the underlying call to \ref command.c::send_sb.
519 *
520 * \sa \ref callback_result_handler, \ref command.c::send_sb.
521 */
522 int afs_cb_result_handler(struct osl_object *result, uint8_t band,
523 void *private)
524 {
525 struct command_context *cc = private;
526
527 assert(cc);
528 switch (band) {
529 case SBD_OUTPUT:
530 case SBD_DEBUG_LOG:
531 case SBD_INFO_LOG:
532 case SBD_NOTICE_LOG:
533 case SBD_WARNING_LOG:
534 case SBD_ERROR_LOG:
535 case SBD_CRIT_LOG:
536 case SBD_EMERG_LOG:
537 assert(result->size > 0);
538 return send_sb(&cc->scc, result->data, result->size, band, true);
539 case SBD_AFS_CB_FAILURE:
540 return *(int *)(result->data);
541 default:
542 return -E_BAD_BAND;
543 }
544 }
545
546 static void flush_and_free_pb(struct para_buffer *pb)
547 {
548 int ret;
549 struct afs_max_size_handler_data *amshd = pb->private_data;
550
551 if (pb->buf && pb->size > 0) {
552 ret = pass_buffer_as_shm(amshd->fd, amshd->band, pb->buf,
553 pb->offset);
554 if (ret < 0)
555 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
556 }
557 free(pb->buf);
558 }
559
560 static int com_select_callback(struct afs_callback_arg *aca)
561 {
562 const struct lls_command *cmd = SERVER_CMD_CMD_PTR(SELECT);
563 const char *arg;
564 int num_admissible, ret;
565
566 ret = lls_deserialize_parse_result(aca->query.data, cmd, &aca->lpr);
567 assert(ret >= 0);
568 arg = lls_input(0, aca->lpr);
569 ret = clear_score_table();
570 if (ret < 0) {
571 para_printf(&aca->pbout, "could not clear score table\n");
572 goto free_lpr;
573 }
574 if (current_play_mode == PLAY_MODE_MOOD)
575 close_current_mood();
576 else
577 playlist_close();
578 ret = activate_mood_or_playlist(arg, &num_admissible);
579 if (ret >= 0)
580 goto out;
581 /* ignore subsequent errors (but log them) */
582 para_printf(&aca->pbout, "could not activate %s\n", arg);
583 if (current_mop) {
584 int ret2;
585 para_printf(&aca->pbout, "switching back to %s\n", current_mop);
586 ret2 = activate_mood_or_playlist(current_mop, &num_admissible);
587 if (ret2 >= 0)
588 goto out;
589 para_printf(&aca->pbout, "could not reactivate %s: %s\n",
590 current_mop, para_strerror(-ret2));
591 }
592 para_printf(&aca->pbout, "activating dummy mood\n");
593 activate_mood_or_playlist(NULL, &num_admissible);
594 out:
595 para_printf(&aca->pbout, "activated %s (%d admissible files)\n",
596 current_mop? current_mop : "dummy mood", num_admissible);
597 free_lpr:
598 lls_free_parse_result(aca->lpr, cmd);
599 return ret;
600 }
601
602 static int com_select(struct command_context *cc, struct lls_parse_result *lpr)
603 {
604 const struct lls_command *cmd = SERVER_CMD_CMD_PTR(SELECT);
605 char *errctx;
606 int ret = lls(lls_check_arg_count(lpr, 1, 1, &errctx));
607
608 if (ret < 0) {
609 send_errctx(cc, errctx);
610 return ret;
611 }
612 return send_lls_callback_request(com_select_callback, cmd, lpr, cc);
613 }
614 EXPORT_SERVER_CMD_HANDLER(select);
615
616 static void init_admissible_files(const char *arg)
617 {
618 int ret = activate_mood_or_playlist(arg, NULL);
619 if (ret < 0) {
620 assert(arg);
621 PARA_WARNING_LOG("could not activate %s: %s\n", arg,
622 para_strerror(-ret));
623 activate_mood_or_playlist(NULL, NULL); /* always successful */
624 }
625 }
626
627 static int setup_command_socket_or_die(void)
628 {
629 int ret, socket_fd;
630 const char *socket_name = OPT_STRING_VAL(AFS_SOCKET);
631
632 unlink(socket_name);
633 ret = create_local_socket(socket_name);
634 if (ret < 0) {
635 PARA_EMERG_LOG("%s: %s\n", para_strerror(-ret), socket_name);
636 exit(EXIT_FAILURE);
637 }
638 socket_fd = ret;
639 PARA_INFO_LOG("listening on socket %s (fd %d)\n", socket_name,
640 socket_fd);
641 return socket_fd;
642 }
643
644 static void close_afs_tables(void)
645 {
646 int i;
647 PARA_NOTICE_LOG("closing afs_tables\n");
648 for (i = 0; i < NUM_AFS_TABLES; i++)
649 afs_tables[i].close();
650 }
651
652 static char *database_dir;
653
654 static void get_database_dir(void)
655 {
656 if (!database_dir) {
657 if (OPT_GIVEN(AFS_DATABASE_DIR))
658 database_dir = para_strdup(OPT_STRING_VAL(AFS_DATABASE_DIR));
659 else {
660 char *home = para_homedir();
661 database_dir = make_message(
662 "%s/.paraslash/afs_database-0.4", home);
663 free(home);
664 }
665 }
666 PARA_INFO_LOG("afs_database dir %s\n", database_dir);
667 }
668
669 static int make_database_dir(void)
670 {
671 int ret;
672
673 get_database_dir();
674 ret = para_mkdir(database_dir, 0777);
675 if (ret >= 0 || ret == -ERRNO_TO_PARA_ERROR(EEXIST))
676 return 1;
677 return ret;
678 }
679
680 static int open_afs_tables(void)
681 {
682 int i, ret;
683
684 get_database_dir();
685 PARA_NOTICE_LOG("opening %d osl tables in %s\n", NUM_AFS_TABLES,
686 database_dir);
687 for (i = 0; i < NUM_AFS_TABLES; i++) {
688 ret = afs_tables[i].open(database_dir);
689 if (ret >= 0)
690 continue;
691 PARA_ERROR_LOG("%s init: %s\n", afs_tables[i].name,
692 para_strerror(-ret));
693 break;
694 }
695 if (ret >= 0)
696 return ret;
697 while (i)
698 afs_tables[--i].close();
699 return ret;
700 }
701
702 static int afs_signal_post_select(struct sched *s, __a_unused void *context)
703 {
704 int signum, ret;
705
706 if (getppid() == 1) {
707 PARA_EMERG_LOG("para_server died\n");
708 goto shutdown;
709 }
710 signum = para_next_signal(&s->rfds);
711 if (signum == 0)
712 return 0;
713 if (signum == SIGHUP) {
714 close_afs_tables();
715 parse_config_or_die(1);
716 ret = open_afs_tables();
717 if (ret < 0)
718 return ret;
719 init_admissible_files(current_mop);
720 return 0;
721 }
722 PARA_EMERG_LOG("terminating on signal %d\n", signum);
723 shutdown:
724 task_notify_all(s, E_AFS_SIGNAL);
725 return -E_AFS_SIGNAL;
726 }
727
728 static void register_signal_task(struct sched *s)
729 {
730 para_sigaction(SIGPIPE, SIG_IGN);
731 signal_task = signal_init_or_die();
732 para_install_sighandler(SIGINT);
733 para_install_sighandler(SIGTERM);
734 para_install_sighandler(SIGHUP);
735
736 signal_task->task = task_register(&(struct task_info) {
737 .name = "signal",
738 .pre_select = signal_pre_select,
739 .post_select = afs_signal_post_select,
740 .context = signal_task,
741
742 }, s);
743 }
744
745 static struct list_head afs_client_list;
746
747 /** Describes one connected afs client. */
748 struct afs_client {
749 /** Position in the afs client list. */
750 struct list_head node;
751 /** The socket file descriptor for this client. */
752 int fd;
753 /** The time the client connected. */
754 struct timeval connect_time;
755 };
756
757 static void command_pre_select(struct sched *s, void *context)
758 {
759 struct command_task *ct = context;
760 struct afs_client *client;
761
762 para_fd_set(server_socket, &s->rfds, &s->max_fileno);
763 para_fd_set(ct->fd, &s->rfds, &s->max_fileno);
764 list_for_each_entry(client, &afs_client_list, node)
765 para_fd_set(client->fd, &s->rfds, &s->max_fileno);
766 }
767
768 /**
769 * Send data as shared memory to a file descriptor.
770 *
771 * \param fd File descriptor to send the shmid to.
772 * \param band The band designator for this data.
773 * \param buf The buffer holding the data to be sent.
774 * \param size The size of \a buf.
775 *
776 * This function creates a shared memory area large enough to hold
777 * the content given by \a buf and \a size and sends the identifier
778 * of this area to the file descriptor \a fd.
779 *
780 * It is called by the AFS max_size handler as well as directly by the AFS
781 * command callbacks to send command output to the command handlers.
782 *
783 * \return Zero if \a buf is \p NULL or \a size is zero. Negative on errors,
784 * and positive on success.
785 */
786 int pass_buffer_as_shm(int fd, uint8_t band, const char *buf, size_t size)
787 {
788 int ret, shmid;
789 void *shm;
790 struct callback_result *cr;
791
792 if (size == 0)
793 assert(band != SBD_OUTPUT);
794 ret = shm_new(size + sizeof(*cr));
795 if (ret < 0)
796 return ret;
797 shmid = ret;
798 ret = shm_attach(shmid, ATTACH_RW, &shm);
799 if (ret < 0)
800 goto err;
801 cr = shm;
802 cr->result_size = size;
803 cr->band = band;
804 if (size > 0)
805 memcpy(shm + sizeof(*cr), buf, size);
806 ret = shm_detach(shm);
807 if (ret < 0)
808 goto err;
809 ret = write_all(fd, (char *)&shmid, sizeof(int));
810 if (ret >= 0)
811 return ret;
812 err:
813 if (shm_destroy(shmid) < 0)
814 PARA_ERROR_LOG("destroy result failed\n");
815 return ret;
816 }
817
818 static int call_callback(int fd, int query_shmid)
819 {
820 void *query_shm;
821 struct callback_query *cq;
822 int ret, ret2;
823 struct afs_callback_arg aca = {.fd = fd};
824
825 ret = shm_attach(query_shmid, ATTACH_RW, &query_shm);
826 if (ret < 0)
827 return ret;
828 cq = query_shm;
829 aca.query.data = (char *)query_shm + sizeof(*cq);
830 aca.query.size = cq->query_size;
831 aca.pbout.max_size = shm_get_shmmax();
832 aca.pbout.max_size_handler = afs_max_size_handler;
833 aca.pbout.private_data = &(struct afs_max_size_handler_data) {
834 .fd = fd,
835 .band = SBD_OUTPUT
836 };
837 ret = cq->handler(&aca);
838 ret2 = shm_detach(query_shm);
839 if (ret2 < 0) {
840 if (ret < 0) /* ignore (but log) detach error */
841 PARA_ERROR_LOG("could not detach sma: %s\n",
842 para_strerror(-ret2));
843 else
844 ret = ret2;
845 }
846 flush_and_free_pb(&aca.pbout);
847 if (ret < 0) {
848 ret2 = pass_buffer_as_shm(fd, SBD_AFS_CB_FAILURE,
849 (const char *)&ret, sizeof(ret));
850 if (ret2 < 0)
851 PARA_ERROR_LOG("could not pass cb failure packet: %s\n",
852 para_strerror(-ret));
853 }
854 return ret;
855 }
856
857 static int execute_server_command(fd_set *rfds)
858 {
859 char buf[8];
860 size_t n;
861 int ret = read_nonblock(server_socket, buf, sizeof(buf) - 1, rfds, &n);
862
863 if (ret < 0 || n == 0)
864 return ret;
865 buf[n] = '\0';
866 if (strcmp(buf, "new"))
867 return -ERRNO_TO_PARA_ERROR(EINVAL);
868 return open_next_audio_file();
869 }
870
871 /* returns 0 if no data available, 1 else */
872 static int execute_afs_command(int fd, fd_set *rfds, uint32_t expected_cookie)
873 {
874 uint32_t cookie;
875 int query_shmid;
876 char buf[sizeof(cookie) + sizeof(query_shmid)];
877 size_t n;
878 int ret = read_nonblock(fd, buf, sizeof(buf), rfds, &n);
879
880 if (ret < 0)
881 goto err;
882 if (n == 0)
883 return 0;
884 if (n != sizeof(buf)) {
885 PARA_NOTICE_LOG("short read (%d bytes, expected %lu)\n",
886 ret, (long unsigned) sizeof(buf));
887 return 1;
888 }
889 cookie = *(uint32_t *)buf;
890 if (cookie != expected_cookie) {
891 PARA_NOTICE_LOG("received invalid cookie (got %u, expected %u)\n",
892 (unsigned)cookie, (unsigned)expected_cookie);
893 return 1;
894 }
895 query_shmid = *(int *)(buf + sizeof(cookie));
896 if (query_shmid < 0) {
897 PARA_WARNING_LOG("received invalid query shmid %d)\n",
898 query_shmid);
899 return 1;
900 }
901 ret = call_callback(fd, query_shmid);
902 if (ret >= 0)
903 return 1;
904 err:
905 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
906 return 1;
907 }
908
909 /** Shutdown connection if query has not arrived until this many seconds. */
910 #define AFS_CLIENT_TIMEOUT 3
911
912 static int command_post_select(struct sched *s, void *context)
913 {
914 struct command_task *ct = context;
915 struct sockaddr_un unix_addr;
916 struct afs_client *client, *tmp;
917 int fd, ret;
918
919 ret = task_get_notification(ct->task);
920 if (ret < 0)
921 return ret;
922 ret = execute_server_command(&s->rfds);
923 if (ret < 0) {
924 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
925 task_notify_all(s, -ret);
926 return ret;
927 }
928 /* Check the list of connected clients. */
929 list_for_each_entry_safe(client, tmp, &afs_client_list, node) {
930 ret = execute_afs_command(client->fd, &s->rfds, ct->cookie);
931 if (ret == 0) { /* prevent bogus connection flooding */
932 struct timeval diff;
933 tv_diff(now, &client->connect_time, &diff);
934 if (diff.tv_sec < AFS_CLIENT_TIMEOUT)
935 continue;
936 PARA_WARNING_LOG("connection timeout\n");
937 }
938 close(client->fd);
939 list_del(&client->node);
940 free(client);
941 }
942 /* Accept connections on the local socket. */
943 ret = para_accept(ct->fd, &s->rfds, &unix_addr, sizeof(unix_addr), &fd);
944 if (ret < 0)
945 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
946 if (ret <= 0)
947 return 0;
948 ret = mark_fd_nonblocking(fd);
949 if (ret < 0) {
950 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
951 close(fd);
952 return 0;
953 }
954 client = para_malloc(sizeof(*client));
955 client->fd = fd;
956 client->connect_time = *now;
957 para_list_add(&client->node, &afs_client_list);
958 return 0;
959 }
960
961 static void register_command_task(uint32_t cookie, struct sched *s)
962 {
963 struct command_task *ct = &command_task_struct;
964 ct->fd = setup_command_socket_or_die();
965 ct->cookie = cookie;
966
967 ct->task = task_register(&(struct task_info) {
968 .name = "afs command",
969 .pre_select = command_pre_select,
970 .post_select = command_post_select,
971 .context = ct,
972 }, s);
973 }
974
975 /**
976 * Initialize the audio file selector process.
977 *
978 * \param cookie The value used for "authentication".
979 * \param socket_fd File descriptor used for communication with the server.
980 */
981 __noreturn void afs_init(uint32_t cookie, int socket_fd)
982 {
983 static struct sched s;
984 int i, ret;
985
986 register_signal_task(&s);
987 INIT_LIST_HEAD(&afs_client_list);
988 for (i = 0; i < NUM_AFS_TABLES; i++)
989 afs_tables[i].init(&afs_tables[i]);
990 ret = open_afs_tables();
991 if (ret < 0)
992 goto out;
993 server_socket = socket_fd;
994 ret = mark_fd_nonblocking(server_socket);
995 if (ret < 0)
996 goto out_close;
997 PARA_INFO_LOG("server_socket: %d, afs_socket_cookie: %u\n",
998 server_socket, (unsigned) cookie);
999 init_admissible_files(OPT_STRING_VAL(AFS_INITIAL_MODE));
1000 register_command_task(cookie, &s);
1001 s.default_timeout.tv_sec = 0;
1002 s.default_timeout.tv_usec = 999 * 1000;
1003 ret = write(socket_fd, "\0", 1);
1004 if (ret != 1) {
1005 if (ret == 0)
1006 errno = EINVAL;
1007 ret = -ERRNO_TO_PARA_ERROR(errno);
1008 goto out_close;
1009 }
1010 ret = schedule(&s);
1011 sched_shutdown(&s);
1012 out_close:
1013 close_afs_tables();
1014 out:
1015 if (ret < 0)
1016 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1017 exit(EXIT_FAILURE);
1018 }
1019
1020 static int com_init_callback(struct afs_callback_arg *aca)
1021 {
1022 uint32_t table_mask = *(uint32_t *)aca->query.data;
1023 int i, ret;
1024
1025 close_afs_tables();
1026 for (i = 0; i < NUM_AFS_TABLES; i++) {
1027 struct afs_table *t = &afs_tables[i];
1028
1029 if (!(table_mask & (1 << i)))
1030 continue;
1031 if (!t->create)
1032 continue;
1033 ret = t->create(database_dir);
1034 if (ret < 0) {
1035 para_printf(&aca->pbout, "cannot create table %s\n",
1036 t->name);
1037 goto out;
1038 }
1039 para_printf(&aca->pbout, "successfully created %s table\n",
1040 t->name);
1041 }
1042 ret = open_afs_tables();
1043 if (ret < 0)
1044 para_printf(&aca->pbout, "cannot open afs tables\n");
1045 out:
1046 return ret;
1047 }
1048
1049 static int com_init(struct command_context *cc, struct lls_parse_result *lpr)
1050 {
1051 int i, j, ret;
1052 uint32_t table_mask = (1 << (NUM_AFS_TABLES + 1)) - 1;
1053 struct osl_object query = {.data = &table_mask,
1054 .size = sizeof(table_mask)};
1055 unsigned num_inputs = lls_num_inputs(lpr);
1056
1057 ret = make_database_dir();
1058 if (ret < 0)
1059 return ret;
1060 if (num_inputs > 0) {
1061 table_mask = 0;
1062 for (i = 0; i < num_inputs; i++) {
1063 for (j = 0; j < NUM_AFS_TABLES; j++) {
1064 struct afs_table *t = &afs_tables[j];
1065
1066 if (strcmp(lls_input(i, lpr), t->name))
1067 continue;
1068 table_mask |= (1 << j);
1069 break;
1070 }
1071 if (j == NUM_AFS_TABLES)
1072 return -E_BAD_TABLE_NAME;
1073 }
1074 }
1075 return send_callback_request(com_init_callback, &query,
1076 afs_cb_result_handler, cc);
1077 }
1078 EXPORT_SERVER_CMD_HANDLER(init);
1079
1080 static int com_check(struct command_context *cc, struct lls_parse_result *lpr)
1081 {
1082 const struct lls_opt_result *r_a = SERVER_CMD_OPT_RESULT(CHECK, AFT, lpr);
1083 const struct lls_opt_result *r_A = SERVER_CMD_OPT_RESULT(CHECK, ATTRIBUTE, lpr);
1084 const struct lls_opt_result *r_m = SERVER_CMD_OPT_RESULT(CHECK, MOOD, lpr);
1085 const struct lls_opt_result *r_p = SERVER_CMD_OPT_RESULT(CHECK, PLAYLIST, lpr);
1086 bool noopt = !lls_opt_given(r_a) && !lls_opt_given(r_A)
1087 && !lls_opt_given(r_m) && !lls_opt_given(r_p);
1088 int ret;
1089
1090 if (noopt || lls_opt_given(r_a)) {
1091 ret = send_callback_request(aft_check_callback, NULL,
1092 afs_cb_result_handler, cc);
1093 if (ret < 0)
1094 return ret;
1095 }
1096 if (noopt || lls_opt_given(r_A)) {
1097 ret = send_callback_request(attribute_check_callback, NULL,
1098 afs_cb_result_handler, cc);
1099 if (ret < 0)
1100 return ret;
1101 }
1102 if (noopt || lls_opt_given(r_p)) {
1103 ret = send_callback_request(playlist_check_callback,
1104 NULL, afs_cb_result_handler, cc);
1105 if (ret < 0)
1106 return ret;
1107 }
1108 if (noopt || lls_opt_given(r_m)) {
1109 ret = send_callback_request(mood_check_callback, NULL,
1110 afs_cb_result_handler, cc);
1111 if (ret < 0)
1112 return ret;
1113 }
1114 return 1;
1115 }
1116 EXPORT_SERVER_CMD_HANDLER(check);
1117
1118 /**
1119 * The afs event dispatcher.
1120 *
1121 * \param event Type of the event.
1122 * \param pb May be \p NULL.
1123 * \param data Type depends on \a event.
1124 *
1125 * This function calls each table event handler, passing \a pb and \a data
1126 * verbatim. It's up to the handlers to interpret the \a data pointer. If a
1127 * handler returns negative, the loop is aborted.
1128 *
1129 * \return The (negative) error code of the first handler that failed, or non-negative
1130 * if all handlers succeeded.
1131 */
1132 __must_check int afs_event(enum afs_events event, struct para_buffer *pb,
1133 void *data)
1134 {
1135 int i, ret;
1136
1137 for (i = 0; i < NUM_AFS_TABLES; i++) {
1138 struct afs_table *t = &afs_tables[i];
1139 if (!t->event_handler)
1140 continue;
1141 ret = t->event_handler(event, pb, data);
1142 if (ret < 0) {
1143 PARA_CRIT_LOG("table %s, event %u: %s\n", t->name,
1144 event, para_strerror(-ret));
1145 return ret;
1146 }
1147 }
1148 return 1;
1149 }
1150
1151 /**
1152 * Dummy event handler for the images table.
1153 *
1154 * \param event Unused.
1155 * \param pb Unused.
1156 * \param data Unused.
1157 *
1158 * \return The images table does not honor events, so this handler always
1159 * returns success.
1160 */
1161 __a_const int images_event_handler(__a_unused enum afs_events event,
1162 __a_unused struct para_buffer *pb, __a_unused void *data)
1163 {
1164 return 1;
1165 }
1166
1167 /**
1168 * Dummy event handler for the lyrics table.
1169 *
1170 * \param event Unused.
1171 * \param pb Unused.
1172 * \param data Unused.
1173 *
1174 * \return The lyrics table does not honor events, so this handler always
1175 * returns success.
1176 */
1177 __a_const int lyrics_event_handler(__a_unused enum afs_events event,
1178 __a_unused struct para_buffer *pb, __a_unused void *data)
1179 {
1180 return 1;
1181 }