server: Convert com_lsatt() to lopsub.
[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  * 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 /**
315  * Send a callback request passing an options structure and an argument vector.
316  *
317  * \param options pointer to an arbitrary data structure.
318  * \param argc Argument count.
319  * \param argv Standard argument vector.
320  * \param f The callback function.
321  * \param result_handler See \ref send_callback_request.
322  * \param private_result_data See \ref send_callback_request.
323  *
324  * Some command handlers pass command-specific options to a callback, together
325  * with a list of further arguments (often a list of audio files). This
326  * function allows to pass an arbitrary structure (given as an osl object) and
327  * a usual argument vector to the specified callback.
328  *
329  * \return The return value of the underlying call to \ref
330  * send_callback_request().
331  *
332  * \sa send_standard_callback_request(), send_callback_request().
333  */
334 int send_option_arg_callback_request(struct osl_object *options,
335                 int argc,  char * const * const argv, afs_callback *f,
336                 callback_result_handler *result_handler,
337                 void *private_result_data)
338 {
339         char *p;
340         int i, ret;
341         struct osl_object query = {.size = options? options->size : 0};
342
343         for (i = 0; i < argc; i++)
344                 query.size += strlen(argv[i]) + 1;
345         query.data = para_malloc(query.size);
346         p = query.data;
347         if (options) {
348                 memcpy(query.data, options->data, options->size);
349                 p += options->size;
350         }
351         for (i = 0; i < argc; i++) {
352                 strcpy(p, argv[i]); /* OK */
353                 p += strlen(argv[i]) + 1;
354         }
355         ret = send_callback_request(f, &query, result_handler,
356                 private_result_data);
357         free(query.data);
358         return ret;
359 }
360
361 /**
362  * Send a callback request with an argument vector only.
363  *
364  * \param argc The same meaning as in send_option_arg_callback_request().
365  * \param argv The same meaning as in send_option_arg_callback_request().
366  * \param f The same meaning as in send_option_arg_callback_request().
367  * \param result_handler See \ref send_callback_request.
368  * \param private_result_data See \ref send_callback_request.
369  *
370  * This is similar to send_option_arg_callback_request(), but no options buffer
371  * is passed to the parent process.
372  *
373  * \return The return value of the underlying call to
374  * send_option_arg_callback_request().
375  */
376 int send_standard_callback_request(int argc,  char * const * const argv,
377                 afs_callback *f, callback_result_handler *result_handler,
378                 void *private_result_data)
379 {
380         return send_option_arg_callback_request(NULL, argc, argv, f, result_handler,
381                 private_result_data);
382 }
383
384 static int action_if_pattern_matches(struct osl_row *row, void *data)
385 {
386         struct pattern_match_data *pmd = data;
387         struct osl_object name_obj;
388         const char *p, *name;
389         int i, ret = osl(osl_get_object(pmd->table, row, pmd->match_col_num, &name_obj));
390         const char *pattern_txt = (const char *)pmd->patterns.data;
391
392         if (ret < 0)
393                 return ret;
394         name = (char *)name_obj.data;
395         if ((!name || !*name) && (pmd->pm_flags & PM_SKIP_EMPTY_NAME))
396                 return 1;
397         if ((pmd->lpr && lls_num_inputs(pmd->lpr) == 0) || pmd->patterns.size == 0) {
398                 if (pmd->pm_flags & PM_NO_PATTERN_MATCHES_EVERYTHING) {
399                         pmd->num_matches++;
400                         return pmd->action(pmd->table, row, name, pmd->data);
401                 }
402         }
403         p = pattern_txt;
404         i = 0;
405         for (;;) {
406                 if (pmd->lpr) {
407                         if (i >= lls_num_inputs(pmd->lpr))
408                                 break;
409                         p = lls_input(i, pmd->lpr);
410                 } else {
411                         if (p >= pattern_txt + pmd->patterns.size)
412                                 break;
413                 }
414                 ret = fnmatch(p, name, pmd->fnmatch_flags);
415                 if (ret != FNM_NOMATCH) {
416                         if (ret != 0)
417                                 return -E_FNMATCH;
418                         ret = pmd->action(pmd->table, row, name, pmd->data);
419                         if (ret >= 0)
420                                 pmd->num_matches++;
421                         return ret;
422
423                 }
424                 if (pmd->lpr)
425                         i++;
426                 else
427                         p += strlen(p) + 1;
428         }
429         return 1;
430 }
431
432 /**
433  * Execute the given function for each matching row.
434  *
435  * \param pmd Describes what to match and how.
436  *
437  * \return Standard.
438  */
439 int for_each_matching_row(struct pattern_match_data *pmd)
440 {
441         if (pmd->pm_flags & PM_REVERSE_LOOP)
442                 return osl(osl_rbtree_loop_reverse(pmd->table, pmd->loop_col_num, pmd,
443                         action_if_pattern_matches));
444         return osl(osl_rbtree_loop(pmd->table, pmd->loop_col_num, pmd,
445                         action_if_pattern_matches));
446 }
447
448 /**
449  * Compare two osl objects of string type.
450  *
451  * \param obj1 Pointer to the first object.
452  * \param obj2 Pointer to the second object.
453  *
454  * In any case, only \p MIN(obj1->size, obj2->size) characters of each string
455  * are taken into account.
456  *
457  * \return It returns an integer less than, equal to, or greater than zero if
458  * \a obj1 is found, respectively, to be less than, to match, or be greater than
459  * obj2.
460  *
461  * \sa strcmp(3), strncmp(3), osl_compare_func.
462  */
463 int string_compare(const struct osl_object *obj1, const struct osl_object *obj2)
464 {
465         const char *str1 = (const char *)obj1->data;
466         const char *str2 = (const char *)obj2->data;
467         return strncmp(str1, str2, PARA_MIN(obj1->size, obj2->size));
468 }
469
470 static int pass_afd(int fd, char *buf, size_t size)
471 {
472         struct msghdr msg = {.msg_iov = NULL};
473         struct cmsghdr *cmsg;
474         char control[255] __a_aligned(8);
475         int ret;
476         struct iovec iov;
477
478         iov.iov_base = buf;
479         iov.iov_len  = size;
480
481         msg.msg_iov = &iov;
482         msg.msg_iovlen = 1;
483
484         msg.msg_control = control;
485         msg.msg_controllen = sizeof(control);
486
487         cmsg = CMSG_FIRSTHDR(&msg);
488         cmsg->cmsg_level = SOL_SOCKET;
489         cmsg->cmsg_type = SCM_RIGHTS;
490         cmsg->cmsg_len = CMSG_LEN(sizeof(int));
491         *(int *)CMSG_DATA(cmsg) = fd;
492
493         /* Sum of the length of all control messages in the buffer */
494         msg.msg_controllen = cmsg->cmsg_len;
495         PARA_DEBUG_LOG("passing %zu bytes and fd %d\n", size, fd);
496         ret = sendmsg(server_socket, &msg, 0);
497         if (ret < 0) {
498                 ret = -ERRNO_TO_PARA_ERROR(errno);
499                 return ret;
500         }
501         return 1;
502 }
503
504 /**
505  * Pass the fd of the next audio file to the server process.
506  *
507  * This stores all information for streaming the "best" audio file in a shared
508  * memory area. The id of that area and an open file descriptor for the next
509  * audio file are passed to the server process.
510  *
511  * \return Standard.
512  *
513  * \sa open_and_update_audio_file().
514  */
515 static int open_next_audio_file(void)
516 {
517         struct audio_file_data afd;
518         int ret, shmid;
519         char buf[8];
520
521         ret = open_and_update_audio_file(&afd);
522         if (ret < 0) {
523                 PARA_ERROR_LOG("%s\n", para_strerror(-ret));
524                 goto no_admissible_files;
525         }
526         shmid = ret;
527         if (!write_ok(server_socket)) {
528                 ret = -E_AFS_SOCKET;
529                 goto destroy;
530         }
531         *(uint32_t *)buf = NEXT_AUDIO_FILE;
532         *(uint32_t *)(buf + 4) = (uint32_t)shmid;
533         ret = pass_afd(afd.fd, buf, 8);
534         close(afd.fd);
535         if (ret >= 0)
536                 return ret;
537 destroy:
538         shm_destroy(shmid);
539         return ret;
540 no_admissible_files:
541         *(uint32_t *)buf = NO_ADMISSIBLE_FILES;
542         *(uint32_t *)(buf + 4) = (uint32_t)0;
543         return write_all(server_socket, buf, 8);
544 }
545
546 /* Never fails if arg == NULL */
547 static int activate_mood_or_playlist(const char *arg, int *num_admissible)
548 {
549         enum play_mode mode;
550         int ret;
551
552         if (!arg) {
553                 ret = change_current_mood(NULL); /* always successful */
554                 mode = PLAY_MODE_MOOD;
555         } else {
556                 if (!strncmp(arg, "p/", 2)) {
557                         ret = playlist_open(arg + 2);
558                         mode = PLAY_MODE_PLAYLIST;
559                 } else if (!strncmp(arg, "m/", 2)) {
560                         ret = change_current_mood(arg + 2);
561                         mode = PLAY_MODE_MOOD;
562                 } else
563                         return -E_AFS_SYNTAX;
564                 if (ret < 0)
565                         return ret;
566         }
567         if (num_admissible)
568                 *num_admissible = ret;
569         current_play_mode = mode;
570         if (arg != current_mop) {
571                 free(current_mop);
572                 if (arg) {
573                         current_mop = para_strdup(arg);
574                         mutex_lock(mmd_mutex);
575                         strncpy(mmd->afs_mode_string, arg,
576                                 sizeof(mmd->afs_mode_string));
577                         mmd->afs_mode_string[sizeof(mmd->afs_mode_string) - 1] = '\0';
578                         mutex_unlock(mmd_mutex);
579                 } else {
580                         mutex_lock(mmd_mutex);
581                         strcpy(mmd->afs_mode_string, "dummy");
582                         mutex_unlock(mmd_mutex);
583                         current_mop = NULL;
584                 }
585         }
586         return 1;
587 }
588
589 /**
590  * Result handler for sending data to the para_client process.
591  *
592  * \param result The data to be sent.
593  * \param band The band designator.
594  * \param private Pointer to the command context.
595  *
596  * \return The return value of the underlying call to \ref command.c::send_sb.
597  *
598  * \sa \ref callback_result_handler, \ref command.c::send_sb.
599  */
600 int afs_cb_result_handler(struct osl_object *result, uint8_t band,
601                 void *private)
602 {
603         struct command_context *cc = private;
604
605         assert(cc);
606         switch (band) {
607         case SBD_OUTPUT:
608         case SBD_DEBUG_LOG:
609         case SBD_INFO_LOG:
610         case SBD_NOTICE_LOG:
611         case SBD_WARNING_LOG:
612         case SBD_ERROR_LOG:
613         case SBD_CRIT_LOG:
614         case SBD_EMERG_LOG:
615                 assert(result->size > 0);
616                 return send_sb(&cc->scc, result->data, result->size, band, true);
617         case SBD_AFS_CB_FAILURE:
618                 return *(int *)(result->data);
619         default:
620                 return -E_BAD_BAND;
621         }
622 }
623
624 static void flush_and_free_pb(struct para_buffer *pb)
625 {
626         int ret;
627         struct afs_max_size_handler_data *amshd = pb->private_data;
628
629         if (pb->buf && pb->size > 0) {
630                 ret = pass_buffer_as_shm(amshd->fd, amshd->band, pb->buf,
631                         pb->offset);
632                 if (ret < 0)
633                         PARA_ERROR_LOG("%s\n", para_strerror(-ret));
634         }
635         free(pb->buf);
636 }
637
638 static int com_select_callback(struct afs_callback_arg *aca)
639 {
640         const char *arg = aca->query.data;
641         int num_admissible, ret;
642
643         ret = clear_score_table();
644         if (ret < 0) {
645                 para_printf(&aca->pbout, "could not clear score table: %s\n",
646                         para_strerror(-ret));
647                 return ret;
648         }
649         if (current_play_mode == PLAY_MODE_MOOD)
650                 close_current_mood();
651         else
652                 playlist_close();
653         ret = activate_mood_or_playlist(arg, &num_admissible);
654         if (ret >= 0)
655                 goto out;
656         /* ignore subsequent errors (but log them) */
657         para_printf(&aca->pbout, "could not activate %s\n", arg);
658         if (current_mop) {
659                 int ret2;
660                 para_printf(&aca->pbout, "switching back to %s\n", current_mop);
661                 ret2 = activate_mood_or_playlist(current_mop, &num_admissible);
662                 if (ret2 >= 0)
663                         goto out;
664                 para_printf(&aca->pbout, "could not reactivate %s: %s\n",
665                         current_mop, para_strerror(-ret2));
666         }
667         para_printf(&aca->pbout, "activating dummy mood\n");
668         activate_mood_or_playlist(NULL, &num_admissible);
669 out:
670         para_printf(&aca->pbout, "activated %s (%d admissible files)\n",
671                 current_mop? current_mop : "dummy mood", num_admissible);
672         return ret;
673 }
674
675 int com_select(struct command_context *cc)
676 {
677         struct osl_object query;
678
679         if (cc->argc != 2)
680                 return -E_AFS_SYNTAX;
681         query.data = cc->argv[1];
682         query.size = strlen(cc->argv[1]) + 1;
683         return send_callback_request(com_select_callback, &query,
684                 &afs_cb_result_handler, cc);
685 }
686
687 static void init_admissible_files(char *arg)
688 {
689         if (activate_mood_or_playlist(arg, NULL) < 0)
690                 activate_mood_or_playlist(NULL, NULL); /* always successful */
691 }
692
693 static int setup_command_socket_or_die(void)
694 {
695         int ret, socket_fd;
696         char *socket_name = conf.afs_socket_arg;
697
698         unlink(socket_name);
699         ret = create_local_socket(socket_name, 0);
700         if (ret < 0) {
701                 ret = create_local_socket(socket_name,
702                         S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IROTH);
703                 if (ret < 0) {
704                         PARA_EMERG_LOG("%s: %s\n", para_strerror(-ret),
705                                 socket_name);
706                         exit(EXIT_FAILURE);
707                 }
708         }
709         socket_fd = ret;
710         PARA_INFO_LOG("listening on socket %s (fd %d)\n", socket_name,
711                 socket_fd);
712         return socket_fd;
713 }
714
715 static void close_afs_tables(void)
716 {
717         int i;
718         PARA_NOTICE_LOG("closing afs_tables\n");
719         for (i = 0; i < NUM_AFS_TABLES; i++)
720                 afs_tables[i].close();
721 }
722
723 static char *database_dir;
724
725 static void get_database_dir(void)
726 {
727         if (!database_dir) {
728                 if (conf.afs_database_dir_given)
729                         database_dir = para_strdup(conf.afs_database_dir_arg);
730                 else {
731                         char *home = para_homedir();
732                         database_dir = make_message(
733                                 "%s/.paraslash/afs_database-0.4", home);
734                         free(home);
735                 }
736         }
737         PARA_INFO_LOG("afs_database dir %s\n", database_dir);
738 }
739
740 static int make_database_dir(void)
741 {
742         int ret;
743
744         get_database_dir();
745         ret = para_mkdir(database_dir, 0777);
746         if (ret >= 0 || ret == -ERRNO_TO_PARA_ERROR(EEXIST))
747                 return 1;
748         return ret;
749 }
750
751 static int open_afs_tables(void)
752 {
753         int i, ret;
754
755         get_database_dir();
756         PARA_NOTICE_LOG("opening %d osl tables in %s\n", NUM_AFS_TABLES,
757                 database_dir);
758         for (i = 0; i < NUM_AFS_TABLES; i++) {
759                 ret = afs_tables[i].open(database_dir);
760                 if (ret >= 0)
761                         continue;
762                 PARA_ERROR_LOG("%s init: %s\n", afs_tables[i].name,
763                         para_strerror(-ret));
764                 break;
765         }
766         if (ret >= 0)
767                 return ret;
768         while (i)
769                 afs_tables[--i].close();
770         return ret;
771 }
772
773 static int afs_signal_post_select(struct sched *s, __a_unused void *context)
774 {
775         int signum, ret;
776
777         if (getppid() == 1) {
778                 PARA_EMERG_LOG("para_server died\n");
779                 goto shutdown;
780         }
781         signum = para_next_signal(&s->rfds);
782         if (signum == 0)
783                 return 0;
784         if (signum == SIGHUP) {
785                 close_afs_tables();
786                 parse_config_or_die(1);
787                 ret = open_afs_tables();
788                 if (ret < 0)
789                         return ret;
790                 init_admissible_files(current_mop);
791                 return 0;
792         }
793         PARA_EMERG_LOG("terminating on signal %d\n", signum);
794 shutdown:
795         task_notify_all(s, E_AFS_SIGNAL);
796         return -E_AFS_SIGNAL;
797 }
798
799 static void register_signal_task(struct sched *s)
800 {
801         para_sigaction(SIGPIPE, SIG_IGN);
802         signal_task = signal_init_or_die();
803         para_install_sighandler(SIGINT);
804         para_install_sighandler(SIGTERM);
805         para_install_sighandler(SIGHUP);
806
807         signal_task->task = task_register(&(struct task_info) {
808                 .name = "signal",
809                 .pre_select = signal_pre_select,
810                 .post_select = afs_signal_post_select,
811                 .context = signal_task,
812
813         }, s);
814 }
815
816 static struct list_head afs_client_list;
817
818 /** Describes one connected afs client. */
819 struct afs_client {
820         /** Position in the afs client list. */
821         struct list_head node;
822         /** The socket file descriptor for this client. */
823         int fd;
824         /** The time the client connected. */
825         struct timeval connect_time;
826 };
827
828 static void command_pre_select(struct sched *s, void *context)
829 {
830         struct command_task *ct = context;
831         struct afs_client *client;
832
833         para_fd_set(server_socket, &s->rfds, &s->max_fileno);
834         para_fd_set(ct->fd, &s->rfds, &s->max_fileno);
835         list_for_each_entry(client, &afs_client_list, node)
836                 para_fd_set(client->fd, &s->rfds, &s->max_fileno);
837 }
838
839 /**
840  * Send data as shared memory to a file descriptor.
841  *
842  * \param fd File descriptor to send the shmid to.
843  * \param band The band designator for this data.
844  * \param buf The buffer holding the data to be sent.
845  * \param size The size of \a buf.
846  *
847  * This function creates a shared memory area large enough to hold
848  * the content given by \a buf and \a size and sends the identifier
849  * of this area to the file descriptor \a fd.
850  *
851  * It is called by the AFS max_size handler as well as directly by the AFS
852  * command callbacks to send command output to the command handlers.
853  *
854  * \return Zero if \a buf is \p NULL or \a size is zero. Negative on errors,
855  * and positive on success.
856  */
857 int pass_buffer_as_shm(int fd, uint8_t band, const char *buf, size_t size)
858 {
859         int ret, shmid;
860         void *shm;
861         struct callback_result *cr;
862
863         if (size == 0)
864                 assert(band != SBD_OUTPUT);
865         ret = shm_new(size + sizeof(*cr));
866         if (ret < 0)
867                 return ret;
868         shmid = ret;
869         ret = shm_attach(shmid, ATTACH_RW, &shm);
870         if (ret < 0)
871                 goto err;
872         cr = shm;
873         cr->result_size = size;
874         cr->band = band;
875         if (size > 0)
876                 memcpy(shm + sizeof(*cr), buf, size);
877         ret = shm_detach(shm);
878         if (ret < 0)
879                 goto err;
880         ret = write_all(fd, (char *)&shmid, sizeof(int));
881         if (ret >= 0)
882                 return ret;
883 err:
884         if (shm_destroy(shmid) < 0)
885                 PARA_ERROR_LOG("destroy result failed\n");
886         return ret;
887 }
888
889 static int call_callback(int fd, int query_shmid)
890 {
891         void *query_shm;
892         struct callback_query *cq;
893         int ret, ret2;
894         struct afs_callback_arg aca = {.fd = fd};
895
896         ret = shm_attach(query_shmid, ATTACH_RW, &query_shm);
897         if (ret < 0)
898                 return ret;
899         cq = query_shm;
900         aca.query.data = (char *)query_shm + sizeof(*cq);
901         aca.query.size = cq->query_size;
902         aca.pbout.max_size = shm_get_shmmax();
903         aca.pbout.max_size_handler = afs_max_size_handler;
904         aca.pbout.private_data = &(struct afs_max_size_handler_data) {
905                 .fd = fd,
906                 .band = SBD_OUTPUT
907         };
908         ret = cq->handler(&aca);
909         ret2 = shm_detach(query_shm);
910         if (ret2 < 0) {
911                 if (ret < 0) /* ignore (but log) detach error */
912                         PARA_ERROR_LOG("could not detach sma: %s\n",
913                                 para_strerror(-ret2));
914                 else
915                         ret = ret2;
916         }
917         flush_and_free_pb(&aca.pbout);
918         if (ret < 0) {
919                 ret2 = pass_buffer_as_shm(fd, SBD_AFS_CB_FAILURE,
920                         (const char *)&ret, sizeof(ret));
921                 if (ret2 < 0)
922                         PARA_ERROR_LOG("could not pass cb failure packet: %s\n",
923                                 para_strerror(-ret));
924         }
925         return ret;
926 }
927
928 static int execute_server_command(fd_set *rfds)
929 {
930         char buf[8];
931         size_t n;
932         int ret = read_nonblock(server_socket, buf, sizeof(buf) - 1, rfds, &n);
933
934         if (ret < 0 || n == 0)
935                 return ret;
936         buf[n] = '\0';
937         if (strcmp(buf, "new"))
938                 return -ERRNO_TO_PARA_ERROR(EINVAL);
939         return open_next_audio_file();
940 }
941
942 /* returns 0 if no data available, 1 else */
943 static int execute_afs_command(int fd, fd_set *rfds, uint32_t expected_cookie)
944 {
945         uint32_t cookie;
946         int query_shmid;
947         char buf[sizeof(cookie) + sizeof(query_shmid)];
948         size_t n;
949         int ret = read_nonblock(fd, buf, sizeof(buf), rfds, &n);
950
951         if (ret < 0)
952                 goto err;
953         if (n == 0)
954                 return 0;
955         if (n != sizeof(buf)) {
956                 PARA_NOTICE_LOG("short read (%d bytes, expected %lu)\n",
957                         ret, (long unsigned) sizeof(buf));
958                 return 1;
959         }
960         cookie = *(uint32_t *)buf;
961         if (cookie != expected_cookie) {
962                 PARA_NOTICE_LOG("received invalid cookie (got %u, expected %u)\n",
963                         (unsigned)cookie, (unsigned)expected_cookie);
964                 return 1;
965         }
966         query_shmid = *(int *)(buf + sizeof(cookie));
967         if (query_shmid < 0) {
968                 PARA_WARNING_LOG("received invalid query shmid %d)\n",
969                         query_shmid);
970                 return 1;
971         }
972         ret = call_callback(fd, query_shmid);
973         if (ret >= 0)
974                 return 1;
975 err:
976         PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
977         return 1;
978 }
979
980 /** Shutdown connection if query has not arrived until this many seconds. */
981 #define AFS_CLIENT_TIMEOUT 3
982
983 static int command_post_select(struct sched *s, void *context)
984 {
985         struct command_task *ct = context;
986         struct sockaddr_un unix_addr;
987         struct afs_client *client, *tmp;
988         int fd, ret;
989
990         ret = task_get_notification(ct->task);
991         if (ret < 0)
992                 return ret;
993         ret = execute_server_command(&s->rfds);
994         if (ret < 0) {
995                 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
996                 task_notify_all(s, -ret);
997                 return ret;
998         }
999         /* Check the list of connected clients. */
1000         list_for_each_entry_safe(client, tmp, &afs_client_list, node) {
1001                 ret = execute_afs_command(client->fd, &s->rfds, ct->cookie);
1002                 if (ret == 0) { /* prevent bogus connection flooding */
1003                         struct timeval diff;
1004                         tv_diff(now, &client->connect_time, &diff);
1005                         if (diff.tv_sec < AFS_CLIENT_TIMEOUT)
1006                                 continue;
1007                         PARA_WARNING_LOG("connection timeout\n");
1008                 }
1009                 close(client->fd);
1010                 list_del(&client->node);
1011                 free(client);
1012         }
1013         /* Accept connections on the local socket. */
1014         ret = para_accept(ct->fd, &s->rfds, &unix_addr, sizeof(unix_addr), &fd);
1015         if (ret < 0)
1016                 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
1017         if (ret <= 0)
1018                 return 0;
1019         ret = mark_fd_nonblocking(fd);
1020         if (ret < 0) {
1021                 PARA_NOTICE_LOG("%s\n", para_strerror(-ret));
1022                 close(fd);
1023                 return 0;
1024         }
1025         client = para_malloc(sizeof(*client));
1026         client->fd = fd;
1027         client->connect_time = *now;
1028         para_list_add(&client->node, &afs_client_list);
1029         return 0;
1030 }
1031
1032 static void register_command_task(uint32_t cookie, struct sched *s)
1033 {
1034         struct command_task *ct = &command_task_struct;
1035         ct->fd = setup_command_socket_or_die();
1036         ct->cookie = cookie;
1037
1038         ct->task = task_register(&(struct task_info) {
1039                 .name = "afs command",
1040                 .pre_select = command_pre_select,
1041                 .post_select = command_post_select,
1042                 .context = ct,
1043         }, s);
1044 }
1045
1046 /**
1047  * Initialize the audio file selector process.
1048  *
1049  * \param cookie The value used for "authentication".
1050  * \param socket_fd File descriptor used for communication with the server.
1051  */
1052 __noreturn void afs_init(uint32_t cookie, int socket_fd)
1053 {
1054         static struct sched s;
1055         int i, ret;
1056
1057         register_signal_task(&s);
1058         INIT_LIST_HEAD(&afs_client_list);
1059         for (i = 0; i < NUM_AFS_TABLES; i++)
1060                 afs_tables[i].init(&afs_tables[i]);
1061         ret = open_afs_tables();
1062         if (ret < 0)
1063                 goto out;
1064         server_socket = socket_fd;
1065         ret = mark_fd_nonblocking(server_socket);
1066         if (ret < 0)
1067                 goto out_close;
1068         PARA_INFO_LOG("server_socket: %d, afs_socket_cookie: %u\n",
1069                 server_socket, (unsigned) cookie);
1070         init_admissible_files(conf.afs_initial_mode_arg);
1071         register_command_task(cookie, &s);
1072         s.default_timeout.tv_sec = 0;
1073         s.default_timeout.tv_usec = 999 * 1000;
1074         ret = write(socket_fd, "\0", 1);
1075         if (ret != 1) {
1076                 if (ret == 0)
1077                         errno = EINVAL;
1078                 ret = -ERRNO_TO_PARA_ERROR(errno);
1079                 goto out_close;
1080         }
1081         ret = schedule(&s);
1082         sched_shutdown(&s);
1083 out_close:
1084         close_afs_tables();
1085 out:
1086         if (ret < 0)
1087                 PARA_EMERG_LOG("%s\n", para_strerror(-ret));
1088         exit(EXIT_FAILURE);
1089 }
1090
1091 static int com_init_callback(struct afs_callback_arg *aca)
1092 {
1093         uint32_t table_mask = *(uint32_t *)aca->query.data;
1094         int i, ret;
1095
1096         close_afs_tables();
1097         for (i = 0; i < NUM_AFS_TABLES; i++) {
1098                 struct afs_table *t = &afs_tables[i];
1099
1100                 if (!(table_mask & (1 << i)))
1101                         continue;
1102                 if (!t->create)
1103                         continue;
1104                 ret = t->create(database_dir);
1105                 if (ret < 0) {
1106                         para_printf(&aca->pbout, "cannot create table %s\n",
1107                                 t->name);
1108                         goto out;
1109                 }
1110                 para_printf(&aca->pbout, "successfully created %s table\n",
1111                         t->name);
1112         }
1113         ret = open_afs_tables();
1114         if (ret < 0)
1115                 para_printf(&aca->pbout, "cannot open afs tables\n");
1116 out:
1117         return ret;
1118 }
1119
1120 static int com_init(struct command_context *cc, struct lls_parse_result *lpr)
1121 {
1122         int i, j, ret;
1123         uint32_t table_mask = (1 << (NUM_AFS_TABLES + 1)) - 1;
1124         struct osl_object query = {.data = &table_mask,
1125                 .size = sizeof(table_mask)};
1126         unsigned num_inputs = lls_num_inputs(lpr);
1127
1128         ret = make_database_dir();
1129         if (ret < 0)
1130                 return ret;
1131         if (num_inputs > 0) {
1132                 table_mask = 0;
1133                 for (i = 0; i < num_inputs; i++) {
1134                         for (j = 0; j < NUM_AFS_TABLES; j++) {
1135                                 struct afs_table *t = &afs_tables[j];
1136
1137                                 if (strcmp(lls_input(i, lpr), t->name))
1138                                         continue;
1139                                 table_mask |= (1 << j);
1140                                 break;
1141                         }
1142                         if (j == NUM_AFS_TABLES)
1143                                 return -E_BAD_TABLE_NAME;
1144                 }
1145         }
1146         return send_callback_request(com_init_callback, &query,
1147                 afs_cb_result_handler, cc);
1148 }
1149 EXPORT_SERVER_CMD_HANDLER(init);
1150
1151 /**
1152  * Flags for the check command.
1153  *
1154  * \sa com_check().
1155  */
1156 enum com_check_flags {
1157         /** Check the audio file table. */
1158         CHECK_AFT = 1,
1159         /** Check the mood table. */
1160         CHECK_MOODS = 2,
1161         /** Check the playlist table. */
1162         CHECK_PLAYLISTS = 4,
1163         /** Check the attribute table against the audio file table. */
1164         CHECK_ATTS = 8
1165 };
1166
1167 int com_check(struct command_context *cc)
1168 {
1169         unsigned flags = 0;
1170         int i, ret;
1171
1172         for (i = 1; i < cc->argc; i++) {
1173                 const char *arg = cc->argv[i];
1174                 if (arg[0] != '-')
1175                         break;
1176                 if (!strcmp(arg, "--")) {
1177                         i++;
1178                         break;
1179                 }
1180                 if (!strcmp(arg, "-a")) {
1181                         flags |= CHECK_AFT;
1182                         continue;
1183                 }
1184                 if (!strcmp(arg, "-A")) {
1185                         flags |= CHECK_ATTS;
1186                         continue;
1187                 }
1188                 if (!strcmp(arg, "-p")) {
1189                         flags |= CHECK_PLAYLISTS;
1190                         continue;
1191                 }
1192                 if (!strcmp(arg, "-m")) {
1193                         flags |= CHECK_MOODS;
1194                         continue;
1195                 }
1196                 return -E_AFS_SYNTAX;
1197         }
1198         if (i < cc->argc)
1199                 return -E_AFS_SYNTAX;
1200         if (!flags)
1201                 flags = ~0U;
1202         if (flags & CHECK_AFT) {
1203                 ret = send_callback_request(aft_check_callback, NULL,
1204                         afs_cb_result_handler, cc);
1205                 if (ret < 0)
1206                         return ret;
1207         }
1208         if (flags & CHECK_ATTS) {
1209                 ret = send_callback_request(attribute_check_callback, NULL,
1210                         afs_cb_result_handler, cc);
1211                 if (ret < 0)
1212                         return ret;
1213         }
1214         if (flags & CHECK_PLAYLISTS) {
1215                 ret = send_callback_request(playlist_check_callback,
1216                         NULL, afs_cb_result_handler, cc);
1217                 if (ret < 0)
1218                         return ret;
1219         }
1220         if (flags & CHECK_MOODS) {
1221                 ret = send_callback_request(mood_check_callback, NULL,
1222                         afs_cb_result_handler, cc);
1223                 if (ret < 0)
1224                         return ret;
1225         }
1226         return 1;
1227 }
1228
1229 /**
1230  * The afs event dispatcher.
1231  *
1232  * \param event Type of the event.
1233  * \param pb May be \p NULL.
1234  * \param data Type depends on \a event.
1235  *
1236  * This function calls each table event handler, passing \a pb and \a data
1237  * verbatim. It's up to the handlers to interpret the \a data pointer. If a
1238  * handler returns negative, the loop is aborted.
1239  *
1240  * \return The (negative) error code of the first handler that failed, or non-negative
1241  * if all handlers succeeded.
1242  */
1243 __must_check int afs_event(enum afs_events event, struct para_buffer *pb,
1244                 void *data)
1245 {
1246         int i, ret;
1247
1248         for (i = 0; i < NUM_AFS_TABLES; i++) {
1249                 struct afs_table *t = &afs_tables[i];
1250                 if (!t->event_handler)
1251                         continue;
1252                 ret = t->event_handler(event, pb, data);
1253                 if (ret < 0) {
1254                         PARA_CRIT_LOG("table %s, event %u: %s\n", t->name,
1255                                 event, para_strerror(-ret));
1256                         return ret;
1257                 }
1258         }
1259         return 1;
1260 }
1261
1262 /**
1263  * Dummy event handler for the images table.
1264  *
1265  * \param event Unused.
1266  * \param pb Unused.
1267  * \param data Unused.
1268  *
1269  * \return The images table does not honor events, so this handler always
1270  * returns success.
1271  */
1272 __a_const int images_event_handler(__a_unused enum afs_events event,
1273         __a_unused  struct para_buffer *pb, __a_unused void *data)
1274 {
1275         return 1;
1276 }
1277
1278 /**
1279  * Dummy event handler for the lyrics table.
1280  *
1281  * \param event Unused.
1282  * \param pb Unused.
1283  * \param data Unused.
1284  *
1285  * \return The lyrics table does not honor events, so this handler always
1286  * returns success.
1287  */
1288 __a_const int lyrics_event_handler(__a_unused enum afs_events event,
1289         __a_unused struct para_buffer *pb, __a_unused void *data)
1290 {
1291         return 1;
1292 }