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