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