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