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