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