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